Android App Dev db.query throw error source not found

Question: I have these 2 lines in which on second line cause error when debugging in eclipse ADT:
String[] tableColumns = new String[] {"_id","name","fruitId","vegeId","totalHours"};
Cursor cursor = db.query("PickingPeriod", tableColumns,"isDeleted = 0", null, null, null, "name" );

When I took "totalHours" out of tableColumns it works ok. It seems something to do with totalHours, but it is of the same type as fruitId and vegeId: INTEGER. Can query return more than 4 columns?
also When I changed to use rawquery it all works fine:
Cursor cursor = db.rawQuery("SELECT * FROM PickingPeriod WHERE isDeleted = 0",null);

I read some suggestions that query is preferred over rawquery, therefore I'd like to get query working. Any idea what is wrong with the query lines?
thanks in advance
Comment: post your PickingPeriod table definition.
Comment: Check the spelling of totalHours and the one define in the table.
Comment: The column name totalHours has been copy-pasted throughout, and I have double checked the create table script and the mapping property in business class, all the same. Thanks anyway Hoan.
Comment: I have even renamed totalHours to hours for sake of simplicity, still no luck... super frustrating...
Comment: db.execSQL("CREATE TABLE PickingPeriod " +
    "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
    "name TEXT NOT NULL, " +
    "fruitId INTEGER NOT NULL, " +
    "vegeId INTEGER NOT NULL, " +
    "totalHours INTEGER NOT NULL, " +
    "isDeleted INTEGER NOT NULL DEFAULT 0);");
Comment: I did not see the 0 inside the quote use Shajeel Afzal answer, or just put "isDeleted = " + 0. The answer below is the prefer way.
Comment: During debug I investigated the output of db.rawquery, apparently totalHours is not included in the returned columns. How could it be in the create table script but not selected when i call "Select *" ? Is there a way to force table to be recreated?
Comment: You probably add the columns after you already created the table, just uninstall your app and run again. It will be OK.
Answer: just want to share my fix here, it was definitely caused by the missing column totalHours in the table. It must have been added into the table after the database was created under the same db version 1. I learnt to trigger the database to be recreated by updating the database version to 2. When I re-loaded the enumerator the table was recreated with column totalHours, now everything works fine. Thanks all for trying to help. Hope my solution is helpful to other beginners.
However the remaining question to me is that I don't want to be forced to increase the db version number every time I want to recreate the database, especially while fixing bugs. Is it possible to modify the database without having to increase the db version?
Comment: Just delete the data though system settings or uninstall your app. These action will delete the database. The database onCreate is called only if it does not exist.
Answer: The problem is in the 3rd argument "isDeleted = 0", Try to change your code as follows:
Cursor cursor = db.query("PickingPeriod", tableColumns,"isDeleted = ? " , new String[] { String.valueOf(0) }, null, null, "name" );
You can read about the query method on the Android Developer site.
Comment: hi Shajeel, thanks for trying to help, but your suggested code shows error: Type mismatch: cannot convert from string to int.
Comment: Check it now. I am sorry that i quickly answered you and forgot to add `new` before `String[]` in the 4th argument.


Is a function that is one-to-one necessarily onto?

Question: I'd would like to know that, because I don't want to prove a function is onto if I don't have to. If the answer is no, is there any particular case where it is true?
Comment: @DonAntonio In my experience, "codomain" is used to denote the set into which the function maps, while "range" is used to denote the image of the function.
Comment: Any function is onto its definition domain's image (codomain), so any 1-1 function is bijective with its codomain.
Comment: @AustinMohr, you may well be right. I really am not sure of this term.
Answer: The function $f:\Bbb N\to\Bbb N:n\mapsto 2n$ is one-to-one but not onto, and there are many other easy examples. An even simpler one is $g:\Bbb N\to\Bbb N:n\mapsto n+1$.
About the only simple situation in which a one-to-one function $f:A\to B$ is necessarily onto is when $A$ and $B$ are finite sets of the same cardinality.
Answer: The answer is no in general, although it does depend on the specific situation. The exponential function is one-to-one but it is not onto if we consider the co-domain to be $\mathbb{R}$. It is onto if we further restrict the co-domain to $\mathbb{R}^+$.
One prominent case in which one-to-one implies onto (and vice versa) is for linear mappings between finite dimensional vector spaces. If we have a linear mapping between spaces of equal dimension, then the mapping is one-to-one if and only if it is onto.
Comment: You cannot conclude that an injective linear map between two vector spaces of the same dimension is necessarily surjective without assuming your spaces are finite dimensional. Consider the map $(x_1,x_2,\dotsc) \mapsto (0,x_1,x_2,\dotsc)$ on some sequence space.
Comment: @kahen Yes you are right. I've added the restriction.
Answer: The function $f: \{0\} \rightarrow \mathbb{R}$ defined by $f(x) = x$ is one-to-one but not onto. (Don't be afraid to be creative with your domains and codomains!)
For a less "gimmicky" example, $f: \mathbb{R}^+ \rightarrow \mathbb{R}$ defined by $f(x) = x^2$ is one-to-one but not onto (the square of a real number is never negative).


How can I selectall visible rows in an icefaces ace:datatable?

Question: It doesn't look like the ace:datatable component has a selectall/deselectall functionality...unless you shift+click on the table directly.
I DON'T want to perform an ajax submit and modify the RowStateMap because:
a) I'd rather not do any submits until the form submission
b) RowStateMap.setAllSelected() selects ALL rows in the table regardless of visibility.
Any ideas?
Perhaps this can help.  The datatable.js file for icefaces has a method:
ice.ace.DataTable.prototype.doMultiRowSelectionEvent = function (lastIndex, current)

I tried running this directly:
<h:commandButton value="Select All"
    onclick="ice.ace.DataTable.prototype.doMultiRowSelectionEvent(0,
    ice.ace.jq('.ui-datatable-data').children().last()); return false;"/>

But that didn't seem to work.
Answer: So I created a function "doSelectAllRows" which is a copy of "doMultiRowSelectionEvent" but has the following changes:
ice.ace.DataTable.prototype.doSelectAllRows = function () {

    var self = this,
        tbody = ice.ace.jq(this.jqId).find('.ui-datatable-data'),
        elemRange = tbody.children(),
        deselectedId, firstRowSelected;

    // Sync State //
    self.readSelections();


Convert an Excel to TIFF file

Question: I have an Excel file with pixel values and I'm trying to convert it to TIFF or raster dataset to be opened with Arcgis. I looked here for similar problems and I could not find any. I tried something but it gave an error. Excel file obtained from DEM  include 2098 rows x 2851 columns without heading.
Here is my code:
import pandas as pd
import Image as im

file = r'C:/Users/owrasa/PycharmProjects/den/demrep2.xlsx'
size = 2098, 2851
df = pd.read_excel(file, header=0)
df2 = pd.np.array(df)
imarray = im.fromarray(df2)
imsave = im.SAVE(imarray, "TIFF")

Here is the error message:

TypeError: Cannot handle this data type

The Excel file looks like this:
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60      60      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60      60      60      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60      60      60      60      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60      60      60      60      60      60
-32767  -32767  -32767  -32767  -32767  -32767  -32767      60      60      60      60      60      60      60      60
-32767  -32767  -32767  -32767  -32767  -32767      60      60      60      60      60      60      60      60      60
-32767  -32767  -32767  -32767      60      60      60      60      60      60      60      60      60      60      60
-32767  -32767  -32767      60      60      60      60      60      60      60      60      60      60      60      60
-32767  -32767      59      60      60      60      60      60      60      60      60      60      60      60      60
-32767      59      59      59      59      60      60      60      60      60      60      60      60      60      60
    59      59      59      59      59      59      59      59      59      60      60      60      59      60      60
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59
    59      59      59      59      59      59      59      59      59      59      59      59      59      59      59

Comment: Just guessing, but I suspect you might have more luck if you exported the file as a CSV from Excel.
Comment: A TIFF isn't a automatically a GeoTIFF. If you use the GDAL library you can set a projection, cell size, etc.
Answer: Your code had several problems:

The Image module was not imported from PIL.
The data type of df2 was int64 rather than int32.
The call to Image.save() was incorrect (the function name has to be lowercase).

The following snippet fixes all those issues and should get the job done:
import pandas as pd
import numpy as np
import PIL.Image as im

file = r'C:/Users/owrasa/PycharmProjects/den/demrep2.xlsx'
df = pd.read_excel(file, header=0)
df2 = pd.np.array(df).astype(np.int32)
imarray = im.fromarray(df2)
imarray.save(r'C:/Users/owrasa/PycharmProjects/den/demrep2.tif')

Comment: Thank you very much. l m new user and l m happy to learn my mistake here .

Convert an Excel to TIFF file


Scale Recommendation for Tricky Key Change

Question: I'm playing a pretty tune, which calls for a solo on the following chords:

Cm G7 C Fm
A♭ Cm G Cm

As you can see, the key temporarily changes, shifting the tonic chord to major before its returns to minor.
I'm looking for a method to play around these changes. My first impression was to focus on C harmonic minor (C, D, E♭, F, G, A♭, B), which would let me comfortably play around almost all of the above chords. When the measure for the C chord comes up, I would need to accent the major 3 note (E) absent in the scale.
But maybe there's another, better way. How does one approach soloing with this key change?
Comment: There is nothing that says one set of notes (a scale if you like) will fit - or has to fit - one piece, not even if it stays in the same key! Your sequence hasn't necessarily changed key, there is some *borrowing* from a parallel key, or maybe a slight modulation. But *playing over the changes* is often a far better way to look at what to do.
Answer: It is clear that this progression is modulating to Fm, the IV of Cm.  Although the G7 is the V7 of Cm, indicating C harmonic or melodic minor I think it is clear that you will hear the change to C maj leading from G7.  Now, the C is the V of Fm, and you could pass through C7 on your way there.  The point is that one option is to play F harmonic minor starting as soon as G7 chord.  In fact the entire first line could use Fm (or harmonic and melodic variants).  This reminds me a bit of All of Me, a standard.  Even though it's in Cmaj and the very first chord is CM7 the next chord is E7, then A7 passing to Dm.  You could pass through each diatonic mode matching chords as you go by the whole first bar works well with D harmonic min, or even A harmonic minor.  The maj 3rd in the A7 does not clash with the minor mode, the combo sounds bluesy.
The Ab could be taken as the rel Maj of Fm.  Even through you start and end on Cmin try playing with Fmin and hm.
The following works imo (I've played it over your progression).
Cmin G7 play C hm
(C Fmin Ab Cmin) play F hm
(G Cmin) C hm
Keep in mind that you don't need to "accent" every chord tone or even get to them.  You could get by with minor pentatonic or blues scales, it does sound bluesy.  I would take some time to find common tones that thread through the changes or some part of them.
***** Correction *****
To add to this, another option is G phygian (C min but thought of differently) as that has the minor 3rd of F in it.  If you add the B natural in the right place it sounds like a scale used in Spanish flamenco music (kind of harmonic phygian (I made that up)).  I guess my advice would be stay away from matching chord to mode, that tends to create more work than necessary.  You can fit a single mode over it and just use voice leading to catch the "out" notes.  Since these are all leading tones you could play through them without exactly matching them.  In other words by ignoring the F natural you create interesting tension while making your life easier (win win).
Answer: I wouldn't call that a key change, unless the C major chord is held for half a minute or something. :) It's simply a temporary scale or mode change, "borrowing" a V-I (or V-i) motion from F minor. In the key of F minor, the dominant-tonic chord combination is C7 - Fm. You can expand on that idea by playing a Bbm or Bbm6 chord on top of the C major - that's even more stuff borrowed from Fm key, like iv-V-i from F minor.
There's one thing that won't work, and that's trying to fit any single scale on top of an entire progression like that. It's better if you can twist the modal feeling elastically all the time, and you already found out that your chord progression moves through different harmonic feelings, so there won't be any one-scale-fits-all solution.
Edit: I forgot the dreaded pentatonics. For example C minor pentatonic might actually fit over everything - but to my defense, the word "pretty" was mentioned in the question, so that rules out a pentatonics-for-them-all approach. ;)
Some scale ideas for each chord

Cm : C natural minor, C harmonic minor, C melodic minor, C dorian, ...
G7 : C harmonic minor, C melodic minor, G half-whole diminished,
C : F harmonic minor, F melodic minor, C half-whole diminished
Fm : C natural minor
A♭ : C natural minor
Cm : same as before
G : same as G7
Cm : same as before

However, instead of playing entire scales, overlay or outline other chords on top of the backing chords. The other chords inevitably create some scale/mode feeling. Here are some ideas for chords to outline:

Cm : (alt. 1, C natural minor) : all diatonic triads in Cm: Cm, Ddim, Eb, Fm, Gm, Ab, Bb
(alt. 2, C harmonic minor) : Cm, Fm, G
(alt. 3, C melodic minor) : Cm, F, G
(alt. 4) : Cm, Db
(alt. 5) : Cm, D major
G7 : (alt. 1) : Cm, G, Fm6, Ab, Bdim7
(alt. 2) : Cm, G, Bdim7, Fm6
(alt. 3) : Bdim7, G, E, Db
C (alt. 1) : C, Db, Edim7, F, Bbm6
(alt. 2) : C, Bb

Etc. I may have made some mistakes with the chord list, but the point is that instead of first deciding an entire scale and then playing notes and chords from that, you can play chords without thinking so much about the scale. Who cares what scale it is - you cook your own scales and change it all the time. On top of a backing Cm chord you can overlay ... Eb, Ddim, Dm7, F, Gb, A, D7, Db, Adim, G7, Bbm6, ... each of these creates a feeling and changes the mode very elastically. Someone might say, all the chords are "from" a scale and in a way it's true, but another perspective is to say that combinations of chords create a scale.
Answer: You can just improvise (play around) on the scale of Cm
using the lead tones B in G7 and E in C7
as this progression is nothing else than
i-V-(V/iv)-iv
VI-i-V-i
in C minor.
Comment: I asked because I suspected that the OP might not be familiar with the notation or the concept.
Comment: What does the "(V)" notation mean? "V of iv"?
Comment: of course: this is the writing of secondary dominants like V7/iv. I avoid the latter notation as it is also used to assign a chord above another root like F/C. **Edit:** You are right: https://de.wikipedia.org/wiki/Zwischendominante (the English translation of the "zwischendominante in (V) in English terminology is V/ ...


Enumerating through an object's properties (string) in C#

Question: Let's say I have many objects and they have many string properties.
Is there a programatic way to go through them and output the propertyname and its value or does it have to be hard coded?
Is there maybe a LINQ way to query an object's properties of type 'string' and to output them?
Do you have to hard code the property names you want to echo?
Answer: Use reflection. It's nowhere near as fast as hardcoded property access, but it does what you want.
The following query generates an anonymous type with Name and Value properties for each string-typed property in the object 'myObject':
var stringPropertyNamesAndValues = myObject.GetType()
    .GetProperties()
    .Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
    .Select(pi => new
    {
        Name = pi.Name,
        Value = pi.GetGetMethod().Invoke(myObject, null)
    });

Usage:
foreach (var pair in stringPropertyNamesAndValues)
{
    Console.WriteLine("Name: {0}", pair.Name);
    Console.WriteLine("Value: {0}", pair.Value);
}

Comment: Instead of pi.GetGetMethod().Invoke(myObject, null) I'd rather use pi.GetValue(myObject, null) - simpler to read.
Answer: You can get all the properties of a type by using the GetProperties method. You can then filter this list using the LINQ Where extension method. Finally you can project the properties using the LINQ Select extension method or a convenient shortcut like ToDictionary.
If you want to limit the enumeration to properties having of type String you can use this code:
IDictionary<String, String> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead && p.PropertyType == typeof(String))
  .ToDictionary(p => p.Name, p => (String) p.GetValue(myObject, null));

This will create a dictionary that maps property names to property values. As the property type is limited to String it is safe to cast the property value to String and the type of the returned type is IDictionary<String, String>.
If you instead want all properties you can do it like this:
IDictionary<String, Object> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead)
  .ToDictionary(p => p.Name, p => p.GetValue(myObject, null));

Answer: If your goal is simply to output the data stored in the object's properties using a human-readable format, I prefer to simply serialize the object into JSON format.
using System.Web.Script.Serialization;
//...

string output = new JavaScriptSerializer().Serialize(myObject);

Answer: How about something like this?
public string Prop1
{
    get { return dic["Prop1"]; }
    set { dic["Prop1"] = value; }
}

public string Prop2
{
    get { return dic["Prop2"]; }
    set { dic["Prop2"] = value; }
}

private Dictionary<string, string> dic = new Dictionary<string, string>();
public IEnumerable<KeyValuePair<string, string>> AllProps
{
    get { return dic.GetEnumerator(); }
}

Comment: How about we not go back to 1995 and use hashtables as classes?


Irreducibility of f following from (other) irreducible polynomial

Question: So this question will probably turn out to be way too trivial but I'd still like to get an answer because I'm not seeing it yet.
Given $f = X^{4} - 4X^{3} - 4X^{2} + 16X - 8$. I have (according to what the exercise asked me to do) shown that $(1/8)*X^{4}*f(2/X)$ is Eisenstein at 2 and therefore irreducible, but now I should see that this implies that f is also irreducible (in $\mathbb{Q}[X]$). You are seeing why? Thanks!
Answer: If $f$ were not irreducible, say $f(X) = g(X) h(X)$ for polynomials $g$ and $h$ over the rationals of degrees $d_g$ and $d_h$, both $\ge 1$, then $X^4 f(2/X)/8 = (X^{d_g} g(2/X)) (X^{d_h} h(2/X))/8$ where $X^{d_g} g(2/X)$ and $X^{d_h} h(2/X)$ would be polynomials over the rationals of degrees $d_g$ and $d_h$, so that would not be irreducible.
Comment: Unfortunately I'm still not seeing it, sorry.
Comment: What part don't you see?


Orthonormal basis for $C([0,1])$

Question: Consider the vector space $C([0,1])$ of continuous complex-valued function on the unit interval. Endow it with the inner product $\int_{0}^1f(x)\overline{g(x)}dx$.
I want to show that the set $\{e^{2\pi i kt}: k\in \mathbb Z\}$ is orthonormal.  I'm aware that a complex integral can be written in the form $\int_{a}^{b} u(x)dx +i\int_{a}^b v(x)dx$, but I'm not sure how to carry out the computations here.
I'd appreciate it if someone could give an explanation or point me to a source that includes this proof, (which I think would be somewhat common, given the relation to Fourier analysis).
Answer: I think you can just do the direct computation. Let's denote $e_k := e^{2\pi i k t}, k\in \mathbb{Z}$ then for $k \neq l$ we have
\begin{equation}
<e_k,e_l> = \int_0^1 e_k \bar e_l dt = \int_0^1 e^{2\pi i k t} e^{-2\pi i l t}dt = \int_0^1 e^{2\pi i(k - l)t}dt = \frac{1}{2\pi i (k-l)}(e^{2\pi i(k - l)} - e^0) = 0.
\end{equation}
But for $k = l$ we have
\begin{equation}
<e_k,e_k> = \int_0^1 e_k \bar e_k dt = \int_0^1 e^{2\pi i k t} e^{-2\pi i k t}dt = \int_0^1 1 dt = 1.
\end{equation}
Answer: Establish the relationship for integers $m$ and $n$
$$
\int_{0}^{1} e^{2\pi i m t} e^{-2\pi i n t} dt =
\int_{0}^{1} e^{2\pi i (m - n ) t} dt =
\begin{cases}
  1 & m=n \\
  0 & m\ne n
\end{cases}
$$

When $m\ne n$,
$$
\int e^{2\pi i (m - n ) t} dt =
\frac{i \left(1 - e^{2 i \pi  (m-n)}\right)}{2 \pi  (m-n)}
$$
When $m=n$
$$
\int e^{2\pi i (m - n ) t} dt =
\int 0 \,dt = 0
$$
Comment: The last integral is not correct. $\int_0^1 e^{0} dt = \int_0^1 1 dt = 1$. Not sure about the other integrals in the way you ahve them written but isn't $\int_0^1 e^{2\pi i k t} = 0$ for $ k \ne 0$?

Orthonormal basis for $C([0,1])$


Is there an elementary argument to show that $\prod_{n=0}^\infty \frac{2n+1}{2n+3}=0$

Question: I managed to prove it by rewriting the partial products in terms of $n!$ and then applying Stirling's approximation. But I was wondering if there is a more elementary method to show that the limit is zero, without using such heavy machinery.
Also, is it true that in general $$\prod_{n=0}^\infty \frac{an+b}{an+c}=0, \qquad a>0\ \textrm{and}\ c>b$$
Comment: See [this related question](http://math.stackexchange.com/questions/2044228/prove-that-the-infinite-product-2n3-2n2-converges-or-diverges) for other choices of $a,b,c$.
Answer: The partial products are
$$ \prod_{n=0}^N\frac{2n+1}{2n+3}=\frac{1}{3}\cdot\frac{3}{5}\cdot\frac{5}{7}\cdots\frac{2N+1}{2N+3}=\frac{1}{2N+3} $$
hence
$$\prod_{n=0}^\infty\frac{2n+1}{2n+3}=\lim_{N\to\infty}\prod_{n=0}^N\frac{2n+1}{2n+3}=\lim_{N\to\infty}\frac{1}{2N+3}=0$$
The general product $\prod_{n=0}^{\infty}\frac{an+b}{an+c}$ requires a bit more work, because there's no reason why terms should cancel as they do in this case.
Taking a logarithm of the partial product, we get
$$ \log\frac{b}{c}+\sum_{n=1}^N\log\Big(\frac{1+\frac{b}{an}}{1+\frac{c}{an}}\Big) $$
and using $\log(1+x)=x+O(x^2)$ for small $x$, we get
$$ \log\Big(\frac{1+\frac{b}{an}}{1+\frac{c}{an}}\Big)=\log\Big(1+\frac{b}{an}\Big)-\log\Big(1+\frac{c}{an}\Big)=\frac{b-c}{an}+O(n^{-2}) $$
Therefore
$$ \log\frac{b}{c}+\sum_{n=1}^{\infty}\log\Big(\frac{1+\frac{b}{an}}{1+\frac{c}{an}}\Big)$$
diverges to $-\infty$, so the product converges to $0$.
Answer: You can write the infinite product as
$$\tag 1 \prod_{n=1}^\infty \left ( 1 -\frac{2}{2n+3}\right ).$$
Apply $\ln $ to get
$$\tag 2\sum_{n=1}^\infty \ln \left( 1 - \frac{2}{2n+3}\right ).$$
Now $\ln (1-u) < -u$ for $u \in (0,1),$ so $(2) \le \sum_{n=1}^\infty -2/(2n+3) = -\infty.$ Thus $(2)=-\infty,$ hence $(1)=0.$
Your more general product can be written as
$$\prod_{n=1}^\infty \left ( 1 -\frac{c-b}{an +c}\right )$$
and the same argument argument will work, nearly verbatim, to show the product converges to $0.$
Answer: For your first question, indeed there is an easy proof that
$$
\lim_{k\to\infty} \prod_{n=0}^k \frac{2n+1}{2n+3} = 0
$$
Simply write $m=k-n$ in the product for a fixed $k$ to turn it into
$$
\prod_{m=0}^k \frac{2k-2m+1}{2k-2m+3} = \frac{2k+1}{2k+3} \cdot \frac{2k-1}{2k+1}
\cdot \frac{2k-3}{2k-1} \cdots \frac35 \cdot \frac13 = \frac{1}{2k+3}
$$
which indeed goes to zero as $k$ goes to infinity.
An identical technique works for your second problem as long as $c-b$ is a positive integer.
If $c-b = q$ with $q\in \Bbb Q$ then multiply the numerator and denominator of the fractions by by the denominator of $q$ and the same technique works again.
To prove the limit is zero when $c$ and $b$ differ by an irrational quantity, you can start by proving that for a fixed $a$ and $b$ the product for any particular $k$ is strictly decreasing in $c$, and then bracket the product by two rational $c$ products.  Then the limit is bracketted by $0$ from above and $0$ from below.


Remove subject from .ics file - python

Question: I need ur help with calendar in .ics format. I would like to remove subject appointment (text after 'SUMMARY:') from calendar with python and save it as .ics. How can I do this? Below I insert a piece of text from my .ics file.
SEQUENCE:0
BEGIN:VALARM
ACTION:DISPLAY
TRIGGER;RELATED=START:-PT5M
DESCRIPTION:Reminder
END:VALARM
END:VEVENT
BEGIN:VEVENT
UID:f468cba2-38bf-4fb1-ace1-1c6e6a9cde91
SUMMARY:
  This is a test text. This is a test text. This is a test text. This is a te
 test text.
LOCATION:calend1\;
ORGANIZER;CN=Kalendarz1:mailto:email@example.com
DTSTART;TZID="Europe/Warsaw":20180529T123000
DTEND;TZID="Europe/Warsaw":20180529T130000
STATUS:CONFIRMED
CLASS:PUBLIC
X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY
TRANSP:OPAQUE

Comment: Use [something like this](https://pypi.org/project/ics/) probably.
Answer: Your input is not a valid ICS file (note END:VEVENT before START:VEVENT and SEQUENCE outside any object). As such, you cannot use an ICS parser. Depending on where you got this file, and whether its consumer expects ICS or this broken ICS-adjacent format, you may want to invest in fixing the file.
To just strike the subject can simply use a regular expression though:
import re

with open('test.ics', 'r', encoding='utf-8') as icsf:
    broken_ics = icsf.read()

out = re.sub(r'\nSUMMARY:(?:.*(?:\n )?)*', '', broken_ics)
print(out)

Comment: This regex is what I was looking for. Thank You very much and have a nice day! :)

Remove subject from .ics file - python


Prove or find a counterexample. If $f : \mathbb{R} \to \mathbb{R}$ is a continuous function such that $f \vert_Z$ is bounded, then $f$ is bounded.

Question: In Lebl's Real Analysis, there is a question:
True/False, prove or find a counterexample. If $f : \mathbb{R} \to \mathbb{R}$ is a continuous function such that
$f \vert_Z$  is bounded, then $f$ is bounded.
I believe this is wrong and I have found a function $f(x)=\frac{1}{x}\sin({\frac{1}{x}})$
How would one go about proving this is UNBOUNDED in the real numbers. I believe I can restrict the domain to $(0,1]$ too.
Thanks :)
Comment: Your function is not defined at $x=0$, and would not be continuous there if it was.
Comment: To prove it is unbounded, show that for every $M\gt 0$ there exists a value of $x$ such that $|f(x)| \gt M$.
Answer: Hint:  find a function whose graph looks something like this.
Answer: Consider the function $f: \Bbb R \longrightarrow \Bbb R$ defined by
$$
f(x) = \left\{
        \begin{array}{ll}
            2(m+1)(x-m) & \quad m \leq x < m + \frac 1 2,\ m \in \Bbb N \cup \{0 \} \\
            -2(m+1) (x-m-1) & \quad m + \frac 1 2 \leq x < m+1,\ m \in \Bbb N \cup \{0 \} \\
             -2m (x+m) & \quad -m \leq x < -m + \frac 1 2,\ m \in \Bbb N \\
              2m (x+m-1) & \quad - m + \frac 1 2 \leq x < -m+1,\ m \in \Bbb N
        \end{array}
    \right.
$$


What is the matrix representation of the linear space isomorphism $\mathbb{R}^4\cong\mathbb{R}^{2\times2}$?

Question: Every linear map between finite dimensional vector spaces can be represented by a matrix, once bases are chosen for the domain and range spaces.
Question:  What is the matrix representation for the linear space isomorphism
\begin{align}
\mathbb{R}^{2\times2}&\rightarrow\mathbb{R}^4\\
\begin{bmatrix}a&b\\c&d\end{bmatrix}&\mapsto[a\;b\;c\;d]
\end{align}
between $\mathbb{R}^4$ and the space $\mathbb{R}^{2\times2}$ of $2\times2$ matrices, given the standard bases of these spaces?
Edit:  Let's say the standard basis of $\mathbb{R}^{2\times2}$ is:
$$
\bigg\{\begin{bmatrix}1&0\\0&0\end{bmatrix},\begin{bmatrix}0&1\\0&0\end{bmatrix},\begin{bmatrix}0&0\\1&0\end{bmatrix},\begin{bmatrix}0&0\\0&1\end{bmatrix}\bigg\}
$$
Comment: What is the standard basis of $\mathbb{R}^{2\times 2}$?  Do you order lexicographically with row first, or column first?  Or do you use another ordering?
Comment: the edit was great!
Answer: Given a map  $V \to U$ with bases $\{e_i\}_{i=1}^{n}$ and $\{u_j\}_{i=1}^n$ respectively, a matrix form is given by forming columns $[u_1 \dots u_n]$ where  $e_i \to a_{1i}u_1+ \dots a_{ni}u_n$.
In your case the map is  $e_i \to u_i$, where $u_i$ is the standard basis for $\mathbb R^4$.
This means that the matrix representation is just the identity.
Answer: Using the (ordered) basis you provided for $\Bbb R^{2\times 2}$ and the standard basis for $\Bbb R^4$, your isomorphism is given by the identity matrix! Check it out. (By the way, most people will denote elements of $\Bbb R^4$ by column vectors.)
Answer: This is a short answer to my own question.
In the given basis of $\mathbb{R}^{2\times2}$, we have that
$$
\begin{bmatrix}a&b\\c&d\end{bmatrix}=a\begin{bmatrix}1&0\\0&0\end{bmatrix}+b\begin{bmatrix}0&1\\0&0\end{bmatrix}+c\begin{bmatrix}0&0\\1&0\end{bmatrix}+d\begin{bmatrix}0&0\\0&1\end{bmatrix},
$$
so this matrix is just the point in the $4$-dimensional vector space $\mathbb{R}^{2\times2}$ with coordinates
$$
\begin{bmatrix}a\\b\\c\\d\end{bmatrix}.
$$
Hence, the desired linear space isomorphism is represented by the identity matrix.


How to find P(X > F) in ANOVA F-test?

Question: (Apologies for the ASCII tables, Stackexchange doesn't allow HTML tables and since I'm not supposed to link to an image, this is the only way I know of showing the data)
I'm learning about ANOVA F-testing and stumbled upon this problem:
There exists the following set of data regarding four teaching methods and the scores of students who were subject to each teaching method:

Method 1  Method 2  Method 3  Method 4
----------------------------------------
  65        75        59        94
  87        69        78        89
  73        83        78        80
  79        81        62        88
  81        72        83
  69        79        76
            90
------------------------------------

$\bar{x} = 75.67$       $78.43$          $70.83$         $87.75$
$s = 8.17$          $7.11$            $9.58$           $5.80$
Where $\bar{x}$ is the mean of all scores for each teaching method and $s$ is the standard deviation for each method.
After conducting an ANOVA, I derive the following ANOVA table:

Source     | Deg. Freedom |    SS     |    MS     |   F  |
-------------------------------------------------------------
Treatment  |     3        | 712.59    |  237.53   | 3.77 |
Error      |     19       | 1196.63   |  62.98    |  -   |
Total      |     22       | 1909.22   |    -      |  -   |

Now the question is: Test a level $\alpha = 0.05$ The null hypothesis is that there is no difference in mean achievement for the four teaching techniques.
So to restate:
$H_0$: Teaching technique does not have an influence on mean achievement of students
$H_1$: Teaching technique does have an influence
I work out the critical f value to be $f_{3,19;0.95}$ from an F-distribution table to be $3.1274$
The next step is what I don't understand.
We can claim that the teaching technique does have an influence on the mean achievement of the students (with less than 5% chance of being wrong)
The associated p-value is:
$p = P(X>3.77) = 0.0281$
and indeed, p < $0.05$ (hence reject of $H_0$)
But now where is this $0.0281$ from? It looks to be the probability that X > 3.77. If I'm not wrong, in this case $X ~ F_{3,19} = 3.1274$ (as calculated before) and so the p value should be the probability that 3.1274 is greater than 3.77. Now how can 3.1274 ever be greater than 3.77?
Comment: Think about it: the chance that $X$ exceeds 3.77 (the p-value) must be *less* than the chance that $X$ exceeds 3.1274 (equal to 0.05 by construction).  "The probability that 3.1274 is greater than 3.77" does not make any sense.  If you're still unclear about this, draw a sketch of the PDF of the F-distribution and highlight the areas under the curve that correspond to (a) the rightmost .05 of the total area and (b) the area to the right of 3.77.
Comment: @Arvin - The p-value is the area to the right of 3.77; with PDFs, we only look at areas.
Comment: Hmm, ok, I think I see. I graphed the F-distribution $F_{3,19}$ on an online graph generator. So is the P value the area under the graph to the right of 3.77 or is it the PDF value of the graph at 3.77?
Comment: Ok, thanks for that. Now how do we calculate the area to the right of 3.77? Is there a formula that i'm missing?
Comment: I realize that this is not the subject of your question, but in the way you have restated your hypothesis, do you notice that you have gone from testing for any statistical connection to presuming a causal connection between the two variables?
Comment: Hmm yes I see what you mean, but yeah, it doesn't make a difference to this question. I'll try to be more careful in the future though!
Comment: FWIW, Arvin, formulas for the F distribution are available at [Wikipedia](http://en.wikipedia.org/wiki/F-distribution).  Most people use software or tables :-).  But that doesn't matter here: at issue is the concept of working with *areas* and PDFs to reason about data.
Answer: The answer can not be retrieved without the aid of computation.
If you look at the F distribution table for F(3,19), you'll see that (for F(3,20):
...
.050 | 3.10
.025 | 3.86
...
Which means 0.025 < p < 0.05.
I'm guessing that they "cheated" with MATLAB or something.
Comment: Indeed they did cheat with MATLAB (Answer actually says that MATLAB gave them the answer). So I'm guessing I won't ever be asked to find a p-value in exact
Answer: Since the test statistics follows F-ratio distribution, the $\mathbb{P}(X>z)$ is known in closed form.
Let $X \sim F(n,m)$. Then
$$
   \mathbb{P}(X > z) = \tilde{B}_{\frac{m}{m+ n z}}\left( \frac{m}{2}, \frac{n}{2} \right)
$$
For $n=3$ and $m=19$ and $z=3.77$, Wolfram Alpha produces the answer of $0.0280768$.
Comment: What is B squiggly bar?
Comment: @Arvin $\tilde{B}$ stands for incomplete beta function, divided over the complete beta function, known as beta regularized
Comment: BTW, most people would not characterize the incomplete Beta function as a "closed form" except for special values of $z$.  It's an integral without a closed form expression in terms of standard functions; its calculation usually proceeds by numerical quadrature or computing sums (of potentially arbitrary length).
Comment: @whuber It's a matter of definition. If you have that special functions routinely available to you on a calculator, you would be less inclined to single it out from elementary functions. Beta regularized is [implemented](http://reference.wolfram.com/mathematica/ref/BetaRegularized.html) in _Mathematica_, as well as in R ([link](http://www.collocations.de/UCS/UCS-R-html/Rbeta.html)).
Comment: *Mathematica*'s help suggests BetaRegularized is evaluated by quadrature, not exactly. It can be important to be aware of and understand the difference, especially from a computing standpoint, so I think this is more than just a "matter of definition." Regardless, in the present context it would seem that "evaluate an incomplete Beta integral" was not what the OP meant by "missing some formula," because it's unlikely to be any more helpful than telling him to "evaluate the CDF of the F distribution" (which is commoner in software than incomplete Beta integrals, although they are equivalent).
Comment: @whuber _Mathematica_'s `BetaRegularized` is not evaluated by quadratures, but rather using its [connection](http://functions.wolfram.com/GammaBetaErf/BetaRegularized/26/01/01/0001/) to Gauss hypergeomeric function.
Comment: Nice!  That hypergeometric function in turn actually *is* evaluated in a closed form for the half-integral arguments involved in the incomplete beta.

How to find P(X > F) in ANOVA F-test?


Attempt to proof following statement (kernel and image of a matrix)

Question: Let $\{\overrightarrow u, \overrightarrow v,\overrightarrow w\}$ be an orthonormal basis of $\mathbb R^3$ with respect to the standard inproduct. We define the matrix $A$ as $A= \overrightarrow u\overrightarrow u^{tr} + \overrightarrow v\overrightarrow v^{tr} + \overrightarrow w\overrightarrow w^{tr}$.

Then show that $A=I_3$.
Hint: Use the preceding exercise and show that $Ker(A-I_3)= \mathbb R^3$.

(i) Let $\overrightarrow u = \{\overrightarrow {u_1},\overrightarrow {u_2}, \overrightarrow {u_3} \}, v=\{\overrightarrow {v_1},\overrightarrow {v_2},\overrightarrow{v_3}\},w=\{\overrightarrow {w_1},\overrightarrow {w_2},\overrightarrow {w_3}\}$ be orthonormal bases (That means you can treat them like $\{\overrightarrow {e_1}, \overrightarrow {e_2}, \overrightarrow {e_3}\}$ of $\mathbb R^3$). This means the value on the diagonals will be equal to $1$ in a matrix of $3\times 3$.
View it as
$A= \begin{bmatrix} \overrightarrow {u_1} & \overrightarrow {v_1} & \overrightarrow {w_1} \\ \overrightarrow {u_2} & \overrightarrow {v_2} & \overrightarrow {w_2} \\ \overrightarrow {u_3} & \overrightarrow {v_3} & \overrightarrow {w_3} \end{bmatrix}\cdot \begin{bmatrix} \overrightarrow {u_1^{tr}} & \overrightarrow {v_1^{tr}} & \overrightarrow {w_1^{tr}} \\ \overrightarrow {u_2^{tr}} & \overrightarrow {v_2^{tr}} & \overrightarrow {w_2^{tr}} \\ \overrightarrow {u_3^{tr}} & \overrightarrow {v_3^{tr}} & \overrightarrow {w_3^{tr}} \end{bmatrix}= \begin{bmatrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0& 0& 1 \end{bmatrix}= I_3$
(ii) Well if $A= I_3$ then we can conclude from the previous excercise that it is equal to $\mathbb R^3$.
L.S.:
Will proofs like this (i.e. informal proofs) if completed be accepted in maths journals or if someone claims to have a solution on one or more of the remaining 6 Millenium Prize Problems?
Answer: The fact that you are treating $u,v,w$ like $e_1,e_2,e_3$ of $\mathbb R^3$,means nothing at all. I do not see any similarity between $u,v,w$ an the standard basis, apart from the fact that both are orthonormal.
The way to see $A$, which you have written, is incorrect. In fact, if say $u = (u_1,u_2,u_3)$, then $uu^T$ is a $3 \times 3$ matrix, whose $(i,j)$th entry is $u_iu_j$. Similarly with $v$ and $w$. So, what you have is:
$$
A_{ij} = u_iu_j + v_iv_j + w_iw_j \quad 1 \leq i,j \leq 3
$$
You can see, for example $A_{11}$ does not match the description I gave.
For example, $A_{23} = u_2u_3 + v_2v_3 + w_2w_3$. It is not at all clear why this entry should be zero.

To show that $A = I_3$, we use the exercise given : show that $\ker(A-I_3) = \mathbb R^3$. I will now only say $I$ rather than $I_3$.
Naturally, we must first find some elements in the kernel. Let's try operating $A - I$ on $u$. What is $Au - Iu$?
$$
Au - Iu = uu^Tu + v(v^Tu) + w(w^Tu) - u = u +0+0 - u = 0
$$
so $(A-I)u = 0$. Note that $v^Tu = w^Tu = 0$ from orthogonality, and $u^Tu = 1$ from normality.

Show that $(A-I)v = (A-I)w = 0$ similarly.
So the kernel of $(A-I)$ contains $u,v,w$, which are three linearly independent elements of $\mathbb R^3$. Can you see why the kernel must be equal to $\mathbb R^3$?
Now use the exercise to complete the problem.
Comment: I must admit that I do not have enough experience (of paper writing / publishing) to comment on the second question.
Comment: The vectors that become zero is because of the fact that (let's say $\overrightarrow {u_1} \times \overrightarrow {u_2}$= 0 comes from the fact that  those vectors are othogonal to eachother.
Comment: *"So the kernel of (A−I) contains u,v,w, which are three linearly independent elements of R3. Can you see why the kernel must be equal to R3?"* Well because of the proof that it is shown in the link I provided from my previous question.
Comment: If the kernel contains $u,v,w$ then since the kernel is a subspace, it contains the smallest subspace which contains $u,v,w$,which is the span of $u,v,w$, which is $\mathbb R^3$. Of course, $\mathbb R^3$ contains the kernel,  whence they are both equal. This is another way to see the point.
Answer: Short answer: no, informal proofs are not permitted, at least, not this informal.
There will always be steps skipped in a mathematics research paper; nobody wants to read every step. However, the skipped steps should be within easy grasp of the reader, able to be filled in with relatively little effort for somebody in the field.
But, importantly, those steps have to exist. There has to be a way to fill in those gaps, all of them, right from axioms to the theorem proven. Maybe some are in a theorem printed elsewhere, or maybe they are just skipped for expediency, but they should be accessible to the interested reader.
This is the problem with your proofs. There are a number of issues, but I think this statement is fairly representative:

Let $\overrightarrow u = \{\overrightarrow {u_1},\overrightarrow {u_2}, \overrightarrow {u_3} \}, v=\{\overrightarrow {v_1},\overrightarrow {v_2},\overrightarrow{v_3}\},w=\{\overrightarrow {w_1},\overrightarrow {w_2},\overrightarrow {w_3}\}$ be orthonormal bases (That means you can treat them like $\{\overrightarrow {e_1}, \overrightarrow {e_2}, \overrightarrow {e_3}\}$ of $\mathbb R^3$).

I understand that you're going for an informal, more intuitive tone here, but it's not clear what's under the intuition. What exactly does it mean to "treat" one basis like another? Do they produce the same coordinate vectors? Since these bases can be treated as the same basis, does this mean we don't have to use any change of basis formulas? In what circumstances can we replace our bases with the standard basis?
By not being properly clear, you've left the connection between your previous statement and your next statement nebulous. Basically, you've then leapt to writing down the conclusion, in full. Somewhere in that gap of similar "treatment", there needs to be substantial logic, and it's not clear that it occurs in your proof.
Of course, learning how to write proofs properly is not easy. There's a lot of really tricky little issues and conventions that you need to learn to navigate. This proof is nowhere near a research standard, but nobody writes research standard proofs out of the gate.


What is the proper humidity range for an acoustic guitar?

Question: What is the range of relative humidity, in percentage, that is optimal for storing a guitar, cello, violin or the like in its case?
I live in Atlanta, Georgia, USA, which is a humid environment year-round. In this climate, musicians never worry about their guitars, cellos, violins and the like experiencing damage from the wood becoming too dry, not even in winter. So I have never encountered this situation before.
I have heard that guitar, cello and violin owners in dry climates use a humidification system when the instrument is stored inside the case; a sponge to deliver water vapor, and a hygrometer to measure the humidity relative to the air temperature.
I've moved into a new ground-floor condominium in Atlanta, and here in August, my rooms are so excessively humid (85% or even higher when the temperature is 78°F or 26°C) that mold and mildew have started to appear. I've had to purchase a stand-alone electric-powered building dehumidifier to remove the excess moisture. It is now removing 50 pints (24 liters) of water out of the air every 24 hours. The relative humidity is now down to about 45% at 78°F.
Is 45% relative humidity at 78°F (26°C) going to harm the wood of my guitar and my viola da gamba (similar to a cello)? Should I purchase humidifiers for the instruments in their cases? If so, what degree of relative humidity is optimal for the instruments?
Comment: Living in an area where it gets very dry in the Winter, I can tell you that every guitar seller/maker in the area recommends a humidifier for all instruments. But I can't tell you the best range for instruments.
Answer: A wooden instrument is ideally kept at about 40-60% humidity, so 45% is fabulous. This range is supposed to produce the best sound, and the least stress on the wood.
But the absolute worst thing you can do is change up the humidity frequently and quickly, because this put stress on the wood and the seams. So if your instruments spend hours a day outdoors, for instance, you might start to run into seams opening up, or even wood cracking from the wood constantly shrinking and expanding. But even this is a low risk situation, especially if you let the instrument sit in the case for a while to adjust before taking it out in new conditions.
That said, most instruments I've seen with those problems were either left in a car, or kept for long periods in an attic or basement. If you've got a lot of concerns, find a local luthier, and ask what he or she suggests.
Answer: My understanding is that the upper limit on relative humidity is set by the conditions which promote mould growth, around 70% RH (a reference for the 70% value), and not due to things like warping/splitting that you have to worry about with low humidity.
I usually target 50% RH, year around.
Martin guitars advocates 45%-55% for their instruments.
Comment: In that case, if the relative humidity in my condo is 45%, because of the need to run the dehumidifier to control the mold and mildew on surfaces, then perhaps I need to humidify my instruments to get them up to 50%, and start monitoring conditions in the winter as well.
Comment: Unless your instruments are vintage or otherwise particularly precious to you, I wouldn't sweat the difference between 45 and 50 -- plus your hydrometer may not be that accurate anyway.


MongoDB - Usar .distinct em 2 propriedades de um documento

Question: Eu tenho o seguinte conjunto de dados no meu banco:
{ "_id": 1, "dept": "A", "item": { "format": "circle", "color": "red" }}
{ "_id": 2, "dept": "A", "item": { "format": "circle", "color": "blue" }}
{ "_id": 3, "dept": "B", "item": { "format": "rect", "color": "green" }}
{ "_id": 4, "dept": "A", "item": { "format": "rect", "color": "geen" }}
{ "_id": 5, "dept": "B", "item": { "format": "circle", "color": "blue" }}
{ "_id": 6, "dept": "A", "item": { "format": "rect", "color": "blue" }}
{ "_id": 7, "dept": "B", "item": { "format": "circle", "color": "blue" }}

Eu preciso distingui-los baseado em format e em color.
O resultado deve ser assim:
{"format" : "circle", color : "red"}
{"format" : "circle", color : "blue"}
{"format" : "rect", color : "green"}
{"format" : "rect", color : "blue"}

Eu tentei usar a função distinc.
db.collection.distinct('item.format')

Porém a mesma só suporta uma propriedade
Usando a função aggregate eu não consigo distinguir as propriedades.
Algo como:
db.getCollection().aggregate([
    { $group : {
        _id : {
            format: '$item.format',
            color : '$item.color'
        }
    }},
])

Não distingue os itens por format ou color nem os agrupa em um mesmo JSON.
Alguém consegue me ajudar?
Answer: Acho que o método $unwind resolveria a sua situação.
Ele primeiro separaria os itens do item e depois você daria o aggregate group.
db.getCollection().aggregate([
    { $unwind: '$item'},
    { $group : {
        _id : {
            format: '$item.format',
            color : '$item.color'
        }
    }},
])

Comment: Isso funcionou perfeitamente. Obrigado!


Get-Command Changing Drive

Question: I wrote a powershell script that includes a check for the invoke-sqlcmd cmdlet.  Script runs fine under Windows Server 2016.  On 2012 R2, the script fails with:
Add-Content : Cannot use interface...
errors when trying to create and write to a log file.
What I discovered is that on Windows Server 2012 R2, when the Get-Command invoke-sqlcmd command is run, it changes my drive to PS SQLSERVER:\> instead of PS C:\>.  This is apparently causing my create and update log file sections to fail.
Any idea why Get-Command would change the drive when checking for a SQL cmdlet, and suggestions to change it back or prevent it in the first place?  I know I could throw a c: in the script, but that seems too simple a solution and might have to do it after every DB call.
Comment: Found an answer on stackoverflow:  https://stackoverflow.com/questions/27273440/why-working-directory-is-changing-when-executing-invoke-sqlcmd
Answer: I found an answer over on StackOverflow.
https://stackoverflow.com/questions/27273440/why-working-directory-is-changing-when-executing-invoke-sqlcmd
Apparently, on Windows Server 2012 R2, doing anything with a sql cmdlet preps the environment to run in PS SQLSERVER:\>.  Following the suggestion in the above link, I wrapped my sql cmdlets with Push-Location and Pop-Location.  This seems to resolve my issue.

Get-Command Changing Drive


How to send a Portainer Webhook to recreate a container

Question: I use Portainer v2.13.1. With a private secured Docker Registry.
After activating the Container webhook in Portainer, I do a POST Request to generated URL.

But this fails with
<code>{
    "message": "Error updating service",
    "details": "Error response from daemon: Head \"https://registry.mydomain/v2/my-gateway/manifests/1.0.3-RELEASE\": no basic auth credentials"
}
</code>
I  added a Basic Auth in Postman to the request with my docker registry credentials. But this also not worked.
How I must build the request to make this work?
Answer: I ran into the same problem as well. It's actually an issue in Portainer itself, which should be solved in the 2.14 release: https://github.com/portainer/portainer/issues/7004
Comment: This is correct
Answer: 2.14 fixes it.
It's actually because of the way the header was being used in the docker proxy.
In 2.13 you're meant to pass a portainer registryId in the x-registry-auth, and not the docker credentials.  I bet few have seen this little gem in the documentation.
https://github.com/portainer/portainer/blob/develop/api/api-description.md#private-registry
It's because we were kind of overriding the standard header.  But we've sorted that now so it'll take either option.
Fix applied here:
https://github.com/portainer/portainer/pull/7037


Erro ao exportar o data.frame para o Excel

Question: Estou tentando exportar um data.frame para o Excel, mas o R apresenta o seguinte erro:

Error in .jnew("org/apache/poi/xssf/usermodel/XSSFWorkbook") :    Java
  Exception .jnew("org/apache/poi/xssf/usermodel/XSSFWorkbook")new("jobjRef",
  jobj = , jclass =
  "java/lang/OutOfMemoryError")

O comando que gera o erro acima é
write.xlsx(base_eng, "base_eng.xlsx")

Comment: usa o pacote `writexl` no lugar. Pacotes que tem dependência de Java costumam dar muito problema.
Comment: `writexl::write_xlsx(base_eng, "base_eng.xlsx")` deve funcionar depois de você instalar o pacote
Answer: Você pode exportar para csv usando
write.table(variavel, "C:/arquivo.csv", sep = ",", row.names = FALSE)

Comment: Ou `write.csv`.


Variable selection for regression and classification

Question: This might be noob question, because I've just started to learn data analytics.
Why should we or should we not include a correlated predictor in our model?
While selecting predictors, for a class project, I observed that 4 variables exhibited more than 90% correlation with each other. I was using logistic regression for my model. And I only included one variable which gave me the lowest misclassification error during the kfold cross validation.
However, my classmates who included one other correlated variables as well the other predictors which I used, performed better on the Test Data.
On reflection, I reasoned that maybe the response could be function of both the correlated pairs ( something like y = ax + bx^2 + c).
I am still not wholly convinced of it. Could someone shed more light on this?
Answer: This is a 'for what it's worth' answer.  Firstly,  I believe one should be cautious with highly correlated variables and logistic regression.  I've heard, and have my own anecdotal evidence, of logistic regression not doing a very good job with correlated or too many variables.  Having said that, I think you have answered your own question.    You have variables, build all the models and let either cross validation or, better yet, a train/test analysis of the data, decide on which model is best. I know one can also bring AIC into the picture for logistic regression in R.
Comment: Every technique will do badly with correlated and/or too many variables if it is not regularized. Logistic regression can be regularized. Moreover, when data is abundant and collinearity is low, regularization is less effective, with the extreme that when every single data point is known (no unobserved cases exist), a nonregularized model will make the best predictions.
Comment: @ jona I agree with everything you say, but different techniques do better than others.  I certainly don't know a mathematical proof, but I believe that, for example,  random forests should specifically help with correlated variables as should neural nets. My main point was about the use of CV or train/test to answer the question.


Como faco para ler e armazenar o dados da resposta de uma API?

Question: Consegui a resposta da API da CIELO abaixo, agora gostaria de entender com faço para ler e armazenar os valores.
Se alguém puder me ajudar com quais as principais informações devo armazenar no  banco de dados?

object(stdClass)#2 (3) { ["MerchantOrderId"]=> string(16)     "2014113245231706" ["Customer"]=> object(stdClass)#3 (1) { ["Name"]=>     string(24) "Comprador rec programada" } ["Payment"]=> object(stdClass)#4    (15) { ["ServiceTaxAmount"]=> int(0) ["Installments"]=> int(1) ["Interest"]=> int(0) ["Capture"]=> bool(false) ["Authenticate"]=> bool(false) ["Recurrent"]=> bool(false) ["CreditCard"]=> object(stdClass)#5 (5) { ["CardNumber"]=> string(16) "123412******1231" ["Holder"]=> string(12) "Teste Holder" ["ExpirationDate"]=> string(7) "03/2019" ["SaveCard"]=> bool(false) ["Brand"]=> string(4) "Visa" } ["SoftDescriptor"]=> string(13) "123456789ABCD" ["Provider"]=> string(8) "Simulado" ["Type"]=> string(10) "CreditCard" ["Amount"]=> int(1500) ["Currency"]=> string(3) "BRL" ["Country"]=> string(3) "BRA" ["Status"]=> int(20) ["RecurrentPayment"]=> object(stdClass)#6 (9) { ["RecurrentPaymentId"]=> string(36) "85717927-b438-461b-908f-764772289cb5" ["ReasonCode"]=> int(0) ["ReasonMessage"]=> string(10) "Successful" ["NextRecurrency"]=> string(10) "2015-06-01" ["StartDate"]=> string(10) "2015-06-01" ["EndDate"]=> string(10) "2019-12-01" ["Interval"]=> int(6) ["Link"]=> object(stdClass)#7 (3) { ["Method"]=> string(3) "GET" ["Rel"]=> string(16) "recurrentPayment" ["Href"]=> string(107) "https://apiquerysandbox.cieloecommerce.cielo.com.br/1/RecurrentPayment/8 5717927-b438-461b-908f-764772289cb5" } ["AuthorizeNow"]=> bool(false) } }    }
Answer: Eles te retornaram um JSON, ao que parece.
Você lê os dados como um objeto normal. Por exemplo:

<?php
echo $objeto->MerchantOrderId; // output: 2014113245231706

Para salvar, depende do que você está utilizando para persistência e o que vai fazer com essas informações. Mas no geral pode salvar normalmente como qualquer outra informação. Exemplos:

Salvar num banco relacional, mapeando as propriedades deste objeto para colunas em alguma tabela ou ainda salvando o json inteiro (usando json_encode($objeto), que retorna uma string;
Salvar num banco não-relacional, como mongo ou couchdb;
Salvar em arquivo `file_put_contents("arquivo.json", json_encode($objeto));

Cabe a você definir como quer salvar estes dados.
Comment: Muito obrigado! E se eu quiser a informação mapeada abaixo: ["Payment"]["RecurrentPayment"]["StartDate"]=> string(10) "2015-06-01", como faço ?
Comment: Poderia colar o JSON assim como aparece na API?
Comment: Algo do tipo funcionaria ?
    $xmlString = "my.xml";
    $xmlObject = simplexml_load_file($xmlString);
    $xmltovar = json_decode(json_encode($xmlObject), true);

    foreach($xmltovar ["Payment"] as $test) {

         echo $test["RecurrentPayment"]["StartDate"]."";

}


Creating file from s3fs (S3 bucket) breaks migration

Question: I have s3fs module installed and configured, so when I upload some file it goes to S3 bucket.
Then I'm making processing plugin which should copy file from another S3 bucket to Drupal's bucket and register that file. Copying bucket to bucket works well, so after that part is done I have file in Drupal's bucket at private/images/image.jpg. Inside private/images folder I also have other images uploaded from the back-end so that part should be ok.
Then my transform() function of my class that extends Drupal\migrate\Plugin\migrate\process\FileCopy should create a file and return it's id. I'm doing it like:
 $file = File::create([
        'uri' => $final_destination,
        'uid' => $uid,
        'status' => FILE_STATUS_PERMANENT,
      ]);

      $file->save();
      return $file->id();

$final_destination has the value: private://images/image.jpg, file is created, id is returned.
Now the problems:

migration fails and when I list messages I get: "[file]: uri.0.value=This value should be of the correct primitive type. "
File does exist in the back-end and it's path looks ok, but when I try to open it I get the message that file doesn't exist. When comparing with some file uploaded from the back-end path looks ok and also location in the bucket is correct.
What I notice is missing is record in s3fs_file table for migrated file, while manually uploaded ones have the record there.
Tried manually adding the record there and after that when trying to open file instead of file is missing I get message that I don't have permission to see the file (logged in as master admin).

What I'm doing wrong? Should I create file somehow differently so it's also processed by s3fs module?
Update:
I added following rows after $file->save();
  $uri = $file->getFileUri();
  $stream = new S3fsStream();
  $stream->writeUriToCache($uri);

  if ($stream->waitUntilFileExists($uri)) {
    return $file->id();
  }
  throw new MigrateSkipProcessException("File could not be retrieved from S3://$uri.");

And now Instead of "file doesn't exist" I'm getting "access denied" when trying to open file, i.e. in drupal's log I see message:
Path: /system/files/images/image.jpg. Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: in Drupal\system\FileDownloadController->download() (line 80 of /var/www/web/core/modules/system/src/FileDownloadController.php).

And there request is identical (except the file name and date stumps), but header is different, for working file uploaded in back-end:
Array
(
    [Content-Type] => image/png
    [Content-Length] => 744920
    [Cache-Control] => private
)

And for problematic one:
Array
(
    [0] => -1
)

Answer: Problem was what plugin returns. It should return file uri object, and not file id:
return $file->getFileUri();

Also, if files are private and not referenced accessing them is not allowed.


How can I use a `when` clause in an ansible ad-hoc command?

Question: I am trying to see the value of an Ansible host variable, xsp_server, for all the hosts in my inventory that have xsp_server defined.  So I execute this commmand:
ansible all -i inventory/production -o -m debug \
-a msg="{% if (xsp_server is defined) %}{{ xsp_server }}{% else %}'notdefined'{% endif %}" \
| grep -v notdefined

The above command I got from this question here: Ansible ad-hoc command with conditionals
I would like to avoid having to use the | grep -v notdefined, but if I don't use the grep I get a lot of noise.  I would like to be able to execute:
ansible all -i inventory/production -o -m debug \
-a msg="{% if (xsp_server is defined) %}{{ xsp_server }}{% endif %}"

and just see output when xsp_server is defined, but I still get a bunch of ...
SUCCESS => {    "changed": false,    "msg": ""}

... lines in my output.
Comment: You cannot use a `when` command in an ad-hoc command (that is playbook syntax that's only available when you're writing a playbook).
Comment: Note that `msg="{% if (xsp_server is defined) %}{{ xsp_server }}{% endif %}"` can be simplified to `msg="{{ xsp_server | d('') }}`
Answer: As reported by @larsks, you cannot use a when clause in an ad-hoc command. Meanwhile, for the above specific case, you might achieve a similar result closer to what you expect with something like:
ANSIBLE_LOAD_CALLBACK_PLUGINS=1 \
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json \
ansible localhost -i inventory/production -m debug \
-a msg="{% set result = {} %}\
{% for s in groups['all'] %}\
{% if hostvars[s].xsp_server is defined %}\
{{ result.update({s: hostvars[s].xsp_server}) }}\
{% endif %}\
{% endfor %}\
{{ result }}" \
| jq ".plays[0].tasks[0].hosts.localhost.msg"


Converting series of Arduino switches to binary series

Question: I am currently working on a project in which there are five switches, and depending on which are on I would like it to do a specific task. I would like to know how to make it that if, say, I had switch 1 on (1), switch 2: 0, switch 3: 0: switch 4: 0, and switch 5: 1, then it would make a variable equal to 10001.
Thanks to anyone who answers!
Answer: Something like this will do (disclaimer: I didn't try to compile it, but you get the idea):
    #define SW_COUNT 5

    uint8_t pins[SW_COUNT] = {2, 3, 4, 5, 6};

    void setup(void) {
      for (uint8_t i = 0; i < SW_COUNT; i++)
        pinMode(pins[i], INPUT);
    }

    void loop(void) {
      uint8_t combined = 0;

      for (uint8_t i = 0; i < SW_COUNT; i++) {
        combined = combined << 1;
        combined |= digitalRead(pins[i]);
      }

      // Now "combined" contains the bitmask you want
    }

Comment: "pinMode(pins[i], OUTPUT);": you mean `INPUT`. But it's actually not needed, all pins are input by default.
Comment: This can be further optimized in several ways, but it's probably not worth, unless you are doing something really tight in terms of resources.
You might want to turn the for loops into functions ... but it's mostly increasing readability and slightly reducing performance, unless the compiler is smart enough to inline them.
Comment: Also, it's probably a good idea to mention that I won't be using a regular switch, I'll be using something more like this: http://forum.arduino.cc/index.php?topic=72276.0
Comment: Like it says in the link, avoid pins 0, 1 and 13: they are serial TX/RX and the LED.
Comment: Ok, so I'll just change the beginning to `uint_8 pins [SW_COUNT] = {2,3,4,5,6};`
Comment: Yes, INPUT, fixed that, thanks.
The idea of setting stuff explicitly is to avoid assumptions.
Even the mistake I made was easier to spot than a wrong assumption I could have made.
Answer: If you have something more or less compatible with an Arduino Uno, you connect your switches to pins 8, 9, etc..., then you could just do:
uint8_t combined = PINB & 0x1f;

Simple and fast, but not portable.
Compatibility: This technique is documented in the Arduino reference
on the page
Port Registers.
It applies not only to the Arduino Uno and compatible boards, but also
to all boards based on the AVR ATmega328 and ATmega168 chips, including
the Uno, Mini, Nano, Fio, Pro, as well as the older Duemilanove and
Diecimila. Boards based on the ATmega32U4 (e.g. Leonardo, Yun, Micro)
and the ATmega2560 (Mega 2560 and Mega ADK) have different pin mappings:
this technique can still be applied, but you need to select the correct
pins and the matching PINx register. The ARM-based Due has a completely
different architecture and is thus out of the scope of this technique.
The Teensy 3, although also ARM-based, supports this through AVR
emulation.
Pros and cons: This is roughly 200 times faster than the alternative
loop over digitalRead(), and is thus well suited for time-critical
work. It is also the only way to read the various inputs
simultaneously, and is the canonical way of reading inputs in the AVR
world. Looping over digitalRead(), however, is the canonical solution
in the Arduino world, as it works across the whole Arduino family, and
is based on the standard Arduino functions. The looping solution should
then be preferred for non-time-critical code that is likely to be shared
with other Arduino users who may have an incompatible board (different
pin mapping or ARM-based).
Comment: Totally not worth, imho.
What does it save? Few cycles? Some space? To which good?
It's much easier to optimize when a problem really arises than to debug/port something like that.
At minimum it should be hidden in a function/macro/method that uses it only when the right conditions are met.
Comment: yes, I do not doubt what you said, my point is solely that, unless power consumption is important, the device will basically be unused anyway.
But it's subjective opinion.
What is objective, instead, is the fact that for a generic question like this, there should be an answer that fits the various cases (think of using a DUE).
The optimized version should be confined to the problem-space it belongs to (UNO R3, for example) using some explicit means, like testing for the target #defined.
Arduino doesn't equate to AVR and even in that case, it might not be always PortB.
Comment: I'll reword the allegedly useless first comment :-D

The non portable solution should be rewritten in a way that is compatible with various scenario.

I still think that it's not easier to debug, at least not unless one has the TRM handy or knows the architecture of the uC, which is not always the case. But let's agree to disagree: we simply have different opinions on what should get higher priority.
Comment: If the question refers to "Arduino" in general, then portability _is_ a requirement. "Arduino" doesn't default to UNOR3 or equivalent.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/72933/discussion-between-edgar-bonet-and-igor-stoppa).


NotifyCollectionChangedEventArgs Item Inaccessible

Question: I have a handler for the CollectionChanged event of an ObservableCollection<T> object, and cannot figure out how to use the NotifyCollectionChangedEventArgs to retrieve the item contained within the IList for the event.
New items added to the collection are in the NewItems property, an IList object. Intellisense won't let me access .Item[Index] (which I should be able to according to the docs) nor can I cast the NewItems list to a local variable (according to debug the NewItems list is a System.Collections.ArrayList.ReadOnlyList which doesn't seem to exist as an accessible class in MSDN.)
What am I doing wrong?
Example:
private void ThisCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        Item I = e.NewItems._________;//<<<<<cannot access any property to get the item
        var j = e.NewItems;//System.Collections.ArrayList.ReadOnlyList, see if you can find in the MSDN docs.
        IList I1 = (IList) e.NewItems;//Cast fails.
        IList<Item> = (IList<Item>)e.NewItems.________;//<<<<<<<Can't make this cast without an IList.Item[Index] accessor.
        var i = j[0]; //null
        var ioption = j.Item[0]; //no such accessor
        string s = (string)i; //null
    }

This example is keeping things as generic as possible and still fails.
Comment: You should provide [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) for better assistance.
Answer: Without a good Minimal, Complete, and Verifiable code example it will be impossible to say exactly what you need to do. But in the meantime, let's try to clear up at least some of your misconceptions from the code you posted:
private void ThisCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    Item I = e.NewItems._________;//<<<<<cannot access any property to get the item
    var j = e.NewItems;//System.Collections.ArrayList.ReadOnlyList, see if you can find in the MSDN docs.
    IList I1 = (IList) e.NewItems;//Cast fails.
    IList<Item> = (IList<Item>)e.NewItems.________;//<<<<<<<Can't make this cast without an IList.Item[Index] accessor.
    var i = j[0]; //null
    var ioption = j.Item[0]; //no such accessor
    string s = (string)i; //null
}

NotifyCollectionChangedEventArgs.NewItems is a property, with the type IList, a non-generic interface. The two key aspects of this interface as it relates to the NewItems property is that you can get the Count of items, and you can index the list. Indexing the list returns an object; it's up to you to cast that to an appropriate type.
System.Collections.ArrayList.ReadOnlyList is a private class in the framework. You are not meant to use it directly. It's simply the implementation of IList that the NewItems property returns. The important thing about this implementation is that it's read-only. IList members like Add(), Insert(), and Remove() are not supported. All you can do is get items out. But just as important is that, as far as your code is concerned, the only type that's important is IList. You don't get to access members of private types directly; they are usable only through the public interfaces they implement.
You are not specific about what you mean by "Cast fails". That it would is implausible, since the NewItems property is already of the type IList. A cast to IList would succeed trivially.
It is true that you can't cast IList to the generic IList<Item>. The implementation of IList you're dealing with is the private class System.Collections.ArrayList.ReadOnlyList, which can't possibly implement the generic IList<Item> interface. After all, the ReadOnlyList was written by Microsoft and is in the .NET framework. How would they know about your Item type?
You are not meant to use the Item property indexer of an object explicitly. This exists as a hidden member. Instead, you're expected to use the built-in C# syntax where you index off the object itself. I.e. e.NewItems[0] or j[0].
Once you have assigned a null to the variable i, no amount of casting is going to change that null value into something else. Not string, not some other type.

You've tried a lot of different things, most of which make no sense so it's not a surprise they don't work. The closest you've gotten would be the j[0] expression. But you can just use e.NewItems directly. Your code should look more like this:
private void ThisCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // Assumes that the elements in your collection are in fact of type "Item"
    Item item = (Item)e.NewItems[0];

    // do something with "item"
}

However, it's important to note that you need to first check to see what kind of change has occurred to the collection. The NewItems list may be empty, if there aren't actually any new items. An element of the list may be null, if the newly set item value was in fact null. Whether you can successfully cast a non-null element value to Item depends on what Item actually is here, and whether your collection would ever actually have an element of that type in it. Likewise your attempts to cast to string. If the list doesn't contain elements of type string, then casting any non-null element value to string isn't going to work.
But these are all issues that are specific to the rest of the code. You haven't provided that, so the best I can do is try to explain in general terms all of the ways you seem to current misunderstand how this event and its supporting types work.
Comment: Thanks for the response, your snippet is perfect. I can see I was thinking of NewItems as a method instead of a list. In the interests of correcting my misunderstanding, why does an ObservableCollection implement IEnumerable (allowing the extension method .ElementAt(index)) yet the args implements IList (Not allowing ElementAt). I think this might be the source of my confusion.
Comment: `INotifyCollectionChanged` isn't generic; it needs to work with any kind of collection, including non-generic scenarios. So the generic `ElementAt(int)` method can't be used there. Note that while you can call `ElementAt(int)` on an `ObservableCollection` instance, there's no need to because you can index an `ObservableCollection` object directly, e.g. `myObservableCollection[17];` to get the element at index 17. You should prefer direct indexing over use of extension methods.


Como organizar meu projeto e ser mais produtivo?

Question: Boa noite pessoal, sou um iniciante digamos assim, e estou com dificuldades para organizar meu projeto, pois mesmo sabendo o que quero não sei a ordem dos passos para concluir meu objetivo, e me vejo perdido diversas vezes
Tentei algumas dicas que vi em outras postagens mas nada me ajudou, tentei até mesmo o github.
Alguem poderia compartilhar as experiencias e o como se organiza para criar os projetos
Atualmente estou montando um sistema web de um e-commerce (PHP/MySQL
Sei que já haviam postagens do tipo no forum porém nenhuma das dicas me ajudou muito
Obrigado!
Comment: [Análise e Modelagem com UML](http://luizantoniopereira.com.br/downloads/publicacoes/AnaliseEModelagemComUML.pdf) disponibilizado online pelo próprio autor.
Comment: [Guia do Scrum](https://www.scrumguides.org/docs/scrumguide/v1/Scrum-Guide-Portuguese-BR.pdf) disponibilizado online pelos autores originalmente em língua inglesa e traduzido pela equipe Scrumguides.
Comment: Agradeço pela ajuda também augusto!
Answer: Olá, José, bem vindo ao StackOverflow.
Bem... não sou avançado em PHP, mas o que eu faço com meus projetos atualmente quanto à estrutura de arquivos separo em:
|-root
---|class
------>Busca.class.php
---|php
------>busca.php
---|plugins
-------|bootstrap
-------|jQuery
---|view
-------index.php
---|js
-------index.js

Explicando basicamente: em class estão todas as classes que EU fiz em PHP para fazer principalmente funções de acesso ao BD, como entrada e busca de dados. Já em php ficam os arquivos de "controle" do php, que é para onde um form vai quando o usuário clica no botão de submit.
Você pode fazer isso de um jeito simples:
--index.php

<form action="busca.php" method="POST">
   <input type="hidden" name="form" value="teste"/>
   <input type="text" name="fieldName"/>
   <button type="submit" value="Enviar"/>
</form>

--busca.php
<?php

include_once '../class/Busca.class.php';

$filter = filter_input(INPUT_POST, 'form');
if (!is_null($filter)) {
    $form = $filter;
}

switch ($form) {
   case 'teste':
      echo Busca::getTeste();
      break;
}

?>

--Busca.class.php
<?php

class Busca {
    public static function getTeste():string {
         return "teste";
    }
}

Bom, essa seria uma comunicação básica modularizada entre o html e o php. A medica que você vai adicionando js para envio de formulários sem a necessidade de refresh em toda a página, por exemplo, as coisas vão ficando mais interessantes.
Essa é a forma como EU organizo basicamente os meus projetos:

view (php com html e formulários)
php (arquivos de controle entre view e classes php)
class (classes do php para fazer acesso ao BD e coisas mais elaboradas)

Espero ter ajudado, qualquer dúvida estou a disposição!
Comment: Amigo, agradeço a ajuda, irei reestruturar meu projeto agora mesmo, tenho 14 pastas nele e não seguem um bom padrão...


Codeigniter remove index.php

Question: I am using CodeIgniter 2.1.1 my site structure is like
mysite/
    application/
        controllers/
            backend/
                welcome.php

            welcome.php

        views/
            backend/
            frontend/

        .htaccess

and I can access backend with
http://localhost/mysite/index.php/backend

but I want
http://localhost/mysite/backend

Similarly for frontend I want
http://localhost/mysite/

In config/config.php I set
$config['base_url'] = '';
$config['index_page'] = '';

and experiment many code in .htaccess the latest one is
<IfModule mod_rewrite.c>
    RewriteEngine On

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

Comment: do you have mod_rewrite enabled on your local server?
Answer: Your .htaccessshould be in the root of your site, one level above the applicationfolder.
Comment: I moved but when I write http://localhost/mysite/backend it showed me localhost main page
Comment: @PHPFerrari Did you move it into `/mysite/` ?
Comment: yes exactly one level above application eg:
mysite/
       .htaccess
        application/
Comment: Default it was AUTO I replaced with REQUEST_URI but nothing happened
Comment: Also see if removing the forward slash before `index.php` in your `.htaccess` makes any difference -  mine is very similar, but doesn't have the forward slash.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16487/discussion-between-php-ferrari-and-mudshark)

Codeigniter remove index.php


Continuity of 1/x

Question: I am confused with what $8(ii)$ wants from me, I answered the first part of this question with help from the question posted here
Is $f(x)=1/x$ continuous on $(0,\infty)$?
But the this proves continuity and works for all $\epsilon>0$, so how do I prove it doesn't for $\epsilon=1$??
Comment: The second one is asking you to prove that $x\mapsto \frac 1 x$ is not uniformly continuous.
Answer: The general proof for all $\epsilon>0$ shows that specifically for $\epsilon=1$:
$$\forall c\in(0,\infty)\colon \exists\delta>0\colon \forall x\in(0,\infty)\colon |x-c|<\delta\Rightarrow |f(x)-f(c)|<1 .$$
Your task is to show that the slightly rearranged claim
$$\exists\delta>0\colon\forall c\in(0,\infty)\colon  \forall x\in(0,\infty)\colon |x-c|<\delta\Rightarrow |f(x)-f(c)|<1 $$
is false.
Answer: The order in which you take $\delta$ and $c$ is the key! Read carefully the last sentence of (i).

Continuity of 1/x


2 unknown one equation and condition

Question: suppose that we have
$P_2+P_3=1-P_1-Q_3$ where $0\le P_1\le 1$ and $0\le Q_3\le 1$ are known, and $0\le P_2\le 1$ and $0\le P_3\le 1$ and $P_2<P_3$
can we finde this probablity ?
Answer: One can't obtain a specific probability from the given constrains
\begin{cases}
P_2+P_3&=1-P_1-Q_3 \\
0&\le P_2,P_3\le 1 \\
P_2&<P_3
\end{cases}
with $0\le P_1,Q_3\le 1$ fixed.  In fact, it's easy to see that
\begin{cases}
0&\le P_2< \frac{1-P_1-Q_3}{2} \\
P_3&=1-P_1-Q_3-P_2.
\end{cases}
Comment: thank you so much for answer
Comment: @moh11aymen you're welcome

2 unknown one equation and condition


Using a While loop and Between operator for query?

Question: I'd like to know if there is a better way to write this query or if how I am doing it is the most efficient.
I am lopping through a list of IP Addresses that I have already converted to their numeric value in its table. I then need to look up the Geo-location  data (from MaxMind GeoIp2) where the selected IP Address is between the start and end IPs of the Geo-location data. Once I get the Geo-location data I update the the AllIP table with the Geo-location table's Id. This will allow me to inner join the tables later.
You will notice I am selecting the Id of the IP address inside the while loop so I can update the record by Id. This is because we may have multiple IP Addresses with the same value. Since I am looping through all the records I did not want to update by the numerical IP address value.
declare @ipcount int
declare @currentCount int
declare @ipAddress bigint
declare @id int
declare @geoCode int
set @currentCount = 0
set @ipcount = (select count(*) from AllIP where Processed = 0)

while @currentCount <=@ipcount
   BEGIN
     set @id = (select top 1 Id from AllIP where Processed = 0)
     set @ipAddress = (select IpAddressNumeric from AllIP where Id = @id)
     set @geoCode  = (
                     SELECT dbo.[GeoLite2-City-Locations].geoname_id
                      FROM
                     dbo.[GeoLite2-City-Blocks2]
                     INNER JOIN dbo.[GeoLite2-City-Locations] ON dbo.[GeoLite2-City-Blocks2].geoname_id = dbo.[GeoLite2-City-Locations].geoname_id
                     Where @ipAddress between dbo.[GeoLite2-City-Blocks2].startIp and dbo.[GeoLite2-City-Blocks2].endIp)

     update AllIP set Processed = 1,geocodeId = @geoCode where Id = @id
     set @currentCount = @currentCount+1
    end

Comment: You have an error `set @ipcount = (select count(*) from AllIP)` will select all records you want to iterate only over `AllIP where Processed = 0`
Comment: So you like doing more work than you have to? Every time you look up a particular IP address, you're going to get the same answer - but rather than use that answer for every instance of that IP address, you're going to just apply it to one row and then force yourself to do another lookup later?
Comment: @LIUFA, true, but the data is initially set to 0. I'll change the code.
Answer: It looks like the entire thing can be replaced by a single UPDATE:
UPDATE a
SET Processed = 1, geoCodeId = gcb.geoname_id
FROM
    AllIp a
       inner join
    dbo.[GeoLite2-City-Blocks2] gcb
       on
          a.IpAddressNumeric between gcb.startIp and gcb.endIp
WHERE
    a.Processed = 0

(I've excluded the join to GeoLite2-City-Locations at the moment since the join column you're using is the same as the column that's being selected)
In general, you should prefer to write set-based code that deals with all rows to be updated in a single statement, rather than working row-by-agonizing-row (RBAR).
Comment: I wasn't sure if I could inner join using a between operator. sweet
Comment: @DDiVita - In general, if you can put it in a `WHERE` clause, you can put it in an `ON` clause for a `JOIN`.


How to check if a column contains backslash

Question: data = {'value': ['red','red\blue','yellow']
}
df = pd.DataFrame (data, columns = ['value'])

I tried to use:
df[df['value'].str.contains("\\", na = False)]['value'].count()

but got the error:
bad escape (end of pattern) at position 0

Thanks a lot.
Comment: does this work? `df['value'].str.contains("\\",na=False,regex=False)` ?
Answer: Data was change for avoid \b value, add r prefix because by default regex=True.
For count is simplier use sum of Trues values:
data = {'value': ['red','red\ blue','yellow']}
df = pd.DataFrame (data, columns = ['value'])
print(df)
       value
0        red
1  red\ blue
2     yellow

print (df['value'].str.contains(r"\\", na = False).sum())
1

Another idea is avoid regexes by regex=False parameter in Series.str.contains:
print (df['value'].str.contains("\\", na = False, regex=False).sum())
1

Answer: It seems you just need to precede r in the code you are showing:
df[df['value'].str.contains(r"\\", na = False)]['value'].count()

This will work because, from documentation:

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C
Answer: Evaluating the df.value Series
>>> df.value
0        red
1    relue
2     yellow
Name: value, dtype: object
>>>

Note df.value[1] shows the value of relue since it evaluate \b as a back space
Using the raw method on 'red\blue'
data = {'value': ['red',r'red\blue','yellow']}
df = pd.DataFrame (data, columns = ['value'])

>>>print (df.value.str.contains("\\", na = False, regex=False).sum())
1
>>>


Why is a simple application of the Bolzano-Weierstrass Theorem not sufficient to prove Helly's Selection Theorem?

Question: Helly's Selection Theorem Problem (From Rudin):
Assume that $\{f_n\}$ is a sequence of monotonically increasing functions on $\mathbb{R}^1$ with $0 \le f_n(x) \le 1$ for all $x$ and all $n$.
Prove that there is a function $f$ and a sequence $\{n_k\}$ such that $f(x) = lim_{n \to \infty} f_{n_k}(x)$ for every $x \in \mathbb{R}^1$.
Why does this proof not work:
For each $x \in \mathbb{R}^1$, the range of $f_n(x)$ is $[0,1]$ and so bounded and closed, and since it is in Euclidean space, the range is compact. By the Bolzano-Weierstrass Theorem, $f_n(x)$ thus has a convergent subsequence (call it $f_{n_k}$). Since this is true of all $x$, we can define a limit function $f$ such that $f(x) = lim_{n \to \infty} f_{n_k}(x)$ for all $x$.
I haven't seen anywhere saying that this proof is incorrect, but I notice that all proofs I can find online are much longer and more involved. What am I missing?
Comment: +1 I learnt a new theorem today.
Answer: thus has a convergent subsequence...
This is subtly wrong, in that you've found a convergent subsequence for a fixed value of $x$, but there's no guarantee this will converge for other values of $x$. E.g. it's not obvious that $\lim_{k\rightarrow\infty} f_{n_k}(y)$ even exists for $y\neq x$.
Comment: Ah, basically you can find a convergent subsequence for every value of x, but you can't just assume that the **same** subsequence is convergent for every value of x? And theoretically those two subsequences may not share any common elements b/w point x and point y.


Why did the NHL move to the current playoff format?

Question: 16 teams make it to the playoffs each season, 8 from each conference.
Until a few years ago, within a conference the number 1 seed would face the number 8, number 2 would face number 7, 6 vs 3, and 4 vs 5.
Under the current format, teams face division opponents. Each conference get 2 wild cards. The top seed of the divisions play the wild cards, and the 2nd and 3rd ranked team within each division play a series. Then there will be a division championship followed by the conference championship.
Eventhough the current format promotes divisional rivalry, it seems very unfair. As of March 27 2017, the top 3 teams of the NHL - Washington Capitals, Columbus Blue Jackets, Pittsburgh Penguins - are all in the same division. This means that one of the top 3 teams is guaranteed to be eliminated after the first round of the playoffs when the 2nd and 3rd rank teams of this division face in the first round. This also allows for lower quality teams to enter the playoffs in the weaker division.
So given the above argument, I'm wondering why the NHL has stuck to this format? I can understand they wanted a change and came up with this system. But the system is clearly flawed. So why doesn't the NHL come up with another scheme or revert back to the old format?
Note: I say "clearly flawed" since there is a huge difference in the strength of the teams playing in the postseason. The league is trying the maximize the parity of the teams getting and moving forward in the postseason. But the current format benefits weak divisions and disfavours strong divisions. Back to my example, with a very high probability one of the 2nd or 3rd best teams in the NHL is guaranteed to exit the playoffs in the first round. There has been a long discussion whether any team in the Atlantic division really wants the 1st position. The division winner will most likely face New York Rangers, the Wild Card from the Metropolitan division who have more points than any team in the Atlantic. Hence finishing 2nd in the Atlantic division gives the division champion a much easier road to get to the Stanley Cup final.
Comment: Why is 'clearly flawed'? That is your value judgment, for a situation that was clearly foreseeable to the framers of the system.
Comment: Please read the part marked as "Note" in the question. My response to your questions was far longer than the limit of a comment. Also I think it's more suitable to discuss my reasoning in the question itself than in the comments.
Answer: The logic behind the new system is that it means more teams are in the playoff race down the stretch, which increases attendance and fan engagement.
In the old system you have one playoff boundary: 9th vs 8th in a conference. This means that the only playoff race in each conference is between teams that surround that boundary. The games that are played by teams who are safely in front of it or behind it down the stretch, end up being largely irrelevant.
But in the new system you can either make the playoffs by winning your division, or by winning a wild card. If you're in a division whose record is well below a wild card spot, you can still make the playoffs via your division. OTOH, if you're well out of the playoffs in a strong division, you may be able to fight for a wild card.
The sum effect is that more teams are in contention for a playoff spot at the end of the year, and the fans of lesser quality teams win by having more reason to care at that period of the season.
Another side-effect, but with more of a neutral impact, is that team strategy has to change too. With divisional play being more important, teams need to focus their efforts on their own division.
Comment: But I recall in the old format a lot of the teams in the middle of the 1st to 8th position would play many high intensity meaningful games to get home advantage. But I do agree the current format could produce more revenue. But at the same time I believe that it lowers the quality of the match ups. Imagine if the same trend continues in the Eastern Conference. Then the Washington, Columbus, Pittsburgh and Rangers will care less about the making it to the playoffs since making the playoffs means that there is a good chance they won't make it to the next round.
Comment: I'm not trying to suggest it's 'fair' or not, just what the logic behind the move is. The point that a team may not make it to the next round is moot, because there is only one left standing regardless. If a team faces a better team in the first round and wins, their odds in subsequent rounds increase. (edited comment)
Comment: i have to disagree. I think it actually lowers fan engagement. Specifically in a stacked division. Where its the same teams playing year in year out. As mentioned, those good teams are weeded out by the 2nd round. Again, bad for fan engagement/revenue. IMO, the solution,

Have those boundaries as you describe them, but reseed the teams in conference. Imagine the rivalries/fan engagement/revenue if the 2 power house teams in division went head to head for a spot in the final.


Is this question on-topic?

Question: I am scared to put my money in a bank in my country because it is in debt and I'm afraid the bank won't be able to preserve it in the future, I want to ask whether it would be safe and what would be my alternatives?
Would that question be on-topic?
Answer: No. This could be answered maybe in https://money.stackexchange.com/
but I would suspect only in very general terms, and so in not a very helpful manner.
Essentially, this requires consulting services, namely professional services for a fee.

Is this question on-topic?


AWS Solution for wildcard subdomains (with SSL)

Question: Is there a solution within AWS for implementing a wildcard subdomain (with Route 53). where any subdomain ex1.example.com, ex2.example.com or whatever.example.com can all point to the same server? This server would then have a wildcard SSL cert to allow for the subdomains.
Is this possible?
Comment: Hi Larry, if the response below answered your question please upvote and accept it. That's the ServerFault's way to say thank you for the time and effort someone took to help you. Thanks!
Answer: Sure AWS can do that.

Set a wildcard CNAME record <code>*.example.com</code> in Route53 that points to your AWS ELB (Elastic Load Balancer), AWS ALB (Application Load Balancer) or directly to your HTTP Server.
If you are using ELB/ALB do not create the wildcard as A-records for the IP addresses as they may change over time. Either create CNAME or ALIAS!

If you're using ELB/ALB check out AWS ACM (Amazon Certificate Manager) - it can create and manage free SSL certificates that you can use with ELB/ALB.

If you're not using ELB/ALB you will either have to buy a commercial wildcard cert or use LetsEncrypt wildcard certificate, however that's a bit of a pain to renew as the challenge handshake must be done through DNS / Route53.

If your website is at least a little important I suggest you look at ALB + ACM instead of terminating the traffic directly on the web server.
Hope that helps :)
Answer: Route53 does support wildcards (from the Route53 FAQ):

Q. Does Amazon Route 53 support wildcard entries? If so, what record
  types support them?
Yes. To make it even easier for you to configure DNS settings for your
  domain, Amazon Route 53 supports wildcard entries for all record
  types, except NS records. A wildcard entry is a record in a DNS zone
  that will match requests for any domain name based on the
  configuration you set. For example, a wildcard DNS record such as
  *.example.com will match queries for www.example.com and subdomain.example.com.

You will need to obtain a wildcard SSL certificate separately and host it on any servers accepting these requests.
Answer: Not with route 53 but with a Load Balancer. Checkout ACM. You will have to create
your wildcard certificate. It is free but you won't have access to it.
If you need a secure connection between the Load Balancer and your server, you will have to install your own on this server.
Comment: "Not with route 53 but with a Load Balancer" implies one is necessary, hence my clarifying comment. An ELB and ACM are one way, but not the only one.
Comment: It's entirely possible to have a wildcard subdomain on AWS without needing ACM and a load balancer.
Comment: I never said that is was not possible.
Comment: @Kaymaz - do you have an example dns entry you can provide with R53 to redirect *.example.com to the apex domain of example.com?


Identify post or page in wordpress and when to use both

Question: I am new to wordress.. I need to create a wordpress site.. I am little confused when I use post and when I use page? How to identify whether the site should be pages or posts??
Comment: you have to go with wordress document and WordPress community website.
Comment: Its not a document.. I need to create a website like some company websites using wordpress
Comment: For make companies website you can use Pages, and Custom Templates for Pages, for bloging system you can use posts
Answer: This post is very usefull for you for make Company website in Wordpress
There are very key differences between posts and pages in your WordPress site.
About Posts
Posts are entries listed in reverse chronological order on the site homepage or on the posts page if you have set one in Reading Settings. If you have created any sticky posts, those will appear before the other posts. Posts can be found in the Archives, Categories, Recent Posts, and other widgets. Posts are also displayed in the RSS feed of the site. You can control how many posts are displayed at a time in the Reading Settings.
If you want your posts to appear on a page other than your home page, see Front Page.
About Pages
Pages are static and are not listed by date. Pages do not use tags or categories. An About page is the classic example. Pages can be displayed in the sidebar using the Pages widget, and some themes display pages in the navigation at the top of the site.
How many can I have?
There is no limit on the number of posts or pages you can have.
How do I post to a Page?
All posts will appear on the main posts page, but you can also display specific posts on category pages with our custom menus feature. If you want, you can change the default page for posts to appear by changing Reading Settings in the Dashboard. This will likely require changing your Front page as well.
Reference from Wordpress Community
Comment: If I have one wordpress site, How can i find the content should  be post or page??
Comment: you are making site from scratch or working on existing site?
Comment: I have added useful link in my answer
Comment: I need to make a new site not working on existing site.. In some of the wordpress sites, I don't know how to identify its a pages or post??
Comment: if you like answer then don't forget to up vote it.:)
Comment: Thanks, but you have marked as correct but not up voted :)