Q: Wordpress API works with VPN only? I'm working on a project on my localhost for sometime now, and i've recently tried to make it online. My project works perfectly on my localhost, and I can post new articles to wordpress blogs with no problem.
The problem is, after uploading my project to a online web server ( Hostgators Baby Plan ) , I tried to add a new post to one of my wordpress blogs and I got the following error :
faultCode 500 faultString You are not allowed to do that.

The thing is, I've searched everywhere in the past few days in-order to solve this problem and had no luck.
Do you guys think this problem is caused because i'm using a webserver and not a VPS? If you have any other solutions I'll be glad to hear them out.

A: It might be related to file permissions or something like that.
There is no need to use VPS. I manage my website on a shared server and I've tested WordPress on free hosting services too.

A: This is probably due to incorrect permissions either on the file structure or the mySQL DB user or something like that.  Take a look at this article on the WP codex about file permissions.
Big services like Hostgater usually have an "auto-install" feature for common software like Wordpress (via Softaculous or something similar).  I don't know how you migrated your site from your local version to the server but it may be worth installing a fresh Wordpress instance through Hostgator and then simply loading in the wp-content folder and your development database on top of that.


Q: SQL query to find maximum tax brackets I have a database table of tax brackets in a variety of locations with the fields: location, tax_bracket, and tax_rate.
I need to create a query that will return a list of countries, with their highest tax rate, that have at least one tax bracket with a tax rate over X.
How could I accomplish this?

A: Here is a sample to get you started, without knowing your schema:
Select
  LocationName,
  MaxTaxRate
FROM
  (select
    Max(tax_rate) as MaxTaxRate,
    LocationName
  from
    MyLocations
  group by
    LocationName
  ) as MaxTable

You will have to join up with other information, but this is as far as I can go efficiently without more schema info.

A: select location, max(tax_rate) from tax_brackets where tax_rate > x group by location
the tax_rate > x should filter all tax_rates lower x, which means if the location has no tax_rates over x, they do not have at least one rate over x, which means they won't appear in the group by.
The group by should organize by location.
The select does location and max of those per location.


Q: javax.servlet.http.Cookie vs javax.ws.rs.core.Cookie Being new to web development, I need some help in understanding what is the difference between the javax.servlet.http.Cookie and javax.ws.rs.core.Cookie.I assume that the latter can be used to set cookie into the response of a rest service. But can we also set the initial Cookie object into the HTTPServletResponse?

A: These are objects that represent the same underlying entity, namely an HTTP cookie as defined by the RFC. Both "do" the same thing, representing a cookie header in an HTTP response (a request cookie is a name=value pair only, whereas response cookies can have several additional attributes as described in the RFC). Where you use one vs the other is simply a matter of what you are coding. If you are writing a JAX-RS provider, then the JAX-RS apis will use javax.ws.core.Cookie. If you are writing an HttpServlet, then you use the javax.servlet.http.Cookie. JAX-RS implementations will also allow you to use context injection so that you can have direct access to the HttpServlet objects within your JAX-RS service provider

A: javax.servlet.http.Cookie is created and placed on the HTTP response object with the addCookie method.
Instead, the description for javax.ws.core.Cookie reads:

Represents the value of a HTTP cookie, transferred in a request

… so you'd expect the getCookies method on the HTTP request object to return an array of that type of cookies, but no, it returns an array of javax.servlet.http.Cookie. Apparently javax.ws.core.Cookie is used by some methods in the javax.ws.rs packages. So you use javax.ws.core.Cookie with jax-rs web services and javax.servlet.http.Cookie with HttpServlets and their request / response objects.


Q: Running NPM install locally deletes required packages from my package-lock.json. This causes Git actions to fail when running NPM ci? When I run npm install, remove or add any package (or do anything that changes the local package.json) and commit to a PR branch, I get the following error in the github actions "run npm ci" build.
npm ERR! `npm ci` can only install packages when your package.json and package-lock.json or npm-shrinkwrap.json are in sync. Please update your lock file with `npm install` before continuing.
npm ERR!
npm ERR! Missing: webpack@5.74.0 from lock file
npm ERR! Missing: @types/eslint-scope@3.7.4 from lock file

Things i've tried:

*

*Deleting node modules & package-lock.json & running npm i - DOESNT WORK

*Changing my github main.yml to npm ci --legacy-peer-deps - DOES FIX THIS BUG but causes other weird bugs about paths to other React components withing my project to not be found with a Type error: Cannot find module '../ etc" (they all work fine if the old package-lock is used)

*Pasting the old package-lock.json to overwrite my local copy and committing - WORKS? But I can never actually remove or add packages.

Running npm ci locally works perfectly fine.
In summary:
If I create a new branch from main > npm install a new package & push the updated package.json and package-lock.json to the branch > it fails the github actions check on npm ci with the above npm ERR because the package-lock.json does not match.
I'm stumped, any help would be greatly appreciated.


Q: C++ code -calling a constructor of one class within a constructor of same class I am trying to compile this C++ code unfortunately, I failed to compile the code below. Can you help me by explaining why I am getting this error ?
#include <iostream>
#include <cstring>
using namespace std;

class student
{
   private:
    char name[10];
    int id;
    int fee;
       public:
           student(char name[10],int id)
           {
               strcpy(this->name,name);  //string copy
               this->id=id;
               fee=0;
           }
           student(char name[10],int id,int fee)
           {
               student::student(name,id); //calling a constructor of one class
                                         // within a constructor of same class
               this->fee=fee;
           }
           void show() //print function
           {
               cout<<"Name:"<<name<<endl;
               cout<<"id:"<<id<<endl;
               cout<<"fee:"<<fee<<endl<<endl;
           }
};

int main()
{
 student s1("DAVID",123);
 student s2("WILLIAM",124,5000);
 s1.show();
 s2.show();

    return 0;
}

Below is the error GCC is complaining about.:
main.cpp|20|error: cannot call constructor 'student::student' directly [-fpermissive]|

A: As rightly suggested by @sweenish, You must do the constructor delegation in the initialization section. Something like this:
#include <iostream>
#include <cstring>
using namespace std;

class student
{
   private:
    char name[10];
    int id;
    int fee;
       public:
           student(char name[10],int id)
           {
               strcpy(this->name,name);  //string copy
               this->id=id;
               fee=0;
           }
           student(char name[10],int id,int fee): student(name, id) // constructor delegation
           {
               this->fee=fee;
           }
           void show() //print function
           {
               cout<<"Name:"<<name<<endl;
               cout<<"id:"<<id<<endl;
               cout<<"fee:"<<fee<<endl<<endl;
           }
};

int main()
{
 student s1("DAVID",123);
 student s2("WILLIAM",124,5000);
 s1.show();
 s2.show();

    return 0;
}

Also, an advice for you. You may define the more specialized constructor and delegate the responsibility of less specialized constructors to more specialized ones.
#include <iostream>
#include <cstring>
using namespace std;

class student
{
   private:
    char name[10];
    int id;
    int fee;
       public:
           student(char name[10],int id, int fee): id{id}, fee{fee} // more specialized
           {
               strcpy(this->name,name);  //string copy
           }
           student(char name[10],int id): student(name, id, 0) { } // less specialized calling the more specialized constructor
           void show() //print function
           {
               cout<<"Name:"<<name<<endl;
               cout<<"id:"<<id<<endl;
               cout<<"fee:"<<fee<<endl<<endl;
           }
};

int main()
{
 student s1("DAVID",123);
 student s2("WILLIAM",124,5000);
 s1.show();
 s2.show();

    return 0;
}

A: Here's your code with changes made to get it compiling; I marked the changes with comments.
#include <iostream>
// #include <cstring>  // CHANGED: Prefer C++ ways when writing C++
#include <string>  // CHANGED: The C++ way
// using namespace std;  // CHANGED: Bad practice

class student {
 private:
  std::string name{};  // CHANGED: Move from C-string to std::string
  int id = 0;          // CHANGED: Default member initialization
  int fee = 0;

 public:
  // CHANGED: Move from C-string to std::string
  student(std::string name, int id)
      : name(name),
        id(id)
  // CHANGED: ^^ Utilize initialization section
  {
    // CHANGED: Not needed anymore
    //  strcpy(this->name,name);  //string copy
    //  this->id=id;
    //  fee=0;
  }

  student(std::string name, int id, int fee) : student(name, id) {
    // CHANGED: Not needed anymore
    //  student::student(name,id); //calling a constructor of one class
    //                            // within a constructor of same class
    // NOTE: Inconsistency with other ctor w.r.t. this->
    this->fee = fee;
  }

  void show()  // print function
  {
    std::cout << "Name:" << name << '\n';
    std::cout << "id:" << id << '\n';
    std::cout << "fee:" << fee << "\n\n";
  }
};

int main() {
  student s1("DAVID", 123);
  student s2("WILLIAM", 124, 5000);
  s1.show();
  s2.show();

  return 0;
}

Here is the same code, but with the stuff I commented out removed to make it easier to read.
#include <iostream>
#include <string>

class student {
 private:
  std::string name{};
  int id = 0;
  int fee = 0;

 public:
  student(std::string name, int id) : name(name), id(id) {}

  student(std::string name, int id, int fee) : student(name, id) {
    this->fee = fee;
  }

  void show()
  {
    std::cout << "Name:" << name << '\n';
    std::cout << "id:" << id << '\n';
    std::cout << "fee:" << fee << "\n\n";
  }
};

int main() {
  student s1("DAVID", 123);
  student s2("WILLIAM", 124, 5000);
  s1.show();
  s2.show();

  return 0;
}

The initialization section follows the parameter list and is marked with :. You then initialize each member, in the order they are declared.
In the case of the constructor doing the delegating, you are unable to initialize fee in the initialization section. The error I receive is a delegating constructor cannot have other mem-initializers.
I don't like splitting my initialization like that, and if you insist on delegating constructor calls for this class, implement the most specific constructor and delegate to it with your less specific constructors. I prefer default member initialization as I think it leads to less confusion and written code overall.
The code then compiles and you get the expected output:
Name:DAVID
id:123
fee:0

Name:WILLIAM
id:124
fee:5000


Q: Creating a custom command as an alternative to setValue() where I can control the type speed Hope someone can help with this. I have come across an issue with the application im testing. The developers are using vue.js library and there are a couple of fields which reformat the entered test. So for example if you enter phone number, the field will automatically enter the spaces and hyphens where its needed. This is also the same with the date of birth field where it automatically enters the slashes if the user does not.
So the issue I have is that using both 'setValue()' or 'sendKeys()' are entering the text too fast and the cursor in the field sometimes cannot keep up and the text entered sometimes appears in the incorrect order. For example, if I try to enter '123456789'. Some times it ends up as '132456798' (or any other combination). This cannot be produced manually and sometimes the test does pass. But its flakey.
What I wanted to do was to write a custom command to do something where it enters the string but in a slower manner. For this I need to have control of how fast I want the text to be entered. So I was thinking of something like this where I can pass in a selector and the text and then it will enter one character at a time with a 200 millisecond pause in between each character. Something like this:
let i = 0;
const speed = 200; // type speed in milliseconds

exports.command = function customSetValue(selector, txt) {
  console.log(selector);
  console.log(txt);
  if (i < txt.length) {
    this.execute(function () {
      document.getElementsByName(selector).innerHTML += txt.charAt(i);
      i++;
      setTimeout(customSetValue, speed);
    }, [selector, txt]);
  }
  return this;
};

When running document.getElementsByName(selector) in browser console I get a match on the required element. But it is not entering any text. Also note that I added a console.log in there and I was actually expecting this to log out 14 times but it only logged once. So itss as if my if condition is false
I checked my if condition and it should be true. So not sure why its not reiterating the function. Any help is much appreciated.
Also if it helps. I am using the .execute() command to inject javascript which is referenced here: https://nightwatchjs.org/api/execute.html
And the idea on this type writer is based on this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter

A: We ended up taking a different approach much simpler. Wanted to post here in case anyone else ever needs something similar
exports.command = function customSetValue(selector, txt) {
  txt.split('').forEach(char => {
    this.setValue(selector, char);
    this.pause(200); // type speed in milliseconds
  });
  return this;
};


Q: Toolbar overlaps status bar I've got a problem with my status bar which gets overlapped by the toolbar.
I wanted to have the function that when the user scrolles the ListView down, the toolbar disappears behind the status bar so that only the tabs are visible, just like in the WhatsApp and YouTube apps.
To achieve this effect or to get this function I used this line:
app:layout_scrollFlags="scroll|enterAlways"

into my android.support.v7.widget.Toolbar, but know as I said before, the status bar gets overlapped by the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

Thankful for any help!
UPDATE:
v21\styles.xml
<resources>>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

styles.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>

A: in v21\styles.xml
remove
<item name="android:statusBarColor">@android:color/transparent</item>

A: Try add android:fitsSystemWindows="true" to android.support.design.widget.AppBarLayout or @style/AppTheme.PopupOverlay style

A: This works for me to get a white overlay on device status bar (problem after update in question)
I changed:
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

to
<item name="android:windowDrawsSystemBarBackgrounds">false</item>

in my styles.xml file

A: try making android:layout_height="?attr/actionBarSize" for  android.support.v7.widget.Toolbar


Q: Remove element from array in mongodb I am new in mongodb and i want to remove the some element in array.
my document as below
{
  "_id" : ObjectId("4d525ab2924f0000000022ad"),
  "name" : "hello",
  "time" : [
      {
              "stamp" : "2010-07-01T12:01:03.75+02:00",
              "reason" : "new"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+03:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+04:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+05:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+06:00",
              "reason" : "update"
      }
  ]
}

in document, i want to remove first element(reason:new) and last element(06:00) .
and i want to do it using mongoquery, i am not using any java/php driver.

A: If I'm understanding you correctly, you want to remove the first and last elements of the array if the size of the array is greater than 3. You can do this by using the findAndModify query. In mongo shell you would be using this command:
db.collection.findAndModify({
    query: { $where: "this.time.length > 3" },
    update: { $pop: {time: 1}, $pop: {time: -1} },
    new: true
});

This would find the document in your collection which matches the $where clause.
The $where field allows you to specify any valid javascript method. Please note that it applies the update only to the first matched document.
You might want to look at the following docs also:

*

*http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D for more on the $where clause.

*http://www.mongodb.org/display/DOCS/Updating#Updating-%24pop for
more on $pop.

*http://www.mongodb.org/display/DOCS/findAndModify+Command for more
on findAndModify.

A: You could update it with { $pop: { time: 1 } } to remove the last one, and { $pop: { time : -1 } } to remove the first one.  There is probably a better way to handle it though.

A: @javaamtho you cannot test for a size greater than 3 but only if it is exactly 3, for size greater than x number you should use the $inc operator and have a field you either 1 or -1 to in order to keep track when you remove or add items (use a separate field outside the array as below, time_count)
{
  "_id" : ObjectId("4d525ab2924f0000000022ad"),
  "name" : "hello",
  "time_count" : 5,
  "time" : [
      {
              "stamp" : "2010-07-01T12:01:03.75+02:00",
              "reason" : "new"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+03:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+04:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+05:00",
              "reason" : "update"
      },
      {
              "stamp" : "2010-07-02T16:03:48.187+06:00",
              "reason" : "update"
      }
  ]
}

A: If you would like to leave these time elements, you can use aggregate command from mongo 2.2+ to retrieve min and max time elements, unset all time elements, and push min and max versions (with some modifications it could do your job):
smax=db.collection.aggregate([{$unwind: "$time"},
{$project: {tstamp:"$time.stamp",treason:"$time.reason"}},
{$group: {_id:"$_id",max:{$max: "$tstamp"}}},
{$sort: {max:1}}])

smin=db.collection.aggregate([{$unwind: "$time"},
{$project: {tstamp:"$time.stamp",treason:"$time.reason"}},
{$group: {_id:"$_id",min:{$min: "$tstamp"}}},
{$sort: {min:1}}])

db.students.update({},{$unset: {"scores": 1}},false,true)

smax.result.forEach(function(o)
{db.collection.update({_id:o._id},{$push:
{"time": {stamp: o.max ,reason: "new"}}},false,true)})

smin.result.forEach(function(o)
{db.collection.update({_id:o._id},{$push:
{"time": {stamp: o.min ,reason: "update"}}},false,true)})

A:
db.collection.findAndModify({
      query: {$where: "this.time.length > 3"},
      update: {$pop: {time: 1}, $pop{time: -1}},
      new: true });

convert to PHP


Q: Silverlight and MikesFlipControl I would like to know when using some third party silverlight controls that are a container control why the controls that are conatined within them are not accessable in code behind. until the control is loaded. The example I am looking at is when using the FlipControl written by Mike Taulty.
Whehn I use his control and place a grid in the front container and texblocks in the behind container. only the grid is availabe at runtime until the flip is done that then show the behind container that then fires the load event of the text block. I woudl liek to populate these textblock before the flip is done but when I do I get object reference error because the textblock is null.
Any help on this would be great, here is mikes blog on this.
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/04/27/silverlight-3-simple-flip-control-built-on-planeprojection.aspx
Thanks in advance.

A: Although I'm not actually looking at Mikes code (you could do that though) I would imagine he has a single content control to which he has assigned the Front content originally.  On Flip a projection is animated until its edge on at which point the Rear content is assigned, and the animation continues.
Hence at anyone time the only one of Front or Rear content can actually be navigated to with something like FindName
However if you give each of the root Child controls that you place in Front and Rear their own x:Name you should be able gain access to your text boxes using the rear name.


Q: Samsung Galaxy S8+ : Device Metrics Gives wrong device screen pixel density This is how I am getting the screen density using Android Studios
float density = getResources().getDisplayMetrics().density;

According to device specification, S8+ has 4.0 Density value and falls under xxxhdpi category
Refer this site https://material.io/devices/,
Have Attached  a screenshot for reference
here
But the value returned by the above code is 2.9,  which seems very wrong
check here
Tried using densityDpi also, but it also returns xxhdpi as opposed to xxxhdpi
int densityDpi = context.getResources().getDisplayMetrics().densityDpi;

The above code works well on other devices, tested on OnePlus 5T, Nexus 6P, Redmi Note 4, Moto g4+ and others...facing issues with the Galaxy s8+, haven't tested for Galaxy s8 but i guess the result will be same.
Is this a know Bug, or am I doing something wrong?
Its getting difficult to manage layout for S8+ devices without the correct pixel density info for s8+ devices.

A: You need to initialize display metrics object
You can try this:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
flat density=metrics.density;
flat densityDpi=metrics.densityDpi;

A: Just like Surfman said. Your phone isn't at the maximum possible resolution. If you take the resolution reported within your screenshot and divide it by the reported 2.9 and multiply it by 4 you end up with roughly the maximum resolution of 2960x1440


Q: Validation for Search box Need a validation for my search box that should allow space and %. The below mentioned letters should not be allowed.
< > ( ) ' " / \  * ; : = { } `(backtick) % + ^ ! - \x00-\x20

I tried by using JS code, please see the code :-
  <script type="text/javascript">
    var specialKeys = new Array();
    specialKeys.push(8); //Backspace
    specialKeys.push(9); //Tab
    specialKeys.push(46); //Delete
    specialKeys.push(36); //Home
    specialKeys.push(35); //End
    specialKeys.push(37); //Left
    specialKeys.push(39); //Right
    function IsAlphaNumeric(e) {
        var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
        var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
        document.getElementById("error").style.display = ret ? "none" : "inline";
        return ret;
    }
</script>

let me know what needs to be modified or added in the above mentioned code.

A: You Can use Java Script Regular Expression to validate input following code will do what you want
$('input').bind('keypress', function (event) {
        var regex = new RegExp("^[a-zA-Z0-9\b _ _%]+$");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
           event.preventDefault();
           return false;
        }
    });

Here is a working js fiddle example
Validation Js Fiddle

A: Try this example:
script
$(function(){
    $("input.rejectSpecial").on('input', function(){
        this.value = this.value.replace(/(\>|\<|\(|\)|\"|\'|\\|\/|\*|;|\:|\=|\{|\}|`|%|\+|\^|\!|\-)/g, '');
    });
})

html
<input type="text" placeholder="special letters not allowed" size="30" class="rejectSpecial"/>
<input type="text" placeholder="does nothing" size="30"/>
<input type="text" placeholder="special letters not allowed" size="30" class="rejectSpecial"/>


Q: Why can I only make GET requests and not POST requests with this python code? I'm trying to get this Etrade stuff up an running.... so far i have:
from rauth import OAuth1Service
import webbrowser

def getSession():
    # Create a session
    # Use actual consumer secret and key in place of 'foo' and 'bar'
    service = OAuth1Service(
              name = 'etrade',
              consumer_key = 'cabf024eaXXXXXXXXX7a0243d8d',
              consumer_secret = '3d05c41XXXXXXXXX1949d07c',
              request_token_url =
'https://etws.etrade.com/oauth/request_token',
              access_token_url =
'https://etws.etrade.com/oauth/access_token',
              authorize_url = 'https://us.etrade.com/e/t/etws/authorize?
key={}&token={}',
              base_url = 'https://etws.etrade.com')

    # Get request token and secret
    oauth_token, oauth_token_secret = service.get_request_token(params =
                              {'oauth_callback': 'oob',
                               'format': 'json'})

    auth_url = service.authorize_url.format('cabf0XXXXXXXXXa0243d8d',
oauth_token)

    webbrowser.open(auth_url)
    verifier = raw_input('Please input the verifier: ')

    return service.get_auth_session(oauth_token, oauth_token_secret,
params = {'oauth_verifier': verifier})

session = getSession()

This authentication process works perfectly fine and allows me to do get/delete requests but when I attempt to make post requests:
url =
'https://etwssandbox.etrade.com/order/sandbox/rest/previewoptionorder'
para = {
    "PreviewOptionOrder": {
     "-xmlns": "http://order.etws.etrade.com",
     "OptionOrderRequest": {
       "accountId": "83550325",
       "quantity": "4",
       "symbolInfo": {
         "symbol": "AAPL",
         "callOrPut": "CALL",
         "strikePrice": "585",
         "expirationYear": "2012",
         "expirationMonth": "07",
         "expirationDay": "21"
       },
       "orderAction": "BUY_OPEN",

                           "priceType": "MARKET",
       "orderTerm": "GOOD_FOR_DAY"
     }
   }
 }
resp = session.post(url,data=para)
resp.text

I get an error:
Unauthorized request: consumer key is missing.

I've tried numerous things (granted I am new to this stuff). I tried authenticating using just requests to no avail and I tried passing the oauth1 object to the posts function as a kw argument. Any ideas?


Q: Order object hold a Customer object or the customers ID or both? If I have an Order object and each Order has a Customer what should the Order object hold, a Customer object or the customers ID or both?
Does it depend on the context or since we are dealing with objects in OOP the Order should ideally hold a Customer object and not just its ID like the database column?
Thanks.

A: Do not mix db thinking with PHP code design.. Regulary the property should be set to the object itself rather then to its id. Like this:
class Order {

    /**
     * @var Contact
     */
    protected $contact;

    public function __construct(Contact $contact) {
        $this->contact = $contact;
    }

}

But there are reasons when it might make sense to just have to id of the contact. The best example would be that the contact has to be fetched from database, but you regulary don't need its information, expect of special cases. Then it might be useful to only have the id as class property and fetch the contact if required. (Known as 'lazy loading'). Note that 'lazy loading' could be hidden behind the scenes by a framework.


Q: Difference between `Pin: release v` and `Pin: version` in apt preferences file I can't seem to find anything related to the difference between Pin: version 5.8 and Pin: release v=5.8 in the documentation for the apt preferences file.
Do they do the same thing or have differences?
Also there is a similar occurrence between Pin: origin "origin" and Pin: release o=origin.

A: After more digging I've figured it out.
TL;DR
Pin: release X=Y filters against fields of the Release file using shorthand notation. In the release file the version should be the version of the release. e.g.) for Debian bullseye you could have Pin: release v=11, or for Ubuntu Jammy you could have Pin: release v=22.04. Origin should the author or vendor name. e.g.) Pin: release o=LP-PPA-mozillateam.
Pin: version X filters against the package version. e.g.) Pin: version 1:91.
Pin: origin X filters against the hostname. e.g.) Pin: origin ppa.launchpad.net.
Release File
In the Determination of Package Version and Distribution Properties section of man apt_preferences we find this.

The locations listed in the sources.list(5) file should provide Packages and Release files to describe the packages available at that location.

So each location (which has an origin) has a release file for each release available. In that link, we see the release file is hosted at dists/$DIST/InRelease.
On my local machine we have
$ apt-cache policy
 500 http://ppa.launchpad.net/mozillateam/ppa/ubuntu jammy/main amd64 Packages
     release v=22.04,o=LP-PPA-mozillateam,a=jammy,n=jammy,l=Firefox ESR and Thunderbird stable builds,c=main,b=amd64
     origin ppa.launchpad.net

Here, you can see my local machine is using the jammy release. So the relevant release file is located at dists/jammy/InRelease. This gives us this file here: http://ppa.launchpad.net/mozillateam/ppa/ubuntu/dists/jammy/InRelease.
That release file is created by the person hosting the repository and contains meta-information about the distribution. Some of the information is optional, and some is not. Some of the optional fields include:

*

*Origin

*Label

*Version

*Suite

*Codename

And some of the non-optional fields include:

*

*Components

This is what you filter against when you specify Pin: release X= in your preferences file. It is also described when you run apt-cache policy. In the example above, we have:

*

*Origin: o=LP-PPA-mozillateam

*Label: l=Firefox ESR

*Version: v=22.04

*Suite: a=jammy

*Codename: n=jammy

*Components: c=main
NB: I couldn't find anything in the man page in relation to the b= field in the output of the apt-cache policy command.
Origin
As well as the above information in the release file, the location also has an origin. This is also included in the output of the apt-cache policy command. As you can see for the example above, it is ppa.launchpad.net.
This is what you filter against when you include Pin: origin X in your preferences file.
In the The Effect of APT Preferences section of the man page, it has this useful sentence:

This should not be confused with the Origin of a distribution as specified in a Release file. What follows the "Origin:" tag in a Release file is not an Internet address but an author or vendor name, such as "Debian" or "Ximian".

Version
Back to the Determination of Package Version and Distribution Properties section of the man page.
As mentioned above, it states:

The locations listed in the sources.list(5) file should provide Packages and Release files to describe the packages available at that location.

So as well as this release file, we also have a packages file. The man page goes on to say:

Only two lines in each record [of the package file] are relevant for setting APT priorities:
the Package: line
    gives the package name
the Version: line
    gives the version number for the named package

This is different to what it says for the Version field of the Release file, for which it says

the Version: line
    names the release version. For example, the packages in the tree might belong to Debian release version 11.

If we find one of these package files, we can see this. For the package above, for my architecture, it is here: http://ppa.launchpad.net/mozillateam/ppa/ubuntu/dists/jammy/main/binary-amd64/Packages.xz
Within that compressed archive, we have a Packages file which contains a list of all the packages available and their versions (and lots of other information). Here is part of one of the many packages available:
Package: thunderbird
Priority: optional
Section: mail
Installed-Size: 227239
Maintainer: Ubuntu Mozilla Team <ubuntu-mozillateam@lists.ubuntu.com>
Architecture: amd64
Version: 1:91.5.1+build1-0ubuntu1

This version is what you fiter against when you include Pin: version X in your preferences file.
If you run apt-cache policy on a specific package, you can see the versions available for that package.
$ apt-cache policy thunderbird
thunderbird:
  Installed: 1:78.14.0-1~deb11u1
  Candidate: 1:78.14.0-1~deb11u1
  Version table:
     1:91.5.1+build1-0ubuntu1 500
        500 http://ppa.launchpad.net/mozillateam/ppa/ubuntu jammy/main amd64 Packages
     1:91.5.1-1+b2 10
         10 http://ftp.us.debian.org/debian unstable/main amd64 Packages
     1:91.5.0-2~deb11u1 500
        500 http://security.debian.org/debian-security bullseye-security/main amd64 Packages
 *** 1:78.14.0-1~deb11u1 900
        900 http://deb.debian.org/debian bullseye/main amd64 Packages
        100 /var/lib/dpkg/status

Confusion with Version
It appears that the version specified in the release file doesn't always appear to be correct. For example, for Google Chrome, we have this:
$ apt-cache policy
 900 http://dl.google.com/linux/chrome/deb stable/main amd64 Packages
     release v=1.0,o=Google LLC,a=stable,n=stable,l=Google,c=main,b=amd64
     origin dl.google.com

I'm not sure what this version is supposed to represent, as it doesn't match the versions in the packages file:
$ grep "Package\|Version" /var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-amd64_Packages
Package: google-chrome-beta
Version: 99.0.4844.17-1
Package: google-chrome-stable
Version: 98.0.4758.80-1
Package: google-chrome-unstable
Version: 100.0.4867.0-1


Q: real eigenvalue
Let matrix $A$ be
  $$\begin{bmatrix}
 -5& 1& 0& 0\\
  a &2& 1 &0\\
  0& 1 &1 &1\\
  0 &0&1& 0
\end{bmatrix}$$
  where $a$ is a constant between 1 and 3.
Show that the dominant eigenvalue is real.

Thanks a lot!!

A: $A$ is a real tridiagonal matrix. One property of real tridiagonal matrices is this: if the signs of the entries in the upper and lower diagonals are symmetric (i.e. the $(i,\,i+1)$-th and $(i+1,\,i)$-th entries have the same sign for every $i$), then the matrix is similar to a real symmetric matrix and hence all of its eigenvalues are real. Now this is your case here.


Q: Save error: Illegal assignment from String to Integer I need a string value transformed to a integer so that I can use it in a number field.
Integer leadSize=(Integer.valueOf(email.plaintextbody.split('Base: ').size()) > 1) ? email.plaintextbody.split('Base: ').get(1).split('\\.00').get(0).replaceAll(',','') : '';

The above code gives me a compile error:

Save error: Illegal assignment from String to Integer

How can I fix this error?

A: try this
Integer leadSize=(Integer.valueOf(email.plaintextbody.split('Base: ').size()) > 1) ? Integer.valueOf(email.plaintextbody.split('Base: ').get(1).split('\.00').get(0).replaceAll(',','')) : 0;


Q: PHP for loop to while loop Hey studying for exams and have this loop.
<?php
$ab = 0;
$xy = 1;

echo "
";

for ($i = 0; $i < 5; $i++) {
    echo "
";

    echo "" . $ab . "	" . $xy . "	";
    $ab += $xy;     $xy += $ab;

    echo "
";
}
echo "
";

the question is now how do i rewrite this as while loop ? what to keep in mind,
thanks !

A: $ab = 0;
$xy = 1;
echo "
";
$i = 0;
while ($i < 5) {
    echo "
$ab	$xy
";
    $ab += $xy;
    $xy += $ab;
    $i++;
}
echo "
";

For explanation :
Compared to the "for" loop, you have to initialize the "counter" before opening the loop [ $i = 0 ]
Inside the loop, you specify the condition to continue the loop [ $i < 5 ]
And somewhere into the loop, you increase your "counter" [ $i++ ]
Your "counter" can be increased or decreased, or directly set ; it's all about your code logic and what are your needs.
You can also break the loop whenever you want in case you need to, see an example :
while ($i < 5) {
    echo "
$ab	$xy
";
    $ab += $xy;
    $xy += $ab;
    if ($ab == 22) { // If $ab is equal to a specific value
        /* Do more stuff here if you want to */
        break; // stop the loop here
    }
    $i++;
}

This example also work with the "for" loop.
And there is also another keyword, "continue", used to tell to "jump" to the next loop iteration :
while ($i < 5) {
    $i++; // Don't forget to increase "counter" first, to avoid infinite loop
    if ($ab == 22) { // If $ab is equal to a specific value
        /* Do more stuff here if you want to */
        continue; // ignore this iteration
    }

    /* The following will be ignored if $ab is equal to 22 */
    echo "
$ab	$xy
";
    $ab += $xy;
    $xy += $ab;
}

A: To replace a for loop with a while loop, you can declare a variable before you initiate the while loop which will indicate the current iteration of the loop. Then you can decrement/increment this variable upon each iteration of the while loop. So you would have something like this:
$counter = 0;
while ($counter < 5) {
  echo "";
  echo "" . $ab . "	" . $xy . "	";
  $ab += $xy;
  $xy += $ab;
  echo "
";
  $counter++;
}

in general:
for ($i = 0; $i < x; $i++) {
  do stuff
}

is equivalent to:
$counter = 0;
while ($counter < x){
  do stuff
  counter++;
}


Q: How can I attach the jar produced by one maven module to another module with a classifier? I have a project for which I've done some refactoring (and module names clarifications).
As a consequence, the module that was neo4j-connector-impl has now become neo4j-connector-1.6. Now, for better compatibility, i want to have the jar produced by this project also be available as neo4j-connector-impl (its old name, if you follow me).
I have created a pom typed project under those GAV coordinates, and have tried attaching the jar using a mix of maven-dependency-plugin and build-helper-maven-plugin.
Unfortunatly, each time I build my project, that jar is not in maven repository and maven says
[INFO] Installing C:\Users\ndx\Documents\workspaces\git\neo4j-connector\neo4j-connector-impl-parent\neo4j-connector-impl\neo4j-connector-impl-1.6.jar to C:\Users\ndx\.m2\repository\com\netoprise\neo4j-connector-impl\1.6-SNAPSHOT\neo4j-connector-impl-1.6-SNAPSHOT.jar
[DEBUG] Skipped re-installing C:\Users\ndx\Documents\workspaces\git\neo4j-connector\neo4j-connector-impl-parent\neo4j-connector-impl\neo4j-connector-impl-1.6.jar to C:\Users\ndx\.m2\repository\com\netoprise\neo4j-connector-impl\1.6-SNAPSHOT\neo4j-connector-impl-1.6-SNAPSHOT.jar, seems unchanged

So ... how can I put that jar as a classified dependency ?
For info, here is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.netoprise</groupId>
        <artifactId>neo4j-connector-impl-parent</artifactId>
        <version>1.6-SNAPSHOT</version>
    </parent>
    <artifactId>neo4j-connector-impl</artifactId>
    <packaging>pom</packaging>
    <description>Compatibility module ensuring previous code can "quite" work</description>
    <properties>
        <dependencies.directory>${project.build.directory}/dependencies</dependencies.directory>
    </properties>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>${project.artifactId}-1.6</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <includeGroupIds>${project.groupId}</includeGroupIds>
                            <excludeTransitive>true</excludeTransitive>
                            <overWriteSnapshots>true</overWriteSnapshots>
                            <stripVersion>true</stripVersion>
                            <outputDirectory>${dependencies.directory}</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- attach all projects artifact to this one in order for user projects
                to have minimum integration work -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>attach-artifact</goal>
                        </goals>
                        <configuration>
                            <artifacts>
                                <!--  for maximum compatibility, the 1.6 version is attached as default jar artifact -->
                                <artifact>
                                    <file>neo4j-connector-impl-1.6.jar</file>
                                    <type>jar</type>
                                </artifact>
                            </artifacts>
                            <basedir>${dependencies.directory}</basedir>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

EDIT 1 Why are there versions numbers in artifacts ? Because that project (neo4j-jca-connector), provides access to neo4j graph database to various JavaEE servers. The neo4j version SHOULD NOT be constrained by this connector. As a consequence, we have to provide users a way to define, for a version of that connector, which neo4j version is used (considering as default - for backwards compatibility version - the 1.6 one).
As a consequence, we have one module for each version of neo4j,n and these modules are aggregated here. For the record, Bouncycastle do so for JDK versions ... in an even worse version, to my mind, as they use the JDK version directly in artifactId, what I plan to do only internaly : exposed artifacts will be neo4j-connector-impl and neo4j-connector-rar ... and classifiers will allow one to select which neo4j version to use.
EDIT 2 For more info, the whole project can be seen on github : https://github.com/Riduidel/neo4j-connector
The parent pom cotnaining the maven-shade-plugin declaration is https://github.com/Riduidel/neo4j-connector/blob/master/neo4j-connector-impl-parent/pom.xml
One version of that connector is https://github.com/Riduidel/neo4j-connector/blob/master/neo4j-connector-impl-parent/neo4j-connector-impl-1.5/pom.xml
And expected aggregator module should be https://github.com/Riduidel/neo4j-connector/blob/master/neo4j-connector-impl-parent/neo4j-connector-impl/pom.xml

A: Ok this is much clearer after reading your comment and EDIT.
So, correct me if I'm wrong.

*

*You want to be able to provide a version of your connector for each neo4j version

*You use module to do so.

What is still not clear to me, is that I cannot see the modules' part of your POM. You say that you want to use classifiers (so, of the same project) but maven modules are different projects...


Q: How can I resolve HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Read timed out. (read timeout=60) Currently, I have a problem in download data from google cloud storage. Here is the error: HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Read timed out. (read timeout=60)
Although I increase the timeout to 600 -> The error still shows 60. Here is my code:
storage_client = storage.Client.from_service_account_json(SERVICE_ACCOUNT_JSON_FILENAME)
bucket = storage_client.get_bucket(BUCKET_NAME)

blob = bucket.blob('blob_name')
blob.download_to_filename('dest_name', timeout=600)

Moreover, I also changed the timeout as a tuple (connect_timeout, read_timeout)
blob.download_to_filename('dest_name', timeout=(600, 600))
but, It still not working.
Could you please help me solve this problem?
Thank you


Q: How to plot 3D surface with X, Y, Z when Z is a list of list in Python? In my case, X is a range(0, 100), Y is a range(0, 10), Z is a list of list. Z has the same length as X, which is 100, and each element list inside of Z has the same dimension of Y.
Z = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ..., [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]].
I have the following code, but it does not work, it complains two or more arrays have incompatible dimensions on axis 1.
fig = plt.figure(figsize=(200, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.set_xticklabels(x_ax)
ax.set_yticklabels(y_ax)
ax.set_title("my title of chart")

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)

ax.set_zlim(0, 100)

fig.colorbar(surf, shrink = 0.5, aspect = 5)
plt.show()

I guess the error is due to the data structure of Z, how do I make a compatible structure with X, and Y? Thanks

A: Here is a basic 3D surface plotting procedure. It seems that your X and Y are just 1D arrays. However, X, Y, and Z have to be 2D arrays of the same shape. numpy.meshgrid function is useful for creating 2D mesh from two 1D arrays.
import matplotlib.pyplot as plt
from  matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.array(np.linspace(-2,2,100))
y = np.array(np.linspace(-2,2,10))
X,Y = np.meshgrid(x,y)

Z = X * np.exp(-X**2 - Y**2);

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink = 0.5, aspect = 5)

plt.show()


Q: iTunes iPhone 3GS Where are the video recordings stored on Windows XP When you record video with an iPhone 3gs and then backup using iTunes where are those video file stored? I'm trying to retrieve some lost files.
Thanks

A: Which version of iPhone OS are you using?
It's only since 3.0 that videos are backed up. And since 3.1 it won't back up videos over 2gb.
More info from Apple KB
From that same article:

The folder where your backup data is
  stored changes depending on the
  computer's operating system. Since
  iTunes only keeps one backup per
  device, you should ensure the backup
  folder is included in your periodic
  data backup routine.

It looks like if you've backed up the iPhone since losing/removing the videos from the device they won't be in the backup.
In XP the backup is stored at:

\Documents and
  Settings(username)\Application
  Data\Apple Computer\MobileSync\Backup\


Q: How pointer adds extra value in printf? #include <stdio.h>

int main() {
    int *const volatile p=5;
    printf("%d",5/2 + p);

    return 0;
}

Without pointer, output is 7 and if I add pointer then the output of the answer is 13. Kindly give the step by step explanation of this program.

A: The code is invalid. The type of 5/2 + p is int *, while %d requires an int.

Kindly give the step by step explanation of this program.

   5/2 + p =                     // 5/2 is equal to 2
   2 + p =                       // p has type int
   2 * sizeof(int) + (char*)p =  // p is 5
   2 * sizeof(int) + 5 =         // sizeof(int) if 4 on your platform
   2 * 4 + 5 =
   13


Q: React App in same Server and multiple Domains I need to know if it's possible to maintain a React App on a IP (X.XXX.XXX.XX) server, and based on the URL that points to this server, render a different application.
An example of this would be to keep the application on one server, while several companies point their DNS's to the server's IP, and based on the company name, render the correct application.
I searched the internet if there is any way to do this with React Router but I didn't find

A: Use nginx reverse proxy to redirect based on url which will point to your different applications.
You can maintain the same IP for all of them.


Q: How can I reference existing groups in my VBA code? I have already grouped cells in a spreadsheet using DATA>GROUP.
Based on a menu style system, I want to collapse/uncollapse a series of already created groups in a sheet, so that it only shows the selection chosen via the menu choices. I hope this makes sense.


Q: A phrase for selecting multiple options with mouse button down In a desktop application or a website we may have a UI element called multiple select. The user may select multiple options by holding the mouse button down, like so:

Is there a word or a phrase that can be used to describe this specific action? The other way to make a multiple selection is to hold Ctrl and click individual options, but I'm talking about the method where you hold the mouse button down and move the cursor to make the selection.
A technically inclined friend suggested simply multiple select, but it seems too broad, while a non-nerd native speaker said highlighting, which doesn't seem to fit the bill either.
In Finnish, this is commonly called painting the selection, with the mouse acting as a makeshift paintbrush, indicating the selection by painting the options with a different colour.
I believe that a similar action, selecting, for instance, a group of files from the desktop with the mouse button down is called lasso select, but it is different in that the lasso is actually visible.

A: If you want to differentiate between holding ctrl and clicking individual items, and the technique where you click once and then move the pointer across all the items you want selected, this would most likely be called drag select.

Alternatively referred to as click-and-drag, drag-select is the process of clicking on a portion of the screen, holding down the mouse button, and dragging the cursor to another location. This action will select everything from the beginning to the end of the drag.


Q: How to avoid OOM in hsqldb while doing a merge? I have two tables where the first is very large (>50M rows):
CREATE CACHED TABLE Alldistances (
    word1 VARCHAR(70),
    word2 VARCHAR(70),
    distance INTEGER,
    distcount INTEGER
);

and a second that can be also quite large (>5M rows):
CREATE CACHED TABLE tempcach (
    word1 VARCHAR(70),
    word2 VARCHAR(70),
    distance INTEGER,
    distcount INTEGER
);

Both tables have indexes:
CREATE INDEX mulalldis ON Alldistances (word1, word2, distance);
CREATE INDEX multem ON tempcach (word1, word2, distance);

In my java program I am using prepared statements to fill/preorganize data in the tempcach table and then I merge the table to alldistances with:
MERGE INTO Alldistances alld USING (

    SELECT word1,
           word2,
           distance,
           distcount FROM tempcach

    ) AS src (

        newword1,
        newword2,
        newdistance,
        newcount

    ) ON (

            alld.word1 = src.newword1
        AND alld.word2 = src.newword2
        AND alld.distance = src.newdistance

    ) WHEN MATCHED THEN

        UPDATE SET alld.distcount = alld.distcount+src.newcount

    WHEN NOT MATCHED THEN

        INSERT (

            word1,
            word2,
            distance,
            distcount

        ) VALUES (

            newword1,
            newword2,
            newdistance,
            newcount
        );

The tempchach table is then dropped or truncated and filled with new data.
During the merge I get the OOM, which is i guess because the whole table is loaded into memory during the merge. So I will have to merge in batches, but can i do that in SQL or do it in my java program. Or is there a smart way to avoid OOM while merging?

A: It is possible to merge in chunks (batches) in SQL. You need to

*

*limit the number of rows from the temp table in each chunk

*delete those same rows

*repeat

The SELECT statement should use an ORDER BY and LIMIT
SELECT word1,
       word2,
       distance,
       distcount FROM tempcach
       ORDER BY primary key or unique columns
       LIMIT 1000

) AS src (

After the merge, the delete statement will select the same rows to delete
DELETE FROM tempcach WHERE primary key or unique columns IN
      (SELECT primary key or unique columns FROM tempcach
       ORDER BY primary key or unique columns LIMIT 1000)

A: First, just because this kind of thing annoys me, why are you selecting all the fields of the temporary table in a subselect?  Why not the simpler SQL:
MERGE INTO Alldistances alld USING tempcach AS src (
    newword1,
    newword2,
    newdistance,
    newcount
) ON (
        alld.word1 = src.newword1
    AND alld.word2 = src.newword2
    AND alld.distance = src.newdistance
) WHEN MATCHED THEN
    UPDATE SET alld.distcount = alld.distcount+src.newcount
WHEN NOT MATCHED THEN
    INSERT (
        word1,
        word2,
        distance,
        distcount
    ) VALUES (
        newword1,
        newword2,
        newdistance,
        newcount
    );

What you need to have the database avoid loading the whole table into memory is indexing on both tables.
CREATE INDEX all_data ON Alldistances (word1, word2, distance);
CREATE INDEX tempcach_data ON tempcach (word1, word2, distance);


Q: Time drift How do you deal with server time drift?

A: And to represent the Virtual Machine crowd...
If you're running virtual servers, time drift seems to be a common problem - and so there's usually a way (other than NTP) to keep the VM's in sync with their host.
In my case, I am using VMWare.  I can turn this on from a linux Virtual Machine by using:
vmware-guestd --cmd "vmx.set_option synctime 0 1"

And from a Windows Virtual machine you can open the vmware-tools icon from the system tray, and select time synchronization between the virtual machine and the host OS

A: VMwareTools SyncTime is not a good option for virtual machines on ESX! VMware itself has altered their recommendations for timekeeping in VM's to using NTP instead of vmware-tools if you experience problems.
I talked about this to an engineer from VMware at VMworld once and was told vmware-tools was never designed to do the job it is doing now. In the old days, lost interrupts was a big problem. Today much less. This is the reason why vmware-tools is able to correct your machine time if the machine is behind, but not when the machine is ahead. In fact, once the machine goes ahead of 'real' time, you're pretty much screwed if you use vmware-tools to do timekeeping.
Better still: when using ntp, the process that corrects your time actually wakes up less often compared to using vmware-tools. So for virtual machines ntp will provide less overhead instead of more.
Therefore, for Linux you should always use ntp in VMware virtual machines. Disable vmware-tools synctime completely.
For Windows VM's on Vmware, I'm less sure, but I think it is pretty much the same. Use the built-in time synchronization stuff in AD, which works better than VMware SyncTime. (Even though AD time synchronization sucks pretty bad by itself; it's sole reason for existence is to keep Windows boxen in sync with their domain controllers and Kerberos will still work as long as the clock difference is less than about 5 minutes, so there is much less need for accuracy.)
You can read about VMware time synchronization on Linux a bit more here

A: Use NTP daemon.

A: NTP is your friend.
RHEL/CentOS:
yum install ntpd

Debian/Ubuntu:
apt-get install ntpd

Windows:

*

*For Windows 2000: Tardis 2000.  Works nicely, comes with a control panel.  If you use this, be sure to turn off Windows Time Service.

*For Windows 2003/2008: Already mentioned in other answers in this question.  Alternatively, you can run Tardis 2000 on a 2k3 box, I don't know if it works on 2k8.

*For any Windows workstation: run the following command at login:  net time /domain:your-domain-here
For all NTP services:
Point your service at pool.ntp.org, although you'll want to at least narrow it down to the same continent.  For example, US servers would use 0.us.pool.ntp.org, 1.us.pool.ntp.org, 2.us.pool.ntp.org, etc.

A: As many have answered, NTP is the way to go. Depending on your needs and requirements, there are several possible designs that you can use for syncing time.

*

*Sync individual machines to public host i.e. pool.ntp.org

*Designate a local master (with upstream NTP) and sync everything else to it

*Local master with your own GPS hw attached (could be $$$)

If you have many machines, options 2 and 3 are a lot friendlier to the network. For more details, read about NTP and clock strata.
Additionally, I find that the Windows default interval for synchronization is too long (once a week) which leads to too much drift. You should check out the following if you want to set things to a shorter period (I use once a day).
http://www.softpedia.com/get/System/System-Miscellaneous/Internet-Time-Update.shtml
http://www.tweakxp.com/article36948.aspx

A: The Network Time Protocol, or NTP, can be used to synchronize the time on a server with an authoritative source.  Windows Servers, for example, will use one of the network domain controllers (the DC which holds the PDC emulator FSMO role for the domain [thanks Graeme]) to get time information.  You can configure the domain controller to get information from some known source, such as time.windows.com.

A: A good NTP server, mainly.  Set it up so that the clock hasn't drifted more than a few seconds since the last NTP sync and you shouldn't have any problems.
If your server is drifting more than a 30 seconds per day, you might want to look at better alternatives, but the clocks inside most computers are generally much better than 30 seconds per day, so one sync per day is usually fine.
BE AWARE that you might skip minutes if you set it up to synch periodically (ntpdate), and don't use the NTP daemon (ntpd) - if you are behind 3 seconds, and the NTP sync attempts an update at 10 minutes 58 seconds, it'll skip to 11 minutes 1 second, and depending on the scheduler you're using, it may not trigger the 11 minute tasks.
The NTP daemon runs in the background and fixes the time slowly so programs and processes notice time may be going slightly more quickly or slowly than usual, but it won't skip second.
-Adam

A: A NTP server it is what's needed to keep time synchronized on your DC, yes. Read this article for instructions on how to synchronize your DC with an external source, and this knowledge base article on how to configure an authoritative time server with Windows 2003. You will need both to keep your domain time synchronized. Workstations joined to the domain, will automatically synchronize with the authoritative time server.

A: Use a common clock source for all your servers and make sure your time zones are setup correctly. A good Internet source is "time.windows.com". If you are using Windows, you can use "net time" and "w32tm" for time related commands.


Q: how to design db schema of an e-learning platform in dynamodb? I am designing No-SQL DB schema for an online e-learning platform, plan is to store it in the AWS DynamoDB
This is similar to Udemy, user can access and see all the available courses and users can buy more than one course.
As of now, I am thinking of the schema as below
User

Course

But I am just thinking from the item size limit wise, if in future a single user bought many courses or if a single course have many modules and videos in it which can automatically increases the item size in the AWS Dynamo DB which is max 400KB, I have seen blogs suggesting to split up the item, but wanted to check here for your inputs as well.
So my questions are

*

*DB schema wise is it fine the way that I am thinking of?

*What could be the better way when the entries are many and item size is large?

I am also exploring GraphQL, so that calls will have less latency from the front end, but worry is about the DB design and large items.
Let me know if anyone have their thoughts or valuable suggestions on this :)
Thanks in advance.

A: Modeling one-to-many relationships (e.g. Users to Courses bought) within a single item is a common pattern.  However, if the many side of the relationship can grow large, you will likely want a different approach.  It sounds like you're use case ins't a good fit for this particular pattern.
One way around this limitation is to model the relationship in an item collection.  For example, you could model the user and the courses bought within the same partition.  Keeping the data together makes it easier to fetch the data in a single query operation.

In this data model, I created a global secondary index named courses using the attribute GSIPK as the primary key for the secondary index.  This would let you fetch all courses with a single query of the courses GSI.

Keep in mind that this is just one of many approaches you could take to model your data.  Check out this talk from AWS Re:Invent about DynamoDB data modeling.  It gives a fantastic walkthrough of some of the key concepts that will help you design your data model.


Q: Difference of two DataTables in c# using LINQ II have two data tables as follows
dtOne
-------------------------
  ID  |   Name
--------------------------
 101  |  ABC
 102  |  XYZ
 103  |  MNO
 104  |  PQR
--------------------------

dtTwo
-------------------------
  ID  |   Name
--------------------------
 101  |  FGH
 102  |  XYZ
 104  |  GPS
--------------------------

I just want the result as data which is in dtOne and  not in dtTwo (dtOne-dtTwo)
dtResult
-------------------------
  ID  |   Name
--------------------------
 103  |  MNO
--------------------------

How can i achieve this .
I have used except method of LINQ but that is giving the result like this
     101  |  ABC
 103  |  MNO
 104  |  PQR
 101  |  FGH

 104  |  GPS

Thats means matching both column in except method

A: If you are trying to find rows that meet criteria based on multiple columns in the DataTable, try something like the following
string stationToFind = "ABC";
DateTime dateToFind = new DateTime(2016, 5, 26);
var result = dataTable.AsEnumerable().Where(row => row.Field<string>("station") == stationToFind
                 && row.Field<datetime>("date") == dateToFind).ToList();

If you are only expecting one row, then you can use .FirstOrDefault() instead of .ToList()

A:         DataTable dt = new DataTable();
        dt.Columns.Add("station", typeof(string));
        dt.Columns.Add("max_temp", typeof(double));
        dt.Columns.Add("min_temp", typeof(double));

        dt.Rows.Add("XYZ", 14.5, 3.5);
        dt.Rows.Add("XYZ", 14.5, 3.5);
        dt.Rows.Add("XYX", 13.5, 3.5);
        dt.Rows.Add("ABC", 14.5, 5.5);
        dt.Rows.Add("ABC", 12.5, 3.5);
        dt.Rows.Add("ABC", 14.5, 5.5);

        var maxvalue = dt.AsEnumerable().Max(s => s.Field<double>("max_temp"));

        var coll = dt.AsEnumerable().Where(s => s.Field<double>("max_temp").Equals(maxvalue)).
            Select(s => new { station = s.Field<string>("station"), maxtemp = s.Field<double>("max_temp"), mintemp = s.Field<double>("min_temp") }).Distinct();

        foreach (var item in coll)
        {
            Console.WriteLine(item.station + " - " + item.maxtemp + " - " + item.mintemp);
        }


Q: How to install Wildcard TDM410P to my Debian? I want to install a WCTDM/0 "Wildcard TDM410P in my Debian 7 for I use in my Asterisk, but I can't it. And it appear DAHDI_SPANCONFIG failed on span 1: Invalid argument (22). I have to configure my /etc/dahdi/system.conf and my /etc/dahdi/system.conf
See my system.conf
       # Autogenerated by /usr/sbin/dahdi_genconf on Tue May 19 15:29:13 2015
# If you edit this file and execute /usr/sbin/dahdi_genconf again,
# your manual changes will be LOST.
# Dahdi Configuration File
#
# This file is parsed by the Dahdi Configurator, dahdi_cfg
#
# Span 1: WCTDM/0 "Wildcard TDM410P" (MASTER)
span = 1,1,0,ccs,hdb3,crc4
bchan = 1-15
dchan =16
fxsks=17-20
echocanceller=mg2,17-20
# channel 2, WCTDM/0/1, no module.
# channel 3, WCTDM/0/2, no module.
# channel 4, WCTDM/0/3, no module.

# Global data

loadzone        = br,us

When I use dahdi_scan it returns
  [1]
  active=yes
  alarms=OK
  description=Wildcard TDM410P
  name=WCTDM/0
  manufacturer=Digium
  devicetype=Wildcard TDM410P
  location=PCI Bus 05 Slot 05
  basechan=1
  totchans=4
  irq=0
  type=analog
  port=1,FXO
  port=2,none
  port=3,none
  port=4,none

And when I use dahdi_cfg -vvvvvv
      DAHDI Tools Version - 2.10.1

  DAHDI Version: 2.10.1
  Echo Canceller(s): MG2
  Configuration
  ======================

  SPAN 1: CCS/HDB3 Build-out: 0 db (CSU)/0-133 feet (DSX-1)

  Channel map:

  Channel 01: Clear channel (Default) (Echo Canceler: none) (Slaves: 01)
  Channel 02: Clear channel (Default) (Echo Canceler: none) (Slaves: 02)
  Channel 03: Clear channel (Default) (Echo Canceler: none) (Slaves: 03)
  Channel 04: Clear channel (Default) (Echo Canceler: none) (Slaves: 04)
  Channel 05: Clear channel (Default) (Echo Canceler: none) (Slaves: 05)
  Channel 06: Clear channel (Default) (Echo Canceler: none) (Slaves: 06)
   07: Clear channel (Default) (Echo Canceler: none) (Slaves: 07)
  Channel 08: Clear channel (Default) (Echo Canceler: none) (Slaves: 08)
  Channel 09: Clear channel (Default) (Echo Canceler: none) (Slaves: 09)
  Channel 10: Clear channel (Default) (Echo Canceler: none) (Slaves: 10)
  Channel 11: Clear channel (Default) (Echo Canceler: none) (Slaves: 11)
  Channel 12: Clear channel (Default) (Echo Canceler: none) (Slaves: 12)
  Channel 13: Clear channel (Default) (Echo Canceler: none) (Slaves: 13)
  Channel 14: Clear channel (Default) (Echo Canceler: none) (Slaves: 14)
  Channel 15: Clear channel (Default) (Echo Canceler: none) (Slaves: 15)
  Channel 16: D-channel (Default) (Echo Canceler: none) (Slaves: 16)
  Channel 17: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 17)
  Channel 18: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 18)
  Channel 19: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 19)
  Channel 20: FXS Kewlstart (Default) (Echo Canceler: mg2) (Slaves: 20)

  20 channels to configure.

  DAHDI_SPANCONFIG failed on span 1: Invalid argument (22)

A: You cannot create span for Wildcard TDM410P. Only one thing you should do is to configure channels the right way. Here is your minimal /etc/dahdi/system.conf for using this card:
loadzone=us
defaultzone=us
fxsks=1

Maybe it is too late to answer this question, but here I am.


Q: Macro to remove highlighting from hyperlinks in Word I'm writing a macro to remove all highlight colors in a Word document except wdGray25 (whose HighlightColorIndex equals 15). The problem arises when macro runs into a hyperlink highlighted with wdGray25, whose hyperlink/field isn't highlighted when revealed by Alt+F9. In that case Do While .Execute loop goes into an infinite loop and never exits.
How can I rewrite the code so that .Execute method wouldn't go into an infinite loop? I appreciate your help.
color_array = Array("2", "3", "4", "5", "6", "7", "9", "10", "11", "12", "13", "14")

For Each color_number In color_array

With Selection
.HomeKey Unit:=wdStory
With Selection.Find
  .Highlight = True
  .Text = ""

  Do While .Execute
   If Selection.Range.HighlightColorIndex = color_number Then
      Selection.Range.HighlightColorIndex = wdNoHighlight
      Selection.Collapse wdCollapseEnd
    End If
  Loop

End With
End With
Next

A: Instead of searching, we can just *loop** through each Hyperlink in the Hyperlinks collection:
Sub RemoveHighlightFromHyperlinks()
    Dim a As Hyperlink
    For Each a In ActiveDocument.Hyperlinks
        If a.Range.HighlightColorIndex <> 15 Then a.Range.HighlightColorIndex = wdAuto
    Next a
End Sub

It loops through all hyperlinks in the document. If HighlightColorIndex <> 15 then remove HighlightColorIndex (by setting to wdAuto.)

More Information:

*

*MSDN : Hyperlinks Collection (Word)

*MSDN : Hyperlink Object (Word)

*MSDN : Range.HighlightColorIndex Property (Word)


Q: Download a Word editable document from an aspx page I currently have an aspx page returning a html form (with images and css). I would like get a download Word editable version of this form without rewrite all the code. Is it possible ?
An example : I Have a page 'WebForm2.aspx' with a simple content like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="WebApplication15.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

Title

        <asp:CheckBox runat="server" ID="myTest" Text="Doc 1" />

        <asp:CheckBox runat="server" ID="myTest2" Text="Doc 2" />

        <asp:CheckBox runat="server" ID="myTest3" Text="Doc 3" />

        <asp:CheckBox runat="server" ID="myTest4" Text="Doc 4" />

    </form>

I would like that from an other page for example a button that lets you download the contents of 'WebForm2.aspx' in an editable Word document.
I Add this in Page_PreRender method
Response.AddHeader("Content-Type", "application/msword");

It's partially work. If I save the document css and images aren't loaded but if I only open the downloadable content css and images are loaded.

A: MS Word can edit html document so by adding Content-Type=application/msword record in header will make browser open your page in browser unfortunately without css and images.
Add following code in prerender event on your page
    Response.AddHeader("Content-Type", "application/msword");


Q: Many-to-one prediction using LSTM in Keras, reshaping data I have multiple pandas dataframes containing multiple users, with for each user, a sequence of sequential timestamps of multiple features. It looks something like the following:
      user    day    feature_1    ...    feature_n
0     1       0      6            ...    5
1     1       1      7            ...    4
2     1       2      6            ...    7
3     1       3      7            ...    8
4     1       4      6            ...    4
5     1       5      4            ...    3
6     1       6      3            ...    5
7     1       7      4            ...    6
8     1       8      3            ...    7
9     1       9      4            ...    7
10    2       0      3            ...    5
11    2       1      5            ...    4

I want to predict the value of feature_1, one timestamp ahead, given seven timestamps of information, per user: many-to-one prediction if I am correct.
I have previously clustered my users and want to create one LSTM model per dataframe.
I've already filtered out users with less than 8 timestamps and I know how to create a target per row using the groupby and shift functions in pandas.
The Keras LSTM implementation requires data in the format of a 3D tensor and gives the following help in the documentation: [nSamples, nTimesteps, nFeatures]
I do not understand how I should achieve this, given my dataset and goal. I have tried searching for solutions or tutorials but have been unable to find any so far. Any help would be greatly appreciated!
If it matters, I am using Python 3.6.6, Keras 2.2.4, Tensorflow 1.11.0 and numpy 1.15.2
EDIT: Thanks to the suggestion from @ely I managed to figure it out. I should create a sample for every 7 timestamps as he explains in his comment. However, the most pythonic way of achieving this I still have not figured out.


Q: Java: How to retrieve a specific value from my arraylist? I'm trying to get a value, deep from an arraylist.
The attributes are in the following order:
arraylist > [0, 1, 2, 3 etc.] >
    (example from array[0]):
        [String name = "x"], [Private Time time] > (in time):
            [String beginTime="12:00", String endTime="12:30",
             long difference="1800000"].

I know how to get to the 0, 1, 2 of the array with help of .get(i) but how do I go deeper?
I have tried .get(i).get(time).get(difference), but, as expected, it did not work.
Basically what I need to do is to sniff through the array and only take the difference value, and add everything up.

A: I'm thinking that you are storing an array of class Time.
You could do something like
((Time)get(i)).difference

Assuming that difference is an accessible field in the Time class.


Q: Is it possible to reach terminal velocity on the ground? If your running from a giant fan (or anything else that can pull laterally) and running at the same speed your pulled, would that count as terminal velocity?

A: The definition on Wikipedia Terminal Velocity is

Terminal velocity is the highest velocity attainable by an object as it falls through a fluid (air is the most common example, but the concept applies equally to any fluid). It occurs when the sum of the drag force (Fd) and the buoyancy is equal to the downward force of gravity (FG) acting on speed that a freely falling object eventually reaches when the resistance of the medium through which it is falling prevents further acceleration.

Ok,  ignore the falling bit for a minute, but I think the difference is also you still have some leeway when running, because you are connected to a static surface,  over your horizontal velocity, but no control at all when you are completely immersed in a  fluid.
So both by definition and the situation you set up here, the answer is no, even if you modified the definition.

A: Well, Wikipedia states that terminal velocity is achieved when the downward gravity and the upward drag force and bouyancy cancel out, giving the object effectively zero acceleration.
I think you can "rotate" this situation to describe e.g. a rocket sled that drives on a very wide plane. Terminal velocity would then be achieved if the acceleration can't overcome the drag force anymore (since buoyancy and gravity fall out of the equation in this scenario).
We can use the drag equation
$$
F_D = \frac{1}{2}\rho v^2 C_D A
$$
and set the left-hand side equal to $m \cdot a$ for a given acceleration. However, considering that (military) airplanes can fly at supersonic speeds easily, I think it's not really useful to apply the concept to this question. Plus, as DilithiumMatrix has mentioned, it's somewhat defined as the velocity achievable solely by falling in a fluid.

A: No.  The term 'terminal velocity' (as apposed to a general, situational maximum-velocity) specifically refers to the balance between gravitational force and drag (and possible buoyancy, depending on the situation).


Q: Author Role - Allow editing of Gallery images Is it possible to give the 'Author' role the capability of editing image titles and captions on post's they have created ?
I have a number of users set to 'Author' , but when i've tested it's not possible to edit any of the image fields , such as title , caption , description etc.
They can delete images , create WP-Galleries , but cannot edit the details ??
I can do the above with 'Editor' role , but would rather stay with 'Author' for these users.
I've tried a plugin 'user role editor' but cannot get a setting that will allow 'Author' to edit image details , without choosing 'edit others post' , which i dont want.
any help advice appreciated :)

A: If I remember correctly, to edit those, users have to have capability of 'upload_images'.
User role editor is really a super plugin, just play with some values for Author role and you will definitely find the one that is needed.


Q: What is the likelihood of a long-period comet impact? I always see lots of information about asteroid impacts, but very little is said about comet impacts. As I see, a long period comet impact is much more dangerous because a) we wouldn't have time to prepare for it, and b) even small bodies would have high kinetic energy, equivalent to large asteroids.
On the flip side, I think that a long period comet would have trouble hitting the Earth, as it wouldn't have time to interact with our planet as an asteroid does. It would just hit us if, by chance, it was crossing the ecliptic plane at 1 AU from the Sun and we happened to be at the same place as well. So, my question boils down to the following:

*

*Do long period comets cross the ecliptic plane at a preferential distance from the sun (or: what is the chance of them crossing at approximately 1 AU)?

*What is the area of the hitting plane, versus the cross section of our planet?

*Does the assumption that a comet wouldn't have time to interact with us holds?

A: An estimate of impacts from long-period comets is available at this NASA JPL site.
They appear to be randomly distributed . Given detection at about 5 AU, we'd only have a year of warning for potential impactors. Their mean impact velocity is in the order of 52 km/s with an impact probability crossing Earth's orbit of 2.2 - 2.5x${10^{ - 9}}$ per perihelion passage. Nuclei large enough to initiate global climate disturbances occur on average, every 16 Myr.
With our current technology, it appears we would have no way to avoid disaster from a long-term comet should we be in the cross-hairs of one of them. Fortunately, impact probability is very small.


Q: How to push notifications from sql database to Flutter App My problem is that i have only found some tutorials about how to push notifications from firebase database using fcm to devices running an app made with flutter. In my case i have a server with mysql database with a lot of tables. User has the oppurtinity to choose from which table to get notifications from always when something is added to the table. I really dont know how to achieve this. I tried to learn about Fcm but it doesnt seem to be suitable for my purpose. I dont also know how to push notifications directly from sql. Im not using php by the way.
Please dont vote negatively im really sorry im new at this. So i would appreciate your help.
I would be very thankful for your answers.


Q: Visualize lowest nodes in hierarchical clustering with dendrogram I'm using linkage to generate an agglomerative hierarchical clustering for a dataset of around 5000 instances. I want to visualize the 'bottom' merges in the hierarchy, that is, the nodes close to the leaves with the smallest distance measures.
Unfortunately, the dendrogram visualization prefers to show the 'top' nodes from the last merges in the algorithm. By default it shows the top 30 nodes, collapsing the bottom of the tree. I can change the P value to show more nodes, but I would have to show all 5000+ to see the lowest levels of the clustering at which point the plot is no longer readable.
MCVE
For example, starting from the linkage documentation example
openExample('stats/CompareClusterAssignmentsToClustersExample')
run CompareClusterAssignmentsToClustersExample
dendrogram(Z, 'Orient', 'Left', 'Labels', species);

Produces a dendrogram with the top 30 nodes visible. The nodes with numerical labels are collapsing lower levels of the tree.

I can increase the number of visible nodes to include all leaves at expense of readability.
dendrogram(Z, size(Z,1), 'Orient', 'Left', 'Labels', species);

What I'd Like
What I'd really like is a zoomed in version of above, like the example below, but showing the first 30 closest clusters.

What I've Tried
I tried providing the function with the first 30 rows of Z,
dendrogram(Z(1:30), 'Orient', 'Left');

but that throws an "Index exceeds matrix dimensions." error when one of the rows references a cluster in a row > 30.
I also tried using the dendrogram Reorder property, but I am having difficulty finding a valid ordering that orders the clusters from closest to farthest.
%The Z matrix is in order from closest cluster to furthest,
% so I can use it to create an ordering
Y = reshape(Z(:, 1:2)', 1, [])
Y = Y(Y<151);
dendrogram(Z, 30, 'Orient', 'Left', 'Labels', species, 'Reorder', Y);

I get the error

In the requested ordering of the nodes, some data points belonging to
  the same leaf in the plot are separated by the points belonging to
  other leaves. Try to use a different ordering.

It may be the case that such an ordering is not possible if the entire tree is calculated because there would be branch crossings, but I'm hoping that there is a better ordering if I am only looking at a portion of the tree, and clusters at higher levels are not considered.
Question
How can I improve my visualization to show the lowest level clusters in the dendrogram?

A: Emmm...like ylim()?
dendrogram(Z, size(Z,1), 'Orient', 'Left', 'Labels', species);
ylim(max(ylim())-[30,0]);

yields


Q: How can I execute multiple NN training? I have two NVidia GPUs in the machine, but I am not using them.
I have three NN training running on my machine. When I am trying to run the fourth one, the script is giving me the following error:
my_user@my_machine:~/my_project/training_my_project$ python3 my_project.py
Traceback (most recent call last):
  File "my_project.py", line 211, in <module>
    load_data(
  File "my_project.py", line 132, in load_data
    tx = tf.convert_to_tensor(data_x, dtype=tf.float32)
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/home/my_user/.local/lib/python3.8/site-packages/tensorflow/python/framework/constant_op.py", line 106, in convert_to_eager_tensor
    return ops.EagerTensor(value, ctx.device_name, dtype)
tensorflow.python.framework.errors_impl.FailedPreconditionError: Failed to allocate scratch buffer for device 0
my_user@my_machine:~/my_project/training_my_project$

How can I resolve this issue?
The following is my RAM usage:
my_user@my_machine:~/my_project/training_my_project$ free -m
              total        used        free      shared  buff/cache   available
Mem:          15947        6651        3650          20        5645        8952
Swap:          2047         338        1709
my_user@my_machine:~/my_project/training_my_project$

The following is my CPU usage:
my_user@my_machine:~$ top -i
top - 12:46:12 up 79 days, 21:14,  2 users,  load average: 4,05, 3,82, 3,80
Tasks: 585 total,   2 running, 583 sleeping,   0 stopped,   0 zombie
%Cpu(s): 11,7 us,  1,6 sy,  0,0 ni, 86,6 id,  0,0 wa,  0,0 hi,  0,0 si,  0,0 st
MiB Mem :  15947,7 total,   3638,3 free,   6662,7 used,   5646,7 buff/cache
MiB Swap:   2048,0 total,   1709,4 free,    338,6 used.   8941,6 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
2081821 my_user  20   0   48,9g   2,5g 471076 S 156,1  15,8   1832:54 python3
2082196 my_user  20   0   48,8g   2,6g 467708 S 148,5  16,8   1798:51 python3
2076942 my_user  20   0   47,8g   1,6g 466916 R 147,5  10,3   2797:51 python3
   1594 gdm       20   0 3989336  65816  31120 S   0,7   0,4  38:03.14 gnome-shell
     93 root      rt   0       0      0      0 S   0,3   0,0   0:38.42 migration/13
   1185 root     -51   0       0      0      0 S   0,3   0,0   3925:59 irq/54-nvidia
2075861 root      20   0       0      0      0 I   0,3   0,0   1:30.17 kworker/22:0-events
2076418 root      20   0       0      0      0 I   0,3   0,0   1:38.65 kworker/1:0-events
2085325 root      20   0       0      0      0 I   0,3   0,0   1:17.15 kworker/3:1-events
2093002 root      20   0       0      0      0 I   0,3   0,0   1:00.05 kworker/23:0-events
2100000 root      20   0       0      0      0 I   0,3   0,0   0:45.78 kworker/2:2-events
2104688 root      20   0       0      0      0 I   0,3   0,0   0:33.08 kworker/9:0-events
2106767 root      20   0       0      0      0 I   0,3   0,0   0:25.16 kworker/20:0-events
2115469 root      20   0       0      0      0 I   0,3   0,0   0:01.98 kworker/11:2-events
2115470 root      20   0       0      0      0 I   0,3   0,0   0:01.96 kworker/12:2-events
2115477 root      20   0       0      0      0 I   0,3   0,0   0:01.95 kworker/30:1-events
2116059 my_user  20   0   23560   4508   3420 R   0,3   0,0   0:00.80 top

The following is my TF configuration:
import os

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "99" # Use both gpus for training.

import sys, random
import time
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import ModelCheckpoint
import numpy as np
from lxml import etree, objectify

# <editor-fold desc="GPU">
# resolve GPU related issues.
try:
    physical_devices = tf.config.list_physical_devices('GPU')
    for gpu_instance in physical_devices:
        tf.config.experimental.set_memory_growth(gpu_instance, True)
except Exception as e:
    pass
# END of try
# </editor-fold>

Please, take the commented lines as commented-out lines.
Relevant source code:
def load_data(fname: str, class_index: int, feature_start_index: int, **selection):
    i = 0
    file = open(fname)
    if "top_n_lines" in selection:
        lines = [next(file) for _ in range(int(selection["top_n_lines"]))]
    elif "random_n_lines" in selection:
        tmp_lines = file.readlines()
        lines = random.sample(tmp_lines, int(selection["random_n_lines"]))
    else:
        lines = file.readlines()

    data_x, data_y = [], []
    for l in lines:
        row = l.strip().split()
        x = [float(ix) for ix in row[feature_start_index:]]
        y = encode(row[class_index])
        data_x.append(x)
        data_y.append(y)
    # END for l in lines

    num_rows = len(data_x)
    given_fraction = selection.get("validation_part", 1.0)
    if given_fraction > 0.9999:
        valid_x, valid_y = data_x, data_y
    else:
        n = int(num_rows * given_fraction)
        data_x, data_y = data_x[n:], data_y[n:]
        valid_x, valid_y = data_x[:n], data_y[:n]
    # END of if-else block

    tx = tf.convert_to_tensor(data_x, np.float32)
    ty = tf.convert_to_tensor(data_y, np.float32)

    vx = tf.convert_to_tensor(valid_x, np.float32)
    vy = tf.convert_to_tensor(valid_y, np.float32)

    return tx, ty, vx, vy
# END of the function

A: Using multiple GPUs
If developing on a system with a single GPU, you can simulate multiple GPUs with virtual devices. This enables easy testing of multi-GPU setups without requiring additional resources.
gpus = tf.config.list_physical_devices('GPU')
if gpus:
  # Create 2 virtual GPUs with 1GB memory each
  try:
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=1024),
         tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.list_logical_devices('GPU')
    print(len(gpus), "Physical GPU,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)

NOTE: Virtual devices cannot be modified after being initialized
Once there are multiple logical GPUs available to the runtime, you can utilize the multiple GPUs with tf.distribute.Strategy or with manual placement.
With tf.distribute.Strategy best practice for using multiple GPUs, here is a simple example:
tf.debugging.set_log_device_placement(True)
gpus = tf.config.list_logical_devices('GPU')
strategy = tf.distribute.MirroredStrategy(gpus)
with strategy.scope():
  inputs = tf.keras.layers.Input(shape=(1,))
  predictions = tf.keras.layers.Dense(1)(inputs)
  model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
  model.compile(loss='mse',
                optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))

This program will run a copy of your model on each GPU, splitting the input data between them, also known as "data parallelism".
For more information about distribution strategies or manual placement, check out the guides on the links.

A: The RAM complaint isn't about your system ram (call it CPU RAM). It's about your GPU RAM.
The moment TF loads, it allocates all the GPU RAM for itself (some small fraction is left over due to page size stuff).
Your sample makes TF dynamically allocate GPU RAM, but it could still end up using up all the GPU RAM. Use the code below to provide a hard stop on GPU RAM per process. you'll likely want to change 1024 to 8096 or something like that.
and FYI, use nvidia-smi to monitor your GPU ram usage.
From the docs:
https://www.tensorflow.org/guide/gpu#limiting_gpu_memory_growth
gpus = tf.config.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.set_logical_device_configuration(
        gpus[0],
        [tf.config.LogicalDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)


Q: What if black holes consumed exotic matter? I've just watched Kurzgesagt in a Nutshell and I've been thinking of exotic matter for a while. What if black holes tried to consume exotic matter?


Q: Inequality of an expression greater than 0 Wolfram says the following is true for all $x>0$:
$$-(x+1)^{(x+1) }+ 2^{(x+1)} x^x\geq0$$
How to prove this algebraically?

A: Since $x >0$, instead of considering function $$f(x)= 2^{(x+1)} x^x-(x+1)^{(x+1) }$$ consider instead
$$g(x)=\log\left(2^{(x+1)} x^x\right) -\log\left((x+1)^{(x+1) } \right)$$ $$g(x)=(x+1)\log(2)+x \log(x)-(x+1)\log(x+1)$$
Now, the derivatives
$$g'(x)=\log (x)-\log (x+1)+\log (2)\qquad \text{and} \qquad g''(x)=\frac{1}{x^2+x}\qquad > 0 \qquad \forall x >0$$
The first derivative cancels at $x=1$. For this value $g(1)=0$ and by the second serivative test, this is a minimum. So, no root for $g(x)=0$ which is a decreasing function for $ 0 < x <1$, goes through a minimum and increases again (for ever).


Q: Show that if $\sigma=(a_1,a_2,\dots,a_m)$ and $\tau$ is any element of $S_n$, then $\tau\sigma\tau^{-1}=(\tau a_1,\tau a_2,\dots,\tau a_m)$ Show that if $\sigma=(a_1,a_2,\dots,a_m)$ and $\tau$ is any element of $S_n$, then $\tau\sigma\tau^{-1}=(\tau a_1,\tau a_2,\dots,\tau a_m)$.
I'm not quite sure how to start this.
The solution starts off by saying that
$$\tau\sigma\tau^{-1}(\tau(a_i))=\tau\sigma(a_i)=\begin{cases}\tau(a_{i+1})&i<m\\\tau(a_1)&i=m\end{cases}$$
but I don't see why.


Q: Maximal subgroups of a finite group Let $G$ be a finite group acting on a finite set $X$. If the action is primitive  then the stabilizers are maximal subgroups of $G$ (converse also true).
Is there any criteria to get maximal subgroups as stabilizers, with some restriction on the "action"?
For ex. the action of $S_3$ on $X=\{1,2,3\}$ is primitive, and so stabilizers are maximal subgroups of $G$, which are Sylow-2 subgroups of $S_3$. But how can we obtain the maximal subgroup $\langle (123)\rangle$?

A: To get an action of $S_3$ in which $\langle(1,2,3)\rangle$ is the stabilizer of a point, take $X=\{1,-1\}$, and let $S_3$ act by parity: even permutations fix both $1$ and $-1$, odd permutations swap $1$ and $-1$. Then the stabilizer of a single point, $1$, is $A_3 = \langle (1,2,3)\rangle$.
In general, if $H$ is a subgroup of $G$, then $G$ acts on the left cosets of $H$ by left multiplication, $g\cdot xH = gxH$. The stabilizer of the coset $H$ is $H$ itself. If you have a partition of the cosets so that $G$ acts on the partition, let $K = \{ g\in G\mid gH\text{ is in the same block as }H\}$ be the collection of all elements that represent cosets in the same part of the partition as $H$. Then $K$ certainly contains $H$. I claim that $K$ is a subgroup of $G$: for if $x\in K$, then $xH$ is the same block of the partition as $H$, hence $x^{-1}(xH)$ is in the same block as $x^{-1}H$. But $x^{-1}(xH) = H$, so $x^{-1}H$ is also in the same block of the partition, hence $x^{-1}\in K$. That is, $K$ is closed under inverses. And if $x,y\in K$, $x^{-1}\in K$. Taking the cosets $x^{-1}H$ and $yH$, which are in the same block, and multiplying by $x$, we conclude that $xyH$ and $H$ are in the same block, so $xy\in K$. Thus, $K$ is a subgroup, $H\leq K \leq G$.
Conversely, if $K$ is a subgroup, $H\leq K\leq G$, then $K$ induces a partition of the cosets into blocks for the action of $G$: just take the cosets of $K$, and partition each into cosets of $H$.
So systems of blocks in the action of $G$ on the left cosets of $H$ correspond to subgroups $K$, $H\leq K\leq G$.
Hence, if $H$ is a maximal subgroup, then the action of $G$ on the cosets is primitive, since the only possible systems of blocks are the trivial and total blocks, corresponding to $H$ and to $G$.
In particular, every maximal subgroup of $G$ is the stabilizer of a point in a primitive action of $G$, namely, $H$ is the stabilizer of $H$ in the (left) action of $G$ on the left cosets of $H$ in $G$.

A: Here is an older version of Arturo's answer:
The symmetric group of degree n acts on polynomials in n variables.  We can view $\operatorname{Sym}(3)$ as acting on the variables $x,y,z$.
Consider its action on the polynomial $x+y$.  The orbit contains $x+y$, $x+z$, and $y+z$.  The stabilizer of $x+y$ is the maximal subgroup $\operatorname{Sym}(\{x,y\})\cong\operatorname{Sym}(2)$.
Consider its action on the polynomial $\Delta = (x−y)(x−z)(y−z)$.  The orbit has only two polynomials, $\Delta$ and $-\Delta$.  The stabilizer of $\Delta$ is the maximal subgroup $\operatorname{Alt}(\{x,y,z\})\cong\operatorname{Alt}(3)$.
You can play similar tricks with any subgroup of $\operatorname{Sym}(n)$.  This is one way to look at "resolvents".


Q: Sort a cell array of strings alphabetically by last name In Matlab, I have a cell array like:
names = {
    'John Doe',
    'Jane Watkins',
    'Jeremy Jason Taylor',
    'Roger Adrian'
    }

I would like to sort these such that the last names appear in alphabetical order. In my example, it would come out being:
names_sorted = {
    'Roger Adrian',
    'John Doe',
    'Jeremy Jason Taylor',
    'Jane Watkins'
    }

I know of inelegant ways of doing this. For instance, I could tokenize at space, make a separate last_names cell array, sort that, and apply the indexing to my original array.
My question is, is there a better way?
Because someone is sure to come up with that list of assumptions you can't make with regards to people names in a database, let me assure you that all my names are either "FIRST MIDDLE LAST" or "FIRST LAST". I checked.

A: If all first names had the same length, then you would be able to use sortrows, but in your case, that would require padding and modifying your array, anyway, so that you're better off converting it into "LAST FIRST MIDDLE" before applying sort. Fortunately, there's a simple regular expression for that:
names = {'John Doe';'Roger Adrian';'John Fitzgerald Kennedy'};
names_rearranged = regexprep(names,'(.*) (\w*)$','$2 $1')
names_rearranged =
    'Doe John'
    'Adrian Roger'
    'Kennedy John Fitzgerald'

[names_rearranged_sorted, idx_sorted] = sort(names_rearranged);

names_sorted = names(idx_sorted)
names_sorted =
    'Roger Adrian'
    'John Doe'
    'John Fitzgerald Kennedy'