Q:

"Center-of-Mass" of lattice polygons (generalization of Pick's theorem)

Call a polygon with integer coordinates (in the Euclidean plane) a 'lattice polygon'. Pick's Theorem allows you to efficiently compute the number of lattice points inside this polygon given just its set of vertices.
Is there a similar method to efficiently compute the sum
$$\sum_{(x,y)\in \mathcal{P}} x$$
where $\mathcal{P}$ is some lattice polygon? In other words, are there any methods to compute the "center-of-mass" of the set of lattice points belonging to the interior/boundary of a given lattice polygon?
(By efficiently, I mean something on the order of the number of vertices of the polygon. Also, by triangulation it's clear that it suffices to answer this question for lattice triangles)
EDIT: In case it was unclear, I am not trying to find the actual center of mass of the triangle - I want to find the center of mass of the set of lattice points inside the triangle (hence the above sum).
EDIT 2: After working on this problem a bit more, I think I've arrived at a fairly simple method which seems to work and avoids the messy machinery of 3D-Ehrhart polynomials.
The idea is (just as in Pick's theorem), since we can inscribe any triangle inside a rectangle, it suffices to compute the sum for rectangles and right triangles. Computing the sum for rectangles is easy; it's just something like $(y_2-y_1)(x_1+(x_1+1)+...+x_2)$.
Because of symmetry, it's almost as simple for right triangles. Namely, the sum of x-coordinates in/on the boundary of any right triangle is just equal to ((sum of x-coordinates in the corresponding rectangle) + (sum of x-coordinates along the diagonal))/2.
Hopefully this helps anyone who later has the same problem.

A:

It depends on what you mean by efficient.  Computing $$\sum_{(x,y)\in P}x$$ is equivalent to computing the number of lattice points in a 3d polyhedron (basically $P$ with a slanted roof.)  This is a job for Ehrhart polynomials. If you decompose $P$ into triangles you can decompose the triangle's corresponding polyhedron into a triangular prism (for which computing the lattice points therein is just an application of Picks Theorem) and two tetrahedra, which are straightforward to deal with, but fiddly (see the mathworld page referenced above.)  All of this is explained clearly in great detail in Computing the Continuous Discretely.


Q:

What nuances does the term "тугрик" have?

When not referring to the actual Mongolian currency, what nuances does the term "тугрик" have, if any?
For example, does it imply that the currency is weak?

A:

It usually metaphorically means "some obscure local currency", hardly known and hardly usable outside the country of origin; "some kind of monetary surrogate of limited use and circulation" (such as chits, company store vouchers, in-game currency in online games etc.).
It's close in meaning to English "monopoly money" or "funny money".

В портах, куда мы заходили, нам выдавали ― донги или еще какие тугрики.
Я не стал говорить Владимиру, что местные тугрики тоже называются долларами
Тут надо заметить, что в Мексике местные тугрики обозначают таким же значком, как доллары

A:

The term as a reference to exotic currency was widepread during times of Soviet international contracts. Since nineties, the meaning became broader.
Phonosemantically and similar to cockney rhyming slang, the term implies a joking attitude (towards the topic, the situation, the currency, goods, etc.).
In this context it can refer not just to an exotic monetary unit, but to Russian roubles or more usual currency as well:
Есть тугрики?
Давай тугрики!

A:

As a native speaker I understand it as just a slang term for "money", similar to "капуста", not sure that teenagers are using it, probably adult audience is more inclined to use it ;-)


Q:

which delimeter to use while spliting String

I need to split this line string in each line, I need to get the third word(film name) but as you see the delimeter is one big blank character in some cases its small like before the numbers at the end or its big as in front of numbers at front.
I tried using string split with(" ") regex, and also \t but get the out of the bounds error.
400115305   Lionel_Atwill   The_Song_of_Songs_(1933_film)   7587
400115309   Brian_Aherne    A_Night_to_Remember_(1943_film) 7952

Did anyone have the same problem?

A:

Have you tried to split on all whitespaces like this: line.split("\\s+"). The split method supports regular expressions.
edit: sorry, should be \\s indeed.
The following code
String line = "400115305   Lionel_Atwill   The_Song_of_Songs_(1933_film)   7587";
System.out.println(Arrays.toString(line.split("\\s+")));

returns with [400115305, Lionel_Atwill, The_Song_of_Songs_(1933_film), 7587] on my machine (Java 6 SE).

A:

The solution was str.split("\\t");


Q:

Writing logarithm formulas on LibreOffice Math

How to write a logarithm (LOG) formula on a base different than base 10 on LibreOffice Math?
In my case, it  seems to only allow me to change the value inside the formula but not the base.

A:

How do I write a logarithm (LOG) formula with a base different to base 10?
To change the base use log_x(y) where x is the base.
Example
To display the logarithm to base 3 of 10 use the following expression:
log_3(10)


Q:

ООП Python. Индексация списка в методе класса

from copy import deepcopy

class Matrix:
    def __init__(self, m):
        self.matrix = deepcopy(m)

    def __add__(self, other):
        sumMatrix = []
        for i in range(len(self.matrix)):
            tempMatrix = []
            for x, y in zip(self.matrix[i], other[i]):
                tempMatrix.append(x + y)
            sumMatrix.append(tempMatrix)
        return sumMatrix

Необходимо реализовать класс Matrix. Он должен содержать:
1) Конструктор от списка списков. Гарантируется, что списки состоят из чисел, не пусты и все имеют одинаковый размер. Конструктор должен копировать содержимое списка списков, т. е. при изменении списков, от которых была сконструирована матрица, содержимое матрицы изменяться не должно.
2) метод add, принимающий вторую матрицу того же размера и возвращающий сумму матриц.
Вопрос: когда реализую метод add (нужно получить список сумм списков),
m1 = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
m2 = Matrix([[0, 1, 0], [20, 0, -1], [-1, -2, 0]])
print(m1 + m2)

то получаю ошибку, что класс 'Matrix' не индексируемый, хотя подается список списков по моей логике.
TypeError: 'Matrix' object does not support indexing

Подскажите пожалуйста в чем проблема и как ее решить?

A:

Замените
for x, y in zip(self.matrix[i], other[i]):

на
for x, y in zip(self.matrix[i], other.matrix[i]):

Т.к. other у вас - это тоже Matrix, а он сам по себе не является списком списков, он только содержит в себе этот список списков в атрибуте .matrix, и к этому атрибуту нужно обратиться явно.
Ну, либо можно реализовать дандер-метод __getitem__ и тогда ваш Matrix будет сам по себе уметь возвращать результат по индексу, но в рамках данной задачи в такой доработке мало смысла.
И, кстати, в текущем варианте у вас __add__ ничего не возвращает. Так что сложить-то он сложит, но этот результат никуда не попадает, и ваш принт напечатает None. Так что добавьте туда return.


Q:

OpenGL GLUT window very slow, why?

The problem
I have just now begun working with OpenGL using GLUT. The code below compiles and displays two wireframe cubes and a sphere. The problem is that when I attempt to drag or resize the window it induces a noticeable delay before  following my mouse.
This problem does not occur on my colleague's computer, same code.
I am working with Visual Studio 2012 c++ express on a Windows 7 computer.
I am a not an experienced programmer.
The code
    // OpenGLHandin1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <GL/glut.h>

void initView(int argc, char * argv[]){
    //init here
    glutInit(&argc, argv);
    //Simple buffer
    glutInitDisplayMode( GLUT_SINGLE | GLUT_RGBA );
    glutInitWindowPosition(100,100);
    glutInitWindowSize(800,400);
    glutCreateWindow("Handin 2");
}
void draw(){

    glClearColor(0,0,0,1);
    glClear(GL_COLOR_BUFFER_BIT);
    //Background color

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(0.6, 0, 0);

    glColor3f(0.8,0,0);
    glutWireCube(1.1); //Draw the cube
    glPopMatrix();

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(-0.5, 0, -0.2);

    glColor3f(0,0.8,0);
    glutWireCube(1.1); //Draw the cube
    glPopMatrix();

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(0, 1.2, 0);
    glRotatef(90, 1, 0, 0);

    glColor3f(1,1,1);
    glutWireSphere(0.6, 20, 20); //Draw the sphere
    glPopMatrix();

    //draw here
    //glutSwapBuffers();
    glutPostRedisplay();
    glFlush();

}
void reshape (int w, int h){
    glViewport(0,0,w ,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, (float)w/(float)h, 1.5, 10);
    gluLookAt(1.5, 2.5, 4,
              0, 0.6, 0,
              0, 1, 0); //Orient the camera
    glRotatef(5, 0, 0, 1);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char * argv[])
{
    initView(argc,argv);
    glutDisplayFunc(draw);
    glutReshapeFunc(reshape);
    glutMainLoop();
}

A:

Solution:
It seems that the simple solution using Sleep(1) in the render function worked. You've also asked why - I'm not sure I will be able to solve this properly, but here's my best guess:
Why does it even work?
Your fellow students can have VSync turned on by default in their drivers. This causes their code to run only as fast as the screen can refresh, most probably 60 fps. It gives you around 16 miliseconds to render the frame, and if the code is efficient (taking, say, 2 ms for render) it leaves plenty of time for the CPU to do other OS-related stuff, such as moving your window.
Now, if you disable vertical sync, the program will try to render as many frames as possible, effectively clogging all other processes. I've suggested you to use Sleep, because it reveals this one particular issue. It doesn't really matter if it's 1 or 3 ms, what it really does is say "hey, CPU, I'm not doing anything in particular right now, so you may do other things".
But isn't it slowing my program?
Using Sleep is a common technique. If you're concerned with that lost 1 ms every frame, you can also try putting Sleep(0), as it should act exactly the same - giving the spare time to the CPU. You could also try enabling vertical sync and verifying if indeed my guess was correct.
As a side note, you can also look at CPU usage graphs with and without sleep. It should be 100% (or 50% on a dual-core CPU) without (running as fast as possible), and much lower with, depending on your program requirements and your CPU's speed.
Additional remarks about Sleep(0)
After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses. - it's from here.
Also note that on Linux systems behavior might be slightly different; but I'm not a linux expert; perhaps a passer-by could clarify.


Q:

How do certain commands change the tabbed autocomplete criteria?

Suppose I am in a directory like this:

:mydirectory$ ls

foo.txt

That only file. If I type a command like cat and then I tab to autocomplete (assume the ‸ character is actually the caret position and not a character for this purpose)...

:mydirectory$ cat ‸

changes to (again: the ‸ here is not a character but the caret)...

:mydirectory$ cat foo.txt ‸

But it is not the same for a command like this:

:mydirectory$ tar ‸

When tabbing I see the options to autocomplete:
A c d r t u x

And when writing something like:

:mydirectory$ tar -zxvf ‸

Then nothing is autocompleted.
My question is: how do many commands change the autocomplete rules in bash?

A:

Commands don't change the autocomplete rules. The autocomplete rules are defined for the shell using scripts and functions and loaded when the shell is started. I am going to use bash as an example since I am familiar with that more than the other shells.
The rules for autocomplete in bash are defined in the script in /etc/bash_completion and supplemented by further scripts in /etc/bash_completion.d/ directory. These rules are sourced into bash when you login.
bash has a complete command that lets you easily define rules for completion. To see all the rules already defined, you can run complete -p.
Now, most distros will already define these rules for you. So, when you type tar <TAB>, there is already a rule defined by your distro to show file which match the pattern *.tar* and the options of the tar command as autocomplete suggestions. This is why when you type tar, it gives you the options A c d r t u x, but for tar -zvxf, it does not since there can be no further options after that. Now, if you out a .tar.gz file in that directory, it will suggest that as an autocomplete option since the next thing after the f option is a tar file.
The default /etc/bash_completion doesn't provide options as suggestions and doesn't filter the file types. In that case, you will also see the foo.txt file as a suggestion to tar.
You can read about creating your own rules here - https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1 and https://debian-administration.org/article/317/An_introduction_to_bash_completion_part_2


Q:

I hate hats!

I hate hats. I got a hat today (00.01 hours). I haven't done anything wrong! Nothing at all, at least here on the not-so-dark-side on ELL (as opposed to EL&U). Why am I being given hats!? Hats is bad. I'm an santaethist and celebrating Santashness is not what I want. And I hate headgear. An for that reason,  I've been avoiding ELL like the plague. Why did I get a hat? Boo to hats.
Now I've been given one, I don't know if I can not wear it or not (I mean within myself, not within the "ELL rules").
Why was I given a hat?
I want an answer.

A:

If you really hate hats, you can always click I hate hats in the Winter Bash drop-down:

Until you do that, I'm afraid the system will assume you love hats and keep giving you hats based on this misapprehension.


Q:

Comparison using modifiable signs (python)

In Python, is there a way of comparing values using a variable comparison sign? For example, I want to be able to change the sign to be < or >, and have the if statement still work.
The code below shows the idea, but it is not valid in Python:
sign = <
if 1 sign 2:
    print("This works")

A:

Python's operators like < and > aren't values, so you can't assign them to variables. However, functions are values in Python, so you can assign them. The operator module has functions named lt and gt respectively:
>>> from operator import lt, gt
>>> lt(1, 2)
True
>>> gt(1, 2)
False
>>> sign = lt
>>> sign(1, 2)
True

So you could write:
from operator import lt, gt

sign = lt

if sign(1, 2):
    print('This works')


Q:

Pass arguments list to sass mixin and compose one value from it

Sry for confusing title, don't know how to write it in simple manor.
What I want is something like this:
.someClass {
  @include transition(color, background);
}

to be transpiled to:
.someClass {
  transition: color 200ms ease-in-out, background 200ms ease-in-out;
}

I couldn't find this in documentation.
Any help appreciated.

A:

There are some ways of doing this, what you are looking for is a sass mixin.
Although it is a good solution for simple use cases, it's not always the easiest.
Here I leave one example. I hope it's useful:
@mixin transition($duration, $ease, $props){
  $value: '';
  @if(type-of($props)=='string'){
    $value: $props $duration $ease;
  }
  @if(type-of($props)=='list'){
    $i: 0;
    @each $prop in $props{
      $i: $i + 1;
      $value: #{$value} $prop $duration $ease if(length($props) == $i, unquote(''), unquote(','));
    }
  }
  transition: $value;
}

.someClass {
    @include transition(200ms, ease-in-out, $props: color background);
}


Q:

Batch - Removing parent section of a specific child in an XML file

I'm trying to remove a parent section using a string in a child's tag.
Section of the XML file (original.xml)
<Mods>
    <ModItem>
        <Name>296707746.sbm</Name>
        <PublishedFileId>296707746</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>294620323.sbm</Name>
        <PublishedFileId>294620323</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>295393216.sbm</Name>
        <PublishedFileId>295393216</PublishedFileId>
    </ModItem>
</Mods>

I need to remove the parent section of a child that matches <Name>numbers.sbm</Name> tags Like this:
<ModItem>
    <Name>294620323.sbm</Name>
    <PublishedFileId>294620323</PublishedFileId>
</ModItem>

to produce this:
<Mods>
    <ModItem>
        <Name>296707746.sbm</Name>
        <PublishedFileId>296707746</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>295393216.sbm</Name>
        <PublishedFileId>295393216</PublishedFileId>
    </ModItem>
</Mods>

Current code i'm using:
FOR /f "tokens=1 delims=:" %%L in ('FINDSTR /n "<Name>294620323.sbm</Name>"      sandboxxml.txt ') do set /a line=%%L-2

BREAK> "%temp%\empty"

FC "%temp%\empty" "sandboxxml.txt" /lb %line% /t | MORE +4 |FINDSTR /b /e /v "*****" >temp.xml

(the code is a modified answer from a different topic)
It adds everything before the section to temp.xml
How would i get the rest of the original.xml into temp.xml, excluding the removed section?
and is there a different/simpler way to achieve this?
( this is my first question on stackoverflow, sorry if i did something wrong!)

A:

The Batch file below use the same method of your example:
@echo off
setlocal

for /F "delims=:" %%L in ('findstr /N "<Name>294620323.sbm</Name>" original.xml') do set /A start=%%L-1, end=%%L+2
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" original.xml') do (
   if %%a lss %start% echo(%%b
   if %%a gtr %end% echo(%%b
)) > new.xml

Note that this method works on this file only, with this specific format.


Q:

RTFString Containing NSASCIIStringEncoding Special Characters?

I have a string in my cocoa GUI that needs to have special formatting (fonts, colors, etc.). Naturally, I'm using an attributed string. For convenience, I Init the string as an RTF:
NSString *inputString = @"This string has special characters";
NSString *rtfString = [NSString stringWithFormat:@"{@"***LENGTHY RTF FORMATTING STRING *** %@", inputString];
NSAttributedString *testString = [[NSAttributedString alloc] initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];

The problem is, the "inputString" might have special characters, which are not displayed properly due to the UTF8Encoding. They're replaced with other symbols.
é is left as Å©.
So, right now I'm doing this:
NSData* intermediateDataString=[inputString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

inputString = [[[NSString alloc] initWithData:intermediateDataString encoding:NSUTF8StringEncoding] autorelease];

This does not display the unexpected characters, but it does remove all accents and leaves in their stead the unaccented letter - é is left as e.
This is an improvement since everything can be read, but it is far from ideal.
Thoughts?

A:

I would do something like this. First, create a dummy attributed string:
NSString *dummyRTFString = @"***LENGTHY RTF FORMATTING STRING *** A";
NSAttributedString *dummyAS = [[NSAttributedString alloc]
                                      initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding]
                               documentAttributes:nil];

and obtain the attributes:
NSDictionary*attributes=[dummyAS attributesAtIndex:0 effectiveRange:NULL];
[dummyAS release];

Now I will use this attribute to create another attributed string:
NSAttributedString* as=[[NSAttributedString alloc] initWithString:inputString attributes:attributes];

Another approach is to use HTML instead of RTF; then you can include non-ascii characters as unicode in it.


Q:

shiny: passing reactiveValues to conditionalPanel

Can I pass a reactiveValues to a conditionalPanel's condition? If so, how?
Here is what I have tried in the conditionalPanel ui.R:
conditionalPanel(condition = "values.cond == 0", etc.

where I have defined values$cond in server.R:
values <- reactiveValues(cond = 0)

I have also tried alternatives like "values.cond == true", without success.
library("shiny")
runGist("https://gist.github.com/anonymous/8281021")

See the code:
https://gist.github.com/anonymous/8281021

A:

As @jdharrison pointed out, you have the problem, that you have reactive values or any other data on the server side and the conditional panel is a JS condition + some HTML on the client side. Hence, if you want to dynamically update the JS condition according to some value you calculated on the server side, you need to get the data from the server to the client. I think what you could do is use an still undocumented feature of shiny to pass custom data from the server to the client. I wrote a blog post on how to do that: http://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/
I guess you could use that approach to dynamically update the JS panel condition. You would need to write a JS function that does this after the data has been passed. So this boils down to replacing the data-display-if attribute of the conditionalPanel output with the values you want.
Another idea: If your UI strongly depends on calculations on the server side you may want to consider creating the (sidebar) content dynamically using renderUI.
EDIT: Btw, that's what @jdharrison referred to in his second comment.

A:

You can also do it by rendering text. UI:
shinyUI(
  fluidPage(
    # Application title
    titlePanel("Test"),

    sidebarLayout(
      sidebarPanel(
        actionButton("ShowCond", "Show Conditional Panel"),
        conditionalPanel(
          condition = "output.test=='5'",
          actionButton("CheckFile", "Check file")
        )
      ),
      mainPanel(
        verbatimTextOutput("test")
      )
    )
  )
)

Server:
shinyServer(function(input, output, session) {
  var <- eventReactive(input$ShowCond, {
    5
  })

  output$test <- renderText({
    var()
  })
})

The catch is here that it doesn't work without the verbatimTextOutput. You need to include it somewhere on your UI side. However, you could reuse it as a message.
EDIT:
It is also possible without the verbatimtext. By default Shiny suspends all output when they are not displayed. However, this can be changed by setting the following option for a specific output variable:
outputOptions(output, "test", suspendWhenHidden=FALSE)

In this case, there is nor more need to use verbatimtext (and the corresponding rendertext).
Source: https://shinydata.wordpress.com/2015/02/02/a-few-things-i-learned-about-shiny-and-reactive-programming/#use-of-isolate-to-prevent-accidental-dependencies


Q:

Can I make threads wait for a lock and then jump over it once released?

Given is the following pseudo code. A function may be entered by multiple threads simultaneously. I want all threads to execute a() and c(), but b() must only be executed by those threads that were not locked when entering the synchronized block.
In other words: If a thread must wait for the lock, then I want it to wait until the lock is released and then jump over b() and continue with c() right away.
    public void code() {
        a() // check if page is present locally

        if (pageMissing) {
            synchronized (this) {
                page = b(); // get page over REST
            }
        }

        c() // access page
    }

How is this useful? Imagine b() calls an external REST function to update local data. When a thread enters, we want to be sure that the function is called and local data is updated, but once the blocking thread exits b() we know local data is current and we don't want to waste resources in having consecutive threads that were already waiting call the update function again.

A:

You can have a boolean flag (instance variable) that denotes whether b() has been called or not. All threads that enter the synchronized block will check this condition before calling b().
private boolean isDone = false;

public void code() {
    a();
    synchronized (this) {
        if (!isDone) {
            b();
            isDone = true;
        }
    }
    c();
}

Only the first thread that acquires the lock will call b(). After it succeeds, it will set the flag to true and will exit the block. All subsequent threads entering the block will fail on the if condition and hence will not invoke b().

If you do not want the other threads to wait on the synchronized block's lock and want to continue to call c(), you can remove the synchronized keyword and use an AtomicBoolean and use its compareAndSet
 private AtomicBoolean isDone = new AtomicBoolean(false);

 public void code() {
    a();
    if (isDone.compareAndSet(false, true)) {
       b();
    }
    c();
}

Javadoc of compareAndSet states

Atomically sets the value to the given updated value if the current value {@code ==} the expected value.
@return {@code true} if successful. False return indicates that the actual value was not equal to the expected value.

So, the first thread that calls compareAndSet while isDone is false will succeed. The others will get false as the return value and hence won't enter the block and can thus continue.

UPDATE:
From your comments

@user7 Yes, I am concerned with threads calling b() unnecessarily, but (see my other comment) I need those threads that arrive while b() runs to wait until it is finished before they continue with c()

Seems you need the first solution of mine.


Q:

Generalized Clifford's Theorem

A typical statement of Clifford's theorem is the following:
Let V be a finite dimensional irreducible representation of a group G, and let N be a normal subgroup of finite index in G. Then the restriction of V to N is a semisimple.
The question I am trying to answer is the following:
Let V be an irreducible representation of a group G and let N be a normal subgroup of G. Show that the restriction of V to N is semisimple.
There are no other restrictions on G,V or N. Is there any way to get this result assuming Clifford's Theorem? Or is there a way to prove this in a similar manner?

A:

The sum of (even an infinite set of) irreducible submodules is semisimple, and the sum of all irreducible $N$-submodules of $V$ is a $G$-submodule, which must be $0$ or $V$, since $V$ is irreducible as a $G$-module. So if the restriction of $V$ has any irreducible submodules at all then it must be semisimple.
If $V$ is finite dimensional then this is the case, even if $N$ has infinite index.
If $N$ has finite index in $G$ then it's also the case. If $v$ generates $V$ as a $G$-module, then $\{vg_1,\dots,vg_n\}$ generates as an $N$-module, where $\{g_1,\dots,g_n\}$ is a set of coset representatives. In particular, the restriction of $V$ is finitely generated, and so has a maximal submodule $U$. But then $Ug_i$ is also a maximal submodule, and the natural map $V\to\bigoplus V/Ug_i$ is a nonzero map to a semisimple $N$-module, whose kernel is a $G$-submodule and therefore zero, since $V$ is irreducible. But every submodule of a semisimple module is semisimple.
But there are infinite dimensional examples for normal subgroups of infinite index where the restriction has no irreducible submodules (and so is not semisimple). For example, let $k$ be any field, let $V=k(t)$, the field of rational functions, let $G$ be the multiplicative group of $k(t)$ acting on $V$ by multiplication, and let $N$ be the cyclic subgroup generated by $t$. Then $V$ is an irreducible $kG$-module, but has no irreducible $kN$-submodule, since the $kN$-submodule generated by any $f(t)\in k(t)$ has a nontrivial proper submodule generated by $(t+1)f(t)$.


Q:

Htaccess 301 Redirect Rules / HTTP to HTTPS / non-www to www

I have an old domain where was the old site:
http://example-old.com/

Would like to do 301 redirect to new domain:
https://www.example-new.com/

How do I achieve that in .htaccess with the 301 redirect rules.
And needs to match these requirements:
If someone types in the URL
http://example-old.com/ >>> https://www.example-new.com/

https://example-old.com/ >>> https://www.example-new.com/

http://www.example-old.com/ >>> https://www.example-new.com/

https://www.example-old.com/ >>> https://www.example-new.com/

">>>" - means 301 redirect

When I put it in the .htaccess file
Redirect 301 / https://www.example-new.com/

It works for
http://example-old.com/ >>> https://www.example-new.com/

The rest is a blank white page or connection error.
I do not need to pass any arguments or query string - because the URL (query string) on the new site is different - so I just need those 4 to be working and pointing to new site domain and always HTTPS (443 port).
Can someone help me with this?

A:

Please try adding this to your .htaccess file instead of what you have here. It should redirect all requests to the new address.
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule .* https://www.example-new.com/ [R=301,L]
</IfModule>


Q:

Initialize structures without defining members of structure - C

I am trying to decipher someone's code and I see something that I don't understand.  I don't see any references on how structures are applied when members aren't defined in the header or in the beginning of code but are defined later on..  Here is an example of what I am trying to figure out. I noted that Data_t *data; in the header is not defined until we enter the funky function and my compiler errors out on this line.  I guess my question would be -- is this a valid way to input data into structures?
Much thanks!
#include <stdio.h>

typedef struct config{
    int a;
    int b;
    int c;
    Data_t *data;
} config_t;

int funky(config_t *config);

int main( void )
{
    printf("In main()\n");
    config_t config;
    funky(&config);

    printf("a = %d\n", config.a);   //accessing config's a member

    return 0;
}

int funky(config_t *config)
{
    printf("In funky()\n");

    Data_t *dataa = config->data;
    for(i=0;i<5;i++){
        dataa[i].mem1=i;
        dataa[i].mem2=4+i;
    }

    //Set values
    config->a = 1;
    printf("a = %d\n", config->a);  //pointer to config's a member

    return 0;
}

A:

The definition of Data_t doesn't appear in your code, which is what's causing the compile error.
Also - to your specific question, that code is dereferencing an uninitialized pointer, which causes undefined behaviour.  Initialize the data field in the config structure in main, or you're going to be in trouble.  This block of code:
Data_t *dataa = config->data;
for(i=0;i<5;i++){
    dataa[i].mem1=i;
    dataa[i].mem2=4+i;
}

Is the bad stuff - as you can see, it copies the unitialized pointer out and tries to access memory through it.
The code after that:
//Set values
config->a = 1;

Is fine, and a totally reasonable way to initialize a structure.


Q:

XCom Enemy Within Long War on OS X

Has anyone tried applying the Long War mod to a Mac running OS X with Enemy Within installed from the Mac App Store?  If so, how stable was the gameplay after applying it?  The creators of the mod do not believe it will work, but they welcome Mac users to try it on the page linked to below.
http://www.nexusmods.com/xcom/mods/88/?
Regards,
Sam

A:

In case you're not yet aware, the Beta 13 version of the mod (released 27th August) is available as a Mac OSX installer - via the files section of the link in your question.
I've successfully used this to install and play the mod on a the Steam version of the game on a Mac.
I do not know if it works or not with the iTunes version of the game.
The install requires a little more effort than the Windows version - a change to the hosts file is required, for example - the readme docs with the download explain this for you, so read them first.


Q:

Existence of connection on dual bundle

I quote the construction given in Madsen's Calculus to Cohomology. This is more or less the construction explained here defining connection on dual bundle.

For a vector bundle $\Omega^i(\xi) := \Omega^i(M) \otimes_{\Omega^0(M)} \Omega^0(\xi)$, where $\Omega^0(\xi)$ are smooth sections, $\Omega^i(M)$ are sections of $i$ forms.
1. We define a non singular pairing
$$ \Omega^i(\xi) \otimes \Omega^j(\xi^*) \xrightarrow{\wedge} \Omega^{i+j}(\xi \otimes \xi^*) \rightarrow \Omega^{i+j}(M)$$
given by
$$(w \otimes s, \tau \otimes s^*) \mapsto (w \wedge \tau) \otimes \langle s,s^* \rangle $$
where $\langle s,s^* \rangle $ is given from the bundle map $\xi \otimes \xi^* \rightarrow \underline{\Bbb K}$ the trivial bundle.

2. We define the connection on $\xi^*$ for all $s \in \Omega^0(\xi),s^* \in \Omega^0(\xi^*)$, we have
$$ d(s,s^*) = (\nabla_{\xi}(s), s^*) + (s, \nabla_{\xi^*} (s^*))$$

I have two questions:
a.  Is it clear that this definition of $\nabla_{\xi^*}$ yields a
connection.
b. Why does this definition guarantee existence ?

A:

Let's work with local frames. Suppose that $\{ e_i \}$ is a local frame for $\xi$, and suppose that $\{ e_j^\star \}$ is the dual frame for $\xi^{\star}$ (i.e. $\langle e_i , e_j^\star \rangle = \delta_{ij}$). And suppose that $\nabla_{\xi} e_i = \sum_k\omega_{ik} e_k$ for suitable one-forms $\omega_{ik}$. An arbitrary section of $\xi^\star$ can be written as $s^\star = \sum_j s^\star_j e_j^\star$, for suitable smooth functions $s_j$, and our aim is to determine $\nabla_{\xi^\star} s$. We can calculate as follows:
\begin{align} (e_i, \nabla_{\xi^\star}s^\star) &= d(e_i, s^\star) - (\nabla_\xi e_i , s^\star) \\ &= \sum_j d\left( s^\star _j \langle e_i, e_j^\star \rangle \right)  -\sum_{jk} s^\star_j \omega_{ik}\langle e_k, e_j^\star \rangle \\ &=ds^\star_i-\sum_j \omega_{ij}s^\star_j.   \end{align}
This implies that
$$ \nabla_{\xi^\star} s^\star = \sum_i( ds^\star_i - \sum_j \omega_{ij} s^\star_j  )e_i^\star. \ \ \ (\star)$$
We still need to show that the $\nabla_{\xi^\star}$ defined in $(\star)$ is a connection. This follows from this calculation:
\begin{align} \nabla_{\xi^\star} (fs^\star) &= \sum_i( d(fs^\star_i) - \sum_j \omega_{ij} fs^\star_j) e^\star_i  \\ &=(df) \sum_is^\star_i e^\star_i + f \sum_i ( ds^\star_i - \sum_j \omega_{ij} s^\star_j) e^\star_i \\ &= (df) s^\star + f\nabla_{\xi^\star} s^\star \end{align}
We also need to show that $d(s,s^*) = (\nabla_{\xi}(s), s^*) + (s, \nabla_{\xi^*} (s^*))$ holds for arbitrary $s$ when $\nabla_{\xi^\star}$ is defined by $(\star)$. Writing $s$ in the form  $s = \sum_i s_i e_i$ for suitable smooth functions $s_i$, this statement follows from the calculations:\begin{align} d(s, s^\star) &=  d\left( \sum_{ij} s_i s^\star_j\langle e_i, e_j^\star \rangle \right) = \sum_i d(s_i s^\star_i) =\sum_i(ds_i) s_i^\star +  s_i (ds^\star_i) \\ (\nabla_\xi s, s^\star) &= \sum_{ij} (ds_i + \sum_k \omega_{ki}s_k) s^\star _j\langle e_i, e_j^\star \rangle =\sum_i (ds_i) s_i^\star + \sum_{ik} \omega_{ki} s_k s_i^\star \\ (s, \nabla_{\xi^\star} s^\star ) &= \sum_{ij} s_i (ds_j^\star - \sum_k \omega_{jk} s_k^\star ) \langle e_i , e_j^\star \rangle =\sum_j s_j (ds^\star_j) - \sum_{jk}\omega_{jk} s_j s_k^\star  \end{align}

Edit: As for coordinate independence, one way is to do the brute force calculation. If $\{ f_i \}$ is a different local frame, valid on a different patch, with $f_i = \sum_{ij} g_{ij} e_j$ on the overlap between the two patches for suitable non-vanishing smooth functions $g_{ij}$, then the dual bases are related by $f_i^\star = \sum_{ij}(g^{-1})_{ji} e_j^\star$. And if $\nabla_\xi f_i = \sum_k \zeta_{ik} f_k$ for suitable one-forms $\zeta_{ik}$, then you can show that
$$ \zeta_{ik} = \sum_l dg_{il} (g^{-1})_{lk} + \sum_{lm} g_{il} \omega_{lm} (g^{-1})_{mk},$$
and from here, you can verify that definition $(\star)$ is consistent whether you work using the $\{ e_i \}$ frame or the $\{ f_i \}$ frame.
But actually, I don't think we need to do all this work! Since $(\star)$ is the unique  $\nabla_{\xi^\star}s^\star$ satisfying $d(s,s^*) = (\nabla_{\xi}(s), s^*) + (s, \nabla_{\xi^*} (s^*))$ for all $s$ on the first patch, and since $(\star)$-written-in-the-new-frame is the unique $\nabla_{\xi^\star}s^\star$ satisfying $d(s,s^*) = (\nabla_{\xi}(s), s^*) + (s, \nabla_{\xi^*} (s^*))$ for all $s$ on the second patch, the two definitions must be equal on the overlap!


Q:

Загрузка файла на удаленный сервер без использования формы

Здравствуйте!
Вопрос - как загрузить/передать файл(в качестве указателя на него используя URL-на моем сервере), на другой удаленный сервер. Ниже приведен код загрузки изображения на хостинг картинок с использованием формы input file. Работает замечетельно.
Но проблема начинается, когда пробую заменить

$filename = $img['tmp_name'];

на
$filename = $image_pass; // где $image_pass == путь к файлу на
сервере-доноре (типа http://server.com/images/image.jpg)

После 5 часов гугления, появляется понимание, что в $_FILES(при использовании формы загрузки файла) - формируется некая структура

$_FILES == Array (
[name] => 1.jpg
[type] => image / jpeg
[tmp_name] => http://server.com/images/image.jpg
[error] => 0 [size] => 60541
)

загружаемый файл - сохраняется во внутренностях массива $_FILES, потом частями пересылается методом POST на удаленный сервер.
Как имитировать работу формы, но отправлять обработчику только лишь URL-файлов а не кодированное значение с массива $_FILES?
Помогите пожалуйста, кто-чем сможет!
Рабочий код ниже:

<!DOCTYPE html>

    <title>Image Upload Using Imgur API</title>

Image Upload Using Imgur API

    <form action="" enctype="multipart/form-data" method="POST">
        Choose Image : <input name="img" size="35" type="file"/>

        <input type="submit" name="submit" value="Upload"/>
    </form>
    <?
    if (isset($_POST['submit'])) {
        $img = $_FILES['img'];
        if ($img['name'] == '') {
            echo "
An Image Please.
";
        } else {
            $filename = $img['tmp_name'];
            $client_id = "77777777777777777";//Your Client ID here
            $handle = fopen($filename, "r");
            $data = fread($handle, filesize($filename));
            $pvars = array('image' => base64_encode($data));
            $timeout = 30;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
            curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
            $out = curl_exec($curl);
            curl_close($curl);
            $pms = json_decode($out, true);
            $url = $pms['data']['link'];
            if ($url != "") {
                echo "
Uploaded Without Any Problem
";
                echo "";
                echo $url;
            } else {
                echo "
There's a Problem
";
                echo $pms['data']['error']['message'];
            }
        }
    }
    ?>

A:

Нельзя переслать фаил урлом. Вам нужно прочитать данные из фаилы и переслать их.
Проблема возникает из-за того что функция fopen ожидает путь до локального файла а не url.
Когда вы загружаете фаил через форму, он сначала сохраняется на сервере во временной папке. tmp_name указывает на этот временный фаил, а не url.
Обычно там что,то типа /tmp/some_random_letters.
Если сделаете $filename = "./images/image.jpg"; должно начать работать (предполагаю что php фаил находится в корне (т.е. доаступен по адресу http://server.com/<image_upload.php>)).


Q:

postfix header_checks to rename email subject

We have a number of external systems reading from our emails, and some are tripping over others. Basically what I need to do is replace an email subject like:
[RT #179497] Internal: blah blah

with
[RT 179497] Internal: blah blah

So drop the hash. Does anyone know the regex to achieve this with postfix header_checks?

A:

See header_checks(5) for examples and http://www.postfix.org/BUILTIN_FILTER_README.html#limitations for additional information.
Modifying the example in the mentioned man page is not that hard:
/etc/postfix/main.cf:
header_checks = pcre:/etc/postfix/header_checks.pcre

/etc/postfix/header_checks.pcre:
/^Subject: \[RT #(\d)\] Internal: (.+)$/    REPLACE Subject: [RT $1] Internal: $2

It could probably be done more elegant or shorter, but that's your job now.


Q:

biblatex-apa: for citations in text of the same author but different publications: shortauthor every time in [ ]

I am using biblatex-apawith the apa6.cls.
In the text I cite several versions of the DSM (Diagnostic and Statistical Manual for Mental Disorders) by the American Psychiatric Association (APA):
@book{APA1994,
    author={{American Psychiatric Association}},
    shortauthor = {APA},
    year={1994},
    title="{Diagnostic and statistical manual of mental disorders: {DSM-IV}}",
    publisher={Autor},
    edition = {4th ed.},
    address={Washington, DC},
}

@book{APA2000,
    title = {Diagnostic and Statistical Manual of Mental Disorders: {DSM-IV-TR}},
    edition = {4th ed., text rev.},
    publisher = {Autor},
    author = {{American Psychiatric Association}},
    shortauthor = {APA},
    year = {2000},
    address={Washington, DC},
}

@book{APA2013,
    author = {{American Psychiatric Association}},
    shortauthor = {APA},
    address = {Washington, {DC}},
    edition = {5th ed.},
    title = {Diagnostic and statistical manual of mental disorders: {DSM-5}},
    publisher = {Autor},
    year = {2013},
}

When I first cite f. e.
\parencite{APA1994} I get the correct output:

(American Psychiatric Association [APA], 1994)

When I cite that a second time, I get (which is also correct):

(APA, 1994)

However, when I cite another publication with \parencite{APA2000} then after that, I get:

(American Psychiatric Association [APA], 2000)

But, as this publication has the same author as cited before, I want the shortauthor to be put there, like:

(APA, 2000)

How do I achieve that?

A:

For those interested:
A new version of biblatex-apa fixed this issue, thanks to PLK.


Q:

In VS2012 how to Browse With IE in private mode

I'm using Visual Studio 2012 and when building an ASP.NET MVC4 application I'm able to set the "Browse With" to an internet browser (Immulator/Simulator) of my choosing. For example: Google Chrome, Firefox, Internet Explorer, etc..
Instead of just using the default Internet Explorer I wanted to use Internet Explorer In-Private Mode.
I've tried:

and

It will work the first time but then every subsequent try after that results back to IE in normal mode.
I am able to accomplish this with Chrome in Incognito mode easily. But for some reason it's not working for IE.  I'm using IE10.
Is anyone else able to do this successfully?

A:

You actually have to use the 32-bit version of Internet Exploring for debugging in Visual Studio 2012.  So, if you add a browser with the following path:
"C:\Program Files (x86)\Internet Explorer\iexplore.exe"
and then use the -private argument, it will work correctly.
-Shaun


Q:

C# timer function won't allow for int values? Requests System.CompontentModel.IContainer?

I've created the delay function below with the intention of creating a delay within the certain bounds of my "min" and "max" inputs.
    private void delay(int min, int max)
    {
        Random rnd = new Random();
        int timerLength = rnd.Next(min, max);
        Timer timer = new Timer(timerLength);
        timer.Start();
    }

I get an error in the line
Timer timer = new Timer(timerLength);

As the compiler cannot convert timer Length from an int to a "System.ComponentModel.IContainer". I've tried to convert the input values to IContainers but with no success, as the random function only allows int values.
Is there a workaround to this at all, so that the timer function can take an int? Thanks.

A:

From msdn:

The Timer constructor enables you to associate a Timer with any
  Container object. By associating the Timer like this, you hand over
  control of the lifetime of the Timer to the Container. This can be
  useful if you use a number of components in your application and want
  to dispose of all of them simultaneously. For example, if you
  associate a ToolTip, an ImageList, and a Timer with a Container,
  calling Dispose on the Container will force disposal of all of these
  components as well.

So, if I understand you right, you are trying to set the interval for your Timer. In that case you need to use the 'Interval` property:
private void delay(int min, int max)
{
    Random rnd = new Random();
    int timerLength = rnd.Next(min, max);
    Timer timer = new Timer();
    timer.Interval = timerLength; // the value in milliseconds.
    timer.Start();
}


Q:

Look up the user with bearer token with Openiddict Core

I am currently using Openiddict, Identity and Entity Framework to manage my users and assign Bearer tokens to users to protect my API.
My infrastructure is currently using ASP.NET Core Web API in the back end and a separate React application in the front end.  The React application makes HTTP calls to my API to retrieve it's data.  There is no server side HTML rendering at all in the back end.
Everything works as I need it to for the most part.  I can register users and retrieve tokens from the API.  These tokens are included in my HTTP call in the Authorization header.  My AuthorizationController uses this: https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/AuthorizationController.cs with a few minor tweaks.  My Startup.cs also uses almost exactly this https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Startup.cs
In some instances, I need to make API calls to the endpoints that are specific to the user.  For instance, if I need to know if a user has voted on a comment or not.  Instead of passing along the users ID in a query string to get the user details, I would like to use the Bearer token I received that they use to make the API call for that endpoint.  I am not sure how to do this though.
In some research I have done it looks like some samples use ASP.NET Core MVC as opposed to the API to retrieve the user with the User variable as seen here https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/ResourceController.cs#L20-L31 however this seems not to apply to my infrastructure.
My question is how do I look up a user based on the Bearer token passed to the API to look up a users details from my database?  I am assuming that all of the tokens passed out by the API are assigned to that specific user, right?  If that's the case it should be easy to look them up based on the Bearer token.

A:

The question is: How with Openiddict can you look up a user based on the token that was assigned to them for API calls? I need to get the user details before anything else can be done with the application first. Is there something baked internally or do I have to write my own support for this?

When you create an AuthenticationTicket in your authorization controller (which is later used by OpenIddict to generate an access token), you have to add a sub claim that corresponds to the subject/entity represented by the access token.
Assuming you use the user identifier as the sub claim, you can easily extract it from your API endpoints using User.FindFirst(OpenIdConnectConstants.Claims.Subject)?.Value and use it to make your DB lookup.


Q:

How to add space between elements in nested arrays using .join method

I'm learning JavaScript and in Arrays part I've got some question when I use .join in array with nested array.
var arr = [1, 2, 3, [4, 5];

console.log(arr.join(', '));

// Output 1, 2, 3, 4,5

How can I get result that include space between 4 and 5?
Like: 1, 2, 3, 4, 5

A:

const myArray = [1, 2, 3, [4, 5]];
const mergedNestedArrays = [].concat.apply([], myArray)

console.log(mergedNestedArrays.join(', '));

First you need to merge/flatten your nested arrays then apply join() method. Hopefully that helps you.


Q:

my question was deleted

I asked a question about a film I am looking for and I logged in today to find that it has vanished.
what happened to it? why was i not notified that it was removed?
how can i recover my deleted question? i spent a lot of time writing it and investigating it, now that it's gone i feel like i've been robbed, how can i get it back?

A:

The policy on identification questions is, that they are eligible for deletion when they don't have any upvoted or accepted answers and remained inactive for 4 weeks, as described in the help center and this meta post. Since this policy has recently been updated as described in this meta discussion, there was a recent cleanup session where questions that are thus deletable were acted upon accordingly, yours was one of them.
You might feel like having been robbed and I see that you have put much detail into the question, but such are the rules of this site and they are necessary to tackle the long-term negative impact those inactive identification questions have on the site. If however, you have any new insights or updates to your question that may provide new possibilities for answering, you can add them in and it might get undeleted.

However, I wonder why you haven't been notified of the removal. I thought a deleted question would automatically trigger a user notification. If not, then I see why you were surprised. Thanks for bringing this to notice.

A:

I'm not entirely sure what the relationship between OnlineDevs.com and StackExchange is, but I do know that OnlineDevs.com reposts StackExchange questions (and answers).
So, using a bit of Google, I was able to locate your original question "Blue ant eater people that turn into flying whales either when they die or for some other reason" on the OnlineDevs.com site at this link.
The full text of your question is available there, along with the answer that had been given (no context in terms of users or anything though).


Q:

How to use a text file as standard input to test my program in XCode 4.33

I'm having trouble figuring out how to test my program using XCode.  I usually edit in the command line with vim, but am trying to transition to an IDE.  I'm sure there is an easy way to do the equivalent of homework.out < testfile.txt
Thanks!

A:

I haven't tested it, but putting "< testfile.txt" in the scheme's command line arguments may work. Apparently doing something similar worked for an earlier version of Xcode.


Q:

"I very like it" is right or wrong?

I heard a lot of non-native speakers said "I very like it".
I think "very" in this case is adverb and means "extremely" Source.
It can be written as "I extremely like it".
But I heard that people in some forums think it is wrong Forum
I personally prefer to say "I really like it".
SO, "I very like it" is right or wrong?

A:

In general we refer to adverbs as a single category, but it's really three different concepts together: adjective-modifiers, verb-modifiers, and adverb-modifiers. Most adverbs can fill all three of these roles, so in English they're conflated into one group. But here you've stumbled onto one of the exceptions.
"Very", "extremely", and a few others can modify adjectives and other adverbs, but they cannot modify verbs directly. So you could say "I very much like this", or even use a different adjective-derived adverb as in "I certainly like this", but not *"I very like this" or *"I extremely like this".


Q:

A result was returned when none was expected. SpringBoot/Postgresql

I want to select only last row in my table and return this int in my variable.
This is my method in my Repository :
@Transactional
@Modifying
@Query(value="SELECT category_id FROM category ORDER BY category_id DESC LIMIT 1\r\n", nativeQuery = true)
int  selectLastRecord();

And when I call method with this code:
int categoryId = this.categoryRepository.selectLastRecord();

I have the error:
org.postgresql.util.PSQLException: A result was returned when none was expected.

A:

Queries that require a @Modifying annotation include INSERT, UPDATE, DELETE, and DDL statements.
Adding @Modifying annotation indicates the query is not for a SELECT query.
So remove @Modifying.
Reference Modifying


Q:

C++ Diamond Console Output Issues

I am trying to get my for loops to output a diamond given user specific max and min, Even inputs are not allowed.  Any ideas would be appreciated.  Practice isn't going as smooth as I thought this would be.
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

int rows, count;

cout<<"What is the width of the diamond (3 to 21, odd values only): ";
cin>>rows;

//Error checking
if(rows < 1 || rows > 25)
    {
        cout<<"Invalid. please enter an odd number from 1 to 25: ";
        cin>>rows;
    }

//Ascending
for (count = 1; count < rows; count += 1)
    {
        for (int rows = 0; rows < count; rows ++)
        cout<<"*";
        cout<<endl;
    }

//Descending
for (count; count > 0; count -= 1)
    {
        for (int rows = 0; rows < count; rows ++)
        cout<<"*";
        cout<<endl;
    }

cin.get();
cin.get();

return 0;

}

A:

This performs the first half of the objective-:
for (int stars = 1; stars <= rows; stars+=2)
{
        int padding = rows - stars;
        for (int c = 0; c < padding/2; ++c)
           cout<<" ";
        for (int s = 0; s < stars; ++s)
           cout<<"*";
        cout<<endl;
}


Q:

C# Add a blank value in between string in of CSV file

I have this on a string that is generated from a list how can I add a blank value in between the string.
       using (var file = File.CreateText()
        {
            foreach (var permutation in result)
            {
                file.WriteLine(string.Join(",", permutation));
                //i++;

            }
        }

Here is the result:
string result = A,B,C,D,E,F,G,H,I,J
How can I add a blank value ", ," in the result at a specific index
Example: A,B,C,D,E,F, ,G,H,I,J
Note: result is a permutation and length is not consistent
Result is a IEnumerable can it be split?

A:

You can split your string with the comma as the separator, go through your characters and add them to a list. Add an extra empty string at your desired index and join the data back together. This way you don't have to deal with deciding if you need to add a commar or not when concatenating the strings.
var index = 6;

var data = "A,B,C,D,E,F,G,H,I,J";
var chars = data.Split(new [] { ',' });

List<string> resultData = new List<string>();

var i = 0;
foreach (var c in chars) {
    if (i == index) {
        resultData.Add(" ");
    }

    i++;

    resultData.Add(c);
}

var result = string.Join(",", resultData.ToArray();


Q:

Change UINavigationBar Background Color of UISearchController

At the minute, my search controllers "navigation bar" background is the standard default translucent however, all the other bars in my app are black translucent. When I print the navigationController property of the searchController, it returns nil and so does the navigationBar, but not the navigationItem. There are no other public properties that seem to let you change the color of the bar. I don't mind overriding private ivars as I wont be releasing this app on the app store.

A:

You can use the barTintColor property, in Swift this would be:
searchBar.barTintColor = UIColor.redColor()


Q:

basic issue: how do I include a category method in another class?

This is a super-basic question.  I want to use a class from Matt Gemmell's MGImageUtilities in my app.  I've added the classes UIImage+ProportionalFill.h and UIImage+ProportionalFill.m to my project.  They define the method imageScaledToFitSize.  But when I try to run the app, I get an unrecognized selector sent to instance error.  Obviously I have to make the method available to the class in which I want it to run, but I don't know how to do that.  I have #import UIImage+ProportionalFill.h in both the .h and .m files of the view controller, and in the .h file I've added
@interface UIImage (ProportionalFill)

- (void)imageScaledToFitSize;

@end

But I'm still getting the error.  I assume there's something very fundamental that I'm failing to do, but I don't know what it is.
Your thoughts?
UPDATE:  My project has the following classes:  UIImage+ProportionalFill, 'GHViewController, and 'GHAppDelegate.UIImage+ProportionalFill` contains the following declaration (and corresponding implementation):
- (UIImage *)imageScaledToFitSize:(CGSize)size;

In GHViewController.m, I have the following code:
    UIImage *img = [self createImage];
    UIImage *pic;
    if (self.serviceType==SLServiceTypeFacebook)
    {
        CGSize size = CGSizeMake((404*320)/([[UIScreen mainScreen] bounds].size.height - 64), 404);
        pic = [img imageScaledToFitSize:size];
    }

That's the only place I'm calling imageScaledToFitSize.

A:

If you have included the .m file, you should not get the unrecognized selector sent to instance error. So, I suspect that either the .m file was not correctly added to your target, or that you misspelled something when calling the method, or sent it to the wrong object (not an instance of UIImage).
If you provide more info about the way you are calling the method (i.e., on which object) and the exact console log output, I might be able to help you further.
To check if the .m file is actually assigned to your target, go to your project info pane in Xcode and show the build phases pane for the target; there you will find a list of all the modules included when building it.
As a general note:

including the .h file for your category will prevent the compiler from emitting a warning about an undefined method; not including the .h file will not prevent the method from being actually called, if the implementation is available;
if you do not include the .m file you get the exception with the unrecognized selector sent to instance.


Q:

Sidechain with Monero as the base token and Zerocoin as the anonymous token

The ZCash protocol has both basecoins which are traceable and Zerocoins which are anonymous. Basecoins can be converted into Zerocoins but the conversion itself is visible on the blockchain.
Could a Monero sidechain be built with Monero as the base token and Zerocoin as the anonymous token?
Would such a sidechain be more private than ZCash itself due to the anonymity that Monero will bring as the base new token?
Essentially I am asking if the ZCash protocol would be more private if the traceable basecoin was replaced with Monero.  Please differentiate your answer as either before or after the introduction of RingCT if it impacts the answer.

A:

Yes it's definitely possible, but why create a whole new coin for that? A better idea would be to create a Zerocoin sidechain (post RingCT) for Monero that allows people to move their Monero into the sidechain, mix it and send it to anyone else on the sidechain, and then pull it back out.
This would avoid the massive risk associated with ZCash's trusted setup because the sidechain would never have much value in it, and so the worst that can happen is an attacker can drain whatever is in the sidechain at the point that they find an exploit.

A:

Another option would be to add a zero-knowledge protocol option, with no side-chain at all.  This might be the least code-bucks for the most privacy-bang.


Q:

Determine if webpage has content using PowerShell

I have created a PHP page that does a basic select against a table to determine the last time data has been inserted by a particular agent. The purpose of the page is to see if any agent has not submitted data in the past 48 hours. Only agents who have not submitted data within that time period will show up on the list. As I don't expect there to be entries in this table 95% of the time, I need to set up an alert to only send if data exists on that PHP page.
I was trying a PowerShell script to scrape the page, and that is working well... I just need to figure out how to:
1) Scrape Page
2) If content exists -> send email
3) ELSE -> close.
I would schedule it through the standard Windows scheduled tasks. I know there are easier, or more straight forward, ways to do this, but I don't have the option to enable mail on the linux web server...
Below is my screen scrape tool:
$web = New-Object Net.WebClient
$web | Get-Member

$web.DownloadString("http://www.bing.com")

I got the code from: http://learn-powershell.net/2011/02/11/using-powershell-to-query-web-site-information/
Any ideas?

A:

1) Scrape Page
You're off to a good start. The DownloadString method will download the HTML.
2) If content exists -> send email
Depends on the content you are looking for. You can use the comparison operators -match or -like or string methods Contains() to test. Then put into an if/else block e.g.
$string = $web.DownloadString("http://somewebsite")
if ($string -match "regex_here") {
    Send-MailMessage -SmtpServer your_server -To to.address@domain -From from.address@domain -Subject foo -Body bar
} else {
    # not necessary unless there is something you want to execute here.
}

Notice I used the Send-MailMessage cmdlet to send the email.
3) ELSE -> close.
See above.


Q:

Indetifying a vector space

I'm trying to identify which sets are vector spaces. I know that a set $V$ is a vector space if its elements (vectors) have addition and scalar multiplication so that the result is also within the set $V$. I'm trying to identify the following sets.

Set of real $m\times n$ matrices $\mathbb{R}^{m\times n}$

If we do operations for two matrices it always yields and matrix within  $\mathbb{R}^{m\times n}$. So this is a vector space.

Line $\{(x,4x) \in \mathbb{R}^2 \: | \: x\in\mathbb{R}\}$

EDIT: Is a vector subspace of $\mathbb{R}^2$.

$\mathbb{R}^n = \{(x_1, \ldots, x_n) \ \vert \ x_i \in \mathbb{R}\}$

Clearly a vector space because for all $n$-vectors in it the operations hold.

Curve $\{(x,x^2) \in \mathbb{R}^2 \: | \: x\in\mathbb{R}\}$

Addition does not hold on this set $(1,1) + (2,4) = (3,5) \notin V$ so it is not a vector space.

Line $\{(x,3x-2) \in \mathbb{R}^2 \: | \: x\in\mathbb{R}\}$. Same as the other line and not an vector space.

EDIT: Under the vector space axioms addition $\mathbf a + \mathbf b \in V$ when $\mathbf a, \mathbf b \in V$ and $\lambda \mathbf a \in V$ thus if $\mathbf b = -1\cdot \mathbf a$ then $\mathbf a + \mathbf b = \mathbf 0 \notin V$. So additive indentity does not hold and the set is not a vector space.

Set of matrices in $\{ M\in\mathbb{R}^{n\times n}\: | \: \det(M)=1\}$.

\begin{align*} \text{det}\left(\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} + \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}\right) = 4 \neq 1\end{align*}
OR
\begin{align*} \text{det}\left(\lambda \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \right) = \lambda \neq 1 \text{ when } \lambda \neq 1\end{align*}
EDIT: So addition from said set yields a matrix with non 1 determinant. Not a vector space.

A:

Hints:

The deduction is correct, although you should actually check all the vector space axioms to conclude that it is one.
Your reasoning that $\tt 3.$ isn't a vector space isn't correct, $\mathbf{x}+\mathbf{y}=(3,12)$ has the form $(\alpha,4\alpha)$, so it is certainly in that set. $-$ Edit 1: That's correct, assuming that you already know that $\mathbf{R}^2$ is a vector space.
Same comment as in 1.
Your reasoning is correct.
Check instead whether that set contains an additive identity.
I assume that the field you're working over is $\mathbf{R}$. So take an element $c\in\mathbf{R}$, and suppose that $M$ is in that set, does it follow that $\det(cM)=1$? (i.e. does it follow that it is closed under scalar multiplication?) $-$ Edit 1: You showed that it isn't closed under addition, hence not a vector space, and that's correct.


Q:

Question about Automorphism group of $\mathbb{H}$

I already know/proved, that $Aut(\mathbb{H})$ consists of all Mobius-transformations $\Phi_M=M\tau$ where $M \in SL_2(\mathbb{R})$.
I know that they are bijective since $\Phi_M^{-1}=\Phi_{M^{-1}}$, i.e there exists an inverse function. However, I am not sure why these functions are holomorph because afaik there is a Pole of 1. order at $\tau=-d/c$.
EDIT: Since the first question was answered fairly quickly. I'd like to ask another one: How can we know that there is no other function in $Aut(\mathbb{H})$ other then the Mobius-transformations.?

A:

With $\tau \mapsto 1-\frac{1}{1/2-i\tau}$ you can send $H = \{Im(\tau) > 0\}$ to the unit disk $D$.
Then with Schwarz's lemma show the automorphisms of $D$ are the Möbius transformations $c\frac{z-a}{\bar{a}z-1}$ where $|c|=1$ and $|a| < 1$ :

Let $\phi(z)$ being an arbitrary automorphism of $D$.
  Choosing the  Möbius automorphism of $D$ : $f(z) =  \frac{z-\phi(0)}{\bar{\phi(0)}z-1}$ we have $g(z) = f \circ \phi (z)$  an automorphism of $D$ satisfying $g(0) = 0$.
Hence by Schwarz lemma, $g(z) = c z = f \circ \phi (z)$ for some $|c| =1$, i.e. $ \phi(z) = f^{-1}(cz)$ was a Möbius automorphism of $D$.

Finally, let $W(\tau) = 1-\frac{1}{1/2-i\tau}, T(z) = W^{-1}(z) = \frac{i}{1-z}-i/2$,
you get that if $\varphi(z)$ is an automorphism of $H$ then $\phi(z) = W \circ \varphi \circ T(z)$ is a Möbius automorphism of $D$ so that $\varphi(z)$ was indeed a Möbius automorphism of $H$.


Q:

Do we need a canonical question on infected Android and iOS?

We have a canonical question on how to handle a PC and one for servers.
Recent activity highlights that we also get questions about "possibly infected" Android and iOS. (More Android than iOS?). They tend to get closed pretty quickly, and hence deleted, so there is not many to find via search.
This presents us with an opportunity to create a "Help! I think my Android/iOS is infected! What do I do?" canonical question.
Should we provide a dupe target for these questions so that we can provide some kind of help? Can such a question be constrained enough to provide concise instructions that would be applicable across a wide range of issues?
Do we need one for iOS and another for Android, or can they be combined?

A:

Yes, we should have a duplicate.
Closing as a duplicate of a canonical question is far the best user experience for the person asking the question, and for people finding it via google later. Just having the question closed, or marked as a duplicate of some specific question describing different circumstances doesn't quite do it.
But it's not easy to ask the right question. One problem is that what people belive is caused by a virus often isn't. A lot of these questions are about situations where it's unclear if it's a virus or not. If we close "I got a error message on a website, do I have a virus?" as a duplicate of "do a full factory reset" we are not helping anyone...
In the PC question I specifically excluded this from the question by just stating that there was a virus. I don't know if that was a good idea for that question, and I don't know if it's a good idea for this one. Just wanted to highlight the issue.
Just brainstorming questions here...

Do I have a virus on my phone? To broad! There's no way to give a general answer.
I have a virus, what do I do? Good in theory, but in practice this is not what people are asking.
How do I do a factory restet? To hands on to be on topic.


Q:

Old router problem Can't enter setup

I have an old router. When I try going into settings by going to 192.168.1.1 .Then I enter my user-name and password and click on OK and it asks for credentials again and then again and nothing else opens. It just keeps on asking for my user name and password.

A:

There should be a pinhole reset button on the router.  Use a paperclip and hold it in with the power on for about 15-20 seconds.  Afterwards look up the router's manual online to find the default username and password.


Q:

How to make sidebar menu in iOS application?

I want to create side bar menu in iOS application like android using xib not by storyboard?
please help me on above.
Thanks

A:

You can do a slide menu by using MFSideMenu
 from git hub.
There are provide you a simple demo application also. Try to use this


Q:

pandas: how do I select first row in each GROUP BY group?

Basically the same as Select first row in each GROUP BY group? only in pandas.
df = pd.DataFrame({'A' : ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
                'B' : ['3', '1', '2', '4','2', '4', '1', '3'],
                    })

Sorting looks promising:
df.sort('B')

     A  B
1  foo  1
6  bar  1
2  foo  2
4  bar  2
0  foo  3
7  bar  3
3  foo  4
5  bar  4

But then first won't give the desired result...
    df.groupby('A').first()
     B
A
bar  2
foo  3

A:

Generally if you want your data sorted in a groupby but it's not one of the columns which are going to be grouped on then it's better to sort the df prior to performing groupby:
In [5]:
df.sort_values('B').groupby('A').first()

Out[5]:
     B
A
bar  1
foo  1

A:

The pandas groupby function could be used for what you want, but it's really meant for aggregation. This is a simple 'take the first' operation.
What you actually want is the pandas drop_duplicates function, which by default will return the first row. What you usually would consider the groupby key, you should pass as the subset= variable
df.drop_duplicates(subset='A')

Should do what you want.
Also, df.sort('A') does not sort the DataFrame df, it returns a copy which is sorted. If you want to sort it, you have to add the inplace=True parameter.
df.sort('A', inplace=True)

A:

Here's an alternative approach using groupby().rank():
df[ df.groupby('A')['B'].rank() == 1 ]

     A  B
1  foo  1
6  bar  1

This gives you the same answer as @EdChum's for the OP's sample dataframe, but could give a different answer if you have any ties during the sort, for example, with data like this:
df = pd.DataFrame({'A': ['foo', 'foo', 'bar', 'bar'],
                   'B': ['2', '1', '1', '1'] })

In this case you have some options using the optional method argument, depending on how you wish to handle sorting ties:
df[ df.groupby('A')['B'].rank(method='average') == 1 ]   # the default
df[ df.groupby('A')['B'].rank(method='min')     == 1 ]
df[ df.groupby('A')['B'].rank(method='first')   == 1 ]   # doesn't work, not sure why


Q:

Angular - Dynamically loading an image

I've searched all over StackOverflow but I haven't been able to find a solution to my problem.

F.Y.I I'm using ASP.net Core 2.0's default angular project
I'm currently building an Angular application where I'm trying to load in a customer's logo based on a config found elsewhere.
I'm trying to load this file into my home.component.html
I created a "CustomerService" which has a function getLogo() which in itself returns the customer's logo's path.
My folder structure is as follows:
FOLDER STRUCTURE IMAGE
The assets folder holds the images, and the HTML found below is found in home.component.html
I know that "../../" isn't the way to go, so my first question is how I'd be able to fix that.
I've created the following HTML structure:

And the CustomerService's getLogo function returns the following:
getLogo() {
    return "../../assets/timeblockr-logo.png";
}

** EDIT: FOUND THE SOLUTION!!! **
Turns out I had to use:
getLogo(): string{
    return require("../assets/timeblockr-logo.png");
}

Special thanks to @Niladri for the solution to this issue!

A:

Your image source should be without ../../. The image paths are relative in the output folder. Just change to this:

And your function should be:
getLogo(): string {
    return "assets/timeblockr-logo.png";
}

As per your comments, you need to change your "assets" entry in .angular-cli.json to this:
"assets": [
    "assets",
    "favicon.ico",
    {
        "glob": "**/*",
        "input": "./assets/images/",
        "output": "./assets/images/",
        "allowOutsideOutDir": false
    }
],

A:

Webpack uses url-loader to load images from your angular project that comes with extension .png,.jpg etc . Take a look at the below code from the url-loader repo in github https://github.com/webpack-contrib/url-loader
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  }
}

it looks for image files with the above extensions. But we need to use require statement to the actual image path for the Webpack to understand the path of the image so that it can pick them up. This is required in .ts / typescript files while using the path of the image as a variable or returning the path value from a method . The first image tag
 was working because Webpack uses html-loader for .html files, which automatically replaces src attribute values on image tags with the bundled image URL.
So your getLogo() method should be like below
getLogo():string {
    return require("../assets/timeblockr-logo.png");
}


Q:

How can i show that $\det(A)=\det(A^\intercal)$?

For all $n$-dimension matrix, how can i show that $\det(A)=\det(A^\intercal)$ by using induction? ($A^\intercal$ is a transpose of $A$)

A:

If $A$ is not invertible, then $A^T$ is also not invertible. So if $det(A) = 0$ then $det(A^T) = 0$ and vice versa. If $A$ is invertible, then $A = E_1\cdot E_2\cdot...E_n$ and $A^T = E_n^T\cdot E_{n-1}^T\cdot ...E_1^T$ with each $E_i$ is an elementary matrix which is obtained by a single row operation on $I_n$, and there are $3$ of types of them. For each of the $3$ types we can verify that $det(E_i) = det(E_i^T)$. So $det(A) = det(E_1)\cdot \det(E_2)\cdot...det(E_n) = det(E_n^T)\cdot det(E_{n-1}^T)\cdot...det(E_1^T) = det(E_n^T\cdot E_{n-1}^T\cdot...E_1^T) = det(A^T)$.


Q:

Format Date and Time in XSLT

I have the column which returns the date and time in the default format.
<xsl:value-of select="/CAudioFile/CRI/LocalStartTime"/>

Which returns

2014-05-08T08:01:26.4000000-0700

I want to put this time in this format:

05/08/2014 08:01:26

I have tried to get the format with the different combination of substring:
<xsl:value-of select="substring(/CAudioFile/CRI/LocalStartTime,1,10)"/>

But it's either returning me just the date or just the time.
Any suggestions?
Thank you.

A:

You need to work a bit harder at it:
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 6, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 9, 2)"/>
<xsl:text>/</xsl:text>
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 1, 4)"/>
<xsl:text> </xsl:text>
<xsl:value-of select="substring(CAudioFile/CRI/LocalStartTime, 12, 8)"/>


Q:

SQL Setting Week Numbers For Months From Monday to Sunday

I am trying to set the week number for months in a table. The logic is the first week starts on the first day of the month until the first Sunday and the rest of the weeks start on every Monday following that. I am having trouble implementing this though. Any Ideas? My code looks something like this.
I had previously received help here to set the week numbers for the entire years in a similar way. It looks like the following:
UPDATE [DimTime]
SET [WeekNumberOfYear] = DATEPART(WEEK,[Date]) - CASE WHEN DATEPART(WEEKDAY,[Date])     in (1) THEN 1 ELSE 0 END

A:

This should give you a correct result:
UPDATE [HMDBDataMartBOS].[dbo].[Dimension.DimTime]
SET [NaturalWeekNumberOfYear] = datediff(d, datediff(d, 0,
dateadd(m, datediff(m, 0, [Date]), 0))/7*7 - 7,[Date])/7


Q:

Click Function in JQuery

$("#displayPanel #save #saveForm").live("click", function(){
                   //Move to forms/homepage
    });

What I'm trying is when clicking on the saveForm Button I want to move to a URL(homepage) Where ii had some list of saved forms.
I'm new to JQuery.
Note:
       Where my saveForm is like
       <input id='saveForm' type='Submit' value='Save Form'>

A:

You shouldn't use document.location. It has been replaced by window.location.
From the Mozilla docs:

document.location was originally a
  read-only property, although Gecko
  browsers allow you to assign to it as
  well. For cross-browser safety, use
  window.location instead.

The only cross-browser way to navigate to a new URL from javascript is:
window.location = "http://mysite.com/url";

A:

You mean redirect to page?
document.location = 'http://yourpage';


Q:

How can I simplify this function - return key value from array?

I have written the following function which returns the value of a key which is the account prefix of a cPanel account.
[prefix] = 'oneclick_'
The function works but I'm only a beginner and I'm sure there's an easier and better way to write this function.
<?php
// Get data from cPanel API
$array = $cp_db_restrictions['cpanelresult']['result']['data'];

//Pass array of $data to function
db_prefix( $array );

//Function accepts array of $data
function db_prefix( $array ) {
  if( count( $array ) > 0 ) {
      return $array['prefix'];
  } else {
      return "No prefix";
  }
}
?>

<?php echo db_prefix($array); ?>

The function echos "oneclick_"
EDIT:
This is the code which returns the array:
$cp_db_restrictions = $cpanel->uapi(
      'Mysql', 'get_restrictions'
  );

However, I'm not quite sure how to add that into the function. When I try I get the following error message:
Notice: Undefined variable: array in ...
Fatal error: Uncaught Error: Call to a member function uapi() on null in...
SOLUTION*
So, thanks to Nick's answer here is the solution. You must make sure to declare the cPanel class at the top of the document and within the same PHP tags.
<?php
include("/usr/local/cpanel/php/cpanel.php"); // Instantiate the CPANEL object.
$cpanel = new CPANEL();

function db_prefix($cpanel) {
      $cp_db_restrictions = $cpanel->uapi('Mysql', 'get_restrictions');
      $array = $cp_db_restrictions['cpanelresult']['result']['data'];
      return $array['prefix'] ?? 'No prefix';
} ?>
<?php echo db_prefix($cpanel); ?>

A:

In PHP7 you can just use the null coalescing operator ??:
echo $array['prefix'] ?? 'No prefix';


Q:

Wörter mit selber Bedeutung, aber unterschiedlichen Artikeln

Mir ist heute beim Spazierengehen aufgefallen, dass die Wörter

die Geldbörse, das Portemonnaie und der Geldbeutel

die gleiche Bedeutung, aber unterschiedliche Artikel haben – was ich irgendwie erstaunlich finde.
Gibt es einen Fachbegriff dafür, bzw. kennt ihr weitere solche Wörter?

A:

Das grammatische Geschlecht hat absolut nichts mit dem Bezeichneten zu tun. Nichts. Bei neuen Wörtern spielt teils gleiche Lautung (der Blog), teils der Originalartikel (der Latte) und teils tatsächlich ein deutsches Synonym (die Latte) eine Rolle.
Im Großen und Ganzen aber ist das nicht der Fall und das Geschlecht hängt von Wortbildung und Etymologie ab. Daher gibt es auch unzählige Beispiele.

Das Auto, der Wagen, die Karre
der Blick, die Sicht, das Panorama
die Frau, das Weib
…


Q:

Find the general solution of the simple harmonic oscillator

Question: Find the general solution of the simple harmonic oscillator equation,
$$\ddot{x}=-\omega^2x$$
My answer: $x(t)=A\cos(\omega t)+B\sin(\omega t)$
Solution given: $x(t)=x_0\cos(\omega t)+\frac{\dot{x_0}}{\omega}\sin(\omega t)$
I can understand inputting $x_0$ for $A$, but can't understand inputting $\frac{\dot{x_0}}{\omega}$ for $B$. Where does the input for $B$ come from?

A:

The input of $B$ is given by the initial value of the velocity. Since your ODE is of second order, you need to give conditions on the velocity, too. Hence, The condition $$\dot{x}(0)=\dot{x_0}$$ leads to $B=\frac{\dot{x_0}}{\omega}$.


Q:

json string fiddling

I have a python dictionary of JSON serialized values.
I want to add to these serialized strings without first doing loads(...), then later doing dumps(...) - so I 'fiddle' with the serialized values:
currently I have:
for key, value in my_dict.items():
    # creating JSON of additional data I want in the JSON string
    extra = dumps({ 'key1': 3, 'key2': 1 }, default=str)

    # cutting the last '}' from the end off 'value', the '{' and '}' from the
    # start and end of 'extra', and then concatting them together.
    my_dict[key] = '%s,%s' % (value[:-1], extra[1:])

I am doing this because I consider the dumps and loads a waste, but my current method is not very pythonic.
Is there a better method?
Note: the 'extra' values are from a different source to the initial JSON values, and cannot be inserted at the point where the original data was serialized.
time differences when using a dict of ~20 JSON blobs:

fiddling:     0.0005 seconds
json>py>json: 0.0025 seconds

5 times quicker
and for fun with 20,000:

fiddling':    0.333
json>py>json: 0.813

over 60% quicker
with 200,000:

fiddling':    4.5
json>py>json: 10.25

over 60% quicker

A:

The Pythonic way would be to parse the JSON string, modify the values then serialize it. JSON is very quick to parse, much faster than the standard pickle/unpickle functions, and will probably not slow you down unless you have enormous amounts of data (tens of thousands of lines). Don't fall into the trap of optimizing prematurely.
In any case, you should always write your application in a nice, Pythonic and readable fashion, then (if necessary!) optimize the slow parts of your code later.

Another method of optimization could be to write the relevant code in C, or use a C library for JSON serialization. Take a look at ultrajson or take a look at this answer, which explains how the standard library simplejson can be much faster than the json module you are using.


Q:

File Name Bubble Hovering on Screen?

I'm not sure what just happened...
I was just about to rename a file, and just mis-clicked off. - After that point there was a constantly floating yellow bubble with the file name in it, on the finder window. I couldn't click it or drag it, however if I showed desktop it would float off screen along with the finder window.
I force closed Finder, and it was gone when I re-opened. Just very intrigued as to what this was? As it didn't seem like a bug (As it tended to float and act in unison with the finder window).
Any ideas?
iMac
OS X 10.8.2

A:

Well I've managed to replicate it myself, seems like a bug.
If you start to edit a filename, right click, click "look up "File name here"", then quickly click off, the yellow look up box will stay floating on the screen.
Screenshot here:


Q:

When I tap the refresh button the images never appear

I have been trying too hard to get around this problom, when I tap the refresh button in my app, the images doesn't load on the screen.
This the DataFragment file, when i build this app there are no errors.
package com.example.popularmovis;

    import android.app.Fragment;
    import android.content.SharedPreferences;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.GridView;
    import android.os.AsyncTask;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.jar.JarException;

    /**
     * A placeholder fragment containing a simple view.
     */
    public class DataFragment extends Fragment {

        public ImageAdapter display;

        public DataFragment() {
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Add this line in order for this fragment to handle menu events.
            setHasOptionsMenu(true);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.datafragment_menu, menu);
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_refresh) {
                FetchMovieData movieData = new FetchMovieData();
                movieData.execute();

                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            display = new ImageAdapter(rootView.getContext());
            GridView gridView = (GridView) rootView.findViewById(R.id.gridView_movies);
            gridView.setAdapter(display); // uses the view to get the context instead of getActivity().
            return rootView;

        }

        public class FetchMovieData extends AsyncTask<Void, Void, String[]>{
            private final String LOG_TAG = FetchMovieData.class.getSimpleName();

            private String[] extractdisplayFromJason(String jasnData)
                                                throws JSONException{
                //These jason display need to be extracted
                final String movie_results = "results";
                final String movie_poster = "poster_path";

                JSONObject movieData = new JSONObject(jasnData);
                JSONArray movieArray = movieData.getJSONArray(movie_results);
                String[] posterAddreess = new String[movieArray.length()];

                //Fill ther posterAddreess with the URL to display
                for(int j=0; j < movieArray.length(); j++){

                    String posterPath;
                    JSONObject movieArrayItem = movieArray.getJSONObject(j);
                    posterPath = movieArrayItem.getString(movie_poster);
                    posterAddreess[j] = "http://image.tmdb.org/t/p/w185/" + posterPath;
                }
                for (String s : posterAddreess) {
                    Log.v(LOG_TAG, "Thumbnail Links: " + s);
                }
                return posterAddreess;
            }

            @Override
            protected String[] doInBackground(Void... params) {

                HttpURLConnection urlConnection = null;
                BufferedReader reader = null;
                String JsonData = null;

                String country = "US";
                String rating = "R";
                String sort = "popularity.desc";
                String apiKey = "";
                //building the URL for the movie DB

                try {
                    //building the URL for the movie DB
                    final String MovieDatabaseUrl = "https://api.themoviedb.org/3/discover/movie?";
                    final String Country_for_release = "certification_country";
                    final String Rating = "certification";
                    final String Sorting_Order = "sort_by";
                    final String Api_Id = "api_key";

                    Uri buildUri = Uri.parse(MovieDatabaseUrl).buildUpon()
                            .appendQueryParameter(Country_for_release, country)
                            .appendQueryParameter(Rating, rating)
                            .appendQueryParameter(Sorting_Order, sort)
                            .appendQueryParameter(Api_Id, apiKey)
                            .build();

                    //Converting URI to URL
                    URL url = new URL(buildUri.toString());
                    Log.v(LOG_TAG, "Built URI = "+ buildUri.toString());

                    //Create the request to the Movie Database
                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.connect();

                    //Read the input from the database into string
                    InputStream inputStream = urlConnection.getInputStream();

                    //StringBuffer for string Manipulation
                    StringBuffer buffer = new StringBuffer();

                    if (inputStream == null) {
                        // Nothing to do.
                        return null;
                    }
                    reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                        // But it does make debugging a *lot* easier if you print out the completed
                        // buffer for debugging.
                        buffer.append(line + "\n");
                    }
                    if (buffer.length() == 0) {
                        // Stream was empty.  No point in parsing.
                        return null;
                    }
                    JsonData = buffer.toString();
                    Log.v(LOG_TAG,"Forecaast Jason String" + JsonData );
                } catch (IOException e) {
                    // If the code didn't successfully get the weather data, there's no point in attemping
                    // to parse it.
                    return null;
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (final IOException e) {
                            Log.e(LOG_TAG, "Error closing stream", e);
                        }
                    }
                    try {
                        return extractdisplayFromJason(JsonData);
                    } catch (JSONException e) {
                        Log.e(LOG_TAG, e.getMessage(), e);
                        e.printStackTrace();
                    }
                }
                return null;
            }
            protected void onPostExecute(String[] posterAddreess) {

                    for (String poster : posterAddreess) {
                        display.addItem(poster);
                    }

            }
        }
    }

This the ImageAdapter code
package com.example.popularmovis;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.example.popularmovis.R;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public ArrayList<String> images = new ArrayList<String>();
    public ImageAdapter(Context c){
        mContext = c;
    }

    @Override
    public int getCount(){
        return images.size();
    }

    @Override
    public Object getItem(int position){
        return images.get(position);
    }

    public long getItemId(int position){
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        ImageView imageview;
        if (convertView == null){
            imageview = new ImageView(mContext);
            imageview.setPadding(0, 0, 0, 0);
            //imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageview.setAdjustViewBounds(true);
        } else {
            imageview = (ImageView) convertView;
        }

        Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
        return imageview;
    }

    /*
    Custom methods
     */
    public void addItem(String url){
        images.add(url);
    }

    public void clearItems() {
        images.clear();
    }
}

A:

When you use this in your onCreate method like this, it means that the object is local to the method and can't be use in other methods.
ImageAdapter display = new ImageAdapter(rootView.getContext());

First create a global class member variable
private ImageAdapter display;

then inside your onCreate method do this
display = new ImageAdapter(rootView.getContext());


Q:

What's the equivalent to "typo" in handwritten texts?

"Typos" are acknowledged as "technical" errors, ones that obviously aren't caused by the writer's poor spelling. Although less frequent than in typing, they can also occur in handwritten texts, as a result of absent-mindedness or just an accidental stroke of the pen.   Since the text wasn't actually typed, it sounds funny to call them "typos". Is there a more fitting word, one that reflects the "accidental" nature of the error?

A:

I use the phrase slip of the pen.  From Wiktionary:

(idiomatic) A mistake in handwriting.

Formally, there's always lapsus calami.  From Oxford Dictionaries:

formal A slip of the pen.

Informally, you could get away with Janus Bahs Jacquet's suggestions or the like, apparently patterned after typo:

I tend to call them writos or pennos, but I doubt either is particularly well-established. (emphasis added)

Or the less specific terms mistake, error, etc.  There are a lot of ways you can describe this sort of error, I think.

A:

Lapsus is a common formalism for inadvertent error, and you could use lapsus calami specifically for writing, though it is far less common than lapsus linguae for speaking. (Wikipedia suggests lapsus clavis for keyboard errors, but that may be a step too far).
Or you could just use the English 'slip of the pen/tongue/fingers'.


Q:

Retrieve folders and sub folders from document library by REST call

I need to get a list of folders and sub folders from document library. I feel that approaching this problem using REST call would be easier than the traditional CSOM query. Please suggest a relevant approach and solution.

A:

You could utilize GetItems method and specify the following query:
<View Scope="RecursiveAll">
     <Query>
         <Where>
            <Eq>
               <FieldRef Name="FSObjType" /><Value Type="Integer">1</Value>
            </Eq>
         </Where>
     </Query>
</View>

to return all folder items in a library.
Example
function getListItems(webUrl,listTitle, viewXml)
{
    var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
    var queryPayload = {
               'query' : {
                      '__metadata': { 'type': 'SP.CamlQuery' },
                      'ViewXml' : viewXml
               }
    };

    return $.ajax({
           url: url,
           method: "POST",
           contentType: "application/json;odata=verbose",
           data: JSON.stringify(queryPayload),
           headers: {
              "X-RequestDigest": $("#__REQUESTDIGEST").val(),
              "Accept": "application/json; odata=verbose"
           }
     });
}

function getAllFolderItems(webUrl,listTitle)
{
    var viewXml = '<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="FSObjType" /><Value Type="Integer">1</Value></Eq></Where></Query></View>';
    return getListItems(webUrl,listTitle,viewXml);
}

Usage
//print folder names from Documents library
getAllFolderItems(_spPageContextInfo.webAbsoluteUrl,'Documents')
.done(function(data)
{
     var items = data.d.results;
     for(var i = 0; i < items.length;i++) {
         console.log(items[i].Title);
     }
})
.fail(
function(error){
    console.log(JSON.stringify(error));
});

A:

Recently I answered a very similar question here. If you need all of the folders and subfolders (but no documents) recursively from a document library, that is what you should use (send it via POST to the server due to GetItems method call):
/_api/web/Lists/GetByTitle('Title of your doc. lib.')/GetItems(query=@v1)?$expand=Folder&$select=Title,Folder/ServerRelativeUrl&@v1={"ViewXml":"<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq></Where></Query></View>"}

Alternatively, you could use the following REST query as well (via HTTP GET):
/_api/web/Lists/GetByTitle('Title of your doc. lib.')/Items?$expand=Folder&$select=Title,Folder/ServerRelativeUrl

It will return all of the items (documents and folders) in you library, you should filter them on the client side based on the FileSystemObjectType property, as you can't use this one in the $filter expression in REST (see details here).
Last, but not least, you can use the SharePoint 2010 compatible REST Interface as shown in option 3:
/_vti_bin/listdata.svc/YourDocLib?$filter=ContentType eq 'Folder'

Note, that the syntax is language-specific in this case. The query above is OK for English, but for German it would be:
/_vti_bin/listdata.svc/YourDocLib?$filter=Inhaltstyp eq 'Ordner'