How could just loading a dll lead to 100 CPU load in my main application?

Question: I have a perfectly working program which connects to a video camera (an IDS uEye camera) and continuously grabs frames from it and displays them.
However, when loading a specific dll before connecting to the camera, the program runs with 100% CPU load. If I load the dll after connecting to the camera, the program runs fine.
int main()
{
    INT nRet = IS_NO_SUCCESS;
    // init camera (open next available camera)
    m_hCam = (HIDS)0;

    // (A) Uncomment this for 100% CPU load:
    // HMODULE handle = LoadLibrary(L"myInnocentDll.dll");

    // This is the call to the 3rdparty camera vendor's library:
    nRet = is_InitCamera(&m_hCam, 0);

    // (B) Uncomment this instead of (A) and the CPU load won't change
    // HMODULE handle = LoadLibrary(L"myInnocentDll.dll");

    if (nRet == IS_SUCCESS)
    {
        /*
         * Please note: I have removed all lines which are not necessary for the exploit.
         * Therefore this is NOT a full example of how to properly initialize an IDS camera!
         */
        is_GetSensorInfo(m_hCam, &m_sInfo);

        GetMaxImageSize(m_hCam, &m_s32ImageWidth, &m_s32ImageHeight);

        m_nColorMode = IS_CM_BGR8_PACKED;// IS_CM_BGRA8_PACKED;
        m_nBitsPerPixel = 24; // 32;
        nRet |= is_SetColorMode(m_hCam, m_nColorMode);

        // allocate image memory.
        if (is_AllocImageMem(m_hCam, m_s32ImageWidth, m_s32ImageHeight, m_nBitsPerPixel, &m_pcImageMemory, &m_lMemoryId) != IS_SUCCESS)
        {
            return 1;
        }
        else
        {
            is_SetImageMem(m_hCam, m_pcImageMemory, m_lMemoryId);
        }
    }
    else
    {
        return 1;
    }

    std::thread([&]() {
        while (true) {
            is_FreezeVideo(m_hCam, IS_WAIT);
            /*
             * Usually, the image memory would now be grabbed via is_GetImageMem().
             * but as it is not needed for the exploit, I removed it as well
             */
        }
        }).detach();

    cv::waitKey(0);
}

Independently of the actually used camera driver, in what way could loading a dll change the performance of it, occupying 100% of all available CPU cores? When using the Visual Studio Diagnostic Tools, the excess CPU time is attributed to "[External Call] SwitchToThread" and not to the myInnocentDll.
Loading just the dll without the camera initialization does not result in 100% CPU load.
I was first thinking of some static initializers in the myInnocentDll.dll configuring some threading behavior, but I did not find anything pointing in this direction. For which aspects should I look for in the code of myInnocentDll.dll?
Comment: The 100% cpu being used by `SwitchToThread` is most likely coming from a spinlock. Are you doing anything in your `DllMain` for thread/process attach events? [Here are some things that will cause problems](https://devblogs.microsoft.com/oldnewthing/20140821-00/?p=183). Static initializations could also invoke the same. If nothing, I'd bite the bullet and just break into the process when it's in `SwitchToThread` and step out to find what's doing it. You'll have to debug in assembly but it's not terribly difficult to get a picture of what's going on.
Comment: @TainToTain Thanks for taking a look! DllMain is not present in my code. It could be some static initializations indeed, however I am clueless on how to find the needle here. Unfortunately, in Release Mode, attaching to the stack just reveals "External code". And in debug mode, the problem does not appear
Comment: `myInnocentDll.dll` will have a `DllMain`. What code is in that function?
Comment: Some other things to check in `myInnocentDll`: are you using COM?; do any of the ctors of statically initialized objects call into STL or CRT methods? Basically anything that might load another library in a static initializer is bad and can cause a deadlock. I suspect there will be. For Visual Studio assembly-level debugging, you need to [enable "address-level debugging"](https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-use-the-disassembly-window?view=vs-2019#:~:text=To%20enable%20the%20Disassembly%20window,select%20Enable%20address%2Dlevel%20debugging.)
Comment: Can you use Process Explorer and inspect the thread stacks and what they do with the CPU time? https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer
Comment: Attempted threading in any static initializer in `myInnocentDll.dll` is just as likely. Another likely option is to check the vendor libraries behavior with Intel Inspector for race conditions. Last, use Dependency Walker to check which symbols and other libraries your, and the vendors library each pull in, you may encounter a conflict there!
Comment: At least in the code files there is no DllMain to be found, maybe it is generated by cmake or the msvc automatically? Unfortunately, the myInnocentDll is rather large but I will look out for COM and threading during static init. Thanks for all the hints and debugging tips!
Answer: After a lot of digging I found the answer and it is both frustratingly simple and frustrating by itself:
It is Microsoft's poor support of OpenMP. When I disabled OpenMP in my project, the camera driver runs just fine.
The reason seems to be that the Microsoft compiler uses OpenMP with busy waiting and there is also the possibility to manually configure OMP_WAIT_POLICY, but as I was not depending on OpenMP anyways, disabling was the easiest solution for me.

https://developercommunity.visualstudio.com/content/problem/589564/how-to-control-omp-wait-policy-for-openmp.html

https://support.microsoft.com/en-us/help/2689322/redistributable-package-fix-high-cpu-usage-when-you-run-a-visual-c-201

I still don't understand why the CPU only went up high when using the camera and not when running the rest of my solution, even though the camera library is pre-built and my disabling/enabling of OpenMP compilation cannot have any effect on it. And I also don't understand why they bothered to make a hotfix for VS2010 but have no real fix as of VS2019, which I am using. But the problem is averted.
Answer: You can disable CPU idle state in the IDS camera manager and then the minimum CPU load in the windows energy plans is set to 100%
I think this is worth mentioning here, even you solved your problem already.


Set and validate return value in IF in PHP

Question: Could I do this in PHP?
if ($Var = $this->test1() == true) {
    var_dump($Var);
}

public function test1() {
    return true;
}

It echoes true, but I'm not sure if this is the correct way to check such return values.
Answer: Yes you can, but write:
if (($var = $this->test1()) === true) {
    var_dump($var);
}

To be safe and to alert the reader there is something going on.
I wouldn't advise you to do this though, but in some cases this is acceptable; such as a complex if-else tree where lazy execution is desirable.
if (($result = slow_process()) !== false) {
    return $result;
} else if (($result = slow_process1()) !== false) {
    return $result;
} else if (($result = slow_process2()) !== false) {
    return $result;
} else if (($result = slow_process3()) !== false) {
    return $result;
}

This is overly simplified, but these situations do occur.
Comment: My function with either return a string or boolean false, would `!== false` be the best way to go?
Comment: I don't know if it's the best way, but I wouldn't object to it.
Answer: You can but there is 2 things you should be aware of :
When you do something like :
if ($Var = $this->test1() == true) {

The operators are confusing :

do you want to do $this->test1() == true and store result $var
do you want to do $var = $this->test1() and compare it with true

In your case, $this->test1() returns true so it does not matter. But if we change your code a bit :
if ($Var = $this->test1() == 5) {
    var_dump($Var);
}

public function test1() {
    return 3;
}

Someone who read your code will not understand if you want to store $this->test1() in $Var (so, make 3 in var) or if you want to put result of comparison $this->test1 == 5 in $Var (false).
What remains in $Var at the end may be a very good question at the PHP 5.3 Certification but not in a useful case.
To avoid mistakes, uses parenthesis :
if (($var = $this->test1()) == true) {

You should take care of types :
I give you an example of what could return something castable to true :
function test1() { return true; }
function test2() { return 3; }
function test3() { return 3.42; }
function test4() { return "x"; }
function test5() { return array('x'); } // array() == true returns false
function test6() { return new stdClass(); }

echo test1() == true;
echo test2() == true;
echo test3() == true;
echo test4() == true;
echo test5() == true;
echo test6() == true;

// outputs 111111 (1 = true)

To avoid mistakes, you should use === operator. Your final piece of code becomes :
if (($var = $this->test1()) === true) {

Answer: The == true part is unnecessary.  What you have is valid syntax, but some find it confusing.  You can always do:
$Var = $this->test1();
if ($Var) { ...

Just decide on the standard with your development team.
Comment: I'd like to do it in one line, because I'm building quite a "complex" if-else code.
Answer: You can also do:
if ($Var = $this->test1()) {
    var_dump($Var);
}

public function test1() {
    return true;
}


Estilização de Grid para galeria usando display flex

Question: Bom, estou tentando criar uma galeria,no modelo logo abaixo, porém, preciso utilizar o display:flex, como posso realizar isso?

Pensei em usar o float, mas lembrei que o display flex ignora qualquer float :/
Comment: Eu sei que não é bem uma resposta, mas da uma olhada nisso http://bulma.io/documentation/layout/tiles/
Comment: Por que teria que usar o `display: flex`?
Comment: @Dvdsamm, para aprender a realizar isso com o display flex, visto que já sei realizar isso com float
Comment: Já usou o GRID? Dá uma olhada neste Fiddle: https://jsfiddle.net/xe468gz8/
Comment: @Dvdsamm formula uma resposta com este exemplo, ficou muito bom.
Comment: Resposta postada. Abs!
Answer: Um exemplo bem simples é criar um "div pai":

/*o BODY no doctype HTML5 ou Strict não ocupa 100%, então isso deve ajustar*/
html, body {
    height: 100%;
}

.flex-parent {
    display: -webkit-flex;
    display: flex;
    width: 100%;
    height: 100%;
}

.col {
    -webkit-flex-direction: column; /* Safari 6.1+ */
    flex-direction: column;
}

.flex-child {
    width: 100%;
    height: 100%;
    background-color: #c0c0c0;
    margin: 2px;
}

Filho 0

Filho 1

Filho 2

Filho 1

Filho 2

Filho 3

flex-parent é classe responsável por criar pais e avôs
flex-child é para ocupar 100% do espaço (pode ser substituído e pode ser opcional, ou seja os filhos podem variar de tamanho), no entanto talvez seja melhor usar ela para evitar que a orientação de botões e formulários ou outras coisas dentro do flex sejam afetadas
col muda a orientação dos filhos

Se tem alguma preocupação com navegadores mais antigos, como alguns mobile por exemplo, pode experimentar usando float: ...; e ajustando a porcentagem da largura e altura conforme necessário, um exemplo:

/*
o BODY no doctype HTML5 ou Strict não ocupa 100%, então isso deve ajustar
A margem afeta os elementos filhos, então neste caso é melhor remover
*/
html, body {
    margin: 0;
    height: 100%;
}

.top, .child, .bottom, .v-block, .big-block {
   box-sizing: border-box;
}

.main {
    width: 100%;
    height: 100%;
}

.top {
    width: 100%;
    height: 66.6665%;
}

.bottom {
    width: 100%;
    height: 33.3332%;
}

.big-block {
    width: 66.6665%;
    height: 100%;
    float: left;
}
.v-block {
    float: left;
    width: 33.3332%;
    height: 100%;
}

.child {
    background-color: #c0c0c0;
    width: 100%;
    height: 100%;

    /*sombra só pra identificar o childs*/
    box-shadow: inset 0 0 2px 2px rgba(0,0,0,.26);
}
.v-block > .child {
    height: 50%;
}
.bottom > .child {
    float: left;
    width: 33.3332%;
    height: 100%;
}

Filho 0

Filho 1

Filho 2

Filho 3

Filho 4

Filho 5

Comment: só da pra pagar em 23 horas, assim que liberar eu dou a rep
Comment: @MuriloGambôa nem precisa se preocupar, eu gosto muito de perguntas de CSS, se tivesse visto antes da recompensa eu teria respondido. PS: vou começar a seguir o Feed da tag CSS https://pt.stackoverflow.com/feeds/tag?tagnames=css&sort=newest  :D
Answer: Você pode usar o CSS GRID que se auto-ajusta à largura da div:

.wrapper {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 5px;
    background-color: #fff;
    color: #444;
    grid-auto-rows: minmax(150px, auto);
}

.box {
    background-color: #444;
    color: #fff;
    padding: 20px;
    font-size: 150%;
}

.box.a{
    grid-column-start: 1;
    grid-column-end: 3;
    grid-row-end:span 2;
}

a

b

c

d

e

f


React Native: Change color of navigation tab

Question: On my navigation tab, I want to change the color of the label + the color of the icon when its active, so what I did is created an if and else statement:
<MealsFavTabNavigator.Screen
                    name="Favorites"
                    component={FavoritesScreen}
                    options={({ route }) => ({
                        tabBarIcon: (tabInfo) => {
                            if (route.name === 'Favorites'){
                                return <Ionicons name="ios-star" size={25} color='tomato'/>
                            } else {
                                return <Ionicons name="ios-star" size={25} color='black' />
                            }

                        }
                    })}

My label color is also fixed above the Navigator level:
    <MealsFavTabNavigator.Navigator
        tabBarOptions={{
            activeTintColor: Colors.primaryColor,
            inactiveTintColor: 'black',
        }}>

Here's my full code:
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import { Ionicons } from '@expo/vector-icons';

import CategoriesScreen from '../screens/CategoriesScreen';
import CategoryMealsScreen from '../screens/CategoryMealsScreen';
import MealDetailScreen from '../screens/MealDetailScreen';

import FavoritesScreen from '../screens/FavoritesScreen';

import HeaderButton from '../components/HeaderButton';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

import { CATEGORIES } from '../data/dummy-data';

import Colors from '../constants/colors';

const MealsNav = createStackNavigator();

const MealsNavigator = () => {
    return (
        <MealsNav.Navigator
            mode="modal"
            screenOptions={{
                headerStyle: {
                    backgroundColor: Colors.primaryColor,
                },
                headerTintColor: '#fff',
                headerTitleStyle: {
                    fontSize: 17
                }
            }}
        >
            <MealsNav.Screen
                name="Categories"
                component={CategoriesScreen}
                options={{
                    title: 'Meals Categories'
                }}

            />
            <MealsNav.Screen
                name="CategoryMeals"
                component={CategoryMealsScreen}
                options={({ route }) => {
                    const catId = route.params.categoryId;
                    const selectedCategory = CATEGORIES.find((cat) => cat.id === catId);

                    return {
                        title: selectedCategory.title,
                    };

                }}
            />
            <MealsNav.Screen
                name="MealDetail"
                component={MealDetailScreen}
                options={{
                    title: 'Meal Detail',
                    headerRight: () => (
                        <HeaderButtons HeaderButtonComponent={HeaderButton}>
                            <Item
                                title='Favorite'
                                iconName='ios-star'
                                onPress={() => console.log('Mark as the favorite')}
                            />
                        </HeaderButtons>
                    ),
                }}
            />
        </MealsNav.Navigator>
    );
};

const MealsFavTabNavigator = createBottomTabNavigator();

const MealsTabNav = () => {
    return (
        <NavigationContainer>
            <MealsFavTabNavigator.Navigator
                tabBarOptions={{
                    activeTintColor: Colors.primaryColor,
                    inactiveTintColor: 'black',
                }}>
                <MealsFavTabNavigator.Screen
                    name="Meals"
                    component={MealsNavigator}
                    options={({ route }) => ({
                        tabBarIcon: ({ color }) => {

                            if(route.name === 'Meals'){
                               color = 'tomato'
                            } else if (route.name === 'Favorites') {
                                color = 'black'
                            }
                             return <Ionicons name="ios-restaurant" size={25} color={color}/>
                        }
                    })}
                />
                <MealsFavTabNavigator.Screen
                    name="Favorites"
                    component={FavoritesScreen}
                    options={({ route }) => ({
                        tabBarIcon: (tabInfo) => {
                            if (route.name === 'Favorites'){
                                return <Ionicons name="ios-star" size={25} color='tomato'/>
                            } else {
                                return <Ionicons name="ios-star" size={25} color='black' />
                            }

                        }
                    })}
                />
            </MealsFavTabNavigator.Navigator>
        </NavigationContainer>
    );
};

export default MealsTabNav;

How can I change the color of the label and color of the iconicons when its active? My solution doesnt work.
Answer: By default there are parameters for colors in tabbar icon and tabbar label and these are set to the active tint color and inactive tint color.
But if you have a requirement to override this you can do the following
 <Tab.Screen
    name="Feed"
    component={Feed}
    options={{
      tabBarLabel:({ focused,color })=>(<Text style={{color:focused?"red":"aqua"}}>1232</Text>),
      tabBarIcon: ({ focused,color, size }) => (
        <MaterialCommunityIcons name="home" color={focused?"green":"blue"} size={size} />
      ),
    }}
  />

References on the props
tabBarLabel can be a text or a react node, and you get the focused and the color as arguments, The color will be the color you set as activetintcolor or inactivetintcolor.
focused is a boolean on whether the tab is focused or not.
Same arguments are passed to the tabBarIcon only difference is the size which is the size of the icon.
If you see the code above, I have given custom colors based on focused without using the color that is passed. You can do this as per your requirement.
Answer: https://stackoverflow.com/a/63033684/17735463 - This is a valid answer but mine works fine too (react-navigation-v5)
<Tab.Navigator
     screenOptions={({ route }) => ({

          tabBarIcon: ({ focused }) => {
            let iconName;
            let size=25;
            let color = focused ? 'black' : 'gray';
            if (route.name === 'HomeScreen') {
              iconName = 'ios-home';

              return <Ionicons name={iconName} size={size} color={color} />;
            } else if (route.name === 'FavoritesScreen') {
              iconName = 'star';

              return <AntDesign name={iconName} size={size} color={color} />;
            }

          tabBarLabel: ({ focused }) => {
            let titleStyle = {
              fontSize: 12,
              fontWeight: focused ? 'bold' : '500',
              color: focused ? 'black' : 'gray',
            };
            if (route.name === 'HomeScreen') {
              return <Text style={titleStyle}>Home</Text>;
            } else if (route.name === 'FavoritesScreen') {
              return <Text style={titleStyle}>Favorites</Text>;
            }
          },

})}>

<Tab.Screen name='Home' component={HomeScreen}/>
<Tab.Screen name='Favorites' component={FavoritesScreen}/>

</Tab.Navigator>


Proof of the Tarski-Vaught test

Question: The Tarski-Vaught test is a way to determine if a substructure is elementary. To my understanding, here is the theorem:

Tarski-Vaught Test Let $N$ be a substructure of $M$. Then the following two statements are equivalent:

$N$ is an elementary substructure of $M$.
For any formula $\phi$ and elements $p_1,p_2,\dots,p_n \in N$ such that $M \models \exists x. \phi(x,p_1,p_2,\dots,p_n)$, there exists $q \in N$ such that $M \models \phi(q,p_1,p_2,\dots,p_n)$.

However, I have not been able to find a proof of this statement. 1 implies 2 is clear to me, but I am not sure how to prove 2 implies 1.
What is a proof of the Tarski-Vaught test?
Comment: I'm curious how you failed to find a proof of this statement. It's proven in literally every textbook on model theory, and probably in almost all online course notes on model theory. And if you google "Tarski-Vaught test proof", the first result is a [Proof Wiki page](https://proofwiki.org/wiki/Tarski-Vaught_Test) which contains a proof.
Comment: @AlexKruckman I only checked online. I saw the proof wiki one, but the formatting made it hard to follow.
Answer: This is more a sketch of proof, but I hope it will be sufficient, if not feel free to ask for additional details.
Basically one have to prove that every formula $\phi$ with parameters in $N$ is true in $M$ if and only if it is true in $N$.
The way to prove that is by induction on the complexity of the formula:

the case for atomic formulas with parameters in $N$ follows easily by the fact that $N$ is a substructure
the case for formulas without quantifier follows easily
the case for existentially quantified formulas follows by the hypothesis
the case for universally quantified formulas follows from the logical equivalence $\forall x. \phi(x)\Leftrightarrow \neg \exists x.\neg \phi(x)$ and by the other cases.

I hope this helps (if not, as I said above, please ask).
Comment: This makes sense! The only small question I have is that formulas without quantifiers transfer into any substructure, right?
Comment: @PyRulez exactly, of course that must be proved, but it isn't really hard. Of course difficulty depend on the familiarity one have with the concepts, so feel free to ask if that's not the case.

Proof of the Tarski-Vaught test


Robustness checks for DiD

Question: I am currently looking at a DiD model to evaluate the impact of a policy on ethnic and non ethnic people in the EU. I have done the regression and got the results.
I have only two time periods but 10 countries. I was wondering what robustness checks I could run? I know for my model the parallel trends assumptions is not possible so what robustness checks could I do?
Much of what I have read on or come across is running a placebo test but confused on what that exactly means.
Answer: You can perform a placebo test by changing the treatment group.  You are actually doing:
$$Y_{it} = \beta_1 + \beta_2 (\text{treat}_i) + \beta_3 (\text{time}_t) + \rho (\text{treat}_i \cdot \text{time}_t) + \epsilon_{it}$$
and checking if $ \rho$ is statiscally significant.  Instead of using your real treatment group, in a placebo test you change the treatment dummy (ethnic) to something like gender (or any other variable that you have). The effect should not be significant

Robustness checks for DiD


Rails method evaluating user input

Question: I'm trying to check for specific entry condition combinations "entry_conditions"  when a user submits a form.
If the user enters these exact values for either of the entry_conditions (a or b), I would like "meets_any_entry_conditions?" to be true.
But I'm struggling with the structure.
def entry_conditions
 condition a = [fielda: 6, fieldb: 6, fieldc: 6]
 condition b = [fielde: 10, fieldf: 10, fieldg: 10]
end

def meets_any_entry_conditions?
  entry_conditions.any?
end

Answer: def entry_conditions
  [{fielda: 6, fieldb: 6, fieldc: 6},{fielde: 10, fieldf: 10, fieldg: 10}]
end

def meets_any_entry_conditions?
  entry_conditions.each do |condition|
    passed = true
    condition.each do |k, v|
      passed = false unless send(k) == v
      break unless passed
    end
    return true if passed
  end
  false
end

Rails method evaluating user input


Set placeholder image if tag does not exist ionic 2 angular 2

Question: When parsing rss feed in xml format, I display the images that are contained in the attibute url inside the tag <enclosure> but whenever the tag enclosure is missing because the article does not have an image, I'm getting an error in the console saying:
Cannot read property 'getAttribute' of undefined

I tried to solve this problem using onError function inside src but when the tag is missing I'm still getting the error in the console and the placeholder image is not shown.
Here's my html file:
<ion-header>
  <ion-navbar color="primary">
    <ion-title text-center>
      App Name
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-item *ngFor="let entry of entries" (click)="openPage(entry)" text-wrap>
      <ion-thumbnail>

      </ion-thumbnail>

{{entry.getElementsByTagName('title')[0].textContent}}

    </ion-item>
  </ion-list>
</ion-content>

Comment: I dont think you need that semi colon at the end there and shouldnt the img src be `[src]=`
Comment: @gerdi I actually edited those part but nothing changes
Answer: You can use *ngif. example:

also check this link
EDIT:

Comment: I added them both inside `` but I'm getting this error:
`Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngif' since it isn't a known property of 'img'.`
Comment: Check till where you got something and change ngif. I update the answer. please use the approach.
Comment: This error has nothing to do with @aminarghavani 's solution. You have to import the correct module (BrowserModule or CommonModule): http://stackoverflow.com/questions/39058075/cant-bind-to-ngif-since-it-isnt-a-known-property-of-div
Comment: @aminarghavani @yadejo It seems that the first answer you gave me was correct! I just had to make one little modification, `*ngIf` instead of `*ngif`. Thanks a lot :)
Comment: "[src]=" is better used when dealing with dynamic/expression image sources


How to get 2-players locations and teleport them each to other location

Question: I need to get 2-players positions(on server only 2 players and i don`t know their names)
and then teleport first player to second(location) and second player to first(location)
like
Player firstplayer = Bukkit.getServer().getplayer(1);
Player secondplayer = Bukkit.getServer().getplayer(2);

Location firstloc = firstplayer.getLocation();
Location secondloc = secondplayer.getLocation();

firstplayer.teleport(secondloc);
secondplayer.teleport(firtsloc);

how to do it?
Answer: You misspelled firstloc.
If that doesn't work, try creating a temporary Location variable like so:
Player firstplayer = Bukkit.getServer().getplayer(1);
Player secondplayer = Bukkit.getServer().getplayer(2);

Location firstloc = firstplayer.getLocation();
Location temp = firstloc;
Location secondloc = secondplayer.getLocation();

firstplayer.teleport(secondloc);
secondplayer.teleport(temp);


Surface area of revolution; $y=0.25x^3$, $0\le x\le 2$, revolved around $x$-axis

Question: I'm trying to solve the surface area of revolution for the function $y=0.25x^3$ revolved around $x$-axis from $0\le x\le 2$.
I got the answer $14.253$ using $$2\pi \int_0^2  0.25x^3 \sqrt{1+(0.75x^2)^2}\,dx$$
And according to my college prof I'm wrong.
Can someone help me find my mistake?
Comment: Maybe check that you understood the problem itself correctly. If there are no mistakes with that, ask the professor to clarify what's wrong.
Comment: I reformatted the formulas. See [math notation guide](http://math.stackexchange.com/help/notation). As a member for over a year, with 14 questions posted, you should have had plenty of opportunities to learn the markup.
Comment: Your answer looks right to me.
Comment: I don't see a problem with the integral you've used, and Wolfram Alpha confirms your answer.
Comment: I am 100% sure that's how the problem was worded. I have it infront of me
Comment: I'll ask tomorrow if there was a typo on the sheet maybe? I don't know
Answer: Here's a quick shot at it. Leave out the square root and integrate.
a = π/2 * x^4 / 4  | from 0 to 2
= 16 π / 8
= 2π

Do it the way you started. This is why I like coming here. I find out what I let get rusty. No areas of revolution integrals for almost 40 years....
Ok, let's try this:
a = 2π∫ 0->2 (1/4)*x^3/4 * (1 + 9/16 x^4)^(1/2) dx
Let's try d/dx (1 + 9/16 x^4)^(3/2)
we get 3/2*9/4*x^3*(1 + 9/16 x^4)^(1/2), or
<code>   (27/8)*x^3*(1 + 9/16 x^4)^(1/2), so
</code>
a = 2π * 2/27 * (1 + 9/16 x^4)^(1/2)  |  0->2
= 4π/27 * (10^(3/2) - 1)
which seems to be reasonable since the answer is a little bigger than 4π.
Comment: This is what I originally got and he said it was wrong too! I did this because I was just taking the perimeter of the discs and adding them and I got 2 Pi.  So then I tried it using the surface area formula with sqrt for tangent
Comment: Are you sure you know what you are doing?
Comment: Oh, duh. Add the final surface area for the end plate at x=2, or
Comment: Ohhhh!!!!!! I wonder
Comment: Good plan. But still wrong /: for both your answer + pi*r^2 on the ends and my answer plus pi*r^2 on ends. I think the prof is just wrong
Comment: I knew my answer was wrong when the end plate area was larger than the area of the revolution.


Is there any way to capture audio through tinymix commands?

Question: I am trying to capture Raw Audio data directly through USB from mobile so is there any tinymix commands to capture it?
Answer:
First record the audio using tinycap
$ adb shell tinycap <dest-file-path>
Pull the recorded file to host over USB
$ adb pull
Comment: Is `tinycap` still works on android 11 in 2021?
Comment: I think only on rooted devices. Tried on the emulator- didn't work


Existence of a certain primitive function

Question: $f(z) = (1-{1 \over {z^2}}) e^{z+  {1 \over z}} $ . Find the $\int_{\vert z \vert =r} f(z) dz $
If the primitive $F(z) = e^{z+{1 \over z}}$ exists, the contour integer's value would be $0$.
But Since the $f$ is analytic on $D = \{ z \Vert 0< \vert z \vert <r \}$(Not simply connected),  I can't sure the existence primitive $F(z)$ of the $f$ on $D$. If the primitive of the $f$ exists or not, would you please tell me reason why you conclude like that?
Thanks.
Comment: The integral is $2i\pi$ times the residue of $f$ at $0$.
Comment: @YvesDaoust, Thanks for your hint. Then more generally if the either residue or sum of those is 0, Could we conclude the existence of the antiderivative?
Answer: $F $ is  a primitive of $f $ on $\mathbb C \setminus \{0\}.$
Hence the integral in question  $=0. $
Comment: Yes if the primitive exists your answer is correct. But Why does the $F$ exist? It is not simply connected so we can't say existence of the primitive.
Comment: If $F (z)=e^{z+1/z}$, then compute the derivative  of $F $. You should get  $f $.


SOLR edismax search

Question: I have 2 documents in SOLR:
first
id = 125
spell = Quanti disperati si rovescerebbero con i barconi sulle nostre coste...

second
id = 321
spell = Quanti disperati si rovescerebbero con i barconi sulle nostre coste...

http://localhost:8080/solr/select?q={!type=edismax qf=spell v='disperati si rovescerebbe*'} - working fine for me, it returns 2 documents but how can I add to this query search by id too?
I need something like this:
http://localhost:8080/solr/select?q={!type=edismax qf=spell v='disperati si rovescerebbe*'} & {!type=edismax qf=id v='125'} - incorrect.
Answer: If you know the id why not use -
http://localhost:8080/solr/select?q={!type=edismax qf=spell v='disperati si rovescerebbe*'}&fq=id:125

SOLR edismax search


Plateau in speed increases

Question: a while ago I posted this question about my ideas for guitar practise: Guitar practice - general techniques
Since then I've been using the little app I put together, ranked up about 40 hours or so in total and it's been mostly great.  I can record how much I've been practising, it slows me down when I make mistakes, gradually speeds up, etc.
I found some interesting things which made me tweak how it works along the way.
But mostly - I seem to get 'stuck' around a particular BPM, about 75% of the target BPM I wrote the riff/part for, for the past couple of weeks.  That's across 3 or 4 different sections, which I practise on average between 10 and 20 minutes each every day (i.e. total 1 to 2 hours each evening, ish)
Usually I pick up each riff for the day, make some mistakes and so drop down 5 or 10 bpm or so until I play it consistently.  Then, the BPM rises to about the same place (or slightly higher, slightly lower) and the time for that exercise/riff/part is finished, so I move on.
I sometimes make better progress on the days I can do 20 minutes on each part, but there's rarely a good solid leap.
The good part is my app can throw out a graph of date vs BPM, and it's recorded everything I've done.  The frustrating part is the line goes up from my starting tempo (30 or 40%) to about 170 bpm in each case - despite some being 16ths, some 16th triplets, some sweeping etc - and has stayed there for a couple of weeks.
I have no doubt it's doing some benefit - I can relax more, play for longer, and when I 'mess around' and try the thing at a high tempo (or full tempo), it sounds a lot better than before - albeit it lots of mistakes.
I want to see what everyone makes of this: am I reaching some talent-based limit, technique-based limit etc?  I feel as is everything is relaxed and when watching myself in the reflection of my old monitor, there's no stray finger flailing around, no massive inefficient movements etc...
(Oh, as per my original question's best answer: I do warm up with some chromatic runs.. despite it sounding like a terrible affliction.. for about 3 min, which seems to get my fingers / muscles in the mood)
Can anyone comment or provide any tips, thoughts?
Comment: I don't know guitar.  But in my piano world, I've heard that you won't improve muscle memory on the same day.  You -program- your muscle memory by stressing it correctly that day.  Then you -sleep- which rewires your brain=>fingers so your brain is effectively soldered directly for that action.  More practice+sleep reps is what does the trick.  Well, that and an overall long range improvement in "general skills".
Comment: Interesting thanks Stephen, I hadn't appreciated that.  So time/days elapsed is an important metric too.  Can you tell I'm a programmer? :)
Comment: Just keep at it. No one has said this yet but 40 hours isn't really that much practicing. I had planned on going to school for performance a while back and I would practice 4-8 hours a day. Keep at it but give it sometime you will plateau again and again but if you practice through it you will see results.
Comment: @enthdegree - it's a long-term plan, I just have a lot on at the moment, busy work, busy preparing an album et :)
Comment: As a programmer, yes, I can tell you're a programmer.  A surprising percentage of "us" make music.
Comment: Being on stackexchange implies that most of us must be more or less accointed to programming :) at least until it goes out of beta
Comment: Would you consider publishing your app?
Answer: Keep in mind that even with a very thorough workout, some things just take time. And you need to rest, too. I regularly find myself making more progress speed-wise when I stop practising something for a day or two than when doing it like hell. As mentioned in another answer, reaching high speeds requires relaxation as much as it relies on repetition. Either work on this, of give yourself some slack : the more you stress yourself, the less you'll reach your goal. If you really want to practice, practise something else. If you really want to practice this part, try breaking it up in multiples parts, or playing it another way : another octave, another fingering, another right or/and left hand technique : it will prevent your from boredom, it will expand what's available to you in term of playing...and you might even find a better way to play it than what you originaly wrote.
Also, playing a hard, fast part, can be really challenging at a very, very slow pace (tai chi style). Try playing it at 40, or 30 bpm. I used to start from an average tempo and then work my way, either up or down in tempo. Both are hard.
Answer: You seem to be focused on the physical aspects and drilling. I'd recommend a complementary pursuit of something with more musical content. Even Steve Vai's 10-hour workout (which, btw, is one of the best things ever published in Guitar World), recommends a heavy dose of transcription and improvisation.
Funk guitar has a lot to offer in the way of complicated riffs that repeat throughout the song. Grab some George Duke or Parliament and play along. You can jam through three 3-minute songs in 10 minutes.
Comment: Top advice thanks.  I think I'm on the right track in that regard, I manage to get the vibrato, dynamics and some interest into it, despite it being a fairly consistent stream of notes.  I'm just frustrated I'm not improving as quickly as I would like :)
Comment: Thanks for this.  I love the idea but I really am goal-driven: I'm recording an album and made up some great sounding parts I want to be able to play at the correct speed to get the right feel.  I would have thought that 'quality' hours spent building muscle memory for those things would have the best direct improvement.. after these are up to scratch I would want to diversify, but before then.. do you think it would help nail these parts specifically to play something else?
Comment: Hmm, perhaps not. If the parts are already written, then drilling probably is the best way to work them up. But make sure you're integrating the riffs back into the complete song. To feel comfortable, you need to be able to play through the whole song without the metronome and still *feel* the pulse.
Answer: It sounds like you have hit a wall, but it has nothing to do with talent or technique.  It has to do with hearing.  One of the most helpful things I ever learned had to do with playing really fast intricate lines.  My technique is really good and I can play fast, but when I did, my lines got boring and sometimes I couldn't keep up with a tempo.  The problem was that I wasn't 'hearing' fast.  My brain couldn't keep up with the speed of the notes, even though my fingers could.  Turns out it's damn near impossible to think about each note flying by at a fast tempo.  The trick is to not do that.  Only think about the line as a whole and practice hearing it that fast in your head a few times before playing it.  Do it without the metronome at first so as not to get caught up in trying for perfection.
Comment: Ah I can certainly believe that.  I have hints of it at least, sometimes I hear or 'feel' just some key parts of a phrase or lick.  Often I use legato and I only 'lock in' to the times I pick or change strings.  Ill see if I can focus on that :)

Plateau in speed increases


How can I improve my playing of faster finger runs?

Question: I am just preparing for my grade 8 piano exam. I'm struggling with quick runs in the 3rd movement of Beethoven's Sonate Pathetique. It really doesn't sound right. When I play I can't do it smothly and it sounds (and feels) like my hands are tired. Does anyone have any good exercises to improve this?
The other matter is that my shoulder hurts after longer sessions. I know that probably I do something wrong, but don't really know what.
Comment: I know it sounds odd, but make sure your eating properly and other similar stuff, I'm not a pianist but I know my technique suffers(and i feel tired) if I don't eat well for a day or two.  Also make sure your properly warmed up before you play the piece  and have periodic short breaks away from your instrument, stretch during the breaks if you think it will help your shoulder.
Answer: Something my teacher regularly had me do with difficult sections was to play it all stacatto.  Slow it down and focus on perfect timing while you do this, then gradually increase the tempo.  Don't increase it further than you can play while still keeping the timing perfect.  Do this every practice session until your speed is relatively close to the speed you need to play it normally, and then play it normally.  You'll be amazed how much easier it is to play smoothly and quickly after training with the much more strenuous staccato version.
The stacatto will tire your hands out even more, of course.  There's not much you can do other than build up your strength, assuming your technique is good and you're rested etc. as Rein and DRL note.  And this is a great method of building hand/finger strength.
Answer: If your shoulder (or anything else) hurts after playing sessions, your playing is ergonomically poor. Keep your posture erect, keep your arms relaxed and loose at your sides, and don't raise your elbows. Make sure your seat is at the correct height. Watch out for tension while you are playing and work on allowing your body to release it.
To improve scales (and many other technical challenges), I find a combination of two practice approaches to be helpful:

Start with the first group of notes that you can play comfortably at (or near) performance speed. Then add a new note (or group), focusing on the new movements necessary to hit that note (or group). This sacrifices consistency for speed.
Go as slow as necessary to play the movement correctly. Speed up gradually at a pace where your technique remains consistent. Use a metronome. This will bring back the consistency you sacrificed previously.

For instance, when practicing arpeggios, I focus on the thumb tucks (cross-overs), doing the arpeggio through the first thumb tuck until that feels natural, then the second, and so on until I can span a number of octaves comfortably. I also practice the same arpeggio slowly and consistently to make sure that I don't learn bad habits (playing out of time, rushing through, etc). The combination of approaches seems to yield greater benefits for me than either individually.
Answer: On violin, it helps to practice entire passages in swing (dotted followed by half value) and reverse swing (half value followed by dotted). This lets you practice playing every other note in quick succession as well as in isolation.
I think the same practice technique should work for piano too.
To play quickly doesn't mean to play each note quickly so much as it means to switch from one note to the next really quickly. And that's where your concentration should be when you practice, thinking about how you can best move your hand to play the next note, how you can prepare your hand for the next note after that etc.
Answer: For fast runs, you have to rely on muscle memory; you have to become "unconsciously competent".
For simple fast runs, play it very(!) slow and very(!) loud (but not hammering) with only the hand doing the run. This strengthens your fingers and builds muscle memory. After playing a fast run two or three times with this technique, try playing it very quiet but faster. I was surprised by how effective this technique is.
For more complicated runs, do the above, but play ever other note twice as long as the other notes. Instead of da da da da da, you play daa da daa da daa, and then you switch it up and play da daa da daa da. This singles out one set of the transitions and focuses learning on these.
Answer: To make runs "sound right", you need to respect the phrasing.  Just because something is played fast doesn't mean that you can't play with dynamics (obviously).  So when you're working with the runs, really look at them, and see if adding a swell, or "leaning into" a beat will make it sound more coherent.  If you have no idea where to start, pick a beat to lean into at random, and see if you like it better!  Singing the melody is my favorite way to pick out which parts of a phrase need a little more "oomph".
Like other people said, when your hand gets fatigued, take a break.  There's no point in playing through it, because that just makes it easier to get hurt.  Over time, your musculature will develop and you'll be able to play for longer without getting that fatigue.  Anything you can do to stay relaxed will delay that fatigue.  I find that playing with "proper piano technique" (according to my teachers, wrists high, fingers curled) is really really annoying at first, but over time, it did wonders for my stamina.
As far as shoulder tension is concerned, make sure that you're sitting at the right height and the right distance from the piano for you; try playing out of a different chair, or adding a cushion on top of your bench.  Also, consciously make sure that you're not tensing up your shoulders, it'll help you with your control over time (tired muscles are imprecise muscles).
Answer: There are 2 main things to remember and be conscious of, when you practice:

relax the hands, fingers, shoulders and your body. If you feel pain, STOP! "No pain, no gain" does not apply in music performance! BTW, they found out it is not good in sports either!
Anticipation: this gives you speed and evenness. For example on the piano when your finger is one one key, prepare the next finger for the next key. Remember also that you don't push in the key, but lift the fingers and let then fall like little hammers (articulation). Keep the arm relax when you have to skip keys. The arm leads the hand.

In violin the same, need to anticipate the position of the next finger that plays, especially if you play arpegios. In violin you also have to coordinate the anticipation of the bow and the arm level of the right hand.
Answer:
Of course, practice is the most important factor.
In sections are are having trouble with, practice one hand at a time. You might be surprised how badly you do with one of the hands. Then, when you learn it with the bad hand, you'll have it with both.
Make sure your bend your fingers enough. If your fingers are too straight, they don't respond as quickly.
Emphasize the first of every 4 or 8 notes. This will help with the timing. Later on you can de-emphasize it if it sounds better that way.
Make sure you are using good fingering. If you are stumbling over the same place (like measures 179-181, for example), you might want to adjust your fingering. The version edited by Stewart Gordon has excellent fingering.
Answer: I'm not a piano player, but I think the same applies for tricky guitar passages. Play along to a metronome at slower speeds and gradually increase tempo. You probably heard that a thousand times, but it's one of the best approaches.


Recursion gives me completely wrong answers

Question: I want to find the number of ways, a given integer X can be decomposed into sums of numbers which are N-th powers and every summand must be unique. For example if X = 10 and N=3, I can decompose this number like that:
10 = 2^3+1^3+1^3 ,but this is not a valid decomposition, because the number 1 appears twice. A valid decomposition for X = 10 and N = 2 would be 10 = 3^2+1^2, since no summand is repeating here.
Now I tried it to use recursion and created the following Python Code
st = set(range(1,int(pow(X,1/float(N))))) # generate set of unique numbers
print(str(ps(X, N, st)))

def ps(x, n, s):
    res = 0
    for c in s:
        chk = x-pow(c,n) # test validity
        if chk > 0:
            ns = s-set([c])
            res += ps(chk,n,ns)
        elif chk == 0:
            res += 1 # one result is found
        else:
            res += 0 # no valid result
    return res

I used a set called st and then I recursively called the function ps that includes the base case "decomposition found" and "decomposition not found". Moreover it reduces a larger number to a smaller one by considering only the ways how to decompose a given number into only two summands.
Unfortunately, I get completely wrong results, e.g.
X = 100, N = 3: Outputs 0, Expected 1
X = 100, N = 2: Outputs 122, Expected 3
X = 10, N = 2: Outputs 0, Expected 1

My thoughts are correct, but I think the Problem is anywhere in the recursion. Does anybody see what I make wrong? Any help would be greatly appreciated.
Answer: The problem is line res += 1 # one result is found in conjuction with res += ps(chk,n,ns) will make the algorithm add twice.
E.g X = 10, N = 2: Outputs 0, Expected 1 because:
c=1:

10 - 1^2 > 0 -> res += ps(chk,n,ns)

c=3:

9 - 3^2 == 0 -> res += 1 # one result is found ... return res

So, in c=3 res=1 is returned to the c=1 call, which will
res += ps(chk,n,ns), and  ps(chk,n,ns) = 1, making res = 2 and doubling the result expected.
E.g. X = 29, N = 2.
29 = 2^2 + 3^2 + 4^2
Solving from bottom to top (the algorithm flow):
c=4 -> res += 1... return res
c=3 -> res += ps() -> res += 1 -> res = 2 ... return res
c=2 -> res += ps() -> res += 2 -> res = 4 ... return res
But res is supposed to be 1.
Solution: You cannot add res to res. And you must remove the previous iterated objects to avoid path repetition. Check the solution below (with prints for better understanding):

def ps(x, n, s):
    print(s)
    print("")
    return ps_aux(x, n, s, 0) # level

def ps_aux(x, n, s, level):
    sum = 0
    for idx, c in enumerate(s):
        print("----> " * level + "C = {}".format(c))
        chk = x - pow(c,n) # test validity
        if chk > 0:
            ns = s[idx + 1:]
            sum += ps_aux(chk,n,ns, level + 1)
        elif chk == 0:
            print("OK!")
            sum += 1 # one result is found
        else:
            sum += 0 # no valid result
    return sum

Try with:
X=10 # 1 solution
N=2
st = list(range(1,int(pow(X,1/float(N))) + 1 )) # generate set of unique numbers
print(str(ps(X, N, st)))

X=25 # 2 solutions [3,4], [5]
N=2
st = list(range(1,int(pow(X,1/float(N))) + 1 )) # generate set of unique numbers
print(str(ps(X, N, st)))

Answer: Hint:
>>> X = 100
>>> N = 3
>>> int(pow(X, 1/float(N)))
4

>>> list(range(1, 4))
[1, 2, 3]

The output is indeed correct for the input you are feeding it.
Comment: I forgot the +1 in end of range; now I fixed this and for X=100,N=3 I get now the result 24, for X = 100,N=2 I get 123 and for X=10,N=2 I get 2. Why?


Maintain setgid bit (after bower install or gulp build)

Question: We run web servers where we have the following situation:

The www-data user runs the web server and must have read+write access to the files
The deploy user deploys all the code
The bob and alice users might login via ssh and change configurations locally

All users must have read+write access on /var/www/mysite. We currently accomplish this by owning the group of /var/www/site to www-data. Then we set the write + setgid bit on the group to make sure all subdirectories are having the same rights.
Now, this is all running fine for some time, but we have issues with the following scenarios:

We use bower to install packages with bower install. The user who ran bower install the first time owns the public/bower_components directory and no setgid bit is set
We use gulp to minify javascripts from public/scripts/src to public/scripts/dist and the first user who ran gulp build owns the files

In both situations, a find path/to/dir -type d -exec chmod g+ws {} \; does mitigate the problem, but is it possible to fix this issue in the first place? We have set the setgid bit on the /var/www/mysite directory, so why does bower install not follow this permission set?
If not, is there a better way to fix this problem? We have thought to set the bits in the deployment automation process, but if a user forgets the setgid bit we think the automated deployment could get stuck as well.
Comment: This is a job for `posix ACLS`.
Comment: What operating system are you using?
Comment: @CristianCiupitu it's Ubuntu 12.04 LTS, though we might switch in the near future to Ubuntu 14.04. Anyhow, "just" GNU/Linux (Debian based) :)
Comment: That's not the sticky bit, that's the *set group ID bit*. Anyway, I take it that newly created subdirectories don't inherit this bit and the files don't belong to the common group?
Comment: Correct. We set it so `ls -al` shows `drwxrwsr-x` and after a Bower install (as an example) the permissions are `drwxrwxr-x` (note the s vs x). Afaik, that's the problem. With `chmod g+ws` it's "fixed" again.
Comment: Thanks for the edit @CristianCiupitu. I will read the answers later this week and try all the different answers.
Answer: Posix ACLs are the only clear-cut elegant way to do this, this is how I deal with shared read/write resource conflicts particularly on web-based systems. Here is a running example.
In my example I have a directory called /var/www/html/share.
In addition I have the users alice, bob, deploy and bower
First, I have created a group called html and then added the users to this group.
groupadd html
for i in alice bob deploy bower; do usermod -a -G html $user; done

Now, I have then added a file ACL against this html group onto that folder.
setfacl -m g:html:rwx /var/www/html/share
setfacl -d -m g:html:rwx /var/www/html/share

The second command is important, it causes inheritance to occur.
Now, we can test out the behaviour of this.
# for user in alice bob bower deploy; do \
    sudo -u $user touch "/var/www/html/share/file_${user}" \
done

[root@localhost html]# ls -l /var/www/html/share/
total 0
-rw-rw-r--+ 1 alice  alice  0 May 13 23:08 file_alice
-rw-rw-r--+ 1 bob    bob    0 May 13 23:08 file_bob
-rw-rw-r--+ 1 bower  bower  0 May 13 23:08 file_bower
-rw-rw-r--+ 1 deploy deploy 0 May 13 23:08 file_deploy
[root@localhost html]#

At first glance, it looks as though the file ownerships are all just simple, and will not allow one user to interact with anothers. However, we can inspect the ACL using getfacl which shows more infomation.
# getfacl file_Al
getfacl: file_Al: No such file or directory
[root@localhost share]# getfacl file_alice
# file: file_alice
# owner: alice
# group: alice
user::rw-
group::r-x          #effective:r--
group:html:rwx          #effective:rw-
mask::rw-
other::r--

You can see that the html group has control over these files.
Note: the standard unix GROUP permission denotes the mask against the permissions. As it is rw for files it is also effectively rw for the ACL, despite the actual permission granted being rwx.
Lets test other users can modify/delete these files.
# sudo -u alice /bin/bash
[alice@localhost share]$ pwd
/var/www/html/share
[alice@localhost share]$ echo "hello world" >>file_alice
[alice@localhost share]$ echo "hello world" >>file_bob
[alice@localhost share]$ echo "hello world" >>file_deploy
[alice@localhost share]$ echo "hello world" >>file_bower
[alice@localhost share]$ ll
total 16
-rw-rw-r--+ 1 alice  alice  12 May 13 23:15 file_alice
-rw-rw-r--+ 1 bob    bob    12 May 13 23:15 file_bob
-rw-rw-r--+ 1 bower  bower  12 May 13 23:15 file_bower
-rw-rw-r--+ 1 deploy deploy 12 May 13 23:15 file_deploy
[alice@localhost share]$ rm file_deploy

Finally, the tricky bit. What happens when alice makes a directory?
[alice@localhost share]$ mkdir dir_alice;
[alice@localhost share]$ ls -l
total 12
drwxrwxr-x+ 1 alice alice  0 May 13 23:16 dir_alice
-rw-rw-r--+ 1 alice alice 12 May 13 23:15 file_alice
-rw-rw-r--+ 1 bob   bob   12 May 13 23:15 file_bob
-rw-rw-r--+ 1 bower bower 12 May 13 23:15 file_bower
[alice@localhost share]$ getfacl dir_alice
# file: dir_alice
# owner: alice
# group: alice
user::rwx
group::r-x
group:html:rwx
mask::rwx
other::r-x
default:user::rwx
default:group::r-x
default:group:html:rwx
default:mask::rwx
default:other::r-x

Because we passed -d to setfacl it instructs new directories to also inherit (and apply that inheritance to further subdirectories). So, now as user deploy we can add and edit existing files inside of that new subdirectory.
[alice@localhost share]$ touch dir_alice/file_indir_alice
[alice@localhost share]$ exit
exit
# sudo -u deploy /bin/bash
[deploy@localhost share]$ cd /var/www/html/share/dir_alice/
[deploy@localhost dir_alice]$ touch file_indir_deploy
[deploy@localhost dir_alice]$ rm file_indir_alice
[deploy@localhost dir_alice]$

Answer: You have mixed up semantics of sticky and setgid.
The sticky bit on a directory is used when multiple users are allowed to create files and directories in that directory, but they are only allowed to change those, which they created themselves, they are not allowed to mess with those contents created by other users. The /tmp directory is the typical use case for this.
The sticky bit is not inherited by subdirectories. There is no need for it to be inherited in order to satisfy its intended purpose. The subdirectories created in a sticky directory are supposed to be off-limits by default for everybody except the creator.
The setgid bit on a directory indicates that files and directories created inside that directory inherit group from the directory, instead of getting the current group of the user creating it. The setgid bit is inherited by new directories created inside the setgid directory.
The setgid bit could achieve part of the goal you are trying to achieve. It would achieve the part where the entire hierarchy of directories and files will have the same group (unless explicitly overridden).
It does however not guarantee that everything in there will be writable by the group. That can be achieved through umask setting.
The umask indicates a set of bits, which are not to be set on newly created files and directories. Typical values for umask are 0002, 0007, 0022, 0027, 0077. In your case you want those directories to be writable for the group, which means you want either 0002 which means what is created will be readable to everybody outside the group or 0007 which means what is created is inaccessible to everybody outside the group.
You need to ensure the umask is set at some point before creating new files or directories. The umask is inherited by child processes. Beware of files created outside that specific directory, since the umask is applied elsewhere as well, so anything created elsewhere will still be writable by the group, even if that is a different group from what is used on the /var/www hierarchy.
Answer: You could try making it harder to reset the permissions of the root directory by making it append only with chattr:
chattr +a /var/www/mysite


Android Studio can't find activity

Question: I am working with Android Studio 1.0 when suddenly, out of the blue I can not run my app on my phone because it is telling me that it can not find the default activity.
Changing the "default activity" to the specific activity I want to launch, ends in the error that apparently the activity I selected is not declared in AndroidManifest.xml.
Which also isn't true, because I did declare it in the .xml, I didn't remove it or add something new, it always has been there and now it doesn't want to work.
Thank you for reading and maybe answering / commenting. :D
Edit: This is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pack.aproject" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondPageActivity">

        </activity>
    </application>

</manifest>

Comment: Have you added the intent-filter with MAIN action and LAUNCHER category to your main activity?
Comment: @bigdestroyer Yes, I did that.
Comment: can you please share your AndroidManifest.xml
Comment: What is this with not posting codes thing? How can we help you if you dont provide us with your code? Obviously it's something wrong inside your code...not with your phone or Android Studio
Comment: @Android007 There you go, I included it.
Comment: Actually Android Studio has been buggy, so there is a very good chance it is IDE related.
Comment: @zgc7009 Ye, possibly, just getting on my nerves, it worked perfectly but now it doesn't.
Comment: can you post the mainactivity.java
Comment: Try doing a 'rebuild project' so it performs a clean rebuild. Unfortunately, sometimes studio will get a little confused with XML changes (but not nearly as bad as eclipse.)
Answer: you may need to refresh the IDE's cache.
File -> Invalidate Caches / Restart...

Android Studio can't find activity


What's the difference between creating a 'Content' or a new 'Pages>>Add Custom Page'?

Question: I'm working on a pre-established site. I've noticed that I can add new 'Content' (Content>>Add Content) or I can add a new Page (Structure>>Pages>>Add custom page).
The site seems to use an indiscriminate amount of both, though Content seems to be used more with templates for blog and product pages.
What are the differences between the two and in what scenarios should I use them?
Answer: Structure -> Pages menu link comes from ctools and it allows you to create more complex pages than your basic drupal core ones (Content -> Add Content link). This may include components comming from other modules (Panels, Fieldable Panel Panes, Views Content Panes and many other that intergrate with Ctools).
With Page Manager (and panels in general) you can create more complex versions of a page (or more, if you use the right contexts).


LetsEncrypt doesn't want to validate my domain

Question: This has been bugging me for the last couple of days, and I just can't seem to figure out what is going on. I have a new server I setup (using Vesta, with nginx). They have a built-in tool for using LetsEncrypt, and supposedly this has worked:

...and then the domain being edited:

The snginx.conf file has the settings in (and those files do indeed exist):
ssl_certificate      /home/admin/conf/web/ssl.steampj.com.pem;
ssl_certificate_key  /home/admin/conf/web/ssl.steampj.com.key;

I also have this when defining the server {  bit:
server {
    listen      443 ssl;
    listen      [::]:443 ssl;

I get no errors when restarting/reloading nginx. You when you go here, you get an error: https://steampj.com/

and:
I'm baffled as to why it's not working
Here is the full server {} condition for that domain:
server {
    listen      443 ssl;
    listen      [::]:443 ssl;
    server_name steampj.com www.steampj.com;
    root        /home/admin/web/steampj.com/public_html;
    index       index.php index.html index.htm;
    access_log  /var/log/nginx/domains/steampj.com.log combined;
    access_log  /var/log/nginx/domains/steampj.com.bytes bytes;
    error_log   /var/log/nginx/domains/steampj.com.error.log error;

    ssl_certificate      /home/admin/conf/web/ssl.steampj.com.pem;
    ssl_certificate_key  /home/admin/conf/web/ssl.steampj.com.key;

    location / {

        location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
            expires     max;
        }

        location ~ [^/]\.php(/|$) {
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            if (!-f $document_root$fastcgi_script_name) {
                return  404;
            }

            fastcgi_pass    127.0.0.1:9005;
            fastcgi_index   index.php;
            include         /etc/nginx/fastcgi_params;
        }
    }

    error_page  403 /error/404.html;
    error_page  404 /error/404.html;
    error_page  500 502 503 504 /error/50x.html;

    location /error/ {
        alias   /home/admin/web/steampj.com/document_errors/;
    }

    location ~* "/\.(htaccess|htpasswd)$" {
        deny    all;
        return  404;
    }

    location /vstats/ {
        alias   /home/admin/web/steampj.com/stats/;
        include /home/admin/web/steampj.com/stats/auth.conf*;
    }

    include     /etc/nginx/conf.d/phpmyadmin.inc*;
    include     /etc/nginx/conf.d/phppgadmin.inc*;
    include     /etc/nginx/conf.d/webmail.inc*;

    include     /home/admin/conf/web/snginx.steampj.com.conf*;
}

I did wonder if maybe the firewall was blocking, but it seems to be set as open in ufw:
root@com:~# ufw status
Status: active

To                         Action      From
--                         ------      ----
8181                       ALLOW       Anywhere
443                        ALLOW       Anywhere
8181 (v6)                  ALLOW       Anywhere (v6)
443 (v6)                   ALLOW       Anywhere (v6)

and then:
root@com:~# lsof -OnP | grep LISTEN
nginx      2382                     root   22u     IPv4              95181      0t0        TCP 220.127.116.11:443 (LISTEN)
nginx      2382                     root   45u     IPv6             264609      0t0        TCP *:443 (LISTEN)
nginx      2637                 www-data   22u     IPv4              95181      0t0        TCP 126.96.36.199:443 (LISTEN)
nginx      2637                 www-data   45u     IPv6             264609      0t0        TCP *:443 (LISTEN)
nginx      2638                 www-data   22u     IPv4              95181      0t0        TCP 22.214.171.124:443 (LISTEN)
nginx      2638                 www-data   45u     IPv6             264609      0t0        TCP *:443 (LISTEN)

UPDATE 2: I managed to get the ipv6 stuff going with http. It was the ufw blocking the port for some reason (disabled it, and ts fine... which is OK as we have iptables and fail2ban anyway)
I still can't get it to connect with openssl or curl on ipv4 though :/
root@steamdev2:~# curl -Iv4 https://steampj.com/
* Hostname was NOT found in DNS cache
*   Trying 184.108.40.206...
* Connected to steampj.com (184.108.40.206) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* SSLv3, TLS Unknown, Unknown (22):
* SSLv3, TLS handshake, Client hello (1):
* error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
* Closing connection 0
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

root@steamdev2:~# openssl s_client -connect steampj.com:443
CONNECTED(00000003)
139846633119256:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:s23_clnt.c:794:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 315 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
---

UPDATE 3: I'm not sure if this could be the issue, but I noticed that my other server (that I setup a couple of weeks ago), is using nginx 1.10.0, whereas this new one is using 1.11.13 ... maybe there is a bug?
Comment: "You when you go here, you get an error" - what kind of error do you get ? please describe it.
Comment: @sfk - do you not get an error? I've added some screenshots in for what I get in FF/Chrome. Apologies, I just assumed everyone would get the error, so didn't bother actually posting it =)
Comment: It actually works for me :

`curl -I https://steampj.com/
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 08 Apr 2017 08:43:34 GMT
Content-Type: text/html
Content-Length: 1045
Last-Modified: Fri, 07 Apr 2017 14:13:42 GMT
Connection: keep-alive
Keep-Alive: timeout=60
ETag: "58e79e96-415"
Accept-Ranges: bytes`
Comment: @sfk - what do you get with: `openssl s_client -connect steampj.com:443 2>/dev/null </dev/null | openssl x509 -noout -enddate` ? curl loads for me, but the browser doesn't (or https://www.sslshopper.com/ssl-checker.html#hostname=https://www.steampj.com )
Comment: Ok, it seems that it works for me with IPv6 (default for me) `curl -Iv6 https://steampj.com/` but not with `curl -Iv4 https://steampj.com/`
Comment: Mmmm odd. I've added the full `server {}` section for that domain in my post. Does that help at all? I'm sure I have it correct with `listen 443 ssl;    listen      [::]:443 ssl;`. Popping out for a bit, back in a little while :)
Comment: "This server could not prove that it is steampj.com; its security certificate is from com.steampunkjunkies.com. This may be caused by a misconfiguration or an attacker intercepting your connection." - You need to request the certificate for the domain you serve
Comment: @ptman - huh? The certificate works fine with ipv6, but not ipv4. Where are you seeing that message?
Comment: I typed steampj.com into my browser, but trying now it seems to work.
Comment: @ptman - so it works for you in the browser? I still get the "not safe" error message. The stupid thing, is that it DOESNT work with:  `curl -Iv4 https://steampj.com/`, yet it does on ipv6:  `curl -Iv6 https://steampj.com/` .. I just don't understand why :/
Comment: yes, first it didn't work, but now it does.
Comment: @ptman - mmm, what the heck! Still not working for me (in any browser, and https://www.sslshopper.com/ssl-checker.html#hostname=https://www.steampj.com also tells me its broken). Eugh :/
Comment: FYI, when using http instead of https, the problem is with ipv6 (ipv4 is fine). So exactly the opposite behavior than with https. So I assume that nginx still requires `ipv6only` option with the `listen [::]`directives. See here for additional guidelines https://bashelton.com/2014/02/nginx-v1-4-5-and-ipv6/
Comment: @sfk - mmm odd, the prot thickens! I didn't even bother checking the non-ssl version, as I just assumed that was fine. I'll have to do some more digging tomorrow. So frustrating!
Comment: @sfk - I found the issue with the non-ssl not working on ipv6. It was the ubuntu firewall blocking it. However, the issue still exists with accessing the ssl version on ipv4 :( I've added "**update 2**" above... does that give any other hints?
Answer: Your certificate seems to work just fine, even on Android that has strict policy.
As based on comments:

Almost everyone else sees the certificate ok now.
You still get errors.
LetsEncypt couldn't still validate it.

I checked your SOA serial, which is 2017040741 from yesterday and your TTL is set to 24 hours. The problem is most likely that there's wrong IP address in the DNS cache of your recursive DNS server, as well as the one LetsEncrypt uses. (Anyone helping you hasn't cached it before.)
Try again tomorrow. From here, It's also possible to use shorter TTL, e.g. 21600 for 6 hours.

UPDATE: Yesterday the certificate seemed to be fine but now I have ERR_SSL_PROTOCOL_ERROR.
With verbose mode of curl I can see the actual problem:
curl -v -ipv4 https://steampj.com/
* About to connect() to steampj.com port 443 (#0)
*   Trying 188.8.131.52...
* connected
* Connected to steampj.com (188.8.131.52) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs
* SSLv3, TLS handshake, Client hello (1):
* error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
* Closing connection #0
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

You usually get SSL23_GET_SERVER_HELLO when there's something else listening on port 443. In most cases this happens when HTTPD is listening on port 443 without SSL, but this time that's not the case, because you get ERR_INVALID_HTTP_RESPONSE from http://steampj.com:443/, and as netcat shows:
nc -v steampj.com 443
DNS fwd/rev mismatch: steampj.com != li1097-44.members.linode.com
steampj.com [220.127.116.11] 443 (https) open
GET / HTTP/1.1
▒▒▒PuTTY

As your nginx was listening to port 443 based on lsof -OnP | grep LISTEN the problem is most likely in the Nginx configuration.

Check whether you have another server {} section unnecessarily having listen 443 and remove it. Also that I had CApath: /etc/ssl/certs instead of configured /home/admin/conf/web/ suggests the same.
Check that you surely have ipv6only=on. You have:
server {
    listen      443 ssl;
    listen      [::]:443 ssl;

According to Nginx ngx_http_core_module documentation on Directive listen:

ipv6only=on|off
this parameter (0.7.42) determines (via the IPV6_V6ONLY socket option)
  whether an IPv6 socket listening on a wildcard address [::] will accept
  only IPv6 connections or both IPv6 and IPv4 connections. This parameter
  is turned on by default. It can only be set once on start.

Despite that by default this option should be on, you should see whether it is set off somewhere in the configuration and update both your server { sections to have:
server {
    listen   443 ssl;
    listen   [::]:443 ipv6only=on ssl;

As this parameter can only be set once on start, it's crucial to have it on on the default_server configuration as will also affect all further servers.
Comment: Your NOW have shorter `TTL` in `steampj.com. 300 IN A` but still the longer in `steampj.com. 86400 IN AAAA` and in `SOA` minimum TTL. But the most important thing is that if already cached, TTL change only applies after the seconds current TTL has left in the cache.
Comment: Mmm thats an interesting point. The DNS *was* set to "default", but I changed it to "300 (5 minutes)" yesterday. I'll give it a whirl on monday, to see if it helped :) Fortunately this is only a test domain (to make sure the server is ready to put live sites on), so I'm hoping that's all it is
Comment: @Esa_Jokien , unfortunately that didn't work :( The "curl" test query works fine for ipv6, but not ipv4. Both of them return the IP I'm expecting: `curl -Iv4 https://steampj.com/` and `curl -Iv6 https://steampj.com/` ... this is so frustrating. I've never had any issues like this before with nginx :(
Comment: Is there another `server {}` sections having `listen 443`? IPv4 on `126.96.36.199:443` now gives `ERR_SSL_PROTOCOL_ERROR`, while yesterday it worked just fine.
Comment: @Esa_Jokinen yes, there is (2 `server {}` bits in this .conf). One is for steamj.com and the other for com.steampunkjunkies.com). I've commented one of them out, and in the steampj.com one I have: `listen [::]:443 ssl; listen 443 ssl;` ... still no joy though :/  Right, I'm off for a bike ride to de-stress!
Comment: @Esa_Jokinen thanks for the suggestion. I'm using VestaCP to manage this. It creates /home/admin/conf/web/[nginx & snginx].conf files. One for standard, and the other for ssl. You mentioned about Apache ... is there somewhere I can check? We do have Apache2.4 on there as a reverse proxy for the Perl scripts
Comment: I added a third thing to check: add `ipv6only=on` parameter to your `listen   [::]:443 ipv6only=on ssl;` on all your `server {` sections and restart Nginx. That'll probably fix this.
Comment: @Esa_Jokinen thanks, but no joy. Isn't that set to "on" by default now anyway? (from what I was reading on the 1.11.0 release blog article)
Comment: Yes, it SHOULD be set `on` by default as described on official documentation. Then, many unofficial tutorials mention that there have been problems and you have to manually set it.
Comment: @Esa_Jokinen ah ok. Unfortunately it didn't help though :(
Answer: Ok well this isn't really an "answer" as such, but I have managed to get it working.
I started from scratch, and re-installed VestaCP from scratch with:
curl -O http://vestacp.com/pub/vst-install.sh

bash vst-install.sh --nginx yes --apache yes --phpfpm no --named no --remi yes --vsftpd yes --proftpd no --iptables yes --fail2ban yes --quota no --exim yes --dovecot yes --spamassassin yes --clamav yes --mysql yes --postgresql no --hostname com.mysite.com --email firstname.lastname@example.com --password xxx

I then edited /usr/local/vesta/data/templates/web/nginx/default.tpl, so it also had:
listen      [%ip%]:%proxy_port% ssl;

(for some reason it only has IPv4 there, not sure why).
I then went in and setup the domain, and voila -- it worked!
Comment: So actually it must have been one of the conditions mentioned in my answer, but the Nginx configuration was tampered by a web hosting control panel making it impossible to find the cause without complete re-install. There are good reasons why [Serverfault doesn't give support for web hosting control panels](http://meta.serverfault.com/questions/8094/where-can-i-ask-questions-about-web-hosting-control-panels).
Comment: @EsaJokinen - ah I wasn't aware that was a case on Serverfault. Although, this wasn't really a CP issue, but an nginx one (the config files look the same as I was using before, but they just "work" now). Thanks for your help though :)


How to solve equations like $8^{2n+1} = 32^{n+1}$

Question: I have stumbled on this question, and there are a few questions after it of the same type. How do I solve it and what is the right approach for this kind of question?
$$8^{2n+1} = 32^{n+1}$$
I need to find the value of $^n$. Step by step if at all possible please. My approach was to start like:
$$(2^3)^{2n+1} = (2^3 \times 2^2)^{n+1}$$
Then I was lost as to how to proceed. Do I need some sort of prerequisite knowledge that I am missing before attempting this? The book has only shown $7$ laws of indices before asking this question.
Answer: The idea of reducing everything to powers of $2$ is good, but you didn't carry it out correctly on the righthand side: you should have
$$\left(2^3\right)^{2n+1}=\left(2^5\right)^{n+1}\;.\tag{1}$$
Now use the fact that $\left(a^b\right)^c=a^{bc}$ to rewrite $(1)$ as
$$2^{3(2n+1)}=2^{5(n+1)}\;,$$ or $$2^{6n+3}=2^{5n+5}\;.$$
This is the case if and only if $6n+3=5n+5$, so all that remains is to solve that simple linear equation for $n$.
Comment: I almost forgot about $(a^b)^c=a^{bc}$ Practice may make me think of that more quickly.
Answer: The general technique is to write both sides with the same base and then equate the powers.
$(2^3)^{2n+1}=(2^5)^{n+1}$
$2^{3(2n+1)}=2^{5(n+1)}$
$3(2n+1)=5(n+1)$
$6n+3=5n+5$
$n=2$
Answer: The other solutions to this problem presuppose two factors:
1) the two bases are themselves both powers of some common base;
2) the solver recognizes that fact.
But suppose that the bases 8 and 32 in the problem above were replaced with 2197 and 371293.  Or even worse, with 2197 and 317293.
A more "bullet-proof" technique would be to get the unknown out of the exponents by taking logarithms of both sides.  The equation to be solved becomes:$$(2n+1)\log(8)=(n+1)\log (32)$$When you divide log32 by log8 and get $\frac{5}{3}$, it's clear that you missed some subtle point. but you're already well on your way to the solution, and the next time the numbers might not work out so neatly...
Comment: +1 and probably going from 2^a = 2^b ==> a == b is implicitly taking log_2 of both sides anyway
Answer: Denote $x=2^n$ and find $x$ out your equation..


how to convey auth token in header with help the fetch?

Question: I'm need send user data at request to my endpoint (rest api), but gets 401 error only if make request from the js side. If make request from Postman, I get 200 status. I did everything as in the documentation. for reference: make request from Nodejs. Thanks
var token = 'Token 897d3c9991952bc715fcf6c3e262e5b3866342';
var myHeaders = new Headers();
myHeaders.append('Authorization', token);
fetch(this.domain + '/v1.0/user/data/', {method: 'GET', headers: myHeaders, mode: 'no-cors'})
.then(response => {
        if (response.ok) {
            return response.json();
        } else {
                throw new Error('error');
        }
  })

Comment: Are you sure that it should be `Token` and not `Bearer`?
Comment: What "documentation" ?
Comment: https://developer.mozilla.org/ru/docs/Web/API/Fetch_API/Using_Fetch Yes, sure. From the postman works fine
Comment: Look at the exact configuration you have in PostMan. Check the details. If this is Basic HTTP Authentication, it should be Basic instead of Token.
Comment: I make from this example: http://cheng.logdown.com/posts/2015/10/27/how-to-use-django-rest-frameworks-token-based-authentication
Comment: is token correct? try appending token to url as query param e.g. fetch(this.domain + '/v1.0/user/data/?auth=' + token,
Answer: Check this link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch or you can use axios to make request.
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('http://<host>:<port>/<end-point>?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

fetch:
// Example POST method implementation:

postData(`http://<host>:<port>/<end-point>`, {answer: 42})
  .then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
  .catch(error => console.error(error));

function postData(url = ``, data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, cors, *same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, same-origin, *omit
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "follow", // manual, *follow, error
        referrer: "no-referrer", // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses response to JSON
}


Remotely bring a computer out of screen saver

Question: Is there any way to remotely send a command to bring a Windows 8 machine out of screen saver (blank screen)?  Maybe sending a down arrow command.  We are putting together a demo for a trade show and one of the request was to be able to turn on several displays at once that will be showing the customer's software.  Any ideas would be greatly appreciated?
Answer: If it were me, and I couldn't just disable the screensaver, I'd install some remote control software (like a flavor of VNC) and shoot an innocuous keypress or mouse movement to them. There are a variety of tools out there that can do that, including command-line tools that could be scripted.
Comment: I have looked into VNC and that may be what I have to use.  Was hoping for a script that could send a "down arrow" command or something similar.  Need to do this for 6 machines at the same time.
Comment: There are a whole bunch of command-line VNC clients out there. Here's a Python-based one, just based on a 30 second search: https://github.com/sibson/vncdotool


Devel output on hooks called during cron run

Question: I'm implementing a hook that is called if certain conditions are met during a cron run.
(Specifically hook_bounce_mails_blocked($mails) from the Bounce module)
The hook is triggered, but any output from dpm() functions is never shown. I do see output from var_dump() after cron finishes.
Is this normal behaviour? Is there a way to get devel output shown once cron finishes?
Comment: @DavidCsonka Messages go in the session, so unless you can hijack the session the cron job happened in, the answer's got to be "no". Using other logging is the right way to go (as in loolooyyyy's answer)
Comment: "Is there a way to get devel output shown once cron finishes?" I would like to know that as well.
Answer: You should use the function dd() to log something during cron.
Here is the doc: https://api.drupal.org/api/devel/devel.module/function/dd/7
It will log the output to a file, which later you can investigate. I think you must have private file path set.
you could use something like this, But be careful about XSS!
$export = var_export($var, TRUE) // TRUE will cause var_export to return the output not print it.
$export = nl2br($export); // Convert new lines to
 tag for display in HTML
$export = strreplace(' ', ' '); // Again convert whitespace to HTML specific chatacter
watchdog('my_debug', $export); // That's it!

or even easier:
but again be careful about CSSF and XSS
watchdog('my_debug', '
' . var_export($variable) . '
');

dd is the safe drupal way to go.

Update
From comments so you wont miss:

... better than dd() is ddl(), from the drupal_debug_log module that enhances > the devel module... –  DrCord

Important point to developers.
If you search drupal.org modules there are many more to  make development easier. After you found and used them, it would sound impossible to go without them (devel_themer to name one). An example search.
Comment: Even better than dd() is ddl(), from the drupal_debug_log module that enhances the devel module. ddl takes what would have been output into the file and outputs it to a log area. Basically necessary for debugging cron and ajax. Also is really useful for still getting debugging output from a script that is failing partways through.


BT Router and Assign Multiple IP Addresses

Question: We have bt router model: BT2700HGV , 2wire, can someone tell me if this router supports this
Scenario is I have 2 webservers and want them to be available publicly , thanks
update:
A bit more information;
I attached pictures of my router system information, how did I assign the public IP to my router and to my Web Server. everything seems okay but I cant access to my web server from outside of my network. Firewall log says "Unknown inbound session stopped" as you can see in the picture.
FirewallLog http://img412.imageshack.us/i/33374963.png/ , PublicIPOnRouter http://img704.imageshack.us/i/73894778.png/ , SystemInfo http://img704.imageshack.us/i/41567708.png/ , ClientIPSettings http://img85.imageshack.us/i/98347985.png/
http://img412.imageshack.us/i/33374963.png/ ,
http://img704.imageshack.us/i/73894778.png/ ,
http://img704.imageshack.us/i/41567708.png/ ,
http://img85.imageshack.us/i/98347985.png/
Answer: Yes, you can configure port forwarding on that model. The problem you're going to have is that you can't port forward HTTP traffic from a single public ip address to two different internal ip addresses. The possible solutions are:

Obtain another ip address from your ISP.
Run both web sites on the same server and use host headers to differentiate the two.
Run one of the web sites on a port other than port 80.
Comment: i have 5 ip address already but dont know how to introduce them to my router
Comment: You'll probably need to look at the router's manual to see how to configure it to NAT multiple public ip addresses to multiple private ip addresses.
Comment: I put some more info about the situation. manual says, as long as I configure client manually (static IP), i dont need to deal with nat.
Comment: It looks like the traffic is getting to the router but the router is blocking it. Can you find a link to an online user guide for your model router? If so, I'll look through it and see if I can figure things out.
Comment: this is the manual, http://home.singtel.com/mio/2700HGV-User-Guide.pdf

also I came across this post on bt forum , http://btb.lithium.com/t5/Broadband-and-internet/trying-to-use-our-static-IPs-inside-our-BT-2700-HGV/m-p/4718#M929 it seems that everything is OK what im doing. i cant see what im missing. thanks
Comment: I'm not sure but I think maybe the Auto Firewall Open checkbox doesn't do what you think it does. Try looking at the firewall settings, referenced on pages 35-51 of the manual.
Comment: it worked if I change the server IP to dynamic first and assign a wan IP on the NAT section of the router, i can see it in the listed computers although it gets IP address from the other companies router which is on the different subnet. And changing it back to static IP did the trick. However now what happened is that one of this server is not displayed in the nat list now so again it doesnt work. is there any way i can force this server to use my own router?


Can free objects be described in these terms, or am I kidding myself?

Question: Suppose $T$ is an equational theory, and let $T[X]$ denote the theory obtained by adjoining a set of constant symbols $X$ to the theory $T$, subject to no axioms.
Is the free $T$-algebra generated by $X$ isomorphic to (the forgetful image of) the initial object in the category of $T[X]$-algebras? Can free objects be described in these terms, or am I kidding myself?
Answer: You are right. A $T[X]$-algebra is the same as a $T$-algebra $A$ equipped with a map $X \to |A|$ to the underlying set. Morphisms are commutative diagrams in the obvious sense. Now the definition of a free $T$-algebra on $X$ coincides with an initial object in the category of $T[X]$-algebras.
More generally, let $F : C \to D$ be left adjoint to $G : D \to C$. If $X \in C$, then $F(X)$ together with the unit $X \to G(F(X))$ is an initial object in $X \downarrow G$.


Numpy.ma polyfit function for masked arrays crashes on integer input

Question: The numpy polynomial fit function for masked arrays, ma.polyfit, crashes on integer iput:
import numpy.ma as ma
x = ma.arange(2)
y = ma.arange(2)
p1 = ma.polyfit(np.float32(x), y, deg=1)
p2 = ma.polyfit(           x , y, deg=1)

The last line results in an error:
ValueError: data type <type 'numpy.int64'> not inexact

Why can't I fit data with integer x-values (it's no problem with the normal numpy.polyfit function), is this a (known) bug?
Answer: It is indeed a bug from numpy.ma : the rcond (a parameter to exclude some values ) takes len(x)*np.finfo(x.dtypes).eps as a default value, and np.int32 does not have any epsfield (because an int does not have a relative precision).
import numpy.ma as ma
eps = np.finfo(np.float32).eps

x = ma.arange(2)
y = ma.arange(2)
p1 = ma.polyfit(np.float32(x), y, deg=1, rcond = len(x)*eps)
p2 = ma.polyfit(           x , y, deg=1, rcond = len(x)*eps)

I've looked quickly into numpy's issues, and this bug does not seems to figured there. It might be a good idea to raise a new issue : New Issue
Comment: Thanks for reassuring, I have submitted a new issue.
Comment: BTW, instead of `import np.finfo(np.float32).eps as eps`, I guess you meant `eps = np.finfo(np.float32).eps` ...? :-)
Comment: it's identical : it's a question of style :p
Comment: That's curious: `import np.finfo(np.float32).eps as eps` gives me a syntax error ...
Comment: oups you're right : I didn't run this part of the code. I fix it immediately.


FDR correction stronger than Bonferroni?

Question: Is it possible to get a situation where, in a multiple-testing scenario, for some individual tests, the Benjamini&Yukatieli (2001)-correction ends up being more stringent than Bonferroni? I.e. that for some tests,
$$
p_{\text{Bonferroni}} < p_{BY}
$$
I seem to have encountered this with data and while I have no conceptual problem with it (the procedures are after all quite different), but would have intuitively said that with every correction any p-value can be at most as large as with Bonferroni.
Comment: related: https://stats.stackexchange.com/questions/59681/why-is-controlling-fdr-less-stringent-than-controlling-fwer/143852#143852
Comment: @ChristophHanck The statement that any control of FWER will trivially also control FDR would also support the idea that any FDR-corrected p-value will be at most as large as its FWER-corrected cousin. But again, it doesn't offer a direct proof that the reverse can't occur for singular tests in a multiple testing situation
Comment: OK, this might be more relevant then: https://stats.stackexchange.com/questions/238458/whats-the-formula-for-the-benjamini-hochberg-adjusted-p-value
Answer: It turns out that indeed, this can and does trivially happen, as tested on two different implementations in Python, from statsmodels and pingouin, with only two tests and p-values of 0.01 and 0.1.
from pingouin import multicomp as pingouin_multicomp
from statsmodels.stats.multitest import multipletests as statsmodels_multicomp
pvals = [0.01, 0.1]

With this,
pingouin_multicomp(pvals, method="bonf")[1] -> array([0.02, 0.2 ])
pingouin_multicomp(pvals, method="fdr_by")[1] -> array([0.03, 0.15])
statsmodels_multicomp(pvals, method="fdr_by")[1] -> array([0.03, 0.15])

Unless there is some deep conceptual mistake I made, it would appear that the smaller value gets corrected more.
Interestingly, this does not seem to happen with the original Benjamini & Hochberg (1995) procedure (as suggested by the method outlined in the post linked by Christoph Hanck). If anyone wants to outline the difference, I'll shift the accept; for now this is at least what seems to be confirmation that I'm not crazy.


Why would a composer arrange chords such that hands cross on piano

Question: I was looking at Rachmaninov's Prelude in C Sharp Minor.
In the first section, a number of chords are played. The way they are written indicate that the pianist has to overlap his hands partially, such as here:

However, this could also potentially be played as follows - no longer requiring hand-crossing:

What would make a composer choose one of the two? I am not very familiar with music theory, but I would imagine playing the non-crossing version is easier?
Comment: I've neither played nor studied this piece, so this is purely speculation, but I would guess that it's because octaves are easier to find. We play octaves all the time and our hands automatically make that interval with no thought. Split the way it's written, it's a little less mental work to get the fingers to the keys.
Comment: Because it makes you look *awesome.*
Comment: I hadn't thought of that. I do prefer the octave version because it's what I learned, but my girlfriend has very small hands and can not reach a full octave, hence we were rearanging the piece so she can play it. It was only then that I realized how the rearanged version seems to be simpler (because a lot of the times, both hands play the same, just one octave apart)
Comment: Pianist: Crossing hands on the keyboard is just wrong!   Composer: Hold my beer...
Answer: The crossed version is quite easily playable (assuming you can reach octaves with ease), and it makes it easier to control the balance between the notes making the theme. So in the first chord, the RH plays two C#s, LH plays two Es. It is easier (for example) to bring out the notes in the RH, than to bring out the upper of two notes in each hand. (Well, yes, there's the third note in between, and that just has to be shared across the hands.)
As Matt Putnam said, it may also be simply easier for finding the notes. I expect Rachmaninoff just wrote down the notes the way he found himself playing them.
Answer: Note that the top notes of the left hand part are all white keys, but the bottom notes of the right hand part are black keys. So the "hand crossing" is easier than it might seem at first glance. It also makes it technically easier to deal with the fact that this is really music written in two parts, each doubled in octaves, with more notes added (and played slightly softer!) to fill up the chords.
Rachmaninov was a virtuoso pianist himself, as well as a composer. Details like these were not "accidental"!