text:
Q: React Minified error #130 only during build and not when running yarn start I've developed a react application using redux and navigation is using react-router-dom. During the development build of the application i.e. while running yarn start the application works perfectly and without no errors but while doing a yarn build and after serving the built index.html the console shows an error Uncaught Invariant Violation: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
I've checked out the previous solutions given to this problem regarding default and named imports but it's still unsolved.
I've tried debugging the minified javascript and decompile using the source maps but still no luck. I can't understand why the same error is not shown during the development mode. I've attached some code of the project for further reference.
Package.json file:
{
  "name": "gyaan",
  "version": "1.0.0",
  "description": "",
  "keywords": [],
  "main": "src/index.js",
  "dependencies": {
    "global": "^4.3.2",
    "moment": "^2.24.0",
    "react": "16.5.2",
    "react-datepicker": "^2.1.0",
    "react-dom": "16.5.2",
    "react-dropzone": "^8.1.0",
    "react-facebook-login": "^4.1.1",
    "react-google-login": "^4.0.1",
    "react-loadable": "5.5.0",
    "react-loader": "2.4.5",
    "react-redux": "6.0.0",
    "react-router": "4.3.1",
    "react-router-dom": "4.3.1",
    "react-router-redux": "4.0.8",
    "react-s3-uploader": "^4.8.0",
    "react-scripts": "^2.1.8",
    "react-semantic-datetime": "^1.0.5",
    "react-tag-input": "^6.2.1",
    "react-youtube": "^7.9.0",
    "redux": "4.0.1",
    "redux-devtools-extension": "2.13.7",
    "redux-logger": "3.0.6",
    "semantic-ui-react": "^0.84.0",
    "serve": "^10.1.2",
    "socket.io-client": "^2.2.0",
    "styled-components": "^4.1.3",
    "superagent": "4.0.0",
    "superagent-promise": "1.1.0"
  },
  "devDependencies": {
    "semantic-ui": "^2.4.2"
  },
  "scripts": {
    "build-semantic": "cd src/semantic && gulp build-css build-assets",
    "watch-semantic": "cd src/semantic && yarn run build-semantic && gulp watch",
    "start": "react-scripts start",
    "build": "yarn run build-semantic && react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import store from "./store";

import App from "./Components/App";

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App/>
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

App.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { APP_LOAD, REDIRECT } from "../Constants/actionTypes";
import { Route, Switch, withRouter } from "react-router-dom";
import agent from "../agent";

import ResponsiveContainer from "./components/Base";

import Home from "./scenes/Home";
import Videos from "./scenes/Videos";
import StudentProfile from "./scenes/StudentProfile";
import TutorProfile from "./scenes/TutorProfile";
import Stream from "./scenes/Stream";
import Streamer from "./scenes/Streamer";
import Category from "./scenes/Category";
import CreateStream from "./scenes/CreateStream";
import VideoDetail from "./scenes/VideoDetail";

import "../semantic/dist/semantic.min.css";

const mapStateToProps = state => ({
  appLoaded: state.common.appLoaded,
  currentUser: state.common.currentUser,
  redirectTo: state.common.redirectTo,
  userType: state.common.userType
});

const mapDispatchToProps = dispatch => ({
  onLoad: (payload, token) => {
    dispatch({
      type: APP_LOAD,
      payload,
      token,
      skipTracking: true
    });
  },
  onRedirect: () => {
    dispatch({ type: REDIRECT });
  }
});

class App extends Component {
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.redirectTo) {
      this.context.router.history.push(nextProps.redirectTo);
      this.props.onRedirect();
    }
  }

  UNSAFE_componentWillMount() {
    const token = window.localStorage.getItem("jwt");
    if (token) {
      agent.setToken(token);
    }
    this.props.onLoad(token ? agent.Auth.current() : null, token);
  }

  render() {
    return (
      <React.Fragment>
        <ResponsiveContainer
          currentUser={this.props.currentUser}
          userType={this.props.userType}
        >
          <Route exact path="/" component={Home} />
          <Route path="/categories" component={Videos} />
          <Route path="/students/:username" component={StudentProfile} />
          <Route path="/tutors/:username" component={TutorProfile} />
          <Route path="/stream/:id" component={Stream} />
          <Route path="/streamer/:id" component={Streamer} />
          <Route path="/create" component={CreateStream} />
          <Route path="/category/physics" component={Category} />
          <Route path="/video-detail" component={VideoDetail} />
        </ResponsiveContainer>
      </React.Fragment>
    );
  }
}

App.contextTypes = {
  router: PropTypes.object.isRequired
};

export default withRouter(connect(mapStateToProps,mapDispatchToProps)(App));

store.js
import { applyMiddleware, createStore } from "redux";
import { createLogger } from "redux-logger";
import { composeWithDevTools } from "redux-devtools-extension/developmentOnly";
import { promiseMiddleware, localStorageMiddleware } from "./middleware";
import reducer from "./reducer";

const getMiddleware = () => {
  if (process.env.NODE_ENV === 'production') {
    return applyMiddleware(promiseMiddleware, localStorageMiddleware);
  } else {
    // Enable additional logging in non-production environments.
    return applyMiddleware(
      promiseMiddleware,
      localStorageMiddleware,
      createLogger()
    );
  }
};

const store = createStore(reducer, composeWithDevTools(getMiddleware()));

export default store;


text:
Q: Do I use Javascript for HTML  needs to affect two variables? I'm currently working on a paypal checkout form.  The form allows the user to specify a few options and when they submit the form, it submits the order to paypal for processing.
The form has a <select> droplist that allows a user to select how many times they want a subscription to recur.  It is set up like this:
<select name="srt">
    <option value="1"></option>
    <option value="2"></option>
    <option value="3"></option>
</select>
<input type="hidden" name="src" value="1">

This works in most cases, however when the user selects the first option with the srt value="1", paypal instead wants this to be submitted with srt blank or omitted and src (the hidden input below the form) with value="0".  The reason for this seems to be that if the payment is to recur 1 time, meaning to charge the customer only once, then this is not a recurring payment at all, so srt is not valid and instead src, which specifies if payments should recur or not, should be set to 0.
I'm wondering what is the best way to handle this.  The only thing I can think of is to use javascript to set hidden form values depending on what the user selects in a <select> drop list.
Is that the best way to handle this, or is there a better way that does not require the browser to handle javascript?
Thanks!

A: First of all I would like to make it clear that all values computed in the browser must be validated on the server. There really is no substitute for server side validation. Client-side scripts must only be used to improve user experience. Failing to do so is a security hole waiting to be exploited.

*

*To solve the issue at hand you could exploit the fact that disabled inputs aren't submitted when a form is posted. Thus if the user doesn't select to make a recurring payment srt will never get posted.

*Start out with srt both disabled and hidden.

*The hidden input src should have a value of 0 to start with.

*Add a "Recurring Payment?" checkbox to the form.

*If the user selects the checkbox, enable and show srt via Javascript.

*Set the value of src equal to whatever the user selects in srt.

*Disable and blank out srt and src if the user ever unchecks the checkbox.

DEMO
Markup:

<input type="checkbox" value="recurring" id="recurring"/>Recurring Payment?

<select disabled id="srt" name="srt">
    <option selected value="2">2</option>
    <option value="3">3</option>
</select>
<input type="hidden" id="src" name="src" value="0">

jQuery:
$('#recurring').click(function() {
    var $srt = $('#srt'),
        $src = $('#src');
    if (this.checked) {
        $srt.prop('disabled', false).toggle();
        $src.val($srt.val());
    } else {
        $srt.prop('disabled', true).toggle();
        $src.val(0);
    }
});

$('#srt').change(function() {
    $('#src').val($(this).val());
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: The following classes could not be instantiated android.support.design.widget.CoordinatorLayout I am using Coordinator Layout inside the Drawer Layout. I want to show a auto hide toolbar and use movie poster in it, which will collapse when movie details are scrolled. My app also uses a drawer layout. Here is my Layout XML activity_coordinator_layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:orientation="vertical"
        tools:context="com.inov8.falconpayconsumer.activities.MovieInfo">

        <RelativeLayout
            android:id="@+id/headerLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/red">

            <include
                android:id="@+id/header_layout2"
                layout="@layout/header" />
        </RelativeLayout>

        <include
            android:id="@+id/sub_header"
            layout="@layout/subheader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/headerLayout"
            android:visibility="visible" />

    </LinearLayout>

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
       tools:context="com.inov8.falconpayconsumer.activities.bookme.MovieDetailsActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:fitsSystemWindows="true"
            android:theme="@style/AppTheme">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:fitsSystemWindows="true"
                    android:minHeight="100dp"
                    android:scaleType="matrix"
                    android:src="@drawable/gods_of_egypt"
                    app:layout_collapseMode="parallax" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin">

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

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

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/title"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textAppearance="@style/TextAppearance.AppCompat.Headline" />

                    <TextView
                        android:id="@+id/description"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="15dp"
                        android:text="@string/lorem_ipsum"
                        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

                </LinearLayout>

            </FrameLayout>

        </android.support.v4.widget.NestedScrollView>

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

    <include
        android:id="@+id/header_layout"
        layout="@layout/drawer_layout_list" />
</android.support.v4.widget.DrawerLayout>

If it is the problem in the default theme of the application them it is <style name="My_App_Theme" parent="Theme.AppCompat.NoActionBar" />
In manifest I am using android:theme="@style/AppTheme"
and Here is the complete Error shown when drawing this layout
Rendering Problems The following classes could not be instantiated:     - android.support.design.widget.CoordinatorLayout (Open Class, Show Exception, Clear Cache)
Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE  Exception Details
java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.   at
android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:34)   at android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:182)   at
android.support.design.widget.CoordinatorLayout.<init>(CoordinatorLayout.java:176)   at
java.lang.reflect.Constructor.newInstance(Constructor.java:423)   at
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)   at
android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:835)   at
android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:70)
  at android.view.LayoutInflater.rInflate(LayoutInflater.java:811)   at
android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)   at
android.view.LayoutInflater.inflate(LayoutInflater.java:515)   at
android.view.LayoutInflater.inflate(LayoutInflater.java:394)

A: For the first one.

classes could not be instantiated
  android.support.design.widget.CoordinatorLayout

you have add this dependecies in your gradle file.
dependencies {

    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
}

and for second thing .

IllegalArgumentException: You need to use a Theme.AppCompat theme (or
  descendant)

All you need to do is add android:theme="@style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.


text:
Q: Django 502 bad gateway causes multiple email send I've a running Django app with uwsgi, served by nginx. The same env I use for many applications (https://github.com/abidibo/cookiecutter-django). I've Postfix configured to receive on localhost and Django configured to send email through it.
I have a view which when receiving a POST request creates some files and sends an e-mail.
What happened is that after processing the POST request, the server returned a 502 page, and multiple e-mail were sent (almost 60 e-mail). It doesn't happen every time, just a few, and I couldn't reproduce the bug in my local environment.
I can't figure out what happened, I mean, if some timeout occurred between Django and uwsgi or postfix itself, then why sending all this e-mail, why the code was executed multiple times?
In the application logs I see that a worker died:
- *** HARAKIRI ON WORKER 4 (pid: 8836, try: 1) ***
- HARAKIRI !!! worker 4 status !!!
- HARAKIRI [core 7] 188.92.61.228 - POST /xxx/xxx/xxx/4/ since 1549027535
- HARAKIRI !!! end of worker 4 status !!!
DAMN ! worker 4 (pid: 8836) died, killed by signal 9 :( trying respawn ...
Respawned uWSGI worker 4 (new pid: 21942)

In the nginx error log I see:
 [error] 2565#2565: *19983 upstream prematurely closed connection while reading response header from upstream, client: xx.xx.xx.xx, server: xxx.xxx.com, request: "POST /xxx/xxx/xx/4/ HTTP/1.1", upstream: "uwsgi://unix:/tmp/uwsgi_xxx.sock:", host: "xxx.xxx.com", referrer: "http://xxx.xxx.com/xxx/xxx/xx/4/"

Update
This is an extract of the post view function
def post(self, request, pk):
# stuff...
    try:
    # stuff...
        if request.POST.get('send_mail', False) and request.POST.get(
                'destinatari', ''):
            send_invoice_mail(fattura, [
                e.strip()
                for e in request.POST.get('destinatari', '').split(',')
            ])

        messages.add_message(
            request, messages.SUCCESS,
            'Nota di Credito cliente generata con successo')
        messages.add_message(
            request, messages.SUCCESS,
            'La nota di credito è stata correttamente inserita in prima nota'
        )
        if request.POST.get('send_mail', False):
            messages.add_message(request, messages.SUCCESS,
                                 'E-mail correttamente inviata')

        return redirect('/admin/fatture/notacreditouscitacliente/')

    except Exception as e:
        # stuff...
        messages.add_message(request, messages.WARNING, str(e))
        return redirect(
            '/admin/fatture/notacreditoentratafornitoreprodotti')

How can I debug this?


text:
Q: Foolproof Way To Check For SSL With PHP We have a need to check for certain if the server has SSL installed. Every method that we tried does not seem to be fool proof.
Our ultimate goal is if someone types in http://somedomain.com, we can test is the server has SSL and then display https://somedomain.com
We need to be able to do this with PHP and not htaccess since this is a module we are creating. Using file_exists or curl all seems to be some sort of drawback where it might not be turned on.
Thanks In Advance!

A: You can use the php $_SERVER['HTTPS'].
eg.
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
    header("Location: myurl.com");
    exit();
}
You should try both if the $_SERVER['HTTPS'] is empty and if the $_SERVER['HTTPS'] is set to on.
Be careful you should place this piece of code at the start of the page, because the redirection is happening with header() which only works if no html output is done.

A: *

*Can you connect to $hostname:443?

*Does $hostname:443 provide a valid certificate for $hostname

*???

*Profit!


text:
Q: CSS Slider: trigger Animation with JavaScript (GreenSock) I have a Question about this code:
codepen.io/ettrics/pen/WvoRQo

I'm trying to animate the content inside the slider with greensock (tweenmax) using javascript. How can i achieve that?
Thank you for your efforts!

A: You just check this and also..
Sample animation with javascript here.
Html

     close

This is overlay content

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries

     open

This is page content

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries

Css
* {
  margin: 0;
  padding: 0;
}
#overlay {
  width: 100%;
  height: 100%;
  color: #fff;
  position: fixed;
  transform: translateY(-100%);
  background-color: rgba(20,20,20,0.9);
}

#open {
  cursor: pointer;
  display: inline-block;
  width: 40px;
  height: 40px;
  background-color: #ea5;
}
#close {
  cursor: pointer;
  display: inline-block;
  width: 40px;
  height: 40px;
  background: #43e;
}

Jquery
//since there's a -100% translateY in the CSS, this just tells GSAP how things should be assigned between regular "y" and yPercent...
TweenLite.set(overlay, {y:0, yPercent:-100});

$('#open').on('click',
  function() {
    TweenMax.to(overlay, 0.8, {
      yPercent: 0
    });
  });

$('#close').on('click',
  function() {
    TweenMax.to(overlay, 0.8, {
      yPercent: -100
    });
  });


text:
Q: How to replace cocos2d-x scene from Java? I want to replace the scene in a cocos2d project from Java. I created the following JNI methods:
void cocos_android_app_init (JNIEnv* env, jobject thiz) {
    LOGD("cocos_android_app_init");
    AppDelegate *pAppDelegate = new AppDelegate();
}

extern "C" {
    JNIEXPORT void JNICALL Java_com_example_myapp_MainActivity_changeScene(
        JNIEnv* env, jobject thiz){
            cocos2d::Scene* scene = MyScene::createScene();
            Director::getInstance()->replaceScene(
                 TransitionFade::create( 1, scene ));
            //NOT WORKING BECAUSE Director::getInstance() is NULL
}
}

However, when the method changeScene is called from java, my App crashes because Director::getInstance() seems to be a NULL-pointer. How can the scene be changed correctly from Java?

A: You have to make a reference to Director::getInstance() in AppDelegate

A: I tried this :
extern "C"
{
    void Java_org_cocos2dx_cpp_SceneChanger_nativeCallbackChangeScene(JNIEnv*  env, jobject thiz)
    {
        Director::getInstance()->replaceScene(MyScene::createScene());
    }
};

and it replaces the scene successfully.
Are you sure Director::getInstance() is a null pointer ?
Make sure that you are running on OpenGL thread.
Check your error log, look for a line saying call to OpenGL ES API with no current context which means you are not running on gl thread.
To run on gl thread use this code :
Director::getInstance()->getScheduler()->performFunctionInCocosThread([&](){
    Director::getInstance()->replaceScene(MyScene::createScene());
});


text:
Q: How to extract 7zip archives with relative paths I have an archive myfile.7z that contains the single file
\Folder1\Folder2\Folder3\Folder4\myfile.txt

When I open this archive in 7-zip gui, navigate to Folder3, click it and click the "Extract" icon, it will correctly extract the relative path:
\Folder3\Folder4\myfile.txt

However when I run the following from command line to extract Folder3:
"C:\Program Files\7-Zip\7z.exe" x myfile.7z -r Folder1\Folder2\Folder3

Instead of extracting the relative path starting with Folder3 in the same fashion as the gui, it extracts the full path:
\Folder1\Folder2\Folder3\Folder4\myfile.txt

How do I get the command line version to extract relative paths the same way the gui does?


text:
Q: Split array at index in Pharo Smalltalk I'm having trouble with this:
Split: lista

li := Array new: 30.
aux := Array new: 30.
j := 0.
1 to: (lista size / 30) ceiling do: [ :i |
    1 to: 30 do: [ :k | aux at: k put: (lista at: k + j) ].
    j := j + 30.
    li at: i put: aux ].
^ li

This is supossed to return the same list, but splitted in 30 groups of 30. I don't know what is failing, I've tried debugging it a lot of times, but it just doesn't work. At first I tried to split it at an index, but it's too hard.
Please, help me! :(

A: Following the comments, I think you want something like
split: lista by: anInteger
| groups j |

groups := OrderedCollection new.
j := 0.
lista withIndexDo: [:element :i | | group |
    i // anInteger = 0
       ifTrue: [ group := Array new: anInteger.
                 j := 1 ].
    group at: j put: element.
    j := j + 1.
    (j > anInteger or: [ i = lista size ])
       ifTrue: [groups add: group]. ].
^ groups


text:
Q: xlrd & openpyxl fetch wrong cell values (Excel) Need help, please! Seems like a simple task – I need to fetch values from certain spreadsheet cells and sum them up. But I failed even at the first step - fetching them. At first, I thought smth wrong was with the module (openpyxl is being regularly upgraded and I missed something), but the xlrd module produced the same wrong results! Here's the code:
import xlrd, xlwt
wb = xlrd.open_workbook(r"E:\Projects_working (11).xlsx")
sheet = wb.sheet_by_name('Language Process')
for i in range(1, 100):
    cellVal = sheet.cell(i, 14).value   #need to find "5" in column 14
       if type(cellVal) == float and cellVal == 5.0: #need to read corresp.
           print(sheet.cell(i, 11).value)            #values в column 11

As a result, instead of an integer (say, 22), the code ends up with a float 42782.61458. (The other values are similar and wrong: 42782.66146, 42781.38542, 42781.42708, etc.)
Orignially I used the openpyxl module and added the flag data_only=True to the loadede workbook: wb = load_workbook("file.xlsx", data_only=True). That code produces the same results. Without this flag, all get is strange formulas: =B32+((M32-B32)/2), =B41+((M41-B41)/2) etc. Here's the code for these formulas (with no flag):
import openpyxl
wb =  openpyxl.load_workbook(r"E:\Projects_working (11).xlsx")
sheet = wb.get_sheet_by_name('Language Process')
for i in range(1, 100):
    cellVal = sheet.cell(row=i, column=14).value
        if type(cellVal) == float and cellVal == 5.0:
            print(sheet.cell(row=i, column=11).value)

And here's a link to the file, just in case: https://docs.google.com/spreadsheets/d/1bFhkEs8JTVWCgZoW5_9lQ1q_T0gtijBhuywr6OVpfGc/edit?usp=sharing

A: The data you are reading look like Excel's version of raw datetime values. You probably have miscounted the columns (that is, given the wrong column index).


text:
Q: integrals for area in 3D space I'm in my first year of uni and we started using double and triple integrals in electrostatics to calculate the areas and volumes of simple shapes such as the cylinder. trying to learn the math behind it I learned about the jacobian and change of variables. now I understand why the triple integral for the volume of a cylinder is what it is since I can use the jacobian to get it from the one in cartesian.
$V(R)= \int_{-\infty}^{+\infty}\int_{-\infty}^{+\infty}\int_{-\infty}^{+\infty} \chi(R)dxdydz$
to
$V(R)=\int_{0}^{2\pi}\int_{0}^{+\infty}\int_{-\infty}^{+\infty} \chi(R)\rho dzd\rho d\theta$
but the problem is when we calculated the area of the lateral surface of the cylinder in class using cylindrical coordinates.
$\int_{0}^{2\pi}\int_{0}^{h}R dzd\theta$
I didn't know what the integral would look like in cartesian, to begin with...I also saw some use the Dirac delta to calculate it in cartesian but I don't know how to manipulate those and I don't know how to transform it to cylindrical, my objective being to prove the use of the integrals the professor used.
QUESTION: can someone show me what the integral for the area of the lateral surface of a cylinder would look like in cartesian? and if it's complicated how to transform it into cylindrical.

A: Integral in cartesian
One way to find the lateral surface area is to add up the areas of
thickened circles of small height like "$\mathrm{d}z$". To do
that, we first need the circumference of those circles.
The circumference of a circle $x^{2}+y^{2}=R^{2}$ (at height $z$)
doesn't change with height, so we can just work in the $xy$-plane.
Then there are two semicircles, one given by $y=\sqrt{R^{2}-x^{2}}$
and the other given by $y=-\sqrt{R^{2}-x^{2}}$. The semicircles each
have the same length, so we can just find twice the length of the
first one. The arc length formula can be found at Paul's Online Notes or
or openstax Calculus Volume 2. We have $\int_{-R}^{R}\sqrt{1+\left(\dfrac{\mathrm{d}}{\mathrm{d}x}\sqrt{R^{2}-x^{2}}\right)^{2}}\,\mathrm{d}x$
for the length of one semicircle, so twice that is the entire circumference.
Then we can multiply these circumferences by a small height $\Delta z$,
add them up, and take a limit to turn it into the following integral:
\begin{align*}
 & \int_{0}^{h}\left(2\int_{-R}^{R}\sqrt{1+\left(\dfrac{\mathrm{d}}{\mathrm{d}x}\sqrt{R^{2}-x^{2}}\right)^{2}}\,\mathrm{d}x\right)\,\mathrm{d}z\\
= & 2\int_{0}^{h}\int_{-R}^{R}\sqrt{1+\left(-\dfrac{x}{\sqrt{R^{2}-x^{2}}}\right)^{2}}\,\mathrm{d}x\,\mathrm{d}z\\
= & 2\int_{0}^{h}\int_{-R}^{R}\sqrt{1+\dfrac{x^{2}}{R^{2}-x^{2}}}\,\mathrm{d}x\,\mathrm{d}z\\
= & 2\int_{0}^{h}\int_{-R}^{R}\sqrt{\dfrac{R^{2}}{R^{2}-x^{2}}}\,\mathrm{d}x\,\mathrm{d}z\\
= & 2\int_{0}^{h}\int_{-R}^{R}\dfrac{R}{\sqrt{R^{2}-x^{2}}}\,\mathrm{d}x\,\mathrm{d}z\\
= & 2\int_{0}^{h}\int_{-R}^{R}\dfrac{1}{\sqrt{1-\left(x/R\right)^{2}}}\,\mathrm{d}x\,\mathrm{d}z
\end{align*}
Note that the inner $x$ integral doesn't depend on $z$, so we could
also write
$$
2\left(\int_{-R}^{R}\dfrac{1}{\sqrt{1-\left(x/R\right)^{2}}}\,\mathrm{d}x\right)\left(\int_{0}^{h}1\,\mathrm{d}z\right)
$$
$$
\text{or }\int_{-R}^{R}\left(\dfrac{1}{\sqrt{1-\left(x/R\right)^{2}}}2\int_{0}^{h}1\,\mathrm{d}z\right)\,\mathrm{d}x\text{.}
$$
The latter suggests a way of thinking of this by cutting slices for
each value of $x$, where the $\dfrac{1}{\sqrt{1-\left(x/R\right)^{2}}}$
accounts for the curve of the semicircle.
Transforming back to cylindrical
To transform back to cylindrical, we can use a trigonometric substitution
(openstax, Paul's). We use $x=R\cos\theta$ and $\mathrm{d}x=-R\sin\theta\,\mathrm{d}\theta$
to convert the $x$ integral above:
\begin{align*}
 & \int_{-R}^{R}\dfrac{1}{\sqrt{1-\left(x/R\right)^{2}}}\,\mathrm{d}x\\
= & \int_{\theta\text{ when }x=-R}^{\theta\text{ when }x=R}\dfrac{1}{\sqrt{1-\left(R\cos\theta/R\right)^{2}}}\left(-R\sin\theta\right)\,\mathrm{d}\theta\\
= & \int_{\pi}^{0}\dfrac{1}{\sqrt{1-\cos^{2}\theta}}\left(-R\sin\theta\right)\,\mathrm{d}\theta\\
= & \int_{\pi}^{0}\dfrac{-R\sin\theta}{\sqrt{\sin^{2}\theta}}\,\mathrm{d}\theta\\
= & \int_{\pi}^{0}\dfrac{-R\sin\theta}{\left|\sin\theta\right|}\,\mathrm{d}\theta\\
= & \int_{\pi}^{0}-R\,\mathrm{d}\theta\text{ since }\sin\theta\ge0\text{ on }[0,\pi]\\
= & \int_{0}^{\pi}R\,\mathrm{d}\theta
\end{align*}
This means the entire area becomes
$$
2\left(\int_{0}^{\pi}R\,\mathrm{d}\theta\right)\left(\int_{0}^{h}1\,\mathrm{d}z\right)=\left(\int_{0}^{2\pi}R\,\mathrm{d}\theta\right)\left(\int_{0}^{h}1\,\mathrm{d}z\right)=\boxed{\int_{0}^{2\pi}\int_{0}^{h}R\,\mathrm{d}z\,\mathrm{d}\theta}
$$
More general areas
The lateral area of a cylinder is a very special kind of surface,
and there are more general techniques we can use to find the area
of it and other surfaces.
Areas of revolution
The cylinder is a surface of revolution: For the cylinder under discussion,
we revolve the line segment $x=R,y=0,z\in[0,h]$ around the $z$-axis.
Rotating things around, this would have the same area as rotating
the line segment $x=R$, $y\in[0,h]$ (in the plane $z=0$) around
the $y$-axis. The standard formula (Paul's, openstax) for the lateral area of a surface of revolution gives:
\begin{align*}
 & \int_{0}^{h}2\pi R\sqrt{1+\left(\dfrac{\mathrm{d}}{\mathrm{d}y}R\right)^{2}}\,\mathrm{d}y\\
= & 2\pi\int_{0}^{h}R\,\mathrm{d}y\\
= & \left(\int_{0}^{2\pi}1\,\mathrm{d}\theta\right)\int_{0}^{h}R\,\mathrm{d}y\\
= & \int_{0}^{2\pi}\int_{0}^{h}R\,\mathrm{d}y\,\mathrm{d}\theta\\
= & \int_{0}^{2\pi}\int_{0}^{h}R\,\mathrm{d}z\,\mathrm{d}\theta
\end{align*}
Areas of parametrized surfaces
If you do more calculus (you might not come across this in a
first study of electrostatics), you might want to find the surface
area of a surface that doesn't have any rotational symmetry, but still
has a nice parametrization. This is described at openstax Calculus Volume 3 and Paul's Online Calculus III Notes, for instance.
One thing to watch out for is that if you have something like a Moebius
strip which has only one side, you might not be calculating the area
you intended. See the Math StackExchange question "Area of Mobius strip" and its answers for some discussion.


text:
Q: Perplexed by SVG viewBox, width, height, etc If my understanding of SVG were correct, the following two SVG descriptions would result in identical images, but they don't.  (NOTE: The two code listings differ only in the coordinate values in their svg tags.  More specifically, for every (x, y) pair in the first listing there's an (x-205, y-55) pair in the second listing.)
<!DOCTYPE html>
<html>
  <head><title>title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>

    <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
     x="0" y="0" width="210" height="60" viewBox="0 0 210 60">

      <g style="stroke: black; fill: none;">
        <path d="M 5 5 Q 105 55 205 55"/>
      </g>

    </svg>

  </body>
</html>

<!DOCTYPE html>
<html>
  <head><title>title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>
  <body>

    <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
     x="-205" y="-55" width="210" height="60" viewBox="-205 -55 5 5">

      <g style="stroke: black; fill: none;">
        <path d="M -200 -50 Q -100 0 0 0"/>
      </g>

    </svg>

  </body>
</html>

In fact, according to Firefox at least, they look quite different.  The rendering that I expected for both of them is what Firefox delivers for the first one (namely, a curve gently sloping down from left to right, with an initial slope of -1/2 and and final slope of 0).  I'm utterly befuddled by what FF produces for the second one, because, AFAICT, the second spec is a simple wholesale ("rigid") translation, by the vector (-205, -55), of the first one.

Why don't the two displays look identical?

A: For a precis on the viewBox see the (only) figure in this article: https://web.archive.org/web/20140119030353/https://software.intel.com/en-us/html5/blogs/viewbox-a-window-into-the-soul-of-svg, inlined below for convenience:

That picture is worth 1000 words of explanation.
The width and height parameters, aka the viewport in W3C terminology are a different thing. But you're not changing those in the above example. There is a slightly complex algorithm for determining if the width and height from the SVG actually do anything because they can be overridden for example by the <object> tag that embeds the SVG in an HTML page. There are more corner cases explained at http://www.w3.org/TR/SVG/coords.html#ViewportSpace. For a more visually oriented (and perhaps more approachable) explanation of this viewport issue, you could also consult the Inkscape manual http://tavmjong.free.fr/INKSCAPE/MANUAL/html/Web-SVG-Positioning.html (As an aside, there's an extension available to set the viewBox visually from Inkscape http://pernsteiner.org/inkscape/viewbox/; you don't really have to edit the XML directly as the Inkscape manual [still] says.)

A: Because the coordinates of viewbox are not x1, y1, x2, y2 - they are minx, miny, width and height.

A: Very late on this one, but to clarify a point Michael made above for future viewers:
if you change some of the numbers in here, but not many, you'll get the same result.
One issue you're running into is that you think that min-x + width is supposed to be the same in either svg node. min-x and min-y are the leftmost and topmost coordinates of your viewBox - effectively changing the 0, 0 position to min-x, min-y, and are really only relevant to the coordinate system of the viewBox (and by extension to your path's d attribute), not to sizing of the viewBox itself.
Also, the x and y position  of an svg node are valid but ignored and have nothing to do with any placement.
So to have your second path look like your first, you can strip away the x and y attributes, and change the width and height numbers insideviewBox to match the first one:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
 width="210" height="60" viewBox="-205 -55 210 60">

  <g style="stroke: black; fill: none;">
    <path d="M -200 -50 Q -100 0 0 0"/>
  </g>

</svg>


text:
Q: Operation not supported: Expense with BillableStatus should have CustomerRef for AccountBasedExpenseLineDetail Line in Purchase I have attempted to submit a Purchase as Check to QBD using PHP SDK with the below XML request content:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:Purchase xmlns:ns0="http://schema.intuit.com/finance/v3" domain="QB">
  <ns0:TxnDate>2014-02-21</ns0:TxnDate>
  <ns0:PrivateNote>Test for QBD Purchase Check</ns0:PrivateNote>
  <ns0:Line>
    <ns0:Description>E1</ns0:Description>
    <ns0:Amount>10.00</ns0:Amount>
    <ns0:DetailType>AccountBasedExpenseLineDetail</ns0:DetailType>
    <ns0:AccountBasedExpenseLineDetail>
      <ns0:ClassRef name="Coffee and tea">QB:8</ns0:ClassRef>
      <ns0:AccountRef name="Computer and Internet Expenses">QB:10</ns0:AccountRef>
      <ns0:BillableStatus>NotBillable</ns0:BillableStatus>
      <ns0:TaxCodeRef>NON</ns0:TaxCodeRef>
    </ns0:AccountBasedExpenseLineDetail>
  </ns0:Line>
  <ns0:Line>
    <ns0:Description>E2</ns0:Description>
    <ns0:Amount>15.00</ns0:Amount>
    <ns0:DetailType>AccountBasedExpenseLineDetail</ns0:DetailType>
    <ns0:AccountBasedExpenseLineDetail>
      <ns0:CustomerRef name="Arnold Schwarzenegger">QB:3</ns0:CustomerRef>
      <ns0:ClassRef name="Alcoholic beverages">QB:2</ns0:ClassRef>
      <ns0:AccountRef name="Computer and Internet Expenses">QB:10</ns0:AccountRef>
      <ns0:BillableStatus>NotBillable</ns0:BillableStatus>
      <ns0:TaxCodeRef>NON</ns0:TaxCodeRef>
    </ns0:AccountBasedExpenseLineDetail>
  </ns0:Line>
  <ns0:AccountRef name="My Bank Account">QB:30</ns0:AccountRef>
  <ns0:PaymentType>Check</ns0:PaymentType>
  <ns0:EntityRef name="Herry Pilor">QB:9</ns0:EntityRef>
  <ns0:TotalAmt>25.00</ns0:TotalAmt>
</ns0:Purchase>

Since both lines have been marked BillableStatus=NotBillable, however, the first line comes without CustomerRef.
Submit that content should get this response message:
http://schema.intuit.com/finance/v3" time="2014-02-21T09:04:42.972Z">Operation failed with errors:
Operation not supported: Expense with BillableStatus should have CustomerRef for AccountBasedExpenseLineDetail Line in Purchase </Message></Error></Fault></IntuitResponse>

So the question is that why it requires Customer when BillableStatus=NotBillable?
But in the previous Java API version, there was no Customer expected when NotBillable
Please advice.
Thanks

A: BillableStatus must be excluded from the request if CustomerRef is not specified.  This is a known issue.


text:
Q: Why is identifier for secondary tile invalid? I am trying to update a Windows 8 secondary tile directly using XML. However, I keep getting an exception that the identifier for the tile I pinned is invalid. I even tried pulling the identifier directly from Windows and then substituting that back into CreateTileUpdaterForSecondaryTile, but I'm still getting the same exception. Here's my code:
public async static void UpdateSecondarySectionTile()
{
    string tileXmlString = "<tile id='SecondaryTile-7-0'>"
                         + "<visual>"
                         + "<binding template='TileWideImage'>"
                         + "<image id='1' src='" + imageSource + "' alt='alt text'/>"
                         + "</binding>"
                         + "</visual>"
                         + "</tile>";

    // create a DOM
    Windows.Data.Xml.Dom.XmlDocument tileDOM = new Windows.Data.Xml.Dom.XmlDocument();
    tileDOM.LoadXml(tileXmlString);

    System.Collections.Generic.IReadOnlyList<Windows.UI.StartScreen.SecondaryTile> tileList = await Windows.UI.StartScreen.SecondaryTile.FindAllAsync();

    foreach (var tile in tileList)
    {
        string tileId = tile.TileId;
        Windows.UI.Notifications.TileNotification tileUpdate = new Windows.UI.Notifications.TileNotification(tileDOM);
        try
        {
            Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId).Update(tileUpdate);
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine("message: " + e.Message + ", inner exception: " + e.InnerException + " string: " + e.ToString());
        }
    }
}

The debug line is outputting:
//message: The application identifier provided is invalid.
, inner exception:  string: System.Exception: The application identifier provided is invalid.

Any idea what the problem is? The foreach loop only executes once because there's only one pinned secondary tile on my build. (Also I realize that UpdateSecondarySectionTile should take the tileId as a parameter and only update one tile per call; this is just debugging code.)
I find it interesting that it's complaining about the application identifier rather than the tile identifier. Also, I'm aware that tile updates sometimes do not work if you run them in the simulator, but I am encountering this issue even on my local machine.

A: The exception referenced in the question ("The application identifier provided is invalid") can be thrown by the CreateTileUpdaterForSecondaryTile method outside of the simulator if the secondary tile was initially pinned while in the simulator.  To work around this issue, unpin the secondary tile and repin it outside of the simulator.
As noted by the question author, the tile update APIs (and other push notification related APIs) are not supported in the simulator.  In this case, the secondary tile pinning was not persisted outside of the simulator.


text:
Q: Ejecutar Ajax sólo con javascript? Me gustaría saber como se puede mejorar el siguiente código para hacer llamadas con ajax http reques.

function fn_EjecutarAjax(s_Metodo, s_Url, s_Parametros, b_Asincrono, s_TipoRespuesta, s_FuncionEjecutar)
{
 var s_MensajeError = '';
 var ESTADO_CORRECTO = 4;
 var ESTATUS_CORRECTO = 200;
 var xmlhttp_Conexion = fn_AjaxHttpReques();
 try
 {
  if(xmlhttp_Conexion != false)
  {
   xmlhttp_Conexion.onreadystatechange  =
   function()
   {
    if(xmlhttp_Conexion.readyState === ESTADO_CORRECTO)
    {
     if(xmlhttp_Conexion.status === ESTATUS_CORRECTO)
     {
      var s_Ejecutar = s_FuncionEjecutar + '(\'' + xmlhttp_Conexion.responseText + '\');';
      s_Ejecutar = s_Ejecutar.replace(/(?:\r\n|\r|\n)/g, ' ');
      eval(s_Ejecutar);
     }
    }
   }
   switch(s_Metodo)
   {
    case 'GET':
     if(s_TipoDatosEnviar === 'JSON')
     {
      s_MensajeError = 'Los parametros no se pueden enviar en JSON para el Método GET, favor de verificar el envío de parámetros.';
      return false;
     }
     var s_UrlCompleta = s_Url + '?' + s_Parametros;
     xmlhttp_Conexion.open(s_Metodo, s_UrlCompleta, b_Asincrono);
     xmlhttp_Conexion.send(null);
    break;
    case 'POST':
     xmlhttp_Conexion.open(s_Metodo, s_Url, b_Asincrono);
     xmlhttp_Conexion.responseType = s_TipoRespuesta;
     s_TipoDatosEnviar = 'application/x-www-form-urlencoded';
     xmlhttp_Conexion.setRequestHeader("Content-Type", s_TipoDatosEnviar);
     xmlhttp_Conexion.send(s_Parametros);
    break;
    default:
     var s_MensajeError = 'El método solicitado no es correcto, la función Ajax sólo acepta método [GET] y método [POST], favor de verificar con el desarrollador de la aplicación.';
     break;
   }
  }
 }
 catch (Error_Ajax)
 {
  console.log(Error_Ajax);
  return false;
 }
}

Creen que esta bien, como podría ser la mejor opción, o me faltaría algo mas que validar.
Saludos.

A: Buenas espero esto sea lo que buscas y te ayude saludos

document.getElementById("cambiar").addEventListener("click",cambiar);

function cambiar(){
    var xhr = new XMLHttpRequest();

    xhr.open("GET","https://jsonplaceholder.typicode.com/users",true);
    xhr.send();

    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            document.getElementById("parrafo").innerHTML = xhr.responseText;
        }
    }
}

consultar usuarios!

    <button id="cambiar">Consultar</button>


text:
Q: Бесконечный ввод чисел в консоли Надо считать бесконечный ряд переменных типа double с консоли. Например, я ввожу:

100 500.20 800

жму Enter, и введенные значения записываются в массив. Как так сделать?

A: Например, что-то вроде этого:
for(;;)
{
    double n;
    cin >> n;
    // Что-то делаем
    // Если все введено - break;
}

Update
Если считывание из одной строки - то можно, например, так
string s;
getline(cin,s);  // Чтение строки ("до нажатия Enter")
istringstream is(s); // Строковый поток для чтения
double n;
while(is >> n)
{
    // Что-то делаем со считанными числами
}

A: Чтение до окончания ввода (в Linux Ctrl+D, в Windows — Ctrl+Z):
#include <iterator>
#include <iostream>
#include <vector>

int main()
{
    std::vector<double> v(std::istream_iterator<double>(std::cin), {});
    std::copy(std::begin(v), std::end(v), std::ostream_iterator<double>(std::cout, " "));
}

Чтение в строку до Enter с последующим чтением из строки:
#include <iterator>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>

int main()
{
    std::string s;
    std::getline(std::cin, s);

    std::istringstream iss(s);

    std::vector<double> v(std::istream_iterator<double>(iss), {});
    std::copy(std::begin(v), std::end(v), std::ostream_iterator<double>(std::cout, " "));
}


text:
Q: $a=b^x+c^x$, How to solve for $x$? If $a=b^x$, then $x$ could be written in terms of $a$ and $b$; $x=\dfrac{\log(a)}{\log(b)}$.
What about $a=b^x+c^x$?
Could $x$ be written in terms of $a, b$ and $c$?
$x={}$?

A: The best we can do (in terms of algebraic solutions) is as follows: rewrite the equation as
$$
a = \left(e^x\right)^{\ln(b)} + \left(e^x\right)^{\ln(c)}
$$
setting $y = e^x$, this becomes an equation on $y$:
$$
a = y^{\ln(b)} + y^{\ln(c)}
$$
Or, rearranging,
$$
y^{\ln(b)} + y^{\ln(c)} - a = 0
$$
In other words, we're looking for $x > 0$ that satisfy
$$
x^\beta + x^\gamma - a = 0
$$
There is no general way to solve for $x$ if $\beta,\gamma$ are integers, let alone if $\beta$ and $\gamma$ can be arbitrary real numbers.

A: As Omnomnomnom answered, in general, there will not be explicit solutions and numerical methods, such as Newton, would be used.
Considering  $$f(x)=b^x+c^x-a$$  we know that the function is such bracketted by  $2 b^x-a$ and $2c^x-a$ which allows to define an approximate range for the solution.
But the function $f(x)$ can be very stiff and so the convergence could be rather slow. If instead we consider $$g(x)=\log(b^x+c^x)-\log(a)$$ the function would probably look like a straight line and convergence could be very fast.
Just in case you need it, starting with a "reasonable" guess of the solution $x_0$, Newton method will update it according to $$x_{n+1}=x_n-\frac{F(x_n)}{F'(x_n)}$$
For illustration purposes, let us choose $b=2$, $c=3$, $a=10^6$. Using the bounding functions, we know that the solution $x$ will be more or less between $12$ and $19$. So, let us start with $x_0=15$.
With $f(x)$, the successive iterates will then be $14.1523$, $13.4017$, $12.8562$, $12.6105$, $12.5708$, $12.5699$ which is the solution for six significant figures.
Doing the same with $g(x)$ and the same starting point, the successive iterates will then be $12.5713$, $12.5699$. Quite faster, isn't it ?
Edit
For the initial guess of the solution, we can do much better :

*

*use the bounding functions to get the upper and lower bounds of the solution

*compute the value of function $g(x)$ at these two points

*assume that these two points are along a straight line ($g(x)\approx A x+B$ in the interval)

*compute parameters $A$ and $B$ and $x=-\frac BA$. This gives as an estimate $x_0$ of the solution.

The two points having coordinates $$x_b=\frac{\log \left(\frac{a}{2}\right)}{\log (b)}~~~~\,~~~~ y_b=\log(b^{x_b}+c^{x_b})-\log(a) $$
 $$x_c=\frac{\log \left(\frac{a}{2}\right)}{\log (c)}~~~~\,~~~~ y_c=\log(b^{x_c}+c^{x_c})-\log(a)$$
$$A=\frac{{x_c} {y_b}-{x_b}
   {y_c}}{{x_c}-{x_b}}~~~~\,~~~~ B=
   \frac{{y_c}-{y_b}}{{x_c}-{x_b}}$$ $$x_0=\frac {x_c y_b-x_b y_c}{y_b-y_c}$$
 For the worked example, this gives $x_0\approx 12.5689$ and one single Newton iteration should suffice.
Edit
By the way, you could use the same procedure for finding the root of $$f(x)=\sum_{i=1}^n a_i^x-b=0$$ rewriting it as $$g(x)=\log\Big(\sum_{i=1}^n a_i^x\Big)-\log(b)=0$$ Admitting $a_1>a_2>a_3>\cdots>a_n>1$, the solution will be such that $$\frac{\log \left(\frac{b}{n}\right)}{\log (a_1)}<x<\frac{\log \left(\frac{b}{n}\right)}{\log (a_n)}$$
If you are lazy and do not want to perform these preliminary calculations, develop $g(x)$ as a Taylor series at $x=0$ and use as estimate $$x_0=\frac{n \log \left(\frac{b}{n}\right)}{\log \left(\prod _{i=1}^n a_i\right)}$$

A: If $b>1$ then $b^x\to\infty$ as $x\to\infty$ and $b\to 0$ as $x\to-\infty$.
If $b>1$ then $b^x\to\infty$ as $x\to-\infty$ and $b\to\infty$ as $x\to-\infty$.
Either way, $b^x$ runs through all of the interval $(0,\infty)$.
Similarly for $c^x$.
If $b>1$ and $c>1$ then $b^x+c^x\to\infty$ as $x\to\infty$ and $b^x+c^x\to0$ as $x\to-\infty$.
If $b<1$ and $c<1$ then $b^x+c^x\to\infty$ as $x\to-\infty$ and $b^x+c^x\to0$ as $x\to\infty$.
Either way $b^x+c^x$ runs through the whole of $(0,\infty)$, and by the intermediate value theorem, a solution exists if $a>0$.
In those cases, you can tell whether $x$ is too big or too small, and after narrowing it down a bit, use Newton's method.
If $b>0$ and $c<0$ or vice-versa, then it's more complicated: there is a positive number that is an absolute minimum and a solution exists if, but only if, $a\ge\text{the minumum}$.
The minimum occurs at a value of $x$ for which $\dfrac d{dx}(b^x+c^x)=0$, so
$$
b^x\log_e b + c^x \log_e c =0.
$$
$$
\left( \frac b c \right)^x = \frac{-\log_e c}{\log_e b} = -\log_b c.
$$
$$
x = \log_{b/c} (-\log_b c) = \log_{c/b}(-\log_c b). \tag 1
$$
(Notice that if either $b<1<c$ or $c<1<b$ then $\log_b c<0$ so $-\log_b c>0$ and we can take its logarithm.)  The phrase "$x=$" in $(1)$ does not mean that that is a solution. Rather it mean if you plug that value of $x$ into $b^x+c^x$ you get the smallest value of $a$ for which a solution exists.


text:
Q: How to fix my Applescript plugins for the Contacts application that are no longer available since 10.9 Mavericks upgrade? I have got 5 scripts listed in ~/Library/Address Book Plug-Ins/

*

*SkypeABDialer.bundle

*SkypeABSMS.bundle

*TelephoneAddressBookPhonePlugIn.bundle

*TelephoneAddressBookSIPAddressPlugIn.bundle

*Dial with Snom VoIP phone.scpt

Since the OS upgrade from 10.7 (Lion) to 10.9 (Mavericks) the .bundle plug-ins are still available within the "Contacts" application, however the AppleScript (.scpt) version is no longer listed at the former entry points.
How to fix this?

A: 1. The launch services database is screwed up
This Contacts.app launch services problem/issue might appear again after each Mac OS X update, like the 10.9.2 combo updater according to http://web.archiveorange.com/archive/v/2NbVio0gzU3nWMhAxfsk
1a. Command line fix
$ /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill -r -all l,s,u

In case of error messages like no such file or directory you can find the location of your lsregister with the command $ locate lsregister.
1b. OnyX fix
Or, you can run the OnyX application (version 2.8.7),
go to tab "Automation".
Disable each check mark,
except for section "Rebuilding",
and make sure that item "LaunchServices" is checked.
Finally hit the [ Execute ] button.
2. Move to new folder
You need to move your Address Book Plug-In AppleScript(s) from the old
~/Library/Address Book Plug-Ins/
/Library/Address Book Plug-Ins/

to a new location:
~/Library/Application Scripts/com.apple.AddressBook/


text:
Q: Using Chromecast as a security device I have google chromecast connected to my TV at home.  I am wondering if I can use it as a security device akin to auto timers that turn on and off lights in the house.
Can you play a video on the chromecast connected to a TV in the house if you are out of the house?

A: I wouldn't call it a security device. It fakes activity in the house. Chromecast wouldn't be required to do this. There are lots of people selling X10 based home networking modules which will turn off and on lights based on computer controls. The TV is only tricky because most now use soft power. X10 had solutions for driving an IR remote and all of the devices from a PC attached to one of the modules. X10 works by using the in house power grid as a carrier for its signal. it wont work across a UPS, and it wont work across the two sides of the electrical panel without a bridging module installed.


text:
Q: OS and subprocess return code 1 whenever execute shell commands with python import os
os.system('ls')

1

import subprocess
subprocess.run(['cd'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

CompletedProcess(args=['cd'], returncode=1, stdout=b'', stderr=b'')

Whenever I run these commands, my return code is 1. I tried uuninstalling and reinstalling powershell. I have python 3.9.1


text:
Q: How to fill down values with limit in R? I looking for a python function like fillna(method='bfill', limit=30) but inside R.
I have this data frame.
DATE                      ELE.CN
   <dttm>                     <dbl>
 1 2009-06-30 00:00:00 115942928608
 2 2009-06-28 00:00:00 115942928608
 3 2009-06-27 00:00:00 115942928608
 4 2009-06-26 00:00:00 115942928608
 5 2009-06-24 00:00:00           NA
 6 2009-06-23 00:00:00           NA
 7 2009-06-21 00:00:00           NA
 8 2009-06-20 00:00:00           NA
 9 2009-06-19 00:00:00           NA
10 2009-06-17 00:00:00           NA
...

The idea I have is to fill a few NAS with a limit of 30. I have searched, but have not found anything similar.
Thank you.

A: One potential solution is to use vec_fill_missing() from the vctrs package which has a "max_fill" option:
library(tidyverse)
library(vctrs)

df <- read.table(text = "DATE                      ELE.CN
 2009-06-30 00:00:00 115942928608
 2009-06-28 00:00:00 115942928608
 2009-06-27 00:00:00 115942928608
 2009-06-26 00:00:00 115942928608
 2009-06-24 00:00:00           NA
 2009-06-23 00:00:00           NA
 2009-06-21 00:00:00           NA
 2009-06-20 00:00:00           NA
 2009-06-19 00:00:00           NA
 2009-06-17 00:00:00           NA", header = TRUE)
df
#>                DATE       ELE.CN
#> 2009-06-30 00:00:00 115942928608
#> 2009-06-28 00:00:00 115942928608
#> 2009-06-27 00:00:00 115942928608
#> 2009-06-26 00:00:00 115942928608
#> 2009-06-24 00:00:00           NA
#> 2009-06-23 00:00:00           NA
#> 2009-06-21 00:00:00           NA
#> 2009-06-20 00:00:00           NA
#> 2009-06-19 00:00:00           NA
#> 2009-06-17 00:00:00           NA

df %>%
  mutate(ELE.CN = vec_fill_missing(ELE.CN, max_fill = 3))
#>                DATE       ELE.CN
#> 2009-06-30 00:00:00 115942928608
#> 2009-06-28 00:00:00 115942928608
#> 2009-06-27 00:00:00 115942928608
#> 2009-06-26 00:00:00 115942928608
#> 2009-06-24 00:00:00 115942928608
#> 2009-06-23 00:00:00 115942928608
#> 2009-06-21 00:00:00 115942928608
#> 2009-06-20 00:00:00           NA
#> 2009-06-19 00:00:00           NA
#> 2009-06-17 00:00:00           NA

Created on 2022-07-14 by the reprex package (v2.0.1)

A: Here is another suggestion, that will work on your example but could fail for a generalized approach (or must be tweaked):
library(dplyr)

df %>%
  group_by(group_id = cumsum(is.na(ELE.CN))) %>%
  ungroup() %>%
  mutate(ELE.CN = ifelse(is.na(ELE.CN) &
                           (group_id >= 0 & group_id <=30),
                         first(ELE.CN), ELE.CN), .keep="unused")

   DATE                      ELE.CN
   <chr>                      <dbl>
 1 2009-06-30 00:00:00 115942928608
 2 2009-06-28 00:00:00 115942928608
 3 2009-06-27 00:00:00 115942928608
 4 2009-06-26 00:00:00 115942928608
 5 2009-06-24 00:00:00 115942928608
 6 2009-06-23 00:00:00 115942928608
 7 2009-06-21 00:00:00 115942928608
 8 2009-06-20 00:00:00 115942928608
 9 2009-06-19 00:00:00 115942928608
10 2009-06-17 00:00:00 115942928608


text:
Q: How to optimize this Pandas code to run faster I have this code to create a swarmplot from data from a DataFrame:
df = pd.DataFrame({"Refined__Some_ID":some_id_list,
                   "Refined_Age":age_list,
                   "Name":name_list
                          }
                         )
#Creating dataframe with strings from the lists
select  = df.apply(lambda row : any([isinstance(e, str) for e in row  ]),axis=1)
#Exlcluding data from select in a new dataframe
dfAnalysis = df[~select]
dfAnalysis['Refined_Age'].replace('', np.nan, inplace=True)
dfAnalysis = dfAnalysis.dropna()
dfAnalysis['Refined_Age'] = dfAnalysis['Refined_Age'].apply(int)
# print dfAnalysis
print type(dfAnalysis['Refined_Patient_Age'][1])
g = sns.swarmplot(x = dfAnalysis['Refined_ID'],y = dfAnalysis['Refined_Age'], hue = dfAnalysis['Name'], orient="v")
g.set_xticklabels(g.get_xticklabels(),rotation=30)
# print g

It's taking a crazy amount of time to run (14 hours and counting!). How can I speed it up? Also, why is the code so slow in the first place?
The 3 lists being included in the dataframe are from a Couchdb database with about 320k documents.
UPDATE 1
I had intended to view the first 20 categories only but excluded the code to do so.
The line should have been:
x = dfAnalysis['Refined_ID'].iloc[:20]

A: Do you really mean a swarmplot with several hundred thousand points? Besides it's gonna take forever, it's nonsense. Try with the first 1000 and see what kind of mess you get. Then use a boxplot or a violinplot instead. Try to understand your tools before using them.
From the docstring:

[...] it does not scale as well to large numbers of observations (both in terms of the ability to show all the points and in terms of the computation needed
  to arrange them).


text:
Q: "AlarmReceiverChangeImage" error message in PendingIntent statement inside a method I'm trying to set up a PendingIntent inside a PreferenceActivity in a method but Eclipse displays a red underline error "AlarmReceiverChangeImage cannot be resolved to a variable". The error is on "AlarmReceiverChangeImage" which is the name of a BroadcastReceiver.
Can you tell me how to change the code so it will not give the error on "AlarmReceiverChangeImage"?
private void setRepeatingAlarm(int time_before_changing_wallpaper) {

    /*
     * Set up alarm manager and get it going.
     */
    AlarmManager myAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    PendingIntent myIntent = PendingIntent
            .getBroadcast(SettingsActivity.this, 0,
                    AlarmReceiverChangeImage, 0);

    myAlarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP, START_TIME,
            time_before_changing_wallpaper, myIntent);
}

Update:
After looking at the link provided by Kurtis I also found it will work if I made the following changes to the code.
Added this static final:
public class SettingsActivity extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {
protected static final Intent AlarmReceiverChangeImage = null;

SharedPreferences pref;

Changed the method to look like this:
private void setRepeatingAlarm(int time_before_changing_wallpaper, Intent AlarmReceiverChangeImage) {

Changed the call to the method to look like this:
                        /*
                         * Set the default wallpaper changing time of 10
                         * seconds if it has not already been set.
                         */
                        String str_list_time_before_changing_wallpaper = pref
                                .getString(
                                        "list_time_before_changing_wallpaper",
                                        "");

                        if (str_list_time_before_changing_wallpaper
                                .equals(null)) {

                            /*
                             * Set the repeating alarms.
                             */
                            setRepeatingAlarm(EVERY_10_SECONDS, AlarmReceiverChangeImage);
                        }

A: Please look at the documetnation for the getBroadcast method. You'll notice the third argument is supposed to be an Intent, not a BroadcastReciever as you're trying to do. What you need to do is create and Intent and then put a IntentFilter on your BroadcastReciever in the manifest so that your BroadcastReciever receives the Intent when ever it's broadcast.


text:
Q: Geometric progression in annuity I am working on the following problem that involves annuity which deposits form a geometric progression.

Stan elects to receive his retirement benefit over $20$ years at the rate of $2,000$ per month beginning one month from now.  The monthly benefit increases by $5\%$ each year.  At a nominal interest rate of $6\%$ convertible monthly, calculate the present value of the retirement benefit.

I understand that when the deposits are forming a geometric progression, the present value at the time of the first deposit will be an annuity-due with the appropriate interest.
So, since the deposits increase with an annual rate of $5\%$, each month the deposits increase by $r\%$ which can be calculated from
$$(1+r)^{12}=1.05$$
Hence,
$$1+r=\sqrt[12]{1.05}-1$$
Also, since the account adds a nominal interest rate of $6\%$ convertible monthly, the deposit will accumulate $i\%$ each month which can be calculated from
$$\left(1+\frac{6\%}{12}\right)=1+i$$
Hence,
$$1+i = 1.005$$
The present value at the moment of the first deposit is
$$2,000\left(1+\frac{1+r}{1+i}+\left(\frac{1+r}{1+i}\right)^2+ \dots + \left(\frac{1+r}{1+i}\right)^{239}\right)$$
(Note: there are 240 conversions in 20 years)
so,
$$2,000 \frac{1-\left(\frac{1+r}{1+i}\right)^{-240}}{1-\frac{1+r}{1+i}}$$
Using the present value factor $(1+j)^{-1}=\frac{1+r}{1+i}$ we can see that the above expression is equivalent to
$$2,000 \ddot{a}_{\overline{240}\rceil j}$$
So, according to my calculation the present value at the time of the first deposit $X$ is equal to
$$X=2,000 \ddot{a}_{\overline{240}\rceil j} \approx 430,816.22$$
Since this value is one conversion after the the very first month, I want to say that the answer to this problem must be
$$(1.005)^{-1}X \approx 428,627.86$$
However, the answer in the book is supposedly $419,253$.
I thought that I counted the number of conversions wrong, and I tried it a couple of times but it still did not give me the right answer.  Can I have some help?
Thank you.

A: I think that you're looking to simplify this expression.
$$\begin{array}{lll}
PV&=&2000\bigg[(1.005)+(1.005)^2+\dots+(1.005)^{12}\bigg]\\
&&+2000(1.05)^1\bigg[(1.005)^{12\cdot 1+1}+(1.005)^{12\cdot 1+2}+\dots+(1.005)^{12\cdot 1+12}\bigg]\\
&&+2000(1.05)^2\bigg[(1.005)^{12\cdot 2+1}+(1.005)^{12\cdot 2+2}+\dots+(1.005)^{12\cdot 2+12}\bigg]\\
&&\dots\\
&&+2000(1.05)^{19}\bigg[(1.005)^{12\cdot 19+1}+(1.005)^{12\cdot 19+2}+\dots+(1.005)^{12\cdot 19+12}\bigg]\\
\end{array}$$

A: What I think you are looking for is the present value of a growing annuity.

*

*Your problem says that your nominal interest rate is 6%, you will have to find the effective interest rate:

$$r=(1+\frac{r_n}{12})^{12}-1$$
$$0.061678=(1+\frac{0.06}{12})^{12}-1$$

*Then you can find the present value of the annuity:

$$PV=C\left(\frac{1}{r-g}\right)\left(1-\left(\frac{1+g}{1+r}\right)^N\right)$$
$$429607.68=2000\left(\frac{1}{(\frac{0.061678}{12})-(\frac{0.05}{12})}\right)\left(1-\left(\frac{1+\frac{0.05}{12}}{1+\frac{0.061678}{12}}\right)^{240}\right)$$
I still don't get the same answer than your book. However, I didn't try converting everything to a yearly payment. Calculate it rather than on 240 \$2000 payments, on 20 \$x payments.


text:
Q: Remove & add split-list using dictionary python for iterate in message_split:
   if(iterate == emotion):
      message_split.remove(iterate)
       message_split = emotion.get(" ", "!")

I tried to remove and add on the same index after taking input from user using split function but it's returning the split list instead of running for loop. i want to replace the iterate with emotion key value


text:
Q: Showing multiple templates within a single modal dialog I am using bootstrap modal dialog in ember.
I render it as a view from the controller.
this.set("modalView", app.AddModalView.create({
controller: this,
templateName: "firstModalScreen"
}));
this.get("modalView").append();

My problem is that I want to show another template in this view upon some action in this first template. For Example, choosing something in firstModalScreen takes you to the details of the particular chosen item and should render say, secondModalScreen.
The behavior is just like navigating from one route to another but I want to achieve this within the modal dialog. What is the best way to do this?
I could hide the first modal and then render it again with another template, but that causes an unnecessary close and open of same dialog.

A: You could replace the content within the modal. I've done this before by simply adding a boolean and having handlebars display certain content. If you want to show more than 2 screens, you might have to use a number and extend a handlebars function that can be use a switch statement to test for different values to show different content

A: I was working on a similar feature recently. I ended up solving it using Ember's Container View nested in a {{view}} helper inside the modal view. You can check out my JSBIN at  http://emberjs.jsbin.com/ruzog/5/edit, or the whole ramble at  https://stackoverflow.com/questions/21733148/swapping-a-child-template-within-a-modal
EDIT:
Upated example:http://emberjs.jsbin.com/ruzog/6/edit
Here's the crucial bit of code. The container view observes a property on the shared context. As user activity alters the state of the model, the container view will dynamically update it's content with a new template/view/controller.
App.ChildContainerView = Ember.ContainerView.extend({
  classNames: ['child-div'],
  didInsertElement: function() {
    this.updateContent();
  },

  updateContent: function() {
    console.log('Update content');
    this.removeObject(this.get('childViews')[0]);
    if(this.get("context.name") == "Jimi"){
      this.pushObject(App.ModalChildView.create());
    } else {
      this.pushObject(App.AlternateChildView.create());
    }
  }.observes('context.name')
});


text:
Q: flink+Kafka: getHostnamePort I want to read a kafka topic from flink
package Toletum.pruebas;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer082;
import org.apache.flink.streaming.util.serialization.SimpleStringSchema;

public class LeeKafka {
  public static void main(String[] args) throws Exception {
    final ParameterTool parameterTool = ParameterTool.fromArgs(args);

    // create execution environment
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

      FlinkKafkaConsumer082<String> kafkaSrc = new FlinkKafkaConsumer082<String>("test02",
      new SimpleStringSchema(),
      parameterTool.getProperties());

      DataStream<String> messageStream = env.addSource(kafkaSrc);

    messageStream.rebalance().map(new MapFunction<String, String>() {
      private static final long serialVersionUID = -6867736771747690202L;

      public String map(String value) throws Exception {
        return "Kafka and Flink says: " + value;
      }
    }).print();

    env.execute("LeeKafka");
  }

}

this code works successfully:
java -cp Package.jar Toletum.pruebas.LeeKafka --topic test02 --bootstrap.servers kafka:9092 --zookeeper.connect zookeeper:2181 --group.id myGroup

But, when I try use from flink:
flink run -c Toletum.pruebas.LeeKafka pruebas-0.0.1-SNAPSHOT-jar-with-dependencies.jar --topic test02 --bootstrap.servers kafka:9092 --zookeeper.connect zookeeper:2181 --group.id myGroup

I get an error:

java.lang.NoSuchMethodError: org.apache.flink.util.NetUtils.getHostnamePort(Ljava/lang/String;)Ljava/net/URL;
        at org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer.getPartitionsForTopic(FlinkKafkaConsumer.java:592)
        at org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer.(FlinkKafkaConsumer.java:280)
        at org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer082.(FlinkKafkaConsumer082.java:49)
        at Toletum.pruebas.LeeKafka.main(LeeKafka.java:22)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.flink.client.program.PackagedProgram.callMainMethod(PackagedProgram.java:497)
        at org.apache.flink.client.program.PackagedProgram.invokeInteractiveModeForExecution(PackagedProgram.java:395)
        at org.apache.flink.client.program.Client.runBlocking(Client.java:252)
        at org.apache.flink.client.CliFrontend.executeProgramBlocking(CliFrontend.java:676)
        at org.apache.flink.client.CliFrontend.run(CliFrontend.java:326)
        at org.apache.flink.client.CliFrontend.parseParameters(CliFrontend.java:978)
        at org.apache.flink.client.CliFrontend.main(CliFrontend.java:1028)

A: Old version lib.....
Correct pom.xml:

            &ltdependency&gt
                    &ltgroupId&gtorg.apache.flink&lt/groupId&gt
                    &ltartifactId&gtflink-connector-kafka&lt/artifactId&gt
                    &ltversion&gt0.10.1&lt/version&gt
            &lt/dependency&gt

A: This problem is due to using the old version of FLink Connector library.
You can check the latest available library and download the latest Maven Dependency.
The Kafka version you are using should also be considered.
Try using latest Maven dependency from Flink Documentation for Kafka Connector
The latest maven dependency is
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-connector-kafka-0.8_2.10</artifactId>
  <version>1.3.2</version>
</dependency>


text:
Q: De-mystifying tricks in proof – If $\{x_n\}$ converges, then Cesaro Mean converges. Stephen Abbott. Understanding Analysis (2016 2 edn). p. 55. Not a duplicate.

Exercise 2.3.11 (Cesaro Means). (a) Show if $\{x_n\}$ is a convergent sequence, then the sequences given by the averages $\{\dfrac{x_1 + x_2 + ... + x_n}{n}\}$ converges to the same limit. (Not a duplicate)

I rewrote and colored the official solution.

Let $\epsilon>0$ be arbitrary. Then we need to find an $N \in \mathbb{N} \qquad  \ni n \geq N \implies\ |\frac{x_1 + x_2 + ... + x_n}{n} - L|< \epsilon \tag{1}$.
Question posits $(x_{n}) \to L$. So $\exists \; M \in \mathbb{N} \ni n \ge M \implies |x_{n}-L|< M \quad (2)$.
$\text{Also } \exists \; C \ni n \ge C \implies |x_{n}-L|< \epsilon/2. \quad \tag{3}$

My question 1. Where does (3) issue from? How to presage $\epsilon/2$?  Normally you start with $\epsilon$.

*Doesn't the same argument prove all the terms can be bounded? Why simply 'the early terms in the averages can be bounded' ? Please expatiate on "Because the original sequence is convergent, we suspect that we can bound ... we will be breaking the limit in two at the end" ?
I still don't understand how "we suspect" these bounds?

Now for all $n \ge C$, we can write

*How to presage rewriting $\color{red}{L = nL/n}?$

*How to presage spltting the sum between $x_{C - 1}$ and $x_C$?
Now apply the Triangle Inequality to each of the $n$ $(x_i - L)$ terms.

$\begin{align}
        \le & \frac{1}{n}( & \color{green}{\left| x_{1}-L\right| +\ldots +\left| x_{c-1}-L\right|}  & + \color{brown}{\left| x_{C}-L\right| +\ldots +\left| x_{n}-L\right|} & )\\
    & & \color{green}{\text{Each of these $(C - 1)$ terms < M by (2)} } & \color{brown}{ \text{ Each of these $(n - C)$ terms < $\epsilon/2$ by (3)}} & \\
\le & \frac{1}{n}( & \color{green}{(C - 1)M} & + \color{brown}{\frac{e}{2}(n - C)} & ). \tag{4}\\
\end{align}$

*Why is the last inequality (4) above $\le$? Why not $<$ like (2) and (3)?

Because C and M are fixed constants at this point, we may choose $N_2$ so that
  $\color{green}{(C - 1)M}\frac{1}{n}  < e/2 \tag{5}$ for all $n \ge N_2$. Finally, let $N$ [in $(1)$]  $= \max\{C, N_2\}$ be the desired $N$.

*Why are we allowed to choose $N_2$ so that $\color{green}{(C - 1)M}\frac{1}{n} < e/2$?

$C \in \mathbb{N} \quad \therefore n - C < n \iff \color{magenta}{\frac{n - C}{n}} < 1 \tag{6}$
$\begin{align}
\text{Equation (4) is} &  & \color{green}{(C - 1)M}\frac{1}{n}  & + \frac{e}{2}\color{magenta}{\frac{n - C}{n}}. \\
\text{Then by (5) and (6),} & & < e/2 & + e/2\color{magenta}{(1)}/  QED. \\
\end{align}$

A:
1. Where does (☺) issue from? Did solution rewrite M in (♪) as C? How to presage $e/2$ ?
  Cesaro means is $\dfrac{a_1 + ... + a_n }{n }$. n is fixed. Ergo how can we choose $K$?
  And what's $l$?
1.1. Your 2e last sentence : " we can bound the later terms using the convergence of the $\color{Red}{regular}$"
  I don't understand. Should there be words after $\color{Red}{regular}$?

Both (☺) and (♪) come from the definition of the limit. The usage of $C$ corresponds to the upper bound $e/2$, while $M$ is used for the upper bound $M$.  To presage $e/2$, consider that for any fixed sum $\dfrac{a_1+\dots+a_\ell}{K} \leq \dfrac{\ell}{K}\max_i(a_i)$, we can choose $K$ to make the fraction arbitrarily small. Here $\ell$ is an arbitrary index chosen so as not to be involved in the problem directly.  For any $\varepsilon>0$ if we choose $\dfrac{l}{K} < \varepsilon \iff K>\ell/\varepsilon$, then the sum $\dfrac{a_1+\dots+a_\ell}{K} <\varepsilon$.  Hence, the early terms in the averages can be bounded. Because the original sequence is convergent, we suspect that we can bound the later terms using the convergence of the regular sequence (the word sequence was omitted in an earlier edit by mistake). Hence, we suspect that we will be breaking the limit in two at the end, so we will want $e/2$ for bound.
As a note, if I were writing the proof, I would write the proof with all my bounds $\eta$ and then choose $\eta$ to make the conclusion match the arbitrary $\epsilon$.

2. How to presage feyly to rewrite $\color{red}{L = nL/n}?$
  I know question posits $\{x_n\}$ is a convergent sequence.
  But I'm nonplussed why 'we would like to compare each term to the limit' ?

We should compare the sequence to the limit because that is the only number to which a meaningful comparison can be made. The sequence may behave arbitrarily with the exception that it converges to some limit $L$.
As we saw in the first part, we suspect that we should break the sum into two parts. Because the sequence is convergent, we would like to compare each term to the limit. To do so we use the rules of algebra to put $L$ on a common denominator, or equivalently, write $nL/n$.

3. How to presage presciently to split the sum between $x_{C - 1}$ and $x_C$ ?

Continuing the argument from the first part, we break the sum into two pieces at an arbitrary point $C$. Then we simplify the fractions, and bound them using the technique from part 1.

4. I know we want the bound to behave, but what or who sanctioned us to choose $N_2$ and to invoke $\color{green}{(C - 1)M}\frac{1}{n} < e/2$? We can't just choose whatever we want?

Because we want the result to be true in the limit we must show that for all sufficiently large $n$, the bound holds.  We choose $N_2$ to make the fraction resulting from the early terms of the series small.  The number $N_2$ is an arbitrary number, with the only requirement that it be large enough to guarantee that the fraction is sufficiently small.

5. Shouldn't this last line start with $<$?

If you are referring to the line given by the triangle inequality, then we must put '$\leq$' because that is all the triangle inequality gives.  The next line is strict inequality for appropriate choices of $M$ and $C$.


text:
Q: Making second api call after first api call returns data I have two seperate functions that make API calls to different endpoints for return JSON Data using BlueBirdPromise.
 const searchVenues = (type) => {
  logger.debug('getVenues : type = ' + type);

  const config = {
    url: urlAPIServer + '/venue/available',
    qs: {
      type,
    },
    headers: {
      'x-api-key': dataApiKey
    }
  };

  return new BluebirdPromise((resolve, reject) => {
    request.get(config, (err, response, body) => {
      if (err) {
        console.error(err);
        reject(err);
      } else {
        resolve(JSON.parse(body));
      }
    });
  });
};

const getVenuesWithCuisine = () => {
  logger.debug('getVenuesWithCuisine');

  const config = {
    url: urlAPIServer + '/venue/viewvenuewithcuisine',
    headers: {
      'x-api-key': dataApiKey
    }
  };

  return new BluebirdPromise((resolve, reject) => {
    request.get(config, (err, response, body) => {
      if (err) {
        console.error(err);
        reject(err);
      } else {
        resolve(JSON.parse(body));
      }
    });
  });
};

Invoking the funtions seperately to get the data from the API and bind it to variable.
searchVenues(venueType).then((venues) => {
      checkContextTimeout(context);
      conversationContext.venueType = venueType;
      conversationContext.venues = venues;
      context.skill = conversationContext;
    });

    getVenuesWithCuisine().then((venueswithcuisines) => {
      conversationContext.venue_details = venueswithcuisines[0}["venue_details"];
      conversationContext.cuisines = venueswithcuisines[1]["cuisines"];
      conversationContext.venueType = venueType;
      conversationContext.venues = venuesJson.venues;
      continueConversation(request, response, context);
    });

The problem with above implementation is, if for some reason getVenuesWithCuisine completed first before searchVenues the continueConversation is getting invokes making           conversationContext.venues = venues as null.
How can i make these API calls synchronous so that the second API call is made only after the first one returns data.

A: You can use Promise.all instead of doing it synchronously. That will resolve once both of your promises resolve and give you the results.
http://bluebirdjs.com/docs/api/promise.all.html
Promise.all([searchVenues(venueType), getVenuesWithCuisine()]).then(function([venueResp, cuisineResp]) {
  ...
});


text:
Q: php include breaking I have a php page that generates all the html and echo's it. Now I want to write a php script that I can use include to handle the footer code. that way if I need to update the footer on all the pages I can just edit the code in the included page.
But when I use include("footer.php"); and the footer page contains the footer code that works if it exists on the page it breaks and prints the code. Im very confused as too why?
  if(isset($_SESSION['user_cart']) && count($_SESSION['user_cart']) > 0)

Starts writing the code on the page if I include from  0)
Please help?
EDIT: The code in the footer is wrapped in <?php   ?>

A: You need to wrap that code in footer.php with php tags.
<?php

 if(isset($_SESSION['user_cart']) && count($_SESSION['user_cart']) > 0) ...

?>

A: Dont your short hand notation of php tags <? ?>, use <?php ?>instead...

A: It sound like you didn't start php file with
<?php

A: Please make sure that your footer file has <?php in the beginning.

A: I'm not sure if you stated your question very clearly.
If you are echoing code out it will appear as soon as you include the file. Your file should look like this:
<?php require_once 'header.php';
// content goes here
require_once 'footer.php'; ?>


text:
Q: PHP Azure Storage - on Table update I get: Server failed to authenticate the request Hello mighty Windows Azure developers,
I am using PHP SDK for Windows Azure in eclipse working with storage table on local compute and storage emulator
I am running this code (basically I am updating data):
$statistics = AzureStorageTable::connection()->retrieveEntities(self::$statisticsTableName);
    foreach($statistics as $statistic) {
        $block = $statistic->getRowKey();
        if(isset($processedLogs[$block])) {
            $processedLog = $processedLogs[$block];
            $statistic->time    = ($statistic->time + $processedLog[0]);
            $statistic->count   = ($statistic->count + $processedLog[1]);
            $statistic->average = ($statistic->time / $statistic->count);
            AzureStorageTable::connection()->updateEntity(self::$statisticsTableName,$statistic);
        }
    }

I get:

Microsoft_WindowsAzure_Exception
Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

It fails here in the SDK:
Storage/Table.php (615) Microsoft_WindowsAzure_Storage_Table-> _changeEntity
The entity object looks like this:
Microsoft_WindowsAzure_Storage_DynamicTableEntity(5) ▼ {
   "_dynamicProperties" protected => array(4) ▼ {
      "timestamp" => stdClass(3) ▼ {
         "Name" => "Timestamp" (9)
         "Type" => "Edm.DateTime" (12)
         "Value" => DateTime(3) { ... }
      }
      "time" => stdClass(3) ▼ {
         "Name" => "time" (4)
         "Type" => "Edm.Double" (10)
         "Value" => 95.899748802185
      }
      "count" => stdClass(3) ▼ {
         "Name" => "count" (5)
         "Type" => "Edm.Int32" (9)
         "Value" => 44
      }
      "average" => stdClass(3) ▼ {
         "Name" => "average" (7)
         "Type" => "Edm.Double" (10)
         "Value" => 2.1795397455042
      }
   }
   "_partitionKey" protected => "timers" (6)
   "_rowKey" protected => "%2F" (3)
   "_timestamp" protected => DateTime(3) ▼ {
      "date" => "2012-04-20 22:51:50" (19)
      "timezone_type" => 3
      "timezone" => "UTC" (3)
   }
   "_etag" protected => "W/"datetime'2012-04-20T22%3A51%3A50.483Z'"" (42)
}

I had the same error also when trying to delete an entity.
I have tried to create the table entity instead of getting it from the storage and then using the same object for update but it doesn't work.
I know that there might be some issue with time according to googling but my time on my system is right (I am UTC+1). Somehow the time stamp in storage is 2 hours behind the actual time but I don't know what to do about it.
I do have Fiddler2 but I have no idea how to set it up to catch communication with http://127.0.0.1:10002 (local table storage).
Any idea what I am doing wrong please?

A: Like you already said, the issue could be related to your system's clock not being configured correctly. But the Make sure the value of Authorization header is formed correctly including the signature. error could be caused by an other reason.
Trying with Fiddler2 is your best option at the moment. You could try setting Fiddler2 as proxy in your web.config (I suppose you have one even though you're working with PHP):
<system.net>
  <defaultProxy>
    <proxy bypassonlocal="False" proxyaddress="http://127.0.0.1:8888"/>
  </defaultProxy>
</system.net>

Are you using the HTTP or HTTPS endpoint for table storage? If you're using HTTPS, you'll also need to make sure Fiddler also decrypts HTTPS traffic (via Tools > Fiddler Options).

A: So... it is a bug in PHP Azure SDK from: http://phpazure.codeplex.com/
I told the developers about it here: http://phpazure.codeplex.com/workitem/6901
I am adding the solution here as well:
The problem is that when I call this:
$entity = $storage -> retrieveEntities($tableName);
$entity -> Name = "New name;"
$storage -> updateEntity($tableName,$entity);

it fails giving me Microsoft_WindowsAzure_Exception Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
The problem is that the result of retrieveEntities is *Microsoft_WindowsAzure_Storage_DynamicTableEntity* and then updateEntity calls on it getAzureValues and both *$this->_dynamicProperties* and parent::getAzureValues() return timestamp which leads to an array with two timestamps which leads to the error
hot fix I made was adding this code:
if(isset($this->_dynamicProperties["timestamp"]))unset($this->_dynamicProperties["timestamp"]);

on the line before return in getAzureValues in *Microsoft_WindowsAzure_Storage_DynamicTableEntity*
and then it works as a magic :]
this error is both in the old SDK and in the latest SDK from trunk


text:
Q: Check number input field only have 8 digits and starts with number 2 I have an input field which already force a user to enter 8 digits, but i want to force him to enter the digits starts with 2 as give him an alert when enter the first number wrong, if he wrote 2 then let him enter the rest of number.
here is my code :
HTML
<input type="number" maxlength="8"  class="form-control myInput" name="myInput" id="myInput" placeholder="myInput" pattern="\d{8}" required>
</div>

JQuery
$(".myInput").unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this) ,val = $this.val(),valLength = val.length, maxCount = $this.attr('maxlength');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
});

Please help.

A: here is my solution
Jquery
$("#myInput").on('keypress', function(){
            var numbers = $(this).val().trim();
            if(numbers[1]){
              if(numbers[0] != '2' || numbers.length > 8){
                $(this).val('');
                $('.error').html("Error the input has to start with number 2 and has to be lesser than 8 numbers");
              }else{
                $('.error').html("Good");
              }
            }
          });

html
<input type="number" maxlength="8" id="myInput" required>
<div class='error'>

</div>

This is just an example feel free to adjust anything, i removed some tags and stuff but you can re add them this is just to show you how to do
So the script checks if 2numbers have been entered if yes it checks if the first one is 2 if not it shows err message and reset input value else it writes good
Here is the fiddle
https://jsfiddle.net/qh7gwecc/3/


text:
Q: Fastest Method to Format I have a Python 2.7 script that transforms various data and outputs it to an XLSX via OpenPyXL 2.4.5.  Currently I'm iterating through all the cells, which I've narrowed down using "max_row" and "max_column".  This doesn't appear very fast or efficient to me.  What's the fastest way to set the following?   If you could suggest general methodologies, I would appreciate it.  The rough benchmarks below are for Windows 7 SP1 x64 with 16 GB RAM and an Intel i7-3740QM@2.69 GHz.

*

*Borders (Formatting 35880 cells takes 40s.)

*Fonts and Alignment (Formatting 35880 cells takes 42s.)

*Shading (Formatting 35880 cells takes 28s.)

*Hiding Unused Row/Column (Hiding 16,380 columns x 1,039,606 rows takes many minutes.  Hiding only the columns takes .2s.)

Below is the iteration methodology.
def format_xlsx(csv_list, ws_to_format):
    """ Use OpenPyXL to format a XLSX. """
    process_start = timer()
    for row in csv_list:
        count = count + 1
        ws_to_format.append(row)
    row_count = ws_to_format.max_row
    column_count = ws_to_format.max_column
    for y_axis in range(1, column_count+1):
        for x_axis in range(1, row_count+1):
            ws_to_format = xlsx_borders(ws_to_format, x_axis, y_axis)
            ws_to_format = xlsx_shading(ws_to_format, x_axis, y_axis)
            ws_to_format = xlsx_font_and_alignment(ws_to_format, x_axis, y_axis)
    ws_to_format = xlsx_hide_unused_colrow(ws_to_format)
    return

Below is the methodology to hide unused rows/columns.
def xlsx_hide_unused_colrow(ws_to_format):
    row_count = ws_to_format.max_row
    column_count = ws_to_format.max_column
    start_range = column_number_to_letter(column_count+2)
    end_range = column_number_to_letter(16384)
    ws_to_format.column_dimensions.group(start_range, end_range, hidden=True)
    start_range = row_count+2
    for y in xrange(start_range, 1048577):
        ws_to_format.row_dimensions[y].hidden=True

A: You should never call ws.max_row or ws.max_column within loops as they are calculated every time they're called. As the size of the worksheet is not changing during your work, then they only need to be called once.
Furthermore, applying styles to row and column dimensions probably won't do what you expect it to do, please refer to the documentation about this. You need to apply the styles to the cells in the relevant rows and columns. And use named styles if you have a lot of cells to format.


text:
Q: Android Studio how can I Do different task for single and double back button press There are a lot of answers on "Clicking the back button twice to exit an activity" and similar things but what I am trying to do with my project is that I want to do different things for single and double click of back button
For example in my case I want to go to Home screen / Main activity of my app if the back button is pressed once and simultaneously show a toast " Press Back Again To Exit " and if the user do that the app does just that .
I am really struggling to write a code for this
I have tried this but it doesn't work as intended , with this even on double press the app doesnt exit .
Any help is appreciated .
My code
enter code here
private static final int TIME_INTERVAL = 2000;
    private long mBackPressed;
 public void onBackPressed() {
 if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
            {
                super.onBackPressed();
                return;
            }

            else {
                Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
}
 mBackPressed = System.currentTimeMillis();

A: You are on the right track, however its because you are setting mBackPressed = System.currentTimeMillis(); every time the back button is pressed, so it will never pass the first if statement you have. It seems also as if you want to track how many times they've clicked the back button.
Try this,
private static final int TIME_INTERVAL = 2000;
private long mBackPressed = -1;
private int clicks = 0;

public void onBackPressed() {
    if (mBackPressed == -1) //checks if the time hasnt been set yet
        mBackPressed = System.currentTimeMillis();
    clicks++; //or you can put this in the if statement below
    if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
        super.onBackPressed();
        return;
    } else {
        Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        mBackPressed = -1; //resets the time the click was made
        clicks = 0; //resets the clicks
    }
}

A: this method might be a simple solution :
@Override
public void onBackPressed() {
     private final static int TIME_INTERVAL = 500;
     long backPressed = 0L;

     if ((System.currentTimeMillis() - backPressed < TIME_INTERVAL))
            System.exit(0); // do what you want on double click
     else {
            backPressed = System.currentTimeMillis();
            getSnackbar(R.string.double_back_press_message,Snackbar.LENGTH_SHORT).show();
            super.onBackPressed();
      }
}


text:
Q: regarding the output of counting the unique numbers of multi-dimension array There is a multi-dimensional array generated from a prediction model. I would like to check the values of this array. Here is my code.
    print('Predictions shape ',predictions.shape)
    unique_items, counts = np.unique(predictions,return_counts=True)
    print('unique_items ',unique_items)
    print('counts ',counts)

This is the result. I do not quite understand the output item marked with yellow. Why it cannot give the exact value instead of 1.... Thanks.

A: This is just the print output of a numpy array.
You can set the linewidth and edgeitems yourself numpy.set_printoptions
Try this:
import numpy as np

np.set_printoptions(linewidth=1000, edgeitems=5)

predictions = np.random.rand(3249, 4096, 2)

print('Predictions shape ',predictions.shape)
unique_items, counts = np.unique(predictions,return_counts=True)
print('unique_items ',unique_items)
print('counts ',counts)

Another way would be to convert np.array to list and print that (docs)
# beware, this takes like forever :)
print('unique_items ',unique_items.tolist())
print('counts ',counts.tolist())


text:
Q: Using Interfaces in Kohana 3.1.3 I'm trying to build a form wizard in Kohana and am learning a bit as I go. One of the things that I've learn might work best is utilizing a state pattern in my class structure to manage the different steps a user can be in during the form process.
After doing some research, I've been thinking that the best approach may be to use an interface and have all of the steps act as states that implement the interface. After a state validates, it will change a session variable to the next step, which can be read upon the initial load of the interface and call the correct state to use.
Does this approach make sense? If so, how the heck do I make it happen (how do I best structure the filesystem?)
Here is the rough start I've been working on:
<?php defined('SYSPATH') or die('No direct script access.');

/**
* Project_Builder @state
* Step_One @state
* Step_Two @state
**/

interface Project_Builder
{
    public function do_this_first();
    public function validate();
    public function do_this_after();
}

class Step_One implements Project_Builder {

    public function __construct
    {
        parent::__construct();

        // Do validation and set a partial variable if valid

    }

    public function do_this_first()
    {
        echo 'First thing done';
        // This should be used to set the session step variable, validate and add project data, and return the new view body.
            $session->set('step', '2');

    }
    public function do_this_after()
    {
        throw new LogicException('Have to do the other thing first!');
    }

}

class Step_Two implements Project_Builder {
    public function do_this_first()
    {
        throw new LogicException('Already did this first!');
    }
    public function do_this_after()
    {
        echo 'Did this after the first!';
        return $this;
    }
}

class Project implements Project_Builder {
    protected $state;
    protected $user_step;
    protected $project_data

    public function __construct()
    {
        // Check the SESSION for a "step" entry. If it does not find one, it creates it, and sets it to "1".
        $session = Session::instance('database');

        if ( ! $session->get('step'))
        {
            $session->set('step', '1');
        }

        // Get the step that was requested by the client.
        $this->user_step = $this->request->param('param1');

        // Validate that the step is authorized by the session.
        if ($session->get('step') !== $this->user_step)
        {
            throw new HTTP_Exception_404('You cannot skip a step!');
        }

        // Check if there is user data posted, and if so, clean it.
        if (HTTP_Request::POST == $this->request->method())
        {
            foreach ($this->request->post() as $name => $value)
            {
                $this->project_data["$name"] = HTML::chars($value);
            }
        }

        // Trigger the proper state to use based on the authorized session step (should I do this?)
        $this->state = new Step_One;
    }
    public function doThisFirst()
    {
        $this->state = $this->state->do_this_first();
    }
    public function doThisAfter()
    {
        $this->state = $this->state->do_this_after();
    }
}

$project = new Project;
try
{
    $project->do_this_after(); //throws exception
}
catch(LogicException $e)
{
    echo $e->getMessage();
}

$project = new Project;
$project->do_this_first();
$project->validate();
$project->do_this_after();
//$project->update();

A: Your way certainly looks possible, however I would be tempted to keep it simpler and use some of Kohanas build in features to take care of what you want. For example, I would use Kostache (mustache) and have separate View classes (and potentially templates) for each step. Then the controller becomes quite simple. See the example below (missing session stuff and validation of the step_number). All of the validation is handled in the model. If there is a validation error, an exception can be thrown which can then pass error messages back to the View.
<?php

class Wizard_Controller {

    function action_step($step_number = 1)
    {
        $view = new View_Step('step_' + $step_number);

        if ($_POST)
        {
            try
            {
                $model = new Model_Steps;
                $model->step_number = $step_number;
                if ($model->save($_POST))
                {
                    // Go to the next step
                    $step_number++;
                    Request::current()->redirect('wizard/step/'.$step_number);
                }
            }
            catch (Some_Kind_Of_Exception $e)
            {
                $view->post = $_POST;
                $view->errors = $e->errors();
            }
        }

        $view->render();
    }
}
?>

Hope this makes sense.


text:
Q: Is there any option in Highcharts for simplifyng a line graph? I´m setting up a preview for a graph, and I want to know if highcharts has any option for reducing the number of points showed in a series. I have points everyday in 5 years, and I would like to reduce for a simple preview. Is this possible?

A: You can reduce the number of points by your own function, but I think that the best solution will be to use provided by Highstock dataGrouping feature:
series: [{
    dataGrouping: {
        enabled: true
    },
    data: [...]
}]

Live demo: http://jsfiddle.net/BlackLabel/3ky0s2oh/
API Reference: https://api.highcharts.com/highstock/plotOptions.series.dataGrouping.enabled
Docs: https://www.highcharts.com/docs/stock/data-grouping