Q: Cant find imgs:s when React.js project is bundled with webpack2 Everything works in development, all images are found. But when I bundle my the files and upload to webhost, product img:s can't be found and returns error:

This is my .htaccess:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>

This is my webpack.config.prod.js file:

//  PRODUCTION

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const entry = {
 app: path.join(process.cwd(), 'src/app.js')
}

const output = {
 path: path.join(__dirname, 'dist'),
 filename: 'bundle.min.js',
}

const plugins = [
 new webpack.DefinePlugin({
   'process.env.NODE_ENV': JSON.stringify('production')
 }),
 new webpack.optimize.UglifyJsPlugin({
  mangle: false,
  compress: {
   warnings: false
  }
 }),
  new ExtractTextPlugin('bundle.css'), // creation of HTML files to serve your webpack bundles
 new HtmlWebpackPlugin({
  template: 'index-template.html'
 }),
 new webpack.optimize.CommonsChunkPlugin({
  name: 'bundle',
  filename: '[name].common.js'
 })
]

const config = {
  context: path.join(__dirname, 'src'),
  entry: entry,
 output: output,
 devtool: "source-map",
  module: {
    rules: [
   {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    include: path.join(__dirname, 'src'),
    use: "babel-loader"
   },
      {
     test: /\.(png|jpg|gif)$/,
     use: [{
     loader: 'url-loader',
     options: { limit: 10000, name: './img/[name].[ext]' } // Convert images < 10k to base64 strings (all in img folder)
    }]
   },
   {
    test: /\.(sass|scss)$/,
    use: ExtractTextPlugin.extract({
       fallback: 'style-loader',
       use: [
         'css-loader',
         {
       loader: 'postcss-loader',
       options: {
        plugins: (loader) => [ require('autoprefixer')() ]
       }
      },
         'sass-loader',
       ]
     })
   }
  ]
  },
 plugins: plugins,
 externals: {
   jquery: 'jQuery'
 }
}

module.exports = config;

Images are imported in my product product component under lifecycle event "componentDidMount":

import React, { Component } from 'react';
import Modal from 'react-modal';
import PropTypes from 'prop-types';

// Custom styles for Modal image
const customStyles = {
  content : {
    top                   : '50%',
    left                  : '50%',
    right                 : 'auto',
    bottom                : 'auto',
    marginRight           : '-50%',
    transform             : 'translate(-50%, -50%)',
    background            : 'rgba(0, 0, 0, 0.8)',
    width                 : '100vw',
    height                : '100vh',
    display               : 'flex',
    justifyContent        : 'center',
    alignItems            : 'center'
  }
};

class ProductItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalIsOpen: false,
      image: '',
      previewImg: ''
    };

    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
  }

  // Set state object "modalIsOpen" to true when click on <ProductItem/> component
  openModal() {
    this.setState({
      modalIsOpen: true
    });
  }

  // Set state object "modalIsOpen" to false when click on <Modal/> component
  closeModal() {
    this.setState({
      modalIsOpen: false
    });
  }

  render(){
    // Create variables for all <ProductItem/> description options. If <PoductItem/> object has props or state, render it. Otherwise return null.
    var img = this.state.image ?
       :
      null;

    const name = this.props.product.stocked ?

{this.props.product.name}
 :

        {this.props.product.name}

;

    var limited = this.props.product.limited ?

begränsad upplaga: {this.props.product.limited} ex
 :
      null;

    var available = this.props.product.available ?

tillgängliga: {this.props.product.available} ex
 :
      null;

    var price = this.props.product.price ?

{this.props.product.price}  kr
 :
      null;

    var type = this.props.product.type ?

{this.props.product.type}
 :
      null;

    var size = this.props.product.size ?

{this.props.product.size} cm
 :
      null;

    var desc = this.props.product.desc ?

{this.props.product.desc}
 :
      null;

    var modalName = this.props.product.name ?

{this.props.product.name}
 :
      null;

    var modalDesc = this.props.product.desc ?

{this.props.product.desc}
 :
      null;

    return (

        <Modal
          isOpen={this.state.modalIsOpen}
          onRequestClose={this.closeModal}
          style={customStyles}
          contentLabel="Modal image"
        >

x

            {modalName}
            {modalDesc}

        </Modal>
        {img}
        {name}
        {type}
        {limited}
        {available}
        {size}
        {price}
        {desc}

    );
  };

  // Import all thumbnail + previewImg images and then() put them into state. If rejection occures catch() returns rejection reasen (err).
  componentDidMount() {
    import(`./images/${this.props.product.thumbnail}`).then(
      (image) => this.setState({
        image: image
      })
    ).catch((err) => {
      console.log('error thumbnail' + err);
    });
    import(`./images/${this.props.product.previewImg}`).then(
      (previewImg) => this.setState({
        previewImg: previewImg
      })
    ).catch((err) => {
      console.log('error previewImg' + err);
    });
  }
};

// Components expected proptypes
ProductItem.propTypes = {
  product: PropTypes.object.isRequired
}

export default ProductItem;

All this works in development environment, images render no problem. Also, my background image and other img work that are being inserted via SASS:

.background-img {
  position: fixed;
  background: url(../images/main.jpg) no-repeat center center scroll;
  background-size: cover;
  z-index: 0;
}

or via "import" as ex "magdaImg":

A: It turned out to be a problem with my project not being located in the root.


Q: What is the story of the Observer Design Pattern? I have been investigating about the observer pattern for an assignment. So far, I have come to the conclusion that it first appeared in a book written by a group of people called "The Gang of Four".
But I also read that its first implementation was in a SmallTalk MVC-based framework.
Is there an origin to the observer pattern? Who designed it first? Which of the GoF members did it? Has it suffered any changes since its creation?
Also, some implementations of the pattern include what they call a "ConcreteSubject" which is a generalization of the Subject class. Is this a variation of the pattern, or rather an evolution from the original model?

A: The Gang of Four's main contribution to Design Patterns is really giving names to some commonly-used patterns to assist communication of design intent. It's so much easier to write
// this is an observer

than a big ol' block of comments that no one will read. And if people shared the jargon, developers can communicate more effectively.
The Observer pattern has been around long before OO programming. Most often it was referred to using the term "callback", often implemented with function pointers in various languages, or perhaps even a flag that was used to indicate which function/procedure/subroutine should be called. This represented one of the earliest forms of abstract communication between modules. I've even seen similar approaches taken in assembler languages - storing a callback address and using it to indirectly notify that "something happened".
A big thing to remember... the implementations that the Gang of Four show in the Design Patterns book are not "absolute" - they're there to demonstrate an approach. You can just as easily implement the Observer pattern with a function pointer as you can with an abstract class, interface, or C# delegate.
(I teach a Design Patterns course at Johns Hopkins, btw ;) )

A: What The Gang of Four did wasn't invent patterns, they observed and researched the software field at the time in order to catalog the solutions to the common problems faced by developers.
As for who initially invented it your guess is as good as mine I suppose. Although I'll be interested if anyone do know who invented it. In my opinion it's like asking who invented fire...
ConcreteSubject refers to the implementation of the Subject interface. And it's not a variation it's simply necessary to have a interface to facilitate the pattern. (or a super class but an interface is much more better).


Q: How does the Windows Python Launcher (py.exe) find the python executable(s)? I'm trying to use the Windows Python Launcher (py.exe) for the first time.  I run python in a command shell but the launcher, running in the same shell, can't find any version of python.exe to run:
where python
C:\Python38\python.exe
py --list
Installed Pythons found by py Launcher for Windows
No Installed Pythons Found!

Obviously there is something missing in my configuration but I'm at a loss as to what.  I've been digging into the registery and have located keys in:
HKEY_LOCAL_MACHINE/SOFTWARE/Wow6432Node/Python/PyLauncher
HKEY_LOCAL_MACHINE/SOFTWARE/Wow6432Node/Python/PythonCore

but there isn't anything that references any executables.
Any help appreciated!

A: You was on the right path. In your case, you would need to add the the following entries in the registry:
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.8]

[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\3.8\InstallPath]
@="C:\\python38\\"
"ExecutablePath"="C:\\Python38\\python.exe"
"WindowedExecutablePath"="C:\\Python38\\pythonw.exe"

Also answered in py launcher does not find my Python 2.7


Q: Hiding .aspx from url in ASP.NET Framework 3.5 I would require to hide .aspx extension and query sting values from complete url. I have tried many solution online but didn't succeeded.
After long search I have found one sample code article (linked below):
http://www.aspsnippets.com/Articles/How-to-hide-remove-ASPX-extension-in-URL-in-ASPNet.aspx
Now, in this article it's given at starting that it would build using Framework 3.5 & Service Pack 1.
Even I have checked the Visual Studio 2008 I have installed on my machine is Framework 3.5 & SP1. Therefore I have tried this application.
But there are some issues while I have tried this solution.
ie:

*

*As we have to import Routing package (System.Web.Routing), I have imported it, but it didn't recognized. Then I have manually referenced the Routing package from .NET Libararies.

*After that it didn't recognizing the method of (routes.MapPageRoute).

*This method is being used to manually set the alias for url, but it shows me Blue Underline under this method and on running it shows me the message as (MapPageRoute is not a member of System.Web.Routing.RouteCollection).

so, please guide me according to this solution.

A: it's available only on .net framework 4.0 & 4.5


Q: Frameless window shows dark border on linux I created a dialog with shadow effect
 Qt::WindowFlags flags = Qt::Dialog| Qt::FramelessWindowHint;

 QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect;
 effect->setOffset(4);
 effect->setBlurRadius(9);
 contWdget->setGraphicsEffect(effect);

This works perfect on windows but when I open the same dialog in Linux its showing dark black color border around the dialog.
What work around I need to do to make it work on Linux.

A: To frameless window in linux use Qt::FramelessWindowHint like this :
QDialog *dialog = new QDialog();
dialog->setWindowFlags( Qt::FramelessWindowHint );
dialog->show();

Tested on :
Qt Creator 4.3.1
Based on Qt 5.9.0 (GCC 5.3.1 20160406 (Red Hat 5.3.1-6), 64 bit)
Ubuntu 16.04 LTS


Q: Focus randomly jumps when scrolling I have an activity with many EditText controls and checkboxes near them. By default, most EditTexts are disabled.
When I open the activity, some random EditText control gets focus (a frame around it) and if you tap on it, the on-screen keyboard appears even though the EditText is disabled and no text appears when you press the on-screen keys.
Also, my whole layout is wrapped in a ScrollView. When you scroll, some random EditTexts get focus. It can be the lowest visible one, or the highest visible, or sometimes one in the middle, sometimes one outside the visible area.
Because a random element of the layout gets focus, the Activity gets randomly scrolled down when you open it, which is pretty annoying.
I guess it's an Android's bug, but is there a workaround?
Stop EditText from gaining focus at Activity startup handles the situation with only 1 EditText for which you can tell to lose focus so that the dummy element could gain it. In my case the dummy element doesn't gain focus, both in onResume or onCreate, with both android:focusable="true" android:focusableInTouchMode="true"
Should I check all the EditText controls (there are 12 of them) and tell them to lose focus? What with scrolling, because it seems focus randomly jumps.

A: Because of the implementation of the fling Method in the ScrollView -
it is sufficient to override the findFocus(), so that it will return this
to prevent the focus from jumping around when scrolling.
@Override
public View findFocus() {
    return this;
}

A: It's not scrolling that randomly focuses the EditText. It's when the scrollview handles a fling event. If you overwrite the fling method the won't be any random focus changes.
Then if you want the fling functionality back you'll need to write your own fling method. There's code here you can copy from:
Smooth scrolling in Android


Q: I have a linked table which is linked to a .txt file in my directory itself I have a linked table which is linked to a .txt file in my directory itself. Now I need to create a command button in a Form which helps me to relink the .txt file whenever I require, using VBA code.
Can anyone please help me on this.

A: You don't have to. The file/data will be read "as is" whenever you open the table.
If you wish to update the text file, just replace it with the new file.

A: Thanks for the reply. But i need to refresh my linked table anyway. So i found this code helpful.
                                                        Private Sub Command3_Click()
Dim b As Boolean
b = RefreshLinkedTables()                                                                        End Sub
                                                                                Function RefreshLinkedTables() As Boolean
Dim db As DAO.Database
Dim tb As DAO.TableDef
Dim fld As DAO.Field

Set db = CurrentDb

For Each tb In db.TableDefs
    ' Skip system files.
    If (Mid(tb.Name, 1, 4) <> "MSys" And Mid(tb.Name, 1, 4) <> "~TMP") Then
        Debug.Print tb.Name
        Debug.Print tb.Connect
        'If (Mid(tb.Connect, 1, 5) = "ODBC;") Then

            If (tb.Name = "P60DZ30") Then
                tb.RefreshLink
                Debug.Print "Refreshing fields data"
                tb.Fields.Refresh

            End If
        'End If
        Debug.Print "=== === ==="
    End If
    db.TableDefs.Refresh
Next

Set db = Nothing

RefreshLinkedTables = True
Exit Function

End Function


Q: android searchview setOnActionExpandListener on Honeycomb 3.2 I'm developing an app for Android 3.2 and greater with android-support-v4. I need to implement OnActionExpandListener for "intercept" when SearchView in the actionbar is expanded and when is collapsed. My code for Android 4.0 and higher it's ok, but for 3.2 no.

menu.xml

<item android:id="@+id/menu_search"
    android:title="@string/menu_search"
    android:icon="@android:drawable/ic_menu_search"
    android:showAsAction="collapseActionView|always"
    android:actionViewClass="android.widget.SearchView" />

MyActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.reader, menu);

    final MenuItem searchMI = menu.findItem(R.id.menu_search);
    if(searchView == null) {
        //searchView = (SearchView) searchMI.getActionView();
        searchView = (SearchView) MenuItemCompat.getActionView(searchMI);
        searchView.setOnQueryTextListener(this);
        searchView.setOnSuggestionListener(this);
        searchView.setOnCloseListener(new OnCloseListener() {

            @Override
            public boolean onClose() {
                //some code
                return false;
            }
        });
    }

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
        MenuItemCompat.setShowAsAction(searchMI, MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        MenuItemCompat.setOnActionExpandListener(searchMI, new OnActionExpandListener() {

            /* (non-Javadoc)
             * @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionExpand(android.view.MenuItem)
             */
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }

            /* (non-Javadoc)
             * @see android.support.v4.view.MenuItemCompat.OnActionExpandListener#onMenuItemActionCollapse(android.view.MenuItem)
             */
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                Toast.makeText(getApplicationContext(), "onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    } else {
        searchMI.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                Toast.makeText(getApplicationContext(), "MenuItem#onMenuItemActionExpand", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }
}

Why, for Honeycomb, methods of listener is not invoked?
Thank you so much.

A: I found that MenuItemCompat.setOnActionExpandListener(...) is not working if you don't pass:
    searchItem
            .setShowAsAction(MenuItemCompat.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW
                    | MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

But this is changing the SearchView and is replacing the DrawerToggle with back arrow.
I wanted to keep the original views and still track the Expanded/Collapsed state and use supported Search View.
Solution:
When android.support.v7.widget.SearchView is changing the view state the LinearLayout view's, with id android.support.v7.appcompat.R.id.search_edit_frame, visibility value is being changed from View.VISIBLE to View.GONE and opposite. So I add ViewTreeObserver to track the visibility change of the search edit frame.
menu_search.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="@string/search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always"/>

</menu>

In the activity:
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;

..........

private View mSearchEditFrame;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    MenuItem searchItem = (MenuItem) menu.findItem(R.id.action_search);

    SearchView searchView = (SearchView) MenuItemCompat
            .getActionView(searchItem);
    searchView.setSubmitButtonEnabled(false);
    mSearchEditFrame = searchView
            .findViewById(android.support.v7.appcompat.R.id.search_edit_frame);

    ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        int oldVisibility = -1;

        @Override
        public void onGlobalLayout() {

            int currentVisibility = mSearchEditFrame.getVisibility();

            if (currentVisibility != oldVisibility) {
                if (currentVisibility == View.VISIBLE) {
                    Log.v(TAG, "EXPANDED");
                } else {
                    Log.v(TAG, "COLLAPSED");
                }

                oldVisibility = currentVisibility;
            }

        }
    });

    return super.onCreateOptionsMenu(menu);
}

Thanks!

A: You probably missed the fact (like I did) that `MenuItemCompat.OnActionExpandListener' interface has a static implementation, and is not an instance method.
So, if you have a class that implements MenuItemCompat.OnActionExpandListener then in that class you need to install it as the listener like this:
MenuItem menuItem =  menu.findItem(R.id.search);
if (menuItem != null) {
  MenuItemCompat.setOnActionExpandListener(menuItem,this);
  MenuItemCompat.setActionView(menuItem, mSearchView);
}

The same paradigm applies to setActionView ... rather than invoke menuItem.setActionView(this), you pass the menuItem as the first argument to the static version MenuItemCompat.setActionView and follow with the other argument(s).

A: For MenuItemCompat.setOnActionExpandListener to work you should add "collapseActionView" added in the menu item -
for example -
<item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          app:showAsAction="ifRoom|collapseActionView"
          app:actionViewClass="android.support.v7.widget.SearchView" />

And in the onCreateOptionsMenu you can use it this way -
MenuItemCompat.setOnActionExpandListener(menu_search,
            new OnActionExpandListener()
            {
                @Override
                public boolean onMenuItemActionCollapse(MenuItem item)
                {
                    // Do something when collapsed
                    return true; // Return true to collapse action view
                }

                @Override
                public boolean onMenuItemActionExpand(MenuItem item)
                {
                    // Do something when expanded
                    return true; // Return true to expand action view
                }
            });

A: Your Listener should be MenuItemCompat.OnActionExpandListener() .
MenuItemCompat.setOnActionExpandListener(searchItem,
            new MenuItemCompat.OnActionExpandListener() {

}

A: thanks for your help,
your solution is work for me. and i'd like to vote you up, but i just realized i have only 1 reputation，(；′⌒`)
actually, my solution is similar to your, there is just one different in the menu xml file like this:
    <item
    android:id="@+id/apps_menu_search"
    android:icon="@drawable/ic_action_search"
    android:title="@string/apps_menu_search"
    android:visible="true"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="ifRoom|collapseActionView" />


Q: Proof-method: Show that if $n$ is not prime then $\Bbb Z /n\Bbb Z$ is not a field The question pertains to the question in the title. That is,

Show that if $n$ is not prime then $\Bbb Z /n\Bbb Z$ is not a field.

I realise that this has many duplicates, but my question is rather this;

Why does it not suffice to say that if $n$ is not prime then $\lvert\Bbb Z /n\Bbb Z \rvert = n \neq p^m$ for some prime $p$ and integer $m$ and so is not a field by definition?

I realise this somewhat misses the reason why it's not a field, but would it suffice as an answer to this question?

A: Because this is not enough to say that $\mathbb Z/9\mathbb Z $ is not a field, as $9$ is in fact of the form $p^m$ for a prime $p$ and positive integer $m$.

A: A major reason why you cannot use this argument is that you seem to saying that because you know every finite field must have $p^{m}$ elements you get a contradiction.
However how do you know that you don't need this result in order to prove that finite field must have $p^{m}$ elements.
So does the proof of finite field must have $p^{m}$ elements, require the knowledge of the prime subfield and does this in turn require knowing that $\mathbb{Z}_{n}$ is a field iff $n$ is prime...


Q: Plot a vertical line using matplotlib I would like to draw a vertical line with Matpotlib and I'm using axvline, but it doesn't work.
import sys
import matplotlib
matplotlib.use('Qt4Agg')

from ui_courbe import *
from PyQt4 import  QtGui
from matplotlib import pyplot as plt

class Window(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.setupUi(self)
        self.boutonDessiner.clicked.connect(self.generatePlot)

    def generatePlot(self):
        # generate the plot
        ax = self.graphicsView.canvas.fig.add_subplot(111)
        ax.plot([1,3,5,7],[2,5,1,-2])
        plt.axvline(x=4)
        self.graphicsView.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

I can see my plot, but no vertical line. Why?

A: Your example is not self contained, but I think you need to replace:
plt.axvline(x=4)

with:
ax.axvline(x=4)

You are adding the line to an axis that you are not displaying. Using plt. is the pyplot interface which you probably want to avoid for a GUI. So all your plotting has to go on an axis like ax.

A: matplotlib.pyplot.vlines

*

*The difference is that you can pass multiple locations for x as a list, while matplotlib.pyplot.axvline only permits one location.

*

*Single location: x=37

*Multiple locations: x=[37, 38, 39]

*If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
plt.vlines(x=[37, 38, 39], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple')
plt.vlines(x=40, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single')
plt.axvline(x=36, color='b', label='avline')
plt.legend()
plt.show()


Q: how to use yii2-bootstrap4 extension with bootstrap 3 in the same app I have tried to install yii2-bootstrap4
but I got this composer error
Your requirements could not be resolved to an installable set of packages.

 Problem 1
- Installation request for yiisoft/yii2-bootstrap4 ^1.0@dev -> satisfiable by yiisoft/yii2-bootstrap4[1.0.x-dev].
- Conclusion: don't install bower-asset/bootstrap v3.3.7
- yiisoft/yii2-bootstrap4 1.0.x-dev requires bower-asset/bootstrap ~4.0.0 -> satisfiable by bower-asset/bootstrap[v4.0.0, v4.0.0-beta.3, v4.0.0-beta1, v4.0.0-alpha.6, v4.0.0-alpha.5, v4.0.0-alpha.4, v4.0.0-alpha.3, v4.0.0-alpha.2, v4.0.0-alpha1].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-beta.3].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-beta1].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.6].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.5].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.4].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.3].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha.2].
- Can only install one of: bower-asset/bootstrap[v3.3.7, v4.0.0-alpha1].
- Installation request for bower-asset/bootstrap (locked at v3.3.7) -> satisfiable by bower-asset/bootstrap[v3.3.7].

Installation failed, reverting ./composer.json to its original content

I want to be able to use bootstrap3 and 4 in the same app, I also tried what is described in this issue "prefer-stable": true, and did not work also.
so what exactly should I do, how to use both bootstrap:~3.0 and bootstrap:~4.0 with official yii2-bootstrap packages

A: You can try to override some requirements in this way:
"minimum-stability": "dev",
"prefer-stable": true,
"require": {
    "php": ">=5.4.0",
    "yiisoft/yii2": "~2.0.14",
    "yiisoft/yii2-bootstrap": "~2.0.8",
    "yiisoft/yii2-bootstrap4": "1.0.x-dev",
    "bower-asset/bootstrap": "3.3.7 as 4.1.3",
    "npm-asset/bootstrap": "~4.1.3"
},

This will install bootstrap 3.3.7 from bower and bootstrap 4.1.3 from npm. You need to update path for bootstrap4 assets bundles:
'components' => [
    'assetManager' => [
        'bundles' => [
            'yii\bootstrap4\BootstrapAsset' => [
                'sourcePath' => '@npm/bootstrap/dist'
            ],
            'yii\bootstrap4\BootstrapPluginAsset' => [
                'sourcePath' => '@npm/bootstrap/dist'
            ]
        ]
    ]
]

Note that yii2-bootstrap4 is not ready to use and does not even have a alpha/beta release, so expect many other problems.

A: A lot of solution on how to use Bootstrap 4 in Yii2. Even the Yii2 team created an extension for that. But since, I don't like too much configuration. This is what I did. In AppAsset.php, remove the yii\bootstrap\BootstrapAsset with custom your own. I'll recommend, you stick with the original filename and classname.
// AppAsset.php
public $depends = [
    'yii\web\YiiAsset',
    //'yii\bootstrap\BootstrapAsset',  // Remove this
    'app\assets\BootstrapAsset',       // Add this
];

Then, I created a BootstrapAsset.php file in assets folder. Copy the code from yii\bootstrap\BootstrapAsset. Then changed some part of the code. No NPM, No Bower.
namespace app\assets;

use yii\web\AssetBundle;

class BootstrapAsset extends AssetBundle
{
  public $basePath = '@webroot';
  public $baseUrl = '@web';
  public $css = [
    'vendor/bootstrap/css/bootstrap.min.css'
  ];
  public $js = [
    'vendor/bootstrap/js/bootstrap.min.js',
    'vendor/popper.js/umd/popper.min.js'
  ];
}


Q: Azure Traffic Manager Load Balance Options I tried to dig on MSDN but could not get concrete statement for which is the best load balancing method.
could someone please share some light on which of the below are best option for given scenario:

*

*Performance

*Failover

*Round Robin.

Scenario:
x Web Roleshosted on Large VM on single data center.
Requirement:
must be 100% up 24x7.
Thank you.

A: First: Do you really want to offer a 100% uptime SLA for your customers, when Azure itself doesn't offer 100% in its SLA's?
That said: Traffic Manager only load-balances your compute, not your storage. So if you're trying to increase uptime by having a set of backup compute nodes running in another data center, you need to think about data access speed and cost:

*

*With round robin, you'll now have distributed traffic across multiple data centers, guaranteed, and constantly. And if your data is in a single data center (which is a good idea to have data in a single System of Record, unless you have replication logic all taken care of), some of your users are going to see increased latency as the nodes separated from your data are going to be requesting data across many miles (potentially between continents). Plus, data egress has a $$$ cost to it.

*With performance, your users are directed toward the data center which offers them the lowest latency. Again, this now means traffic across multiple data centers, with the same issues as round robin.

*With failover, you now have all traffic going to one data center, with another designated as your failover data center (so it's for High Availability). In the event you have an outage in the primary data center, you'd now have a failover data center to rely on. This may help justify the added latency and cost, as you'd only experience this latency+cost when your primary app location becomes unavailable for some reason.

So: If you're going for the high availability route, to help approach the 100% availability mark, I'm guessing you'd be best off with the failover model.

A: Traffic manager comes into picture only when your application is deployed across multiple cloud services within same data center or in different data centers. If your application is hosted in a single cloud service (with multiple instances of course) , then the instances are load balanced using Round Robin pattern. This is the default load balancing pattern and comes to you without any extra charge.
You can read more about traffic manager here: https://azure.microsoft.com/en-us/documentation/articles/traffic-manager-overview/

A: As per my guess there can not be comparison which is best load balancing method of Azure Traffic manager. All of them have unique advantages and vary depending on the requirement of application. Most common scenario is to use performance load balancing option with azure traffic manager. But as Gaurav said, you will have to have your cloud service application hosted on more than one cloud services. If you wish to implement performance load balancing then here is the link to get you started - http://sanganakauthority.blogspot.com/2014/06/performance-load-balancing-using-azure.html


Q: How to draw a vertical line at specified x value on QHorizontalBarSeries/QChart? I've followed this example to create a horizontal bar chart. I'd like to draw a static vertical line at a specific value along the x-axis. I've tried adding a QLineSeries to the QChart, but nothing is showing up. I'm doing this in Python, but C++ works, too.

A: A possible solution is to override the drawForeground() method to paint the vertical line, to calculate the positions you must use the mapToPosition() method:
import sys

from PyQt5.QtCore import Qt, QPointF
from PyQt5.QtGui import QColor, QPainter, QPen
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtChart import (
    QBarCategoryAxis,
    QBarSet,
    QChart,
    QHorizontalBarSeries,
    QChartView,
    QValueAxis,
)

class ChartView(QChartView):
    _x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        self._x = x
        self.update()

    def drawForeground(self, painter, rect):
        if self.x is None:
            return
        painter.save()

        pen = QPen(QColor("indigo"))
        pen.setWidth(3)
        painter.setPen(pen)

        p = self.chart().mapToPosition(QPointF(self.x, 0))

        r = self.chart().plotArea()

        p1 = QPointF(p.x(), r.top())
        p2 = QPointF(p.x(), r.bottom())
        painter.drawLine(p1, p2)

        painter.restore()

def main():
    app = QApplication(sys.argv)

    set0 = QBarSet("Jane")
    set1 = QBarSet("John")
    set2 = QBarSet("Axel")
    set3 = QBarSet("Mary")
    set4 = QBarSet("Samantha")

    set0 << 1 << 2 << 3 << 4 << 5 << 6
    set1 << 5 << 0 << 0 << 4 << 0 << 7
    set2 << 3 << 5 << 8 << 13 << 8 << 5
    set3 << 5 << 6 << 7 << 3 << 4 << 5
    set4 << 9 << 7 << 5 << 3 << 1 << 2

    series = QHorizontalBarSeries()
    series.append(set0)
    series.append(set1)
    series.append(set2)
    series.append(set3)
    series.append(set4)

    chart = QChart()
    chart.addSeries(series)
    chart.setTitle("Simple horizontal barchart example")
    chart.setAnimationOptions(QChart.SeriesAnimations)

    categories = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    axisY = QBarCategoryAxis()
    axisY.append(categories)
    chart.addAxis(axisY, Qt.AlignLeft)
    series.attachAxis(axisY)
    axisX = QValueAxis()
    chart.addAxis(axisX, Qt.AlignBottom)
    series.attachAxis(axisX)
    axisX.applyNiceNumbers()

    chart.legend().setVisible(True)
    chart.legend().setAlignment(Qt.AlignBottom)

    chartView = ChartView(chart)
    chartView.setRenderHint(QPainter.Antialiasing)

    chartView.x = 11.5

    window = QMainWindow()
    window.setCentralWidget(chartView)
    window.resize(420, 300)
    window.show()

    app.exec()

if __name__ == "__main__":
    main()


Q: How to pass cv::mat objects from a python module to a c++ function and give back returned object which is type cv::mat? I try to start a project with Django which a part of that is about showing some images.
As probably you know, c++ is so faster than python. so I wrote a c++ function which receives two Mat type input and do some pre processing on them and finally return a cv::mat variable as it's output.
I want to call this function inside my python module and send from my python code, two images as input argument and show the result of c++ function in my django project.
I tried to call my c++ function with ctypes.CDLL, ctypes work with simple functions but for this c++ code gives a memory error.
this is my c++ function:
extern "C" Mat watermark2(Mat source_img, Mat logo)
{
        // Simple watermark

        double alpha = 0.5;

        int width = logo.size().width;
        int height = logo.size().height;
        int x_pos = rand() % (source_img.size().width - width);
        int y_pos = rand() % (source_img.size().height - height);

        cv::Rect pos = cv::Rect(x_pos, y_pos, width, height);
        addWeighted(source_img(pos), alpha, logo, 1 - alpha, 0.0, source_img(pos));

        return source_img;
}

as you see, this is a simple function and don't use a lot of memory. I test it for some very small pictures and I saw the same error.
I search a lot in net and found some instructions about Wrapping C/C++ for Python. but I don't sure that it can help me.
because I'm new in Django, can anybody help me how to negotiate from my python code which I have two images with my c++ function to some manipulate on images and save the returned output in my Django?

A: Maybe consider using the Boost-Python library for interfacing between Python and C++.


Q: sequence genration I am having difficulty -normalizing sequence $1,x,x^3$ in $L^2([-1,0]\cup[1,2],dx)$
So I begin by choosing basis $1,x,x^2...$ and i need to use Gram-Schmidt? or how should i approach this?
I have attempted to integrate x from -1 to 0 and add integral from 1 to 2, but I don't think I understand the problem

A: Let $f_n = x^n$ for $n=0,1,2,\ldots$. Define $u_1=f_1$ and $$u_{n+1} = f_{n+1} - \sum_{k=0}^n \frac{\langle f_{n+1},f_k\rangle}{\langle f_k,f_k\rangle}f_k,$$ where
$$\langle f,g\rangle = \int_{[-1,0]\cup[1,2]}f(x)g(x)\ \mathsf dx. $$
Then $\{u_n\}$ is an orthogonal sequence ($\langle u_i,u_j\rangle=0$ for $i\ne j$) with the span of $\{u_0, \ldots, u_n\}$ equal to the span of $\{f_0,\ldots, f_n\}$. To normalize, set
$$e_n = \frac{u_n}{\|f_n\|_2} $$
where $$\|f\|_2 = \int_{[-1,0]\cup[1,2]}f(x)^2\ \mathsf dx. $$
For example,
$$u_2 = x - \frac{\int_{-1}^0 x\ \mathsf dx + \int_{1}^2 x\ \mathsf dx}{\int_{-1}^0  \mathsf dx + \int_{-1}^0 \mathsf dx}\cdot 1 = x-\frac12, $$
and
$$\|u_2\|_2 = \int_{-1}^0 \left(x-\frac12\right)^2\ \mathsf dx + \int_{1}^2 \left(x-\frac12\right)^2\ \mathsf dx = \frac{13}6, $$
so
$$e_2 = \frac6{13}\left(x-\frac12\right). $$


Q: java.lang.SecurityException: Requires VIBRATE permission on Jelly Bean 4.2 Since yesterday I have an issue on Android 4.2 when I receive push notifications it requires the permission even if i don't set it to vibrate
Notification notification = new Notification(icon, notificationItem.message, when);
notification.setLatestEventInfo(context, "App", notificationItem.message,
            PendingIntent.getActivity(context, 0, intent, 0));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;

NotificationManager nm =
            (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(notificationItem.notificationID, notification);

the exception is raised by nm.notify
I have this issue in two different apps and i never modify the code

A: I got the same Exception in Jelly Bean 4.1.2, then following changes I made to resolve this
1.added permission in manifest file.
 <uses-permission
 android:name="android.permission.VIBRATE"></uses-permission>

2.Notification Composing covered by Try-Catch
 try
    {
        mNotificationManager = (NotificationManager)
        this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                        this)
                .setSmallIcon(R.drawable.ic_notif_alert)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg)
                .setStyle(bigTextStyle)
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
            mBuilder.setAutoCancel(true);
            mBuilder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            Log.d(TAG, "---- Notification Composed ----");
    }
    catch(SecurityException se)
    {
        se.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

A: Since this bug only occurs on Android 4.2 and 4.3 you might use this as a workaround (i.e. include the maxSdkVersion):
<uses-permission android:name="android.permission.VIBRATE" android:maxSdkVersion="18"/>

Note: the maxSdkVersion attribute was only added in API level 19, which in this case is luckily exactly the minimum we want! In theory we could put any value <= 18 to get the same effect, but that would be nasty.

A: This was a bug in Android 4.2 due to a change in the notification vibration policy; the permission bug was fixed by this change in 4.2.1.


Q: How to select specific div using BeautifulSoup when multiple divs have the same class name no id tag? Please help I don't know how to select specific div using BeautifulSoup when multiple divs have the same class name no id tag.
Web page that I am trying to scrape: https://www.helpmefind.com/rose/l.php?l=2.65689.
I want to select contents of specific divs independently and then pass to a csv file. Got stuck since find_all returns multiple divs and I don't know how to restrict further.
rose_div = rose.find_all("div", class_="hdg")

Returns:
[
HMF Ratings:
,
Origin:
,
Class:
,
Bloom:
,
Parentage:
,
Notes:
,

]

I want to select individually below divs:

Origin:

Class:

Bloom:

Parentage:

A: You can use CSS selector div.hdg:contains("Origin:") to select
 with class="hdg" that contains word "Origing:". To get next element with class grp, you can add + .grp.
For example:
import requests
from bs4 import BeautifulSoup

url = 'https://www.helpmefind.com/rose/l.php?l=2.65689'
soup = BeautifulSoup( requests.get(url).content, 'html.parser' )

origin = soup.select_one('div.hdg:contains("Origin:") + .grp').text
class_ = soup.select_one('div.hdg:contains("Class:") + .grp').text
bloom = soup.select_one('div.hdg:contains("Bloom:") + .grp').text
parentage = soup.select_one('div.hdg:contains("Parentage:") + .grp').text

print(origin)
print(class_)
print(bloom)
print(parentage)

Prints:
Bred by Arai (Japan, before 2009).
Floribunda.
Light pink and white, yellow stamens.  Single (4-8 petals), cluster-flowered bloom form.  Blooms in flushes throughout the season.
If you know the parentage of this rose, or other details, please contact us.


Q: Pass 3D shape through hole in scaled copy of itself The way I understand it, the problem of Prince Rupert's cube essentially requires one to look for the projection of a cube onto $\mathbb{R}^2$ such that the largest possible square (a square being the smallest projection of a cube onto $\mathbb{R}^2$) can be inscribed inside it. That led me to the following problem: for an arbitrary connected three-dimensional geometrical object $V$, by what scale factor $s$ would $V$ have to be uniformly scaled, such that the scaled object could fit through a hole that could be cut in $V$ without making it disconnected?
Obviously, if $V$ is a cube then any $s<\frac{3\sqrt{2}}{4}$ will do and if $V$ is a sphere then any $s<1$, but I was wondering if there is some nice way to do this sort of problem for more general objects. I certainly can't see a nice way. At first I thought all that would be required would be to find which orthogonal projection of the shape onto $\mathbb{R}^2$ had maximal area, but that would not work if $V$ is not convex (e.g. a dumbbell-like shape is an extreme example, which also requires $s$ quite small) since it might not preserve connectedness, and also maximizing the area might not work, since we want to inscribe a shape within the object. Perhaps it is not even sufficient to find projections onto $\mathbb{R}^2$ since the path taken through $V$ might not be straight (e.g. passing a banana along a curved path through a hollowed-out banana). It seems like the cut itself will be hard to describe since it will have to be some surface intersecting $V$ that is given (and the scaled object must be passed from end to end 'within' this surface), and I cannot see any nice general way of working with such a surface.
My questions are: is there some clever way of working around this problem to even find a general expression for at the very least the surface required to cut $V$ such that the largest possible scaled version of $V$ can pass through it, or even an expression for $s$, and are there simpler objects other than cube and sphere (e.g. a torus, a pyramid) for which $s$ is known? More specifically, is there any way of finding for which sort of objects we can have $s>1$ (i.e. pass $V$ through a smaller version of $V$) and for which must we have $s<1$? Can $s$ be arbitrarily large for some shapes, and if not what is the largest possible value of $s$ for any shape (I assume there are shapes that require arbitrarily small $s$)? Are there shapes $V$ for which the range of allowed $s$ is discontinuous (perhaps the case for the banana example with curved path)?


Q: How can I create a camera including guidelines for the user to snap the picture between? I'm working with OCR using tess-two as my scanner and it works great when taking the photo, and using https://github.com/IsseiAoki/SimpleCropView to crop the image for the right numbers to be read from tess-two.
What I'd like to do is to take the second step of cropping the image out of the process, making it quicker for the user. I'm just confused on how to add my own crop rectangle area to allow the user to take a picture in.
Even something as simple as "[                  ]" with the rest of the camera surface view blacked out or dimmed, guiding the user to take the photo of the numbers in between the brackets.
Are there any good tutorials out there involving this? I've searched, but with no success. Or if anyone can point me in the right direction on how to start this that would be a big help! Thanks in advance!


Q: maximum plot points in R? I have come across a number of situations where I want to plot more points than I really ought to be -- the main holdup is that when I share my plots with people or embed them in papers, they occupy too much space.  It's very straightforward to randomly sample rows in a dataframe.
if I want a truly random sample for a point plot, it's easy to say:
ggplot(x,y,data=myDf[sample(1:nrow(myDf),1000),])

However, I was wondering if there were more effective (ideally canned) ways to specify the number of plot points such that your actual data is accurately reflected in the plot.  So here is an example.
Suppose I am plotting something like the CCDF of a heavy tailed distribution, e.g.
ccdf <- function(myList,density=FALSE)
{
  # generates the CCDF of a list or vector
  freqs = table(myList)
  X = rev(as.numeric(names(freqs)))
  Y =cumsum(rev(as.list(freqs)));
  data.frame(x=X,count=Y)
}
qplot(x,count,data=ccdf(rlnorm(10000,3,2.4)),log='xy')

This will produce a plot where the x & y axis become increasingly dense. Here it would be ideal to have fewer samples plotted for large x or y values.
Does anybody have any tips or suggestions for dealing with similar issues?
Thanks,
-e

A: I tend to use png files rather than vector based graphics such as pdf or eps for this situation. The files are much smaller, although you lose resolution.
If it's a more conventional scatterplot, then using semi-transparent colours also helps, as well as solving the over-plotting problem. For example,
x <- rnorm(10000); y <- rnorm(10000)
qplot(x, y, colour=I(alpha("blue",1/25)))

A: Beyond Rob's suggestions, one plot function I like as it does the 'thinning' for you is hexbin; an example is at the R Graph Gallery.

A: Here is one possible solution for downsampling plot with respect to the x-axis, if it is log transformed.  It log transforms the x-axis, rounds that quantity, and picks the median x value in that bin:
downsampled_qplot <- function(x,y,data,rounding=0, ...) {
  # assumes we are doing log=xy or log=x
  group = factor(round(log(data$x),rounding))
  d <- do.call(rbind, by(data, group,
    function(X) X[order(X$x)[floor(length(X)/2)],]))
  qplot(x,count,data=d, ...)
}

Using the definition of ccdf() from above, we can then compare the original plot of the CCDF of the distribution with the downsampled version:
myccdf=ccdf(rlnorm(10000,3,2.4))

qplot(x,count,data=myccdf,log='xy',main='original')

downsampled_qplot(x,count,data=myccdf,log='xy',rounding=1,main='rounding = 1')

downsampled_qplot(x,count,data=myccdf,log='xy',rounding=0,main='rounding = 0')

In PDF format, the original plot takes up 640K, and the downsampled versions occupy 20K and 8K, respectively.

A: I'd either make image files (png or jpeg devices) as Rob already mentioned, or I'd make a 2D histogram. An alternative to the 2D histogram is a smoothed scatterplot, it makes a similar graphic but has a more smooth cutoff from dense to sparse regions of space.
If you've never seen addictedtor before, it's worth a look. It has some very nice graphics generated in R with images and sample code.
Here's the sample code from the addictedtor site:
2-d histogram:
require(gplots)

# example data, bivariate normal, no correlation
x <- rnorm(2000, sd=4)
y <- rnorm(2000, sd=1)

# separate scales for each axis, this looks circular
hist2d(x,y, nbins=50, col = c("white",heat.colors(16)))
rug(x,side=1)
rug(y,side=2)
box()

smoothscatter:
library("geneplotter")  ## from BioConductor
require("RColorBrewer") ## from CRAN

x1  <- matrix(rnorm(1e4), ncol=2)
x2  <- matrix(rnorm(1e4, mean=3, sd=1.5), ncol=2)
x   <- rbind(x1,x2)

layout(matrix(1:4, ncol=2, byrow=TRUE))
op <- par(mar=rep(2,4))
smoothScatter(x, nrpoints=0)
smoothScatter(x)
smoothScatter(x, nrpoints=Inf,
              colramp=colorRampPalette(brewer.pal(9,"YlOrRd")),
              bandwidth=40)
colors  <- densCols(x)
plot(x, col=colors, pch=20)

par(op)


Q: How to solve a linear algebra problem of finding a linear combination as a problem in matrix algebra of solving a system of linear equations? Linear Algebra problem:
Write the vector $w = \left[ \matrix{ 1 & -2 & 5 \cr} \right]$ as a linear combination of the vectors
$$
u_1 = (1, 1, 1), \ u_2 = (1, 2, 3), \ u_3 = (2, -1, 1)
$$
Expressing $w  = x u_1 + y u_2 + z u_3$ and solving for $x, y, z$, we obtain
$$
x = -6,  y = 3, z = 2.
$$
How can the same problem be solved using matrix algebra as a problem of solving linear equations?

A: We define the column vectors
$$
v_1 = u_1' = \left[ \begin{array}{c}
      1 \\
      1 \\
1 \\
\end{array} \right], \ \
v_2 = u_2' = \left[ \begin{array}{c}
      1 \\
      2 \\
3 \\
\end{array} \right], \ \
v_3 = u_3' = \left[ \begin{array}{c}
      2 \\
      -1 \\
1 \\
\end{array} \right]
$$
We form the matrix
$$
A = \left[ \matrix{v_1 & v_2 & v_3 \cr} \right] =
\left[ \begin{array}{ccc}
 1 & 1 & 2 \\[1mm]
 1 & 2 & -1 \\[1mm]
 1 & 3 & 1 \\[1mm]
\end{array} \right].
$$
We define
$$
b = w' = \left[ \begin{array}{c}
      1 \\
-2 \\
5 \\
\end{array} \right]
$$
Solving the linear system of equations
$$
A \mathbf{x} = b,
$$
we obtain the unique solution
$$
x_1 = -6, \ \ x_2 = 3, \ \ x_3 = 2
$$
Thus, the given problem in linear algebra can be solved by posing it as a problem in matrix algebra of solving a system of linear equations using the standard methods of linear system solvers. $\ \ \ \blacksquare$


Q: How to force g++ to create C symbol name I have a function called init in a cpp file, but when I compile it, g++ creates in the object file a symbol named _Z4initv, so when I link after with ld with the option -e init, obviously ld doesn't recognize the symbol init. Is there a way to create symbols name in C style with g++ ?

A: If you have a definition like e.g.
void init() { ... /* some code */ ... }

Then to inhibit name mangling you need to declare it as extern "C":
extern "C" void init() { ... /* some code */ ... }

If you have a declaration in a header file that you want to include in a C source file you need to check if you're including the header file in a C or C++ source file, using the __cplusplus macro:
#ifdef __cplusplus
extern "C"
#endif
void init(void);

Note that the function in the header file has to be declared with void in the argument list, if it doesn't take any arguments. That's because the declaration void init() means something else in C.


Q: Angularjs : failing to generate c3 directive based charts dynamically I am trying to create c3 charts dynamically using c3 chart directives. C3 chart directive is working fine. However dynamic chart creation upon button click is not working. Can any one suggest where I am going wrong?
Please find my plunker at http://plnkr.co/edit/wWJx3zU3Sm1cN9ZCtvoh?p=preview
I am compiling my c3 directive as shown below:
 $scope[chartName] = {

    data: {
        x: 'x',
        columns: [["x","2014-02-01","2014-03-01","2014-04-01","2014-05-01","2014-06-01","2014-07-01","2014-08-01","2014-09-01"],["LH",".00",".00",".00",".00",".00",".00",".00","31.50"],["DW","42.57",".00",".00","321.14","1070.06","6501.42","144337.85","329159.85"],["PS",".00","82.22","-2.87","179.60","835.85","6925.52","479631.24","1386751.16"]],
        type: 'line'
    },
    axis: {
        x: {
            type: "timeseries",
            tick: {
                format: "%d-%m-%Y"
            }
        }
    },
    subchart: {
        show: true
    }

};

   var  template = '

' + dashletterName + '
 <c3-simple id = "' + chartName + '" config="' + chartName + '"></c3-simple>
';
     angular.element(document.body).append($compile(template)($scope));

A: I downloaded you Plnkr and tried it in browser. Here is error from Chrome console:
ReferenceError: $compile is not defined

This means that AngularJS can't use $compile, because it is not injected into your controller. This should be done in controllers.js like this:
// I have added $compile
controller('DemoCtrl', ['$scope', 'c3SimpleService', '$compile', function ($scope, c3SimpleService, $compile)
{
  // rest of the controller code
}

I also fixed your Plnkr. Hope it helps :)


Q: How do nameservers "failover"? How do nameservers do failover? What decides the order in which nameservers are queried when the primary nameserver is not reachable?
To illustrate, here's part of my zonefile:
$TTL 3m;
site.com.       IN      SOA     ns1.sitese.com. admin.site.com. (
                   2007010403           ; Serial
                         1800           ; Refresh [1h=3600] 1800=30m
                          600           ; Retry   [10m]
                        86400           ; Expire  [2weeks] 86400=1day
                          180 )         ; Negative Cache TTL [1h]
;
site.com.      IN     NS      ns1.sitese.com.
site.com.      IN     NS      ns2.sitese.com.
site.com.      IN     NS      ns3.sitese.com.
ns1.sitese.com.  IN     A       199.168.35.23
ns2.sitese.com.  IN     A       38.124.113.106
ns3.sitese.com.  IN     A       38.128.98.213

Obviously the primary nameserver is ns1.sitese.com as it is listed in the SOA record. But which one becomes the secondary nameserver if the primary is unreachable? Is it ns2, or ns3? What decides the order in which secondary nameservers are queried? Is it the order in which they appear in the zonefile? Is it something else?

A: AFAIK the order in which NSs are queried is up to the client. Even if your primary is up, a client can elect to query the secondary, if it feels so inclined.
From a client standpoint, all RRs returned by either the secondary or primary NSs are equivalent as all of them are marked as authoritative.

A:
How do nameservers do failover?

They do not.

What decides the order in which nameservers are queried when the primary nameserver is not
  reachable?

Downstream servers just select one. If that does not answer another one. I am not sure there is a definitive spec how those are selected - so at the end, that is an implementation detail.


Q: SqlDataReader.GetString and sqlnullvalueexception I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception.
What is the best coding practice for this?
if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n);

Any better way of coding?

A: If you don't want to repeat this a lot, just create a helper function, like this:
public static class DataReaderExtensions
{
    public static string GetStringOrNull(this IDataReader reader, int ordinal)
    {
        return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
    }

    public static string GetStringOrNull(this IDataReader reader, string columnName)
    {
        return reader.GetStringOrNull(reader.GetOrdinal(columnName));
    }
}

Which you can call like this:
value = reader.GetStringOrNull(n);

A: That really is the best way to go about it if you wish to avoid any exceptions.  You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method.  If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.
But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.

A: This worked for me:
value = reader.GetValue(n).ToString();

A: The code you posted is fine. You could also do something like that :
value = r[n] as string;

If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.


Q: Selenium Chrome Driver opens a different page than regular Chrome Browser I'm trying to pull some information from this URL and ones like it: "https://www.rockymountainatvmc.com/tires-and-wheels/tusk-impact-complete-wheel-rear-p?s=1033997&v=1216"
My goal is to get the MSRP and other info for a specific part. To do this, I'm using python to run a selenium chrome webdriver that opens several of these URLs. The problem is the links aren't opening with the same information that I would get in my regular Chrome browser.
The link is supposed to contain all the information to "select a vehicle" and thus a specific part. When I open this in my regular chrome browser, everything works fine. When I open this using the automated Chrome page, it fails to select a vehicle and shows a general part page.
I can't figure out what the difference might be between these two browsers that would cause this. My regular chrome browser and the chromedriver are both version 81.0.4044.113. I've tried going to whatismybrowser.com and all settings are identical. Another interesting thing is opening this in internet explorer gives me the same result as the automated chrome browser. Help!
regular chrome browser
automated chrome browser

A: The Regular chrome browser is fetching the details of your bike(Something -- yamaha 125). It could be from past cookies or cache.
However, once you are opening it with Automation, a clean session s opened.
Try cleaning your cookies and cache on the browser(regular) and then try, both of them should appear same.
Or you can use options in chrome to select the profile your regular chrome browser is using. See https://startingwithseleniumwebdriver.blogspot.com/2015/07/working-with-chrome-profile-with.html.
Hope it Helps!


Q: Envoy proxy forward to https endpoint: facing protocol error I'm trying to do this one: call public.com/api/v1/{proxy} to envoy proxy behind an ingress proxy. Envoy proxy will forward traffic to https private endpoint inside my VPC with diffrent path: https://private.com/internal/{proxy}.
But I'm still facing the issue

upstream reset: reset reason: connection termination, transport failure reason:

I even tried with public https endpoint but it's still the same.
Below is my configuration:
admin:
  access_log_path: /tmp/admin_access.log
  address:
    socket_address:
      protocol: TCP
      address: 0.0.0.0
      port_value: 9901
static_resources:
  listeners:
    - name: listener
      address:
        socket_address:
          address: 0.0.0.0
          port_value: 10000
      filter_chains:
        - filters:
          - name: envoy.filters.network.http_connection_manager
            typed_config:
              '@type': "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
              stat_prefix: http_proxy
              access_log:
                - name: envoy.access_loggers.stdout
                  typed_config:
                    "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog
              route_config:
                name: all
                virtual_hosts:
                  - name: local_service
                    domains:
                      - '*'
                    routes:
                      - match: { prefix: "/api/v1"}
                        route:
                          prefix_rewrite: "/internal/"
                          cluster: allbackend_cluster
              http_filters:
                  - name: envoy.filters.http.router
  clusters:
    - name: allbackend_cluster
      connect_timeout: 1s
      type: strict_dns
      lb_policy: round_robin
      load_assignment:
        cluster_name: allbackend_cluster
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: private.com
                    port_value: 443
      transport_socket:
        name: envoy.transport_sockets.tls
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
          common_tls_context:
            validation_context:
              trusted_ca: {filename: /etc/ssl/certs/ca-certificates.crt}

A: I believe you need to add certificates information for envoy
tls_context:
          common_tls_context:
            tls_certificates:
              - certificate_chain:
                  filename: "/etc/ssl/certs/https.crt"
                private_key:
                  filename: "/etc/ssl/certs/key.pem"

And also add trust the certificate used by cluster.
tls_context:
      common_tls_context:
          validation_context:
            trusted_ca:
              filename: "/etc/ssl/certs/cluster.crt"


Q: Passing Value in ASP.NET Pages I am developing a web application using asp.net and C#. I have a question
Is there any way for passing values in asp pages without using QueryString or Session values or Cookies or previous page?

A: You may see: ASP.NET State Management Overview
Profile Properties

You can use: ASP.NET provides a feature called profile properties,
  which allows you to store user-specific data. This feature is similar
  to session state, except that the profile data is not lost when a
  user's session expires. The profile-properties feature uses an ASP.NET
  profile, which is stored in a persistent format and associated with an
  individual user. The ASP.NET profile allows you to easily manage user
  information without requiring you to create and maintain your own
  database. In addition, the profile makes the user information
  available using a strongly typed API that you can access from anywhere
  in your application. You can store objects of any type in the profile.
  The ASP.NET profile feature provides a generic storage system that
  allows you to define and maintain almost any kind of data while still
  making the data available in a type-safe manner.

A: You can use asp.net cache or  save data from one page in to some persistent medium and other page would read from that medium could be database or xml etc.

A: Beside your requirements(not using QueryString or Session values or Cookies) yes you can use public property like
public String YourProperty
{
    get
    {
        return "Return What you want to pass";
    }
}

Check this MSDN article for full code


Q: Different unit for Kubernetes resource memory on pods My question is related to Kubernetes and the units of the metrics used for the HPA (autoscaling).
When I run the command
kubectl describe hpa my-autoscaler
I get (a part of more information) this:
...
Metrics:                                               ( current / target )
  resource memory on pods:                             318067507200m / 1000Mi
  resource cpu on pods  (as a percentage of request):  1% (1m) / 80%
...

In this example, when you can see the metrics for the resource memory on pods, you can see that the unit for the current value is m, which is "millis" (as is described in the official documentation), but the unit used for the target value is Mi, which is "Mebis"
Is there any problem with the usage of different units?
Thanks!

A: No, they are just different multipliers. The actual code is using a raw number of bytes under the hood.


Q: Haskell Attoparsec infinite loop The code is based on Haskell Attoparsec, and when I use parseOnly pString "v", it gives me the right answer as Right (DontNeedTrim, "v").
While when I use the instruction parseOnly (many' pString) "v", it seems drops into the infinite loop and finally failed with the overflowed stack.
data Signal = NeedTrim
              | DontNeedTrim
              deriving (Show)

pString :: Parser (Signal, [Char])
pString = ((char '\"' *> many' pChar' <* char '\"') >>= \s -> return (NeedTrim, s))
          <|> (many' pChar >>= \s -> return (DontNeedTrim, s))

pChar :: Parser Char
pChar = char '\\' *> (pEscape <|> spaces *> endOfLine *> pChar)
        <|> satisfy (`C.notElem` "\"\\\n#;")

pChar' :: Parser Char
pChar' = char '\\' *> pEscape
         <|> satisfy (`C.notElem` "\\\"")

pEscape :: Parser Char
pEscape = choice (zipWith decode "bnt\\\"" "\b\n\t\\\"")
  where decode c r = r <$ char c

A: The second alternative in pString accepts the empty string: many' pChar >>= \s -> return (...). Thus many' pString keeps consuming the empty string ad infinitum.


Q: Jquery select element outside of li by ID im looking to select the follow element by id toggleThisDiv. The markup looks like:

       <asp:HyperLink ID="lnkCategory" runat="server">
       <asp:Literal ID="litCategory" runat="server" Visible="true" />
       <asp:Image ID="imgMan" runat="server" Visible="false" /></asp:HyperLink>
       <asp:Button ID="btnToggleDiv" runat="server" Text="+" Visible="false" />

And the jQuery:
$(document).ready(function () {
        $('[id*="btnToggleDiv"]').click(function () {
            $(this).next().slideToggle(100);
            return false;
        });
    });

This works when the button is outside of the listitem but this is all inside a repeater and if i leave it like that, all of the buttons created will be next to each other instead of within their associated list item.
I'm looking for something within jQuery that would allow me to select the next div (toggleThisDiv), is this possible?
Thankyou

A: Use unique ID's, or classes if generating elements where the same identifier will be used.
To target an element outside the current parent of the clicked element you can find the closest parent that matches a selector, and then the next element etc.
$(document).ready(function () {
   $('[class*="btnToggleDiv"]').on('click', function () {
       $(this).closest('li').next('div').slideToggle(100);
       return false;
   });
});

A: Use something like this to select the toggleThisDiv
$('#<%= toggleThisDiv.ClientID %>')

When the website is generated from your asp code, your IDs will be different than what you have given them.  This is because they are run at server.  Anytime that you are using runat server, use the format above to find the generated ID.
You should use a class inside to repeater though.


Q: create a mp3 player embedded in a facebook post The Serial podcast has this cool feature where they share their webpage on their facebook page and Facebook lets the audio be played within Facebook.  See this image:

I've created a blog post with all of the proper meta tags to match the relevant tags expected by facebook:
music:preview_url:url, the og:type is music.song, etc.
But I can't get a mp3 player to appear.
When I compare the open graph meta data in the Facebook debugger from the Serial webpage to my own webpage, the tags match up fine.  Yes, mine has a 'locale' array but that can't be the issue.
I'm thinking they must have some type of Facebook app?  Or I don't know what.  I've never built a Facebook app so if you think that is how they are doing it, where would I start looking?
This is my non-working open graph output:

This is the one from the Serial podcast.  You can see in the Share Dialog the player buttons for the MP3.  How are they getting that in there?  I would have thought just be me using the correct meta tags, Facebook would put player buttons on top of my mp3 and create the player for me.


Q: "The server could not update. Check your API credentials and internet connection and try again." - Google Sheets API, service account error I'm currently building a website/platform following using this: https://forensic-architecture.org/investigation/timemap-for-cartographic-platforms. It works by reading a Google sheet I have, and I need to press an 'update' button in order for the sheets to be read. However, rather than it updating, I get the following: "The server could not update. Check your API credentials and internet connection and try again."
I'm unsure what's going wrong, as I've followed all the steps as needed for the Google Sheets api, as outlined in the link above. I also previously had this running with a different API key locally (which I since deleted). Now, I can't even get it to work locally, though previously there was no issue. The service account has permission on the Sheet itself. I've also tried setting the sheet to publicly available online with no change. I've checked the service account and key are correct about a million times, and have created a new project with whole new key etc so see if the issue was reproduced. I also tried making a new sheet (and granting a new key etc permission) but still get the same error.
The metrics panel for Sheets API tells me "google.apps.sheets.v4.SpreadsheetsService.GetSpreadsheet" has an error rate of 100%. I'm well below my quota, and have billing enabled (two other reasons I keep seeing on Stack as possible reasons for similar errors), so I'm not sure that's the issue.
Below is also what I see in terminal when trying to run locally (rn switched to trying to fix this locally as this is the last step for me in making the platform live, and I'm wary of doing anything on my remote server that could end up causing problems elsewhere):
Enabling CORS in development...
Connected to {{My Google Sheet name}} (Google Google Sheet with ID {{Sheet ID}}).
===================
grant access to: {{my service account email}}
===================
Started on port 4040

GET /api/blueprints 200 46.784 ms - 1677

GET /api/update 404 452.498 ms - 115

The platform reads my service key credentials through my .env (which it seems to be doing fine going from what I see in terminal), and uses a config file to find the Google Sheets id (which again seems fine from above).
Please let me know if there's any extra info needed here; I'm pretty new to all of this, and so not necessarily aware when I'm relaying issues what is vital info and what is not.


Q: The model item passed into the dictionary is of type ' ', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable? After executing the application I get the "The model item passed into the dictionary is of type 'ClubStarterKit.Web.ViewData.Forum.NewMessageListViewData', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ClubStarterKit.Web.ViewData.Forum.NewMessageListViewData]'.
In view I have the codes below

    <%if ( User.Identity.IsAuthenticated) { %>

          <%using (Ajax.AsyncForm(Website.Shared.Views.DisplayTemplates.NewForumMessageList, new AsyncFormOptions(AsyncFormType.TargetUpdate, FormMethod.Post, "newMessages", targetUpdate: "messages", elementBlockId: "message-add-block", postRequestFunction: "afterMessageUpdate")))
          {%>

Add New Message Final Test

                <%: Html.Wysiwyg("message") %>

               <%-- <input type="hidden" value="<%: Model.ThreadSlug %>" name="thread" />--%>
                <input type="hidden" value="-1" name="messageId" />
                <input type="submit" value="Add Message4 final" />
          <%}%>

          New message4 final

          <%}%>

in the controller the code is
 public virtual ActionResult Index()
    {
        ViewData.Title("New Message");
        return View(Views.List, new ClubStarterKit.Web.Infrastructure.Forum.NewMessageListAction().Execute());
    }

and in screenshot below it is :

The model item passed into the dictionary is of type 'Myapplication.Web.ViewData.application.NewMessageListViewData', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
Please advise which area of code is the issue

A: You are passing the View a single NewMessageListViewData, but it has been strongly typed to accept only objects implementing IEnumerable<T> where T is NewMessageListViewData. For example, a List<NewMessageListViewData> would work.
As mentioned in the comments, I would start by looking at the return type of ClubStarterKit.Web.Infrastructure.Forum.NewMessageListAction.Execute(), or, if you only intend to display a single instance of NewMessageListViewData in this View, you need to set the model in the View to reflect that.


Q: Confirm dialog in Cordova I'm writing an app in javascript and html with phonegap/cordova.
I have this code in javascript:
$('#diario_delete_btn').live('tap',function(e){
    var iddb = $(this).find('a').attr('rel');
    confirm_diario_delete(iddb);
});

function diario_delete(iddb) {
    var db = window.openDatabase("Database", "1.0", "123nozze", 200000);
    db.transaction(function(tx){
        tx.executeSql('DELETE FROM AgendaItemJDO WHERE id='+iddb);
        lastChangeUpdate();
    });

    $('.diario_row[db_id="'+ iddb +'"]').remove();
    $('#popupMenuDiario').popup("close");
}

function confirm_diario_delete(iddb) {
    var r = confirm("Confermi l'eliminazione dell'elemento?");
    if (r) {
        diario_delete(iddb);
    } else {
        $('#popupMenuDiario').popup("close");
    }
}

It seems to work but if I choose "cancel button" (so r = false) n times before I press "confirm button", next time the confirm dialog is displayed 2 times, next time it is displayed 3 times, and so on. I don't know why this behaves this way. The same is if a change the code and I use the Cordova example code for confirm dialog.
Any ideas on what is the problem and how can I solve it?
Thanks!

A: You should use the native notification which Phonegap supports.
Specifically the .confirm() method taken from link above;
// process the confirmation dialog result
function onConfirm(button) {
    alert('You selected button ' + button);
}

// Show a custom confirmation dialog
//

navigator.notification.confirm(
    'You are the winner!',  // message
    onConfirm,              // callback to invoke with index of button pressed
    'Game Over',            // title
    'Restart,Exit'          // buttonLabels
);

A:    navigator.notification.confirm(
        'Are you sure you want to signup ',  // message
        onConfirm,              // callback to invoke with index of button pressed
        'SignUp',            // title
         ['yes','no']             // buttonLabels
    );

    function onConfirm(buttonIndex){
    alert('You selected button ' + buttonIndex);
    if(buttonIndex==2){
    alert('You selected button - no');
    }else{
    alert('You selected button - yes');

    }

    }


Q: How to do this type of incrementation in PHP? I am using this category script:
<?php

include("connect.php");

$nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `id`");
$tree = "";
$depth = 1;
$top_level_on = 1;
$exclude = array();
array_push($exclude, 0);

while ($nav_row = mysql_fetch_array($nav_query)) {
    $goOn = 1;
    for ($x = 0; $x < count($exclude); $x++) {
        if ($exclude[$x] == $nav_row['id']) {
            $goOn = 0;
            break;
        }
    }
    if ($goOn == 1) {
        $tree .= $nav_row['name'] . "
";
        array_push($exclude, $nav_row['id']);
        if ($nav_row['id'] < 6) {
                    $top_level_on = $nav_row['id'];
                }

        $tree .= build_child($nav_row['id']);
    }
}

function build_child($oldID) {
    global $exclude, $depth;
    $child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID);
    while ($child = mysql_fetch_array($child_query)) {
        if ($child['id'] != $child['parent_id']) {
            for ($c=0; $c < $depth; $c++) {
                            $tempTree .= " ";
                        }
            $tempTree .= "- " . $child['name'] . "
";
            $depth++;
            $tempTree .= build_child($child['id']);
            $depth--;
            array_push($exclude, $child['id']);
        }
    }

    return $tempTree;
}

echo $tree;

?>

It relies on the following mysql database structure:
id | parent_id | name

1                Cats
2    1           Siamese Cats
3    2           Lilac Point Siamese Cats
4                Dogs

etc...

The script allows for unlimited category depth but has one major downfall. It displays the category navigation to the front end like so:
Cats
 - Siamese Cats
 - Lilac Point Siamese Cats
Dogs

How can I have it display like this:
Cats
 - Siamese Cats
   - Lilac Point Siamese Cats
Dogs

So that for each additional category depth another space with be added to the beginning indentation of the category text?

A: As you are already keep track of the depth, make use of it. E.g.
$indent = '';
for($i = 0; $i < $depth; $i++) {
     $indent .= " ";
}
$tempTree .= $indent . "- " . $child['name'] . "
";

To make it look the way you want it you might have to initialize $depth with 0.

Also note that executing SQL queries in a nested for loop is not the best approach. If possible, try to reduce the number of queries.
You could for example use classes and, get all the entries at once and then build the tree structure with objects and arrays.


Q: pass cookie and reload one frame from another frame I have main html page which have two frames frame1 and frame2. In frame1, a textbox & a button where the button click passes the value in textbox to a cookie. In frame2 this value passed through cookie is used. I need to refresh or reload the frame2 page as & when the cookie value is changed from the button click event on frame1. Any suggestions for achieving this???


Q: Docker Machine error: Hyper-V PowerShell Module is not available I've checked my Hyper-V settings and PowerShell Module is enabled. I've also found this documented issue: https://github.com/docker/machine/issues/4342 but it is not the same issue since I do not have VMware PowerCLI installed. The issue was closed with a push to the repo and is supposedly fixed in 0.14.0-rc1, build e918c74 so I tried it anyways. After replacing my docker-machine.exe, I'm still getting the error and still getting the error even if I reinstall Docker for Windows.
For some more background, this error starting happening after a reinstall because my Docker install had an error: https://github.com/docker/for-win/issues/1691, however, I'm not longer getting that issue after reinstalling.

A: For those who struggle with this issue in Windows, Follow the instruction here

A: When creating a Hyper-v VM using docker-machine on win10, an error was returned"Error with pre-create check: "Hyper-V PowerShell Module is not available"。
The solution is very simple. The reason is the version of the docker-machine program. Replace it with v0.13.0. The detailed operation is as follows:

*

*Download the 0.13.0 version of the docker-machine command. Click to download: 32-bit system or 64-bit system

*After the download is complete, rename and replace the " docker-machine.exe " file in the " C:\Program Files\Docker\Docker\resources\bin" directory. It is best to back up the original file.

A: Here is the solution
https://github.com/docker/machine/releases/download/v0.15.0/docker-machine-Windows-x86_64.exe
Save the downloaded file to your existing directory containing docker-machine.exe.
For my system this is the location for docker-machine.exe
/c/Program Files/Docker/Docker/Resources/bin/docker-machine.exe
Backup the old file and replace it file with the new one.
cp docker-machine.exe docker-machine.014.exe
Rename the downloaded filename to docker-machine.exe
mv docker-machine-Windows-x86_64.exe docker-machine.exe
Build Instructions

*

*Create virtual switch in Hyper-V manager named myswitch

*Request Docker to create a VM named myvm1
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1
Results
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1

Running pre-create checks...
(myvm1) Image cache directory does not exist, creating it at C:\Users\Trey Brister\.docker\machine\cache...
(myvm1) No default Boot2Docker ISO found locally, downloading the latest release...
(myvm1) Latest release for github.com/boot2docker/boot2docker is v18.05.0-ce
(myvm1) Downloading C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v18.05.0-ce/boot2docker.iso...
(myvm1) 0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100%
Creating machine...
(myvm1) Copying C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso to C:\Users\Trey Brister\.docker\machine\machines\myvm1\boot2docker.iso...
(myvm1) Creating SSH key...
(myvm1) Creating VM...
(myvm1) Using switch "myswitch"
(myvm1) Creating VHD
(myvm1) Starting VM...
(myvm1) Waiting for host to start...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\Docker\Docker\Resources\bin\docker-machine.exe env myvm1

A: (1),
V0.15 fixed this issue officially:
Fix issue #4424 - Pre-create check: "Hyper-V PowerShell Module is not available"
Official Introduction:
https://github.com/docker/machine/pull/4426
Address to donload V0.15
https://github.com/docker/machine/releases
(2),
I tested this, it works fine.
No need restart docker
It take effect immdiately after the "docker-machine.exe" is replaced with version 0.15
(3),
Backup the original one is a good habit

A: Just start docker desktop if you are on Windows


Q: HTTP mp4 filetransfer. IE downloads file too fast I have a web server that serves mp4 files. When I get a http request for a video that is 35mb, I use “send()” repeatedly in a loop to send 1mb each time.
Chrome and Firefox handle this well and receive no more data than needed. Only if the user has reached far enough in the webplayer, the browser requests/receives more data. IE however, receives my "send()" every two seconds, which means the entire file is downloaded in about a minute. That is not good for a user who only watched 1 min of 14 (considering data consumption/useage).
Can I do something differently?

Best regards
Arre


Q: Past Simple for repeated actions/habits This question evolved from a thread I created here yesterday (Past simple vs used to vs would). But as some of my previous doubts were resolved, another arose, and for the sake of brevity, and because I hoped this might draw in some new people, I decided it'd be best to write a separate post.
I'm having a bit of trouble telling the difference between using the past simple tense and "would" form in sentences that describe past repeated/habitual actions. The main troubling issue for me is the fact that it's sometimes pretty vague whether the speaker implies single or repeated action if they use solely the past tense. Does it always depend on the context of the whole statement?
Is there a situation when one of these forms is preferred to another? Are there even any rules regarding their use, or are they mostly interchangable?
For example, this quotation from The Clockwork Orange incorporates both forms in separate, consecutive utterances:

The Korova milkbar sold milk-plus, milk plus vellocet or synthemesc or drencrom, which is what we were drinking. This would sharpen you up and make you ready for a bit of the old ultraviolence.

Still, a short note about Ted Bundy's Modus Operandi seems to limit its structure solely to "would" forms.

Sometimes, Bundy would use a fake cast to play on a potential victim's sympathy. He would ask them for assistance of some kind, such as helping him put something in his car or asking for directions.

On the other hand though, the Wikipedia article about this murderer again utilizes both forms:

He would employ various ruses designed to lure his victim to the vicinity of his vehicle where he had pre-positioned a weapon, usually a crowbar. In many cases he wore a plaster cast on one leg or a sling on one arm, and sometimes hobbled on crutches, then requested assistance in carrying something to his vehicle.

To top it all, the two following sentences sound to my ear equally good no matter which form I choose and I really can't tell if one's better than another.

*

*The Aztecs used/would use shells and jewels to create dyes.

*He only spoke of it/would only speak of it when he was under a lot of pressure.

I find the entire issue really twisted and tangled, and I really hope someone can provide an in-depth explanation.

A: In this statement
He spoke of it when he was drunk.
we don't know if he was often drunk. He might have been. Maybe it was just that one time. Or now and then.
In this statement
He would speak of it when he was drunk.
we know that he was drunk at least from time to time. More than once. Enough to qualify as a "recurrence".
P.S. But all we have to do, to change the first sentence into a recurrent scenario, is to change one little word:
He spoke of it whenever he was drunk.
The tense did not change.  You must attend to the other time-aspect-words in the sentence (e.g. "only ... when").
P.P.S. The simple past can be used to express a recurrent or habitual situation, or a modus operandi/modus vivendi scenario; however, it cannot do so unambiguously, not unless corroborating time-phrases appear in the statement itself, or a corroborating context has been established in the conversation.
In antiquity, they made pain-killers from willow bark.
They spent winters in Florida and summers in Maine.

A:
The Korova milkbar sold milk-plus, milk plus vellocet or synthemesc or drencrom, which is what we were drinking. This would sharpen you up and make you ready for a bit of the old ultraviolence.

There are actually two different uses going on here. I think the "would" in "This would sharpen you up" is used to transform the statement into a conditional or hypothetical. For example, "That painting would look nice over the fireplace." In this case the implied condition under which "sharpening up" will occur is the drinking the milk-plus.
In the Bundy examples, "would" is preferred because they are generalized statements about his tactics rather than a recital of his crimes. The same generalization is accomplished without the use of "would" by starting a sentence with "in many cases," although the meaning of the sentence would not significantly change had the author chosen to include the word "would".
The last two examples are perfectly valid constructions either way, but you might prefer one over the other depending on context. The meanings are only very subtly different.

The Aztecs used shells and jewels to create dyes.

The above sentence simply states a historical fact about what the Aztecs did. It works well in multiple contexts.

Example A: "I walked through the exhibit. In one diorama, the Aztecs sacrificed a human being. In another, the Aztecs used shells and jewels to create dyes."
Example B1: "Archaeological evidence suggests that the Aztecs used shells and jewels to create dyes for application to clothing, ceramics, and architecture."
Example B2: "Archaeological evidence suggests that the Aztecs would use shells and jewels to create dyes for application to clothing, ceramics, and architecture."

Note that in Example A, "would use" would not be appropriate. However, in Example B, "used" and "would use" are interchangeable without losing the essential meaning.

The Aztecs would use shells and jewels to create dyes.

The above sentence states the same historical fact, but generalizes it as a habitual aspect in past time. As an example, it might be used when describing a scene or trying build a sense of atmosphere. The "would" might also be used for emphasis or contrast.

Example C: "The Aztecs would gladly use shells and jewels to create dyes, but they would never use turmeric."
Example D: "In the fourteenth century, Aztecs would use shells and jewels to create dyes, toiling for untold hours to achieve what is now accomplished by simply boiling powdered cochineal insects. How fortunate we are to live in such an enlightened age."

Again, in the Example D above, you could substitute "used" for "would use" without greatly affecting the meaning. However, "would use" is favored by the author to call attention to the abnormality.

Edit for more examples:
Remember that "would" in this usage describes habitual, or typical behavior.
I'm going to drop the "only" from your final example, because the modifier makes the two statements roughly equivalent. There is more contrast without it.

He spoke of it when he was under a lot of pressure

This statement means he spoke of it at least one time, and he was under pressure at the time that he spoke of it.
It can be considered a discrete event, solidly in the past.

He would speak of it when he was under a lot of pressure

This statement means that whenever he was under pressure, he spoke of it. It suggests that this occurred more than once. The central meaning conveyed is not the past event(s), but the past behavior: activity that was typical, or which could be generalized. This is why we call it "habitual."
The behavior is typical, such that if you traveled back to the timeframe being discussed, the occurrence "would" happen again (conditional/future tense) if the correct conditions were supplied.
Here are a few more examples that may shed some light on the different scenarios:
Simple Past for Discrete event(s):

Last month, I stopped at a gas station for a bite to eat after work.
Seven times last month, I stopped at a gas station for a bite to eat after work.

Simple Past with a frequency for Habitual Behavior:

Last month I frequently stopped at a gas station for a bite to eat after work.

Would for Habitual Behavior:

Before getting married I would stop at a gas station for a bite to eat after work.

Would for Contrasting Habitual Behavior:

In previous years I would stop at a gas station for a bite to eat. Now I wait until I get home.

Would for Habitual Past Tense Conditional:

I would stop at a gas station for a bite to eat if it wasn't too cold outside.

And for the sake of completeness...
Would for Present Tense Conditional:

I would stop at a gas station for a bite to eat if it weren't so cold outside.

Would for Discrete Past Tense Conditional:

I would have stopped at a gas station for a bite to eat if it hadn't been so cold outside.

A: This is just to add some commentary regarding the ambiguity of the simple past. And also some strategies that a person  might use to try to resolve this ambiguity.
Yesterday I started reading a new book. (This is not an example sentence; I'm telling you something true about my life, something that brought this question to my mind.) Anyway, I opened the book and read the first paragraph (which is one sentence), and I have no Idea whether the simple past is being used to talk about a single activity in the past or about a habitual activity. Let me quote this opening sentence from Men at Arms, the first novel in the trilogy Sword of Honour by Evelyn Waugh.

When Guy Crouchback's grandparents, Gervase and Hermione, came to Italy on their honeymoon, French troops manned the defenses of Rome, the Sovereign Pontiff drove out in an open carriage and Cardinals took their exercise side-saddle on the Pincian Hill.

Now, I am not sure how great an opening sentence to a novel that is. An opening sentence is supposed to grab you and make you want to keep reading, or so say many. However, the point is that when I read that opening sentence, my mind was trying to interpret what the author, or rather the text, was saying.
For one who is fairly new to Evelyn Waugh's style and also who is ignorant of all but the most cursory description of what the book is about, I am all but "flying blind" here, with no instruments to guide me.
Anyway, as I read the sentence, I frowned. Because I immediately recognized that the simple past here could be referring to a one time action (all the verbs) or those verbs in the independent clause could be talking about three customary or habitual activities that just happened to be going on when 'the grandparents came to Italy'.
It is very easy to read the sentence either way.
Now the strategies we use to solve this conundrum include our knowledge of how novels usually begin. Many novels, as I hinted, begin with action. So, taking this into account points toward the single event interpretation. Supporting evidence for this is that the arrival of a honeymooning couple often calls for certain individuals to perform certain activities.
On the other hand, novels can open with description, in order to set up a background against which events unfold. In addition, the singularity of events being described point a customary activity, because the singularity suggests that they occur repeatedly at a certain place only.
One last clue that is ultimately inconclusive  in helping solve our mystery is to notice that the use of the zero-article before French troops and Cardinals serves as an indefinite rather than as a definite reference to these two groups. One could argue that such an indefinite reference is used for descriptions of habitual activities, but, alas, this is not always the case. Again, we cannot lay down ironclad rules for these things. Which is a good thing, because this openness does not restrain the speaker or writer in his creativity. It also allows for a reader or listener to potentially take wonder in how different texts, speakers or authors can utilize the language as a means of unique and even genius creative expression.
Thus the point of posting this real life example from a native speaker who is a skilled and educated reader is to show you that struggling with this issue is not unique to the language learner. It was also meant to show that we use our intuition to try to intuit the text's meaning. We make a possible case for each meaning, and perhaps most importantly we rely on context to provide clues to the intended meaning. And we do this no matter which text is before us,   whether a novel or the screaming rampage of a neighbor.
So now what does one do?
The only answer is to keep reading. The hope is that reading further will lend more clues as to which sense the simple past is being used in. Further reading could provide clues lifted from the writer's style itself (this is how the writer normally describes a single  activity or a customary activity) or from further description of the plot. It remains to be seen if the French troops, the Supreme Pontiff and the Cardinals were actually performing a (single) activity or just having their normal or customary behavior described. Certainly a simple would before the last three verbs would solve the issue. But why would an author choose not to do this? I doubt it is to disconcert his reader.  I think it has to do with style and how the sentences read with the 'bare' simple past. That is a question you can ponder.