text:
Q: Admin-On-REST custom REST client fails to compile After starting with the Admin-On-REST Tutorial I tried to bind the app to my existing ArangoDB backend with a custom REST-Client implementation.
The backend exposes a simple auto-generated "default" FOXX HTTP API.
That basically worked with the simple client. For better integration I'm aiming for using a custom client based on the json client. Therefore I copied the admin-on-rest/src/rest/jsonServer.js file into my project. I modified it to that file content:
import { stringify } from 'query-string';
import { fetchJson, flattenObject } from 'admin-on-rest';
import {
    GET_LIST,
    GET_ONE,
    GET_MANY,
    GET_MANY_REFERENCE,
    CREATE,
    UPDATE,
    DELETE,
} from 'admin-on-rest';

/**
 * Maps admin-on-rest queries to a json-server powered REST API
 *
 * @see https://github.com/typicode/json-server
 * @example
 * GET_LIST     => GET http://my.api.url/posts?_sort=title&_order=ASC&_start=0&_end=24
 * GET_ONE      => GET http://my.api.url/posts/123
 * GET_MANY     => GET http://my.api.url/posts/123, GET http://my.api.url/posts/456, GET http://my.api.url/posts/789
 * UPDATE       => PUT http://my.api.url/posts/123
 * CREATE       => POST http://my.api.url/posts/123
 * DELETE       => DELETE http://my.api.url/posts/123
 */
export default (apiUrl, httpClient = fetchJson) => {
    /**
     * @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
     * @param {String} resource Name of the resource to fetch, e.g. 'posts'
     * @param {Object} params The REST request params, depending on the type
     * @returns {Object} { url, options } The HTTP request parameters
     */
    const convertRESTRequestToHTTP = (type, resource, params) => {
        let url = '';
        const options = {};
        switch (type) {
            case GET_LIST: {
                const { page, perPage } = params.pagination;
                const { field, order } = params.sort;
                const query = {
                    ...flattenObject(params.filter),
                    _sort: field,
                    _order: order,
                    _start: (page - 1) * perPage,
                    _end: page * perPage,
                };
                url = `${apiUrl}/${resource}?${stringify(query)}`;
                break;
            }
            case GET_ONE:
                url = `${apiUrl}/${resource}/${params.id}`;
                break;
            case GET_MANY_REFERENCE: {
                const { page, perPage } = params.pagination;
                const { field, order } = params.sort;
                const query = {
                    ...flattenObject(params.filter),
                    [params.target]: params.id,
                    _sort: field,
                    _order: order,
                    _start: (page - 1) * perPage,
                    _end: page * perPage,
                };
                url = `${apiUrl}/${resource}?${stringify(query)}`;
                break;
            }
            case UPDATE:
                url = `${apiUrl}/${resource}/${params.id}`;
                options.method = 'PUT';
                options.body = JSON.stringify(params.data);
                break;
            case CREATE:
                url = `${apiUrl}/${resource}`;
                options.method = 'POST';
                options.body = JSON.stringify(params.data);
                break;
            case DELETE:
                url = `${apiUrl}/${resource}/${params.id}`;
                options.method = 'DELETE';
                break;
            default:
                throw new Error(`Unsupported fetch action type ${type}`);
        }
        return { url, options };
    };

    /**
     * @param {Object} response HTTP response from fetch()
     * @param {String} type One of the constants appearing at the top if this file, e.g. 'UPDATE'
     * @param {String} resource Name of the resource to fetch, e.g. 'posts'
     * @param {Object} params The REST request params, depending on the type
     * @returns {Object} REST response
     */
    const convertHTTPResponseToREST = (response, type, resource, params) => {
        const { headers, json } = response;
        switch (type) {
            case GET_LIST:
            return {
                data: json.map((obj) => {
                  obj.id = obj._key;
                  delete obj['_key'];
                  return obj;
                }),
                total: headers.get('X-Total-Count')
            };
            case GET_MANY_REFERENCE:
                if (!headers.has('x-total-count')) {
                    throw new Error(
                        'The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Expose-Headers header?'
                    );
                }
                return {
                    data: json,
                    total: parseInt(
                        headers
                            .get('x-total-count')
                            .split('/')
                            .pop(),
                        10
                    ),
                };
            case CREATE:
                return { data: { ...params.data, id: json.id } };
            default:
                return { data: json };
        }
    };

    /**
     * @param {string} type Request type, e.g GET_LIST
     * @param {string} resource Resource name, e.g. "posts"
     * @param {Object} payload Request parameters. Depends on the request type
     * @returns {Promise} the Promise for a REST response
     */
    return (type, resource, params) => {
        // json-server doesn't handle WHERE IN requests, so we fallback to calling GET_ONE n times instead
        if (type === GET_MANY) {
            return Promise.all(
                params.ids.map(id => httpClient(`${apiUrl}/${resource}/${id}`))
            ).then(responses => ({
                data: responses.map(response => response.json),
            }));
        }

        const { url, options } = convertRESTRequestToHTTP(
            type,
            resource,
            params
        );

        return httpClient(url, options).then(response =>
            convertHTTPResponseToREST(response, type, resource, params)
        );
    };
};

It's much like the original - I only edited:

*

*the import section at the top

*the convertHTTPResponseToRESTmethod for the GET_LIST section.

Finally I bound it into the App by importing it through the App.js file so that it looks like:
import CustomRestClientJson from './CustomRestClientJson'

const App = () => (
    <Admin restClient={CustomRestClientJson('http://localhost:8529/_db/orgraph/admin')}>
      <Resource name="assets" list={AssetList} />
    </Admin>
);

The problem is that:
a.) either the App fails in the browser with an Object(...) is not a function error (thrown by the call to the ...flattenObject(params.filter) call from within the clients convertRESTRequestToHTTP method) while trying to load the data.
b.) or the yarn build / compilation fails when I change the import statements of my client from:
import { stringify } from 'query-string';
import { fetchJson, flattenObject } from 'admin-on-rest';
import {
    GET_LIST,
    GET_ONE,
    GET_MANY,
    GET_MANY_REFERENCE,
    CREATE,
    UPDATE,
    DELETE,
} from 'admin-on-rest';

to:
import { stringify } from 'query-string';
import { fetchJson, flattenObject } from 'admin-on-rest/src/util/fetch';
import {
    GET_LIST,
    GET_ONE,
    GET_MANY,
    GET_MANY_REFERENCE,
    CREATE,
    UPDATE,
    DELETE
} from 'admin-on-rest/src/rest/types';

with the following error:
Failed to compile.

./node_modules/admin-on-rest/src/util/fetch.js
Module parse failed: Unexpected token (20:24)
You may need an appropriate loader to handle this file type.
|     }
|
|     return fetch(url, { ...options, headers: requestHeaders })
|         .then(response =>
|             response.text().then(text => ({

So, as I'm not a React programmer I'd love to hear about how I could fix this issue to be able to bind to my backend for further testing.
;-)
Thanks for any tips!

A: I haven't read the whole description, but the error you got should be resolved by changing
import { fetchJson, flattenObject } from 'admin-on-rest/src/util/fetch';
to:
import { fetchJson, flattenObject } from 'admin-on-rest/lib/util/fetch';
Your project's babel will not transpile any code under node_modules. Whatever you import from outside of your src must be transpiled already.


text:
Q: Can you make several pages of figures in a row in the middle of a Latex document? I have several figures, each of which needs to have its page. I want to put them in consecutive pages of an Overleaf document. The Latex code of these figures are written together, but Overleaf automatically separates them by other text and makes them non-consecutive.
\begin{figure*}[p]
    \centering
    \includegraphics[width=\textwidth]{fig1.png}
    \caption{caption1}
\end{figure*}

\begin{figure*}[p]
    \centering
    \includegraphics[width=\textwidth]{fig2.png}
    \caption{caption2}
\end{figure*}

\begin{figure*}[p]
    \centering
    \includegraphics[width=\textwidth]{fig3.png}
    \caption{caption3}
\end{figure*}

\begin{figure*}[p]
    \centering
    \includegraphics[width=\textwidth]{fig4.png}
    \caption{caption4}
\end{figure*}

A: Are the graphs (including captions) possibly taller than \textheight, once you've set their widths to \textheight? If so, the following approach should still work.
\documentclass[twocolumn]{article}
\usepackage[demo]{graphicx} % remove 'demo' option in real document
\usepackage{afterpage} % for '\afterpage' macro
\begin{document}

% ... document material
\afterpage{%
\clearpage % flush any queued-up floats
\begin{figure*}[p!]
    \includegraphics[width=\textwidth]{fig1}
    \caption{caption1}
\end{figure*}
\clearpage
\begin{figure*}[p!]
    \includegraphics[width=\textwidth]{fig2}
    \caption{caption2}
\end{figure*}
\clearpage
\begin{figure*}[p!]
    \includegraphics[width=\textwidth]{fig3}
    \caption{caption3}
\end{figure*}
\clearpage
\begin{figure*}[p!]
    \includegraphics[width=\textwidth]{fig4}
    \caption{caption4}
\end{figure*}
\clearpage} % end of scope of \afterpage directive
% ... more document material

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finite Group that it has almost d element of order d The following question was in one of my assignment:
Question 1: $G$ a finite group that for each number $d$ the number of elements that $x^d=1_G$ is at most $d$. Prove that $G$ cyclic.
I solve this question by getting its higher element order. I was thinking on this question with the a little narrowing its assumption:
Question 2: $G$ a finite group that for each number $d$ the number of elements with order $d$ is at most $d$. Prove that $G$ cyclic.
I am not sure even it is correct for all $|G|=n$. I have tried lots of inequalities but I could not reach any thing. In the way that we use Sylows Theorem and the $|G|=n$, odd number, we can see $G$ is a cyclic group as following:
Assume $|G|=n=p_1^{\beta_1}p_2^{\beta_2}\dots p_k^{\beta_k}$ then we have subgroups with the $p_i^{\beta_i}$ order.
Lemma 1: A group with $p^{\beta}$ order with the assumption that for each $p^{\alpha}$ that $\alpha \le \beta$. the number of elements with this order is less that $p^{\alpha}$, then the group is cyclic.
Proof: Assume that there is not any element with the $p^{\beta}$ order. Thus each element has order  $p^{\alpha}$ that $\alpha \lt \beta$, and we have at most $p^{\alpha}$ this elements.
$$p^{\beta} \le \sum_{i=0}^{\beta-1}p^{i}=\frac{p^{\beta}-1}{p-1}<p^{\beta}$$
As a result, we should have at least one element with the $p^{\beta}$ order.$\blacksquare$
Now we should show that each of this sylow subgroups are normal, and with the use of above lemma we will get that the result.
For being normal proof see that each sylow subgroup is a cyclic and there are $p^{\beta -1}(p-1)$ members that have $p^{\beta}$ order. If we have another sylow subgroup then we have at least $2.p^{\beta -1}(p-1)$ elements of $p^{\beta}$. With the assumption that all $|G|$ is odd, and the number of elemnts of order $p^{\beta}$ is less than $p^{\beta}$, we can conclude that it could not happen. As a result, there are only one p-sylow subgroup. and this means that each of them are Normal. With the use of Lemma 1, each of them are cyclic too. So, $G$ is the product of cyclic sylow subgroups, then it is cyclic too.
My Question:

*

*Is my proof Okay, or I am missing something.

*Is there any basic solution. Like using inequalities or counting numbers?

*Any other proof for first or the second question will be great.

Thanks.


text:
Q: How to properly follow a forked git repository? We have to fork a repository and keep it up to date, with adding changes here and there. The important branches are remote/1.0 and remote/1.1
The workflow currently used is to fork the repository, create our own 1.0 branch that is the same as remote/1.0. Changes are then made that are pushed to our 1.0. Now, we have to create a new 1.1 branch based on our 1.0 and merge remote/1.1 to it. The idea is to end up with the copy of remote/1.1 branch, but with all our previous changes kept (where that made sense, some changes may have to be adjusted to remote/1.1).
Is merging every so often a correct strategy here? Or should rebasing be more appropriate? Is a better third way to do it?


text:
Q: copy vmware vmdk files while vm is running I need to copy some VMs from one datastore to another. I'm running ESX 3.5 U3, VMs are mostly Windows-based. I don't care about data integrity since it's only to test NetApps deduplication on the target destination and the VMs will never be running from this files. Since the VMs are used, i cannot shut them down. If I try to copy it with 'cp' of course I get errors complaining about locked files.
E.g.: "cp: cannot open ....vmdk' for reading: Device or resource busy"
Is there a trick to do this? With dd or cpio?
Regards

A: See this article and this one, seems like what you're looking for.
here's the process:

Taking a snapshot of the source VM using vmware-cmd.
Create a new VM and delete all vmdks in it
Copy the vmdk files from your snapshot into your new using vmkfstools.
Fix your configurations files accordinately.

Hope this helps.

A: For anyone reading this thread that has VMware Workstation, then to produce an independent functioning copy (ie a backup) is not possible according to the user guide without shutting down the VM first. The Uranium backup application will copy VMs while they are running but it is not cheap (150 Euro's) for a small startup like mine. I found in practice that simply suspending the VM and copying the files to a backup location works fine; giving a fully independent copy. The VM is only offline during the copy phase, and will resume its programs and files state after the copy is done. When you start the backed up VM it will ask whether you have moved it or copied it. Copying the files of an active VM is understandably risky, as the backup may not function due to state changes during the backup. So I wrote a very basic script to suspend the VM, copy the files to another location, then Resume the VM. Send me an email if you would like a copy.

A: Try using the VMWare Standalone Converter and use it's "Copy a running machine" option.  It will temporarily install an agent; but that should take care of your need to make sure the VM stays running during the conversion.


text:
Q: Linux incompatible with work access points? just started a new job.  When I connect to the network at work using Kubuntu 16.04 it takes a few minutes to reach a destination (if it reaches it at all).  I don't have this problem at other places (home, the hotel etc.).  Others at work are using Windows and Mac and have normal speeds on the network.  I also get normal speeds when I connect via my Android phone.  But my 16.04 laptop has slow networking only when using the network at work.  How can I diagnose this issue and is it possible the problem is with the network at work itself?

A: I can't comment, so I guess I'll "answer" :P
The first step, I'd say, would be to compare the terminal output of "ipconfig /all" on a Windows laptop (or "ifconfig" on a Mac, although it's very cluttered from what I recall) compared to that of "ifconfig" on your Kubuntu 16.04 laptop.
You can also get some verbose information from your Android phone by 'becoming a developer' (ie. going into Settings -> "About phone" and tapping on "Build number" a bunch of times) and then, in the Developer Options, enabling Wi-Fi Verbose Debugging. This'll make the Wi-Fi section in Settings much more verbose. Alternatively, you can open the dialer and run "##4636##" (this may not work on all devices, but it does if they're close to stock, ex. Nexus devices) which brings up the hidden Testing menu which includes "Wi-Fi information" -> "Wi-Fi Status" and should at least tell you the RSSI.
Combine that with the "iwconfig" command on you Kubuntu laptop and you should have enough information to start comparing some things and seeing if there's some obvious difference between the connection your Kubuntu laptop is making and what others are.
As to what's going on, my initial guesses would be that either the Kubuntu laptop isn't getting the right gateway for some reason, or that it's not negotiating a decent frequency and thus the RSSI is bad or the TX rate is being severely limited. Those are just spurious guesses, however; more information is definitely needed, including very much as per the comments folks have already made (which again, I would've joined in on, but for some weird reason Stack Exchange makes the lower-tier methods of textual interaction the ones hardest to get the 'points' to be able to do!).


text:
Q: JSF 2 : disable button when submitted using Richfaces 4 I am using JSF 2 and Richfaces 4, I need to disable button when submitted. I need to call the action of the button too. When the form validation fails, submit button should be enabled. I can do using Richfaces 3 but not been able to do with Richfaces 4.
Looking for the help.

A: You can use the onbegin and oncomplete attributes of the <a4j:commandButton> for this.
<a4j:commandButton ... onbegin="disabled=true" oncomplete="disabled=false" />


text:
Q: db2 update dbm cfg fails with error: SQL5133N. Specified value: "0". Configuration parameter name: "fcm_buffer_size" I am trying to load SSL certificate from java keystore to db2 dbm.
I did below steps:
Step 1: List certificates in truststore
$ keytool -list -v -keystore db-truststore
Enter keystore password:
Keystore type: jks
Keystore provider: SUN

Your keystore contains 2 entries

Alias name: caintermediate
Creation date: May 24, 2018
Entry type: trustedCertEntry
...
...
Alias name: carootcert
Creation date: May 24, 2018
Entry type: trustedCertEntry

Step 2: Exported these certificates to files
keytool -export -alias carootcert -keystore db-truststore -file rootcert.pem
Enter keystore password:
Certificate stored in file <rootcert.pem>

keytool -export -alias caintermediate -keystore db-truststore -file intermediatecert.pem
Enter keystore password:
Certificate stored in file <intermediatecert.pem>

Step 3: created key database:
gsk8capicmd_64 -keydb -create -db "dbclient.kdb" -pw "passw0rd" -stash

Step 4: Added certificate files to key database
gsk8capicmd_64 -cert -add -db /full-path/dbclient.kdb -pw passw0rd -label carootcert -file rootcert.pem
gsk8capicmd_64 -cert -add -db /full-path/dbclient.kdb -pw passw0rd -label caintermediate -file intermediatecert.pem

Step 5: Added catalog:
db2 => catalog TCPIP NODE phdbdev  REMOTE  bldbz173038.cloud.dst.ibm.com  SERVER 60443  SECURITY SSL
DB20000I  The CATALOG TCPIP NODE command completed successfully.
DB21056W  Directory changes may not be effective until the directory cache is
refreshed.
db2 => catalog DATABASE phdbdev  AT NODE phdbdev  AUTHENTICATION SERVER
DB20000I  The CATALOG DATABASE command completed successfully.
DB21056W  Directory changes may not be effective until the directory cache is
refreshed.

Step 6: Updated gdm
db2 update dbm cfg using SSL_CLNT_KEYDB /full-path/dbclient.kdb
SQL5133N  The configuration parameter was not updated because the specified
value is not valid.  Specified value: "0".  Configuration parameter name:
"fcm_buffer_size".

Further investigation as suggested:
$ db2level
DB21085I  This instance or install (instance name, where applicable: "vizeet")
uses "64" bits and DB2 code release "SQL11010" with level identifier
"0201010F".
Informational tokens are "DB2 v11.1.0.0", "s1606081100", "DYN1606081100AMD64",
and Fix Pack "0".
Product is installed at "/home/vizeet/sqllib".

$ db2 get dbm cfg | grep 'Node type'
     Node type = Enterprise Server Edition with local and remote clients

$ db2 get dbm cfg | grep FCM
 Number of FCM buffers                 (FCM_NUM_BUFFERS) = AUTOMATIC(4096)
 FCM buffer size                       (FCM_BUFFER_SIZE) = 0
 Number of FCM channels               (FCM_NUM_CHANNELS) = AUTOMATIC(2048)
 FCM parallelism                       (FCM_PARALLELISM) = AUTOMATIC(1)

db-truststore works properly with db2 drivers.
Unable to resolve this issue. Kindly help.


text:
Q: Error in running SQL Server script I copied oldDatabase as newDatabase. Modified newDatabase's schema.
Meanwhile, oldDatabase's data are processing and updating.
I want to copy oldDatabase's data to newDatabase.
What I have done is:

*

*Clean the data of newDatabase

*Generate data only script of oldDatabase

*Run this script in newDatabase.

And I got a lot of error messages like:
Cannot insert explicit value for identity column in table 'MyTableName' when
IDENTITY_INSERT is set to OFF.

Invalid column name 'MyColumnName'.

Violation of PRIMARY KEY constraint 'PK_MyTableName'. Cannot insert duplicate
key in object 'dbo.MyTableName'.

Some tables and rows data are affected. But, tables with above error are not affected. How can I fix it? Is there a best way to make this stuff?
PS
I run my script using this command ,
sqlcmd -S myServerName -U userName -P passowrd -i PathOfMyScriptFile

A: What your script is doing is explicitly attempting to insert data into an IDENTITY column. You need to do one of two things:  Either set IDENTITY_INSERT to ON for that table prior to the insert, or rework the INSERT statement so that it doesn't have the IDENTITY column specified with a value.

A: You have three different types of problems from the looks of it.

Cannot insert explicit value for identity column in table 'MyTableName' when
IDENTITY_INSERT is set to OFF.

You have identity columns.  For a table that has an identity column you have three choices.  First when you do your insert exclude the identity column.  Second remove the identity property from the column in the destination table.  Third use identity_insert.  To use identity_insert you first turn it on for the table.
SET IDENTITY_INSERT MyTableName ON

Then you do your insert.  Note: you have to list all of the columns in the insert.
INSERT INTO MyTableName (fieldlist) VALUES (valuelist)

Not
INSERT INTO MyTableName VALUES (valuelist)

And last but not least make sure you turn identity_insert back off again.  Identity_insert can only be turned on for one table at a time for a given connection.
SET IDENTITY_INSERT MyTableName OFF

Here is a good walkthrough for insert into identity columns.

Invalid column name 'MyColumnName'.

You said you changed the structure of 'newDatabase'.  Well my guess is you removed 'MyColumnName'.  Either exclude this from the insert or add the column back.  You either need to make sure the structure in newDatabase matches oldDatabase or account for the differences in your inserts.

Violation of PRIMARY KEY constraint 'PK_MyTableName'. Cannot insert duplicate
key in object 'dbo.MyTableName'.

Last but not least you are inserting data into newDatabase were the data already exists.  Or at least the primary key values already exist in newDatabase.MyTableName.  My suggestion here is if there is any chance that you are doing updates as well as inserts  change your INSERT statements to MERGE statements.  Otherwise add a WHERE NOT EXISTS or something similar to the SELECT statement in your INSERT statement to exclude any rows where the primary key already exists in newDatabase.MyTableName.


text:
Q: Laravel 5.8 Eloquent querying I know all the Eloquent model querying is in the Laravel documentation and I have read through them to figure this out but can't seem to work my way around it. I am building a recipe application, and I want to get access to a particular profile picture of a user based on an uploaded recipe.
I have a grid of recipes that have been uploaded by various users. The User and Recipe model are below.
User Model
public function recipes()
{
    return $this->hasMany('App\Recipe');
}

Recipe Model
public function user()
{
    return $this->belongsTo('App\User');
}

In my recipe grid, I have the following code in a recipe card.
Index Blade/View
@foreach($recipes as $recipe)
user_id) }}">
    {{$recipe->author}}

@endforeach

Through the $recipe I can access the name of the creator of that particular recipe like this $recipe->author. I am trying to get access to this specific users profile photo too. I want to get something like this $recipe->author->profile_pic. (profile_pic is a column in my users table).
How would I go about solving this problem in a simple way? I'm a newcomer to coding and am still working on solving these problems myself. Thank you!

A: You can do it like this:
$recipe->user->profile_pic

A: You can change the model by rename user to author like this:
public function author()
{
    return $this->belongsTo('App\User');
}

or changing view (blade) like this:
@foreach($recipes as $recipe)
user_id) }}">
    {{$recipe->user->profile_pic}}

@endforeach


text:
Q: Current status of Bloch Constant and Landau Constant bounds The Bloch constant B (based on a theorem introduced by André Bloch in 1925 on the maximum radius of a one-to-one disk in the image of a normalized analytic function of the unit disk, see for instance Remmert Funktionentheorie II or Steven Finch marvelous "Mathematical Constants") was conjectured by Ahlfors to be
$$ \frac{1}{\sqrt{1+\sqrt{3}}}\frac{\Gamma(\frac{1}{3})\Gamma(\frac{11}{12})}{\Gamma(\frac{1}{4})}$$
(This value, if I remember well Ahlfors' article corresponds to a particular function that he constructed for this purpose).
The Bloch Constant $B$ is currently known to be at least slightly greater than  $\frac{\sqrt{3}}{4}$ (several articles improving upon each other by Mario Bonk, Chen and Gauthier, Xiong).
Has there been some progress since 1998 on the lower bound ?
Same question for the closely related (univalent) Landau constant (quite often called Bloch-Landau constant, sometimes seen as $B_\infty$) ?
The conjectured upper bound is
$$\frac{\Gamma(\frac{1}{3})\Gamma(\frac{5}{6})}{\Gamma(\frac{1}{6})}$$

What can be said of the various adaptations or specializations of this constant to various class of functions, and extensions of these constants to several complex variables or other functional spaces ?

I give as background the original article from Bloch, Ahlfors and Grunsky.
(1) A. Bloch, Les théorèmes de M. Valiron sur les fonctions entières et la théorie de l'uniformisation, Ann. Fac. Sci. Univ. Toulouse, vol. 17, (1925), pp1-22.
(2) L. V. Ahlfors and H. Grunsky, Über die Blochsche Konstante, Math. Zeitschrift 42 (1937), pp671–673.
(3) L. V. Ahlfors, An extension of Schwarz's lemma, Trans. Amer. Math. Soc. 43 (1938), pp359–364.
(these two are reprinted in Ahlfors Works vol 1)

Ahlfors life and works are evocated in an AMS Notices of 1998.

A: The world record on the Bloch's constant seems to be MR1690898 by C. Xiong, who proved
$B\geq \sqrt{3}/4+3.10^{-4}$. I recall that $\sqrt{3}/4$ is the Ahlfors estimate, then Heins
proved that $B$ is strictly greater than that, and Bonk was the first to prove this with
a specific constant. Then this constant was slightly improved, first by Gauthier and Chen
MR1428103 and then by Xiong.
This is far from the conjectured value. There are also results which show that
the Ahlfors - Grunsky conjectured extremal function gives a local extremum for certain
variations. But the classes of variations considered are narrow.
For example, Baernstein II and Vinson proved that the Ahlfors Grunsky function gives
a local extremum for the class of ramified coverings which are ramified
only over some lattice
points. (So the hexagonal lattice is locally extremal for such restricted problem).


text:
Q: Changing a Int to a String then Formatting the String
 Credit Limit:  $@Model.CreditLimit.ToString().ToLocaleString()

I am changing an Int to a String using ToString() Then I am trying to format the number I am getting using ToLocaleString(). The number looks like this: 80567. I am trying to format it to look like this: 80,567.
The error I get is "string does not contain a definition for "ToLocaleString"
Thoughts?
EDIT: Going to have this issue closed. Found where my error resided. Please refer to this link if you have any questions on the topic: Link to StackOverFlow issue

A: I see that you want to show money amount, you should use currency NumberFormatInfo for this. First get current CultureInfo or create it for specific language-country:
var culture = Thread.CurrentThread.CurrentCulture;
// or
var culture = new CultureInfo("en-US");

Then use it to format your number:
var creditLimit = 100;
var creditLimitFormatted = creditLimit.ToString("c", culture);

The "c" stands for "currency", you can see other possible options in the documentation of NumberFormatInfo.
Formatting Numeric Data for a Specific Culture

A: @Model.CreditLimit - this is Integer
@Model.CreditLimit.ToString() - this is a String
now you are trying to execute the ToLocaleString() which clearly from the error

"string does not contain a definition for "ToLocaleString"

To do what you want to archive try the solutions below:
String.Format("{0:n}", @Model.CreditLimit); //Output: 80,567.00
string.Format("{0:n0}", @Model.CreditLimit); // Output: 80567

A: That's because the int (Int32) class is not formattable, that is, it's representation does not depend on the culture, for example. You have to roll out your formatting code.

A: This article gives a nice overview of the different format types available. It sounds like you want the Numeric Format Specifier. You'd use it like this
int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0


text:
Q: setContentLength is set high When the setContentLength method is used to set the length of the response with a higher size that is higher than the actual size, why is the container not auto calculating the length?
for instance,
String s = "hello";
byte[] b = s.getBytes();

response.setContentLength(100);
response.getOutputStream().write(b);
response.flush();

When i hit the servlet, it takes about half a minute to load the page, is this because of the content length header..?
What is the need for such a method? why cant the container be made to calculate the length of the response by itself?

A: If you want to return large contents it is often not practical to load te full response and send it at once,but instead load and send it in chunks. Since the length is sent as part of the beginning of the response there is no way for the container to later on change it.
In this case you tell the container that your response is 100 bytes, you send the first 5 bytes (which triggers the header "Content-Length: 100" to also be sent), so now the recipient will expect another 95 bytes.
Now, on the other hand, say your content was 10GB, you would not want to first load all of that into memory just so the container would calculate the size.


text:
Q: How to correctly use an object type in an Oracle stored procedure? I have this type definition:
Create Type "T1" as Table of Varchar2(10);/

This got executed.
How to use the T1 type variable in PL/SQL?. I have the following procedure:
Create or replace PROCEDURE P1
AS
  P_K   T1;
BEGIN
  SELECT P_K_J INTO P_K FROM SOME_TABLE WHERE NAME='JONES' ;
  FOR I IN P_K.FIRST..P_K.LAST LOOP
    DBMS_OUTPUT.PUT_LINE('THE VALUES OF P_K ARE' || P_K(I));
  END LOOP;
END P1;

This gives the following error:

ERROR:
3/5      PL/SQL: Item ignored
3/5      PLS-00311: the declaration of "T1" is incomplete or malformed

My question is: how to instantiate a variable of type T1

A: Create Type "T1" as Table of Varchar2(10);
/
Create or replace PROCEDURE P1
AS
  P_K   T1;
BEGIN

  SELECT P_K_J BULK COLLECT INTO P_K FROM SOME_TABLE WHERE NAME='JONES';

  FOR I IN P_K.FIRST..P_K.LAST LOOP
    DBMS_OUTPUT.PUT_LINE('THE VALUES OF P_K ARE' || P_K(I));
  END LOOP;

END P1;
/


text:
Q: Run a node.js "Script" on aws ec2 with no front end? I have built a node.js "script" which is basically a single javascript (.js) file which communicates with a smart contract in ethereum blockchain. This needs to be running forever. The problem is, it has no front-end, no server-client architecture so no request / response mechanism needs to be implemented when uploading to aws ec2 instance. This is more like a daemon script which should run in background forever, talking to ethereum blockchain and changing some state variables. So my questions are:

*

*Should i keep no front end, and if so, what will happen when i access the public dns?

*if possible, the only front end I could have is the console logs of the node.js script. Is it possible to configure the front-end (public dns) of ec2 such that the console logs are visible?

A: It's possible to set up a front-end that only shows the logs, but it sounds like what you're building is more of a service, which wouldn't normally have its own UI. When you hit your instance at its host name (over DNS, for example if you have example.com pointing to your instance) you might not see anything, unless you add an endpoint to return some data. I'd recommend checking out some basic Node API and web server examples, as well as examples in some of the most popular web frameworks (Express, Koa, and Hapi) to see how that would work. But there's nothing wrong with just having a long-running process on an instance that doesn't respond to the outside world.


text:
Q: Racing time Normal distribution The time taken by Ariff and Bob to run in 250 metres races are independent and normally distributed with means 35.8 and 36.1 seconds respectively and standard deviations 2.5 and 6.1 seconds respectively.
(i) Bob runs faster than k seconds in 95% of the 250 metres races. Find the value of k.
(ii) Both of them sign up to run in the 250 metres race with a track record of 35.2 seconds. Determine with clear working shown, whether Ariff or Bob has a higher chance of breaking the track record.
My Answers:
(i)  Let Bob's running time be Y.
Y - N(36.1 , $6.1^2$)
P(Y>k) =0.95
Using Graphic calculator, inverse normal function with area = 0.95, mean = 36.1, standard dev = 6.1, right tail
Therefore obtain k = 26.1 to 3 sig fig
(ii)
Let X be the running time for Ariff.
X - N(35.8, $2.5^2$)
From graphic calculator:
P(X>35.2) = 0.595
P(Y>35.2) = 0.559
Based on the probability obtained, Ariff has a higher chance of breaking the record.
Are my answers correct? If not, what is wrong? thanks


text:
Q: Conditional Probability A Box Of Fuses?
A box of fuses contain $20$ fuses, of which five are defective. If three of the fuses are selected at random and removed from the box in succession without replacement what is the probability that all three fuses are defective?

For this question I know that one must use the formula
$$P \left(A \cap B \cap C \right ) = P(A) * P(B|A) * P(C| A \cap B)$$
I am able to to identify that $P(A) = \frac{5}{20}$. I assume since their are five out of 20 defective fuses. My question for this probelm is how does one identify $P(B|A) \text{ and }  P(C| A \cap B)$?
I know that $P(B|A) = \frac{P(B \cap A)}{p(A)}$ and $ P(B|A) = \frac{P(A \cap B)}{p(A)} $
Unfortunately identifying how one solves this problem eludes my understanding any advice on how to solve this would be beneficial to I.

A:
I am able to identify that $P(A)=5/20$. I assume since their are five out of 20 defective fuses. My question for this probelm is how does one identify $P(B|A)$ and $P(C|A∩B)$?

Second verse, same as the first.
$\mathsf P(B\mid A) = 4/19$ because when given that you have selected one defective fuse there are 4 defectives left among the 19 remaining.
$\mathsf P(C\mid A\cap B) = 3/18$ for some obscure reason.
So $\mathsf P(A\cap B\cap C) =\dfrac{~~5\cdot ~~4\cdot ~~3}{20\cdot 19\cdot 18}$
As others have pointed out this equals ${\binom 5 3}\big/{\binom {20} 3}$, from comparing counts: ways to select 3 from 5 defectives (and no non-defectives) versus ways to select any 3 from 20.

A: If you've done combinations, you see that there are ${{5}\choose{3}} = 10$ ways to choose any 3 of the 5 defective fuses. There are ${{20}\choose{3}} = 1140$ ways of choosing 3 fuses at random from the 20 fuses. Therefore, the chance for all fuses to be defective is $\frac{10}{1140} = \frac{1}{114}$.

A: you can straightforwardly apply the hypergeometrical distribution here:
Given a box with $x$ black and $y$ white balls, the probability $P$ of choosing (without replacement) $n$ balls, such that $k$ are black and the rest $n-k$ are white is given by
$$
P=\frac{\binom{x}{k}\binom{y}{n-k}}{\binom{x+y}{n}}
$$
In your problem, $x=5$, $y=15$, $n=3$, $k=3$, so
$$
P=\frac{\binom{5}{3}\binom{15}{0}}{\binom{20}{3}}=\frac{1}{114}
$$


text:
Q: Cycle through finite set of colours for indefinite set of data in Javascript I'm using ChartJS to show stock data. I have seven colours I want to iterate through for the objects. When I add an 8th object, I want it's colour on the chart to be the first colour in the colour array.
$(document).ready(function () {
  var context = document.getElementById('positions_chart');
  var ctx = context.getContext("2d");

  var quantities = [];
    $("#positions_chart").data('positions').forEach(function(element){
      quantities.push(element['quantity']);
  });

  var colors =[ "#FFCE56",
            "#FFA75D",
            "#46BFBF",
            "#5975CB",
            "#FF5D5D",
            "#FFCC5D",
            "#52DF52",
            'black'
];

  var tickers = [];
  $("#positions_chart").data('positions').forEach(function(element){
    tickers.push(element['ticker']);
  });

  var pieData = {
    labels: tickers,
    datasets: [
    {
      backgroundColor: [
            "#FFCE56",
            "#FFA75D",
            "#46BFBF",
            "#5975CB",
            "#FF5D5D",
            "#FFCC5D",
            "#52DF52",
            'black'

          ],
      borderColor: "rgba(220,220,220,1)",
      data: quantities
  }
]
}

var chartInstance = new Chart(ctx, {
    type: 'doughnut',
    data: pieData,
    options: {
        responsive: true
    }
});

The number of tickers indicate how many objects will need a colour on the chart. Cycling through the tickers to assign new colours is something ChartJS does in the background. The problem I'm facing is when tickers amount > colours amount I want the colours array to reset from the top. So I don't have blank colours for new objects in the chart.

A: You can switch out the colors array with a doubly-linked list.
Or just use an anonymous function on the object creation,
datasets: [{backgroundColor: (() => {
  let bgcolors = [];
  for (let i=0; i < tickers.length; ++i) bgcolors.push(colors[i % colors.length]);
  return bgcolors;
  })()
}]


text:
Q: PHP getimagesize not working on external links I have some issues on my server in running getimagesize on remote url images.
For example if I run this code on my local server it works fine and returns OK:
<?php
$file = 'http://inspiring-photography.com/wp-content/uploads/2012/04/Culla-bay-rock-formations-Isle-of-Uist.jpg';
$pic_size = getimagesize($file);
if (empty($pic_size))
{
    die('FALSE');
}
die('OK');

?>

But if I run the same code on my server I cannot make it work properly. Can you help in determining which settings shall I ask to enable?
I think some of these may be involved:

*

*mod_security

*safe_mode

*allow_url_fopen

Can you help me in determining the right configuration to get this solved?
Thank you very much in advance.

A: allow_url_fopen  is  off. Either enable it on your php.ini, or use curl to get the image:
function getImg($url){
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

$url = "http://inspiring-photography.com/wp-content/uploads/2012/04/Culla-bay-rock-formations-Isle-of-Uist.jpg";
$raw = getImg($url);
$im = imagecreatefromstring($raw);
$width = imagesx($im);
$height = imagesy($im);
echo $width." x ".$height;

SRC

A: You have to turn allow_url_fopen on in your php.ini file in order to allow it to access resources that are not local.
This is specified in the official document of getimagesize in the description of the filename parameter.


text:
Q: Ansible sysctl setting bridge-nf-call-iptables failed: sysctl: cannot stat /proc/sys/bridge-nf-call-iptables: No such file or directory I am using ansible in CentOS 7 and trying to set the kernel setting but it's giving an error.
Ansible version 2.3.0.0.
Here is the value I am trying to change:
 - name: update kernel settings
       sysctl:
         name: bridge-nf-call-iptables
         value: 1
         sysctl_set: yes
         state: present
         reload: yes

the file is in this path /proc/sys/net/bridge/bridge-nf-call-iptables, but Ansible is looking at in /proc/sys/bridge-nf-call-iptables.
How can I fix this error?

setting bridge-nf-call-iptables failed: sysctl: cannot stat
  /proc/sys/bridge-nf-call-iptables: No such file or directory

A: Per sysctl module manual:

name - The dot-separated path (aka key) specifying the sysctl variable.

So you need to specify:
- name: update kernel settings
  become: yes
  sysctl:
    name: net.bridge.bridge-nf-call-iptables
    value: 1
    sysctl_set: yes
    state: present
    reload: yes

I added become explicitly to avoid confusion.
The code in your question is also incorrectly indented.


text:
Q: error loading javascript files dynamically i am trying to lazy (dynamically) load javascript files in my webpage.
i have used this :
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
   function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript1.js", "js") //dynamically load and add this .js file
loadjscssfile("myscript2.js", "js") //dynamically load and add this .js file
loadjscssfile("myscript3.js", "js") //dynamically load and add this .js file

these 3 script are to be loaded in a sequence.
myscript3 is dependent on myscript2
 and myscript2 is dependent on myscript1.
trying to load it in this way is behaving wierdly.
Looks like these are  not  loaded in the sequence intended and hence
undefined errors are thrown at times and at times no error are thrown.
Am i doing something wrong.

Updated :

I am using this code to load the files in the correct sequence
 function loadjscssfile(filename, filetype) {
        if (filetype == "js") { //if filename is a external JavaScript file
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", filename)
        }
        else if (filetype == "css") { //if filename is an external CSS file
            var fileref = document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }
        return fileref;
    }

    function loadSync(files, types) {
        if (typeof (files[0]) === 'undefined') return false;
        var script = loadjscssfile(files[0], types[0]);
        script.onload = function () {
            files.shift();
            types.shift();
            loadSync(files, types);
        }
        if (typeof script != "undefined")
            document.getElementsByTagName("head")[0].appendChild(script)
    }

    loadSync(['scripts/module3.base.js', 'scripts/module3.core.js', 'scripts/module3.init.js'], ['js', 'js', 'js']);
    console.log('this should get printed when all the three files are loaded');

But the console output is :
this should get printed when all the three files are loaded
scripts/module3.base.js:9 base is initialised
scripts/module3.core.js:6 core is initialised
scripts/module3.init.js:3 app is initialsed

Looks like the first call to loadSync is itself an Asynchronous call

A: There are open source js which will ease your problem.
You can use LABJS or RequreJS plugins.
Script loaders like LABJS, RequireJS will improve the speed and quality of your code.
You can preserve order of loading your script like this in LABJS.
$LAB.setOptions({AlwaysPreserveOrder:true})
.script("script1.js")
.script("script2.js")

OR
$LAB
.script("script1.js").wait()
.script("script2.js")

script2.js will wait untill script1.js is loaded.
I guess this will solve your problem.

A: For HTML5 just use async attribute ( info at http://davidwalsh.name/html5-async )
Example of function for loading script with a optional callback option
function loadScript(url, callback) {
    if (!callback) callback = function () {};
    var script = document.createElement("script")
    script.type = "text/javascript";
    script.setAttribute("async", "true");

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

For a mixed solution:
function loadjscssfile(url, type, callback) {
    if (!type) {
        type = "js";
    }
    var node;
    if (type === "js") {
        var node = document.createElement("script")
        node.setAttribute("async", "true");
        node.type = "text/javascript";

        if (node.readyState){  //IE
            node.onreadystatechange = function(){
                if (node.readyState == "loaded" ||
                        node.readyState == "complete"){
                    node.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            node.onload = function(){
                callback();
            };
        }

        node.src = url;
    } else if (type === "css") {
        var node = document.createElement("link")
        node.type = "text/css";
        node.setAttribute("rel", "stylesheet");
        node.setAttribute("async", "true");

        if (node.readyState){  //IE
            node.onreadystatechange = function(){
                if (node.readyState == "loaded" ||
                        node.readyState == "complete"){
                    node.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            node.onload = function(){
                callback();
            };
        }
        node.href = url;
    }
    if (node) {
        document.getElementsByTagName("head")[0].appendChild(node);
    } else {
        callback(new Error("File not found"));
    }
}

Loading a list of files
function loadjscssfileList(arr_original, callback) {
    var arr = [];
    arr_original.forEach(function (v) {
        arr.push(v);
    });
    var next = function () {
        if (arr.length) {
            var file    = arr.shift();
            loadjscssfile(file[0], file[1], function () {
                next();
            });
        } else {
            callback();
        }
    };
    next();
};

// use without callback
loadjscssfileList([
    ["myscript.js","js"],
    ["style.css","css"],
    ["myscript2.js","js"]
]);

// use with callback
loadjscssfileList([
    ["myscript.js","js"],
    ["style.css","css"],
    ["myscript2.js","js"]
], function () {
    alert("loaded")
});

A: you can load them synchronously.
function get_contents(file){
   var xhr = new XMLHttpRequest();
   xhr.open('get', file, false);
   xhr.send();
   return xhr.responseText;
 }

function loadjscssfile(filename, filetype){
var content = get_contents(filename);
if (filetype=="js"){ //if filename is a external JavaScript file
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.innerHTML = content;
}
else if (filetype=="css"){ //if filename is an external CSS file
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.innerHTML = content;
}
if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref)
}

To load it externally:
there're 2 ways:
Callback as the another answer.
Or you can do this:
function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    return fileref;
}

function loadSync(files,types){
    if(files[0] === 'undefined')return false; //if there's no files to load
    var script = loadjscssfile(files[0],types[0]); //load first file
    script.onload = function(){//after the script is loaded delete them and continue;
        files.shift();
        types.shift();
        loadSync(files,types);
    }
    if (typeof script !="undefined")
        document.getElementsByTagName("head")[0].appendChild(script)
}

loadSync(["myscript1.js","myscript2.js","myscript3.js"],['js','js','js']);


text:
Q: How to force reloading webview resources (ignore webview cache) every time opening? I find it instantly opening the webview page from cache after the first load. And it can't see the updated content on the webview page.
=== Edit ====
My webview code
The subModuleUrl may be a static html or pure domain

render() {
    const { subModuleUrl } = this.props   // the webview url, like: http://a.example.url.com/index.html
    const { isWebViewLoadFails } = this.state

    return (
      <View style={ApplicationStyles.screen.mainContainer}>
        {
          isWebViewLoadFails ?
            <View style={styles.errorShow}>
              <Text>Load fail</Text>
            </View>
            :
            <WebView
              style={{ flex: 1 }}
              startInLoadingState={false}
              ref={webview => { this.webview = webview }}
              source={{ uri: subModuleUrl }}
              javaScriptEnabled
              injectedJavaScript={WebViewBridge}
              onNavigationStateChange={this.onNavigationStateChange}
              automaticallyAdjustContentInsets={false}
              onMessage={this.handleMessage}
              onLoadStart={this.onWebViewLoadStart}
              onError={this.onErrorLoad}
              scalesPageToFit={false}
              domStorageEnabled
            />
        }
      </View>
    )
  }


text:
Q: Why are these check-boxes not being checked from code-behind? I have a website written in ASP.NET MVC and I have a parameter set to the page in question that specifies what the preceding page is. The reasoning for this is so when a user clicks an image from a particular page, the loaded page will automatically check the appropriate check box using javascript (jQuery particularly).
Here is the code that gets and sets the parameter:

Next, here is the collection of check-boxes:

        <%= Html.CheckBoxFor(model => model.Interests[0])%>
        Insulation
        <%= Html.CheckBoxFor(model => model.Interests[1])%>
        Windows
        <%= Html.CheckBoxFor(model => model.Interests[2])%>
        Siding
        <%= Html.CheckBoxFor(model => model.Interests[3])%>
        Roofing

        <%= Html.CheckBoxFor(model => model.Interests[4])%>
        Gutters/Protection
        <%= Html.CheckBoxFor(model => model.Interests[5])%>
        Patio Doors

When rendered in the browser, here is what each of the check-boxes look like:
<input id="Interests_0_" name="Interests[0]" type="checkbox" value="true" />
<input name="Interests[0]" type="hidden" value="false" />
Insulation

Here is the javascript that I am using, that is not working:

I am obviously doing something completely wrong, can anyone point me in the right direction?
Thanks!
EDIT: Looks like another JS file that was on a MasterPage that was called before my JS block was causing the boxes to not be checked. The main problem was forgetting the # identifier.

A: #id selectors need a # prefix, like this:
$('#Interests_0_').attr('checked', 'checked');

Without the #, it's an element selector, looking for a <Interests_0_> element.
You can slim it down overall with an object though, like this:
var ref = '<%= Referrer %>';
var map = {"insultation":"#Interests_0_",
           "windows":"#Interests_1_",
           "siding":"#Interests_2_",
           "roofing":"#Interests_3_",
           "gutters":"#Interests_4_",
           "patiodoors":"#Interests_5_"};
$(function () {
   var id = map[ref];
   if(id) $(id).attr('checked', true);
});

A: This is not MVC, but rather classic ASP.NET webforms.  There is no concept of code-behind in MVC, under normal circumstances you don't use events like OnLoad, and you don't normally use runat=server script blocks.  Take a look at the nerd dinner example for an overview of MVC.


text:
Q: Android and Objective-C I'm completing a project for the iPhone entirely written in Objective-C. I'd like to port this for Android too.
While the user interface of the iPhone and the Android OS are very different and will need different code, can I some how import the core of my code (ie. the black box that does the thinking) as is to Android as part of some Java code?
I have no familiarity with bridging between Objective-C and Java even though I have written in both.

A: You got luck! Phil Hassey has recently ported his own game from iPhone to Android within a week and wrote up what he did steps by steps. Here is his journey: http://www.philhassey.com/blog/2010/08/03/porting-galcon-using-the-android-ndk/

A: You could have a look at Apportable which allows to generate an Android app from an existing Objective-C code base. See this article too.

A: there is a fork of the gcc that supports objective-c on the android by patching the NDK on
http://code.google.com/p/android-gcc-objc2-0/. But it's considered beta at the moment and i'm not sure if jni/java bridges are already implemented

A: I have been doing a lot of work on this front — for example by creating my own C++ base framework that does not depend on STL (called Platform Core) and writing the core of the next version of my iOS app with that, so that I can easily port it to Android and whatever else has a C++ compiler and strikes my fancy.
I suggest having a (ick, I can't believe I'm about to say this, but eh), ahem, having a C++ core (there, I said it!) so it can be easily ported.


text:
Q: Excel vba search in array I need search in array
Sub f()
    Dim myArray As Variant
    myArray = Worksheets("QQ").Range("D:F")

    Dim searchTerm As String
    searchTerm = "927614*"

    'Check if a value exists in the Array
    If UBound(Filter(myArray, searchTerm)) >= 0 And searchTerm <> "" Then
        MsgBox "Your string match value from F column is " & myArray(Application.Match(searchTerm, myArray, False),3)
    Else
        MsgBox ("Search Term could NOT be located in the Array")
    End If
End Sub

But I get error Type mismatch. So how to lookup value with * in array?

A: Just loop through the array and use Like.
Untested code:
Dim matchFound As Boolean
matchFound = False
For i = 1 To UBound(myArray, 1)
    For j = 1 To UBound(myArray, 2)
        If myArray(i, j) Like searchTerm Then
            MsgBox "Found match at (" & i & "," & j & ") : " & myArray(i, j)
            matchFound = True
            Exit For
        End If
    Next j
    If matchFound Then Exit For
Next i
If Not matchFound Then MsgBox "No match found."


text:
Q: Ruby Spread sheet OLE issue I upgrade application from Rails 2 to Rails 3 using ruby 1.9.3.Everything works fine in Rails 2 with ruby 1.8.7.I have gem "spreadsheet" in gem file . But while running rails server, it throws error like this "rake aborted!
undefined method `new0' for Ole::Types::FileTime:Class"

A: Try with
bundle update ruby-ole


text:
Q: Specify environmental variables as commandline parameter in a debug session of VisualStudio C# I want to use an environment variable as a commandline parameter in a debug session.
So Project Properties->Debug->Command line arguments: %TEMP% gives me not the temp path as a parameter rather than the string "%TEMP%".
Of course I could resolve the environment variable to a path programmatically or copy past the correct path.
But I want just to know, if an envvariable works and when, how it works?!
Does someone know how I can specify an envvar as a commandline parameter in VS debug commandline arguments?

A: If the program is launched by visual studio then it inherits VS's environment variables. VS gets its environment variables when it starts. So:

*

*Change/set the environment variable

*Restart Visual Studio

*Launch/debug your program

A: You could modify your local environment variables for debugging in code. In your main entry point you can define as many enviroment variables as you like.
static void Main(string[] args) {
    #if DEBUG
    string path = Environment.GetEnvironmentVariable("path");
    Environment.SetEnvironmentVariable("path", path + @";c:\foo");
    Environment.SetEnvironmentVariable("temp", @"c:\bar");
    #endif

    new Program();
}

Together with that #if directive this code will also only compiled if you have a debug build. On release builds this code will be skiped (if you don't change your default settings of your project).

A: You can use this feature and define few lauch enviroments in launchSettings.json file.
It works both for asp.net web projects and console applications


text:
Q: Jenkins rebuild Test Result Trend I just have deleted old build files from disk and did a "Reload Configuration from Disk", but in the "Test Result Trend" the old builds are still visible.
I've also restarted Jenkins - same result.
How can I rebuild Test Result Trend to show only statistics of builds existing on disk?
I'm running Jenkins 2.73.1 on Windows7.
Tia Udo


text:
Q: ES6 block-scoped variable definition as condition In C++ you can do
if (MyClass* obj = MyClass::getInstance()) { ... }

In JavaScript, there were only function-scoped variables, so following statement wouldn't make sense
if (var x = getTrueOrFalseValue()) { ... }

But ES6 introduced let and const keywords, which declare variable accessible only in block-scope. Why aren't you allowed to use it in if/while conditions? For example:
if (let x = getTrueOrFalseValue()) { ... }

I find this pretty cool, because it doesn't spoil function scope with unused variables and allows to use them only in if/while block scope.

A: I think this is impossible, because let can be only used as a statement, not as an expression. If you try (let f = 3); you also get an error.

A: This is closest could get , here
function getTrueOrFalseValue() {
  return true
}

if (!(x = void 0)) {
  let x = getTrueOrFalseValue();
  if (x) {
    console.log(x)
  }
}

function getTrueOrFalseValue() {
  return true
}
if (!(this["x"]) || !(x)) {
  let x = getTrueOrFalseValue();
  if (x) {
    console.log(x)
  }
}


text:
Q: How to use a dictionary and isin()? I have a dictionary and I want to use that dictionary to classify a new column in a df. The Value column in the df should be compared to the values in the dictionary. The new column in the df should be the Key associated with the value.
d = {'Car':['1','2','3'],
     'Chicken legs':['4','5','6'],
     'Coronary artery bypass graft surgery':['7','8','9','10','11','12']}

df
Color   Style      Value
red     round      1
blue    square     5
green   triangle   9
orange  sphere     12

final df
Color   Style      Value   Thing
red     round      1       Car
blue    square     5       Chicken legs
green   triangle   9       Coronary artery bypass graft surgery
orange  sphere     12      Coronary artery bypass graft surgery

My first inclination was to put this into a df (df_dict) but I'm having trouble comparing the single value in the df to the list in the df_dict.
df_dict = pd.DataFrame({'Thing':list(d.keys()), 'Values':list(d.values())})

    Thing                                   Values
0   Car                                     [1, 2, 3]
1   Chicken_legs                            [4, 5, 6]
2   Coronary artery bypass graft surgery    [7, 8, 9, 10, 11, 12]

The below code works for a single element. My dictionary however has 32 elements and I imagine there is a better approach than just creating 32 versions of the code below. I just don't know what that approach would be.
df.loc[df['Value'].isin(['1', '2', '3]),'Thing']='Car'

Is it possible to use a dictionary and isin()?
Should I instead convert the dictionary to a list?

A: Even better, reverse the dictionary, so you have something like:
v_map = {
    1: 'Car', 2: 'Car', 3: 'Car',
    4: 'Chicken legs', 5: 'Chicken legs', 6: 'Chicken legs',
    7: 'Coronary artery bypass graft surgery',
    ...
    12: 'Coronary artery bypass graft surgery'
}

Now your new column is simply a matter of plugging in v_map[df['Value']] for the strings in the new column.

A: You could make a helper function for this:
In [60]: def argcontains(item):
    ...:     for i, v in d.items():
    ...:         if item in v:
    ...:             return i
    ...:

then map it to the appropriate column:
In [61]: df['thing'] = df.Value.map(argcontains)

In [62]: df
Out[62]:
   Value                                 thing
0      1                                   Car
1      5                          Chicken legs
2      9  Coronary artery bypass graft surgery
3     12  Coronary artery bypass graft surgery

This can be slightly more general (and avoid recalculating d.items() each time, though that's pretty minor) such as:
In [73]: def argcontains2(item_iterator, item):
    ...:     for i, v in item_iterator:
    ...:         if item in v:
    ...:             return i
    ...:

In [74]: from functools import partial

In [75]: argcontains = partial(argcontains2, d.items())

If you will need to reference the data in d by value often, then it will be better to create a reverse index of the data (the reverse dictionary) as mentioned in another answer.
But if you only need the reverse lookup one time for purposes of constructing this column, it will use less memory and require less computation to use a simple loop like shown above.


text:
Q: Scanner never stops reading input I'm simply trying to read integers (separated by spaces, such as : "6 9 20") from the console and transferring them into an array for later use. However, with the code I currently have written, my scanner object never stops reading my input. I feel like the scanner object simply doesn't know exactly when to stop taking input, but I'd like it to stop reading as soon as I hit Enter. I've searched this website extensively for a precise answer, but to no avail.
Here is my code:
        int[] mcNug = new int[5];

        Scanner scanner = new Scanner(System.in);
        List list = new ArrayList<Integer>();
        int i = 0;
        while(scanner.hasNextInt() && scanner.hasNext())
        {
          list.add(scanner.nextInt());
          mcNug[i] = (int) list.get(i);
          i++;
          scanner.next();
        }

A: use a nextLine().
while( scanner.hasNextLine() ){
  String line = scanner.nextLine();
  String[] numbers = line.split("\\s+");
  ... do something with numbers array ..
}


text:
Q: MI Max 2 Error: App not installed I am a react-native app developer an owe mi max 2 and trying to install a apk into it but it is showing an error:

"The package conflicts with an existing package by the same name"

.
Although i have uninstalled the previous version of it but still it is showing this error. It is also giving error. What should i do ?

A: You must uninstall application via adb instead, although you already uninstalled application using the normal method
Run this command when you connect android phone with PC via USB adb uninstall <package_name>
more info read this answer


text:
Q: Why do these two cases show different results for Array elements in Java? Here, the value of Array arr elements do not change after changing values of a and b.
int a=10, b=20;
int[] arr = {a,b};
a = 20;
b = 10;
System.out.println("a = " + a); // a=20
System.out.println("b = " + b); // b=10
System.out.println(Arrays.toString(arr)); // prints [10, 20]

Here, intArr2 elements change value once you change value of IntArr elements.
int[] intArr = {10,12};
int[] intArr2 = intArr;
intArr[1] = 1000;
System.out.println("intArr2[1]: " + intArr2[1]); // prints 1000

And here, it doesn't change the value of str Array elements:
        String word1="abc";
        String word2="def";
        String[] str = {word1, word2};
        word1 = str[1];
        word2 = str[0];
        System.out.println("word1 = " + word1); //def
        System.out.println("word2 = " + word2); //abc
        System.out.println(Arrays.toString(str)); // prints [abc, def]

Can someone please explain this?

A: In first case, values of a & b are assigned to array arr. So after assigned any change in a, b doesn't reflect to arr.
In second case intArr2 is using the reference of intArr, so any change in any one of these array should reflect both, in fact the location is unique.
Does it make sense to you?

A: Every object, has 2 things that can make it be distinguished.

*

*Its Value

*Its address

one is having a value(intArr) and the other is having address (intArr2)


text: Q: Let $X\in\mathbb{A}^n$ be a variety, $U\in X$ open, $f\in A(X)$, $f(x)=0\ \forall\ x\in U$, then $f=0$. I know that an analogous statement holds true in complex analysis, but I don't know how to prove the statement here. I know that $U$ is dense in $X$, and $f:X\to\mathbb{A}^1$ defines a continuous mapping, and the usual theorem in topology is that for topological spaces $X$, $Y$, with $Y$ Hausdorff, given $U\in X$ a dense set, and $f,g:X\to Y$ continuous s.t. $f|_U=g|_U$, then $f=g$ on all of $X$. However, $\mathbb{A}^1$ is not Hausdorff, so this particular approach doesn't seem to work.


text:
Q: Import of xml with XPath and encoding I would like to import data from an xml with german umlauts (ä,ö,ü). To analyze the problem I imported the data as sql-insert, csv-file and xml-file. To see the source of the imports the entries are marked with prefix insert,csv and xml. Here is the result:

The umlauts from the xml source are not correctly imported.
Here are the codes to produce this:
Table definition
DROP TABLE IF EXISTS test01.animal;
CREATE TABLE test01.animal (
name VARCHAR(50) DEFAULT NULL
, category VARCHAR(50) DEFAULT NULL
) ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci
;

INSERT
INSERT INTO test01.animal (name, category)
VALUES
('insert_snäke','reptile')
,('insert_frög','amphibian')
,('insert_tüna','fish')
,('insert_racoon','mammal')
;

CSV
data
csv_snäke,reptile
csv_frög,amphibian
csv_tüna,fish
csv_racoon,mammal

sql
LOAD DATA INFILE 'C:/animals.csv'
INTO TABLE test01.animal
FIELDS TERMINATED BY ','
;

XML
data
<?xml version="1.0" encoding="UTF-8"?>
<database>
 <select query="SELECT name, category FROM animal">
  <row>
   <name>xml_snäke</name>
   <category>reptile</category>
  </row>
  <row>
   <name>xml_frög</name>
   <category>amphibian</category>
  </row>
  <row>
   <name>xml_tüna</name>
   <category>fish</category>
  </row>
  <row>
   <name>xml_racoon</name>
   <category>mammal</category>
  </row>
 </select>
</database>

Perl/XPath
use strict;
use DBI;
use XML::XPath;
use XML::XPath::XMLParser;

my $dir0 = "C:";

my $dbh = DBI->connect ("DBI:mysql:test01",
                        "root", "fire2013",
                        { RaiseError => 1, PrintError => 0});
my $xp = XML::XPath->new (filename => "$dir0/animals.xml");
my $nodelist = $xp->find ("//row");
foreach my $row ($nodelist->get_nodelist ())
    {
        $dbh->do (
            "INSERT INTO animal (name, category) VALUES (?,?)",
            undef,
            $row->find ("name")->string_value (),
            $row->find ("category")->string_value ()
            );
    }
$dbh->disconnect ();

Any idea why I don't get umlauts by importing xml? Any help appreciated. Thanks.
PS: Windows 7 / MariaDB 5.5.31 / Strawberry Perl 5.16

A: Try this:
$dbh->do(qq{SET NAMES 'utf8'}) or die $dbh->errstr;


text:
Q: Why DataGridView cell does not accept value from textbox I populate DataGridView1 by typing into cells or by passing text to a cell from TextBox1 when clicking on a button:
ButtonClick_PassTextToDataGridView1:
 DataGridView1.SelectedRows(0).Cells(2).Value = TextBox1.Text

ButtonClick2_Update DataGridView:
 Dim cmdbuilder As New OleDb.OleDbCommandBuilder(adp)
 adp.Update(ds, "Table1")

What I type in the cells are saved into the table, but problem is what I pass from TextBox1.Text to DataGridView1.SelectedRows(0).Cells(2) does not persist.
Any ideas about this?


text:
Q: giving 2 diff users access to a folder I need to give access to 2 users one with read access and other with write access to a particular folder(/folder). Both the users are supposed to be in the same group(sftp)
user with read access: readsftp
user with write access: writesftp
I have done
useradd -G sftp readsftp
useradd -G sftp writesftp

Now the user writesftp should be able to write files to /folder and user readsftp should be able to only read files in the folder /folder
The vipw files read
36 sftp:x:47173:47173::/data:/bin/sh
37 ft:x:1002:1002::/home/ft:/bin/bash
38 readsftp:x:47176:47173::/data:/bin/sh
39 writeuser:x:47177:47173::/data:/bin/sh

Have I changed it rightly?
(Please observe the ID's)
Could you please help me do this by using sticky bit, and umask and chmod? In the /folder folder
I have previously changed files and folder permissions using chmod and I am unable to get through the right understanding on how to do it wrt users.
Thanks in advance.

A: First, you need to transfer the ownership of the folder (recursively) to writeftp and the group ownership to sftp:
sudo chown -R writeftp:sftp /path/to/folder

Then you enable executable permissions for the group to all folders and full permissions to the owner:
find /path/to/folder -type d -exec chmod 750 {} \;

and set read permissions for all files to the group and read/write permissions for the owner for all files:
find /path/to/folder -type f -exec chmod 640 {} \;

Following the above steps you'll solve your problem, but however, there are better solutions for your problem. You could use ACLs (access control lists) on that file system or use SELinux while the latter is much more complicated to configure and maintain.


text:
Q: How does PLTScheme Catch errors? I am amazed by the "error" function in PLTScheme.
If I have a division by zero, it doesnt do any other recursion and just comes out of the call stack and give me an error.
Is there an implicit continuation before all the functions? Does the error throw away the call stack? Does anybody have any idea about this?

A: In PLT Scheme, the procedure error raises the exception exn:fail, which contains an error string. There is no "implicit catch" for all defines. Look at the following sample:
;; test.ss
(define (a d)
  (printf "~a~n" (/ 10 d)))

(a 0) ;; The interpreter will exit here.
(printf "OK~n")

Execute the above script from the command line and you will see the interpreter existing after printing something like
/: division by zero

 === context ===
/home/user/test.ss:1:0: a

If an exception is not handled within the user program, it is propagated up to the core interpreter where a default handler deals with it, i.e print the exception and exit. In other words, the interpreter just says, "an exception was raised and I don't know how to deal with it, so I am quiting". This is not much different from how the JVM or some other virtual machine handle exceptions.
To learn more about PLT Scheme's exception handling mechanism, please read about with-handlers and dynamic-wind in the MzScheme Language Manual. Using these, you can even emulate Java's try-catch-finally block.
(define (d a b)
  (try
   (printf "~a~n" (/ a b))
   (catch (lambda (ex)
            (printf "Error: ~a" ex)))
   (finally
    (if (> b -2)
      (d a (sub1 b))))))

Here is the syntax extension that made the above possible:
;; try-catch-finally on top of with-handlers and dynamic-wind.

(define-syntax try
  (syntax-rules (catch finally)
    ((_ try-body ... (catch catch-proc))
     (with-handlers (((lambda (ex) #t)
              (lambda (ex)
            (catch-proc ex))))
            (begin
              try-body ...)))
    ((_ try-body ... (catch catch-proc) (finally fin-body ...))
     (dynamic-wind
     (lambda () ())

     (lambda ()
       (with-handlers (((lambda (ex) #t)
                (lambda (ex)
                  (catch-proc ex))))
              (begin
                try-body ...)))

     (lambda () fin-body ...)))
    ((_ try-body ... (finally fin-body ...))
     (dynamic-wind
     (lambda () ())

     (lambda () try-body ...)

     (lambda () fin-body ...)))))


text:
Q: Comparing string input I'm not sure why guess isn't the same as words[random][0] even if I type the correct answer. It skips the if statment and goes to else.
    do{

System.out.println("The scrambled word is: " + scramble[random]);

                Scanner fooBar = new Scanner(System.in);

                System.out.println("What is this word?: ");
                guess = fooBar.next();

                if(guess == words[random][0])
                {
                    System.out.println("Congratulations, you have guessed correctly!");
                    done = true;
                }
            else
                System.out.println("Sorry, that is not it.");

            }while(done == false);


text:
Q: Sorting pandas dataframe by groups I would like to sort a dataframe by certain priority rules.
I've achieved this in the code below but I think this is a very hacky solution.
Is there a more proper Pandas way of doing this?
import pandas as pd
import numpy as np

df=pd.DataFrame({"Primary Metric":[80,100,90,100,80,100,80,90,90,100,90,90,80,90,90,80,80,80,90,90,100,80,80,100,80],
                "Secondary Metric Flag":[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0],
                "Secondary Value":[15, 59, 70, 56, 73, 88, 83, 64, 12, 90, 64, 18, 100, 79, 7, 71, 83, 3, 26, 73, 44, 46, 99,24, 20],
                "Final Metric":[222, 883, 830, 907, 589, 93, 479, 498, 636, 761, 851, 349, 25, 405, 132, 491, 253, 318, 183, 635, 419, 885, 305, 258, 924]})

Primary_List=list(np.unique(df['Primary Metric']))
Primary_List.sort(reverse=True)

df_sorted=pd.DataFrame()

for p in Primary_List:
    lol=df[df["Primary Metric"]==p]
    lol.sort_values(["Secondary Metric Flag"],ascending = False)

    pt1=lol[lol["Secondary Metric Flag"]==1].sort_values(by=['Secondary Value', 'Final Metric'], ascending=[False, False])

    pt0=lol[lol["Secondary Metric Flag"]==0].sort_values(["Final Metric"],ascending = False)

    df_sorted=df_sorted.append(pt1)
    df_sorted=df_sorted.append(pt0)

df_sorted

The priority rules are:

*

*First sort by the 'Primary Metric', then by the 'Secondary Metric
Flag'.

*If the 'Secondary Metric Flag' ==1, sort by 'Secondary Value' then
the 'Final Metric'

*

*If ==0, go right for the 'Final Metric'.

Appreciate any feedback.

A: You do not need for loop and groupby here , just split them and sort_values
df1=df.loc[df['Secondary Metric Flag']==1].sort_values(by=['Primary Metric','Secondary Value', 'Final Metric'], ascending=[True,False, False])
df0=df.loc[df['Secondary Metric Flag']==0].sort_values(["Primary Metric","Final Metric"],ascending = [True,False])

df=pd.concat([df1,df0]).sort_values('Primary Metric')

A: sorted with loc
def k(t):
    p, s, v, f = df.loc[t]
    return (-p, -s, -s * v, -f)

df.loc[sorted(df.index, key=k)]

    Primary Metric  Secondary Metric Flag  Secondary Value  Final Metric
9              100                      1               90           761
5              100                      1               88            93
1              100                      1               59           883
3              100                      1               56           907
23             100                      1               24           258
20             100                      0               44           419
13              90                      1               79           405
19              90                      1               73           635
7               90                      1               64           498
11              90                      1               18           349
10              90                      0               64           851
2               90                      0               70           830
8               90                      0               12           636
18              90                      0               26           183
14              90                      0                7           132
15              80                      1               71           491
21              80                      1               46           885
17              80                      1                3           318
24              80                      0               20           924
4               80                      0               73           589
6               80                      0               83           479
22              80                      0               99           305
16              80                      0               83           253
0               80                      0               15           222
12              80                      0              100            25

sorted with itertuples
def k(t):
    _, p, s, v, f = t
    return (-p, -s, -s * v, -f)

idx, *tups = zip(*sorted(df.itertuples(), key=k))

pd.DataFrame(dict(zip(df, tups)), idx)

lexsort
p = df['Primary Metric']
s = df['Secondary Metric Flag']
v = df['Secondary Value']
f = df['Final Metric']
a = np.lexsort([
    -p, -s, -s * v, -f
][::-1])

df.iloc[a]

Construct New DataFrame
df.mul([-1, -1, 1, -1]).assign(
    **{'Secondary Value': lambda d: d['Secondary Metric Flag'] * d['Secondary Value']}
).pipe(
    lambda d: df.loc[d.sort_values([*d]).index]
)


text:
Q: OSX: Dynamically binding a dylib with the loading executable I'm loading a dylib from an OSX executable using dlopen. I would like the dylib to resolve it's symbols by binding back with the original executable. Is this possible?
Note that the main executable will always have a known name, i.e. I don't need to dynamically tell the dylib what to bind back to.
To be clear, I have
X: OSX executable
D: OSX dylib

*

*Run X.

*X calls dlopen (at some point in time) to open D.

*D has undefined symbols which should be resolved against X.

*OSX automatically binds undefined symbols in D against X before static constructors in D are run.

N.B. The last part about static ctrs is crucial.
I basically want an LC_LOAD_DYLIB load command referencing back to the original binary.
EDIT
I'm pretty sure I can work around the issue by adding an intermediate dylib E. Then I can do:

*

*Run X.

*X calls dlopen (at some point in time) to open E.

*E initialises some proxy symbols then calls dlopen to open D.

*D's undefined symbols resolve against E's proxy symbols.

*E implements it's proxy symbols (manually) using X.

Bit annoying if that's the only way to do this though.


text:
Q: XTS searching in dates prior to current index I have an xts with OHLC and a logical column: isSwingBottom. I want a new column that gives the index of first occurrence of isSwingBottom by searching only in dates prior to the current row. I need the closest found row.
For example, in this data for isSwingBottom, 1995-10-04/1995-10-10 should be NA, 1995-10-11/1995-10-31 should be 1995-10-10 and so on. I want to avoid using a loop.
myXTS <- structure(c(408.75, 417.2937, 423.3188, 423.775, 419.3375, 415.55,
419.325, 417.25, 415.8375, 411.7812, 408.975, 406.2625, 396.6062,
385.6125, 374.375, 368.0375, 369.8625, 356.2688, 360.45, 357.45,
354.35, 363.6313, 356.25, 361.0813, 364.375, 365.9, 351.15, 342.0375,
333.5938, 315.4812, 418.75, 431.25, 431.25, 429.375, 421.875,
422.5, 419.375, 418.125, 417.5, 415.625, 411.875, 406.25, 396.875,
378.75, 393.8188, 373.5, 371.5, 366.25, 366.25, 358.4937, 364.625,
372.25, 363.75, 368.75, 369.25, 362.5, 350, 343.75, 337.5, 322.5,
408.75, 417.625, 420.625, 415.625, 412.5, 417.625, 417, 415.125,
406.25, 406.25, 405, 387.5, 382.5, 368.75, 361.875, 368.125,
353.75, 350, 356.25, 350.875, 355, 360.625, 355.125, 358.875,
362.5, 344, 339.5, 332.5, 313.375, 309.5, 417.2937, 423.3188,
423.775, 419.3375, 415.55, 419.325, 417.25, 415.8375, 411.7812,
408.975, 406.2625, 396.6062, 385.6125, 372.0562, 368.0375, 369.8625,
356.2688, 360.45, 357.45, 354.35, 363.6313, 361.5, 361.0813,
364.375, 365.9, 351.15, 342.0375, 333.5938, 315.4812, 315.8188,
4560, 11120, 30840, 8640, 7400, 3040, 6360, 1720, 6080, 6840,
9200, 38440, 53000, 32000, 46240, 17680, 57240, 57840, 28680,
28880, 66760, 56640, 23240, 33480, 39120, 62480, 64320, 79920,
66320, 60360, NA, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, NA, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0,
0, 0, 0), .Dim = c(30L, 7L), .Dimnames = list(NULL, c("Open",
"High", "Low", "Close", "Volume", "isSwingBottom", "isSwingTop"
)), index = structure(c(812764800, 812851200, 812937600, 813196800,
813283200, 813369600, 813456000, 813542400, 813801600, 813888000,
813974400, 814060800, 814147200, 814406400, 814492800, 814579200,
814665600, 814752000, 815011200, 815097600, 815184000, 815270400,
815356800, 815616000, 815702400, 815788800, 815875200, 815961600,
816220800, 816307200), tzone = "UTC", tclass = "Date"), class = c("xts",
"zoo"))

A: If you want a new column with dates you might need to convert myXTS to dataframe. Try this approach :
library(dplyr)
library(zoo)
library(tidyr)

myXTS %>%
  fortify.zoo() %>%
  mutate(new_col = if_else(isSwingBottom == 1, Index, as.Date(NA))) %>%
  fill(new_col)

#        Index     Open     High     Low    Close Volume isSwingBottom isSwingTop    new_col
#1  1995-10-04 408.7500 418.7500 408.750 417.2937   4560            NA          0       <NA>
#2  1995-10-05 417.2937 431.2500 417.625 423.3188  11120             0          0       <NA>
#3  1995-10-06 423.3188 431.2500 420.625 423.7750  30840             0          0       <NA>
#4  1995-10-09 423.7750 429.3750 415.625 419.3375   8640             0          0       <NA>
#5  1995-10-10 419.3375 421.8750 412.500 415.5500   7400             1          0 1995-10-10
#6  1995-10-11 415.5500 422.5000 417.625 419.3250   3040             0          1 1995-10-10
#7  1995-10-12 419.3250 419.3750 417.000 417.2500   6360             0          0 1995-10-10
#8  1995-10-13 417.2500 418.1250 415.125 415.8375   1720             0          0 1995-10-10
#9  1995-10-16 415.8375 417.5000 406.250 411.7812   6080             0          0 1995-10-10
#10 1995-10-17 411.7812 415.6250 406.250 408.9750   6840             0          0 1995-10-10
#11 1995-10-18 408.9750 411.8750 405.000 406.2625   9200             0          0 1995-10-10
#12 1995-10-19 406.2625 406.2500 387.500 396.6062  38440             0          0 1995-10-10
#13 1995-10-20 396.6062 396.8750 382.500 385.6125  53000             0          0 1995-10-10
#14 1995-10-23 385.6125 378.7500 368.750 372.0562  32000             0          0 1995-10-10
#15 1995-10-24 374.3750 393.8188 361.875 368.0375  46240             0          0 1995-10-10
#16 1995-10-25 368.0375 373.5000 368.125 369.8625  17680             0          0 1995-10-10
#17 1995-10-26 369.8625 371.5000 353.750 356.2688  57240             0          0 1995-10-10
#18 1995-10-27 356.2688 366.2500 350.000 360.4500  57840             0          0 1995-10-10
#19 1995-10-30 360.4500 366.2500 356.250 357.4500  28680             0          0 1995-10-10
#20 1995-10-31 357.4500 358.4937 350.875 354.3500  28880             1          0 1995-10-31
#21 1995-11-01 354.3500 364.6250 355.000 363.6313  66760             0          0 1995-10-31
#22 1995-11-02 363.6313 372.2500 360.625 361.5000  56640             0          1 1995-10-31
#23 1995-11-03 356.2500 363.7500 355.125 361.0813  23240             1          0 1995-11-03
#24 1995-11-06 361.0813 368.7500 358.875 364.3750  33480             0          0 1995-11-03
#25 1995-11-07 364.3750 369.2500 362.500 365.9000  39120             0          1 1995-11-03
#26 1995-11-08 365.9000 362.5000 344.000 351.1500  62480             0          0 1995-11-03
#27 1995-11-09 351.1500 350.0000 339.500 342.0375  64320             0          0 1995-11-03
#28 1995-11-10 342.0375 343.7500 332.500 333.5938  79920             0          0 1995-11-03
#29 1995-11-13 333.5938 337.5000 313.375 315.4812  66320             0          0 1995-11-03
#30 1995-11-14 315.4812 322.5000 309.500 315.8188  60360            NA          0 1995-11-03


text:
Q: MapView in android is it possible to achieve something like this?
I am preparing one application using mapView, i want to display the current location and even add marks of all other users.. that thing i implemented now i want to select some marks by drawing circle on mapView. i.e first user will zoom the map at his desire level then, the user will select the number of users by drawing circle on mapView and at that time zoom of map will freeze i.e on pinch zoom circle will draw on zooming functionality of map.
Is there a sample code on this implementation?
Thanks!

A: Adding items on the MapView onTouch
and
Drawing a circle on the MapView


text:
Q: Fetch data from internet on App install android I developed an app which fetches a website data. Now the app will work only when the internet is available. But I want to add some content to the app for viewing in offline mode. So I want to know is it possible to fetch data from internet on installation time?

A: It's not possible. You can consider downloading your data on first launch.


text:
Q: emacs AUCTeX macros fontification I recently started using the excellent package xargs
that provides \newcommandx. It shares a syntax similar to the default \newcommand.
I would like font-lock to reflect this.
I did
(custom-set-variables
 '(font-latex-user-keyword-classes
   (quote (("cx" ("newcommandx" "*|{\\[[{")
        (:family "font-lock-type-face") command)))))

But this fontifies just the command name itself, not its body
(\newcommand fontifies the body with 'font-lock-function-name-face,
which in my case is bold). I want \newcommandx to fontify its body with 'font-lock-function-name-face.
To summarize the question: how to make fontification for \newcommandx be exactly the same as for \newcommand (i.e. bold body in my case)?

A: Here is an example that you can modify to suit your needs.  See lines 280 to 436 of font-latex.el within auctex-11.86 for a complete list of predefined keywords.  The following examples are used to add additional keywords, and/or define your own coloration for the contents of wavy / square brackets.
;; \EFFECT{[font-lock-function-name-face]}
(setq font-latex-match-function-keywords
    '(
        ("newcommandx" "*|{\\[[{")
    )
 )

;; \EFFECT{[font-lock-constant-face]}
(setq font-latex-match-reference-keywords
    '(
        ("fancypagestyle" "[{")
        ("fancyhead" "[{")
        ("fancyfoot" "[{")
    )
 )

;; \EFFECT{[font-lock-type-face]}
(setq font-latex-match-textual-keywords
    '(
        ("parentext" "{")
        ("hybridblockquote" "[{")
        ("parskip" "")
        ("footskip" "")
    )
)

;; \EFFECT{[font-lock-variable-name-face]}
(setq font-latex-match-variable-keywords
    '(
        ("newgeometry" "[{")
        ("quotingsetup" "[{")
        ("TabPositions" "[{")
        ("rfoot" "")
    )
)

;; \font-latex-warning-face
(setq font-latex-match-warning-keywords
    '(
        ("fixme" "{")
    )
)

;; only affects inside wavy brackets
(setq font-latex-user-keyword-classes
          '(("my-warning-commands"
                (("fixme" "{"))
                (:foreground "purple" :background "yellow")
                command)))

See also:  http://www.gnu.org/software/auctex/manual/auctex/Fontification-of-macros.html

I have chosen the following method to customize all of my special keywords:
(defvar lawlist-face-01 (make-face 'lawlist-face-01))
(set-face-background 'lawlist-face-01 "black")
(set-face-foreground 'lawlist-face-01 "white")
(set-face-bold-p 'lawlist-face-01 t)
(set-face-italic-p 'lawlist-face-01 t)
(set-face-underline-p 'lawlist-face-01 t)
(set-face-underline 'lawlist-face-01 "yellow")

(defvar lawlist-face-02 (make-face 'lawlist-face-02))
(set-face-attribute 'lawlist-face-02 nil :background "gray" :foreground "red" :font "Courier" :height 180 :bold t :underline "yellow" :italic t)

(font-lock-add-keywords 'latex-mode '(
("\\\\test01\\|insert\\|BUGS\\|FIXME\\|TODO\\|and\\|or\\|not" 0 lawlist-face-01 prepend) ;; 0 = highlight all
("\\\\test02\\|INSERT\\|document-name\\|\\\\begin{document}" 0 lawlist-face-02 prepend) ;; 0 = highlight all
("\\test01{\\([^}]*\\)}" 1 lawlist-face-02 prepend) ;; 1 = colorize contents of wavy brackets
))


text:
Q: Saving a "for loop" iteration When I run the code below, the for loop saves the first text correctly into a separate file, but the second iteration saves the first AND the second into another separate file, and the third iteration saves the first, second and third into a separate file and so on.... I'd like to save each iteration into a separate file but not adding the previous iterations. I don't have a clue to what I'm missing here. Can anyone help, please?
import requests

from bs4 import BeautifulSoup

import pandas as pd

base_url = 'http://www.chakoteya.net/StarTrek/'

end_url = ['1.htm', '6.htm', '8.htm', '2.htm', '7.htm',
          '5.htm', '4.htm', '10.htm', '12.htm', '11.htm', '3.htm', '16.htm']

episodes = []

count = 0

   for end_url in end_url:

             url = base_url + end_url

             r = requests.get(url)

             soup = BeautifulSoup(r.content, 'html.parser')

             episodes.append(soup.text)

             file_text = open(f"./{count}.txt", "w")

             file_text.writelines()

             file_text.close()

             count = count + 1

             print(f"saved file for url:{url}")

A: It doesn't appear that your code would save anything to the files at all as you are calling writelines with no arguments
if __name__ == '__main__':
    import requests
    from bs4 import BeautifulSoup

    base_url = 'http://www.chakoteya.net/StarTrek/'
    paths = ['1.htm', '6.htm', '8.htm', '2.htm', '7.htm',
             '5.htm', '4.htm', '10.htm', '12.htm', '11.htm', '3.htm', '16.htm']

    for path in paths:
        url = f'{base_url}{path}'
        filename = path.split('.')[0]
        r = requests.get(url)
        soup = BeautifulSoup(r.content, 'html.parser')

        with open(f"./{filename}.txt", "w") as f:
            f.write(soup.text)

        print(f"saved file for url:{url}")

This is reworked a little.  It wasn't clear why the data was appending to episodes so that was left off.
Maybe you were writing the list to the file which would account for dupes.  You were adding the content to each file to a list and writing that growing list each iteration.

A: You needed to empty your episodes for each iteration. Try the following:
import requests

from bs4 import BeautifulSoup

import pandas as pd

base_url = 'http://www.chakoteya.net/StarTrek/'

end_url = ['1.htm', '6.htm', '8.htm', '2.htm', '7.htm',
           '5.htm', '4.htm', '10.htm', '12.htm', '11.htm', '3.htm', '16.htm']

count = 0

for end_url in end_url:
    episodes = []
    url = base_url + end_url

    r = requests.get(url)

    soup = BeautifulSoup(r.content, 'html.parser')

    episodes.append(soup.text)

    file_text = open(f"./{count}.txt", "w")

    file_text.writelines(episodes)

    file_text.close()

    count = count + 1

    print(f"saved file for url:{url}")

A: Please consider the following points!

*

*there's no reason at all to use bs4! since response.text is actually holding the same.

*You've to use Same Session explained on my previous answer

*You can use iteration with fstring/format which will let your code more cleaner and easier to read.

*with context manager is less headache as you don't need to remember to close your file after!

import requests

block = [9, 13, 14, 15]

def main(url):
    with requests.Session() as req:
        for page in range(1, 17):
            if page not in block:
                print(f'Extracing Page# {page}')
                r = req.get(url.format(page))
                with open(f'{page}.htm', 'w') as f:
                    f.write(r.text)

main('http://www.chakoteya.net/StarTrek/{}.htm')


text:
Q: TypeError when passing mocked object to parent constructor with PHPUnit In my project, I have the following structure where Foo (subject of tests) inherit ParentFoo and A implements AInterface.
The ParentFoo constructor receives an instance of AInterface. The Foo constructor needs to execute some code and receive an instance of A.
class Foo extends ParentFoo
{
    public function __constructor(A $a)
    {
        // ...
        parent::__construct($a);
    }
}

class ParentFoo
{
    public function __constructor(AInterface $a)
    {
        // ...
    }
}

class A  implements AInterface
{
    // ...
}

In the tests, I mock the object A - which make PHPUnit generate the Mock_A_62d11d77 object - and I pass it to the Foo constructor.
class FooTest extends PHPUnit\Framework\TestCase
{
    public function testFooMethod()
    {
        $mockA = $this
            ->getMockBuilder(A::class)
            ->disableOriginalConstructor()
            ->getMock();

        $foo = new Foo($mockA);   // error stack begins here <
        // ...
    }
}

However, it is returning the following error:
TypeError: Argument 1 passed to ParentFoo::__construct() must be an instance of AInterface, instance of Mock_A_62d11d77 given

Does anyone know if I should mock differently or something else?

A: I cannot reproduce your problem:
<?php declare(strict_types=1);
interface AnInterface
{
}

class AnInterfaceImplementation implements AnInterface
{
}

class ParentClass
{
    public function __constructor(AnInterface $i)
    {
    }
}

class ChildClass extends ParentClass
{
    public function __constructor(AnInterface $i)
    {
        parent::__construct($i);
    }
}

final class Test extends PHPUnit\Framework\TestCase
{
    public function testOne(): void
    {
        $i = $this->createStub(AnInterfaceImplementation::class);

        $o = new ChildClass($i);
    }
}

$ phpunit Test.php
PHPUnit 9.1.4 by Sebastian Bergmann and contributors.

R                                                                   1 / 1 (100%)

Time: 00:00.022, Memory: 6.00 MB

There was 1 risky test:

1) Test::testOne
This test did not perform any assertions

/home/sb/Test.php:27

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Risky: 1.


text:
Q: Brother DCP-L2560DW will it work on ubuntu Has anyone used this printer? And do it work properly on Ubuntu 14.04 wireless, the same goes for the scanner.

A: Just installed using this driver: http://support.brother.com/g/b/downloadlist.aspx?c=gb&lang=en&prod=dcpl2560dw_eu&os=128
Printing and scanning seem to work fine.


text:
Q: Regex precedence for multiple characters building on from this question, I have a problem extending my regex, which now looks like this:
String pattern= "(?:I[XV]|X[LC]|C[DM]|[XVLCDM])+";
        String test="XM";
        System.out.println(test.matches(pattern));

The allowable characters in my string are IVXLCDMAQT
XM currently returns true. But it should not because X can only precede L or C. How can I modify my current regex to prevent XM from returning true and also have the allowable characters in my string?
Update based on request:
The precedence:
I can be followed only by X or V, X can only be followed by L or C, C can only be followed by D or M. The rest of the letters don't matter.
Thus XM should return false. However, currently it doesn't

A: If I understand your requirements, we need to remove X and C from the final alternation, and to add some lookaheads:
^(?:I(?=[XV])|X(?=[LC])|C(?=[DM])|[VLDM])+$

Option: Allowing I, X and Cat the end of the string
If you want to allow I, X or C at the end of the string, add this: |[IXC]$ (one of several ways to do it)
The regex becomes:
(?:I(?=[XV])|X(?=[LC])|C(?=[DM])|[VLDM]|[IXC]$)+


text:
Q: Syntax highlighting with QSyntaxHighlighter in pyqt5 I have been trying to use the QSyntaxHighlighter module for highlighting syntax with QTextEdit(). I have looked here and here. Unfortunately, both are pyqt4. For example, pyqt5 doesn't use QString() or QStringList() anymore and suggests using str() and list() respectively. Even if I make the above changes I am unable to make the appropriate changes to the following code:
def highlightBlock( self, text ):
  for rule in self.highlightingRules:
    expression = QRegExp( rule.pattern )
    index = expression.indexIn( text )
    while index >= 0:
      length = expression.matchedLength()
      self.setFormat( index, length, rule.format )
      index = text.indexOf( expression, index + length )
  self.setCurrentBlockState( 0 )

The error that I get is AttributeError: 'str' object has no attribute 'indexOf'. So what should be the appropriate changes in this case for pyqt5? I am not looking forward to use QScintilla.

A: Simply replace
index = text.indexOf(expression, index + length)

with
index = expression.indexIn(text, index + length)

which should do the trick ;)