text:
Q: Forward declaring a function with defined array size in Objective-C I'm sure that this is quite a silly question, but it's really caught me off guard and it may be that I'm just not thinking this through correctly. I've ran into the following line of code when working with OpenGL ES 2.0
/////////////////////////////////////////////////////////////////
// Forward declarations
static void SceneMeshInitIndices(
   GLushort meshIndices[NUM_MESH_INDICES]);
static void SceneMeshUpdateNormals(
   SceneMeshVertex mesh[NUM_MESH_COLUMNS][NUM_MESH_ROWS]);
static void SceneMeshUpdateMeshWithDefaultPositions(
   SceneMeshVertex mesh[NUM_MESH_COLUMNS][NUM_MESH_ROWS]);

Now, what catches me off guard is the fact that the functions declare their input as a 2D array with a specific size. I've never seen this done like this and am completely unsure of if it's legal or how it's legal within Objective-C. I've always been told to use a pointer to the original array and pass that it in. But this, just seems odd. Could anyone try explaining this to me or point out what I'm deducting wrong?

A: When passing arrays to functions, they decay into pointers according to a set of rules. These are:
One. The first level of indirection (i. e. the first dimension/index of an array) decays into a pointer, thus its size need not be specified (nor is it used).
Two. Further dimensions of the array remain unchanged, and don't decay into a pointer. They need to be specified, and they are part of the type of the argument.
That's why essentially the following are equivalent and legal:
void foo(int arr[]);
void foo(int arr[MAX_ARRAY_SIZE]);
void foo(int *arr);

But the following are not equivalent, yet legal:
void foo(int arr[MAX_ROWS][MAX_COLUMNS]);
void foo(int **arr);

The following are again equivalent and legal:
void foo(int arr[MAX_ROWS][MAX_COLUMNS]);
void foo(int arr[][MAX_COLUMNS]);

(and these are interpreted as int (*arr)[MAX_COLUMNS]), i. e. as a pointer-to-array).
And the following is illegal, i. e. it generates a compiler error:
void foo(int arr[MAX_ROWS][]);

A:
I've always been told to use a pointer to the original array and pass that it in.

You've been told to use a pointer to an element of the original array. You've been told this because if you try to declare a function that takes an array by value the language specifies that the parameter type is 'adjusted' to take a pointer to the element type (effectively causing the array parameter type to forget its size and to be passed by reference instead of by value). So basically you've been told to do the adjustment manually so that the source code accurately and explicitly represents the actual truth.
The declarations you show could also be declared using this advice:
static void SceneMeshInitIndices(GLushort *meshIndices);
static void SceneMeshUpdateNormals(SceneMeshVertex (*mesh)[NUM_MESH_ROWS]);
static void SceneMeshUpdateMeshWithDefaultPositions(SceneMeshVertex (*mesh)[NUM_MESH_ROWS]);

It should be clear that a type of int [X][Y] means 'an array of X arrays of Y ints.' So the element type is 'an array of Y ints.' So the adjusted type is 'int (*)[Y]' or 'a pointer to an array of Y ints.'

The rule that 'adjusts' the parameter types is one of the several reasons raw arrays are awful and should not be used if it's possible to avoid them. Unfortunately C doesn't really have a good way to do that, but C++ has std::array, which behaves as arrays ought to; i.e. you can pass them by value, you can return them by value, they don't ever automatically convert to a pointer to the element type (so they never forget their size), etc.

Maybe more examples will make it clearer. If you wrote:
void foo(int param[10]);

And you weren't aware of the rule that adjusts the parameter type then you might expect the following code to produce an error:
int bar[5];
foo(bar); // error? an array of 5 ints is not the expected type.

And for this code:
int baz[10];
foo(baz);

You might expect the array bar to be copied into the parameter, and that any modifications done on the parameter would have no effect on the original array. Unfortunately these entirely reasonable expectations are wrong. When you write void foo(int param[10]); the compiler sees the parameter with the array type and modifies it to be the same as if you'd written void foo(int *param);
Thus when you write foo(bar) the compiler sees that the function takes an int* (not the int[10] that you wrote), sees that it can convert bar to an int * and so instead of reporting an error the compiler maliciously produces a program which calls the function. No matter that the type you wrote is incompatible with the variable passed, no matter that the body of foo() could do something like param[9] *= 2; and ought to be assured that this is well defined.
Similarly, foo(baz) does not pass the array by value and anything done to the array parameter inside the function is done directly on the actual array. This is utterly unlike the usual C semantics where everything is passed by value/copy and the only way to 'pass by reference' is to obtain a pointer value that acts as a reference to another object. In this case the compiler automatically obtains a pointer on your behalf and effectively passes the array by reference.
Additionally, note that whether you write void foo(int [10]) or void foo(int [100]) doesn't matter; in both cases the parameter type is adjusted to int * and therefore those declarations declare the same function, even though they appear to be different.

A: To verify ontop of what's been noted above, I have also found the following explanation (that basically states I haven't needed to pass a 2D array in quite some time) that just iterates what's above.
When declaring a single-dimensional array as a formal parameter inside a function, you learned that the actual dimension of the array is not needed; simply use a pair of empty brackets to inform the C compiler that the parameter is, in fact, an array.This does not totally apply in the case of multidimensional arrays. For a two-dimensional array, the number of rows in the array can be omitted, but the declaration must contain the number of columns in the array. So the declarations
int array_values[100][50]

and
    int array_values[][50]
are both valid declarations for a formal parameter array called array_values containing
100 rows by 50 columns; but the declarations
   int array_values[100][]

and
int array_values[][]

are not because the number of columns in the array must be specified.


text:
Q: Automatically Generate a Table with multiple rows and columns from keys in the .tex file I would like to loop through a LaTeX document and collect every instance of a key with multiple entries.
i.e.
\begin{document}
\lipsum[1-1]
\key{name=Peter, age=50, gender=male}
\lipsum[1-1]
\key{name=Max, age=20, gender=male}
\lipsum[1-1]
\key{name=Lena, age=90, gender=female}

\makekeylist

\end{document}

\makekeylist should generate a \tabularx like table with the above entries as well as theire respective page they apear first.
My tries to do this with makeidx so far did not yield a result - and I am a bit clueless towards the right ansatz.
Thanks for all help.

A:
\documentclass[a5paper]{article}
\usepackage{keyval,tabularx}
\usepackage{lipsum}

\makeatletter
\def\zz@table{}
\newcount\zz@count
\define@key{zz}{name}{\def\zz@name{#1}}
\define@key{zz}{age}{\def\zz@age{#1}}
\define@key{zz}{gender}{\def\zz@gender{#1}}

\newcommand\key[1]{%
\global\advance\zz@count\@ne
\label{zz\the\zz@count}%
\setkeys{zz}{name=?,age=?,gender=?}%
\setkeys{zz}{#1}%
\xdef\zz@table{\expandafter\unexpanded\expandafter{\zz@table}%
  \zz@name&\zz@age&\zz@gender&\noexpand\pageref{zz\the\zz@count}\noexpand\\}%
}

\newcommand\makekeylist{%
  \begin{center}
    \begin{tabularx}{\textwidth}{XXXX}
    Name&Age&Gender&Page\\
\hline
  \zz@table
\end{tabularx}
\end{center}}

\begin{document}
\lipsum[1-1]
\key{name=Peter, age=50, gender=male}
\lipsum[1-1]
\key{name=Max, age=20, gender=male}
\lipsum[1-1]
\key{name=Lena, age=90, gender=female}

\makekeylist

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Short-Circuiting Interaction with Ternary Operator in JavaScript I'm currently learning JavaScript and I encountered this problem:
const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) =>
   console.log(acc) && current % 2 === 0
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i),
      [{"even": 0, color: 'red'}, {"odd": 0, color: 'green'}]
);

const numArray = [1, 6, 9, 4, 21, 8, 15];

const sumEvenOdd = numArray.reduce((acc, current) =>
   console.log(acc) || current % 2 === 0
      ? acc.map(i => i.hasOwnProperty('even') ? {...i, even: i.even + current} : i)
      : acc.map(i => i.hasOwnProperty('odd') ? {...i, odd: i.odd + current} : i),
      [{"even": 0, color: 'red'}, {"odd": 0, color: 'green'}]
);

When you run each of the above code, you'll notice that the first one only modifies the "odd" property which is not what I'm expecting when I used the && operator but when I changed it to the || operator I got the code that I was expecting originally. Can someone explain to me how I got those 2 outputs?


text:
Q: Check membership of a certain class of an individual in Protege I understand that we can list the members of a certain class in Protege. All I need to do is to start the reasoner, visit the DL Query tab, put the name of the class in the Query box, keep Instances checked and the press Execute. I get a list of all the individuals who belong to this class.
I wanted to issue a DL query to check whether individual a belongs to class A.
Is there a way I can do this in Protege? If this is not possible in Protege, is there an alternative?

A: You could write something like this: {a} and A.
If a belongs to A, then it will be displayed in the "Instances" section:

One would have to be able to use Snap SPARQL Query Plugin for this purpose.
Snap SPARQL Query Plugin, as opposed to SPARQL Query Plugin, is able to work with inferred knowledge.
Unfortunately, Snap SPARQL Query Plugin does not support ASK queries. Try the following:
SELECT DISTINCT ?is WHERE { :a rdf:type :A . BIND (("Found!") AS ?is) }


text:
Q: Always on top like task manager I am working on a project but I faced a problem in making a form stay always on top like task manager in delphi
I used this code but didn't work
SetWindowPos(Form1.Handle, HWND_TOPMOST, 0,0,0,0, SWP_NOACTIVATE+SWP_NOMOVE+SWP_NOSIZE);

A: Modern task manager uses internal private Windows functionality for its stay on top behaviour. The system does not make this available to user windows. The functionality that task manager uses simply isn't available to you.
Related question: Is Task Manager a special kind of 'Always on Top' window for windows 10?

A: Just use the Object Inspector at design time to set the form's FormStyle property to fsStayOnTop.

A: The code from the original post might work on a main form, but will not work on a secondary form. fsStayOnTop is only part of the solution for a secondary form. Below is an easy solution for making a secondary form stay on top while the main form is obscured by other applications - without resorting to showmodal or form creation hacks.
Put this in the "Form B" OnCreate event:
FormStyle:= fsStayOnTop;
but that alone won't do the trick...
Drag a TApplicationEvents onto your "Form B"
In the OnDeactivate event for ApplicationEvents1, add the following:
SetForegroundWindow(Handle);
I keep an eye on a small status window while my main form is crunching data out of site. Works beautifully!


text:
Q: Python request module gives error 400(bad request) for POST I am new to http requests and trying to automate some work. But I am unable to get the required result. I have looked many posts and documentation of python requests module but there is no change in the result.
Code I wrote
def installFont():
    print "Installing font"
    urlToHit = "some http address"
    header_ = {  "UserID": "00000",  "PortalName": "EDC",  "ModifyBy" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "Content-Type" : "application/json"}

    body_ = {
  "Email": "abc@xyz.com",
  "AssetLicenseType": "Trial",
  "MachineIds":  ["machine1", "machine2"],
  "fontAsset":
  [
     {
          "FontId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
          "FontName": "Neue Aachen™ Pro Ultra Light",
          "FontUrl": "http://helveticaurl",
          "FontDownloadUrlAPI": "url",
          "FontDownloadUrl" : "url1,
          "FontFamilyName": "Neue Aachen™ Pro",
          "FontFamilyUrl": "http://FontFamilyUrl",
          "FontStyle": "Normal",
          "FontWeight": "100",
          "ExpiryDate": "2017-2-27 11:17:01",
          "FontFamilyId": "34"
     }
  ]
}

r = requests.request("POST", urlToHit, data=body_, headers=header_)
print r.headers
print r.status_code
print r.text

Itried same thing with postman which gives me correct result but via python I am getting output as

{'X-Processing-Time-Milliseconds': '3', 'Transfer-Encoding': 'chunked', 'X-Powered-By': 'ASP.NET', 'Server': 'Kestrel', 'Date': 'Mon, 06 Feb 2017 14:51:59 GMT', 'Content-Type': 'application/json'}
400
{"Message":"''"}

I think I am doing some mistake while passing body_ in
r = requests.request("POST", urlToHit, data=body_, headers=header_)
Output via postman
{"Message":"Created Successfully","SuccessCount":2,"FailCount":0}

A: You need to use:
r = requests.post(urlToHit, json=body_, headers=headers_)

Please go through the documentation.


text:
Q: Citrus Framework: I am getting NoSuchBeanDefinitionException for testing JMS sample provided by Christopher I am new to Citrus framework.
I am getting the following errors:
NoSuchBeanDefinitionException: No bean named 'helloServiceEndpoint' available

I am trying to use Citrus for a project I am working on. Any help will be appreciated.

A: The NoSuchBeanDefinitionException tells me that you are using a Citrus endpoint component named helloServiceEndpoint in your test case and this component is missing in your Spring application context configuration.
You need to define a Citrus endpoint named helloServiceEndpoint either in XML e.g. citrus-context.xml or in any Java Spring bean configuration class as @Bean annotated method definition.
Please review your Spring bean configuration and the concrete bean naming in your test and configuration.


text:
Q: How to compare two files using spark? I want to compare two files if not matched extra records load into another file with the unmatched records.
Compare each and every fields in both file and count of records also.

A: Let's say you have two files:
scala> val a = spark.read.option("header", "true").csv("a.csv").alias("a"); a.show
+---+-----+
|key|value|
+---+-----+
|  a|    b|
|  b|    c|
+---+-----+

a: org.apache.spark.sql.DataFrame = [key: string, value: string]

scala> val b = spark.read.option("header", "true").csv("b.csv").alias("b"); b.show
+---+-----+
|key|value|
+---+-----+
|  b|    c|
|  c|    d|
+---+-----+

b: org.apache.spark.sql.DataFrame = [key: string, value: string]

It is unclear which sort of unmatched records you are looking for, but it is easy to find them by any definition with join:
scala> a.join(b, Seq("key")).show
+---+-----+-----+
|key|value|value|
+---+-----+-----+
|  b|    c|    c|
+---+-----+-----+

scala> a.join(b, Seq("key"), "left_outer").show
+---+-----+-----+
|key|value|value|
+---+-----+-----+
|  a|    b| null|
|  b|    c|    c|
+---+-----+-----+

scala> a.join(b, Seq("key"), "right_outer").show
+---+-----+-----+
|key|value|value|
+---+-----+-----+
|  b|    c|    c|
|  c| null|    d|
+---+-----+-----+

scala> a.join(b, Seq("key"), "outer").show
+---+-----+-----+
|key|value|value|
+---+-----+-----+
|  c| null|    d|
|  b|    c|    c|
|  a|    b| null|
+---+-----+-----+

If you are looking for the records in b.csv that are not present in a.csv:
scala> val diff = a.join(b, Seq("key"), "right_outer").filter($"a.value" isNull).drop($"a.value")
scala> diff.show
+---+-----+
|key|value|
+---+-----+
|  c|    d|
+---+-----+

scala> diff.write.csv("diff.csv")


text:
Q: Will_paginate behavior for deleted posts - displaying correct number of pages Background:
I made a new rails 3 app with User model and the model has paperclip attachments (Picture model). I posted the first 15 Picture records (attachments) that I submitted as a test for checking out functionality.
I do the following in the controller to display all pictures except first 15 test images:

@pictures=Picture.order('pictures.id DESC').limit(Picture.last.id-15).paginate(:page => params[:page], :per_page => 15)

Though I don't display the first 15 records, will_paginate still shows number of pages assuming the first 15 records were still displayed in the index view (since will_paginate takes this from the Picture model)
What I want to do:
Show correct number of pages using will_paginate. Delete the test picture records (first 15 records)
Questions:
 I could use Picture.destroy(:id) to remove the first 15 Picture records.

*

*After removing the records this way, would will_paginate still show pages assuming those records still existed?

*Would will_paginate throw an error saying that Picture with :id =>1 does not exist?

*How do I delete the Picture records and start again from :id =>1 ? (though this might not be essential if
Thanks

A: Generally when you're testing functionality you should be using a different database to your production environment so that you don't need to mess around with trying to offset ID's or delete after the fact.
To answer your questions though...

*

*No, as they'll be destroyed in the database, unless your using something like is_paranoid they won't exist any more.

*will_paginate won't care if the ID's are in sequence or not, it only cares about the total number of rows

*Picture.each(&:destroy) will delete all the photos, to reset the auto_increment (a database peice of functionality) you'll need to run something like this...

ALTER SEQUENCE your_sequence_name RESTART WITH 1;


text:
Q: Cannot set state of multiple checkboxes? I am rendering multiple checkboxes:
className, content, visible, handleFeaturesChange}= props;

...
<FormCheck type="checkbox" label={"parking"} name={"parking"} onChange={handleFeaturesChange}></FormCheck>
<FormCheck type="checkbox" label={"Laundry"} name={"laundry"} onChange={handleFeaturesChange}></FormCheck>

from parent component:
function handleFeaturesChange(event) {
// event.preventDefault();
  const {name, checked} = event.target
  setFeatures({
    ...features,
    [name]: checked
  })
}

But this results in state being over-riden onChange so that only one checkbox is recorded as checked in any instance.
How do I get multiple checkboxes to work together?

A: It looks like you're not binding the state value to each checkbox. It looks like this can be fixed by binding the values:
<FormCheck
  type="checkbox"
  label={"parking"}
  name={"parking"}
  onChange={handleFeaturesChange}
  checked={features.parking}
/>

Note: This assumes the FormCheck component takes a checked prop. If not, you'll need to add that to FormCheck.

A: you have store the checkBox values in a global variable then setState on that variable,otherwise you are just setting state for current checked box value
Note:this is not correct code,this is only for your understanding and I am assuming setFeatures as a function where You setState()

let globalCheckBox=[]

<FormCheck
  type="checkbox"
  label={"parking"}
  name={"parking"}
  onChange={handleFeaturesChange}
  checked={features.parking}
/>

function handleFeaturesChange(event) {
  const {name, checked} = event.target

globalCheckBox.push({name, checked})

  setFeatures({
...features,
   globalCheckBox

  })
}

`

A: You can use the state hook, useState.
const [checkedItems, setCheckedItems] = React.useState([false, false])

Then:
<Checkbox
    isChecked={checkedItems.parking}
    onChange={e => setCheckedItems([e.target.checked, checkedItems.parking])}
/>

https://reactjs.org/docs/hooks-state.html


text:
Q: Map Showing Blue Screen ,when drawing Path Between Two Places in Android In android Google Map , I want to draw a path between two places.
When Iam Using Hardcoded latitude and Longitude Showing Perfectly.
Problem-1
But Latitude and Longitude Getting from other Intent Showing Blue Screen in Map
Then closing that page again opening its Showing path Between Two Points.
Problem-2
then Iam Changing the Latitude and longitude of Both Locations its Showing Previous Location Path.
Here Latitute and Longitude values Iam getting from Previous intent.
How to resolve it. I Have Added my Code
MainActivity .java
    public class MainActivity extends FragmentActivity implements OnInfoWindowClickListener{

        public double Latitude1_Current_double,Longitutde1_Current_double,Latitude1_Center_double,Longitude1_Center_double;

         private int zoomLevel = 11;

         LatLng origin1 = new LatLng(Latitude1_Current_double, Longitutde1_Current_double);
            LatLng dest1 = new LatLng(Latitude1_Service_double,Longitude1_Service_double);

            double lat1=Latitude1_Current_double;
            double lang1=Longitutde1_Current_double;
            double lat2=Latitude1_Center_double;
            double lang2=Longitude1_Center_double;

            GoogleMap map;
            ArrayList<LatLng> markerPoints;

             /*private int zoomLevel1 = 14;
             private int zoomLevel2 = 11;*/

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

            Bundle extras = getIntent().getExtras();

            String Latitude1_Current_String=extras.getString("STRING_I_NEED_LATITUDE_Current");
            String Longitutde1_Current_String =extras.getString("STRING_I_NEED_LONGITUDE_Current");
            String Latitude1_ServiceCenter_String =extras.getString("STRING_I_NEED_LATITUDE_ServiceCenter");
            String Longitude1_ServiceCenter_String =extras.getString("STRING_I_NEED_LONGITUDE_ServiceCenter");

                Latitude1_Current_double = Double.parseDouble(Latitude1_Current_String);
                Longitutde1_Current_double = Double.parseDouble(Longitutde1_Current_String);
                Latitude1_ServiceCenter_double = Double.parseDouble(Latitude1_ServiceCenter_String);
                Longitude1_ServiceCenter_double = Double.parseDouble(Longitude1_ServiceCenter_String);

            Toast.makeText(getApplicationContext(), "Get Direction"+Latitude1_Current_double+","+Longitutde1_Current_double+
                    Latitude1_Center_double+","+Longitude1_Center_double,Toast.LENGTH_SHORT).show();

            // Initializing
            markerPoints = new ArrayList<LatLng>();

            // Getting reference to SupportMapFragment of the activity_main
            SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting reference to Button
        //  Button btnDraw = (Button)findViewById(R.id.btn_draw);

            // Getting Map for the SupportMapFragment
            map = fm.getMap();

            // Enable MyLocation Button in the Map
            map.setMyLocationEnabled(true);

             map.addMarker(new MarkerOptions().position(origin1)
                     .title("User Current Location")
                     .snippet("LatLng"+"("+lat1+","+lang1+")")
                     .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

             map.addMarker(new MarkerOptions().position(dest1)
                     .title("Service Center Destination Location")
                     .snippet("LatLng"+"("+lat2+","+lang2+")")
                     .icon(BitmapDescriptorFactory
                      .defaultMarker(BitmapDescriptorFactory.HUE_RED)));

            map.moveCamera(CameraUpdateFactory.newLatLngZoom(origin1, zoomLevel));
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(dest1, zoomLevel));

            markerPoints.add(origin1);
            markerPoints.add(dest1);

            // Getting URL to the Google Directions API
            String url = getDirectionsUrl(origin1, dest1);

            DownloadTask downloadTask = new DownloadTask();

            // Start downloading json data from Google Directions API
            downloadTask.execute(url);

            // The map will be cleared on long click
            map.setOnMapLongClickListener(new OnMapLongClickListener() {

                @Override
                public void onMapLongClick(LatLng point) {
                    // Removes all the points from Google Map
                    map.clear();

                    // Removes all the points in the ArrayList
                    markerPoints.clear();

                }
            });

        }

        private String getDirectionsUrl(LatLng origin,LatLng dest){

            // Origin of route
            String str_origin = "origin="+origin.latitude+","+origin.longitude;

            // Destination of route
            String str_dest = "destination="+dest.latitude+","+dest.longitude;

            // Sensor enabled
            String sensor = "sensor=false";

            // Waypoints
            String waypoints = "";

            for(int i=2;i<markerPoints.size();i++)
            {
                LatLng point  = (LatLng) markerPoints.get(i);
                if(i==2)
                waypoints = "waypoints=";
                waypoints += point.latitude + "," + point.longitude + "|";
            }

            // Building the parameters to the web service
            String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;

            // Output format
            String output = "json";

            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

            return url;
        }

        /** A method to download json data from url */
        private String downloadUrl(String strUrl) throws IOException{
            String data = "";
            InputStream iStream = null;
            HttpURLConnection urlConnection = null;
            try{
                    URL url = new URL(strUrl);

                    // Creating an http connection to communicate with url
                    urlConnection = (HttpURLConnection) url.openConnection();

                    // Connecting to url
                    urlConnection.connect();

                    // Reading data from url
                    iStream = urlConnection.getInputStream();

                    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                    StringBuffer sb  = new StringBuffer();

                    String line = "";
                    while( ( line = br.readLine())  != null){
                            sb.append(line);
                    }

                    data = sb.toString();

                    br.close();

            }catch(Exception e){
                    Log.d("Exception while downloading url", e.toString());
            }finally{
                    iStream.close();
                    urlConnection.disconnect();
            }
            return data;
         }

        // Fetches data from url passed
        private class DownloadTask extends AsyncTask<String, Void, String>{

            // Downloading data in non-ui thread
            @Override
            protected String doInBackground(String... url) {

                // For storing data from web service
                String data = "";

                try{
                    // Fetching the data from web service
                    data = downloadUrl(url[0]);
                }catch(Exception e){
                    Log.d("Background Task",e.toString());
                }
                return data;
            }

            // Executes in UI thread, after the execution of
            // doInBackground()
            @Override
            protected void onPostExecute(String result)
            {
                super.onPostExecute(result);

                try
                {
                ParserTask parserTask = new ParserTask();

                // Invokes the thread for parsing the JSON data
                parserTask.execute(result);

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Log.i("Exceptoin in DownloadTask onPostExecute", "Errroor");
            }

            }
        }

        /** A class to parse the Google Places in JSON format */
        private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

            // Parsing the data in non-ui thread
            @Override
            protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

                JSONObject jObject;
                List<List<HashMap<String, String>>> routes = null;

                try{
                    jObject = new JSONObject(jsonData[0]);
                    DirectionsJSONParser parser = new DirectionsJSONParser();

                    // Starts parsing data
                    routes = parser.parse(jObject);
                }catch(Exception e){
                    e.printStackTrace();
                }
                return routes;
            }

            // Executes in UI thread, after the parsing process
            @Override
            protected void onPostExecute(List<List<HashMap<String, String>>> result)
            {

                try
                {

                ArrayList<LatLng> points = null;
                PolylineOptions lineOptions = null;

                // Traversing through all the routes
                for(int i=0;i<result.size();i++){
                    points = new ArrayList<LatLng>();
                    lineOptions = new PolylineOptions();

                    // Fetching i-th route
                    List<HashMap<String, String>> path = result.get(i);

                    // Fetching all the points in i-th route
                    for(int j=0;j<path.size();j++){
                        HashMap<String,String> point = path.get(j);

                        double lat = Double.parseDouble(point.get("lat"));
                        double lng = Double.parseDouble(point.get("lng"));
                        LatLng position = new LatLng(lat, lng);

                        points.add(position);
                    }

                    // Adding all the points in the route to LineOptions
                    lineOptions.addAll(points);
                    lineOptions.width(5);
                    lineOptions.color(Color.BLUE);
                }

                // Drawing polyline in the Google Map for the i-th route
                map.addPolyline(lineOptions);

            }
            catch (Exception e)
            {
                e.printStackTrace();
                Log.i("Exceptoin in  parsing process onPostExecute", "Errroor");
            }

            }
        }

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

        @Override
        public void onInfoWindowClick(Marker marker)
        {

            Intent intent = new Intent(this, NewActivity.class);
            intent.putExtra("snippet", marker.getSnippet());
            intent.putExtra("title", marker.getTitle());
            intent.putExtra("position", marker.getPosition());
            startActivity(intent);

        }
    }

DirectionsJSONParser.java
import com.google.android.gms.maps.model.LatLng;

public class DirectionsJSONParser {

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){
        }

        return routes;
    }

    /**
     * Method to decode polyline points
     * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

A: Figured out your problem:
    public double Latitude1_Current_double,Longitutde1_Current_double,Latitude1_Center_double,Longitude1_Center_double;

 private int zoomLevel = 11;

 LatLng origin1 = new LatLng(Latitude1_Current_double, Longitutde1_Current_double);
    LatLng dest1 = new LatLng(Latitude1_Service_double,Longitude1_Service_double);

    double lat1=Latitude1_Current_double;
    double lang1=Longitutde1_Current_double;
    double lat2=Latitude1_Center_double;
    double lang2=Longitude1_Center_double;

The variables origin1 and dest1 does not change even if you change lat1 and lang1, so map.addMarker(new MarkerOptions().position(origin1) will have origin1 =(0,0) the default value. You need to make sure that variables origin1 and dest1 are modified inside onCreate method so your markers does not placed in the middle of the ocean. Hope this clarifies. I've tested your code and as soon as I put origin1 and dest1 the correct lat/lng info in onCreate method, I've got desired result.


text:
Q: OS killing the app when it going to background I'm develop application on React native and have an unexpected behavior. When I minimize the app OS kill it, so when I come back to the app it start loads again. I just want to keep using app from the moment I minimezed it.

The same when I blocking device. Is it something wrong with my app or it's default behavior of OS?

A: It was caused by errors in "Release" build of the app. So, it's not a normal behavior!


text:
Q: Minio Spark Integration I am trying to load data using spark into the minio storage -
Below is the spark program -
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from datetime import datetime
from pyspark.sql import Window, functions as F
spark = SparkSession.builder.appName("MinioTest").getOrCreate()
sc = spark.sparkContext
spark.conf.set("spark.hadoop.fs.s3a.endpoint", "https://minioendpoint.com/")
spark.conf.set("spark.hadoop.fs.s3a.access.key", "username")
spark.conf..set("spark.hadoop.fs.s3a.secret.key", "password" )
spark.conf..set("spark.hadoop.fs.s3a.path.style.access", True)
spark.conf..set("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
df = spark.read.csv('s3a://bucketname/spark-operator-on-k8s/data/input/input.txt',header=True)
df.write.format('csv').options(delimiter='|').mode('overwrite').save('s3a://bucketname/spark-operator-on-k8s/data/output/')

Spark Submit Command -
/usr/middleware/spark-3.2.0-bin-hadoop3.2/bin/spark-submit --jars /usr/middleware/maven/hadoop-aws-3.2.0.jar,/usr/middleware/maven/aws-java-sdk-bundle-1.11.375.jar  --driver-class-path /usr/middleware/maven/hadoop-aws-3.2.0.jar,/usr/middleware/maven/aws-java-sdk-bundle-1.11.375.jar --conf spark.executor.extraClassPath="/usr/middleware/maven/hadoop-aws-3.2.0.jar:/usr/middleware/maven/aws-java-sdk-bundle-1.11.375.jar" /usr/middleware/miniocerts/minio.py

Error 1 -
Although password was provided in the scripts not sure why this error is thrown -

java.nio.file.AccessDeniedException: s3a://bucketname/spark-operator-on-k8s/data/output: org.apache.hadoop.fs.s3a.auth.NoAuthWithAWSException: No AWS Credentials provided by TemporaryAWSCredentialsProvider SimpleAWSCredentialsProvider EnvironmentVariableCredentialsProvider IAMInstanceCredentialsProvider : com.amazonaws.SdkClientException: Unable to load AWS credentials from environment variables (AWS_ACCESS_KEY_ID (or AWS_ACCESS_KEY) and AWS_SECRET_KEY (or AWS_SECRET_ACCESS_KEY))

Then i
export AWS_ACCESS_KEY_ID=usenrame
export AWS_SECRET_KEY=password
/usr/middleware/spark-3.2.0-bin-hadoop3.2/bin/spark-submit --jars /usr/middleware/maven/hadoop-aws-3.2.0.jar,/usr/middleware/maven/aws-java-sdk-bundle-1.11.375.jar  --driver-class-path /usr/middleware/maven/hadoop-aws-3.2.0.jar,/usr/middleware/maven/aws-java-sdk-bundle-1.11.375.jar --conf spark.executor.extraClassPath="/usr/middleware/maven/hadoop-aws-3.2.0.jar:/usr/middleware/maven/aws-java-sdk-bundle-1.11.375.jar" /usr/middleware/miniocerts/minio.py

Now the error is -

java.nio.file.AccessDeniedException: s3a://bucketname/spark-operator-on-k8s/data/input/input.txt: getFileStatus on s3a://bucketname/spark-operator-on-k8s/data/input/input.txt: com.amazonaws.services.s3.model.AmazonS3Exception: Forbidden (Service: Amazon S3; Status Code: 403; Error Code: 403 Forbidden; Request ID: XX9TMS6ANGYZXXKN; S3 Extended Request ID: t4kasdasda=; Proxy: null), S3 Extended Request ID: t4kYUfgfSAnw7ymP:403 Forbidden
at org.apache.hadoop.fs.s3a.S3AUtils.translateException(S3AUtils.java:249)

mc S3 -policy -
.
The access fothe useris is {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::bucketname",
"arn:aws:s3:::bucketname/*"
]
}
]
} ..

Any pointers on what could be the error ?

A: I modified your code. It should work now.
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from datetime import datetime
from pyspark.sql import Window, functions as F
spark = SparkSession.builder.appName("MinioTest").getOrCreate()
sc = spark.sparkContext
spark.conf.set("spark.hadoop.fs.s3a.endpoint", "https://minioendpoint.com/")
spark.conf.set("spark.hadoop.fs.s3a.access.key", "username")
spark.conf.set("spark.hadoop.fs.s3a.secret.key", "password" )
spark.conf.set("spark.hadoop.fs.s3a.path.style.access", "true")
spark.conf.set("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem")
df = spark.read.csv('s3a://bucketname/spark-operator-on-k8s/data/input/input.txt',header=True)
df.write.format('csv').options(delimiter='|').mode('overwrite').save('s3a://bucketname/spark-operator-on-k8s/data/output/')


text:
Q: Save large variables on a file in Python (without Pickle) I looked for a working answer everywhere but up to now I haven't found one.
I have to save multiple variables, mostly dictionaries, on a file using Python.
I tried to use Pickle but I had a "Memory Error" because of the size of my data, it's really really large, also if i explicit "protocol = 2".
How can I save such a huge data to a file? I have dictionaries with 7 entries, each one with a (1058694, 10, 9) numpy array, just to be clear.
Thanks in advance


text:
Q: How many divisions are there for each league in Starcraft 2? In Starcraft 2 competitive online games you get placed in a league and are ranked against approximately 100 other people of your skill level.
For the different skill levels there are bronze, silver, gold, platinum and diamond leagues, but each of these levels is divided into several "divisions" of 100 people.
How many such divisions are there for each level?

A: At the time of this writing there are:
Type      Total     Russia  Taiwan   SE Asia   Europe  Korea    NA    Latin America
 All      25,670     862     1,707    1,299     7,371  2,678  11,380       373

Broken down by Type and League (approximate numbers)
 X          1v1         2v2         3v3         4v4        2Rand        3Rand        4Rand
Diamond     700         200          50          25         200          200          100
Plat       1400         700         200          50         400          400          300
Gold       1900        1100         400         200         700          700          500
Silver     1900        1300         500         200         800          700          500
Bronze     3500        2600        1600         600        1400          800          400
Total      9400        5900        2700        1050        3500         2800         1800

This data was tabulated by myself based on the website: http://sc2ranks.com/
As to what that split represents, I refer you to this question:
What percentage of players get into each league tier

A: I think the answer would be as many as there need to be.
Here is a good article talking about the new ladder system:
Divisions Explained
They are split up approximately like so:
    * Diamond (top 10%)
    * Platinum (10-25%)
    * Gold (25-45%)
    * Silver (45-70%)
    * Bronze (70-100%)

A: total number of players = x, multiplied by percent of league P (ie. diamond would multiply by .1), divided by 100. (x*P/100). this would give an approximate answer for number of divisions.


text:
Q: Asp NET Core 2.2 on IIS in windows server problem we are thinking in upgrading our new projects to start using ASP .NET Core 2.2 but our windows server is constantly running and hosting a lot of applications that are running and being used.
My fear is that if I install .NET Core 2.2 hosting bundle it will reset my IIS and all applications will go offline. How can I install the 2.2 module without affecting all the other applications?


text:
Q: Why is versioning required to enable MFA delete on S3? I mean you can have MFA delete capabilities without versioning. So why this constraint?

A: MFA Delete is primarily intended to prevent accidental data loss due to deletion or overwrites.
MFA Delete requires a versioned bucket, because if a bucket isn't versioned, you can permanently "delete" any object (that is, you can obliterate its contents) simply by overwriting the object, which is done by creating a new object with the same key -- so requiring MFA for deletions in that case would accomplish no real purpose since it would be trivial to override or work around, whether accidentally or on purpose.
With MFA Delete active (and versioning active, as required), you can still "overwrite" an object by creating a new object with the same key, but that isn't really an overwrite. No data is lost, because the prior current version of the object simply becomes a previous version of the object.  Its contents are retained in the bucket, and the "overwrite" change can be reverted by deleting the newly-created version (with MFA, of course), which automatically promotes the most recent previous version of the object back to being the current version of the object.
But versioning can be suspended on a bucket, which would bring us back to the same problem, and that's why MFA Delete also requires MFA to be used if you try to suspend versioning on the bucket.
Depending on what you are trying to accomplish, requiring MFA on all API calls might be more appropriate than MFA Delete:

Note
MFA Delete and MFA-protected API access are features intended to provide protection for different scenarios. You configure MFA Delete on a bucket to ensure that data in your bucket cannot be accidentally deleted. MFA-protected API access is used to enforce another authentication factor (MFA code) when accessing sensitive Amazon S3 resources. You can require any operations against these Amazon S3 resources be done with temporary credentials created using MFA.
https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html#MultiFactorAuthenticationDelete

A: This might give you the answer -
https://aws.amazon.com/blogs/security/securing-access-to-aws-using-mfa-part-3/

A: You can use versioning to keep multiple versions of an object in one bucket.
Basically, using MFA-protected S3 buckets will enable an extra layer of protection to ensure that the S3 objects cannot be accidentally or intentionally deleted by the AWS users that have access to the buckets.


text:
Q: Georeferenced vector file to raster file problem When I rasterize the vector file it keeps getting an error 6. How do I manually put a -3d,-a, or -burn value?
I am only a beginner.
Feel free to ask for clarifications about my problem.


text:
Q: asp.net core database ms sql and postgresql I want to set a database for development environment and production but the database provider are different.
The dev environment is pointed to appsettings.development.json and for production is appsettings.json.
I would like to use MS Sql server (localDb) on dev environment and postgresql on production.
How could i achieve that?


text:
Q: Omnifaces 1.3 + Primefaces 3.4 + session timeout I ran into the following problem. I have a web application which uses JSF (PrimeFaces 3.4) and Glassfish. I am trying to redirect the user to the login page, when a session timeout occurs. Now I have read a lot about this, and tried a lot of solutions. First I tried writing an ExceptionHandler with no results. After hours of research, I decided to try Omnifaces (1.3-SNAPSHOT) FullAjaxExceptionHandler. Still no result.
While debugging, I noticed, that the handlerfactory is being called correctly, but the UnhandledExceptionQueue is always empty for me. It seems that there is no ViewExpiredException (or any other type of exception) is thrown.
The symptom is always the same: after the session timeout occurs, there is absolutely no response from the server. Only if I reload the whole page, the login page appears, showing that the session is not valid anymore.
Please give me some advice on this, thank you very much!


text:
Q: Overloading macros with variadic arguments I'm trying to build a macro M which will expand to one of two possibilities, depeding on whether it has one, or more than one, arguments:
M(x)

should expand to
f(x)

While
M(x, "%d%d%d", 1, 2, 3)

should expand to
g(x, "%d%d%d", 1, 2, 3)

Where the function signatures are
f(int x);
g(int x, const char *fmt, ...);

There are various answers regarding the "overloading" of macros if the argument count is known; however their methods of determining the length of __VA_ARGS__ all work only to a finite, chosen number.
Is there any trick that might make a similar approach work for my "one argument / more than 1 arguments" case?
Note:
Overloading the functions is not an option because in my case they are actually constructors for two different classes.

A: Simple. We just do a little probing to find out if a token is 1:
#define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)
#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__

#define CHECK_N(x, n, ...) n
#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)
#define PROBE(x) x, 1,

#define IS_1(x) CHECK(PRIMITIVE_CAT(IS_1_, x))
#define IS_1_1 PROBE(~)

So IS_1 expands to 1 if the token is a 1, otherwise it expands to 0.
So next, count the number of arguments(up to 8):
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)

Then overload on whether it's equal to 1 or not:
#define M_1 f
#define M_0 g

#define M(...) CAT(M_, IS_1(NARGS(__VA_ARGS__)))(__VA_ARGS__)

So then you can call M like this:
M(x) // Expands to f(x)
M(x, "%d%d%d", 1, 2, 3) // Expands to g(x, "%d%d%d", 1, 2, 3)

Now, you can only count up to 64 arguments(my example counts up to 8), for standard C preprocessor(gcc can count up to 32767 arguments). If you need to have more arguments than it is better to use a sequence, which has no limit. So first write a method to convert the sequence back to arguments using sequence iteration:
#define TO_ARGS(seq) TO_ARGS_END(TO_ARGS_1 seq)
#define TO_ARGS_END(...) TO_ARGS_END_I(__VA_ARGS__)
#define TO_ARGS_END_I(...) __VA_ARGS__ ## _END
#define TO_ARGS_1(x) x TO_ARGS_2
#define TO_ARGS_2(x) , x TO_ARGS_3
#define TO_ARGS_3(x) , x TO_ARGS_2
#define TO_ARGS_1_END
#define TO_ARGS_2_END
#define TO_ARGS_3_END

Next define the M macro to overload on whether there is one element in the sequence:
#define IS_PAREN(x) CHECK(IS_PAREN_PROBE x)
#define IS_PAREN_PROBE(...) PROBE(~)

#define EAT(...)

#define M_1(seq) g(TO_ARGS(seq))
#define M_0(seq) f(TO_ARGS(seq))

#define M(seq) CAT(M_, IS_PAREN(EAT seq))(seq)

And then you can call it like this:
M((x)) // Expands to f(x)
M((x)("%d%d%d")(1)(2)(3)) // Expands to g(x, "%d%d%d", 1, 2, 3)

Of course in C++14 if you don't need source information then you can use variadiac templates instead:
template<class T>
auto M(T&& xs) -> decltype(f(std::forward<T>(x)))
{
    return f(std::forward<T>(x));
}

template<class T, class U, class... Ts>
auto M(T&& x, U&& y, Ts&&... xs) -> decltype(g(std::forward<T>(x), std::forward<U>(y), std::forward<Ts>(xs)...))
{
    return g(std::forward<T>(x), std::forward<U>(y),std::forward<Ts>(xs)...);
}

Or for constructors:
class M : f, g
{
    template<class T>
    M(T&& xs) : f(std::forward<T>(x))
    {}

    template<class T, class U, class... Ts>
    M(T&& x, U&& y, Ts&&... xs) : g(std::forward<T>(x), std::forward<U>(y), std::forward<Ts>(xs)...)
    {}
};


text:
Q: Python: How to retrieve class information from a 'frame' object? Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an instance).

A: This is a bit shorter, but does about the same. Returns None if class name not available.
def get_class_name():
    f = sys._getframe(1)

    try:
        class_name = f.f_locals['self'].__class__.__name__
    except KeyError:
        class_name = None

    return class_name

A: I just came across this post as I was faced with the same problem. I did not consider the 'self' method an acceptable solution, however, for all the reasons already listed.
The following code demonstrates a different approach: given a frame object it searches the globals for an object with matching member name and code block. The search is hardly exhaustive so it is possible that not all classes will be uncovered, but what classes are found should be the ones we are looking for because we verify matching codes.
Object of the code is to prepend a function name with its class name, if found:
def get_name( frame ):
  code = frame.f_code
  name = code.co_name
  for objname, obj in frame.f_globals.iteritems():
    try:
      assert obj.__dict__[name].func_code is code
    except Exception:
      pass
    else: # obj is the class that defines our method
      name = '%s.%s' % ( objname, name )
      break
  return name

Note the use of __dict__ instead of getattr to prevent catching of derived classes.
Note further that a global search can be avoided if self = frame.f_locals['self']; obj = self.__class__ gives a match, or any obj in self.__class__.__bases__ or deeper, so there is certainly room for optimization / hybridization.

A: I don't believe that, at the frame object level, there's any way to find the actual python function object that has been called.
However, if your code rely on the common convention : naming the instance parameter of a method self, then you could do the following :
def get_class_from_frame(fr):
  import inspect
  args, _, _, value_dict = inspect.getargvalues(fr)
  # we check the first parameter for the frame function is
  # named 'self'
  if len(args) and args[0] == 'self':
    # in that case, 'self' will be referenced in value_dict
    instance = value_dict.get('self', None)
    if instance:
      # return its class
      return getattr(instance, '__class__', None)
  # return None otherwise
  return None

If you don't want to use getargvalues, you can use directly frame.f_locals instead of value_dict and frame.f_code.co_varnames[:frame.f_code.co_argcount] instead of args.
Keep in mind that this is still only relying on convention, so it is not portable, and error-prone:

*

*if a non-method function use self as first parameter name, then get_class_from_frame will wrongly return the class of the first parameter.

*it can be misleading when working with descriptors (it will return the class of the descriptor, not of the actual instance being accessed).

*@classmethod and @staticmethod won't take a self parameter and are implemented with descriptors.

*and surely a lot more

Depending on what exactly you want to do, you might want to take some time to dig deeper and find workarounds for all these issues (you could check the frame function exist in the returned class and share the same source, detecting descriptor calls is possible, same for class methods, etc..)

A: If a method is a class method, the class will be the first argument. This prints out the type of the first arg if present for each calling stack frame:
    def some_method(self):
        for f in inspect.getouterframes(inspect.currentframe() ):
            args, _,_, local_dict = inspect.getargvalues(f[0])
            if args:
                first_arg = args[0]
                first_value = local_dict[first_arg]
                print(type(first_value).__name__)

A: Hello and forgive the necro; but none of these worked for me so inspired by some of the snippets here I cooked up an alternative. This is how I managed to do it for class methods in python 3.7:
import inspect;

def QLNAME(frame):

    code = frame.f_code;
    name = code.co_name;
    qual = None;

    for cls in ( obj for obj in frame.f_globals.values()  #
                     if  inspect.isclass(obj)             ):

        if hasattr(cls, name):

            member = getattr(cls, name);
            if not inspect.isfunction(member): continue;

            if member.__code__ == code:
                qual = member.__qualname__;
                break;

    return qual;

The way it works is actually quite simple, we check

*

*For classes within the frame's global scope

*If this class has a member sharing the name in question

*Whether this member is a function

*Finally, compare the codes of both functions

If Nº4 is true, then we know for a fact that cls is a class with some method member that has code identical to the one we get from the frame.
All well and good, but this is not perfect. It won't work for a property-decorated method far as I've tested, and I'm not yet entirely sure how one would handle that corner case. But it is working for me on regular and static methods which is all I need at the moment, so fair enough.
Do note however that this is very slow, though I think that goes without saying. From my own benchmarks, it usually takes around two to almost three seconds per 100,000 calls. This is acceptable for my current use-case, but if you need to use this more than a handful of times in one go, you may want to work out some optimizations first. I'll leave that in your capable hands (:
Hope someone else who search-engine stumbles here can find some of this useful.
Cheers.

A: The following answer gets the type by utilizing the GC:
Another necro, but this time with a definite answer that has the exactly wanted result.
The idea is to utilize the references that are saved within the GC to the function.
The bottom line: Using the functions defined below, the returned value is the calling class:
import inspect

def get_type_of_calling_func():
    frame = inspect.currentframe().f_back
    func = get_func_from_frame(frame)
    return get_class_from_func(func)

class Class:
    def f(self):
        return get_type_of_calling_func()

print(Class().f())
# <class '__main__.Class'>

The main functionality is given below in two utility functions (the division is for usability). These functions' definitions are:
import gc
from types import FunctionType, MethodType, FrameType
from typing import Optional, Union, Iterator, Mapping

def get_func_from_frame(frame: FrameType) -> Optional[FunctionType]:
    # Nifty trick - get the function from the reference to its code object
    refs = gc.get_referrers(frame.f_code)

    for ref in refs:
        if isinstance(ref, FunctionType):
            return ref

    return None

def get_class_from_func(func: Union[FunctionType, classmethod, MethodType]) -> Optional[type]:
    cls_qual_name, func_name = func.__qualname__.rsplit('.', 1)
    assert func_name == func.__name__

    # If classmethod or method
    if not isinstance(func, FunctionType):
        self = getattr(func, '__self__', None)
        for possibility in (self, type(self)):
            if isinstance(possibility, type) and possibility.__qualname__ == cls_qual_name:
                return possibility

    # Recursively check GC references
    visited_ids = set()
    items_to_check = [func]

    # The function is referenced within the type's dict, or its descriptor
    while len(items_to_check) > 0:
        obj = items_to_check[0]
        items_to_check = items_to_check[1:]

        obj_id = id(obj)
        if obj_id in visited_ids:
            continue
        visited_ids.add(obj_id)

        refs = gc.get_referrers(obj)
        for ref in refs:
            if isinstance(ref, type) and ref.__qualname__ == cls_qual_name:
                return ref

            if (
                    hasattr(ref, '__get__') or
                    # Then this is a descriptor (e.g. `classmethod`). Check if this works with the descriptor
                    isinstance(ref, Mapping)
                    # Then this is possibly a `__dict__` of a type
            ):
                items_to_check.append(ref)

    return None


text:
Q: open cv can not read all files form a path I am working with a dataset of 72 images and 72 masks. I appended the images into a numpy ndarrayI want the cv2 to read the files from the path corresponding to the files in the numpy ndarray.
this is the path to images and masks:
images_dir = '/content/drive/MyDrive/dataset/images'
masks_dir = '/content/drive/MyDrive/dataset/masks'

#adding the images to the numpy ndarray
file_names = np.sort(os.listdir(images_dir))
file_names = np.char.split(file_names, '.')
filenames = np.array([])
for i in range(len(file_names)):
    filenames = np.append(filenames, file_names[i][0])

this is the function I want open cv to read every image and then masks from the corresponding path:
def augment_dataset(count):
    '''Function for data augmentation
        Input:
            count - total no. of images after augmentation = initial no. of images * count
        Output:
            writes augmented images (input images & segmentation masks) to the working directory
    '''
    transform_1 = augment(512, 512)
    transform_2 = augment(480, 480)
    transform_3 = augment(512, 512)
    transform_4 = augment(800, 800)
    transform_5 = augment(1024, 1024)
    transform_6 = augment(800, 800)
    transform_7 = augment(1600, 1600)
    transform_8 = augment(1920, 1280)

    i = 0
    for i in range(count):
        for file in filenames:
            tile = file.split('_')[1]
            img = cv2.imread(images_dir+file+'.jpg')
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            mask = cv2.imread(masks_dir+file+'.png')
            mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)

when I run the code:
augment_dataset(8)

there is this error showing up:
---------------------------------------------------------------------------

error                                     Traceback (most recent call last)

<ipython-input-112-fae4beb79e15> in <module>()
----> 1 augment_dataset(8)

<ipython-input-111-121d55acd3fc> in augment_dataset(count)
     20             tile = file.split('_')[1]
     21             img = cv2.imread(images_dir+file+'.jpg')
---> 22             img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
     23             mask = cv2.imread(masks_dir+file+'.png')
     24             mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)

error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

I know that this is because OpenCV did not read the files. so how can I make openCV to read the files?

A: In These cases, it's better to print(path/to/directory) to see if the directory is correct or not. In this case, we can see that I missed a / in the path to the directory. So Python was not able to parse the data.
also, you can use ose.path.exists(path/to/directory) to see if the path exists or not. if the returned value is False, you must check the specified path for errors


text:
Q: How to make my menu list on the top page? I'm new in web development and currently learning react tutorial from youtube and my list menu is not on top of the page:

how can i move the list menu on the topside of the page?
I tried to download and run the code from github and it appears the list on the bottom of the page.
here's my code, thankyou in advance.
JS:
function Navbar() {
const [click, setClick] = useState(false);
const [button, setButton] = useState(true);
const menuClicked = () => setClick(!click);
const closeMobileMenu = () => setClick(false);
const showButton = () => {
    if (window.innerWidth <= 960) {
        setButton(false);
    } else {
        setButton(true);
    }
};
useEffect(() => {
    showButton()
}, []);

window.addEventListener('resize', showButton);
return (
    <>

                <Link to='/' className='navbar-logo' onClick={closeMobileMenu}>
                    TRVL

                </Link>

                        <Link to='/' className='nav-links' onClick={closeMobileMenu}>
                            Home
                        </Link>

                        <Link
                            to='/services'
                            className='nav-links'
                            onClick={closeMobileMenu}
                        >
                            Services
                        </Link>

                        <Link
                            to='/products'
                            className='nav-links'
                            onClick={closeMobileMenu}
                        >
                            Products
                        </Link>

                        <Link
                            to='/sign-up'
                            className='nav-links-mobile'
                            onClick={closeMobileMenu}
                        >
                            Sign Up
                        </Link>

                {button && <Button buttonStyle='btn--outline'>SIGN UP</Button>}

    </>
)
}

export default Navbar

CSS:
.navbar {

background: linear-gradient(90deg, rgb(28, 27, 27) 0%, rgb(26, 23, 23) 100%);
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2rem;
  position: sticky;
  top: 0;
  z-index: 999;
}

.navbar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  max-width: 1500px;
}

.navbar-logo {
  color: #fff;
  justify-self: start;
  margin-left: 20px;
  cursor: pointer;
  text-decoration: none;
  font-size: 2rem;
  display: flex;
  align-items: center;
}

.fa-typo3 {
  margin-left: 0.5rem;
  font-size: 1.8rem;
}

.nav-menu {
  display: grid;
  grid-template-columns: repeat(4, auto);
  grid-gap: 10px;
  list-style: none;
  text-align: center;
  width: 60vw;
  justify-content: end;
  margin-right: 2rem;
}

.nav-item {
  height: 80px;
}

.nav-links {
  color: #fff;
  display: flex;
  align-items: center;
  text-decoration: none;
  padding: 0.5rem 1rem;
  height: 100%;
}

.nav-links:hover {
  border-bottom: 4px solid #fff;
  transition: all 0.2s ease-out;
}

.fa-bars {
  color: #fff;
}

.nav-links-mobile {
  display: none;
}

.menu-icon {
  display: none;
}

@media screen and (max-width: 960px) {
  .NavbarItems {
    position: relative;
  }

  .nav-menu {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 90vh;
    position: absolute;
    top: 80px;
    left: -100%;
    opacity: 1;
    transition: all 0.5s ease;
  }

  .nav-menu.active {
    background: #242222;
    left: 0;
    opacity: 1;
    transition: all 0.5s ease;
    z-index: 1;
  }

  .nav-links {
    text-align: center;
    padding: 2rem;
    width: 100%;
    display: table;
  }

  .nav-links:hover {
    background-color: #fff;
    color: #242424;
    border-radius: 0;
  }

  .navbar-logo {
    position: absolute;
    top: 0;
    left: 0;
    transform: translate(25%, 50%);
  }

  .menu-icon {
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    transform: translate(-100%, 60%);
    font-size: 1.8rem;
    cursor: pointer;
  }

  .fa-times {
    color: #fff;
    font-size: 2rem;
  }

  .nav-links-mobile {
    display: block;
    text-align: center;
    margin: 2rem auto;
    border-radius: 4px;
    width: 80%;
    text-decoration: none;
    font-size: 1.5rem;
    background-color: transparent;
    color: #fff;
    padding: 14px 20px;
    border: 1px solid #fff;
    transition: all 0.3s ease-out;
  }

  .nav-links-mobile:hover {
    background: #fff;
    color: #242424;
    transition: 250ms;
  }
}


text:
Q: How to setup cron job in cron tab with Laravel 4 and Digital Ocean Linux 12.04 Greeting all
I started working with Laravel 4 and I must say I just love it, and one of the stuffs I like about it is the artisan command.
And I created one, an artisan command that fetches posts from my database and tweets them to my official twitter page, my artisan command works pretty well and tweets the number of posts which I had set it to.
Now my problem is the cron job, I need to set it up in the cron tab, so it can be tweeting an X-number of post titles over a 10 min period (I have read up on how to do the timing), what have been giving me some issues is how to get the path to artisan correctly in the cron tab editor and am using DIGITAL OCEAN Linux 12.04 with no additional panel.
Look at how my file is organized (attached image)
How do I set up the path to artisan in my cron tab?
I tried using this Cron Job in Laravel couldn't get it right.
Thanks.

A: Just use the Laravel 4 Dispatcher package: https://github.com/Indatus/dispatcher
Then you can schedule this command, and many others through your application, rather than the server.
Laracasts has a (paid) lesson on this package here.


text:
Q: Let $G=GL(2,\mathbb{Z}/5\mathbb{Z})$, the general linear group of $2 \times 2 $ matrices with entries from $\mathbb{Z}/5\mathbb{Z}$
Let $G=GL(2,\mathbb{Z}/5\mathbb{Z})$, the general linear group of $2 \times 2 $ matrices with entries from $\mathbb{Z}/5\mathbb{Z}$.
i) List the elements of the centre of $G$.
ii) Compute the order of $G$.
iii) Give an example of an element of $G$ of order $4$, and of an element of $G$ of order $8$.
iv) Let $x$ and $y$ be the elements just constructed. Compute $\det(x)$, $\det(y)$, and $\det(xy)$. What algebraic property of the mapping $\det:G \rightarrow \mathbb{Z}/5\mathbb{Z}$ causes $\det(xy)=\det(x)\det(y)$?

For part i), notice that the only commutative matrices are $rI_n$, where $I_n$ is $n \times n$ identity matrix. Hence, elements of centre of $G$ are $rI_2$, where $r \in \mathbb{Z}_5$
For part ii), since every entry has $5$ choices, we have $5^4$ matrices. But determinant of a matrix will be zero if one row or column is zero or both rows or columns are the same. So, exclude thse matrices , we have $|G|=5^4-5$ (matrix with zero column)$-5$ (matrix with same column and row)
For part iii),  notice that $2$ has order $4$ in $\mathbb{Z}_5$, hence consider the matrix $\pmatrix {2 & 0 \\ 0 & 2}$ and it has order $4$. Consider the matrix $\pmatrix {0 & 1 \\ 2 & 0}$ and it has order $8$.
For part iv), let $x = \pmatrix {2 & 0 \\ 0 & 2}$ and $y= \pmatrix {0 & 1 \\ 2 & 0}$. Then $\det(x)=4$ and $\det(y)=-2$ and $\det(xy)=-8$. Then I don't know what is meant by algebraic property here.
Can anyone help me to check my working is valid or not. This is not homework, just an extra exercise for me to prepare for final.

A: Looks good, idonknow...Nice work.
I do think you undercounted the number of matrices with a zero column: I get $2\cdot5^2 - 1$ (subtracting for the double counting of the zero matrix).
Re: The algebraic property referenced in $(iv)$: I think they might be referring to the fact that the determinant function is a homomorphism between multiplicative groups, which certainly holds for your group. And it is needed to establish that for arbitrary matrices $x, y$ in $\operatorname{GL}(2, \mathbb Z/5\mathbb Z)$, $\det(x, y) = \det(x)\det(y)$. You showed this to be the case with example matrices, but we can use this property of the determinant to generalize and know it must hold for all matrices in your group.


text:
Q: Optimal sleep time in multiple producer / single consumer model I'm writing an application that has a multiple producer, single consumer model (multiple threads send messages to a single file writer thread).
Each producer thread contains two queues, one to write into, and one for a consumer to read out of.  Every loop of the consumer thread, it iterates through each producer and lock that producer's mutex, swaps the queues, unlocks, and writes out from the queue that the producer is no longer using.
In the consumer thread's loop, it sleeps for a designated amount of time after it processes all producer threads.  One thing I immediately noticed was that the average time for a producer to write something into the queue and return increased dramatically (by 5x) when I moved from 1 producer thread to 2.  As more threads are added, this average time decreases until it bottoms out - there isn't much difference between the time taken with 10 producers vs 15 producers.  This is presumably because with more producers to process, there is less contention for the producer thread's mutex.
Unfortunately, having < 5 producers is a fairly common scenario for the application and I'd like to optimize the sleep time so that I get reasonable performance regardless of how many producers exist.  I've noticed that by increasing the sleep time, I can get better performance for low producer counts, but worse performance for large producer counts.
Has anybody else encountered this, and if so what was your solution?  I have tried scaling the sleep time with the number of threads, but it seems somewhat machine specific and pretty trial-and-error.

A: You could pick the sleep time based on the number of producers or even make the sleep time adapt based on some dyanmic scheme.  If the consumer wakes up and has no work, double the sleep time, otherwise halve it.  But constrain the sleep time to some minimum and maximum.
Either way you're papering over a more fundamental issue.  Sleeping and polling is easy to get right and sometimes is the only approach available, but it has many drawbacks and isn't the "right" way.
You can head in the right direction by adding a semaphore which is incremented whenever a producer adds an item to a queue and decremented when the consumer processes an item in a queue.  The consumer will only wake up when there are items to process and will do so immediately.
Polling the queues may still be a problem, though.  You could add a new queue that refers to any queue which has items on it.  But it rather raises the question as to why you don't have a single queue that the consumer processes rather than a queue per producer.  All else being equal that sounds like the best approach.

A: Instead of sleeping, I would recommend that your consumer block on a condition signaled by the producers.  On a posix-compliant system, you could make it work with pthread_cond.  Create an array of pthread_cond_t, one for each producer, then create an additional one that is shared between them.  The producers first signal their individual condition variable, and then the shared one.  The consumer waits on the shared condition and then iterates over the elements of the array, performing a pthread_cond_timed_wait() on each element of the array (use pthread_get_expiration_np() to get the absolute time for "now").  If the wait returns 0, then that producer has written data. The consumer must reinitialize the condition variables before waiting again.
By using blocking waits, you'll minimize the amount time the consumer is needlessly locking-out the producers. You could also make this work with semaphores, as stated in a previous answer. Semaphores have simplified semantics compared to conditions, in my opinion, but you'd have to be careful to decrement the shared semaphore once for each producer that was processed on each pass through the consumer loop.  Condition variables have the advantage that you can basically use them like boolean semaphores if you reinitialize them after they are signaled.

A: Try to find an implementation of a Blocking Queue in the language that you use for programming. No more than one queue will be enough for any number of producers and one consumer.

A: To me it sounds like you are accidentally introducing some buffering by having the consumer thread be busy somewhere else, either sleeping or doing actual work.  (the queue acting as the buffer)  Maybe doing some simple buffering on the producer side will reduce your contention.
It seems that your system is highly sensitive to lock-contention between the producer and consumer, but I'm baffled as to why such a simple swap operation would occupy enough cpu time to show up in your run stats.
Can you show some code?
edit: maybe you are taking your lock and swapping queues even when there is no work to do?


text:
Q: Starting a spidev program during U-boot or right after U-boot So I need some guidance on how to make spidev run at the very beginning of the kernel init. I am using an ILI9341 display connected to the pocketbeagle that is being driven using SPI. Thing is, I need to "send" an image to the display during boot. For that, I need to start spidev at the very beginning of the boot process, and I am not really sure what process starts spidev. I am not sure if it's something started by a systemd process or elsewhere.
Here is my device tree declaration of spidev (original: am335x-pocketbeagle.dts):
&spi0 {
    #address-cells = <1>;
    #size-cells = <0>;
    status = "okay";

    channel@0 {
        #address-cells = <1>;
        #size-cells = <0>;
        compatible = "spidev";
        reg = <0>;
        spi-max-frequency = <100000000>;
    };

    channel@1 {
        #address-cells = <1>;
        #size-cells = <0>;
        compatible = "spidev";
        reg = <1>;
        spi-max-frequency = <100000000>;
        status = "disabled";
    };
};

&spi1 {
    #address-cells = <1>;
    #size-cells = <0>;
    status = "okay";

    channel@0 {
        #address-cells = <1>;
        #size-cells = <0>;
        compatible = "spidev";
        reg = <0>;
        spi-max-frequency = <100000000>;
    };

    channel@1 {
        #address-cells = <1>;
        #size-cells = <0>;
        compatible = "spidev";
        reg = <1>;
        spi-max-frequency = <100000000>;
    };
};

Here is the beginning of the boot process (just the first few secs is shown here):
U-Boot SPL 2018.01-dirty (May 06 2018 - 17:12:35)
Trying to boot from MMC1

U-Boot 2018.01-dirty (May 06 2018 - 17:12:35 -0400)

CPU  : AM335X-GP rev 2.1
I2C:   ready
DRAM:  512 MiB
No match for driver 'omap_hsmmc'
No match for driver 'omap_hsmmc'
Some drivers were not found
Reset Source: Power-on reset has occurred.
MMC:   OMAP SD/MMC: 0, OMAP SD/MMC: 1
Using default environment

Model: BeagleBoard.org PocketBeagle
<ethaddr> not set. Validating first E-fuse MAC
Net:   usb_ether
Press SPACE to abort autoboot in 2 seconds
board_name=[A335PBGL] ...
switch to partitions #0, OK
mmc0 is current device
SD/MMC found on device 0
** Bad device 0:2 0x82000000 **
** Bad device 0:2 0x82000000 **
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
gpio: pin 56 (gpio 56) value is 0
gpio: pin 55 (gpio 55) value is 0
gpio: pin 54 (gpio 54) value is 0
gpio: pin 53 (gpio 53) value is 1
switch to partitions #0, OK
mmc0 is current device
gpio: pin 54 (gpio 54) value is 1
Checking for: /uEnv.txt ...
Checking for: /boot.scr ...
Checking for: /boot/boot.scr ...
Checking for: /boot/uEnv.txt ...
gpio: pin 55 (gpio 55) value is 1
24 bytes read in 15 ms (1000 Bytes/s)
Loaded environment from /boot/uEnv.txt
Checking if uname_r is set in /boot/uEnv.txt...
gpio: pin 56 (gpio 56) value is 1
Running uname_boot ...
loading /boot/vmlinuz-4.4.113-ti-r149 ...
9431560 bytes read in 612 ms (14.7 MiB/s)
loading /boot/dtbs/4.4.113-ti-r149/am335x-pocketbeagle.dtb ...
130113 bytes read in 84 ms (1.5 MiB/s)
uboot_overlays: add [enable_uboot_overlays=1] to /boot/uEnv.txt to enable...
debug: [console=ttyO0,115200n8 root=/dev/mmcblk0p1 ro rootfstype=ext4 rootwait]                                                                                ...
debug: [bootz 0x82000000 - 0x88000000] ...
## Flattened Device Tree blob at 88000000
   Booting using the fdt blob at 0x88000000
   Loading Device Tree to 8ffdd000, end 8ffffc40 ... OK

Starting kernel ...

[    0.000000] Booting Linux on physical CPU 0x0
[    0.000000] Initializing cgroup subsys cpuset
[    0.000000] Initializing cgroup subsys cpu
[    0.000000] Initializing cgroup subsys cpuacct
[    0.000000] Linux version 4.4.113-ti-r149 (luis@luis) (gcc version 5.5.0 (Lin                                                                                aro GCC 5.5-2017.10) ) #2 SMP Fri Jun 29 16:50:45 EDT 2018
[    0.000000] CPU: ARMv7 Processor [413fc082] revision 2 (ARMv7), cr=10c5387d
[    0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instructio                                                                                n cache
[    0.000000] Machine model: TI AM335x PocketBeagle
[    0.000000] cma: Reserved 48 MiB at 0x9c800000
[    0.000000] Memory policy: Data cache writeback
[    0.000000] CPU: All CPU(s) started in SVC mode.
[    0.000000] AM335X ES2.1 (sgx neon )
[    0.000000] PERCPU: Embedded 13 pages/cpu @df8f2000 s24192 r8192 d20864 u5324                                                                                8
[    0.000000] Built 1 zonelists in Zone order, mobility grouping on.  Total pag                                                                                es: 129408
[    0.000000] Kernel command line: console=ttyO0,115200n8 root=/dev/mmcblk0p1 r                                                                                o rootfstype=ext4 rootwait
[    0.000000] PID hash table entries: 2048 (order: 1, 8192 bytes)
[    0.000000] Dentry cache hash table entries: 65536 (order: 6, 262144 bytes)
[    0.000000] Inode-cache hash table entries: 32768 (order: 5, 131072 bytes)
[    0.000000] Memory: 448072K/522240K available (12533K kernel code, 1016K rwda                                                                                ta, 4064K rodata, 824K init, 857K bss, 25016K reserved, 49152K cma-reserved, 0K                                                                                highmem)
[    0.000000] Virtual kernel memory layout:
[    0.000000]     vector  : 0xffff0000 - 0xffff1000   (   4 kB)
[    0.000000]     fixmap  : 0xffc00000 - 0xfff00000   (3072 kB)
[    0.000000]     vmalloc : 0xe0800000 - 0xff800000   ( 496 MB)
[    0.000000]     lowmem  : 0xc0000000 - 0xe0000000   ( 512 MB)
[    0.000000]     pkmap   : 0xbfe00000 - 0xc0000000   (   2 MB)
[    0.000000]     modules : 0xbf000000 - 0xbfe00000   (  14 MB)
[    0.000000]       .text : 0xc0008000 - 0xc103d760   (16598 kB)
[    0.000000]       .init : 0xc103e000 - 0xc110c000   ( 824 kB)
[    0.000000]       .data : 0xc110c000 - 0xc120a0e8   (1017 kB)
[    0.000000]        .bss : 0xc120d000 - 0xc12e355c   ( 858 kB)
[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1
[    0.000000] Hierarchical RCU implementation.
[    0.000000]  Build-time adjustment of leaf fanout to 32.
[    0.000000]  RCU restricting CPUs from NR_CPUS=2 to nr_cpu_ids=1.
[    0.000000] RCU: Adjusting geometry for rcu_fanout_leaf=32, nr_cpu_ids=1
[    0.000000] NR_IRQS:16 nr_irqs:16 16
[    0.000000] IRQ: Found an INTC at 0xfa200000 (revision 5.0) with 128 interrup                                                                                ts
[    0.000000] OMAP clockevent source: timer2 at 24000000 Hz
[    0.000022] sched_clock: 32 bits at 24MHz, resolution 41ns, wraps every 89478                                                                                484971ns
[    0.000048] clocksource: timer1: mask: 0xffffffff max_cycles: 0xffffffff, max                                                                                _idle_ns: 79635851949 ns
[    0.000061] OMAP clocksource: timer1 at 24000000 Hz
[    0.001914] clocksource_probe: no matching clocksources found
[    0.002223] Console: colour dummy device 80x30
[    0.002254] WARNING: Your 'console=ttyO0' has been replaced by 'ttyS0'
[    0.002262] This ensures that you still see kernel messages. Please
[    0.002268] update your kernel commandline.
[    0.002289] Calibrating delay loop... 995.32 BogoMIPS (lpj=1990656)
[    0.021215] pid_max: default: 32768 minimum: 301
[    0.021365] Security Framework initialized
[    0.021380] Yama: becoming mindful.
[    0.021418] AppArmor: AppArmor disabled by boot time parameter
[    0.021590] Mount-cache hash table entries: 1024 (order: 0, 4096 bytes)
[    0.021603] Mountpoint-cache hash table entries: 1024 (order: 0, 4096 bytes)
[    0.022464] Initializing cgroup subsys io
[    0.022497] Initializing cgroup subsys memory
[    0.022543] Initializing cgroup subsys devices
[    0.022561] Initializing cgroup subsys freezer
[    0.022578] Initializing cgroup subsys net_cls
[    0.022592] Initializing cgroup subsys perf_event
[    0.022607] Initializing cgroup subsys net_prio
[    0.022630] Initializing cgroup subsys pids
[    0.022688] CPU: Testing write buffer coherency: ok
[    0.022747] ftrace: allocating 37522 entries in 111 pages
[    0.128715] CPU0: thread -1, cpu 0, socket -1, mpidr 0
[    0.128838] Setting up static identity map for 0x80008280 - 0x800082e0
[    0.133343] Brought up 1 CPUs
[    0.133369] SMP: Total of 1 processors activated (995.32 BogoMIPS).
[    0.133377] CPU: All CPU(s) started in SVC mode.
[    0.134975] devtmpfs: initialized
[    0.172782] VFP support v0.3: implementor 41 architecture 3 part 30 variant c                                                                                rev 3
[    0.223366] omap_hwmod: debugss: _wait_target_disable failed
[    0.277491] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, ma                                                                                x_idle_ns: 7645041785100000 ns
[    0.277527] futex hash table entries: 256 (order: 2, 16384 bytes)
[    0.281782] xor: measuring software checksum speed
[    0.321202]    arm4regs  :  1219.000 MB/sec
[    0.361191]    8regs     :   957.000 MB/sec
[    0.401188]    32regs    :  1089.000 MB/sec
[    0.441187]    neon      :  1725.000 MB/sec
[    0.441195] xor: using function: neon (1725.000 MB/sec)
[    0.441228] pinctrl core: initialized pinctrl subsystem
[    0.442711] NET: Registered protocol family 16
[    0.445513] DMA: preallocated 256 KiB pool for atomic coherent allocations
[    0.446456] cpuidle: using governor ladder
[    0.446477] cpuidle: using governor menu
[    0.452463] OMAP GPIO hardware version 0.1
[    0.475562] No ATAGs?
[    0.475601] hw-breakpoint: debug architecture 0x4 unsupported.
[    0.476766] omap4_sram_init:Unable to allocate sram needed to handle errata I                                                                                688
[    0.476789] omap4_sram_init:Unable to get sram pool needed to handle errata I                                                                                688
[    0.557214] raid6: neonx2   gen()  1887 MB/s
[    0.625198] raid6: neonx2   xor()  1161 MB/s
[    0.625207] raid6: using algorithm neonx2 gen() 1887 MB/s
[    0.625214] raid6: .... xor() 1161 MB/s, rmw enabled
[    0.625221] raid6: using intx1 recovery algorithm
[    0.635476] edma 49000000.edma: TI EDMA DMA engine driver
[    0.640859] vgaarb: loaded
[    0.641610] SCSI subsystem initialized
[    0.642367] usbcore: registered new interface driver usbfs
[    0.642449] usbcore: registered new interface driver hub
[    0.642560] usbcore: registered new device driver usb
[    0.643413] omap_i2c 44e0b000.i2c: could not find pctldev for node /ocp/l4_wk                                                                                up@44c00000/scm@210000/pinmux@800/pinmux_i2c0_pins, deferring probe
[    0.644286] omap_i2c 4802a000.i2c: bus 1 rev0.11 at 400 kHz
[    0.644967] omap_i2c 4819c000.i2c: bus 2 rev0.11 at 400 kHz
[    0.645404] media: Linux media interface: v0.10
[    0.645482] Linux video capture interface: v2.00
[    0.645611] pps_core: LinuxPPS API ver. 1 registered
[    0.645620] pps_core: Software ver. 5.3.6 - Copyright 2005-2007 Rodolfo Giome                                                                                tti <giometti@linux.it>
[    0.645655] PTP clock support registered
[    0.646615] omap-mailbox 480c8000.mailbox: omap mailbox rev 0x400
[    0.648938] NetLabel: Initializing
[    0.648955] NetLabel:  domain hash size = 128
[    0.648961] NetLabel:  protocols = UNLABELED CIPSOv4
[    0.649029] NetLabel:  unlabeled traffic allowed by default
[    0.649769] clocksource: Switched to clocksource timer1
[    0.773340] NET: Registered protocol family 2
[    0.774347] TCP established hash table entries: 4096 (order: 2, 16384 bytes)
[    0.774397] TCP bind hash table entries: 4096 (order: 3, 32768 bytes)
[    0.774456] TCP: Hash tables configured (established 4096 bind 4096)
[    0.774539] UDP hash table entries: 256 (order: 1, 8192 bytes)
[    0.774560] UDP-Lite hash table entries: 256 (order: 1, 8192 bytes)
[    0.774925] NET: Registered protocol family 1
[    0.775551] RPC: Registered named UNIX socket transport module.
[    0.775567] RPC: Registered udp transport module.
[    0.775574] RPC: Registered tcp transport module.
[    0.775580] RPC: Registered tcp NFSv4.1 backchannel transport module.
[    0.776750] hw perfevents: enabled with armv7_cortex_a8 PMU driver, 5 counter                                                                                s available
[    0.780201] audit: initializing netlink subsys (disabled)
[    0.780300] audit: type=2000 audit(0.712:1): initialized
[    0.790964] zbud: loaded
[    0.791713] VFS: Disk quotas dquot_6.6.0
[    0.791995] VFS: Dquot-cache hash table entries: 1024 (order 0, 4096 bytes)
[    0.795073] NFS: Registering the id_resolver key type
[    0.795149] Key type id_resolver registered
[    0.795157] Key type id_legacy registered
[    0.795187] nfs4filelayout_init: NFSv4 File Layout Driver Registering...
[    0.795579] fuse init (API version 7.23)
[    0.796227] SGI XFS with ACLs, security attributes, realtime, no debug enable                                                                                d
[    0.805645] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 2                                                                                47)
[    0.806079] io scheduler noop registered
[    0.806100] io scheduler deadline registered
[    0.806175] io scheduler cfq registered (default)
[    0.808070] pinctrl-single 44e10800.pinmux: 142 pins at pa f9e10800 size 568
[    0.809173] gpio-of-helper ocp:cape-universal: Allocated GPIO id=0
[    0.809332] gpio-of-helper ocp:cape-universal: Allocated GPIO id=1
[    0.809521] gpio-of-helper ocp:cape-universal: Allocated GPIO id=2
[    0.809670] gpio-of-helper ocp:cape-universal: Allocated GPIO id=3
[    0.810219] gpio-of-helper ocp:cape-universal: Allocated GPIO id=4
[    0.810400] gpio-of-helper ocp:cape-universal: Allocated GPIO id=5
[    0.810547] gpio-of-helper ocp:cape-universal: Allocated GPIO id=6
[    0.810691] gpio-of-helper ocp:cape-universal: Allocated GPIO id=7
[    0.810844] gpio-of-helper ocp:cape-universal: Allocated GPIO id=8
[    0.811050] gpio-of-helper ocp:cape-universal: Allocated GPIO id=9
[    0.811224] gpio-of-helper ocp:cape-universal: Allocated GPIO id=10
[    0.811392] gpio-of-helper ocp:cape-universal: Allocated GPIO id=11
[    0.811539] gpio-of-helper ocp:cape-universal: Allocated GPIO id=12
[    0.811692] gpio-of-helper ocp:cape-universal: Allocated GPIO id=13
[    0.811838] gpio-of-helper ocp:cape-universal: Allocated GPIO id=14
[    0.811988] gpio-of-helper ocp:cape-universal: Allocated GPIO id=15
[    0.812144] gpio-of-helper ocp:cape-universal: Allocated GPIO id=16
[    0.812293] gpio-of-helper ocp:cape-universal: Allocated GPIO id=17
[    0.812445] gpio-of-helper ocp:cape-universal: Allocated GPIO id=18
[    0.812598] gpio-of-helper ocp:cape-universal: Allocated GPIO id=19
[    0.812752] gpio-of-helper ocp:cape-universal: Allocated GPIO id=20
[    0.812907] gpio-of-helper ocp:cape-universal: Allocated GPIO id=21
[    0.813055] gpio-of-helper ocp:cape-universal: Allocated GPIO id=22
[    0.813189] gpio-of-helper ocp:cape-universal: Allocated GPIO id=23
[    0.813332] gpio-of-helper ocp:cape-universal: Allocated GPIO id=24
[    0.813467] gpio-of-helper ocp:cape-universal: Allocated GPIO id=25
[    0.813602] gpio-of-helper ocp:cape-universal: Allocated GPIO id=26
[    0.813842] gpio-of-helper ocp:cape-universal: Allocated GPIO id=27
[    0.814192] gpio-of-helper ocp:cape-universal: Allocated GPIO id=28
[    0.814350] gpio-of-helper ocp:cape-universal: Allocated GPIO id=29
[    0.814491] gpio-of-helper ocp:cape-universal: Allocated GPIO id=30
[    0.814629] gpio-of-helper ocp:cape-universal: Allocated GPIO id=31
[    0.814774] gpio-of-helper ocp:cape-universal: Allocated GPIO id=32
[    0.814911] gpio-of-helper ocp:cape-universal: Allocated GPIO id=33
[    0.815048] gpio-of-helper ocp:cape-universal: Allocated GPIO id=34
[    0.815196] gpio-of-helper ocp:cape-universal: Allocated GPIO id=35
[    0.815338] gpio-of-helper ocp:cape-universal: Allocated GPIO id=36
[    0.815485] gpio-of-helper ocp:cape-universal: Allocated GPIO id=37
[    0.815624] gpio-of-helper ocp:cape-universal: Allocated GPIO id=38
[    0.815762] gpio-of-helper ocp:cape-universal: Allocated GPIO id=39
[    0.815909] gpio-of-helper ocp:cape-universal: Allocated GPIO id=40
[    0.816053] gpio-of-helper ocp:cape-universal: Allocated GPIO id=41
[    0.816194] gpio-of-helper ocp:cape-universal: Allocated GPIO id=42
[    0.816343] gpio-of-helper ocp:cape-universal: Allocated GPIO id=43
[    0.816354] gpio-of-helper ocp:cape-universal: ready
[    0.822156] wkup_m3_ipc 44e11324.wkup_m3_ipc: could not get rproc handle
[    0.824170] Serial: 8250/16550 driver, 6 ports, IRQ sharing disabled
[    0.827881] 44e09000.serial: ttyS0 at MMIO 0x44e09000 (irq = 158, base_baud =                                                                                3000000) is a 8250
[    1.921701] console [ttyS0] enabled

"Important" things like GPIOs and I2C appear to be running at the very beginning of the boot process. How could I do the same thing with spidev?
I am a little unclear where in the boot process is the pocketbeagle's device tree being "declared"? Where in the boot process does /dev/spidev becomes available? And how can I make it start earlier?

A: Summarizing @sawdust and my comments into an answer:

*

*Don't use SPIdev for this

*Use the Linux Framebuffer drivers for small TFT LCD display modules

*Set bootdelay to 0 or -2 in U-Boot Env

*

*Don't worry about the warning, you can recover and modify the Env file by booting from SD card or if on SD, by modifying its contents on a computer.

*Add a systemd service to render your splash screen early during boot

*

*Simple and has some good pointers

*Quite verbose, not everything applies (e.g. console), but might contain some good bits to selectively pick out


text:
Q: Maximizing a certain eigenvalue ratio Let $A\in\mathbb{R}^{n\times n}$ be an Hurwitz stable matrix (i.e., the spectrum of $A$ lies on the left-half complex plane) and let $P$ be the unique positive definite solution of the following Lyapunov equation
$$
AP+PA^\top = -Q,
$$
where $Q\in\mathbb{R}^{n\times n}$ is a positive definite matrix. Moreover, let $\lambda_{\min}(X)$ and $\lambda_{\max}(X)$ denote the smallest and largest (resp.) eigenvalue of the positive definite matrix $X$.

My question. For which positive definite $Q$ the following ratio
  $$
r(Q) = \frac{\lambda_\min(Q)}{\lambda_\max(P)}
$$
  is maximized and what is the value of the maximum?