text:
Q: Social Media sharing Buttons in Ruby on Rails I'm trying to add custom social media sharing buttons in a blog app in Ruby on Rails. It is important for me that a pop-up window will show for sharing the "post" meaning I want to include Javascript.
Unfortunately this code does not work:

  <a oneclick="javascript:window.open('http://twitter.com/share?text=<%= @post.title %>
  by Martin Bortowski - &url=<%= url_for([@post, {only_path: false}]) %>',
  '_blank', 'width=800, height=500, top=200, left=300');void(0);">

  <a oneclick="javascript:window.open('http://facebook.com/sharer.php?u=<%= url_for([@post, {only_path: false}]) %>',
  '_blank', 'width=800, height=500, top=200, left=300');void(0);">

  <a oneclick="javascript:window.open('https://plus.google.com/share?url=<%= url_for([@post, {only_path: false}]) %>',
  '_blank', 'width=800, height=500, top=200, left=300');void(0);">

When I click on a button nothing happens. What I am missing? Can someone help me please? If you need further information just let me know.

A: There are number of gems available in ruby on rails for implementing social shairing feature below are few links

*

*https://github.com/huacnlee/social-share-button

*https://github.com/hermango/shareable


text:
Q: Mobile Application Xamarin.Form, what is the use of TabLayoutResource and ToolbarResource I am new using Xamarin and I am using VS2019, I created a new project using Mobile App(Xamarin.Forms).
The MainActivity class is defined as MainLauncher and I understand it.
That class also have two lines of code within the OnCreate method
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
Tabbar and Toolbar are defined within the Resource.designer and the views are placed within the Layout folder.
Then the App is loaded, the MainPage is assigned and loaded too. The Views within the Views folder are loaded
And the application is building and showing fine.
I understand (at least that is what I think) the Xamarin application cycle, but what I do not understand is the use of those two lines of code.
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
If I comment or delete those lines, the application still working fine.
What is the purpose of those lines?

A:
What is the purpose of those lines?

TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

These two lines in Xmarin.Forms Android used to set the layout resource. To specify the toolbar and tabs layout in Resource/layout folder so Xamarin.Forms knows how to reference them.

If I comment or delete those lines, the application still working fine.

When you comment or delete, the application works well, but it would lose the default layout.
I use toolbaritem for reference.
 <ContentPage.ToolbarItems>
    <ToolbarItem Text="Example Item"
         IconImageSource="monkeyicon.png"
         Order="Primary"
         Priority="0" />
</ContentPage.ToolbarItems>

The original layout:

When I comment it, the layout would be below.

A: You use those lines to setup the style of the tabbar and toolbar on Android. Many of those setups where missing in the earlier versions of Xamarin.Forms, so those things are much less needed now, but I think they still offer a more wide level of customization.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Panel Events not firing? (C#) I have a Form and I have some defined methods that are different from the standard events provided by winforms. I have a panel overlaying my form and I want to add custom mouse_up and mouse_down events.
What I've tried (which works for the form but not for the outer panel) is:
public Form1()
{
    InitializeComponent();

    OuterPanel.MouseUp += delegate(object sender, MouseEventArgs e) { OnMouseEvent_UpDown(sender, e, "custom param"); };
    OuterPanel.MouseDown += delegate(object sender, MouseEventArgs e) { OnMouseEvent_UpDown(sender, e, "custom param"); };
}

where OuterPanel is the name of the panel which overlays my main form. When I switch "OuterPanel.event += OnEvent(args)" to "this.event += OnEvent(args)" and remove the panel entirely, I get the functionality that I want.


text:
Q: How can I use migrations to move data I have a scenario where I need to move the data from one model (Old model where some data already exist) to another model and in turn to another model if necessary.how can I add this process in migration file so,that I can accomplish the requirement with just python manage.py migrate command.
this is the model where All the old items exist:
class UserFavorite(CreatedAtMixin):
    user = models.ForeignKey('auth.User')
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

objects = UserFavoriteManager()

def __str__(self):
    try:
        return str(self.content_object)
    except AttributeError:
        return 'None'

class Meta:
    get_latest_by = "date_added"
    unique_together = ("user", "content_type", "object_id")`

Here is the model where I need to insert item first, per item in above model:
class CollectionItem(models.Model):

sort_number=models.PositiveIntegerField(blank=True,null=True)
type=models.CharField(max_length=20,null=False, blank=False)
item_type = models.ForeignKey(ContentType, limit_choices_to=models.Q(app_label='news', model='News') | models.Q(app_label='work', model='Work') | models.Q(app_label='collection', model='Quote'))
item_id = models.PositiveIntegerField()
item = generic.GenericForeignKey('item_type', 'item_id')

class Meta:
    verbose_name = "Collection Item"
    verbose_name_plural = "Collection Items"
def __str__(self):
    return self.item.title

then I need to insert that into:
class Collections(CreatedAtMixin):
user = models.ForeignKey('auth.User', related_name='collections_user')
collection_place=models.ForeignKey('companies.CompanyOffice',related_name='collections_place',null=True)
collection_name = models.CharField(max_length=40,null=False, blank=False)
description = models.TextField(null=True, blank=True)
items=models.ManyToManyField('collection.CollectionItem')
def __str__(self):
    return self.collection_name

class Meta:
    unique_together = ("user","collection_name")
    verbose_name = "Collection"
    verbose_name_plural = "Collections"
    ordering = [ '-created_at']
    get_latest_by = "created_at"

A: First write your new models and create a schema migration.
Then create a data migration and write the required code to transfert your old models data to the new models (hint: if possible, also write the code to revert your migration).
Finally - assuming the old models are not used anymore -, remove the old models code and create a last schema migration.
The details are all documented in the above links, and what's left is specific to your application so we cannot help further.


text:
Q: evaluating this difficult integral I have to evaluate this integral:
$\int^{\infty}_{-\infty}\int^{x}_{-\infty}xe^{-x^2}e^{-y^2}dydx$
I know how to evaluate the next integral:
$\int^{\infty}_{-\infty}e^{-x^2}dx$
But I just cant figure out how to do first one. I need hints.

A: Interchange the order of the variables:
$$ \int_{-\infty}^\infty \int_{-\infty}^x x e^{-x^2} e^{-y^2}\ dy\ dx
= \int_{-\infty}^\infty e^{-y^2} \int_{y}^\infty x e^{-x^2}\ dx\ dy $$

A: You can integrate by parts:
$$
\begin{eqnarray}
\int_{-\infty}^{\infty} x e^{-x^2} \left(\int_{-\infty}^{x} e^{-y^2} dy\right) dx
&=& -\frac{1}{2}\int_{-\infty}^{\infty} \left(\int_{-\infty}^{x} e^{-y^2} dy\right)d(e^{-x^2}) \\
&=&\frac{1}{2}\int_{-\infty}^{\infty}e^{-x^2}d\left(\int_{-\infty}^{x} e^{-y^2} dy\right) \\
&=&\frac{1}{2}\int_{-\infty}^{\infty}e^{-x^2}\left(e^{-x^2}dx\right) \\
&=&\frac{1}{2}\int_{-\infty}^{\infty}e^{-2x^2}dx \\ &=&\frac{1}{2}\sqrt{\frac{\pi}{2}}.
\end{eqnarray}
$$

A: $$\int_{-\infty}^\infty xe^{-x^2} \int_{-\infty}^x e^{-y^2}\, dy \, dx =
 \frac{\sqrt \pi}{2} \int_{-\infty}^\infty xe^{-x^2} \left[\operatorname{erf}x \right]_{-\infty}^x \, dx =
 \frac{\sqrt \pi}{2}\int_{-\infty}^\infty (\operatorname{erf} x+1)x e^{-x^2} \, dx =
\frac{\sqrt{\pi}}{2\sqrt 2}$$
and the last integral can be done by parts, because $\frac{d}{dx}\operatorname{erf} x = \frac{2e^{-x^2}}{\sqrt{\pi}}$

A: Hint: Change the order of integration. It turns into two known integrals.


text:
Q: Подсчет средного значение чисел вводящихся в TextBox Есть textbox1 и textbox2. В textbox1 вводятся 4 разные цифры по очереди, каждый раз одну цифру. В коде должно подсчитываться среднее значение суммы этих цифр и выводиться в textbox2.
private void button1_Click(object sender, EventArgs e)
{
    int sum = 0;
    List<int> list = new List<int>();
    if (!(textBox17.Text == null))
    {
        list.Add(int.Parse(textBox17.Text));
        for (int i = 0; i < list.Count; i++)
        {
            sum += list[i];
        }
        textBox17.Clear();
    }
    textBox18.Text = (sum / 4).ToString();
}

A: Список введенных чисел должен быть общим во всех нажатиях на кнопку, так что стоит сделать его полем класса - просто переставить повыше, вне обработчика:
List<int> list = new List<int>();

private void button1_Click(object sender, EventArgs e)
{
    int sum = 0;

    // if (!String.IsNullOrWhitespace(textBox17.Text)) - пустая строка и null - разные вещи
    if (!(textBox17.Text == null))
    {
        list.Add(int.Parse(textBox17.Text));

        // можно заменить на sum = list.Sum();
        for (int i = 0; i < list.Count; i++)
        {
            sum += list[i];
        }
        textBox17.Clear(); // = "";
    }

    // стоит делить на 4.0 вместо 4 - чтобы получить дробный результат
    textBox18.Text = (sum / 4).ToString();
}

и еще - стоит переименовать текстбоксы. textBox17 и textBox18 не добавляют читабельности.

A:
            float sum = 0;
            int count = 0;

            foreach (char digit in textBox1.Text)
            {
                if (char.IsNumber(digit)
                {
                    sum += byte.Parse(digit.ToString());
                    count++;
                }
            }

            textBox2.Text = (sum / count).ToString();


text:
Q: sqlalchemy MSSQL+pyodbc schema none I'm trying to connect to SQL server 2019 via sqlalchemy. I'm using both mssql+pyodbc and msql+pyodbc_mssql, but on both cases it cannot connect, always returns default_schema_name not defined.
Already checked database, user schema defined and everything.
Example:
from sqlalchemy import create_engine
import urllib
from sqlalchemy import create_engine
server = 'server'
database = 'db'
username = 'user'
password = 'pass'
#cnxn = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';Trusted_Connection=yes'
cnxn = 'DSN=SQL Server;SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password+';Trusted_Connection=yes'
params = urllib.parse.quote_plus(cnxn)

engine = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params)
cnxn = engine.connect()

return None, dialect.default_schema_name
AttributeError: 'MSDialect_pyodbc' object has no attribute 'default_schema_name'

TIA.....

A: Hopefully the following provides enough for a minimum viable sample. I'm using it in a larger script to move 12m rows 3x a day, and for that reason I've included an example of chunking that I pinched from elsewhere.
#Set up enterprise DB connection
# Enterprise DB to be used
DRIVER = "ODBC Driver 17 for SQL Server"
USERNAME = "SQLUsername"
PSSWD = "SQLPassword"
SERVERNAME = "SERVERNAME01"
INSTANCENAME = "\SQL_01"
DB = "DATABASE_Name"
TABLE = "Table_Name"

#Set up SQL database connection variable / path
#I have included this as an example that can be used to chunk data up
conn_executemany = sql.create_engine(
    f"mssql+pyodbc://{USERNAME}:{PSSWD}@{SERVERNAME}{INSTANCENAME}/{DB}?driver={DRIVER}", fast_executemany=True
)

#Used for SQL Loading from Pandas DF
def chunker(seq, size):
    return (seq[pos : pos + size] for pos in range(0, len(seq), size))

#Used for SQL Loading from Pandas DF
def insert_with_progress(df, engine, table="", schema="dbo"):
    con = engine.connect()

    # Replace table
    #engine.execute(f"DROP TABLE IF EXISTS {schema}.{table};") #This only works for SQL Server 2016 or greater
    try:
      engine.execute(f"DROP TABLE Temp_WeatherGrids;")
    except:
      print("Unable to drop temp table")

    try:
      engine.execute(f"CREATE TABLE [dbo].[Temp_WeatherGrids]([col_01] [int] NULL,[Location] [int] NULL,[DateTime] [datetime] NULL,[Counts] [real] NULL) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];")
    except:
      print("Unable to create temp table")

    # Insert with progress
    SQL_SERVER_CHUNK_LIMIT = 250000
    chunksize = math.floor(SQL_SERVER_CHUNK_LIMIT / len(df.columns))

    for chunk in chunker(df, chunksize):
        chunk.to_sql(
            name=table,
            con=con,
            if_exists="append",
            index=False
        )

if __name__ == '__main__':

    # intialise data. Example -  make your own dataframe. DateTime should be pandas datetime objects.
    data = {'Col_01':[0, 1, 2, 3],
            'Location':['Bar', 'Pub', 'Brewery', 'Bottleshop'],
            'DateTime':["1/1/2018", "1/1/2019", "1/1/2020", "1/1/2021"],
            'Counts':[1, 2, 3, 4}

    # Create DataFrame
    df = pd.DataFrame(data)

    insert_with_progress(df, conn_executemany, table=TABLE)
    del [df]


text:
Q: Android: SharedPreferences not getting updated from PreferenceFragment I'm posting this question again as I didn't get any answers last time, and I still haven't solved the problem.
I have a settings menu with a PreferenceScreen in which I create a lot of CheckBoxPreferences during runtime (Adding them into the "Exclusion List" prefscreen). I created them no problem, here's the XML code below that it starts with:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceScreen
        android:key="exclusion_list_key"
        android:title="Exclusion List"
        android:persistent="true"
        android:summary="" >
    </PreferenceScreen>
</PreferenceScreen>

I create the checkboxes in the onCreate method of my PreferenceFragment and add them to the "Exclusion List" PreferenceScreen and that works fine.
I'm trying to set the summary of the "Exclusion List" to be a list of all the checkbox titles that are checked off (so if the checkbox is checked, it's name will be listed in the summary of the "Exclusion List").
In the onCreate() method, the summary gets set properly, there's no problem.
But in the onPreferenceChanged() method, I set the summary of "Exclusion List" to the 'summary' string I built (which contains the correct value), but it doesn't update it! When i press back from my checkbox menu, the "Exclusion List" does not have the updated values.
The last few lines are the ones of interest. I did some printlns to see what's going on:

*

*The listener works fine, runs when expected

*My summary var contains what's expected

*After calling setSummary(summary), the getSummary() returns the expected value (so that means it got set properly)

*However, when I actually press back and see "Exclusion List", it's summary doesn't actually get updated!
Did I miss something? Thanks in advance!
All the code for reference:
public class Settings extends AppCompatActivity {

    public static final String EXC_LIST_KEY = "exclusion_list_key";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preferences);
            String summary = "";

            //Create all the checkboxes inside of the PreferenceScreen
            for (int i = 0; i < MainActivity.contactNames.length; i++) {
                CheckBoxPreference checkbox = new CheckBoxPreference(getActivity());
                checkbox.setTitle(MainActivity.contactNames[i][0]);
                checkbox.setKey(MainActivity.contactNames[i][2]);
                checkbox.setSummary(MainActivity.contactNames[i][1]);
                checkbox.setDefaultValue(false);
                ((PreferenceScreen) findPreference(EXC_LIST_KEY)).addPreference(checkbox);
                if (checkbox.isChecked()) {
                    summary = summary + checkbox.getTitle() + "\n";
                }
            }
            findPreference(EXC_LIST_KEY).setSummary(summary);
            getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            //Checkbox keys all start with 'key_'
            if (key.startsWith("key_")) {
                String summary = "";
                for (int i = 0; i < MainActivity.contactNames.length; i++) {
                    CheckBoxPreference checkbox = (CheckBoxPreference) findPreference(MainActivity.contactNames[i][2]);
                    if (checkbox.isChecked()) {
                        summary = summary + checkbox.getTitle() + "\n";
                    }
                }
                System.out.println("Summary I have: " + summary); //Correct summary is printed out
                findPreference(EXC_LIST_KEY).setSummary(summary); //Isn't updating the value???
                System.out.println("Summary system has: " + findPreference(EXC_LIST_KEY).getSummary()); //Correct summary is printed out
            }
        }
    }
}

A: try Adding this code in your SettingsFragment
 @Override
public void onResume() {
    super.onResume();

    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();

    // CHANGE 1: load saved values to set the summaries
    onSharedPreferenceChanged(prefs, "exclusion_list_key");

    // CHANGE 2: register shared prefs listener in onResume
    prefs.registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    super.onPause();
    SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
    prefs.unregisterOnSharedPreferenceChangeListener(this);
}

A: Got it working by adding the following line of code to the end of my onSharedPreferenceChanged() method:
((BaseAdapter)getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();


text:
Q: Output Hidden Inputs based on Dropdown Selection in form I am trying to output four hidden inputs based upon the user's selection in a dropdown box.
<label>Neighborhood:</label>
<select id="district">
    <option value="">- Select -</option>
    <option value="warehouse">Warehouse District</option>
    <option value="gateway">Gateway District</option>
    <option value="tremont">Tremont</option>
    <option value="shoreway">Detroit Shoreway</option>
</select>

For instance, if the user selects warehouse district, these hidden inputs are added to the form.
<input type="hidden" name="idx-q-LatitudeMax" value="41.50534740463771" />
<input type="hidden" name="idx-q-LatitudeMin" value="41.49729607499309" />
<input type="hidden" name="idx-q-LongitudeMin" value="-81.70605182647705" />
<input type="hidden" name="idx-q-LongitudeMax" value="-81.69352054595947" />
I've found some solutions to deal with changing a single value, but I need to output all four .
Any help would be greatly appreciated

A: "type property cannot be changed(IE Security Model)."
See this change type of input field with jQuery
Alternatively you can do this
Add a class to your input like this
<input class="hidden warhouse" name="idx-q-LatitudeMax" value="41.50534740463771"/>
<input class="hidden warhouse" name="idx-q-LatitudeMin" value="41.49729607499309"      />
<input class="hidden warhouse" name="idx-q-LongitudeMin" value="-81.70605182647705" />
<input class="hidden warhouse" name="idx-q-LongitudeMax" value="-81.69352054595947" />

hidden css class has "display:none"
on change first hide all and then display the one you want
$('#district').change(function(){
 $('input.hidden').hide()
 if($(this).val() == "warehouse"){
   $("input.warehouse").show()
 }
})


text:
Q: Express router create a new session not wanted I am doing a react project using express and passport-local for the authentication part based on this tutorial :
https://scotch.io/tutorials/easy-node-authentication-setup-and-local
The authentification work very well, I added the express router to define my routes for my api, but when I call for example "/api/myroute" the router of express creates an other session and I lose the user, so my function isLoggedIn blocks the call of my controllers because there is no user in this new session. So my question is : Why the router recreate a session ? What it is wrong in my configuration ? Here is my code :
//server.js
var path = require('path');
    var webpack = require('webpack');
    var webpackDevMiddleware = require('webpack-dev-middleware');
    var webpackHotMiddleware = require('webpack-hot-middleware');
    var config = require('./webpack.config');

    var express  = require('express');
    var app      = express();
    var port     = process.env.PORT || 8080;
    var mongoose = require('mongoose');
    var passport = require('passport');
    var flash    = require('connect-flash');

    var morgan       = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser   = require('body-parser');
    var session      = require('express-session');

    var configDB = require('./config/database.js');

    var router = express.Router();

    // configuration ===============================================================
    mongoose.connect(configDB.url); // connect to our database

    require('./config/passport')(passport); // pass passport for configuration

    // set up our express application
    app.use(morgan('dev')); // log every request to the console
    app.use(cookieParser()); // read cookies (needed for auth)
    app.use(bodyParser()); // get information from html forms

    app.set('view engine', 'ejs'); // set up ejs for templating

    // required for passport
    app.use(session({ secret: 'secret' })); // session secret
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
    app.use(flash()); // use connect-flash for flash messages stored in session

    var compiler = webpack(config);
    app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
    app.use(webpackHotMiddleware(compiler));
    app.use('/plugins/bootstrap', express.static(path.join(__dirname, './plugins/bootstrap')));
    app.use('/plugins/jquery', express.static(path.join(__dirname, './plugins/jquery')));
    app.use('/plugins/font-awesome', express.static(path.join(__dirname, './plugins/font-awesome')));

    // all of our routes will be prefixed with /api
    app.use('/api', router);

    // routes ======================================================================
    require('./api/routes.js')(app, passport,router); // load our routes and pass in our app and fully configured passport

    // launch ======================================================================
    app.listen(port, function(error) {
      if (error) {
        console.error(error)
      } else {
        console.info("==>   Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
      }
    });
    console.log('The magic happens on port ' + port);

And here is my routes.js :
module.exports = function(app, passport,router) {
    var MyController = require("../api/controllers/mycontroller");

    // =====================================
    // HOME PAGE (with login links) ========
    // =====================================
    app.get('/', function(req, res) {
        console.log("welcome")
        res.render('index.ejs', { message: ""}); // load the index.ejs file
    });

    // =====================================
    // LOGIN ===============================
    // =====================================
    // show the login form
    app.get('/login', function(req, res) {
        console.log("login")
        // render the page and pass in any flash data if it exists
        res.render('index.ejs', { message: req.flash('loginMessage') });
    });

    app.post('/login', passport.authenticate('local-login', {
        successRedirect : '/welcome', // redirect to the secure profile section
        failureRedirect : '/login', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

    // =====================================
    // SIGNUP ==============================
    // =====================================
    // show the signup form
    app.get('/signup', function(req, res) {
        console.log("signup")
        // render the page and pass in any flash data if it exists
        res.render('signup.ejs', { message: req.flash('signupMessage') });
    });

    // process the signup form
    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/welcome', // redirect to the secure profile section
        failureRedirect : '/signup', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

    // process the signup form
    // app.post('/signup', do all our passport stuff here);

    // =====================================
    // LOGOUT ==============================
    // =====================================
    app.get('/logout', function(req, res) {
        console.log("logout")
        req.logout();
        res.redirect('/');
    });

    router.get('/myroute', isLoggedIn, function(req, res) {
        //HERE the router recreate a session and req.user is now undefined why ?
        MyController.getAllObjects(req,res);
    });

    // =====================================
    // HOME SECTION =====================
    // =====================================
    // we will want this protected so you have to be logged in to visit
    // we will use route middleware to verify this (the isLoggedIn function)
    app.get('*', isLoggedIn, function(req, res) {
        console.log("HOME")
        res.render('home.ejs', {
            user : req.user // get the user out of session and pass to template
        });
    });
};

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    console.log("redirect because not log in")
    // if they aren't redirect them to the home page
    res.redirect('/');

}

The function for login, logout, signin... are a copy paste of the tutorial.

A: You seem to be using the fetch library. This library does not include the domain cookies by default, so in order to work your request should look like this:
fetch('/api/myroute', {
    credentials: 'same-origin' // This is the line you are missing
}).then(response => response.json())
.then(json => {
    dispatch({
        type: types.MY_ACTION, forms: json, receivedAt: Date.now()
    })
})

See this link for more information.


text:
Q: VBA Macro to filter a table by specific cell value and delete all rows The intention of my macro is to perform the following steps:
 1: Filter table looking at column D to retrieve all "0" values
 2: Delete all rows with "0" values
 3: Remove filter.
The issue is that my table has 75,000+ rows of data so I keep getting alerts saying I have too much data. I tried a loop macro but it was taking too long to perform the job so I am now working on a macro that performs the above steps. My code keeps getting hung up on the line to delete the range of cells I selected. (my range goes  past the table range because this table will always have a variable amount of rows).
Error: "Method 'Range' of oject'_Worksheet' failed
I am assuming that I need to specify the exact number of rows in my table. How do I change the code so that I do not have to change the range every time I perform the macro?
Here is what I have so far:
Sub Delete_Zero_Rows()

Dim ws As Worksheet
  Set ws = ThisWorkbook.Worksheets("Status")
  ws.Activate

  On Error Resume Next
    ws.ShowAllData
  On Error GoTo 0
  ws.Range("B3:F1").AutoFilter Field:=4, Criteria1:="0"

  Application.DisplayAlerts = False
    ws.Range("B4:F").SpecialCells(xlCellTypeVisible).Delete
  Application.DisplayAlerts = True
  On Error Resume Next
    ws.ShowAllData
  On Error GoTo 0

End Sub

A: A loop should work fine with 75,000 rows. Turning off screen updating to speed it up.  Try this:
Sub DeleteZeroRows()
    Dim LastRow As Long, n As Long
    LastRow = Cells(Rows.Count, "B").End(xlUp).Row
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    For n = LastRow To 1 Step -1
        If Cells(n, 5).Value = 0 Then Cells(n, 5).EntireRow.Delete
    Next n
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

Note that I'm stepping backwards (bottom up) so when the row is deleted and shifted up it doesn't change the row number you move to in the next loop iteration.
Also note Cells(n, 5) where 5 is the column ("E") and is where I'm looking for zeros.

A: If you want to filter on column "D" then it's the third one when starting from column "B"
Sub Main
    With ThisWorkbook.Worksheets("Status")
        .ShowAllData
        With .Range("B1", .Cells(.Rows.Count, 2).End(xlUp))
            .AutoFilter Field:=3, Criteria1:="0"
            On Error Resume Next
            .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Delete
           On Error GoTo 0
        End With
        .AutofilterMode = False
    End With
End Sub

A: Modify Range in Array

*

*The following code only works if there are values in the range, not
formulas. If there are formulas, values will be returned.

*The following code will copy the entire range into an array, where it
will check each row for the criteria and if not found, will
(over)write to the same array resulting in a too big array, but will
then in 1 of 3 possible ways (cWriteDelete) write back to the
range:

*

*It will write empty strings ("") to the remainder of the array and
paste it back to the range.

*It will copy the array as is into the range and delete the
unnecessary rows.

*It will copy the array as is into the range and delete the
unnecessary range.

*Why not resize the array?
The array is a 2D array, and we cannot resize its first dimension (rows).
The Code
Sub Delete_Zero_Rows()

    Const cSheet As String = "Status"       ' Worksheet Name
    Const cRange As String = "A:F"          ' Source Columns Range Address
    Const cFR As Long = 4                   ' First Row Number
    Const cCol As Variant = "E"             ' Criteria Column Letter/Number
    Const cCrit As Long = 0                 ' Criteria
    Const cWriteDelete As Long = 2          ' 1 - Write "" to array
                                            ' 2 - Delete remaining rows
                                            ' 3 - Delete remaining range

    Dim Rng As Range      ' Last Used Cell Range In Criteria Column,
                          ' Source/Target Range
    Dim vntST As Variant  ' Source/Target Array
    Dim ACC As Long       ' Array Criteria Column Number
    Dim i As Long         ' Source Array Row Counter
    Dim j As Long         ' Source/Target Array Column Counter
    Dim k As Long         ' Target Array Row Number (Counter)

    ' Speed up.
    With Application
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    On Error GoTo ProcedureExit   ' Safely exit program.

    With ThisWorkbook.Worksheets(cSheet)

        '************************************************
        ' Last Used Cell Range in Criteria Column (Rng) '
        '************************************************

        ' Calculate Last Used Cell Range in Criteria Column.
        Set Rng = .Columns(cCol).Find("*", , xlFormulas, _
                xlWhole, xlByColumns, xlPrevious)
        ' Check if all cells in Criteria Column (cCol) are empty i.e. Last Used
        ' Cell Range in Criteria Column (Rng) is Nothing.
        If Rng Is Nothing Then  ' Inform user.
            MsgBox "No Data in Column '" & Split(.Cells(1, cCol).Address, _
                    "$")(1) & "'.", vbInformation, "Empty Column"
            GoTo ProcedureExit  ' Safely exit program.
        End If

        '******************************
        ' Source (Target) Range (Rng) '
        '******************************

        ' Calculate Source/Target Range (Rng) from Source Columns Range(cRange).
        Set Rng = .Columns(cRange).Resize(Rng.Row - cFR + 1).Offset(cFR - 1)
        ' Copy Source/Target Range (Rng) to Source/Target Array (vntST).
        vntST = Rng

        '******************************
        ' Source/Target Array (vntST) '
        '******************************

        ' Calculate Array Criteria Column Number.
        ACC = .Columns(cCol).Column
        ' Loop through rows (i) of Source/Target Array (vntST).
        For i = 1 To UBound(vntST)
            ' Check if value of current row (i) in Array Criteria Column (ACC)
            ' does not equal to Criteria  (cCrit).
            If vntST(i, ACC) <> cCrit Then
                ' Count (add 1 to) Target Array Row Number (k).
                k = k + 1
                ' Loop through columns(j) of Source/Target Array (vntST).
                For j = 1 To UBound(vntST, 2)
                    ' Write from current row(i) in column(j) to current row(k)
                    ' in column (j) of Source/Target Array (vntST).
                    ' Note: Data is being overwritten since always k <= j.
                    vntST(k, j) = vntST(i, j)
                Next
            End If
        Next
        ' Check if Target Array Row Number is equal to the number of rows in
        ' Source/Target Array (or in Source/Target Range).
        If k = UBound(vntST) Then ' or k = Rng.Rows.Count; Inform user.
            MsgBox "No cell containing '" & cCrit & "' in Column '" _
                    & Split(.Cells(1, cCol).Address, "$")(1) & "' found.", _
                    vbInformation, "Nothing Changed"
            GoTo ProcedureExit  ' Safely exit program.
        End If

        Select Case cWriteDelete
            Case 1  ' Slower version.
                ' Loop through the remaining rows (i) of Source/Target
                ' Array (vntST) starting from the current Target Array Row
                ' Number (k) increased by 1 (next).
                For i = k + 1 To UBound(vntST)
                    ' Loop through columns(j) of Source/Target Array (vntST).
                    For j = 1 To UBound(vntST, 2)
                        ' Write empty strings ("") to current row(i) in
                        ' column (j) of Source/Target Array (vntST)
                        vntST(i, j) = ""
                    Next
                Next

                '******************************
                ' Target (Source) Range (Rng) '
                '******************************

                ' Copy completely modified Source/Target Array (vntST)
                ' to Source/Target Range (Rng).
                Rng = vntST

            Case 2  ' Faster Version.

                '******************************
                ' Target (Source) Range (Rng) '
                '******************************

                ' Copy not completely modified Source/Target Array (vntST)
                ' to Source/Target Range (Rng).
                Rng = vntST

                ' Delete remaining (not modified) rows greater than current
                ' Target Array Row Number (k) increased by First Row (cFR),
                ' i.e. starting from the calculated row:
                ' (k + 1) + (cFR - 1) = k + cFR.
                .Rows(k + cFR & ":" & Rng.Rows.Count + cFR - 1).Delete

            Case 3  ' Faster Version.

                '******************************
                ' Target (Source) Range (Rng) '
                '******************************

                ' Copy not completely modified Source/Target Array (vntST)
                ' to Source/Target Range (Rng).
                Rng = vntST

                ' Delete remaining (not modified) range.
                .Columns(cRange).Resize(Rng.Rows.Count - k) _
                        .Offset(k + cFR - 1).Delete ' Clear, ClearContents
            Case Else

        End Select

    End With

ProcedureExit:
    With Application
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With

End Sub


text:
Q: Run series of command independent of each other If I have a file with
cmd1

cmd2

cmd3
And I want to run them independent of each other, and independent whether it outputs an exit status or not (that means do not expect to end, just keep starting processes, which can fail or not. I know that ; would run the next command, but that's not the case, because it waits until the previous command either fails or succeeds. I want to start all the commands at once.
It is like something like sleep 60m; and then play music, sound a bell, run the browser, but obviously, there is not way to wait until the music plays to sound a bell, then after that run the browser. It has to happen at once.
ADDED: how to, for example,
read lines from file, open a terminal for each line and run it?

A: Simply adding an ampersand to the end of each line will fork all the commands into the background.
cmd1 &
cmd2 &
cmd3 &

Example
$ more at_once.bash
#!/bin/bash

echo "1" && sleep 10 &
echo "2" && sleep 10 &
echo "3" && sleep 10 &
pgrep -a sleep

Now when we run this script:
$ ./at_once.bash
1
3
2
7533 sleep 10
7535 sleep 10
7536 sleep 10

You can even see that the tasks were run out of order due to their backgrounded nature with the 3rd command being echoed prior to the 2nd one. The pgrep sleep shows that all 3 of the backgrounded commands are running at the same time.
NOTE: I used the notation echo "X" && sleep 10 simply to show that the commands were running backgrounded. This notation has nothing to do with the backgrounding itself, the trailing & is what "puts" the sleep 10 commands into the background.
You can also use & as a separator if you'd rather do this in a single command line:
$ sleep 10 & sleep 10 & sleep 10 &
[1] 7731
[2] 7732
[3] 7733

Checking on this one liner:
$ pgrep -a sleep
7731 sleep 10
7732 sleep 10
7733 sleep 10

Again we see them all running simultaneously. If you were to use a semi-colon:
$ sleep 10 ; sleep 10 ; sleep 10

The sleep 10 commands would run in series taking 30 seconds to complete vs. in parallel, only taking 10 seconds.


text:
Q: A spring with two masses in an inelastic collision An ideal spring is attached to a wall, and the other end is attached to a mass $m$.  The spring is initially compressed a distance $x$.  After it is released, the mass collides with another mass $2m$ at a distance $x/2$ to the right of the spring equilibrium.  The collision is inelastic and they slide together.  How far will they slide before coming to a momentary stop?
My work
Since the collision is inelastic then mechanical energy is not conserved.  And since the two-mass system has an external force, momentum is not conserved.  So one has to use only mechanical principles to solve this.
We can compute the velocity of the mass at the moment of impact using simple harmonic motion, $r(t) = -x\cos\left( t\sqrt{k/m}\right)$ so that $x/2 = -x\cos \left(t^{*}\sqrt{k/m}\right)$.  With this I could do an awkward solution for time and maybe continue from there.
At this point, though, I'm not perfectly clear on how to move forward.  Do I just assume that momentum is conserved for a very, very short time period during the collision and use that to find the velocity of the combined mass system, then put that into another simple harmonic motion problem?

A: Remember that an inelastic collision means energy is lost but not momentum. Momentum is always conserved in collisions. So you have to figure out what kind of velocity the two joint masses have and use your knowledge of springs to compute the halt at the given position, velocity and mass.

A: I would proceed as follows:
Assuming that the stored energy in the spring, compressed/extended a distance $d$ from equilibrium, is given by$$E_{stored}=kd^2$$

*

*Find stored energy, kinetic energy, and thus total energy at the moment of release;

*Find stored energy, and thus kinetic energy, just before the collision

*Step aside for a moment, and use conservation of momentum to find out what happens to the kinetic energy when a mass $m$ collides inelastically with a stationary mass of $2m$;

*Combine stored energy and reduced kinetic energy to find new total energy, just after the collision;

*Find extension/compression needed to store all this new total energy...


text:
Q: Get a 95% confidence interval for Cohen's Kappa in R I've got a study with two radiologist's reading chest x-rays and want to calculate Cohen's kappa of their agreement. The kappa2 function in the "irr" package and cohen.kappa in "psych" can both give me an answer but don't generate a 95% confidence interval. Is there any good way to do this in R as well?

A: If you have two raters, no missing ratings, and are using the 1960 unweighted kappa, you can calculate the conditional variance using the following formula (see references below):
$$
v = \frac{1-f}{n(1-p_e)^2}\Bigg( p_a(1-p_a)-4(1-\kappa)\Big(\sum_{k=1}^qp_{kk}\hat{\pi}_k-p_a p_e\Big)+4(1-\kappa)^2\Big(\sum_{k=1}^q\sum_{l=1}^qp_{kl}[(p_{Al}+p_{Bl})/2]^2-p_e^2\Big)\Bigg)
$$
This variance estimate can then be used to calculate the bounds of a confidence interval.
$$ CI = \kappa \pm \sqrt{v}\times t_{(1-\alpha/2, n-1)}$$
References
Fleiss, J. L., Nee, J. C. M., & Landis, J. R. (1979). The large sample variance of kappa in the case of different sets of raters. Psychological Bulletin, 86, 974-977.
Gwet, K. L. (2008). Computing inter-rater reliability and its variance in the presence of high agreement. British Journal of Mathematical and Statistical Psychology, 61, 29-48.


text:
Q: How to store.csv file to a custom location on public internal drive (FileOutputStream) I would like to know if someone can assist me with the problem in saving the file to custom location. The purpose of the application is to store data in the csv when the button is pressed, which can be later transferred to the computer from internal disk on Android phone from the specific location (for Excel review and further manipulation). Code currently stores it into private application folder which can not be accessed:
    public void saveLogOnClick(View view) {
    //Name of the file created
    String FILENAME = "happy_log.csv";

    //Obrain the current text in the files convert it to string and save it to .csv file
    String entry = edtDate.getText().toString() + "," + edtTime.getText().toString() + "," +
            happyScore.getText().toString() + "," + normalScore.getText().toString() + "," +
            sadScore.getText().toString() + "\n";

    //Open a file with the streamer/pointer
    try {
        FileOutputStream out = openFileOutput(FILENAME, Context.MODE_APPEND);
        out.write(entry.getBytes());
        out.close();
        toastIt("Entry saved");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Edit:
Now it works to the part where the new folder is created in public Directory Download, and also the csv file in the custom directory. However everytime when the method saveLogOnClick is initiated, does not append new information to the .csv, however just saves the latest one.
    String FILENAME = "happy_log.csv";
    //Obrain the current text in the files convert it to string and save it to .csv file
    String entry = edtDate.getText().toString() + "," + edtTime.getText().toString() + "," +
            happyScore.getText().toString() + "," + normalScore.getText().toString() + "," +
            sadScore.getText().toString() + "\n";
    //Open a file with the streamer/pointer
    try {
        File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File logDir = new File (directoryDownload, "Happy App Logs"); //Creates a new folder in DOWNLOAD directory
        logDir.mkdirs();
        File file = new File(logDir, FILENAME);
        FileOutputStream out = new FileOutputStream(file);
        out.write(entry.getBytes()); //Write the obtained string to csv
        out.close();
        toastIt("Entry saved");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

Thanks for your help in advance.
Animus

A: First, in AndroidManifest.xml you have to request permission to write to external storage (ie outside of the app's sandbox)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Then you can read/write in "/sdcard/", so for example
String FILENAME = "/sdcard/happy_log.csv";

will be accessible both to your app, and to your PC.
EDIT:
You can make directories like this
File picDirectory = new File("/sdcard/myFolder");
picDirectory.mkdirs();

source
EDIT2:
I don't know how openFileOutput() works because I've never used it, but I do the following:
File outfile = new File(getResources().getString(R.string.default_file_location)); // which is a string like "/sdcard/file.csv"
BufferedWriter bw = null;
try {
    bw = new BufferedWriter(new FileWriter(outfile, true));
    bw.append(matchNum + ",");
    bw.flush();
    bw.close();
} catch (IOException e) {

}


text:
Q: What is this syntax, and how do I use it? I came across this syntax from a previous question on Stack Overflow, and I am unfamiliar with it.
However, it seems to work pretty good and I've been able to work out how to use it, but that doesn't mean I understand it.
Is this base R, or a library?
cor.test( ~ hp + qsec, mtcars)

I am referring to the usage of ~, and the subsequent use of + in the call, and how that allows the specification of columns in a dataframe.

A: The help page for cor.test lists one form of the function as
        cor.test(formula, data, subset, na.action, ...)
and in the description of the arguments it says:
        formula:    a formula of the form ~ u + v
~ hp + qsec  is a formula, so you can get a lot of information by looking at the help page  help(formula). However, that page emphasizes formulas of the form a ~ b which can be interpreted as something like "a as a function of b".  This formula (~ a+ b) has no dependent variable. It can be interpreted as something like "using the variables a and b".


text:
Q: OUT OF BREATH v.s BREATHLESS What is the difference between 'out of breath' and 'breathless'? I have read the dictionary carefully. I saw an example is that:" We were out of breath after only five minutes''. And 'out of breath' is used with the meaning ' having the difficulty breathing after exercise'. I Wonder if we can use 'breathless' instead of ' out of breath' in that case ?

A: Out of breath means just that, that you are physically out of breath.
Breathless is generally used in other phrasing, such as "breathless with anticipation" or a similar "breathtaking candor." Usually it's used metaphorically to say that something so exceptional has happened that it figuratively took your breath away. Out of breath means you're literally out of breath.
If you are trying to say you are literally physically out of breath from exercise, I think it would be more elegant to use out of breath instead of breathless.


text:
Q: When is a compact orbifold Riemann surface a global quotient of a Riemann surface While reading the paper Seifert Fibred Homology 3-Spheres and the Yang-Mills Equations on Riemann Surfaces with Marked points by M. Furuta and B. Steer, I stumbled upon the following statement:

Any compact orbifold Riemann surface, with $n\geq 3$ singular points or $n=2$ and $\alpha_1=\alpha_2$ if the genus $g$ is zero, has the form $N/D$, where $N$ is a compact Riemann surface and $D$ is a finite group of diffeomorphisms.

However, there is no comment why this should be true. The paper cites the article of P. Scott on the geometrization conjecture, but on that paper the only thing that is assured is that if this conditions are satisfied, then the orbifold is a global quotient, by some unspecified manifold. However,

How can we deduce that this manifold must be a Riemann surface?

This also leads me to ask,

If $N$ is a compact Riemann surface and $D$ is a finite group of diffeomorphisms, is the quotient $N/D$ a compact Riemann orbifold surface?

Thanks in advance for your answers.

A: Let $M$ be a your compact orbifold Riemann surface and let $S\subset M$ be the finite set of orbifold singularities.
Theorem:
The following are equivalent:

*

*$M$ is the quotient of a closed Riemann surface by a finite group

*$M$ admits a conformal metric of constant curvature (with the correct cone angles at the singularities)

Proof:
If $M = N/D$, $N$ admits a metric of constant curvature by Poincaré--Koebe'uniformization, which is essentially unique and thus invariant by $D$ (one has to be a bit careful in the positive curvature case).
Conversely, a metric of constant curvature on $M$ gives rise to a holonomy representation $\rho$ of the fundamental group $\pi_1(M\backslash S)$ into $\mathrm{Isom}(X)$, where $X$ is the sphere/the euclidean plane/the hyperbolic plane depending on the sign of the curvature. The image of $\rho$ is a finitely generated linear group which admits a torsion-free subgroup of finite index $\Gamma$ (by Selberg's lemma). The preimage of $\Gamma$ is a normal finite index subgroup of $\pi_1(M\backslash S)$ which thus defines a finite ramified normal cover $N$ of $M$. One verifies that the ramifications have the correct degree at the singularities, so that $N$ is a smooth Riemann surface covering $M$.    QED
Now, by a theorem of Troyanov, every closed orbifold of non-positive Euler characteristic admits a conformal metric of constant non-positive curvature. This shows that every orbifold is covered by a smooth Riemann surface except for the few ones that have positive Euler characteristic, namely, spheres with 1 or 2 singularities, or 3 singularities of angles $\pi, 2\pi/3, 2\pi/3$ or $\pi, \pi, 2\pi/3$.
These cases are not too hard to treat. For instance, the sphere with 3 singularities of angle $\pi, 2\pi/3, 2\pi/3$ is the double of a spherical triangle with angles $\pi/2, \pi/3, \pi/3$.


text:
Q: Python: create nested dictionary from parent-child mapping I have child-parent mapping as follows:
{4:6,
 6:9,
 7:6,
 5:6,
 8:9,
 11:9,
 10:9,
 12:10,
 13:10}

I want to create following nested dictionary using above:
{"id":9,
 "children":[
             {"id":6,
              "children":[
                          {"id":4,
                           "children":[]},
                          {"id":5,
                           "children":[]},
                          {"id":7,
                           "children":[]},
                         ]
              },
              {"id":10,
              "children":[
                          {"id":12,
                           "children":[]},
                          {"id":13,
                           "children":[]},
                         ]
              },
              {"id":11,
              "children":[]
              },
              {"id":8,
              "children":[]
              }
              ]
}

I am able to figure out how I can do it if in place of having keys as "id" and values as 9,6,etc , I have values as keys. Please help me with the above format.

A: I got the solution to my query.
I converted the child-parent mapping to a list of tuples as follows:
queue_tuples= [(6,9,1),(11,9,1),(8,9,1),(10,9,1),(5,6,2),(7,6,2),(4,6,2),(12,10,2),(13,10,2)]
root = 9

Following is the code:
pGraph = {"id":root,"children":[]}

for tuple in queue_tuples:
    level = tuple[2]
    g = pGraph["children"]
    for i in range(level-1):
        for e in g:
            if tuple[1]==e["id"]:
                g = e["children"]
    flag = 0
    for e in g:
        if tuple[0]==e["id"]:
            flag = 1
            break
    if flag==0:
        g.append({"id":tuple[0],"children":[]})
print pGraph


text:
Q: Set different filenames to different loggers Using this python code:
import logging
log1 = logging.getLogger("module1")
log2 = logging.getLogger("module2")

How can I set log1 to be written to fileName1 and log2 to be written to filename2 ?
by default they both write to STDERR instead of files at all
Thanks ahead

A: Add the relevant handler to each logger directly e.g.

log1.addHandler(logging.handlers.FileHandler(fileName1)
log2.addHandler(logging.handlers.FileHandler(fileName1)

You may need to set whatever formatter on these handlers.
Note that at this point, the messages sent to either logger will still be written to stderr: logging is a tree of handlers, logging records start at a "leaf" logger and are handled by each logger before being sent to its parent, until the root logger. Every single logger in the path might both print the message to some output (e.g. file, syslog, stream, …) and send it to its parent.
There are several options to avoid/configure/improve this behaviour:

*

*do nothing if that's fine (e.g. you want all logging to go to the default output, but some to be duplicated in other destinations)

*set these loggers to not propagate (logger.propagate = False), in which case the log records will "stop" at the relevant logger and not go up the tree any further

*set a NullHandler as handler to the root logger so it doesn't print the messages it receives (if a message reaches the root logger and it has no handler configured, a StreamHandler(sys.stderr) is automatically set on it), this allows all messages to reach the root logger and only be dropped there, which is convenient if you want to add further handlers in the future (e.g. send every logging message to the syslog at one point)

*disable the root logger entirely (logging.getLogger().disabled = True) but that's not really documented and a bit iffy


text:
Q: Getting automatic comments in jupyter notebook why i am getting this very frequently >>> from sympy.polys.domains import ZZ  automatically in jupyter notebook,  getting automatic comments in in jupyter python notebook
how to avoid such commenting of codes and comments.
if anyone has encounter the same problem please help
Autofill generally can be done by pressing tab when I feel the necessity of it, but this feature which is simply commenting automatically everywhere which I dont like.
please help me in avoiding this.


text:
Q: How to send custom headers from JavaScript WebSocket client to the server? I know there are no standard JS WebSocket APIs for the same. My main aim is to send the info like resourceId, routingInfo, auth-token, protocol etc. from JS web-socketclient to the server.
I could think of below few approaches. Kindly share the thoughts if my approach is fine or is there any other better approach:

*

*Can we use cookies for sending the custom headers from client and retrieve them in server side?

*Can we use web-storage API for storing them in the browser and retrieve them on server side?
PS: I am using a Java based server

A: Assuming you're talking about a webSocket connection from a browser, here are your traditional choices for sending additional "header-like" information.

*

*You can encode them as a query parameters on the initial URL which might be fine for everything except auth-token.

*If the origin you are connecting the webSocket connection is the same as the origin of your web page, then you can put the parameters into cookies and those cookies will be sent with the original webSocket connection request where the server can retrieve them upon the connection request.

*You can make a "conditional" webSocket connection to the server and then send credentials in subsequent webSocket messages.  You'd have to implement safety for that on your server so that the "conditionally" connected webSocket was not allowed to do anything else except authenticate itself and probably timeout the connection if appropriate credentials do not arrive shortly.

As it sounds like you may already know, the browser interface to webSockets does not allow custom headers on the initial HTTP request that starts the webSocket connection.  Those custom headers are possible from some other kind of client - it's just that the browser interface to a webSocket connection does not have that feature.

Can we use web-storage API for storing them in the browser and retrieve them?

The Javascript in your web page can use the web-storage API to store data in the browser and that data can be retrieved later from another script in a page from the same origin.  That data is not available to the server, it is only available within the client.


text:
Q: What does a and b stand for in the sorting function I have started learning javascript a few days ago and I have a bad time understand what these lines:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

What is a and b equal to in this function?
Thank you very much for your help in advance

A: The sorting algorithm implement by sort() will call the specified function with various combinations of elements from array to determine which element should go first in the order.  The two chosen element for comparison will be a and b.


text:
Q: unsigned char to unsigned char array of 8 original bits I am trying to take a given unsigned char and store the 8 bit value in an unsigned char array of size 8 (1 bit per array index).
So given the unsigned char A
Id like to create an unsigned char array containing 0 1 0 0 0 0 0 1 (one number per index)
What would be the most effective way to achieve this? Happy Thanksgiving btw!!

A: You could use bit operators as recommended.
#include <stdio.h>

main() {
    unsigned char input_data = 8;
    unsigned char array[8] = {0};
    int idx = sizeof(array) - 1;
    while (input_data > 0) {
        array[idx--] = input_data & 1;
        input_data /= 2; // or input_data >>= 1;
    }

    for (unsigned long i = 0; i < sizeof(array); i++) {
        printf("%d, ", array[i]);
    }
}

A: Take the value, right shift it and mask it to keep only the lower bit. Add the value of the lower bit to the character '0' so that you get either '0' or '1' and write it into the array:
unsigned char val = 65;
unsigned char valArr[8+1] = {};

for (int loop=0; loop<8; loop++)
    valArr[7-loop] = '0' + ((val>>loop)&1);

printf ("val = %s", valArr);

A: The fastest (not sure if that's what you menat by "effective") way of doing this is probably something like
void char2bits1(unsigned char c, unsigned char * bits) {
    int i;
    for(i=sizeof(unsigned char)*8; i; c>>=1) bits[--i] = c&1;
}

The function takes the char to convert as the first argument and fills the array bits with the corresponding bit pattern. It runs in 2.6 ns on my laptop. It assumes 8-bit bytes, but not how many bytes long a char is, and does not require the input array to be zero-initialized beforehand.
I didn't expect this to be the fastest approach. My first attempt looked like this:
void char2bits2(unsigned char c, unsigned char * bits) {
    for(;c;++bits,c>>=1) *bits = c&1;
}

I thought this would be faster by avoiding array lookups, by looping in the natural order (at the cost of producing the bits in the opposite order of what was requested), and by stopping as soon as c is zero (so the bits array would need to be zero-initialized before calling the function). But to my surprise, this version had a running time of 5.2 ns, double that of the version above.
Investigating the corresponding assembly revealed that the difference was loop unrolling, which was being performed in the former case but not the latter. So this is an illustration of how modern compilers and modern CPUs often have surprising performance characteristics.
Edit: If you actually want the unsigned chars in the result to be the chars '0' and '1', use this modified version:
void char2bits3(unsigned char c, unsigned char * bits) {
    int i;
    for(i=sizeof(unsigned char)*8; i; c>>=1) bits[--i] = '0'+(c&1);
}


text:
Q: static outgoing IP on GKE I'm running in a GKE cluster (1.15.12-gke.2)  some applications that need to connect to a third-party API. This third-party API has mandatory IP filtering. So in order to get API authorized, I need to declare what are the public IP that I'll use to connect to the API.
My problem is that public IPs of GKE nodes are not stable across upgrade and it would prevent the use of node autoscaling & after every time of nodes restart IP will change
Is there any way to have a stable outbound public IP on GKE?
Thanks
-Ashok Patidar

A: As I said in my comment, the solution to have a static outbound IP in GKE is to use Cloud NAT.

Disclaimer!
A Cloud NAT gateway can perform NAT for nodes and Pods in a private cluster, which is a type of VPC-native cluster.
Cloud.google.com: NAT: Docs: Overview: NAT with GKE

You can read more about private GKE clusters by following official documentation:

*

*Cloud.google.com: Kubernetes Engine: Docs: Concepts: Private cluster concept
There is also an official guide showing the process of creating a private GKE cluster and then connecting it with Cloud NAT:

*

*Cloud.google.com: NAT: Docs: GKE example

When following above guide you can choose to use previously reserved static IP address or create a new one. This will be the IP that GKE nodes and pods will be using when communicating with "outside".

I ran a test where I spawned private GKE cluster with 3 nodes. Created pods that each one of them was scheduled on a different node. Every pod sent a packet to a remote server. Listening on remote server showed that every pod that sent a message had the same source IP:
tcpdump: listening on ens4, link-type EN10MB (Ethernet), capture size 262144 bytes
14:06:11.692832 IP (tos 0x0, ttl 54, id 46751, offset 0, flags [DF], proto TCP (6), length 60)
    35.198.XXX.XXX.1027 > 10.168.0.2.9833: # NODE1 (POD1) TO SERVER
    10.168.0.2.9833 > 35.198.154.155.1027: # REPLY TO (POD1)
    35.198.XXX.XXX.2051 > 10.168.0.2.9833: # NODE2 (POD2) TO SERVER
    10.168.0.2.9833 > 35.198.154.155.2051: # REPLY TO (POD2)
    35.198.XXX.XXX.1538 > 10.168.0.2.9833: # NODE3 (POD3) TO SERVER
    10.168.0.2.9833 > 35.198.154.155.1538: # REPLY TO (POD3)


text:
Q: Analogue Tape how long do I have to record? If I have 1200ft (feet) of tape.
How long will I be able to record for at 7.5ips (inches per second)
Thank you

A: 1 foot is 12 inches. we have 1200 ft so 14400 inches. we have 7.5 inches per second.  14400 inches/7.5 inches per second = 1920 seconds.


text:
Q: Example numbers with respect to chapters in tcolorbox title I found this link which explains how to add index number to example in tcolorbox. However, I have been unable to modify it to include chapter reference numbering (e.g., Example 1.1, or 4.3, etc.). Any hints?

A: Updated 2015-08-29 to include a label, as requested by @Qasim.

Use tcolorbox's number freestyle option along with auto counter and number within=chapter, as in the following MWE. You can also add a label by using an optional (first) argument to \newtcolorbox (the second mandatory argument will be the title).

\documentclass{book}
\usepackage{tcolorbox}
    \tcbuselibrary{skins,breakable}
\usepackage{lipsum}

\newtcolorbox[auto counter, number within=chapter, number freestyle={\noexpand\thechapter.\noexpand\arabic{\tcbcounter}}]{myexample}[2][]{%
    enhanced,
    breakable,
    fonttitle=\bfseries,
    title=Example~\thetcbcounter: #2,
    #1
}

\begin{document}

\chapter{First chapter}

\begin{myexample}[label=exfirst]{First example}
  \lipsum[4]
\end{myexample}

\begin{myexample}{Second example}
  \lipsum[4]
\end{myexample}

\chapter{Second chapter}

\begin{myexample}[label=exthird]{Third example}
  \lipsum[4]
\end{myexample}

I can now refer to example~\ref{exfirst} and example~\ref{exthird}.
\end{document}

Output:

If you would also like the title to be optional, you could use the following approach:
\documentclass{book}
\usepackage{etoolbox}
\usepackage{tcolorbox}
    \tcbuselibrary{skins,breakable}
\usepackage{lipsum}

\tcbset{mytitle/.style={title={Example~\thetcbcounter\ifstrempty{#1}{}{: #1}}}}
\newtcolorbox[auto counter, number within=chapter, number freestyle={\noexpand\thechapter.\noexpand\arabic{\tcbcounter}}]{myexample}[1][]{%
    enhanced,
    breakable,
    fonttitle=\bfseries,
    mytitle={},
    #1
}

\begin{document}

\chapter{First chapter}

\begin{myexample}[mytitle={First example}, label=exfirst]
  \lipsum[4]
\end{myexample}

\begin{myexample}
  \lipsum[4]
\end{myexample}

\chapter{Second chapter}

\begin{myexample}[mytitle={Third example}, label=exthird]
  \lipsum[4]
\end{myexample}

I can now refer to example~\ref{exfirst} and example~\ref{exthird}.
\end{document}

Output:

A: You need to redefine the exa counter to achieve what you want:
\documentclass{book}
\usepackage[most]{tcolorbox}
\usepackage{lipsum}

\newcounter{exa}
\renewcommand\theexa{\thechapter.\arabic{exa}}
\tcbmaketheorem{Examples}{Example}{
breakable,
fonttitle=\bfseries,
}{exa}{ex}

\begin{document}
\chapter{Foo}
\begin{Examples}{Additional description}{test}
  \lipsum[4]
\end{Examples}
\end{document}


text:
Q: How to fully clean hard disk before further use? Is it possible to completely erase a corrupted internal Hard Drive and then use it as an external HD for extra storage with a HD enclosure case? Or would I face problems with it as an external? Any ideas - please let me know.

A: It is possible and easy. You did not provide information about your operating system, so I give instructions for Windows and for Linux.
In Windows
Use built-in diskpart tool. Start the command line window as administrator, and type:
C:\ diskpart
Then list available disks:
DISKPART> list disk
You will see a list of all available hard disks, including external ones. Determine disk to wipe-out number, note that disks are counted from 0. Let's say that disk to wipe-out has number 1. Select that disk:
DISKPART> select disk 1
and then wipe it out:
DISKPART> clean all
It may take hours, depending of disk's speed and size. At the end, exit diskpart:
DISKPART> exit
In Linux
Use dd command to overwrite disk with zeros. Let's assume that disk to clean is /dev/sdb:
dd if=/dev/zero of=/dev/sdb bs=1M
As in previous example, it may take quite a long time (few hours) to finish.
Be extremely careful! The dd command doesn't ask any questions, it works as ordered without any warning as soon as you hit Enter. A typo in disk name (i.e. sda instead of sdb) can cause disastrous consequences!
Note, that if your disk - as you suspect - has hardware malfunction, both methods will detect it and print some sort of error message. If cleaning is finished without errors, then it is safe to use disk as you need. The disk will work as external one in the proper USB disk case.
PS
Although diskpart command clean instead of clean all would take few seconds, it would clean only first and last megabyte of disk surface, missing any bad sectors that are out of those small cleaned parts. clean all puts zero in every single disk sector, so when some sector is damaged and unwritable, command will fail with error message. If you want to check whole disk - use clean all. If you want only to get rid of old MBR - go with simple clean.
The Linux dd method described above also fills whole drive with zeros. If you don't need such deep clean, then just clean first megabyte of disk by: dd if=/dev/zero of=/dev/sdb bs=1M count=1 - it takes only a second or two.

A: Another tool that works on just about any PC is DBAN - "Darik's Boot and Nuke". This is a free utility. You download it as an ISO and burn it to a CD or put it on a bootable USB key. It lets you wipe a hard drive with your choice of data streams: All zeroes, a pseudorandom sequence, even DoD-approved wipe patterns. All zeroes is fastest and will serve for what you want.
I'm not saying that diskpart or dd are poor choices in any way! This is simply an alternative.
The idea in all cases is to wipe the partition info on the drive (the Master Boot Record, unless your drive is partitioned with GPT). This really only requires wiping block 0 (again, unless GPT). So you usually don't have to wipe the entire drive. As soon as the wipe utility has done virtually anything at all to the drive, the previous partition structure is gone and it will be seen as a completely unformatted drive. But since you suspect hardware issues with the drive it is a good idea to let it go ahead and wipe the whole thing, hence testing all blocks.
With any of these tools, just be darn sure to select the right drive! Do not count on any recovery being possible. If you're at all unsure, physically disconnect all drives other than the one you want to wipe, and use DBAN.

A: You can try dd with:
dd if=/dev/zero of=/dev/sda bs=1M status=progress


text:
Q: use get parameters in DOMDocument::loadHTMLFile() I want to load an url like this using DOMDocument::loadHTMLFile(): http://www.domain.com/dir/page?param1=235235&param2=2345, but it gives this error, even though the page exists:
Warning: DOMDocument::loadHTMLFile(http://www.domain.com/dir/page?param1=235235&param2=2345): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

How can I solve this?


text:
Q: Selenium python get attribute by class and title I have googled this extensively but can't get to an answer, I'm trying to extract "90,856" in the title. It's value changes over time:

Search
Volume

my code is:
find_element_by_xpath("//div[@class='h4-param-content']").get_attribute("title")

grateful for some help. Thanks

A: Your XPath contains a typo (according to your sample data) : h4-param instead of h4 param...
First, test with :
find_element_by_xpath("//div[@class='h4 param-content']").get_attribute("title")

If it doesn't work, try with an expected condition.
Add the following imports :
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Code :
wait = WebDriverWait(driver, 10)
output = wait.until(EC.visibility_of_element_located((By.XPATH, "//div[@class='h4 param-content']"))).get_attribute("title")
print(output)


text:
Q: How to Deprecate an Optional Field in .thrift Files? Let's say I have a struct definition like this:
struct SomeStruct {
  1: optional binary content;
  2: optional binary newConetent;
}

What is the best practice to deprecate the first field ("content"), without affecting deployment? The deployment of the new code will be into multiple applications that is using this thrift structure? (Assuming some applications are still using the "content" field before the deployment)?
Thank you!

A: The recommended solution is to comment out the field but leave it in the IDL. This  prevents the field ID from becoming reused later for sth. else which then of course would produce incompatibilities.
If "in use by clients" means that they are accessing the outdated field for RPC only, that's not a problem w/regard to Thrift. Thrift will behave just like with a new field.
If however you mean that the field is used for serialization and the old data contain relevant information that needs to be converted somehow into the new format, you will have to leave the field active in the IDL. You may consider renaming the field in order to make it visible to the target audience of your IDL.


text:
Q: Cross Linux-Flavor Method - List all fonts I was trying to use x11, or file system, to get a list of all the installed fonts on the system. Is there a cross linux-flavor method to do this?

A: You can run the fc-list command to list all the fonts the logged in user can use.


text:
Q: Isotope won't sort alphabetically I'm trying to extract text and sort that text alphabetically with the isotope library..the text is in each p tag with the class of .box-title.  I'm passing a function to get that text via the getSortData option..... but this is not working. Any ideas why? I've inspected $container, $elem and $('.box-title') and they both return arrays of data
$container.isotope({
    getSortData: {
        name: function ($elem) {
            return $elem.find('.box-title').text();
        }
    }
});
$container.isotope({
    sortBy: 'name'
});

A: You have an error in your code.
name: function (elem) {
            return $(elem).find('.box-title').text();
      }


text:
Q: InsertOrUpdate vs. InsertOrMerge in Azure Storage Tables, what is the difference? After looking at the Microsoft documentation for both of these methods, I don't see any difference between two, or maybe I've missed something.  I've experimented a little with InsertOrMerge, but all it does it replace the old data with the new data.

A: InsertOrUpdate = replaces the entire entity, including removing any fields that were not defined in the new entity.
InsertOrMerge = The old fields and values remain if the new entity does not include them, and all the other fields will be updated.

A: https://blogs.msdn.microsoft.com/windowsazurestorage/2011/09/15/windows-azure-tables-introducing-upsert-and-query-projection/

The two Upsert APIs provided by Windows Azure Table are
  InsertOrReplace Entity and InsertOrMerge Entity which are defined as
  follows:

*

*InsertOrReplace Entity: as the API name implies, InsertOrReplace Entity will insert the entity if the entity does not
  exist, or if the entity exists, replace the existing one. This means
  that once the operation successfully completes the table will contain
  the new entity with properties as defined in the InsertOrReplace
  Entity request, replacing the prior entity and its properties if it
  had previously existed.

*InsertOrMerge Entity: InsertOrMerge Entity will insert the entity if the entity does not exist or, if the entity exists, merges
  the provided entity properties with the already existing ones. Once
  the operation successfully completes, the table will contain the
  provided entity with updated properties provided in the request. In
  other words, if the entity exists, the API would have the same effect
  as Merge Entity, where the resultant entity is a union of
  properties between the existing and the updated ones.


text:
Q: Name for SELECT equivalent of UPSERT UPSERT means INSERT and\or UPDATE, is there a standard name for a stored procedure that will INSERT if necessary and then SELECT?
e.g.  I want to get the IS of a row that matches columns and give me the ID, if nothing matched then I want it to INSERT a new row and return me the ID of that row.

A: In PostgreSQL we have a name for it INSERT ... RETURNING.
You can use this form in a CTE to obtain the effect you want..
CREATE TABLE foo ( foo serial, bar int );

WITH t1 AS (
  SELECT x
  FROM generate_series(1,10) AS t(x)
),
t2 AS (
  INSERT INTO foo (bar)
  SELECT x
  FROM t1
  WHERE NOT EXISTS (
    SELECT *
    FROM foo
    WHERE foo.bar = x
  )
  RETURNING foo, bar
)
SELECT foo, bar
FROM foo
INNER JOIN t1 ON (foo.bar = t1.x)
UNION ALL
  SELECT *
  FROM t2
;

Here we

*

*Generate test data in a cte t1 which we plan to INSERT or SELECT on.

*With t2 we INSERT the data we don't already have into our desired table... foo, and return the results (that which was inserted) as t2

*We run a SELECT to get all of the elements in our test data (t1) that already exist.

*INSERT all of the others.


text:
Q: upload all the extentions of allowed format hello all i am having a issue with my upload document by php
i have validated the upload file by php like
      function uploadanyfile($fileName){
$allowedExts = array("pdf","doc","docx","png","jpg","jpeg","gif","GIF","ppt","pptx","PNG","JPEG","JPG","psd","txt","xlsx","xls","rtf");$refrenext=explode(".", $_FILES["$fileName"]["name"]);
$extension = end($refrenext);
if ( (
($_FILES["$fileName"]["type"] == "application/pdf") ||
($_FILES["$fileName"]["type"] == "application/acrobat") ||
($_FILES["$fileName"]["type"] == "application/x-pdf") ||
($_FILES["$fileName"]["type"] == "application/msword") ||
($_FILES["$fileName"]["type"] == "application/rtf") ||
($_FILES["$fileName"]["type"] == "application/vnd.ms-excel") ||
($_FILES["$fileName"]["type"] == "application/vnd.ms-powerpoint") ||
($_FILES["$fileName"]["type"] == "application/vnd.openxmlformats-officedocument.presentationml.presentation") ||
($_FILES["$fileName"]["type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") ||
($_FILES["$fileName"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") ||
($_FILES["$fileName"]["type"] == "image/psd") ||
($_FILES["$fileName"]["type"] == "application/psd") ||
($_FILES["$fileName"]["type"] == "text/plain") ||
($_FILES["$fileName"]["type"] == "application/photoshop") ||
($_FILES["$fileName"]["type"] == "image/photoshop") ||
($_FILES["$fileName"]["type"] == "image/PJPEG") ||
($_FILES["$fileName"]["type"] == "image/pjpeg") ||
($_FILES["$fileName"]["type"] == "image/PNG") ||
($_FILES["$fileName"]["type"] == "image/png") ||
($_FILES["$fileName"]["type"] == "image/GIF") ||
($_FILES["$fileName"]["type"] == "image/gif") ||
($_FILES["$fileName"]["type"] == "image/jpeg") ||
($_FILES["$fileName"]["type"] == "image/JPG") ||
($_FILES["$fileName"]["type"] == "image/jpg") ) &&
in_array($extension, $allowedExts))
{
  if ($_FILES["$fileName"]["error"] > 0)
  {
 $retuva= 'error in uploading may be the file type is not supported.!!';
  }
  else
 {
$retuva= 'Success1230';
  }
 } else {
 $retuva= 'file not uploaded !! Invalid file type.';
  }
 return $retuva;
}

the function works good but the problem is that when i try to upload any ppt or doc of any other extention like pptx or csv etc the function says invalid file i know the reason but i can not list all the possible values of any perticular file a doc can have hundreds of extentions in mac or windows..
can i get a help where i can allow all the possible uploads only restrict the files which can harm my server lke .php or exe files... ?


text:
Q: Ubuntu VM disk error- first went read-only and now won't boot I have a Ubuntu Server VM on a Mac OS X host. Stupidly, I have no recent snapshot of this VM (let this be a grim reminder to me).
My host was running slowly and erratically- low on RAM. While trying to change files on the VM, I received a constant "file system is read-only" error (similar to this question Ubuntu VM "read only file system" fix?). I shutdown the VM and restarted the computer, then opened Virtual Machine with no other applications running. Now, when I attempt to load the VM, I get a number of these errors on the start-up screen and then it freezes:
comm init: bad extended attribute block (some numbers here)

I am able to get to Recovery mode but don't have any experience in repairing a Linux machine. Is there anything I could do in Recovery mode, or otherwise, to attempt to save my virtual machine?

A: To answer my own question, as suggested above:
First I attempted to restore the Ubuntu file system using fsck and the instructions contained in this helpful video below:
http://www.youtube.com/watch?v=twBf4MR5sh8
Summarised, they are:

*

*Assuming you have file system problems that can't be fixed while the file system is mounted:

*

*Download a Ubuntu Desktop disk image

*Attach the disk image to the VM and set it as first in the boot order

*Boot into the CD and click "Try Ubuntu"

*Run file recovery commands (such as fsck) that need the file system un-mounted from the Terminal in the CD version

This fixed a bunch of file system problems, but the machine was still hanging on start-up and I was running out of time for Linux System Recovery 101. So I decided to see if restoring from Time Machine back-up would work.
Roughly, that process goes like this:

*

*Restore known good back-up of VM to desktop

*Run a command to change the UUID of the restored VM. On my Mac, that was
VBoxManage internalcommands sethduuid /path/to/my/restored/disk/image.vdi

*In VirtualBox, open the Settings for the broken machine, go to Storage, detach existing disk image and attach restored disk image

*Start-up & hold your breath.

That worked, although many of the files that ought to have been there weren't. Fortunately I have separate back-ups of those files, so have been able to restore it all with only, er, 1.5 days downtime.


text:
Q: How to determine closest AWS region to client's browser? I'm making a service that will allow clients to do text-to speech in the browser for language-learning purposes.
The the client will submit the text to the backend server, which will send back a pre-signed request url for the AWS Polly service. The client will then request the audio directly from AWS Polly.
Because this is audio, the documentation makes it clear that the AWS region specified is important for minimizing latency. However my clients can be anywhere, and I need to determine the closest AWS region to them.
I have seen only answers that involve extremely complicated solutions to this, but some of them are old.
Is there a simple way to make sure that my AWS request goes to the closest region to the client? I'll have access to their IP I suspect in most cases.
To be clear I need the actual text region (eg 'us-east-2')
const client = new Polly({
    region: "REGION",
    credentials: fromCognitoIdentityPool({
        client: new CognitoIdentityClient({ region: "REGION" }),
        identityPoolId: "IDENTITY_POOL_ID" // IDENTITY_POOL_ID
    }),
});

Update**
It looks like I can probably cobble together ip-range-check and ip-ranges.json to get this done programmatically without DNS lookup.
Anyone want to make an NPM package for me? Maybe this will be my first NPM package, lol.


text:
Q: Basic Webscraping with Python (Beautiful Soup & Requests) So I've been working through Al Sweigart's online Automate The Boring Stuff With Python tutorials, and I've just got to the webscraping part. Here's my code with a description of what the program is supposed to do:
#! python3
# lucky.py - A small program that allows you to get search keywords from
# command line arguments, retrieve the search results page, and open
# a new browser tab for each result

# Steps:
# 1. Read the command line arguments from sys.argv
# 2. Fetch the search result page with the requests module
# 3. Find the links to each search result
# 4. Call the webbrowser.open() function to open the web browser

import sys, requests, bs4, webbrowser

# 1. Read the command line arguments from sys.argv

print('Googling...')

if len(sys.argv) > 1:
    search = ' '.join(sys.argv[1:])

url = "https://www.google.com/#q="

for i in range(len(search.split())):
    url += search.split()[i] + "+"

# 2. Fetch the search result page with the requests module

page = requests.get(url)

# 3. Find the links to each search result

soup = bs4.BeautifulSoup(page.text, 'lxml')
linkElems = soup.select('.r a')

# 4. Call the webbrowser.open() function to open the web browser

numOpen = min(5, len(linkElems))
for i in range(numOpen):
    webbrowser.open("http://google.com" + linkElems[i].get('href'))

So the issue here is that when I check the length of linkElems, it's 0, meaning that the soup.select('.r a') command failed to aggregate the content defined under element <a> inside class=r (a class only used for search results in Google as can be seen when using the developer tools). As a result, no web pages of the search results open up in my browser.
I think the issue has something to do either with the HTML-parser not working correctly, or Google changing the way their HTML code works(?). Any insight into this issue would be greatly appreciated!

A: Google seems to be detecting that you're a bot and not a real webbrowser with Cookies and Javascript. What they seem to be trying to do with the new results is still get web scrapers to follow the links they provide and prefix them with https://www.google.com so that when you then go to that URL, they can still track your movement.
You could also try to find a pattern in the link provided. For instance, when you search for 'linux', it returns the following:
/url?q=https://en.wikipedia.org/wiki/Linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.org/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.com/what-is-linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=d50ea51a-206b-11e8-9432-2bee635f8337
/url?q=https://www.ubuntu.com/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=dab9f6a4-206b-11e8-a999-3fc9d4576425
/search?q=linux&ie=UTF-8&prmd=ivns&source=univ&tbm=nws&tbo=u&sa=X&ved=9775308e-206b-11e8-b45f-fb72cae612a8

You could use a regex to grab the part between '/url?q=' and '&sa=U&ved=' as that's the URL that you probably want. Of course, that doesn't work with the 5th result that it returned because it's something special for the Google website. Again, Probably tacking https://www.google.com on the front of each URL returned is the safest thing to do.
Most search engines (even duckduckgo.com) are trying to track search results and clicks. If you try to avoid it they have detection code in place to block you. You may have run into this with Google telling you they've detected a large number of searches from your IP and you have to go through a CAPTCHA test to continue.

A: linkElems = soup.find_all('a',href=True) This returns all the relevant <a> tags and you can process the list to decide what to keep and what not to keep.

A: There's no need in phantomjs or selenium. Also, query param is wrong: #q= -> ?q=.
You can limit selected links by using list slicing:
linkElems = soup.select('.r a')[:5]
# or
for i in soup.select('.r a')[:5]:
    # other code..

Make sure you're using user-agent because default requests user-agent is python-requests thus Google blocks a request because it knows that it's a bot and not a "real" user visit and you'll receive a different HTML with some sort of an error. User-agent fakes user visit by adding this information into HTTP request headers.
I wrote a dedicated blog about how to reduce chance of being blocked while web scraping search engines that cover multiple solutions.
Pass user-agent in request headers:
headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
requests.get('YOUR_URL', headers=headers)

Code:
from bs4 import BeautifulSoup
import requests, lxml

headers = {
    'User-agent':
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}

params = {
  "q": "samurai cop what does katana mean",
  "gl": "us",
  "hl": "en"
}

html = requests.get("https://www.google.com/search", headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')

for result in soup.select('.tF2Cxc')[:5]:
  title = result.select_one('.DKV0Md').text
  link = result.select_one('.yuRUbf a')['href']

  print(title, link, sep='\n')

--------
'''
Samurai Cop - He speaks fluent Japanese - YouTube
https://www.youtube.com/watch?v=paTW3wOyIYw
Samurai Cop - What does "katana" mean? - Quotes.net
https://www.quotes.net/mquote/1060647
"It means "Japanese sword"... 2 minute review of a ... - Reddit
https://www.reddit.com/r/NewTubers/comments/47hw1g/what_does_katana_mean_it_means_japanese_sword_2/
Samurai Cop (1991) - Mathew Karedas as Joe Marshall - IMDb
https://www.imdb.com/title/tt0130236/characters/nm0360481
What does Katana mean? - Samurai Cop quotes - Subzin.com
http://www.subzin.com/quotes/Samurai+Cop/What+does+Katana+mean%3F+-+It+means+Japanese+sword

Alternatively, you can achieve the same thing by using Google Organic Results API from SerpApi. It's a paid API with a free plan.
The difference in your case is that you only need to iterate over structured JSON and get the data you want rather than making everything from scratch and maintain it over time.
Code to integrate:
import os
from serpapi import GoogleSearch

params = {
  "engine": "google",
  "q": "samurai cop what does katana mean",
  "hl": "en",
  "gl": "us",
  "api_key": os.getenv("API_KEY"),
}

search = GoogleSearch(params)
results = search.get_dict()

for result in results["organic_results"][:5]:
  print(result['title'])
  print(result['link'])

---------
'''
Samurai Cop - He speaks fluent Japanese - YouTube
https://www.youtube.com/watch?v=paTW3wOyIYw
Samurai Cop - What does "katana" mean? - Quotes.net
https://www.quotes.net/mquote/1060647
"It means "Japanese sword"... 2 minute review of a ... - Reddit
https://www.reddit.com/r/NewTubers/comments/47hw1g/what_does_katana_mean_it_means_japanese_sword_2/
Samurai Cop (1991) - Mathew Karedas as Joe Marshall - IMDb
https://www.imdb.com/title/tt0130236/characters/nm0360481
What does Katana mean? - Samurai Cop quotes - Subzin.com
http://www.subzin.com/quotes/Samurai+Cop/What+does+Katana+mean%3F+-+It+means+Japanese+sword
'''

Disclaimer, I work for SerpApi.


text:
Q: How to stop formatting/indentation breaking elements? Ok so this is a strange one and I'm not sure I can really give an effective code example here. But basically, I have some markup and if I add a space or a tab between anydiv to format it for readability, it will break the html. I haven't saw this before....
So this is what I have, and when you hover over one of the boxes, it will slide up to reveal some text behind it like so.

The problem is that there isn't much spacing and/or indentation in the markup.

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 48 48"><g transform="translate(0, 0)">
    <path data-color="color-2" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round" d="M2,24L6,24" style="stroke-dasharray: 4, 6; stroke-dashoffset: 0;"></path>
    <path data-color="color-2" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round" d="M8.4,8.4L11.3,11.3" style="stroke-dasharray: 5, 7; stroke-dashoffset: 0;"></path>
    <path data-color="color-2" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round" d="M24,2L24,6" style="stroke-dasharray: 4, 6; stroke-dashoffset: 0;"></path>
    <path data-color="color-2" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round" d="M39.6,8.4L36.7,11.3" style="stroke-dasharray: 5, 7; stroke-dashoffset: 0;"></path>
    <path data-color="color-2" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round" d="M46,24L42,24" style="stroke-dasharray: 4, 6; stroke-dashoffset: 0;"></path>
    <path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" d="M36,24c0-6.6-5.4-12-12-12  s-12,5.4-12,12c0,5.2,3.3,9.7,8,11.3V40h8v-4.7C32.7,33.7,36,29.2,36,24z" stroke-linejoin="round" style="stroke-dasharray: 85, 87; stroke-dashoffset: 0;"></path>
    <path data-color="color-2" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round" d="M20,46L28,46" style="stroke-dasharray: 8, 10; stroke-dashoffset: 0;"></path>
    </g></svg>

Lorem Ipsum

Vestibule convallis pulvinar tellus eget ultricies. Sed sollicitudin, sem vitae elementum euismod, veilt arcu mattis diam, in scelerisque purus.

If I try to add any spacing using the spacebar, return or tab key, the elements breaks. Instead of the title and icon being placed in the center as I'd expect, for what ever reason, it drops below.
Any ideas as to what could be causing this?
UPDATE: fiddle

SPACE/TAB HERE

If you go on the fiddle, and add the space or a tab where I've added a comment on the above markup, you will see that it will break the code.

A: As posted by  Paulie_D it is correlating wit the following question.
You could use additional css, which is a "fix" like (first case vs second case):
float: left;

or on the parent element:
font-size: 0;

etc. Those are not the best solutions. The conclusion in the mentioned thread is the following:

...remove the whitespace in the HTML between the inline-block elements.


text:
Q: Do I need to write SELECT query additionally while using content values? I'm working on a code snippet for performing CRUD operations in Sqlite DB in Android Studio. I created a listView to hold two attributes, i.e., name and job but the application is getting crashed at runtime. It says:

Sqlite Exception: no such column( code 1) "name" Found.

I've searched for the solution but every solution I've checked is a failed one. My DB browser shows the table contains the column. Do I need to add SELECT FROM ...query to my code? If it is, then where should I put the code?

my code as below:
DatabaseHelper.class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "USERS";
public static final String _ID = "_id";
public static final String DESC = "occupation";
public static final String SUBJECT = "name";
SQLiteDatabase myDb;

private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
        "(" + _ID  + " INTEGER  PRIMARY KEY AUTOINCREMENT,"
        + SUBJECT + "TEXT NOT NULL,"
        + DESC + "TEXT"+ ")" ;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);

}

public long insert(String name, String desc) {
     myDb = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(DatabaseHelper.SUBJECT, name);
    contentValues.put(DatabaseHelper.DESC, desc);
    long id = myDb.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
    myDb.close();
    return id;
}

public Cursor read(){
    SQLiteDatabase myDb = this.getWritableDatabase();
    String[] columns = new String[] {DatabaseHelper._ID,DatabaseHelper.SUBJECT,DatabaseHelper.DESC};
    Cursor cursor = myDb.query(DatabaseHelper.TABLE_NAME,columns,null,null,null,null,null);
    if(cursor!=null){
        cursor.moveToFirst();
    }
    myDb.close();
 return cursor;
}

 }

MainActivity.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button addUser;
ArrayList<String> list;
ArrayAdapter<String> adapter;
DatabaseHelper dbManager;

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

    addUser = findViewById(R.id.add_button);
    list = new ArrayList<>();
    adapter = new ArrayAdapter<>(this, R.layout.populate_list, R.id.name, list);
    dbManager = new DatabaseHelper(this);

    addUser.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addAccount();
        }
    });

}

public void addAccount() {
    Intent intent = new Intent(MainActivity.this, AddUser.class);
    startActivityForResult(intent, 1);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 1) {
        final String name = intent.getStringExtra("name");
        final String occupation = intent.getStringExtra("occupation");
        ListView listView = findViewById(R.id.parentLayout);

        dbManager.read();
        list.add(name);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i = new Intent(MainActivity.this, UpdateActivity.class);
                i.putExtra(name, "username");
                i.putExtra(occupation, "occupation");
                startActivity(i);

            }
        });
    }
}
}

AddUser.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddUser extends AppCompatActivity {
EditText userName, job;
Button submitButton, cancelButton;

DatabaseHelper dbManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_user);
    dbManager = new DatabaseHelper(this);
    userName = findViewById(R.id.userText);
    job = findViewById(R.id.occupation);
    submitButton = findViewById(R.id.submit_button);
    cancelButton = findViewById(R.id.cancel_button);

    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(AddUser.this, MainActivity.class);
            startActivity(intent);
        }
    });
    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = getIntent();
            String name = userName.getText().toString();
            String desc = job.getText().toString();
            intent.putExtra(name, "name");
            intent.putExtra(desc, "occupation");
            dbManager.insert(name, desc);
            setResult(1, intent);
            finish();

        }
    });
}

  }

A: You can try using a rawquery like this :
String sql = " SELECT * FROM " + TABLE_NAME + " WHERE " + ONE_COLUMN_NAME + "=?" + " AND " + PERHAPS_ANOTHER_COLUMN + " =?";
    ArrayList<YourKindOfObject> array = new ArrayList<>();
    Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{firstParameter, secondParameter});
    while (cursor.moveToNext()) {

        YourKindOfObject yourKindOfObject = new YourKindOfObject();
        yourKindOfObject.setOneThing(cursor.getString(cursor.getColumnIndex(ColumnName));
        yourKindOfObject.setOneOtherThing(cursor.getString(cursor.getColumnIndex(ColumnName1)));
        array.add(yourKindOfObject);
    }
    cursor.close();
    return array;