If each face of a die is a normal n-sided polygon, how many faces does the die have?

Question: A die with normal 4-sided polygon faces has 6 faces.
A die with normal 5-sided polygon faces has 12 faces.
If a die has normal $n$-sided polygon faces, how many faces does it have?
Is there a general formula for this, and is there a rigorous proof?
Intuitively, if $n$ is odd, then the number of faces is $2n+2$, but I can't think of a rigorous proof for this. The hard cases seem to be when $n$ is even.
Comment: If you are restricting the die to (convex) regular polyhedra, there are exactly 5: a tetrahedron ($n = 3$, 4 faces), a cube ($n = 4$, 6 faces), an octahedron ($n = 3$, 8 faces), a dodecahedron ($n = 5$, 12 faces), and an icosahedron ($n = 3$, 20 faces). As you can see, there are 3 different cases with triangular faces ($n = 3$) which have a different number of faces, so there isn't a general formula. Edit: for reference, these are called the Platonic solids.
Comment: @BrianYao I didn't know that, thanks. Is there a geometric reason why there can't be, for example, a regular hexagon faced die?

Conversely, are there any particular properties that $n=3,4,5$ satisfies? Edit: just saw your edit come through. Thanks for the tip.
Comment: Yes, there is. Try to construct a vertex of this hexagon-faced die. The problem is, 3 hexagons can share a vertex perfectly on a flat plane, so there's no way to create a 3-dimensional object. On the other hand, 3 pentagons sharing a vertex, for example, occupy only $324^\circ$ out of $360^\circ$, so we have a $36^\circ$ "gap." When we close the gap by bringing the pentagons together, the vertex will be pushed outward, creating a convex shape. This is what allows us to have a convex polyhedron.
Comment: That makes a lot of sense, especially when considering polygons of even more sides. Thanks!
Comment: Yes; when you attempt to do this with three regular polygons with vertex larger than a hexagon (eg three heptagons), their isn't a gap, but an overlap.
Comment: Ah, I should have touched on that. It is because in a cube, each vertex is shared by 3 faces, not 4 (which would be planar). Something similar occurs with the triangle-faced platonic solids: if each vertex is shared by 3 triangles, you get a tetrahedron. If each vertex is shared by 4 triangles, you get an octahedron. Shared by 5 triangles? Icosahedron. Shared by 6 triangles? Oops, no more "gap," and we're back to a plane.
Answer: Most relevant aspects have already been discussed in comments.
The most typical generalization of a "die" to other faces would be a platonic solid. There are exactly five platonic solids, including the dodecahedron with its pentagonal faces which you already mentioned in the question. Three of these have the same face shape, namely the tetrahedron, the octahedron and the icosahedron. They all have triangular faces, but four, eight or twenty faces respectively.
So at this point you can already see that there can be no formula to deduce the number of faces from the number of corners per face alone.
In my opinion the most useful formula you can get for computing the number of faces is Euler's polyhedron formula which states that for each convex polyhedron you get $$V-E+F=2$$ where $V$ is the number of vertices, $E$ the number of edges and $F$ the number of faces.
In a comment you asked why there are only five platonic solids, but that is probably better discussed in the question Platonic Solids. Two of the current answers there make use of Euler's polyhedron formula, too.
One could generalize the question further, e.g. by dropping the convexity constraint (and therefore considering Kepler–Poinsot polyhedra as well) or by dropping one of the transitivity requirements of regular polyhedra. For example, the ten-sided die is convex and face-transitive but not edge- or vertex-transitive, and its faces are not regular polygons. So it all depends on what you call a "die".


How to validate annotations during build or during startup on Spring Boot?

Question: Let's say, for example, that I have a @TimedMillis and a @TimedSeconds annotation. What they do is log the method execution duration time, one in milliseconds and the other in seconds.
It would not make any sense to have them both on the same method. A method can have one of these annotations, or he can have none of them, but not them both at the same time.
How can I check that a method does not have them both during build (preferably)? If not possible during build, how can I do this during startup and prevent application from starting? I have seen hibernate doing this during startup. Although it didn't prevent the application from starting, it did prevent the application from working.
Answer: You can use the reflections library to easily scan a package and all its subpackages for classes that contain methods annotated with a specific annotation.
You can then inject the validation logic wherever you see fit.
For example you could:

Add the reflections dependency:

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.12</version>
</dependency>

Add the validation logic, even earlier than Spring Boot bootstrap if you want, like so:

  public static void main(String[] args) {
    validateAnnotations();
    SpringApplication.run(ExampleApplication.class, args);
  }

  private static void validateAnnotations() {
    Set<Method> annotatedMethods =
      new Reflections("com.example", new MethodAnnotationsScanner())
      .getMethodsAnnotatedWith(TimedMillis.class);

    annotatedMethods.stream()
    .filter(method -> method.getDeclaredAnnotationsByType(TimedSeconds.class).length > 0)
    .findFirst()
    .ifPresent(method -> {
      throw new IllegalStateException("Invalid annotations for method " + method);
    });
  }

Comment: It worked as expected. I have made [this public repo on github](https://github.com/Chuque/annotation-validation) with my implementation. Thanks.
Answer: There is also alternative option - by making it impossible by annotation itself.
This approach assumes that both @TimedMillis and a @TimedSeconds are actually very similar - and can be refactored to a single annotation.
To achieve such functionality new annotation can be introduced - that will have the desired timeunit as the value provided.
@Target({ElementType.METHOD})
public @interface Timed {

    /**
     * Defines time unit of duration.
     *
     * @return duration time unit
     */
    TimeUnit timeUnit();
}

It will help to achieve needed functionality as duplicate annotations are not allowed (only if not marked with @Repeatable)
Answer: You can define a custom annotation processor to do this validation. The annotation processing will occur at build time. Here is a nice tutorial on how to use the annotation processing API: https://www.baeldung.com/java-annotation-processing-builder


Is it safe to use boost::lockfree with c++11 thread support library?

Question: I currently have a code written using C++ 11 thread support library: http://en.cppreference.com/w/cpp/thread
I am wondering whether it would be safe to mix that code with boost::lockfree. http://www.boost.org/doc/libs/1_54_0/doc/html/lockfree.html
That is, I want multiple C++11 std::threads to concurrently access boost::lockfree::queue.  Probably it would be safer to replace C++11 thread with boost::thread, but if I could minimize the code change it would be nice.
Comment: A short answer is "Probably": every lock free data structure and algorithm I know of do not rely all that heavily on the details of the threading model as much as they rely on processor primitives.  A long answer is "dunno", because this will possibly depend on some deep mojo in your language and boost implementation.  On a platform with lack of concurrency primitives (like CAS), you could imagine a bunch of stuff being implemented through some seriously crazy ways, and `boost` and `std` choosing different crazy ways.  Are you programming on relatively standard hardware?
Comment: Is Portability a concern ? If yes, then you cold use it. If the development is on Windows then you can use Parallel Pattern Libraries.
Answer: I am currently working on a threadpool implementation myself using a lockfree queue and std::thread however I am using the Joe Seigh atomic queue algorithm rather than the boost version. I can see no reason why the boost version would not be fine, I've examined the source and it seems an excellent implementation to me.


Migrate existing documentation from word / excel to web

Question: Backstory:
We are looking at the posibility to migrate existing documentasion from a windows folder tree ( containing word and excel mostly) to a internal web site ( this is IT dokumentation, if the first go).
Because this is internal use, i was personaly considering using drupal to host site, but its my understanding this is what sharepoint does aswell.
What we need are:

Restrict access ( IE login )
Ability to search the documentation

What would be a pluss

Version control
Get access rights from AD
Ability to import existing word / excel sheets into the site ( either bulk or 1 at the time, main   problem here might be that our word   docs contain pictures)
Low cost ( Why i was thinking drupal )

anyone have personal experience with doing this ? And got recommendations on what software to use and so on
Answer: I installed Mediawiki for my employer and am currently part way through importing existing documentation, mostly in Word or on scraps of paper. With the huge number of extensions available there is very little that it can't do, at least not in the wiki sense. There are several extensions for authenticating against AD. Those can be combined with a number of extensions providing various degrees of access control, allowing you to have it as open or closed as you desire.
There is no direct translation from Word or Excel to Mediawiki but there are Word macros that make the conversion process from that format very easy. The macros even handle images. I don't know if such macros exist for Excel but in that case it wouldn't take too much effort to write a converter in Perl, thanks to the excellent Perl modules available for reading and writing Excel format.
Mediawiki is free. It keeps a full history of all changes and allows you to go back to any earlier revision on an article, thus meeting your version control requirements.
Answer: Since you already mentioned it just to expand. SharePoint will be able to do:

Restrict Access based on Active Directory User
Index documentation for searching via SharePoint and Enterprise Search
Version control
Open files and save directly to Library
WSS 3.0 with the above feature set is free and part of Server 2008.

For your needs the full SharePoint 2007 will be an overkill. Unless your not a Microsoft house it does meet all your requirements. SharePoint 2010 will also offer full Office 2010 Web integration.
Answer: If you trust google, google docs can be used for this purpose. You can import word / excel files and control access. Version control is there so you can see old revisions. Many people can edit files at same time. Low cost as it is free. I think it google supports searching in google docs, not sure, but makes sense.
Minus point: Access rights from active directory.
Comment: Did not think about google docs, its a posible solution. On a side note, we got hardware to run any software we might need internaly
Answer: We use confluence, it's a commercial wiki, but does the tie-ins very well.
It has a word plugin that's been able to take even fairly complex documents nicely, I've not tested Excel sheets.
Also you want a wiki, not a CMS, your aim should be easy to edit to reduce excuses for not updating documentation.
Finally, remember to keep paper copies of critical DR docs, eg contact details with ISP, support numbers for hardware, etc.


How to use a class abc as object in a datastructure say "List"?

Question: public class abc
    {
        public static void main()
        {
            List<abc> list = new List<abc>() ;
        }
    }

I want to add all the fields which i used in my class in a list and display them by using a list.. plzz tell.. how can i write a code in c# ??
Comment: Can you edit the question and add an example of what the output should be?
Comment: Please read at-least a minimum level of  Object Oriented Program or try to understand what is OOP's and then start work. Its worthless to ask syntax and logic. Its waste of time.
Comment: You might want to have a look at PropertyGrid (http://msdn.microsoft.com/en-us/library/system.windows.forms.propertygrid.aspx)
Answer: Well first create an instance of abc
abc instance = new abc();
//then set the properties
abc.Property1 = "Some value";
//similarly set the value of rest of the properties.

//insert this instance in your list by using add method
list.Add(instance);

//iterate through each instance in list

foreach(abc instance in list)
{
    //print value of a property
    console.Writeline(abc.Property1);
    //similarly other properties
}

Comment: Nope. I think these hints are enough for a beginner. You should do rest of the effort
Comment: can i use the claas name instead of the intance?? how can i print all the property value in a single console statement??
Comment: `can i use the claas name instead of the intance??` for what exactly? `how can i print all the property value in a single console statement??` console.Writeline(abc.Property1 + abc.Property2); similarly you can add rest of the properties
Comment: can we declare our list like this:

list list= new list();

so that we can use all the class properties as objects in the list??
Comment: Yes we can. You have done it right in your example `List list = new List() ;` here abc is class name
Comment: can u plzz tell me the syntax for writing the list??
Comment: List listName = new List();
Answer: If you want to print out all properties of objects, then you might want to use reflection code, e.g:
public class abc
{
    public string Name {get; set;}
}

    //....

var list = new List<abc>();
list.Add(new abc() {Name="instance 1"});
list.Add(new abc() {Name="instance 2"});

foreach (var instance in list)
{
    foreach (var property in instance.GetType().GetProperties())
    {
        Console.WriteLine(property.Name + "=" +
                          property.GetValue(instance, null));
    }
}

Comment: where did u declare the main method?? it wont compile...plz help me with the proper code..


Why are there curly braces around item?

Question: What is the purpose of the curly braces around item in the renderItem prop? I've tried passing it in like so
renderItem={ item => <Text style={styles.item}>{item}</Text>}

but it doesn't seem to work. Kindly guide me for this.
//Code snippet from React Native docs as below.
//url: https://facebook.github.io/react-native/docs/using-a-listview

import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, View } from 'react-native';

export default class FlatListBasics extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={[
            {key: 'Devin'},
            {key: 'Dan'},
            {key: 'Dominic'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingTop: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
})

Comment: I'm surprised no one has answered this.
Answer: What's happening here is object destructing; an ES6 feature. Look it up. The actual object passed to the function you define in renderItem is not your actual item array. It's actually and object that has your item inside it for example {a: ..., b: ... , item: /*your item*/}. object destructing allows you to specify the parameter of the function as one of the objects inside the actual object that's passed in.
E.g
function printName({name}) {
  console.log(name)
}
obj = {age: 32, name: 'Alex'}

printName(obj);

this will print 'Alex'
What makes it confusing is the fact that destructing syntax uses curly braces and so does the JSX parser... but the curly braces mean different things.
Answer: It's to extract the values of item , that's how JSX works. If there would have been only item , i.e <Text>item</Text> then it will render item as the output , but if you want to display the value of item , suppose item =50, then display <Text>{item}</Text> so 50 will be displayed.
Comment: Hey, thanks for the answer but it's not quite what I meant. I was referring to this bit:

```
renderItem={(**{item}**) => {item.key}}
```

Why are there curly braces around item?


iOS Development Simulator view squashed

Question: I have just started iOS programming and am following a tutorial on iTunesU from Stanford.
In the first tutorial we were shown how to build a simple RPN calculator. When I built and compiled in the simulator launched as normal but everything was "squashed". I figured this was because the View in XCode is bigger than the iOS simulator. How can I resize the view in Xcode or am I missing something.
Here is the iOS simuator view compared with the one from xcode
Comment: Are you adding controls programmatically or via interface builder ?
Comment: If you're using IB, try turning off auto-layout just to test. Looks like auto-layout is squashing your buttons since you're going from a 4-inch screen in IB to a 3.5-inch simulator
Answer: Looks like your view in Xcode's Interface Builder is a 4" view, and the simulator is running a 3.5" device. You can change either one.
The view size in Xcode is changeable by selecting the entire view, and in the attributes inspector, you can change the size between Freeform, 3.5, 4.
You can change the device in the simulator by going to Hardware>Device> Select your device
However, the overlapping buttons, etc, are more related to using Auto Layout, or misused struts. You can either turn off Auto Layout and use struts, or take the challenge to learn Auto Layout.
Here's a start for Auto Layout: What is Auto Layout?
Answer: It's not 'squashed' you are using the device simulator for the latest iPhone, which has a 4 inch display instead of 3.5 inch. To change device go to Hardware->Device in the simulator bar. And the iPhone frame does not show in the latest version of the simulator so to press the home button you go under Hardware->Home.

iOS Development Simulator view squashed


How to create any number of sublists using jQuery and Javascript array with objects?

Question: I have a simple html code of elements including
,
,
, , <and> and  <spawn> and by using css i created a menu with on hover show the sub lists.
So because the html code became too large i decided to create dynamically the menu by using jQuery and a javascript array with objects inside but something went wrong with my code and works only when i have 1 sub-menu. But when i try to put a sub-menu to other sub-menu nothing appeared on the browser
Each
 if have only 1
 inside no have sub-menu, If have and a second
 this means that have sub-menu with the same loop
My current code of html looks like this:

                Item 1

                            Sub-item 1

                Item 2

I tried to generate the items i want with the following jQuery code and an array like this but i failed:
var menuData = [
    {
        "image": "files/img/nav/aaa.png",
        "text": "Item 1",
        "subMenu": [
            {
                "image": "files/img/nav/aaa.png",
                "text": "Sub-item 1",
                "subMenu": [
                    {
                        "image": "files/img/nav/aaa.png",
                        "text": "Sub-item 1.1",
                        "subMenu": []
                    }
                ]
            }
        ]
    },
    {
        "image": "files/img/nav/aaa.png",
        "text": "Item 2",
        "subMenu": []
    }
];

$(document).ready(function(){
    function createSubMenu(arrayData){
        var elementsArray = [];
        var $ul = $('
');
        $.each(arrayData, function(index, value){
            var $li = $('
');
            var $div = $('
');
            var $img = $('', {'src': arrayData[index].image } );
            var $span = $('', {'text': arrayData[index].text});
            $div.append($img, $span);
            $li.append($div);
            if(arrayData[index].subMenu.length){
                $div2 = $('
');
                $subUl = createSubMenu(arrayData[index].subMenu);
                $div2.append($subUl);
                $li.append($div2);
            }
            elementsArray.push($li);
        });
        $.each(elementsArray, function(index, value){
            $ul.append(value);

        });
        return $ul;
    }

    $ul = createSubMenu(menuData);
    $('.navigation').append($ul);
});

What sould i change on my code to works for any number of down level sub-lists???
Here is a working jsfiddle code with 1 sub-list: https://jsfiddle.net/za6bj2vs/
Answer: The problem is that you have used global variables for the following two variables:
            $div2 = $('
');
            $subUl = createSubMenu(arrayData[index].subMenu);

Thus they get overwritten when recursing, and backtracking. This gives undesired results; in fact it makes $div2.append($subUl); do something disastrous: as $div2 has in the mean time changed by the recursive call, this actually attempts to append an element that is a parent of $div2, and so jQuery ... gives up.
Just use var and you're all good:
            var $div2 = $('
');
            var $subUl = createSubMenu(arrayData[index].subMenu);


Simplifying a fraction with a cubed root in the denominator

Question: I have an equation the following equation in my textbook, but I don't understand how it's legal for it to be simplified this way.
$${1000\over \pi\sqrt[3]{500\over \pi}^2}=2\sqrt[3]{500\over \pi}$$
I know that an equivalent equation is $${1000\over \pi{500\over \pi}^{2/3}}={1000\over \pi({500\over \pi})^{1/3}({500\over \pi})^{1/3}}$$
Looking at it I can see where things might cancel, like in one of the ${500\over \pi}^{1/3}$, the $500$ could go into $1000$ twice, and cancel out the $\pi$ in the denominator, but as far as I can remember that's not allowed.
Why is this okay?
Comment: There are no math cops out there, unless you count the self-appointed ones who don't really have the power to send you to jail. So rather than "legal", you're asking about "valid" or maybe "possible".
Answer: Hint:
multiply numerator and denominator for:
$$
\sqrt[3]{\dfrac{500}{\pi}}
$$

 you find: $\dfrac{1000 \sqrt[3]{\frac{500}{\pi}}}{500}$
Answer: it is $\frac{1000}{\pi\sqrt[3]{\frac{500}{\pi}}\sqrt[3]\frac{500}{\pi}}$=$\frac{\sqrt[3]{1000^3}}{\sqrt[3]{500\pi\cdot500}}$=$\sqrt[3]{\frac{1000^3}{500^2\pi}}$=$\sqrt[3]{\frac{4000}{\pi}}$=$2\sqrt[3]{\frac{500}{\pi}}$
Answer: Rewrite:
$$\frac{1000}{\pi \sqrt[3]{\frac{500}{\pi}}^2}=\frac{1000}{\pi}\times \left(\frac{500}{\pi}\right)^{-2/3}$$
And note:
$$\frac{1000}{\pi}=2\left(\frac{500}{\pi}\right)^{3/3}$$
Answer: Note that $1000 = \sqrt[3]{1000^3}$  In general $a = \sqrt[3]{a^3}$
$\displaystyle {1000\over \pi\sqrt[3]{500\over \pi}^2}= \sqrt[3]{\frac{1000^3}{\frac{\pi^3 500^2}{\pi^2}}}$
And you have to remember that $1000^3 = (2 \cdot 500)^3 = 8 (500)^3$


A sign on black orpheus' lead sheet

Question: What is the name of this symbol and what does it mean?

Source
Answer: It's  a 'segno' sign. Later in the tune there a marking "D.S. al " (short for 'dal segno al coda'). At that point you jump back to the segno sign and play all the way to the coda  sign. Then you jump to the coda (also marked with a coda sign).
Answer: This is a segno sign. Segno is sign in Italian. It is a point that you are supposed to return to when you encounter D.S. or "dal segno" later in the piece, in this case in the third line from the bottom.
You should also follow any other instructions there. In this case it is "al Coda" (the circle with the cross in the center) where you jump from one coda sign to the other. Other common instructions are "al fine" or "and continue". It is a very common way to avoid writing out the same music twice and shortening the written length of pieces.

A sign on black orpheus' lead sheet


Proof of the infamous Happy Number

Question:
Suppose you take a natural number of any number of digits. You square each digit of that number and add all the outputs. You get another number by doing this. Repeat this process with the new number. Continue this process until you end up with a single digit number. There's a catch. If the number is not $1$ or $4$ write the single digit number as $01$, $02, $03$ and so on, and continue the process.

Prove that the single digit number obtained at the last will either be $1$ or a $4$.

I have no idea how to prove this. I tried with a two digit number. I assumed the number as $10a+b$ and the new number will be $a^2+b^2$. But after this I was stuck. Like what if I took $11$ and then the new number will be $02$ and then we will get $4$.
Any help is greatly appreciated.
Comment: Sketch:  Usually one does this sort of thing by showing that there is some $N\in \mathbb N$ such that, assuming the claim is true up to $N$, then it holds forever.  That comes down to remarking that, for a sufficiently large $n$, your process produces a lower value.
Comment: Let $f$ be the function mapping an input number to it's output after applying this process.  My first instinct would be to try to prove a statement along the lines of $n>100\implies f(n)<n$.  If we manage to do that, then we could argue that whatever number we started with, however large, will eventually after repeated application of $f$ get us into a smaller finite range of values which can be checked manually if need be, and if we tighten the bound could make it a very small number of cases to check.
Comment: "*There's a catch... write the single digit number as 01, 02, 03 and so on and continue the process*"  I don't see why this should have mattered.  Squaring an existent zero and adding that accomplishes the same thing as having not included a zero in the first place.
Answer: For large numbers the sum of digit squares is smaller, for example at most 81 million for one million digit numbers, 49+7*81=616 for numbers up to 81 million, 5^2+2*81 for numbers up to 616, 162 for numbers up to 187.
Then you make a table of the values for numbers up to 162 and check.

Proof of the infamous Happy Number


a simple tensor product question

Question: I have just started to learn about this today, and though i understand this is probably a very simple question, i'm still quite not sure about it:
is $\mathbb{C}\otimes_{\mathbb{R}}\mathbb{C}=\mathbb{H}$ (when this is a tensor product of algebras)?
my feeling is that the answer is yes. however, I am trying to build the product algebra with the regular construction, and can't seem to get it.
I would greatly appreciate a detailed answer, and not a hint, as i'm very new to this. tahnks alot!
Answer: The short answer is that you don't have $\mathbb{C}\otimes_{\mathbb{R}}\mathbb{C}=\mathbb{H}$ because the left hand side is commutative but the $\mathbb R$- algebra $\mathbb H$ is not.
The more complete  answer is that $\mathbb{C} \otimes_{\mathbb R} \mathbb{C}$ is isomorphic to  $\mathbb{C} \times \mathbb{C}$ as an $\mathbb R$ -algebra : do you see why?
 [Hint: write $\mathbb C \otimes_{\mathbb R} \mathbb{C}=\mathbb{R}[X]/(X^2+1) \otimes_{\mathbb R} \mathbb{C}=\mathbb C[X]/(X^2+1) $ and use the Chinese remainder theorem, noticing that the ideal $(X^2+1)\subset \mathbb C[X]$ equals $(X+i)(X-i)=(X+i)\cap(X-i)  ]$
Warning Despite a widespread misconception $\mathbb H$ has no canonical structure of $\mathbb C$-algebra (but an infinity of non-canonical ones!), whereas $\mathbb{C} \otimes_{\mathbb R} \mathbb{C}$ has two such structures: the one coming from the $\mathbb C$ on the left of $\otimes_{\mathbb R}$ and the one coming from the right.
Answer: This algebra can't be isomorphic to the quaternions because its multiplication is commutative whereas that of the quaternions isn't.

a simple tensor product question


Action on module enable?

Question: I want to show a message when a module is being enabled. I used hook_modules_enabled and it shows me the message while enabling a new module.
Now I need the currently enabled module machine name in the hooks argument.
But hook_modules_enabled($modules) returns an array of modules in the argument.
Eg:
When views is enabled, I need to set a message as:

"Views Module is enabled"

Here I need "views" (i.e. the module name) as argument in hook_modules_enabled in order to print it in message but it returns me an array.
How can I achieve this. Is there any other hook for this?
Answer: hook_module_enable() should do the job unless I'm missing something from your question.

Perform necessary actions after module is enabled.
The hook is called every time the module is enabled. It should be
  implemented in the module's .install file. The implementation can rely
  on the .module file being loaded.
Comment: I updated my question
Answer: I don't see any other hooks that you could invoke; you could keep track of modules yourself, compare it with what you get in hook_modules_enabled() and then do whatever you want for each of the enabled/installed modules.
Here are general steps:

Upon installation of your custom module (or in update hook), save the snapshot of what is installed in the system at the moment. This would go into .install file and you could use part of the code from this answer. Querying directly the {system} table might even work. Store everything as an array using variable_set().
Use hook_modules_enabled (or hook_modules_installed) to compare the new list with the old one. Store differences in a separate array (e.g. array_diff()).
For each of the newly installed/enabled modules perform your action.
Update the custom variable for storing the list of modules using variable_set().

Let me know if I misunderstood the question.
Comment: do you mean I have to take the difference between the module list before installing a new one and after it. In order to get the currently installed module name?
Comment: Yes, that's exactly what I meant.
Answer: The argument $modules in hook_modules_enabled($modules) returns an array of modules enabled. You should loop through the array to print the message.
Note: But only machine name of the module will be in the array.
For eg:
function MY_MODULE_modules_enabled($modules) {
  foreach ($modules as $module) {
    // To get Module Name
    $module_info = system_get_info('module', $module);
    $module_name = $module_info['name'];
    //Loop through the modules and set the message.
    $msg= "$module_name is enabled";
    drupal_set_message(t($msg), 'status', FALSE);
  }
}

Action on module enable?


Evaluate $\int\frac{\cos x}{\sin x + \cos x}\,\text{d}x$.

Question: I'm trying to figure out how to take this indefinite integral:
$$ \int\frac{\cos x}{\sin x + \cos x}\,\text{d}x.$$
I tried simplifying and rearranging it, and this is the best I got:
$$\int\frac{1}{\tan x + 1 }\,\text{d}x.$$
But I still can't figure out how to integrate from there. I know that it's integrable, as Wolfram Alpha indicates that the integral is $ \frac{1}{2}\big(x+\ln{(\sin x + \cos x)}\big)+C$, but I can't figure out the steps to deriving it. Does anyone know how to evaluate this integral?
Comment: This is basically the same as [this question](http://math.stackexchange.com/questions/180744/compute-int-frac-sinx-sinx-cosx-mathrm-dx). (To be more precise, if you know one of the two integrals, it is easy to calculate the other one and vice versa.)
Answer: Let $I=\int\frac{\cos x}{\sin x+\cos x}\ dx$ and $J=\int \frac{\sin x}{\sin x+\cos x}\ dx$.
Then $I+J=\int\frac{\cos x+\sin x}{\sin x+\cos x}\ dx=x+C_1$ and $I-J=\int\frac{\cos x-\sin x}{\sin x+\cos x}\ dx=\ln |\sin x+\cos x|+C_2$.
Hence $I=\frac{1}{2}((I+J)+(I-J))=\frac{1}{2}(x+\ln |\sin x+\cos x|)+C$.
Comment: This is very elegant in that it requires no substitutions.
Comment: @user54147 You are using a substitution, $u = \sin(x) + \cos(x)$ in the end
Answer: A general (but not necessarily efficient) tool is the Weierstrass substitution $t=\tan(x/2)$.
Then $\cos x=\frac{1-t^2}{1+t^2}$, $\sin x=\frac{2t}{1+t^2}$, and $dx=\frac{2}{1+t^2}$. Do the substitution. We end up needing the  following ugly integral:
$$\int \frac{2(1-t^2)}{(1+2t-t^2)(1+t^2)}\,dt.$$
We are integraing a rational function, and it can be done using partial fractions. But it takes some work.
The same idea works in principle for any rational function of $\sin x$ and $\cos x$.
Answer: Notice that
$$\sin x+\cos x=\sqrt{2}\left(\frac{1}{\sqrt{2}}\sin x+\frac{1}{\sqrt{2}}\cos x\right)=\sqrt{2}\sin\left(x+\frac{\pi}{4}\right)$$
Therefore
$$I=\frac{1}{\sqrt{2}}\int\frac{\cos x}{\sin\left(x+\frac{\pi}{4}\right)}dx$$
Now let $x+\frac{\pi}{4}=t$
$$I=\frac{1}{\sqrt{2}}\int\frac{\cos \left(t-\frac{\pi}{4}\right)}{\sin t}dt=\frac{1}{2}\int\frac{\sin t + \cos t}{\sin t}dt=\frac{1}{2}\left(t+\ln {\left|\sin t\right|}\right)+C_1\\=\frac{1}{2}\left(x+\frac{\pi}{4}+\ln {\left|\sin x+\cos x\right|}\right)+C_1=\frac{1}{2}\left(x+\ln {\left|\sin x+\cos x\right|}\right)+C$$
Answer: $\displaystyle \int \frac{1}{1+ \tan x} \ dx $
$ \displaystyle = \int \frac{1}{1+u} \frac{1}{1+u^{2}} \ du$ (let $u = \tan x$)
$ \displaystyle =  \frac{1}{2} \int \left( \frac{1}{1+u} + \frac{1-u}{1+u^{2}} \right) \ du$
$ \displaystyle = \frac{1}{2} \int \left( \frac{1}{1+u}  - \frac{u}{1+u^{2}} + \frac{1}{1+u^{2}} \right) \ du $
$ \displaystyle =\frac{1}{2} \left(\ln(1+u) - \frac{1}{2} \ln(1+u^{2}) + \arctan u \right) + C$
$ \displaystyle =\frac{1}{2} \left(\ln(1+u) - \ln(\sqrt{1+u^{2}}) + \arctan u \right) + C$
$ \displaystyle = \frac{1}{2} \left( \ln(1+\tan x) - \ln (\sqrt{1+\tan^{2}x}) + x \right) + C$
$  \displaystyle = \frac{1}{2} \left( \ln(1+\tan x) - \ln (\sec x) + x \right) + C$
$ \displaystyle = \frac{1}{2} \Big( \ln \big(\frac{1+ \tan x}{\sec x}\big)  + x \Big) + C$
$ \displaystyle = \frac{1}{2} \left( \ln (\cos x + \sin x ) + x \right) + C $


Prove set of primes is equal to set of natural numbers

Question: I was studying for an upcoming test in college and was looking at an old test. I'm struggling to understand how to prove this problem and was hoping someone could help me out.
Prove that |P| = |N| where P is the set of primes and N is the set of natural numbers.
Comment: Note that the question in the title, is incorrectly stated.  The sets are not *equal*, they are equicardinal.
Answer: To show the two sets are of the same cardinality, the easiest way is to find a bijection between the two sets. I.E - a one to one correspondence.
How could we match each prime number to one natural number and vice versa? The obvious way would be to match the first prime number to the number 1, the second prime number to the number 2, etc. As J.G said, Euclid proved the are infinitely many primes, so you wouldn't run out of any along the way.
We found a bijection between the two sets, so they are of the same cardinality ($\aleph_0$).


Load balancing a simple website (Apache)

Question: I have two webservers colocated in the same place.  Currently only 1 is active and it hosts a online forum, but it's biggest use by far is serving large binary files to a couple hundred thousand people and responding to automated update checks.  Users reported that there have been some issues so I got the second webserver to share some of the load (I'm rsyncing between the two).  How can I implement an effective (simple) load balancer for these two servers?  The facility doesn't offer any sort of load balancing for me.
Round robin seems ineffective and not really a proper choice.
Comment: what are the problems being reported?  what is the current bottleneck?
Comment: Users reported that when they click a link (php link) which sends them a PHP header Location(thefile), that they get a strange message "Copyright 2002-2011 Google Inc.". And that's the only thing which loads on the page.  I figure it must be that the server is overloaded, so I just assumed a second server would solve the problem.   EDIT: The link is sent via an email.
Answer: HA-Proxy is your friend. You can find it at http://haproxy.1wt.eu/
It's not the simplest thing to set up, but the price is nice. As far as I am aware, it is the de-facto load balancing standard in the open source world.
Comment: Actually a really basic setup is pretty straight forward for anyone who knows how to navigate `vi`


Not getting notification on clicking the button why?

Question: i want when user clicks the button a notification is shown in top of phone , here is my code what i have done
My logcat
<code>E/NotificationService: No Channel found for pkg=com.example.imageslider, channelId=null, id=0, tag=null, opPkg=com.example.imageslider, callingUid=10286, userId=0, incomingUserId=0, notificationUid=10286, notification=Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x0 color=0x00000000 vis=PRIVATE)
</code>
My java code on click method
<code> NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_baseline_account_box_24
            )
            .setContentTitle("This is the test notification")
            .setContentText("test notifications ");

    Intent  notificationIntent = new Intent(this,MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(contentIntent);

    NotificationManager  notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,builder.build());
</code>
Comment: yes, i m missing the notification channel
Answer: From Android 8.0 if you want to show a notification, you should associate it to a Notification Channel.
First you should create a new notification Channel then show your notification.
You can find more detailed information here: https://developer.android.com/training/notify-user/channels
Comment: i did and i getting the notification, but on clicking  the notification i m not going inside the app how to do that?


Python pandas json_normalized a dataframe

Question: I'm trying to do a pd.json_normalized on a dataframe but it results into an empty dataframe.
initial dataframe
(https://i.stack.imgur.com/jGphv.png)
after applying json_normalized,
df1 = pd.json_normalize(df)
print(df1)

it became an empty dataframe. (https://i.stack.imgur.com/733Dx.png)
when I tried to define the dataframe manually using below, I got my expected output
data = [
    {'birthday': '542217600000', 'first_name': 'Char', 'gender': 'Male', 'last_name': 'Mander', 'nick_name': ''},
    {'birthday': '967046400000', 'first_name': 'ABC', 'gender': 'Male', 'last_name': 'ZXY', 'nick_name': ''},
    {'birthday': '739900800000', 'first_name': 'Test', 'gender': 'Male', 'last_name': 'tickles', 'nick_name': ''}
]

birthday = pd.json_normalize(data, max_level=1)
print(birthday)

(https://i.stack.imgur.com/IB2th.png)
May I know how can I directly normalized from a dataframe?
Answer: You should pass a Series to json_normalize, not a Dataframe:
# your initial DataFrame
df = pd.DataFrame({'properties': data})

# passing the relevant column/Series
birthday = pd.json_normalize(df['properties'], max_level=1)

Output:
       birthday first_name gender last_name nick_name
0  542217600000       Char   Male    Mander
1  967046400000        ABC   Male       ZXY
2  739900800000       Test   Male   tickles

Comment: thank you but I was not able to mention that the initial dataframe im using is from a csv file. I used this code to load

with open (input1 ,'r') as data1:
    df1 = pd.read_csv(data1, encoding='utf-8', dtype= 'object', sep=',')

then running json normalized provided me this error code
line 461, in _json_normalize
    if any([isinstance(x, dict) for x in y.values()] for y in data):
  File "C:\Users\xxx\pandas\io\json\_normalize.py", line 461, in
    if any([isinstance(x, dict) for x in y.values()] for y in data):
AttributeError: 'str' object has no attribute 'values'
Comment: can you provide the content of the csv file for debugging?
Comment: cardinality|create_time|properties
382|2022-04-05 16:32:43.000+0000|{'birthday': '542217600000', 'first_name': 'Char', 'gender': 'Male', 'last_name': 'Mander', 'nick_name': ''}
400|2022-02-07 14:20:59.000+0000|{'birthday': '967046400000', 'first_name': 'ABC', 'gender': 'Male', 'last_name': 'ZXY', 'nick_name': ''}
132|2021-08-09 14:01:30.000+0000|{'birthday': '739900800000', 'first_name': 'Test', 'gender': 'Male', 'last_name': 'Tickles', 'nick_name': ''}
Comment: Complete steps im doing:
1. with open (input1 ,'r') as data1: df1 = pd.read_csv(data1, encoding='utf-8', dtype= 'object', sep=',')
2. df1=df1['properties']
3. pd.json_normalized(df1)
Comment: Can you add these details directly in the question?
Answer: Note that calling dict() on a pd.DataFrame does not result in a valid JSON object, therefore you need a workaround, e.g.:
regular_json = [row[1].to_dict() for row  in df.iterrows()]
pd.json_normalize(regular_json)


Form Alter: How to check if a node has a Field Type

Question: My module provides a field. In hook_form_alter() I need to change only those nodes that have this field set up. (I can't operate use hook_field_form_alter() because it does operates changes for other things than my own field.)
How can check if my field belongs to the node?
Is there an easy function to check if the field type exists in $form?
Otherwise, if I need to look at $form the problem is that I can't know the machine name used for the field by the admin/drupal as it looks like something like $form['my_field_namedbyuser'].
Comment: are u searching for specific field named 'type' or a 'field type' like term reference , integer,text etc..
Comment: Yes i am searching for a 'field type' like 'page' 'article' etc
Comment: sorry but 'page', 'article' are node types and not the field types .Do you want to check whether the field belongs to a particular node type ?
Comment: Yes sorry: field types: my module creates a field type, that's what i am looking for. Now it is ok: answer below :)
Answer: If you are searching for specific field then see the code below
 function hook_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'form_id_name') {
        $abc = array();
        foreach ( $form_state['field'] as $key => $value ) {
            $abc[$key] = $key;
        };
}
    }

From this $abc variable you will get all the field name and then you can check from this array to see if the field you want exists or not using any of the php functions.
For e.g.
you can use array_key_exists('field_name', $abc);
Comment: Thanks for that, and sorry i was not clear, i am searching for a 'field type' like 'page' 'article' etc

so i just had to call the function field_info_field to make it happen !

            $abc[$key] = field_info_field($key);
Answer: I have found this other solution as well if this can help someone:

Set up a new variable in $form_state of hook_mymodule_field_widget_mywidget_form_alter
Check for this variable in mymodule_form_alter
function mymodule_field_widget_mywidget_form_alter(&$element, &$form_state, $context){
$form_state['IsMyField']['#value'] = TRUE;
}

function mymodule_form_alter(&$form, $form_state, $form_id)
if ($form_state['IsMyField']['#value']  == TRUE ) {
    //My CODE HERE
}


MongoDB Hadoop connector streaming not running

Question: I want to launch the MongoDB Hadoop Streaming connector, so I downloaded a compatible version of Hadoop (the 2.2.0) (see https://github.com/mongodb/mongo-hadoop/blob/master/README.md#apache-hadoop-22)
I cloned the git repository mongohadoop, changed the build.sbt hadoopRelease for 2.2 :
<code>$ cat build.sbt
name := "mongo-hadoop"

organization := "org.mongodb"

hadoopRelease in ThisBuild := "2.2"
</code>
Then I launched:
<code>$ ./sbt package
$ ./sbt mongo-hadoop-streaming/assembly
$ cp core/target/mongo-hadoop-core_2.2.0-1.2.0.jar ../hadoop-2.2.0/lib/
$ cp mongo-2.7.3.jar ../hadoop-2.2.0/lib/ # Previously downloaded
$ cd ../hadoop-2.2.0/
$ ./bin/hadoop jar ../mongo-hadoop/streaming/target/mongo-hadoop-streaming-assembly-1.1.0.jar -mapper ...
</code>
And I get this :
<code>Exception in thread "main" java.lang.ClassNotFoundException: com.mongodb.hadoop.streaming.MongoStreamJob
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:249)
at org.apache.hadoop.util.RunJar.main(RunJar.java:205)
</code>
I don't understand why, I tried almost every version supposed to support streaming but I always get the same error !
I precise I am on Mac OS X.
Thanks !
Answer: That is actually a bug that will be fixed in an upcoming release.  Need for that main class was removed but the generated manifest was not.  You can tweak your jar by removing the Main-Class entry from the manifest in the streaming jar.  If you run the script below in the directory where your streaming jar is, it'll fix that for you:
<code>#! /bin/sh

M=META-INF/MANIFEST.MF
mkdir tmp
cd tmp
cp ../$1 .
JAR=$1

jar xf ${JAR}

sed -e '/Main-Class/d' ${M} >> ${M}.new
mv ${M}.new  ${M}

jar cvfm ${JAR} ${M}

mv ${JAR} ..
cd ..
rm -r tmp
</code>
It's not super pretty but should get you over the hump.  We'll try to get a formal 1.2.1 release out soonish.  Here's the jira ticket in the meantime:  https://jira.mongodb.org/browse/HADOOP-121
Comment: Thanks, it resolved my error, but now, instead of com.mongodb.hadoop.streaming.MongoStreamJob, I get `java.lang.ClassNotFoundException: -mapper` when I do : `./bin/hadoop jar ../../mongo-hadoop/streaming/target/mongo-hadoop-streaming-assembly-1.1.0.jar -mapper ../../mongo-hadoop/streaming/examples/enron/enron_map.js -reducer ../../mongo-hadoop/streaming/examples/enron/enron_reduce.js`
I don't really know how Java works (that's why I would like to use streaming actually :))
Comment: I think you'll want -libjars there instead of 'jar'. See https://github.com/mongodb/mongo-hadoop/blob/master/streaming/README.md#overview for an example
Comment: Thanks, but in that case you should update `streaming/examples/enron/*.sh`, because it is not the same command at all... I couldn't figure out how to make 2.2 works, so I changed to 0.23 and now it works.
Comment: I'll definitely double check that documentation.  Thanks for the heads up.


How to find number of files in directory recursively along with its directory name linux

Question: I have following structure in directory on linux:
-dirA
    -dir1
        -dirX
        -dirY
    -dir2
        -dirX
        -dirY
    -dir2
        -dirX
        -dirY
    -dir2
        -dirX
        -dirY
    -dir2
        -dirX
        -dirY
    -dir2
        -dirX
        -dirY
    .
    .
    .
    .
    .
    .
    .
    .
    .
    -dirn
        -dirX
        -dirY

I want to get details for count of files as follows or any format:
dir1
dirX = count
dirY = count

dir2
dirX = count
dirY = count

dir3
dirX = count
dirY = count

......
......

dirn
dirX = count
dirY = count

note here folder name of dirX and dirY is same inside subdirectory dir1,dir2.....dirn
i used following command but it gives accumulated result:
find $DIR -exec stat -c '%F' {} \; | sort | uniq -c | sort -rn

and this
find . -type f | wc -l

Answer: A simple while loop should be enough
find "$DIR" -type d -print0 |
    while IFS= read -r -d '' path; do
        echo -e "$(ls -A -- "$path" | wc -l)\t$path"
    done

If you want them sorted by file count, you can append a | sort -n at the end of the command (right after the done keyword).
Comment: should this be saved as shell script and ran
Comment: @virendrao If you want, you can do that. Just replace `"$DIR"` by `"$1"` and save it as `myscript.sh` and run it as a script. e.g. `./myscript.sh "/path/to/directory"`. You can also run it directly: just replace `"$DIR"` with the path of the directory and paste it in a terminal.


Por que os Traits podem ter métodos chamados diretamente quando estes são estáticos?

Question: Acabei de fazer um questionamento sobre Traits e me veio uma outra dúvida.
Se os Traits são mecanismos que facilitam a importação de métodos, por conta das limitações de um herança no PHP, por que podem os seus métodos serem acessados estaticamente?
Por exemplo:
trait Stack
{
    protected $items = [];

    public static function say()
    {
        return 'stack';
    }

}

echo Stack::say(); // stack

Isso não fica confuso tendo em vista o sentido da implementação do trait na linguagem?
É recomendado o uso de um método estático vindo de um trait, ou é melhor utilizá-lo numa classe?
Answer: Após dar uma lida neste site, eu entendi o seguinte:

Membros (campos e/ou métodos) vindos de um trait tem uma prioridade maior que os vindos de uma super classe, mas menor que os da classe atual.
Quando duas classes diferentes usam o mesmo trait, membros estáticos do trait são diferentes para cada uma das classes.

E tem outras coisas mais sobre traits no site linkado, se tiver mais dúvidas.


Number of different ways to join 4 tables

Question: I am reading a database textbook which says the following:

There is no further explanation or elaboration for how this formula was arrived at.  In attempting to derive it myself, I come up with something different.  For example:
For N = 2 (two tables A and B), I count 2 ways to join them:
A join B
B join A

Now for N = 3 (three tables A, B, C), I count 12 ways to join them, which agrees with the text.  The way I get this is by considering that after the first join (out of the two joins that must be performed total in a 3-table situation), there will be 2 tables remaining, and in that case we've already seen there are 2 options.  So we need to find out how many different options we have for this "first join" and then multiply that by 2.  There are 6 "first step" options (enumerated below), and 6 x 2 = 12.
A join B
A join C
B join A
B join C
C join A
C join B

Now, for N = 4 (four tables A, B, C, D), I count 144 ways to join, which does not agree with the 120 quoted in the text.  As before, my strategy is to find the number of ways to make the "first join" and then multiply that by the N = 3 option count (12), since at this point 3 tables and 2 joins will remain.  I count 12 options for the "first join" which leads to 12 x 12 = 144.
A join B
A join C
A join D
B join A
B join C
B join D
C join A
C join B
C join D
D join A
D join B
D join C

I am assuming the text is correct and I am mistaken.  Where is my error?
Comment: How are joins defined in your case? Normally, the total number of join orders is `N!` if there are no further constraints on order.
Comment: @usr I'm not sure what you mean by join definition, other than the obvious: a binary operation between 2 tables that selects a subset of a cross product satisfying some predicate.  The text I pasted is from a chapter on dynamic programming cost-based query optimization, and if it helps, the sentence that proceeds it reads "For the sake of simplicity when discussing dynamic programming, let's consider the case of joining N relations together in an N-way join, that is, "R1 JN R2 . . . JN RN−1 JN RN."
Answer: My first suggestion would have been to better ask this question on https://math.stackexchange.com/ , but then I just spent some time researching a possible answer. By the way, I found the original quote on Google Books, and also the referenced paper by Selinger 79.
Of course, the factorial indicates the formular describes a problem in combinatorics, but
I was intrigued by the expression (2*(n-1))! as I could not figure out what the 2*(n-1) would refer to.
If we take n as the number of tables ("relations" in database theory language), then n-1 is the number of JOINs. But how should the double of the number of JOINS be relevant for the result?
As it turned out, the formula (2*n)!/n! is related to Catalan numbers (see section Quadruple factorial):

In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively defined objects.

From the application

Cn is the number of different ways n + 1 factors can be completely parenthesized (or the number of ways of associating n applications of a binary operator)

I conclude, that if we take a JOIN as binary operator, then the number of alternatives in OP is Cn * number of combinations of tables.
Comment: Wow.  Good info, albeit maybe deeper than my brain can go at the moment.  Thanks for the links though, I will try to digest them.  I'm not sure I entirely understand the formula in your conclusion... what does that give you for N = 4?  Maybe I will take your advice and see if I can get this migrated to Math.
Comment: Great answer. Then the joins in the example given by the OP are all ordered (no commutativity). If they were not ordered (which is usually the case), `N!` would be the formula.
Comment: N! is the number of permutations. The Catalan number, from what I understand, gives the number of associative combinations (e.g. A JOIN (B JOIN C) vs. (A JOIN B) JOIN C). The query optimizer uses table statistics to determine which associative combination is the most optimal to compute. This seems similar to matrix multiplication.


Como resolver o problema do printf no meu código? (Ele não imprime saída)

Question: O objetivo do código é quebrar a cifra de Vigenère, usando o método de Kasiski para encontrar o comprimento da chave, análise de frequência para descobrir a chave. E acontece que não sei o porquê dele não estar imprimindo a saída no console, dado que ele não apresenta nenhum erro quando compilado.
Eu queria que ele apresentasse a mensagem de entrada decifrada na saída. A saída decifrada esperada é "David" e a chave é "chave". Revisei o código, porém com meus conhecimentos atuais não consegui resolver o problema. Segue abaixo o código.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// Função para calcular o índice de coincidência de um texto
double calculateIndexOfCoincidence(char *text, int len) {
    int letterCount[26] = {0};

    // Conta a frequência de cada letra no texto
    for (int i = 0; i < len; i++) {
        if (isalpha(text[i])) {
            char c = toupper(text[i]);
            letterCount[c - 'A']++;
        }
    }

    // Calcula o índice de coincidência
    double ic = 0.0;
    for (int i = 0; i < 26; i++) {
        ic += (double)(letterCount[i] * (letterCount[i] - 1)) / (len * (len - 1));
    }

    return ic;
}

// Função para encontrar o tamanho da chave usando o método de Kasiski
int findKeyLength(char *ciphertext) {
    int lenCiphertext = strlen(ciphertext);
    int maxKeyLength = 20; // Máximo comprimento da chave a ser verificado (suposição)

    // Inicializa um array para armazenar as distâncias entre sequências iguais
    int *distances = (int *)malloc(lenCiphertext * sizeof(int));
    for (int i = 0; i < lenCiphertext; i++) {
        distances[i] = 0;
    }

    // Encontra sequências iguais e calcular as distâncias entre elas
    for (int i = 0; i < lenCiphertext; i++) {
        for (int j = i + 1; j < lenCiphertext; j++) {
            if (strncmp(ciphertext + i, ciphertext + j, maxKeyLength) == 0) {
                distances[j - i]++;
            }
        }
    }

    // Encontra o maior divisor comum das distâncias
    int keyLength = 0;
    int maxCount = 0;

    for (int i = 1; i < maxKeyLength; i++) {
        int count = 0;
        for (int j = 0; j < lenCiphertext; j++) {
            if (distances[j] >= i) {
                count++;
            }
        }
        if (count > maxCount) {
            maxCount = count;
            keyLength = i;
        }
    }

    free(distances);
    return keyLength;
}

// Função para encontrar a chave usando análise de frequência
void findKeyWithFrequencyAnalysis(char *ciphertext, int keyLength, char *foundKey) {
    int lenCiphertext = strlen(ciphertext);

    for (int k = 0; k < keyLength; k++) {
        double maxIC = 0.0;
        char bestChar = 'A';

        for (char c = 'A'; c <= 'Z'; c++) {
            char *subtext = (char *)malloc(lenCiphertext);
            int subtextLen = 0;

            // Coleta letras em intervalos de tamanho keyLength
            for (int i = k; i < lenCiphertext; i += keyLength) {
                subtext[subtextLen++] = (ciphertext[i] - c + 26) % 26 + 'A';
            }

            subtext[subtextLen] = '\0';
            double ic = calculateIndexOfCoincidence(subtext, subtextLen);

            if (ic > maxIC) {
                maxIC = ic;
                bestChar = c;
            }

            free(subtext);
        }

        foundKey[k] = bestChar;
    }

    foundKey[keyLength] = '\0';
}

// Função para decifrar a cifra de Vigenère
void decryptVigenere(char *ciphertext, char *foundKey, char *plaintext) {
    int lenCiphertext = strlen(ciphertext);
    int keyLength = strlen(foundKey);

    for (int i = 0; i < lenCiphertext; i++) {
        char c = ciphertext[i];
        char k = foundKey[i % keyLength];

        if (isalpha(c)) {
            char base = islower(c) ? 'a' : 'A';
            plaintext[i] = ((c - k + 26) % 26) + base;
        } else {
            plaintext[i] = c;
        }
    }

    plaintext[lenCiphertext] = '\0';
}

int main() {
    char ciphertext[] = "FHVDH"; // Texto cifrado

    int keyLength = findKeyLength(ciphertext);
    char foundKey[keyLength + 1];
    findKeyWithFrequencyAnalysis(ciphertext, keyLength, foundKey);

    char plaintext[strlen(ciphertext) + 1];
    decryptVigenere(ciphertext, foundKey, plaintext);

    printf("Chave encontrada: %s\n", foundKey);
    printf("Texto decifrado: %s\n", plaintext);

    return 0;
}

Answer: A função findKeyLength está retornando o valor zero, assim foundkey será criada com nenhum elemento.
int keyLength = findKeyLength(ciphertext);
char foundKey[keyLength + 1]; /// keyLength tem valor zero
                              /// foundkey igual nulo

// Função para decifrar a cifra de Vigenère
void decryptVigenere(char *ciphertext   ,
                     char *foundKey     ,
                     char *plaintext   )
{
  int lenCiphertext = strlen(ciphertext);
  int keyLength     = strlen(foundKey  );

  for (int i = 0; i < lenCiphertext; i++)
  {
    char c = ciphertext[i];
    char k = foundKey[i % keyLength]; /// keyLength contem o valor zero
                                      /// erro, local de memoria invalido
                                      /// quando i for zero (0 % 0) = nao
                                      /// se pode dividir por zero
    if (isalpha(c))
    {
      char base = islower(c) ? 'a' : 'A';
      plaintext[i] = ((c - k + 26) % 26) + base;
    }
    else
    {
      plaintext[i] = c;
    }
  }
  plaintext[lenCiphertext] = '\0';
}


Creating arrays in Lua from list returned by gmatch

Question: I am programming in Lua and so far I have this.
S=tostring(M[i].AllSegmentsList)      --it returns "MSH, PID"
for i in string.gmatch(S, ",") do      --I have  ", " as delimiter
  t= {}        --Now, I want the values returned by delimiter to be added into an array.
end

How can I do that.
Answer: Declare the table before, and add the elements in the loop like this:
local t = {}
for i in S:gmatch("([^,%s]+)") do
    t[#t + 1] = i
end

The pattern [^,%s]+ matches one or more non-comma, non-space characters.
Comment: I would not recommend the `t[#t + 1]` approach. It's better to store the current index in a local variable. With #t Lua has to compute the length of the table at each iteration.
Comment: `%w` assumes the items are words formed with letter and digits, which is fine for the example given, but may not be general enough.
Comment: @lhf I changed it to `[^,%s]+`, hopefully that satisfies the OP's needs.
Comment: @W.B. If the table is large, I agree with you. I'm using `#` operator because it's more clear and in most cases, the table is small, so the performance is not an issue.
Comment: Thank you so much , it totally worked. But, can you please please please explain how is "([^,%s]+)" part working? I really need to now this. Thank you
Comment: I know I'm kinda late, but why not use table.insert(t, i)? Does it introduce significant overhead?
Comment: @Xerus Both are OK to use.
Comment: This answer here confirms what @W.B. said, that the length operator `#` isn't free, it does some calculations each time it's called. This answer here points to the relevant Lua interpreter source code: https://stackoverflow.com/a/18208085/4206247 (and if you use LuaJIT, the relevant code is this: https://github.com/LuaJIT/LuaJIT/blob/v2.1/src/lj_tab.c#L640-L686)


Elliptic Curve Point Division

Question: I have seen several different responses to this type of question, and I find them all contradictory or unclear.  This is a multi-part question.

If I have a point Q on an elliptic curve over a finite field, can it be divided by an integer say 2 to find the point which generates it by being doubled?

To illustrate, let's take a toy example that I have seen elsewhere:
$y^2 = x^3 + ax + b$
where:
a = -2
b = 1
*modulus = 89
With a Generator Point of (4,18)
We get the set:
<code>1 * P = (4, 18)    2 * P = (45, 73)
3 * P = (49, 28)   4 * P = (80, 64)
5 * P = (27, 36)   6 * P = (11, 81)
7 * P = (66, 47)   8 * P = (58, 40)
9 * P = (76, 12)   10 * P = (43, 52)
11 * P = (53, 26)  12 * P = (0, 88)
13 * P = (13, 6)   14 * P = (54, 19)
15 * P = (20, 60)  16 * P = (26, 80)
17 * P = (64, 88)  18 * P = (10, 64)
19 * P = (25, 88)  20 * P = (81, 22)
21 * P = (14, 15)  22 * P = (88, 25)
23 * P = (31, 2)   24 * P = (1, 0)
25 * P = (31, 87)  26 * P = (88, 64)
27 * P = (14, 74)  28 * P = (81, 67)
29 * P = (25, 1)   30 * P = (10, 25)
31 * P = (64, 1)   32 * P = (26, 9)
33 * P = (20, 29)  34 * P = (54, 70)
35 * P = (13, 83)  36 * P = (0, 1)
</code>
So, for example, I know that doubling 7*P (66,47) gives me the point 14*P (54,19).

Is there a division operation which can take the point (54,19) and give me (66,47)?  If so, could I do it again to 7*P, and what would be the result? 3*P or 4*P?

In this blog post towards the top, she mentions the Multiplicative Inverse being used in the division operation.
I am using a C# Library (found here) to calculate the values above, and it also has an "Extended Euclidean" Function which when I plug in 14*P (54,19) spits out (6,-17).

Is (6,-17) the multiplicative inverse of (54,19), and if so how do I use it to get back to (66,47)
If this is possible, can the same rules be applied to very large sets for example NIST P-192 or the secp256k1?

Thanks for your consideration and time.
Comment: Not every point can be divided by any integer. If $n\in\mathbb N$ and $E$ is an elliptic curve over a finite field $\mathbb F_q$, then you can divide all $\mathbb F_q$-rational point of $E$ by $n$ if and only if $\gcd(n,|E(\mathbb F_q)|)=1$. Just like in any finite abelian group.
Comment: What is the modulus for this curve?
Comment: I would say that you write down the generic equations for doubling a point, you equal them to the point that you have and you solve. Alternatively, but I guess it boils down to the same calculations, say that you have $Q$ and you want to divide it by 2. Take the pencil of lines passing through $-Q$, and intersect it with $E$. You will get a parametric equation of degree 3, say with parameter $t$. The discriminant is a polynomial of degree 3 in $t$. Its roots are the slopes of the lines which pass through $Q$ and $Q/2$, if there are any.
Comment: I can't believe that I left that out.  I'm editing the question now.
Comment: @Ferra so, I am assuming that only the points from my example which are even numbers * P are divisible by 2.  _How do I then go about the division?_
Comment: @ThereIsNoSky I came across this question because I'm in exact same situation. Pulling down the c# example I wasn't able to generate the same set of numbers as you using the `a=-2`. `b=1`, `p=89`. My results start with `1 * P = (3, 45)`. Are you sure those numbers are right? I tried every prime number < 100 for p with no luck.
Comment: @Levitikon - You have to set your first point to (4,18), and then you add it to itself to get the rest of the set.  EX:
'code'
 BigInteger a = -2;
 BigInteger b = 1;
 BigInteger p = 89;
 BigInteger x = 4;
 BigInteger y = 18;
 BigInteger k = 1;
 EllipticCurve ec = new EllipticCurve(0, 0, 0, a, b, p, p);
 ECPoint P = new ECPoint(p, p, x, y);
 ECPoint P2 = null;
'code'
Comment: OK, apparently, I'm too slow and accidentally hit enter instead of shift+enter.  Sorry.  Here is the full example:
'code'
 BigInteger a = -2;
 BigInteger b = 1;
 BigInteger p = 89;
 BigInteger x = 4;
 BigInteger y = 18;
 BigInteger k = 1;
 EllipticCurve ec = new EllipticCurve(0, 0, 0, a, b, p, p);
 ECPoint P = new ECPoint(p, p, x, y);
 ECPoint P2 = null;
 ECPoint P3 = null;
 ECPoint P4 = null;
 P2 = ec.Addition(P, P);
 P3 = ec.Addition(P, P2);
 P4 = ec.Addition(P, P3);
'code'
I haven't tested that code, so let me know if you have problems with it.
Answer: After doing some additional research on this topic, I think I have found an answer to my question.  I do appreciate everyone's comments, and the first answer provided, as they helped move me towards where I wanted to go with this.

Yes and no.  On several levels.  In order to divide on the elliptic curve you must find the multiplicative inverse of the SCALAR by which you want to divide.  In the question I suggest dividing by 2.  In order to do this you must find the multiplicative inverse of the scalar 2 on the specific curve / set / Field you are working with.  (I know that there are differences between those, but I won't get into the nuances as I'm not an expert)
It's important to realize that division is just multiplication by the "multiplicative inverse".  I believe that it is only possible to multiply a point in a set like this by a Scalar, so therefore you can only divide by a scalar, and the multiplicative inverse is therefore a scalar.

Now for the "NO".  Not all Fields have a multiplicative inverse for all numbers, and not all numbers when multiplied by a multiplicative inverse yield a point on the curve.

In short, yes.  But I'm trying to go about it in the wrong way.  The Extended Euclidean Algorithm takes 2 arguments.  The number for which you are trying to find the multiplicative inverse (2) and the modulus of the Field (89).  It then returns 3 values- x, y, gcd.  The multiplicative inverse is x % p.  (a SCALAR).  I determined this by additional analysis of the blog post I mentioned in the question.  Follow the python script closely.

14*P when multiplied by the multiplicative inverse of 2 will yield the point 7*P.
7*P when multiplied by the multiplicative inverse of 2 will yield a point I like to think of as 3.5*P.  This point won't necessarily be in the set or even on the curve.  This is because 7 is not evenly divisible by 2 and the set only contains Integers*P.

No, the multiplicative inverse is a SCALAR, not a point.
Yes, I believe these rules are applicable to all EC sets.

If I have made any grossly inaccurate statements in this answer, please point them out, and I will most likely update my answer.
Comment: @LordSharktheUnknown Well, it's not 3*P and it's not 4*P.  And, if you add (1*P)/2 to the result, you get 4*P.  So I think of it like 3.5*P.  I know it's not necessarily traditional, but it's just how I look at it.
Comment: What do you mean by "3.5\ast P"?
Comment: @ThereIsNoSky Out of curiosity, have you discovered any other way of detecting if the nP being divided by 2 is odd, other than the point produced not being on the curve? Because I'm not sure that's always true. Using the SECP256k1 curve, I'm seeing that 3*P / 2 is producing a point on the curve `(89636686429439908262420422079980100111093242688153882571369946125714247242771, 10834049905482024808827094233028503931704324296739647619935835709590451240976)`
Comment: Even 0.5*P is on the curve. It seems like there ought to be some sort of sign we're looking at a fractional point. Although, it's pretty mind bending to think about these actually being on the curve. Where can they possibly be? It's like the Upside Down Place in Stranger Things.
Comment: As a further note to this, I think that if you can find the multiplicative inverse for a Finite Field then the points are always on the curve / in the field.  This is because you are simply multiplying your point by a SCALAR, and any point in the field multiplied by a Scalar generates a point on the curve and in the field.  (Why all n*P are in the field and on the curve).  I'm stretching here, so if someone sees an error in my ways, please correct me.
Comment: I think this is incorrect. There is nothing you can multiply the point $14P$ by in order to get the point $7P$, because the order of the point $14P$ is 24, and $\gcd(14,24) \neq 1$, so you can't solve the equation $14x \equiv 7 \pmod{24}$. $14P$ multiplied by the multiplicative inverse of 2 mod 89, yields the point $6P$. However 14 the scalar multiplied by the inverse of 2 mod 89 will give you 7.
Answer: If you could divide 7P by 2 the result would be 48P because doubling 48P gives 7P:
48 * 2 mod 89 = 96 mod 89 = 89 + 7 mod 89 = 7
(I'm guessing you're trying to divide nP by 2 until you get to 1P. That won't help you any more than doing P + P + P... to get to nP. Unless n is a power of 2)
Comment: This is incorrect (see my comment above). $48P$ is the point at infinity, because the order of $P$ is 48, so doubling it will just give you the point of infinity again, not $7P$

Elliptic Curve Point Division


Cannot target #id as menu link?

Question: Drupal 6
How can i allow drupal to accept #idname as link? When I put # I cannot submit the form. Is there a way to do this?
Comment: Problem is that Drupal tries to validate what you put in your menu, but cannot validate if element of that id exists on a target page. How open you feel about hacking contrib modules?
Answer: You have five options.

Use the https://drupal.org/project/special_menu_items module
Do something like node/16#gohere (I'm not sure if you have a static page this is for)
Create a module to either edit a menu item or add one
Backport the https://drupal.org/project/void_menu module
Make your own module to do this :)

Sadly there is no way to do this by default.
Comment: Not to necro but special menu items module does not support #ID.

Cannot target #id as menu link?


warning MSB8004: Output Directory does not end with a trailing slash.

Question: I am getting a warning in my VC++ project as

1>...Microsoft.Cpp\v4.0\V140\Microsoft.CppBuild.targets(368,5):
  warning MSB8004: Output Directory does not end with a trailing slash.
  This build instance will add the slash as it is required to allow
  proper evaluation of the Output Directory.

I do have OutputDirectory value correctly set with trailing slash in my configuration property. How do I debug the path which is creating the problem ?
Comment: Do you have set Intermediate Directory value with trailing slash in your configuration property?
Answer: That warning only occurs when $(OutDir) has no trailing slash, see Microsoft.Cpp.Current.targets line 29. So even though you say you set it correctly (Output Directory in the properties sets $(OutDir) in the project file), msbuild doesn't see that. My guess: you set Output Directory for e.g. the Debug|Win32 configuration but are now building Release|Win32 or so. Or, it gets overridden somewhere else in your project file: open it with a text editor and look for OutDir.


Detect when, iframe(AVPlayer) of video player inside wkwebkit

Question: When I am open any website with movie inside WKWebKit and press on players this movie will be open inside some player, where I can pause, remove etc.
My question How I can detect when this iframe(window or player, I don't know how it is named) is open or closed and do something in background if window open or closed.
For clarity I am attached screenshot of simulator where this player was opened if I am press on player with movie on website.
Answer: I am solved this problem using NotificationCenter using UIWindowDidBecomeVisibleNotification & UIWindowDidBecomeHiddenNotification.
My code:
<code>override func viewDidLoad() {
        super.viewDidLoad()

// listen for videos playing in fullscreen
        NotificationCenter.default.addObserver(self, selector: #selector(onDidEnterFullscreen(_:)), name: UIWindow.didBecomeVisibleNotification, object: view.window)

        // listen for videos stopping to play in fullscreen
    NotificationCenter.default.addObserver(self, selector: #selector(onDidLeaveFullscreen(_:)), name: UIWindow.didBecomeHiddenNotification, object: view.window)
}

@objc func onDidEnterFullscreen(_ notification: Notification) {
    print("Enter Fullscreen")
}

@objc func onDidLeaveFullscreen(_ notification: Notification) {
    print("Leave Fullscreen")
}
</code>


Some ideals in $k[[x,y]]$

Question: I have an ideal in $k[[x,y]]$, and I know that it contains $x$ but isn't $\langle x \rangle$ (here $k$ is a field, maybe not alg closed).  This means that my ideal must be of the form $\langle x ,y^n \rangle$ for some $n$.
This is not hard to prove, but a proof isn't what I'm looking for.  What I want is the suitable commutative algebra lingo: how do I explain this fact in as few words as possible?  What more general principle is at work?
Comment: The ideals of $k\left[\left[x,y\right]\right]$ containing $x$ are in 1-to-1 correspondence with ideals of $k\left[\left[x,y\right]\right] / \left(x\right)$. But $k\left[\left[x,y\right]\right] / \left(x\right) \cong k\left[\left[y\right]\right]$ (this follows from $k\left[\left[x,y\right]\right] = \left(k\left[\left[y\right]\right]\right)\left[\left[x\right]\right]$), so we are looking for the ideals of $k\left[\left[y\right]\right]$. And that should be well-known.
Answer: The general principles are:
(1) the correspondence theorem for ideals, and
(2) the isomorphism $R[[X]]/(X)\simeq R$ for any commutative ring $R$.

Some ideals in $k[[x,y]]$


Issue of display in css

Question: I have following CSS and I want all my three select box in one line.Though I have implemented display as inline but its not working in div..
.block_feedback .field select { color: #FFF; width:375px; height:20px; line-height:17px; margin-left:13px; margin-top:4px; display:none; background-color:#00A2B1; border:0px; font-family:Arial, Helvetica, sans-serif; font-size:16px; }

            <select name="dobmonth" id="dobmonth" class="w_def_text" style="width:150px;">
              <?php getmonth(); ?>
            </select>
            <select name="dobdate" id="dobdate" class="w_def_text" style="width:80px;">
              <?php getbirthdate(); ?>
            </select>
            <select name="dobyear" id="dobyear" class="w_def_text" style="width:80px;">
              <?php getyear(); ?>
            </select>

Comment: Which browsers are you seeing this behavior on?  I see all 3 selects inline in firefox (via jsfiddle)
Comment: same: http://jsfiddle.net/YXNAH/
Comment: @RahulSingh, which browser?  The selects are aligned horizontally for me...
Comment: My question is not about select are not visible. I wish to have all three select in same line (horizontally in same line)... not vertically same line(one after another.)
Comment: @RahulSingh Are you saying you want it to look like this? http://jsfiddle.net/YXNAH/1/
Comment: @jackwink I want same as eg. by joseph but it is showing me as u showed me in ur eg. HOw Can I align all horizontally.?
Answer: Add float:left to the select in your css, like so: http://jsfiddle.net/YXNAH/5/
Answer: Use float:left to the select's as motoxer4533 said,
and in ".field" add float:left; and a specific width
Answer: Considering that select is an inline element, you don't need to float them. When rendered visually, inline elements do not usually begin on a new line.
http://jsfiddle.net/qByj4/
Also I would avoid the inline CSS. You can use its id to set a width.

Issue of display in css


How to switch between streams of data in Python Pandas

Question: I have two streams of data, both a series of (timestamp, value) tuples.
ie:
[(2013-04-03T22:16:36+0000, 2334.5), (2013-04-03T22:46:36+0000, 43543.23), ...]

The idea is one of these will be 'preferred' and one not, and I want to create a single time series that is a result of the higher preference stream when available, and falls back to a least preferable stream when not.
My idea was to put the timestamps of values from both streams into buckets, and use the buckets as an index for a DataFrame, with a column for each stream, and a list of (timestamp, value) tuples in each bucket. Then I can just go through per bucket, and choose the one with the highest number of points for example.
The data frame would look something like this:
timestamp            stream1                                  stream2
2013-04-03 00:00:00  [(2013-04-03T00:16:36+0000, 2334.5),     [(2013-04-03T00:17:36+0000, 2314.5)]
                      (2013-04-03T00:17:36+0000, 2314.5)]
2013-04-03 00:30:00  [(2013-04-03T00:43:44+0000, 43543.23),   [(2013-04-03T00:47:36+0000, 2364.5)]
                      (2013-04-03T00:54:24+0000, 4443.23)]
2013-04-03 01:00:00  []                                       [(2013-04-03T01:01:30+0000, 34.34)]
2013-04-03 01:30:00  [(2013-04-03T01:35:32+0000, 238734.3)]   [(2013-04-03T01:45:32+0000, 238734.3)]

In this situation, the timestamps have been put into half-hourly buckets, and stream1 is the preferred stream. For the bucket at 00:00, the two points in stream1 would be chosen, for the bucket at 00:30 the two points in stream 1 would be chosen, for the bucket at 01:00 the single point in stream2 would be chosen as stream1 has no data, for the bucket at 01:30 the single data point in stream1 would be chosen as it is the preferred stream.
How would I go about doing this? I have attempted creating the data frame and using resample('h', how='count') to split into hourly counts, and using groupby, but can't quite put the timestamps into buckets and create the lists of values for each stream per bucket.
Answer: I have a solution but I'm not sure how efficient it is (being a Pandas noob myself), or if there is a way that is more 'panda-style':
hh = date_range('2013-01-01T00:30:00', periods=48, freq='1800S')
s5 = date_range('2013-01-01', freq='5S', end='2013-01-02')
s5 = s5[:720] + s5[1440:]  # introduce a gap in the 5 second data
hh_d = Series(hh.astype('int') / 10 ** 9, index=hh)
s5_d = Series(s5.astype('int') / 10 ** 9, index=s5)
df = DataFrame({
    'hh': hh_d,
    '5s': s5_d,
})
# Make a grouping, for simplicity by day, hour
grp = df.groupby(lambda x: (x.day, x.hour))

result = TimeSeries()
for name, group in grp:
    winner = None
    for column in group.keys():  # iterate over the columns (streams)
        data = group[column].dropna()  # ditch any NaNs that will be present
        # next, perform the test (in this case, just the length)
        if not winner or len(data) > len(group[winner].dropna()):
            winner = column
    # finally, add the data to the result set.
    result = result.append(group[winner].dropna())

Checking the result at the time of the 5 second gap gives:
ipdb> result[719:725]
2013-01-01 00:59:55    1357001995
2013-01-01 01:00:00    1357002000
2013-01-01 01:30:00    1357003800
2013-01-01 02:00:00    1357005600
2013-01-01 02:00:05    1357005605
2013-01-01 02:00:10    1357005610
dtype: float64

Which shows that the half-hour stream was selected during the gap.
The example above is based on length of each column in the group, but I guess any test could be applied.
Hopefully someone with more pandas experience can elaborate on my strawman answer!


Does the central limit theorem hold for the prediction error over different samples?

Question: Given an (infinite) data population from which you repeatedly draw samples of a fixed size. On each sample you learn a classifier which you then evaluate by computing the prediction error on a large independent test set.
The prediction error is defined as the average over all instances in the test set of the zero-one loss function $\mathcal{L}(y,\hat{y})$. (The zero-one loss function $\mathcal{L}(y,\hat{y})=0$ if the predicted label $\hat{y}$ of an instance equals the true label of the instance y, and is 1 otherwise.)
My question is whether the central limit theorem holds in this situation, so that the distribution of the prediction error over the samples approximates a normal distribution, given a sufficient number of samples?
I know that the theorem holds for a sufficiently large number of independent random variables. So I am in doubt because the individual predictions for one test set originate from the same classifier, and the classifiers vary over the samples.
Comment: (1) Is the "large independent test set" the same for each sample or does it also vary from sample to sample?  In the first case all evaluations of prediction error will be correlated, whereas in the second case they will be independent. (2) How are you presuming to apply the CLT here?  The only correct way I can conceive of is to let the *sample sizes* grow large.  The CLT says nothing about what happens when you just take more and more samples.
Answer: Your scenario is idealized, in reality you will not have infinitely many records with labels so that you can draw 30 training sets and 30 test sets each of ample size and such that no records overlap between any of the 60 sets. You need 30 of each because in addition to the independence issue, you also cannot assume a normal distribution of classification performance measures. With 30 i.i.d. measures of any distribution though, you're good.
You could always divide your existing data-set with $n$ records into 60 such sets though. The classification performance measures (of which you have one value per test-set) would then be independent across test-sets making the central limit theorem applicable which means you can basically use t-tests to compare classifier performance. Let's see how that plays out.
For simplicity, say you have only 2 classes. Your classification algorithm needs 100 records per class in the training set to adequately learn to recognize a class. That's already $30*2*100=6000$ training records.
Regarding test sets, you also need enough records per class per test set. The reason for this is different though. Your 0-1 loss function can be transformed into an accuracy score between 0 and 1 on each test set. (You could also leave it as a loss function, but then you need to have test sets of exactly the same size because sets with fewer records need to show fewer misclassifications to have the same actual classifier performance. Therefore, better express it as a standardized accuracy rating. Or perhaps an F-measure if mis-classification costs are imbalanced.) In any case, the measures based on such 0-1 loss outcomes can only be seen as interval variables (continuous variables that can take (almost) any value on a given scale) if they are based on many 0-1 loss decisions. You need interval variables to do the t-tests that your question is obviously aimed at. So you need say 100 records of each class in each training set. 100 is not a hard limit here, but if you have too few records you are not justified doing t-tests and are stuck with low power McNemar tests that are non-parametric and therefore difficult to aggregate (Ditterich, 1988). This makes for another 6000 test records and 12000 records in total.
To your last question: depending on what you mean with "classifier", you might be confusing independence with identical distribution here (and you need both, hence i.i.d.). If by "classifier" you mean "classification algorithm", then don't worry about using the same classification algorithm for all training- and test sets. On the contrary, if you used $k$NN on one traning-test combination, neural nets on the second, logistic regression on the third etc. you would be producing measures that are not identically distributed. Each training-test combination would be based on a different algorithm, some of which are better than others. In such a scenario, it would also be impossible to compare the performance of two algorithms each run on the same number of training-test set combinations.
If by "classifier" you mean, "classifier model based on specific algorithm as applied to training data", then you will have a different classifier for each training set as you should. They will produce independent performance measures if the training- and test sets don't overlap, which you made sure is the case by dividing your data set into 60 parts.
In conclusion, your approach is statistically sound. But it's not the most practical. Even with perfectly balanced binary classes, you need 12k records based on my assumptions (which I think are on the lower end). With 10 perfectly balanced classes, you would need 72k records. If classes are unbalanced, you still need enough records of the smallest class which further increases the required data set size. You need to make the 60 subsets randomly out of your data set without forcing uniform class distribution in all 60 via stratification (otherwise independence would be questionable). So some will have fewer records of some classes than some other subsets, better raise the total number of $n$ to compensate for that as well.
Many data sets are not that large, but even if they were, your approach wouldn't be the best use one can make of them. The same (Ditterich, 1988) paper rules out two common practices. You cannot repeatedly divide your data set into training and test data so that each training-test split covers the entire data-set. Even if you do that 30 times, the 30 test set performance measures you obtain are not independent (training- and test sets overlap). A similar objection is made to cross validation, here only the training sets overlap, but still.
In the meantime, progress has been made, (Nadeau and Bengio, 1999) found a way to correct for the fact that training sets overlap in a cross validation (and also for the fact that test sets overlap in a repeated cross validation). Those corrected resampled t-tests satisfy all the assumptions of the t-test if you have at least 30 measures (typically 3 repetitions of 10 fold CV). They can be used on much smaller data-sets than your approach because they don't need so many totally distinct subsets in the data-set. Applied to the same sufficiently large data-set, corrected resampled t-tests still have the advantage of constructing better classifiers based on more records than your approach does.


how to download an original image or video with the baseUrl of Google Photos API?

Question: I want to use the REST Google Photos API to download original photos or videos from Goolge Photos, and I found there is no way to achieve it with the "baseUrl".
I have checked the following pages, but there is not a definitive answer:
https://issuetracker.google.com/issues/112096115
https://issuetracker.google.com/issues/80149160
So if there is indeed a way to get the original photos and videos or if there will be one?
Answer: The addition of '=d' will not give you the original file! I tested it. The quality and resolution of the image seems to match the original one, but some information like exif metadata (geo location) is missing. As a result, the file size is also smaller than the original. This makes is not usable for backup synchronization where I want the original file.
Actually, I expect from google that they give me automated access to my own original data. It looks like that is currently not the case.
I'm afraid there are currently only two options how to get the original fotos:

Manual download on Google Fotos
Manual download via Google Takeout

Very disappointing!
Answer: So I just read through the issue tracker answers you provided, and I noticed that one reply was to add '=d'to the baseUrl.
So example: GET https://lh3.googleusercontent.com/lr/AGb3...HG2n=d


C# MVC - UnitTest - If PartialView file exists

Question: I need to verify, in unit tests (using NUnit), if a PartialView file exists in directory.
Someone knows how can I verify this?
I tried these ways:
var result = ViewEngines.Engines[0].FindPartialView(context, name, false);

var result = ViewEngines.Engines[0].FindView(context, name, null, false);

But none of them was run properly.
Answer: You can have a look on FluentMVCTesting
Test would look like this:
using MyApp.Controllers;
using NUnit.Framework;
using TestStack.FluentMVCTesting;

[TestFixture]
class HomeControllerShould
{
    [Test]
    public void Render_default_view_for_get_to_index()
    {
        var controller = new HomeController();
        controller.WithCallTo(c => c.Index()).ShouldRenderDefaultView();
    }
}

More examples on their page.
Comment: It doesn't verify if the PartialView file exists in directory. :(
Comment: BTW, the FluentMVCTesting is very useful! Thank you.
Comment: that's a shame. I did not use it for partials, but it helped me some time ago with controller tests, until I gave up on that.