text:
Q: Excel spread sheet if statement I'm working on an excel spreadsheet and want an if statement in a cell that allows user input if a certain condition is met, and calculates a value otherwise.  Something like
=if(condition true, whatever user wants, 5*$A$1,)

Is there a way to do this?

A: You won't be able to have the user-input in the same cell as your formula. (without using VBA)
To do it without VBA you will need to use at least 2 cells, one with your formula, and one for the user value
There are a couple of ways you can do it with VBA
Heres a simple one, but would not really recomment it, if lots of cells use this it you'll get lots of inputboxes!
usage: =IF(condition, UserInput(), false result)
Public Function UserInput() As Integer ' used integer as an example
Dim Result As Variant

    Result = Application.InputBox("Enter an Integer", "Input Required", , , , , , 1) ' inputbox, the final 1 makes it only accept numbers
    If VarType(Result) = vbBoolean Then
        UserInput = 0 ' the default value
    Else
        UserInput = CInt(Result) ' make sure its an integer
    End If
End Function

Another one, would involve using the selection change and cell change events to read the initial value of the cell being changed, and allow the change (adding the value into the initial formula's "true" block or deny the changes by reverting the cells formula to the initial one.

A: You either need to use a Macro to update only null columns or you need to allow user to enter values in another column and then merge the values in this column, third option is to fill it with formulas and allow people to edit it to any value if they want only values

A: =IF(C11="Economic",120,IF(C11="DBServer",480,IF(C11="Gamer",120,IF(C11="Custom",M15,"null"))))

My example was to build an optimal computer given certain constraints.  There was a drop down with Economic, DBServer, Gamer, and Custom as options.  If you chose economic, then 120 would show up in the cell, DbServer meant 480, etc.  If you selected custom, then it would refer to cell M15 which was a user input that didn't affect the code of the cell you wanted the final number  in.


text:
Q: Обновление файла локализации в Django без перетирания Делаю локализацию сайта.

*

*Выполняю команду: makemessages -l ru;

*Получаю django.po файл;

*Редактирую этот файл;

*Нахожу на сайте непереведённое слово;

*Оборачиваю это слово в {% trans 'word' %}.

*Запускаю повторно makemessages;

После запуска makemessages повторно - все переводы из django.po стираются.
Как не перетирать имеющиеся переводы в файле django.po, а дополнять новыми?
UPD:
Перетирание вызывает сочетание параметров makemessages -l ru -e html
До команды:
#: env/lib/python3.5/site-packages/sorl/thumbnail/admin/compat.py:61
msgid "Clear image"
msgstr "Удалить картинку"

После команды:
#~ msgid "Clear image"
#~ msgstr "Удалить картинку"

Структура:

Команда makemessages запускается из ИДЕ от manage.py проекта.
Расположения сгенерированного django.po:

Строка из base.py:
LOCALE_PATHS = [os.path.join(BASE_DIR, 'stroyprombeton/locale')]

A: Команда makemessages задумана для создания файла переводов django.po из ВСЕХ файлов ВСЕГО проекта (или отдельного приложения, если перейти в каталог с ним). Соответственно, он заменяет, а не дополняет файл переводов, так и задумывалось.
Соответственно, -e html указывает команде просматривать файлы только с расширением html, в итоге только они и будут считаться для makemessages всем проектом, а все фразы, которых в html-файлах нет, будут убраны из po-файла.
Собственно, достаточно убрать -e html, чтобы фразы не убирались.
Однако makemessages обрабатывает все файлы в текущей директории, а, как выяснилось в комментариях, в текущей директории есть и виртуальное окружение env, в которой установлена джанга, и makemessages добирается и туда и выковыривает все внутренние фразы для перевода. Но в этом нет никакой необходимости: переводы внутренних фраз уже лежат в env/lib/python3.5/site-packages/django/conf/locale/ru/LC_MESSAGES/django.po (и ещё в 12 файлах) и будут автоматически подхвачены джангой, и нет никакой необходимости переводить их повторно.
Чтобы makemessages не лез в каталог env, можно:

*

*запускать его в каталоге с приложением: cd stroyprombeton; ../manage.py makemessages -l ru

*добавить каталог в игнорируемые: ./manage.py makemessages -l ru --ignore env
P.S. Рекомендую для удобства создать или дополнить Makefile:
.PHONY: messages compilemessages

PYTHON?=python

messages:
    cd stroyprombeton && $(PYTHON) ../manage.py makemessages -l ru

compilemessages:
    cd stroyprombeton && $(PYTHON) ../manage.py compilemessages

(у compilemessages опции --ignore почему-то нет)
Тогда достаточно будет выполнить команду make messages для обновления django.po и make compilemessages для создания файлов mo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery slideUP/DOWN working funny In my code below, when I select the radio button marked 'yes' it does slide down. But when I click on the one marked 'no' it doesn't slide up. Why is this?
html:
Yes<input type="radio" name="teacher" id="teacher" value="yes"/>
No<input type="radio" name="teacher" id="teacher" value="no"/>

jquery:
$("#teacher").click(function() {
    if($(this).val() === "yes")
    {
        $("#teacher-info").slideDown();
    }
    else if($(this).val() === "no")
    {
        $("#teacher-info").slideUp();
    }
});

A: You have two elements with an id of teacher.
id is meant to be a unique property (only one element has one particular id) and jQuery assumes that to be true. If you have two elements with the same id, jQuery always picks the first one.
That being said, the solution to your problem is to change the id to a class, which is designed to be used for many elements.
HTML:
Yes
<input type="radio" name="teacher" class="teacher" value="yes"/>

No
<input type="radio" name="teacher" class="teacher" value="no"/>

JavaScript:
$(".teacher").click(function() {
    if($(this).val() === "yes")
    {
        $("#teacher-info").slideDown();
    }
    else if($(this).val() === "no")
    {
        $("#teacher-info").slideUp();
    }
});

By the way, since your radio buttons have only two states (yes and no), your code can be simplified:
$(".teacher").click(function() {
    if ($(this).val() === "yes") {
        $("#teacher-info").slideDown();
    } else {
        $("#teacher-info").slideUp();
    }
});

A: For getting radiobutton values in Jquery you can simply do:
$('input:radio[name=teacher]:checked').val();

First of all change your code and add an class:
Yes
<input type="radio" name="teacher" class="teacher" value="yes"/>

No
<input type="radio" name="teacher" class="teacher" value="no"/>

So now change your code like this:
$(".teacher").click(function() {
    var btnValue = $('input:radio[name=teacher]:checked').val()
    if(btnValue === "yes")
    {
        $("#teacher-info").slideDown();
    }
    else if(btnValue === "no")
    {
        $("#teacher-info").slideUp();
    }
});


text:
Q: Django group permission activate If you have django.contrib.auth in your INSTALLED_APPS django will automatically create add, change, delete and view permissions to every model in your system (or any one you add later). These are stored in auth_permission.
In django doc, here is what we can read under Groups section:
django.contrib.auth.models.Group models are a generic way of categorizing users so you can apply permissions, or some other label, to those users. A user can belong to any number of groups.
A user in a group automatically has the permissions granted to that group. For example, if the group 'Site editors' has the permission can_edit_home_page, any user in that group will have that permission.
I've a group with no permission at all (call it NADA) and I've assign that group to a specific user (let's call him Pierre). Pierre can still connect and create, update, delete or view anything on my web interface.
How can I make it working? There's few or no doc on the web for native Django Permission.

*

*I've read this nice publication
django-permission-apps-comparison.

*I know I could install django-guardian, django-role-permissions or
django-rules...

*I know we can manage access via middleware or decorator But since django IS creating these tables for us (user, groups, permissions and group_permissions)

I thought it was extremely simple to implement CRUD access to any model class!
Wrong?
Do I miss something?
Note: Working with Python3.6 and Django 2.1.3

A: Django permissions are simple. As far as I understand your question, you are trying to create a user with no permission and he should not see any entries on the Django admin.
First thing is to make sure the user is not marked as "superuser", the superuser sees everything no matter which group they are added in.
If he is not a superuser and is still able to see the model then you should make sure he is not part of multiple groups. If a user is in multiple groups then a union of all permissions is what is applied to them. This link will give you more details on different flags for a user https://djangobook.com/users-groups-permissions/. Let me know if this helps.


text:
Q: How to interact with Cooca objects in an application without an API (Skype) I'm trying to make it possible for an application to interact with Skype for Mac, which would be fine except the Skype API is no longer supported (I've heard that it does work, but not reliably: they've replaced it with URI, which can't deal with messages, if I remember correctly). I'm reasonably sure that Skype for Mac uses the Cocoa framework, based on the fact that I can toggle Text-to-Speech and use the system autocorrect features in the text boxes.
It's most important that I'm able to send messages (because I can probably use the Notification Center to deal with receiving them), so I'm wondering if there's a way to use a tool like AppleScript to interact with the text boxes and send messages. If that's impossible, would you suggest a tool to use to simulate Skype and user input?
The entire project that I'm trying to do is to use Discord and Skype at the same time, so I planned to have a Discord bot sending data to my Skype wrapper application which runs on my home computer.
Sorry if this question is overly vague or nonsensical, I'm just having problems figuring out where to start with this project.


text:
Q: WebView works with react-native-router-flux NavBar but not with shoutem/ui NavigationBar When I try to use a custom NavigationBar with a WebView my NavigationBar's back button isn't clickable/pressable
Router.js
  render() {
    return (
      <Router
        hideNavBar={true}
      >
        <Scene key='root' passProps={true}>
          <Scene
            key='Posts'
            title='Posts'
            component={PostList}
            passProps={true}
            initial={true}
          />
          <Scene
            key='Random'
            title='Random'
            component={Random}
            passProps={true}
            style={{paddingTop: 70}}
          />
          <Scene
            key='Login'
            title='Login'
            component={Login}
            passProps={true}
            style={{paddingTop: 70}}
          />
          <Scene
            key='Post'
            title='Post'
            component={Post}
            passProps={true}
          />
        </Scene>
      </Router>
    );
  }

Post.js
import {
  NavigationBar,
  Title,
} from '@shoutem/ui'

class Post extends Component {
  render() {
    console.log(this.props.uri)
    return (
      <View
        style={styles.main}
      >
        <NavigationBar
          centerComponent={<Title>{this.props.title}</Title>}
          hasHistory
        />
        <WebView
          source={{uri: this.props.uri}}
          style={styles.webView}
        />
      </View>
    )
  }
}

However, if I remove the WebView and only render the NavigationBar in Post.js the back button is clickable.  If I remove the custom NavigationBar from Post.js and use the default router in Router.js the back button is clickable and the WebView is visible.

A: I got it to work by passing a custom component as the navBar prop in Router.js
Router.js
import TopNav from '../components/TopNav.js'

class AppRouter extends Component {
  render() {
    return (
      <Router
        navBar={TopNav}
      >
      ...
      </Router>
    )
    ...

TopNav.js
import React, { Component } from 'react'
import { StyleSheet } from 'react-native'
import {
  Actions,
  ActionConst,
} from 'react-native-router-flux'

import {
  NavigationBar,
  Title,
} from '@shoutem/ui'

import DrawerSwitch from '../components/DrawerSwitch.js'

export default class CustomNav extends Component {
  render(){
    return (
      this.props.hasHistory ?

      <NavigationBar
        hasHistory
        navigateBack={Actions.pop}
        centerComponent={<Title>{this.props.title}</Title>}
      /> :
      <NavigationBar
        leftComponent={<DrawerSwitch iconName='sidebar'/>}
        centerComponent={<Title>{this.props.title}</Title>}
      />
    )
  }
}


text:
Q: Using css only, position div within another div that uses vh unit I'm trying to position a div within another div where the height of the parent is defined using vh unit.
Basically, what I need to do is to have the child height = parent height - 50px.
The parent max-height should be 80% of the height of the screen.
The child height should have a scrollbar to display long content.
I tried a couple of different things but nothing seems to work.
This is what I tried:
.wrapper {
    background: yellow;
    max-height: 80vh;
    width: 300px;
}

.body {
    background: pink;
    position: absolute;
    bottom: 50px;
    overflow-y: auto;
    top: 0;
}

http://jsfiddle.net/qLhhk46n/
Do you have any idea?
Thanks

A: Since you're using viewport units (css3 feature), you can use calc to do the math.

A: Using calc is the solution, but you gave the wrapper the max-height of 80vh. As the child element will be smaller, the parent element will be adjusting to that size (I hope I'm understanding you right, if you didn't want the parent element to be bigger than the child element, making the child element 50px smaller wouldn't make sense). So you need to change it from max-height to height. Link
.wrapper {
    background: yellow;
    height: 80vh;
    width: 300px;
}

.body {
    background: pink;
    position: relative;
    overflow-y: auto;
    height: calc(80vh - 50px);
    height: -webkit-calc(80vh - 50px);
    height: -moz-calc(80vh - 50px);
    height: -o-calc(80vh - 50px);
    height: -ms-calc(80vh - 50px);
}

A padding for .wrapper would do it, too.


text:
Q: Crash due to unaccessable memory in shared memory on Windows 10 I created a shared memory using CreateFileMapping and get a view using MapViewOfFile:
  HANDLE hMappedFile =
    CreateFileMapping(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(nSharedMemorySize), L"some-file-identifier")

void* lpViewOfData = MapViewOfFile(m_hMappedFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);

Then I cast lpViewOfData to unsigned  int *
unsigned int *address= reinterpret_cast<unsigned int *>(lpViewOfData)

when writing to the address, the process crashed
for(size_t i=0; i<len; ++i){ // len is not out-of-rangle
    address[i] = i;
}

I dumped the memory with windbg and get some ?? in the shared memory,which means unmapped address according to ?? in memory locations.
000001c7`47bc0ff0  00000b18 00000b1a 00000c79 00000b1a
000001c7`47bc1000  ???????? ???????? ???????? ????????
...// bad
000001c7`47bc1ff0  ???????? ???????? ???????? ????????
000001c7`47bc2000  00000000 00000000 d3304ef3 10f7808e
...
... // good
...
000001c7`47c2eff0  47c2f000 000001c7 00000000 00000000
000001c7`47c2f000  ???????? ???????? ???????? ????????
... // bad
000001c7`47c2fff0  ???????? ???????? ???????? ????????
000001c7`47c30000  00000000 00000000 c5305ef5 0101c17e

As showed above, these ?? regions are exactly 4k bytes in length.
I want know what's possible reasons to this problem, does this means hard disk error or wrong operations to these memory(other thread freed these region)?


text: Q: Infinite dimensional topological quantum field theories? A topological quantum field theory is a functor $Z:Cob(n) \to Hilb$ mapping from the $n$-dimensional cobordisms to $Hilb$, the category of Hilbert spaces with morphisms being bounded linear operators. It's a simple theorem that every such TQFT always takes values of finite-dimensional Hilbert spaces. This set of notes (prop. 2.6) says that it is possible to extend that by restricting to a subcategory of $Cob(n)$ or allowing "volume dependence". Can anyone point me to a reference to something like that? Is there a good way to create a similar functor from some subcategory $cob(n)$, or even from $hTop$ which can take infinite-dimensional values? Is there a way to make that functor full?


text:
Q: AndroidThings TimeZone for a Date object is GMT+00 I am writing an android things app (dev preview 3) for the raspberry pi 3.
I am connecting the app to a wifi network and  when I do a new Date() the time is correct (offset by the timezone - minutes/seconds correct) except for the timeZone which is being set to GMT+00:00  (i.e., timezone 0).
I want to deploy the device into households and need to automatically set their timezone,  since I'm connecting to their wifi network, I assume the I should be able to know their timezone.   Is this do able or is this just a problem with preview 3 and will be corrected in future releases of Android things?


text:
Q: ActionBarSherlock + maven + eclipse: dependency not found in workspace I've updated to lastest version of ADT Plugin and I faced this issue, solved updating also m2e-android eclipse plugin. Now, I'm able to compile my project through console, but not with eclipse. This is the exception thrown by pom.xml file in eclipse:
dependency=[com.actionbarsherlock:library:apklib:4.1.0:compile] not found in workspace
In previous versions of ADT/m2e-android, I was able to build both console and eclipse without problems.
Does anyone know how to solve this? Maybe my pom.xml is wrong?
Thanks for your time.

Currently using:

*

*Eclipse classic 3.7.2 (with Juno the problem persists)

*ADT 20.0.3

*m2e-android 0.42

*android-maven-plugin 3.3.0

*maven 3.0.4

*m2e 1.1.0 (included as a dependency in m2e-android 0.42)

pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jelies</groupId>
    <artifactId>my-project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>apk</packaging>

    <dependencies>
        <dependency>
            <groupId>android</groupId>
            <artifactId>android</artifactId>
            <version>4.1_r2</version>
            <scope>provided</scope>
        </dependency>

        <!-- some unrelated dependencies -->

        <dependency>
            <groupId>com.actionbarsherlock</groupId>
            <artifactId>library</artifactId>
            <version>4.1.0</version>
            <type>apklib</type>
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <version>3.3.0</version>
                <configuration>
                    <sdk>
                        <platform>16</platform>
                    </sdk>
                    <emulator>
                        <avd>avd-4.1</avd>
                    </emulator>
                    <deleteConflictingFiles>true</deleteConflictingFiles>
                    <undeployBeforeDeploy>true</undeployBeforeDeploy>
                </configuration>
                <extensions>true</extensions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>eclipse</id>
            <activation>
                <!-- This profile is only activated when m2e.version is present (only
                    in eclipse) -->
                <property>
                    <name>m2e.version</name>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>com.google.android</groupId>
                    <artifactId>support-v4</artifactId>
                    <version>r7</version>
                    <scope>provided</scope>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
</project>

EDIT:
Answer is right. Having ABS library project mavenized in my workspace, error is gone! But, another problem appeared: ABS transitive dependencies are added to my project, causing eclipse to be not able to launch the application. This is a known issue you can follow here.

A: For those who don't know what "MAVENIZED" means it is convert a simple project to be a Maven Project.
In Eclipse, right click in your project, Configure -> Convert to Maven Project

A: As of Android 0.4.2 you now need to mavenise the Android library projects in your Eclipse workspace for m2e-android to successfully detect them. The POM for ActionBarSherlock can be found here:
https://github.com/JakeWharton/ActionBarSherlock/blob/master/library/pom.xml#
Note: m2e-android is beta software and so changes that might affect functionality can occur between releases.

A: you can include the actionbarsherlock dependency as jar file only when using eclipse via profiles
<profile>
  <id>m2e</id>
  <activation>
    <property><name>m2e.version</name></property>
   </activation>
   <dependencies>
    <dependency>
      <groupId>com.actionbarsherlock</groupId>
      <artifactId>actionbarsherlock</artifactId>
      <version>${abs.version}</version>
      <type>jar</type>
    </dependency>
  </dependencies>
</profile>

and don't need to include the entire actionbarsherlock as project in eclipse

A: I've wrote detailed tutorial about mvn + eclipse + action bar sherlock integration http://v.zasadnyy.com/blog/abs-maven-eclipse-integration/
Hope it will be helpful.

A: Add this to your parent pom.xml file as a dependency:
<dependency>
  <groupId>com.actionbarsherlock</groupId>
  <artifactId>actionbarsherlock</artifactId>
  <type>apklib</type>
  <version>4.2.0</version>
</dependency>

And the following lines to your project pom.xml:
<dependency>
    <groupId>com.actionbarsherlock</groupId>
    <artifactId>actionbarsherlock</artifactId>
    <version>4.2.0</version>
</dependency>


text:
Q: how to return values from joined tables in sequelize at the same level as master table I am trying to find a way how to put all joined tables at the same level as my master table... so far it only results in the nested values in my final object ..
Here is what I have
Orders.findAll({
   include: [
      {model: Products, attributes: ['product_name']}
   ],
   attributes: ['id_order', 'dtime_order', 'amount']
})

what I am getting is:
[
 {
   id_order: 1,
   dtime_order: '2021-05-24T22:00:00.000Z',
   amount: 20,
   products: {
      product_name: 'Picture'
   }
 }
]

but what I wanna get is:
[
 {
   id_order: 1,
   dtime_order: '2021-05-24T22:00:00.000Z',
   amount: 20,
   product_name: 'Picture'
 }
]

I tried this How to return result from include model in same level of main model in Sequelize? but unfortunately when I did:
Orders.findAll({
   include: [
      {model: Products, attributes: []}
   ],
   attributes: ['id_order', 'dtime_order', 'amount', ['products.product_name', 'product_name']]
})

doesn't work for me saying
column "products.product_name" does not exist

There might be a hacky way to modify the object before sending it back in the response .. but I would rather do it within Sequelize ..
any idea is very welcome... thank you guys!
EDIT: adding the generated SQL
Executing (default): SELECT "orders"."id_order", "orders"."dtime_order", "orders"."amount", "products.product_name", FROM "orders" AS "orders" LEFT OUTER JOIN "products" AS "products" ON "orders"."id_order" = "products"."ir_order";
error:   Get dashboard data error: column "products.product_name" does not exist

SOLUTION:
I had to use an alias in my association
Orders.hasOne(Products, {as: 'products', ....})
And then use that EXACTLY SAME alias in my include and referencing
include: [{model: Products, attributes: [], as: 'products'}]
And
attributes: [ ... , [Sequelize.col('products.product_name', 'product_name')]
without the raw: true works like a charm :) Thank you @Emma !!!

A: Please use Sequelize.col to wrap the nested column so that Sequelize can properly alias the column.
Orders.findAll({
  include: [
    {model: Products, attributes: []}
  ],
  attributes: ['id_order', 'dtime_order', 'amount', [Sequelize.col('products.product_name'), 'product_name']],
  raw: true
})


text:
Q: Ansible playbook fail install apt I'm trying to do a test installation on remote via ANSI, and I can not run the Apt-get, attached images:
Playbook

Error

A: apt would require root privileges. Add:
become: true
to your playbook. Ensure that user has the required sudo privileges.

A: thank you very much for the quick response, it is very urgent to fix this bug and get install via ansiable. Now I ask for a password, I tried putting the user and password in the execution sentence of the playbook:
ansible-playbook playbook.yml --user=username --sudo-pass=yourPassword
ansible-playbook playbook.yml -i inventory.ini --user=username --sudo-pass=yourPassword
ansible-playbook playbook.yml -i inventory.ini --user=username \ --extra-vars "ansible_sudo_pass=yourPassword"
ansible-playbook playbook.yml -i inventory.ini --user=username \ --extra-vars "ansible_become_pass=yourPassword"
You could tell me how to enter the pass.
The sentence of the playbook is as follows:
"---
 - hosts: webservers
   remote_user: user
   tasks:
     - name: install example
       apt: name:filezilla state=present
       become: yes
"
Billion thanks
actual error


text:
Q: How to do password rotation through secrets manager for RDS MySQL aurora? I have secrets manager with the secret value url in following format:
 mysql+pymysql://username:password@db-name-dbcluster-13aaj5jwbujqa.cluster-cim1u06sewzq.us-west-2.rds.amazonaws.com/
I want to automatically rotate the password and have two users , so there is no downtime as well.
I tried using was multi user rotation lambda function in sample code provided but it doesn't fit my needs as they need in following format :
        'engine': <required: must be set to 'mysql'>,
        'host': <required: instance host name>,
        'username': <required: username>,
        'password': <required: password>,
        'dbname': <optional: database name>,
        'port': <optional: if not specified, default port 3306 will be used>,
        'masterarn': <required: the arn of the master secret which will be used to create users/change passwords>
    }

I do not have master Arn in my secrets value.
I would like to have my custom lambda function which will to automatic rotation of password using secrets manager and with two user, so it swaps user 1 to user 2 during rotation.


text:
Q: Coverting a decimal to binary using for loops? I'm trying to write a program that converts decimal to binary and decimal to octal.
I can convert from decimal to binary, but from decimal to octal it just doesn't work.
import java.util.*;
public class RadixConversion
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = scan.nextInt();
System.out.println("Convert to base: ");
String letter = scan.next();

if (letter.equals("b")||letter.equals("B"))
    {
        int remainder = 0;
        for (int i = 1; number > 0; i++)
        {
        number /= 2;
        remainder = number % 2;
        System.out.print(remainder);
        }
    }

    else if (letter.equals ("o") || letter.equals ("O"))
    {
        int remainder = 0;
        for (int i = 1; number >0 ; i++)
        {
        number /= 8;
        remainder = number % 8;
        System.out.print(remainder);
        }
    }
 }
 }

A: This is a bit more complicated the way I learned it. You have to find the largest power of 8 that fits in the number, see how many times it goes into the number, and repeat the process with the next lowest power of 8. You print each digit as you go.

A: neither one looks to be generating the correct value, it would just be less obvious with 0's and 1's.  You are dropping the first digit and printing the digits in reverse order (the one's digit get printed first)
    int remainder = 0;
    String result = "";
    for (int i = 1; number >0 ; i++)
    {
      remainder = number % 8;
      result = remainder + result;  // remainder first puts the digits in the right order
      number /= 8;
    }
    System.out.print(result);


text:
Q: Using Code Behind Function when click on Menu Item I have tried to read this link
[How to call function on menu item click?
which was asking about the same problem, but i am unable to understand how should i amend my code to achieve this.
what i want to achieve is that when a user click the menuitem it should execute the code behind function available on the same page.
my code is here
        item = new MenuItem();
        item.Text = "  Chart of Account Master";
        item.NavigateUrl = "~/ChartAccount.aspx";
        item.ImageUrl = "Subicon.png";
        Menu1.Items.Add(item);

what i want to achieve is.
        item = new MenuItem();
        item.Text = "  Chart of Account Master";
        item.NavigateUrl = myfunction();
        item.ImageUrl = "Subicon.png";
        Menu1.Items.Add(item);

A: The link you mentioned is not exactly what you want to do.
You have to add a MenuEventhandler to the MenuItemClick event from your menu and then check the MenuEventArgs for the right Value.
The menu:
<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
    <Items>
        <asp:MenuItem Text="First Item" Value="myFirstItemValue" />
    </Items>
</asp:Menu>

The MenuEventHandler
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
    if(e.Item.Value == "newMenuItemValue")
        //do stuff;
}

Adding a menu item:
MenuItem item = new MenuItem();
item.Text = "new Menu Item";
item.Value = "newMenuItemValue";
Menu1.Items.Add(item);

Thats all, that should work.


text:
Q: replace values of elements of a list using values of another list as a reference I have the following 2 list
>>> a
['a', 'b', 'c', 'd']
>>> b
['b a d c f g', 'a b b c d f', 'b c d c h']

and I want to update/replace b to looks like :
['b a d c var_1 var_2','a b b c d var_1','b c d c var_1']

i.e those key elements from a that it doesn't appear in the chain of the elements of b
I'm trying to convert b in a list of list an iterate over each element of the chain and compare against a, but I don't know if there is the proper approach here.

A: I'm not sure if I totally understand your requirement, but my output is same as yours:
a = ['a', 'b', 'c', 'd']
b = ['b a d c f g', 'a b b c d f', 'b c d c h']

def replace_sub_b(sub_b):
    bl = sub_b.split()
    index = 0
    rl = []
    for c in bl:
        if c in a:
            rl.append(c)
        else:
            index += 1
            rl.append(f'var_{index}')
    return ' '.join(rl)

new_b = [replace_sub_b(sub_b) for sub_b in b]
print(new_b)

A: I would do it this way.
set_a = set(a)
n = len(b)

for i in range(n):
    unknown_vars_mapping = dict()

    chain_vars = b[i].split()

    for j, var in enumerate(chain_vars):
        # if the variable is not in a, store it
        if var not in set_a and var not in unknown_vars_mapping:
            unknown_vars_mapping[var] = 'var_' + str(len(unknown_vars_mapping) + 1)
        # if the variable is not in a, but already been seen
        if var in unknown_vars_mapping:
            chain_vars[j] = unknown_vars_mapping[var]

    b[i] = " ".join(chain_vars)


text:
Q: Good books on the divisor sum function $\sigma(n)$? I would like gain detailed knowledge about properties of the divisor sum function $\sigma(n)$, special equation that have been studied (e.g. $\sigma(n) = 2n$ perfect numbers, ...) and progress that was made in the past centuries.
I am interested in arithmetic functions in general so the books mentioned in this question Good books on Arithmetic Functions ?  is already a good start.
However, it would be great if you could recommend a book or a comprehensive paper that introduces/summarizes knowledge about the $\sigma(n)$ function.

A: For me a very good source for those matters, comprehensive in many aspects and adding enlightening notes and exercises, is

Tenenbaum G., Introduction to Analytic and Probabilistic Number
  Theory, Cambridge Studies in Advanced Mathematics, Cambridge
  University Press, 1995

It has just been reedited by the AMS. Moreover, he also wrote a book Divisors, at Cambridge Tracts. Despite I don't know what is inside, it would be worth a look.

A: Sándor, Jó.; Mitrinović, D. S. & Crstici, B. Handbook of number theory. I Springer, 2006
This book describes a lot of results concerning almost all arithmetical functions.

A: Hint: try to check this online book under this title The math encyclopedia of smarandach type notion in number theory include also arithmitic function , And bellow papers  ,  However they  include iterate sum of divisor function, but you w'ill find solution of your problem , papers include " meta perfect number:"
Cohen, Graeme L., and Herman JJ te Riele. "Iterating the sum-of-divisors function."
Kátai, I. "On the prime power divisors of the iterates of $\phi(n)$ and $\sigma(n)$, Šiauliai
Math." Semin 4.12 (2009): 125-143
Experimental Mathematics 5.2 (1996): 91-100.


text:
Q: UITableViewCell section set and display data into section I have main array(CartPProductListArray) like this
  data=
 {
  data =  (
            {
        "cart_id" = 760;
        "cart_quantity" = 1;
        "image_url" = "http://web-medico.com/web2/kibbeh/uploads/14776327941523279103.jpg";
        name = "Milk Test ";
        price = "2.34";
        "product_id" = 44;
        "store_id" = 3;
    },
            {
        "cart_id" = 760;
        "cart_quantity" = 1;
        "image_url" = "http://web-medico.com/web2/kibbeh/uploads/14776327911430225702.jpg";
        name = "Fish Test ";
        price = "2.34";
        "product_id" = 43;
        "store_id" = 3;
    },
            {
        "cart_id" = 760;
        "cart_quantity" = 1;
        "image_url" = "http://web-medico.com/web2/kibbeh/uploads/14877289882050445800.jpg";
        name = "Cortas Apricot Jam ";
        price = "3.62";
        "product_id" = 77;
        "store_id" = 7;
    }
);
msg = "Data Found";
status = 1;
}

Now, I filtered this two array store wise(store_id)
LebaneseStoreArray(store_id=3) and BabylonStoreArray(store_id=7)
lenbanese==(
    (
            {
        "cart_id" = 760;
        "cart_quantity" = 1;
        "image_url" = "http://web-medico.com/web2/kibbeh/uploads/14776327941523279103.jpg";
        name = "Milk Test ";
        price = "2.34";
        "product_id" = 44;
        "store_id" = 3;
    },
            {
        "cart_id" = 760;
        "cart_quantity" = 1;
        "image_url" = "http://web-medico.com/web2/kibbeh/uploads/14776327911430225702.jpg";
        name = "Fish Test ";
        price = "2.34";
        "product_id" = 43;
        "store_id" = 3;
       }
    )
)
 babylon==(
    (
    {
        "cart_id" = 760;
        "cart_quantity" = 1;
        "image_url" = "http://web-medico.com/web2/kibbeh/uploads/14877289882050445800.jpg";
        name = "Cortas Apricot Jam ";
        price = "3.62";
        "product_id" = 77;
        "store_id" = 7;
      }
  )
)

In my UITableViewCell there are two section(labansese and babylon)
this is my code in numberOfRowsInSection
if(section == 1)
{
    return LebaneseStoreArray.count;
}
else if (section == 2)
{
    return BabylonStoreArray.count;
}
else
{
    return CartPProductListArray.count;
}

But, its getting this(check image)
I want the product in cart store wise.
Please help me with this
thanks in advance.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartCustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"CartCell"];
    if (Cell == nil)
    {
        Cell = [[CartCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CartCell"];
    }

    Cell.ProductNameLabel.text = [[CartPProductListArray objectAtIndex:indexPath.row] objectForKey:@"name"];
    Cell.ProductPriceLabel.text =[NSString stringWithFormat:@"$%@",[[[CartPProductListArray objectAtIndex:indexPath.row] objectForKey:@"price"] stringValue]];
    Cell.ProductQuantityTextField.text =[[[CartPProductListArray objectAtIndex:indexPath.row] objectForKey:@"cart_quantity"] stringValue];

    [Cell.ProductImageview sd_setImageWithURL:[NSURL URLWithString:[[CartPProductListArray objectAtIndex:indexPath.row]objectForKey:@"image_url"]] placeholderImage:[UIImage imageNamed:@"logo.png"]];

    [Cell.PlusQuantityButton addTarget:self action:@selector(PlusQuantityButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    Cell.PlusQuantityButton.tag = indexPath.row;
    [Cell.MinunQuantityButton addTarget:self action:@selector(MinusQuantityButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    Cell.MinunQuantityButton.tag = indexPath.row;

    return Cell;
}

help me with this i'm new in ios.

A: you can use NSSortDescriptor to sort your array.
let sortDescriptor = NSSortDescriptor(key:"storeID",ascending:true,selector: #selector(NSString.localizedCompare(_:)))

A: Just print the  array in log. if you getting current array.
I think the problem is inside the
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // here your code}

Check the array is loading inside the cellfor row at indexpath.
// its always loading first arrary. Change the array depends on the section.

A: You have to update your numberOfRowsInSection like this:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
    {
        return LebaneseStoreArray.count;
    }
    else if (section == 1)
    {
        return BabylonStoreArray.count;
    }
    else
    {
        return 0;
    }
}

For Cell for Row use below code :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartCustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"CartCell"];
    if (Cell == nil)
    {
        Cell = [[CartCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CartCell"];
    }

    // For Section 1 : Lebanese Store Data
    if (indexPath.section == 0) {
        Cell.ProductNameLabel.text = [[LebaneseStoreArray objectAtIndex:indexPath.row] objectForKey:@"name"];
        Cell.ProductPriceLabel.text =[NSString stringWithFormat:@"$%@",[[[LebaneseStoreArray objectAtIndex:indexPath.row] objectForKey:@"price"] stringValue]];
        Cell.ProductQuantityTextField.text =[[[LebaneseStoreArray objectAtIndex:indexPath.row] objectForKey:@"cart_quantity"] stringValue];

        [Cell.ProductImageview sd_setImageWithURL:[NSURL URLWithString:[[LebaneseStoreArray objectAtIndex:indexPath.row]objectForKey:@"image_url"]] placeholderImage:[UIImage imageNamed:@"logo.png"]];

    }else if (indexPath.section == 0){ // For Section 2 : Babylon Store Data
        Cell.ProductNameLabel.text = [[BabylonStoreArray objectAtIndex:indexPath.row] objectForKey:@"name"];
        Cell.ProductPriceLabel.text =[NSString stringWithFormat:@"$%@",[[[BabylonStoreArray objectAtIndex:indexPath.row] objectForKey:@"price"] stringValue]];
        Cell.ProductQuantityTextField.text =[[[BabylonStoreArray objectAtIndex:indexPath.row] objectForKey:@"cart_quantity"] stringValue];

        [Cell.ProductImageview sd_setImageWithURL:[NSURL URLWithString:[[BabylonStoreArray objectAtIndex:indexPath.row]objectForKey:@"image_url"]] placeholderImage:[UIImage imageNamed:@"logo.png"]];
    }

    [Cell.PlusQuantityButton addTarget:self action:@selector(PlusQuantityButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    Cell.PlusQuantityButton.tag = indexPath.row;
    [Cell.MinunQuantityButton addTarget:self action:@selector(MinusQuantityButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    Cell.MinunQuantityButton.tag = indexPath.row;

    return Cell;
}


text:
Q: Send object to VIewModel with mvvm-light I'm pretty new to MVVM light world, and after searches I can't find what I want to do.
My WP7 application contains a pivot, each pivot item content is View1 and viewmodel is VM1.
When loading my application, I'd like to create every pivot item with the same view and view model but with different parameter.
example :
PivotItem 1 -> send param "car" to the view model
PivotItem 2 -> send param "truck" to the view model, etc.
Google told me to use messaging but if I send 2 messages from my MainViewModel, both PivotItem1 and PivotItem2 ViewModel will receive these messages.
Am I wrong with this approach ?
Is there another solution to succeed ?
Thank you in advance for your answer.
PS : be indulgent, english is not my native language, don't hesitate to ask for further information.
Regards,
Aymeric Lagier

A: To seperate the messages use the second constructor signature whereby you can pass a token. This token can be anything but I generally use an enum to store all my message types within the system.
Create a static class in a common library and reference this in all projects where you need to send or receive messages.
The following code hopefully shows this approach, notice I am sending a string as a value within the message but this can be anything, even a complex object such as one of your business objects.
namespace MyProject.Common
{
    public static class AppMessages
    {
        enum MessageTypes
        {
             ViewmodelA,
             ViewmodelB
        }

        public static class ViewModelAUpdate
        {
            public static void Send(string value)
            {
                 Messenger.Default.Send(value, MessageTypes.ViewmodelA);
            }

            public static void Register(object recipient, Action<string> action)
            {
                Messenger.Default.Register(recipient, MessageTypes.ViewmodelA, action);
            }
        }

        public static class ViewModelBUpdate
        {
            public static void Send(string value)
            {
                Messenger.Default.Send(value, MessageTypes.ViewmodelB);
            }

            public static void Register(object recipient, Action<string> action)
            {
                Messenger.Default.Register(recipient, MessageTypes.ViewmodelB, action);
            }
        }
    }
}

A: How about using a method to set the message you want to receive. (this could be done as a parameter in the constructor or a property as well)
    public void RegisterForAppMessage(AppMessages.MessageTypes messageType)
    {
        switch (messageType)
        {
            case AppMessages.MessageTypes.PivotViewItem1Message:
                 AppMessages.PivotViewItem1Message.Register(this,DoSomethingWhenIRecievePivotViewItem1Messages)
            break;
            case AppMessages.MessageTypes.PivotViewItem2Message:
                 AppMessages.PivotViewItem2Message.Register(this,DoSomethingWhenIRecievePivotViewItem2Messages)
            break;
        }
    }

    private void DoSomethingWhenIRecievePivotViewItem2Messages(string obj)
    {
        // TODO: Implement this method
        throw new NotImplementedException();
    }

    private void DoSomethingWhenIRecievePivotViewItem1Messages(string obj)
    {
        // TODO: Implement this method
        throw new NotImplementedException();
    }

A: Messaging sounds a bit heavy for this purpose. Could you simply inject a parameter into your ViewModel. If you already have MVVMLight you also have support for SimpleIOC. Maybe let the view locate its ViewModel when the view is resolved and there decide which parameter to use on the view model?
You can see an example of it here


text:
Q: Proper way to implement Pikaday in Meteor React I'm trying to implement Pikaday in Meteor React. I've searched through numerous solutions and I can't get any of them to work.  As I understand it, this is supposed to work:
I installed pikaday as follows: npm install -- save react react-pikaday.
Below is my code - What am I doing wrong?

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import Pikaday from 'react-pikaday';

export default class TestForm extends Component {

  ComponentDidMount() {

    new Pikaday({
      field: ReactDOM.findDOMNode(this.refs.TestForm),
      format: 'DD/MM/YYYY',
      firstDay: 0,
      minDate: new Date(new Date()),
      maxDate: new Date('2050-12-31'),
      yearRange: [2000,2050],
    });
  }

  render() {

    return(

        <form>

              <input ref="TestForm" type="text"  />

        </form>

    )
  }

}

A: From the github page, there is a component that can be used:
<Pikaday value={date} onChange={this.handleChange} />

If you want to do the componentDidMount way, add an id to the div tag. and use document.getElementById('textId'); instead of using ReactDOM.
I also noticed a typo in ComponentDidMount() {. It should be componentDidMount (c - lowercase).


text: Q: When does $cov(X,Y)\neq 0$ imply $cov(XZ,ZY)\neq 0$? For random variables $X$,$Y$,$Z$, when does $cov(X,Y)\neq 0$ imply $cov(XZ,ZY)\neq 0$? It would be great if you could provide some sufficient conditions or give some special cases such that this hold.


text:
Q: Not being able to maintain php session when in CORS environment I have a situation that goes like this :
I have a php project that I made from scratch serving as an API endpoint to a client web app created with React. For now they are both locally, php running on localhost:8000 and react on localhost:3000.
The issue appears when I try to make token protected request using axios. The php generated session is lost after login.
I've tried to add withCredentials:true client side and also enable
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); in the server side as many of the accpeted answers here mentioned but did not have no luck.
PHP headers :
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');

Axios request:
return axios({
    method: 'GET',
    url: LOAD_NOTES_ENDPOINT,
    headers: {'Authorization': token, 'Access-Control-Allow-Origin': '*',}
})
.then(response => {
    console.log(response.data);
    return response;
})
.catch(
    (err) => {
        return err.response;
    }
);

Currently I'm able to send generate token on login and send it back when trying to access protected route and this works fine if I make the request on Postman and this confirmed that this is strictly a CORS issue.
I've struggled for 2 days now to find a solution and opened every possible link on the web regarding this issue but all of them are are proposing things I've already tried and didn't work.
I could find a workaround but that would leave the server open to CSRF attacks and that is something that I have to prevent.
I'm I missing something here? Did anyone else find a solution about this?

A: Well, I don't know what's going wrong there. However I got it running with this little setup:
file 55976696.php

header('Access-Control-Allow-Origin: http://localhost:3000');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');

echo json_encode('php successs');

php -S localhost:8000 55976696.php

file 55976696.js
var express = require('express');
const app = express()

app.get('/', (req, res) => res.sendFile('55976696.html', {root: __dirname}))

app.listen(3000, () => console.log(`Example app listening on port 3000!`))

file 55976696.html

test

go

node 55976696.js

There is just a little change to your axios.get call and I made sure that the PHP header is what I want ...


text:
Q: Interval classification in r I have two dataframes as follows
str(daily)
Classes 'grouped_df','tbl_df','tbl' and 'data.frame':15264 obs.of 3 variables:
$ steps   : int  0 0 0 0 0 0 0 0 0 0 ...
$ date    : Date, format: "2012-10-02" "2012-10-02" "2012-10-02" ...
$ interval: int  0 5 10 15 20 25 30 35 40 45 ...

interval<-data.frame(unique(daily$interval))

 str(interval)
'data.frame':   288 obs. of  1 variable:
 $ unique.daily.interval.:int 0 5 10 15 20 25 30 35 40 45 50 55 100..2350 2355

using dplyr, what I intended to do was find the mean of daily$steps for each interval across daily$Date using the following
mutate(daily,class=cut(daily$steps,c(0,interval$unique.daily.interval.),
       include.lowest = TRUE) %>%
group_by(class) %>%
summarise(Mean = mean(daily$steps)))

The code fails giving the following error
Error: 'breaks' are not unique

which I have isolated to the 'class=cut' function. I have checked the interval df for uniqueness being only 288 values. Can someone point out what I am doing wrong ?  Here is a reference I used Create class intervals in r and sum values
Here is a link to the data in question Activity monitoring data
thanks.


text:
Q: Ubuntu 14.04 package dependency issue Host: Ubuntu 14.04
When I executed a script, I got the following issue:
The following packages have unmet dependencies:
dh-python : Depends: python3:any (>= 3.3.2-2~)
lsb-release : Depends: python3 but it is not going to be installed

Depends: python3:any (>= 3.3.2-2~)
ubuntu-minimal : Depends: python3 but it is not going to be installed
              Depends: resolvconf

E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I have entered apt-get -f install and executed the script again. However, it did not make any change.
The python version on my system is:
Python 2.7.6 (default, Jun 22 2015, 17:58:13)

A: Python 3 is the key here.  You are using Python 2.
So, I highly recommend using Anaconda for your purposes.  It will allow you to switch between Python2 and Python3
In your browser download the Anaconda installer for Linux, then in your terminal window type the following, replacing the file path and name with the path and name of your downloaded install file. (There is also a gui installer that sets up a PATH entry)
Follow the prompts on the installer screens, and if unsure about any setting, simply accept the defaults, as they can all be changed later:
bash ~/Downloads/Anaconda-2.3.0-Linux-x86_64.sh

Now add conda to your path
PATH=$PATH:$HOME/anaconda/bin

*replace the path with the correct path to anaconda/bin wherever it lives on your machine
Now create an environment that uses python3
conda create --name test python=3

Activate your environment
source activate test

You will see an environment (test) in front of your command prompt.  Test can be renamed to suit your needs.
Verify:
python --version


text:
Q: What is the summand of $y(n) = \frac{1}{n^2}$? In the book of Difference Equations by Peterson, it is given that
$\Delta_n (\sum_{k=a}^{n-1} y(k)) = y(n),$
where $\Delta_n y(n) = y(n+1) - y(n)$.
So, if we can find $\sum y(n)$ (where $\sum$ in there stands for the inverse operation of $\Delta$, and it is called summand of $y(n)$), we can find the partial sum of $\sum_{k=a}^{n-1} y(k)$ - it is $\sum y(n)$.
Question:
What is the summand of $y(n) = \frac{1}{n^2}$ ?

Just for those who are not familiar with this notation:
$$\sum (\Delta_n y(n)) = y(n) \quad \& \quad \Delta_n(\sum y(n)) = y(n).$$


text:
Q: not convergent in norm I want to show that $u_n(x)=sin(2nx)$ is not strongly convergent in $L^p(0, \pi)$
The problem is that I don't have a candidate function. If I pick $0$ then for p larger than 2 it is hard to calculate the integral of $sin(2nx)$ raised to the $p$th power. There has to be an easier way. What is an elegant way of showing there is no strong convergence?

A: If $(u_n)$ were norm-convergent, then there would be an a.e. pointwise convergent subsequence $(u_{n_k})$. And since $m(\mathbb P)=\pi>0,$ there must then be an irrational number $0<\alpha<\pi$ for which $(\sin n_k\alpha) $ converges, which is impossible.

A: Answer for $p \geq 2$: Holder's inequality tells us that if $u_n$ converges in $L^{p}$ then it converges in $L^{2}$ also. This implies that $\int_0^{\pi} |\sin (2nx)-\sin (2mx)|^{2}dx \to 0$ as $ n,m \to \infty$. But you can evaluate this explicitly and see that this is false.
Proof for $0<p<2$: Due to boundedness of $u_n$'s convergence in $L^{P}$ implies convergence in $L^{2}$: $\int_0^{\pi} |\sin (2nx)-\sin (2mx)|^{2}dx \leq 2^{2-p}\int_0^{\pi} |sin (2nx)-\sin (2mx)|^{p}dx $.


text:
Q: sockjs - example of implementing rooms I would like to have users create and join a "rooms" so that they can collaborate.
I'm looking at SockJs Multiplexer server and wondering if I can leverage some of that to create and broadcast to specific channel/room.
In the example, a channel is created manually and client connects to that channel.
Would treating these channels as rooms work?
Is there a way to dynamically create these channels instead of manually declaring them on server?

A:
Disclaimer:  I didn't notice that you were referring to the Javascript-version of the server until I had written my answer.  Therefore, my code examples are given using the Python-based sockjs-tornado, but I guess the principles should be the same.
Yes, you may treat the channels as rooms by keeping a set of referenced connections in each SockJSConnection-derived class.  To do that, all you would need is to change each connection class slightly from
class AnnConnection(SockJSConnection):
    def on_open(self, info):
        self.send('Ann says hi!!')

    def on_message(self, message):
        self.broadcast(self.connected, 'Ann nods: ' + message)

to
class AnnConnection(SockJSConnection):
    connected = WeakSet()

    def on_open(self, info):
        self.connected.add(self)
        self.send('Ann says hi!!')

    def on_message(self, message):
        self.broadcast(self.connected, 'Ann nods: ' + message)

    def on_close(self):
        self.connected.remove(self)
        super(AnnConnection, self).on_close()

in server.py.
To create the channels dynamically, I changed the __main__ code and MultiplexConnection class slightly and added a couple of new classes.  In the if __name__ == "__main__": block,
# Create multiplexer
router = MultiplexConnection.get(ann=AnnConnection, bob=BobConnection,
                                 carl=CarlConnection)

was changed to
# Create multiplexer
router = MultiplexConnection.get()

While
class MultiplexConnection(conn.SockJSConnection):
    channels = dict()
    # …

    def on_message(self, msg):
        # …
        if chan not in self.channels:
            return

in MultiplexConnection was changed to
class MultiplexConnection(conn.SockJSConnection):
    channels = dict()
    _channel_factory = ChannelFactory()
    # …

    def on_message(self, msg):
        # …
        if chan not in self.channels:
            self.channels[chan] = self._channel_factory(chan)

and the classes
class DynamicConnection(SockJSConnection):
    def on_open(self, info):
        self.connected.add(self)
        self.send('{0} says hi!!'.format(self.name))

    def on_message(self, message):
        self.broadcast(self.connected, '{0} nods: {1}'
            .format(self.name, message))

    def on_close(self):
        self.connected.remove(self)
        super(DynamicConnection, self).on_close()

class ChannelFactory(object):
    _channels = dict()

    def __call__(self, channel_name):
        if channel_name not in self._channels:
            class Channel(DynamicConnection):
                connected = WeakSet()
                name = channel_name

            self._channels[channel_name] = Channel

        return self._channels[channel_name]

were added to multiplex.py.


text:
Q: Open Document Content Type from SharePoint 2010 Library with perfect trust I just created Document Content Type and then create new document from New Document. I got the popup "Some files can harm your computer. If the file information below looks suspicious, or you do not fully trust the source, do not open the file". I have 2 questions:

*

*How can I ignore the popup? What consequence will I encounter after doing?

*When I filled the metadata properties on the Document Content Type, I didn't find the publishing feature in order to save document back to library. Anyone know the way to create new document from SharePoint Library and save back to Library after finished filling document.

Thanks & Best Regards,

A: *

*It is IE security issue and here is similar question with an answer on Server Fault: https://serverfault.com/questions/59110/sharepoint-error-message-some-files-can-harm-your-computer

*Check Why is Word document created from template saved locally, instead of to the document library? for some additional info but generally it cannot be done

A: We face the same problems in the word template document libray:
1- popup messag when click add new document " Some files can harm your computer. If the file imformation below looks suspicious, or you do not fully trust the source, do not open file."
2- Cannot upload the file to the Shared document (when i click save > click ok > the shared document open > and i cannot save the document template on it )
and my technical question for you it's required to have Office 2010 to be able to save the word template into the shared document libary or we can use office 2007 ?
Regards
hassib
Please help me to solve this issue


text:
Q: difference in data of mysql same tables of different databases I want to find out the differences of two same structured tables but in different databases,One is master table & i want to sync all other similar tables in different databases with it.
For example t1 table in db1 and t2 table in db2, want to find out difference between t1 & t2 using mysql.


text:
Q: My do while loop does not work, im not sure where I went wrong The area that I think needs work is the do while loop because I want it to loop when it only ties. However it also loops when the user wins or loses.
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

const int ROCK = 1;
const int PAPER = 2;
const int SCISSORS = 3;

int getComputerChoice();
int getUserChoice();
void displayChoice(int);
int winner(int, int);

MAIN FUNCTION
int main()
{
    int computerChoice,
    userChoice;
    int playAgain;

THE DO WHILE LOOP DOES WORK BUT IF I WIN OR LOSE IT STILL LOOPS. I JUST WANT IT TO LOOP IF A TIE OCCURS.
    do
    {
        computerChoice = getComputerChoice();
        userChoice = getUserChoice();

        displayChoice(computerChoice);
        playAgain = winner(computerChoice, userChoice);
    } while (playAgain == 1);

    return (0);
}

THIS GETS THE COMPUTER CHOICE
int getComputerChoice()
{
    unsigned seed = time(0);
    srand(seed);

    return (rand() % (SCISSORS - ROCK + 1)) + ROCK;
}

THIS IS GOOD I THINK
int getUserChoice()
{
    int uChoice;
    cout << "Enter your choice of Rock, Paper, Scissors.\n"
         << "(1) For rock, (2) for paper, (3) for scissors: ";

    cin >> uChoice;

    while (uChoice < 1 || uChoice > 3)
    {
        cout << "Please enter a number between 1 and 3. Try again, thank you.";
        uChoice = getUserChoice();
    }

    return uChoice;
}

THIS IS GOOD I THINK.
void displayChoice(int computerChoice)
{
    cout << "Computer Choice: ";

    if (computerChoice == 1)
        cout << ROCK;
    else if (computerChoice == 2)
        cout << PAPER;
    else if (computerChoice == 3)
        cout << SCISSORS;

    cout << endl;
}

AREA I THINK NEEDS WORK.
int winner(int computerChoice, int userChoice)
{
    int playAgain = 1;
    if (computerChoice == ROCK)
    {
        if (userChoice == SCISSORS)
        {
            cout << " You lose :( (The Rock smashes the Scissors) ";
        }
        else if (userChoice == PAPER)
        {
            cout << "You win! (Paper beats rock) ";
        }
        else if (userChoice == ROCK)
        {
            cout << "Its a tie. Play again.";
            playAgain == 1;
        }
    }
    else if (computerChoice == PAPER)
    {
        if (userChoice == ROCK)
        {
            cout << "You lose :( (Paper wraps rock)";
        }
        else if (userChoice == SCISSORS)
        {
            cout << "You win! (Scissors cuts paper)";
        }
        else if (userChoice == PAPER)
        {
            cout << "Its a tie. Play again.";
            playAgain == 1;
        }
    }
    else if (computerChoice == SCISSORS)
    {
        if (userChoice == ROCK)
        {
            cout << "You Win! (The rock smashes the scissors.)";
        }
        else if (userChoice == PAPER)
        {
            cout << "You lose :(. (Scissors cuts paper.)";
        }
        else if (userChoice == SCISSORS)
        {
            cout << "Its a tie. Play again.";
            playAgain == 1;
        }
    }

    cout << endl;
    return playAgain;
}

A: Within winner, you attempt to update playAgain with playAgain == 0. But == is the equality operator. It does not perform assignment. The assignment operator is =, i.e. a single equal sign. As a result, playAgain is never updated, and winner() always returns 1.
To fix, use the assignment operator instead of the equality operator when updating a variable's value.


text:
Q: Issues with NSOperationQueue and dealloc being called and crashing App I've created an NSOperation in the queue like so:
ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];
[operationQueue addOperation:operation];
[operation release];

And this works fine but if the view gets popped before the operation finishes the App crashes with "EXC_BAD_ACCESS"
I've tried to cancel the the operation Queue by calling cancelAllOperations but as its already in process it doesn't prevent the App from crashing. The docos say that if the operation is running it is up to the operation to detect that it has been canceled and respond appropriately but not too sure how I would implement this?
Any ideas?

A: It is a general problem for View calling some network and then callback.
My solution is you can retain the view before you call the operation. And then, when the operation finishes, you release the view.
- (void)longTask {
   [self retain];
}

- (void)longTaskDidFinish {
   // do something if you want
   [self release];
}

A: You will have to either override the "cancel" operation in your ImageLoadingOperation class, or have your ImageLoadingOperation  add itself as KVO observer to the "cancelled" property. There - you can intelligently cancel your operation in such way that it won't crash.
Also, if your ImageLoadingOperation runs in the background, it would be wiser to defer your access to the views somehow to the main thread (where all drawing takes place). You could use a dispatch_sync(dispatch_get_main_queue(), ^{}); or even performSelectorOnMainThread for actual access to the related view.
You see - the whole point of using an operation queue is to remove dependencies, and let things run in parallel, but your operation must synchronize with the view-system changes, and that must be designed for completeness and robustness.

A: You could retain the view before the callback of operation is called, as vodkhang mentioned above. But that will prolong the life of the view unnecessarily because since the view is popped you don't want the operation to continue any more.
Here is a sketch about what you should do to respond to the cancel command:
- (void)start{
    if(self.isCancelled){
       [self markAsFinished];
       return;
    }
    //start your task asynchronously
}

//If you want to cancel the downloading progress immediately, implement your own 'cancel' method
- (void)cancel{
    [super cancel];
    if(self.isExecuting){
       {
          ......
          cancel load process
          ......
       }
       [self markAsFinished];
    }
}

- (void)markAsFinished{
    ......
    change 'finished' to YES'  generate KVO notifications on this key path
    change 'executing' to 'YES'; generate KVO notification on this key path
    ......
}

This sketch is based on  ASIHTTPRequest networking library, and
 there is an official guide on how you should respond to cancel command.


text:
Q: Error "converting string to float" when using model.predict() When I use model.predict(), the following error occurs,

ValueError: could not convert string to float:

One-hot encoding was used in my code as follows,
features_df = pd.get_dummies(df, columns=['garage_type', 'city'])

The predict code used is given below.
sample = [["attached"], ["Richardport"]]
predictedvalue = model.predict(sample)'

Any suggestions to solve this error? Thank you.

A: The reason why you are getting an error is because you are sending strings to your model, while the model is expecting a vector of floats which is to be of the same shape as that of your training data.
From the code, it is clear that you are using one hot encoding before you use your data for training. You need to convert your sample also into the same one hot encoded vector format to get the answer.

A: You'll need to convert your sample to separate columns also, That means, you have to check the new dummy columns, and convert your sample to a boolean list L, where L[i]=True if column[i]=='attached' or column[i]=='Richardport' and False for all other list elements, before calling the .predict(L) method.
 This response might be helpful:

How to use Pandas get_dummies on predict data?


text:
Q: node.js killing a request early In my app I'm downloading a file if I click on it thanks to http.get
var buffer = fs.createWriteStream('file.txt');
$('a').click(function(){
    http.get(url, function(res) {
        res.on('data', function(chunk) {
             buffer.write(chunk);

and if I click on a second link, it will download it on the same buffer as well.
this doesn't work well and the two files get mixed.

*

*What I want is to kill the first request when I start the second one, any idea how to do this?

*Also I'm using http.get, but sometimes the module request.get, I don't see any differences, which one should I use for this job?

A: I found a way around with event emitters:
require('event')

just emit something, and catch it to kill the request with a res.destroy();


text:
Q: FileSystemNotFoundException when accessing resources inside a Docker container I have an application that runs inside a Docker container. The application has a dependency to a library called mylibrary. The library gets the path to a folder called /schemas within the classpath as follows.
URL resource= getClass().getClassLoader().getResource("schemas");
Path path = Paths.get(resource.toURI());

Running the application results in a FileSystemNotFoundException caused by Paths.get(). I was able to fix this by creating a FileSystem object using FileSystem.getDefault() and using this object to get the path.
Running the code locally on my linux machine, I get a path like /data/code/mylibrary/target/classes/schemas/. However, running the my application via Docker it gives me something file:/root/.m2/repository/de/monticore/lang/monticar/mylibrary/0.4.10-SNAPSHOT/mylibrary-0.4.10-SNAPSHOT.jar!/schemas. Using the latter, my code throws FileNotFoundExceptions.
What is wrong here?
Hint: I have to provide the path to another library, which does some schema validation. Therefore, I need the path.


text:
Q: How to do horizontal scrolling in a web browsrer by pixels? Just pressing  right or left button is no good for me - it makes too big skips. Using mouse by clicking and dragging the slide bar is better, but still I have a feeling that my hand is too rough and it doesn't scroll by pixels. How can I do horizontal scrolling by pixels? I am especially interested in Firefox and Chrome browsers.

A: In Chrome, I don't think there is a built-in way of single pixel scrolling.  An alternative you might try is what they call "auto-scrolling", which is smooth scrolling and not high velocity.  You hold down the middle mouse button or wheel and move the cursor in the direction you want the display to be moved.

A: Hold the Shift button and use the mouse wheel to scroll horizontally. This works universally, across browsers and platforms.
However, how quickly the mousewheel scrolls depends on the browser or the platform. Mostly, it is slower than the left/right keys. And often, there are settings that you can tweak.


text:
Q: Segmentation fault when trying to get lowest number from user inputted array I'm making a program that calculates the average of user inputted tests, after the user has inputted the number of tests, the user then has to input every grade for the number of tests inputted, after that the program will then read into the array of grades inputted then get the lowest grade, after that the program will calculate the average, then output that, then output the lowest grade, then call function "letter();" to get the letter grade based on the value on the average. but when it goes into getting the lowest number from the array it gives me a segmentation fault that I can't fix
I have tried to redo that part of the code to no avail
#include <stdio.h>

void letter();

int average;

int main()
{
    int a[100], i, sum = 0, num, lowest, test;

    printf("Enter the numbers of tests: ");
    scanf("%d", &test);

    while (test > 100 || test <= 0)
    {
        printf("Error! The number of tests should be in range of (1 to 100).\n");
        printf("Enter the number again: ");
        scanf("%d", &test);
    }

    for(i = 0; i < test; ++i)
    {
        printf("%d. Enter grade for this test: ", i+1);
        scanf("%d", &a[i]);
        sum += a[i];
    }

    lowest = a[0];

    for (i = 0; i < num; i++)
    {
        if (a[i] < lowest)
        {
            lowest = a[i];
        }
    }

    average = sum / test;
    printf("Average = %d", average);

   return (0);
}

void letter()
{
    if (average == 0 || average <= 60)
    {
        printf("Your average is a F. \n");
    }

    else if (average <= 70 || average >= 61)
    {
        printf("Your average is a D. \n");
    }

    else if (average <= 80 || average >= 71)
    {
        printf("Your average is a C. \n");
    }

    else if (average <= 90 || average >= 81)
    {
        printf("Your average is a B. \n");
    }

    else if (average <= 100 || average >= 91)
    {
        printf("Your average is a A. \n");
    }
}

EDIT
I added
printf("Your average is: %d \n", average);

printf("The lowest grade is: %d \n", lowest);

letter();

after
average = sum / test;

and changed the letter function to this but doesnt give me correct letter grade with average
void letter()
{
    if (average >= 0 || average <= 59)
    {
        printf("Your average is a F. \n");
    }

    else if (average >= 60 || average <= 69)
    {
        printf("Your average is a D. \n");
    }

    else if (average >= 70 || average <= 79)
    {
        printf("Your average is a C. \n");
    }

    else if (average >= 80 || average <= 89)
    {
        printf("Your average is a B. \n");
    }

    else if (average >= 90 || average <= 99)
    {
        printf("Your average is a A. \n");
    }
}

EDIT #2
Changed letter function to this, now it works, thanks everyone for you help and taking your time to help me out.
void letter()
{
    if (average == 0 && average <= 60)
    {
        printf("Your average is a F. \n");
    }

    else if (average <= 70 && average >= 61)
    {
        printf("Your average is a D. \n");
    }

    else if (average <= 80 && average >= 71)
    {
        printf("Your average is a C. \n");
    }

    else if (average <= 90 && average >= 81)
    {
        printf("Your average is a B. \n");
    }

    else if (average <= 100 && average >= 91)
    {
        printf("Your average is a A. \n");
    }
}

A: The problem that I see is
 for (i = 0; i < num; i++)

here, num is used unintialized. If you try to use the value of a variable which

*

*is never initialized

*can have trap representation

*never has the address taken

it invokes undefined behavior.
Solution: You'd want to use test as the loop counter.
And also, in your code, you never made a call to letter().
A modified version of your code which prints the expected output.

A: The variable num is allocated on stack and and it is not initialised so it will have garbage value.
You are using it in below for loop. Hence if num is arbitrarily greater than or equal to 100, you would try to access a[num] which is array out of bound access and can result in crash. You should use test instead of num in below for loop.
for (i = 0; i < num; i++)
    {
        if (a[i] < lowest)
        {
            lowest = a[i];
        }
    }

A: The variable num is not initialized and it is used in the for loop
for (i = 0; i < num; i++)

This leads to undefined behavior. The segmentation fault is probably caused by the fact that the uninitialized value of num used as an index to array a leads to an out of bounds memory access in the below check.
 if (a[i] < lowest)

A: At the time you enter loop
for (i = 0; i < num; i++) {
    if (a[i] < lowest)

your variable num is not initialized. This is undefined behaviour, probably leading to a segfault due to a value of i larger than 99 then.
Write for (i = 0; i < test; i++) instead.


text:
Q: Calling javascript via AS3 externalinterface within a colorbox I have a swf that opens up inside a colorbox window. When the video finishes playing, I make an externalinterface call to a javascript function to close the colorbox.
I'm trying to execute the following AS3 code:
ExternalInterface.call('parent.$.fn.colorbox.close()')
I can't seem to get this to work. The colorbox won't close.
I also tried this to see if I was just making the wrong function call, but this didn't work either:
ExternalInterface.call('alert("hello world")')
However, if I browse to the url of the swf file, so that it doesn't open inside the colorbox, the alert() call works just fine.

A: Try this:
ExternalInterface.call('parent.$.fn.colorbox.close');

And this:
ExternalInterface.call('alert','hello world');

Alternatively, you could call eval and pass JS code as a String (you don't need this here, but it's handy in some cases).
ExternalInterface.call('eval','parent.$.fn.colorbox.close()')


text:
Q: Splitting a list of objects into n lists while keeping all attributes I'm trying to code a class method that takes every nth item and puts into a separate list. Then puts each of those lists into a separate object, all with the same attributes as the original object except for the lst attribute
For some reason when I run the program it only returns the first half of the inputted list
Here's the code
    def return_nfolds(self,num=3):
        j = 0
        lst = []
        while j < num:
            lst.append(self.lst[j:len(self.lst):num])
            j+=1
        objs = [copy.deepcopy(self) for i in range(len(lst))]
        for i in range(len(lst)):
            objs[i].lst = copy.deep(lst[i])
        return objs

I've tried the first half of the function, splitting the list, by itself(shown below) which works as expected but it doesn't work when I run the full code
j = 0
num = 2
test = list(range(100))
lst = []

while j<num:
    lst.append(test[j:len(test):num])
    j+=1
print(lst)

edit: update
I've tried the following code which works exactly as intended so I have no clue why the original isn't working
import copy
class listholder():
    def __init__(self):
        self.list = []
        self.a = 1
        self.b = 2
    def __str__(self):
        return str(self.a)+str(self.b)+str(self.list)
j = 0
num = 2
test = list(range(100))
lst = []
obj = listholder()
obj.a = 0
obj.b = 1
while j<num:
    lst.append(test[j:len(test):num])
    j+=1
    objs = [copy.deepcopy(obj) for i in range(len(lst))]
    for i in range(len(lst)):
        objs[i].list = copy.deepcopy(lst[i])
print(*objs)

A: I've found the solution
If anyone is wondering there were actually 2 variables in the object that I needed to keep track of instead of one
the one I tracked here only held the object, there was another with all the string identifiers of the objects that I also needed to change


text:
Q: set ignore case value in when expression on strings I know how to check a string is in another string
like this code.
when (myString) {
        in "FirstString"  -> {
                // some stuff
        }
        in "SecondString" -> {
                // some stuff
        }
        else -> {
                // some stuff
        }
}

in keyword under the hood calls this method CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false)
the question is this :
is there any way that in this case i can set ignoreCase = true ?

A: You can declare an ad-hoc local operator function contains for strings before when:
fun main() {

    operator fun String.contains(other: String): Boolean = this.contains(other, ignoreCase = true)

    when(myString) {
        in "firstString" -> ...
    }
}

This way that function will be invoked for in operator instead of the one declared in the standard library because it's located in the closer scope.
Note, however, that this trick works only if the original contains function is an extension. If it's a member function, it cannot be overridden with an extension.

A: You can use toLowerCase() function here :
when (myString.toLowerCase()) {
    in "firststring"  -> {
            // some stuff
    }
    in "secondstring" -> {
            // some stuff
    }
    else -> {
            // some stuff
    }
}

For the cases of when, if they're variables toLowerCase() needs to be called on each of them. But, if they're constants, simple using lower case strings will work - "firststring", "secondstring"


text:
Q: setting up ubuntu server with spoofed mac address I have two computers and one ethernet cable.
The cable is from admin and only one mac address is allowed to have internet connection.
The mac address is set for my main pc.
I want to set up an ubuntu server on my second pc while I am gone.
I already installed the ubuntu server on the second pc but it was unable to automatically configure the network (since it has a wrong mac address).
I am familiar with changing the mac address, but not with setting up the network manually.
Is there a way to set up the network automatically like it was seen in the setup phase?

A: I didn't find a way to set up the network automatically after the instalation finished, but I have solved my problem by choosing "set network manually" in the installation menu.
Then I retyped all network info from my first pc - I have windows so I looked up ethernet part of ipconfig /all.
After the installation finished I spoofed the mac address and it works!


text:
Q: Augmented reality Interaction between two phones I try use Wikitude to development AR app. (Use Unity)
Now I want phones can interact with each other.
I think if at the same place I need GPS indoor, so it's seem difficult. I just want they can create group and play together.
If anyone have solution, thanks a lot


text:
Q: Excel VBA: Error 0x800c00008 I made a small macro in Excel that helps find IANA TimeZone names from timezonedb.com using API. I made it work for my PC, but when someone else used it from their PC, it began showing an error like this

I've found solutions over the internet saying that the Microsoft Core Package has to be repaired, but I want to know if I could bypass that by adding something in the code, maybe? Is there a way to accomplish that?
I'm adding the function code here:
Function FetchTZ(qLat As Double, qLong As Double, c_check As String, rN As Integer) As String
    Dim JSON_content As String
    Dim IANAtz As String
    Dim temp_l As Long
    Dim XMLobj As Object
    Dim qURL As String
    Dim CheckCountry As String

    temp_l = 0
    JSON_content = vbNullString

    qURL = "https://api.timezonedb.com/v2/get-time-zone?key=NB7W9T1K95UT&format=json&by=position&lat=" & qLat & "&lng=" & qLong
    Set XMLobj = CreateObject("Microsoft.XMLHTTP")
    With XMLobj
        .Open "POST", qURL, False
        .send
        JSON_content = .responseText
    End With
    Set XMLobj = Nothing

    temp_l = InStr(1, JSON_content, "zoneName")
    IANAtz = Mid(JSON_content, (temp_l + 11), ((InStr(temp_l, JSON_content, "abbreviation") - 3) - (temp_l + 11)))

    IANAtz = Replace(IANAtz, "\/", "/")

    temp_n = InStr(1, JSON_content, "countryCode")
    CheckCountry = Mid(JSON_content, (temp_n + 14), 2)

    If CheckCountry <> c_check And Len(c_check) = 2 Then
        Sheets("TZMacro").Range(Cells(rN, 1), Cells(rN, 4)).Interior.ColorIndex = 3
    End If

    FetchTZ = IANAtz

Thanks in advance and I really hope you can teach me how to crack this one!

A: I changed
CreateObject("Microsoft.XMLHTTP")
to
CreateObject("MSXML2.ServerXMLHTTP.6.0")
and the error didn't pop up anymore.


text:
Q: Issue with email form in JQuery/PHP I'm still getting my way around JQuery, what i'm trying to do here is send a message to all my users on site, i'm attempting to use JQuery/Ajax more, the code so far:
mass-email.php
<?php
include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
include('includes/header.php');
include('includes/navbar-logged.php');
// who is the admin sending the email?
$row       = DB::getInstance()->selectOneByField('membership', 'member_username', $member);
$admins_id = $row['member_id'];
?>

Mass e-mail all users.

        <form id="frmAjax" action="mass-email.php" method="post" class="form-horizontal container-fluid" role="form">

Message:

                    <textarea id="" name="message" class="form-control" required="required"></textarea>

                    <button type="submit" name="submit" class="btn btn-default">Send</button>

        </form>

Send a mass e-mail to all users currently registered.

<?php
include('includes/footer.php');

ajax-emails.php
<?php
    include('includes/db_connection.php');
    include('includes/functions.php');
    // mass email
    $result = DB::getInstance()->selectAll('membership');
    // loop through the emails
    foreach ($result as $row) {
        $email         = $row['member_email'];
        $username      = $row['member_username'];
        $message       = nl2br($_POST['txtAreaValue']);
        $message       = stripslashes($message);
        echo $message;
        //$mailSent = sendMassEmail($email, $username, $message);
        echo "email sent to: ".$email."";
    }
?>

This is what i have done so far, i can pring out the value of the message fine, i just cannot seem to pass the value through to the PHP file, any help on where i'm going wrong would be appreciated.

A: I think this is what you want. $('#insert-text').load('ajax-emails.php'); won't do anything.


text:
Q: scale() CSS3 property moves other elements on hover I'm trying to make a gallery, however, I'm having a problem with scale property.
It appears that if I hover quickly over several elements they start to move about 1px back and forth due to scale().
HTML:

Cappuccino

                                    This is Photoshop's version  of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet.

Cappuccino

                                    This is Photoshop's version  of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet.

Cappuccino

                                    This is Photoshop's version  of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet.

Cappuccino

                                    This is Photoshop's version  of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet.

Cappuccino

                                    This is Photoshop's version  of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet.

Cappuccino

                                    This is Photoshop's version  of Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet.

CSS:
#first img, .shade{
    margin-left:0.5%;
    margin-bottom:0.5%;
}
#first>section{
    position:relative;
    float:left;
    margin: 0.7% 0.7% 0 0;
    overflow:hidden;
    width:273px;
    height:182px;
}
#first>section img{
    position:relative;
    -webkit-transition: all 0.2s linear;
}
#first>section>img:hover{
     -webkit-transition: all 0.2s linear;
}
.shade:hover{
    opacity:1;
}
.shade{
    width: 253px;
    height: 162px;
    background:rgba(255, 144, 0, 0.65);
    position:absolute;/* needed*/
    top:0;/* needed*/
    left:0;/* needed*/
    opacity:0;
    color:#fff;
    padding:10px;
    -webkit-transition: all 0.2s ease-in-out;
}
.shade p{
    margin-top:60px;
    width: 255px;
}
.shade h5{
    text-decoration:underline;
    font-size:110%;

jQuery:
$(window).load(function(){

picLink=$("#first a");
picLink.mouseover(function(){
$(this).prev().css("-webkit-transform","scale(1.3)");
});
picLink.mouseout(function(){
$(this).prev().css("-webkit-transform","scale(1.0)");
});

});

Here's a live example:
http://jsfiddle.net/VJWg6/1/

A: I assume that by "going back and forth" you mean this slightly disturbing effect of images covering that small, 1px wide space on their left-side.
It happens because you have a margin-left property specified on them (#first img). This margin keeps space inside the overflow:hidden container (section), so when images are resized they simply cover this space.
As a solution you could just remove the margin-left on images and move it to the section (of course you will need to adjust the percentage, since the context changes.).
This small fix: http://jsfiddle.net/VJWg6/23/


text:
Q: 'git diff' between a remote and local repository I am trying to diff my local file with a GitHub repository before I submit a pull request, so I can see what will show up. Is there an accurate way of doing this?
I assume GitHub's compare tool manipulates Git's diff.

A: Per the OP's comment that part of his "problem was Windows vs. Unix LFs", this should help:
You can use the following configuration command to tell git-diff to ignore the difference of the EOL code.
git config --global core.whitespace cr-at-eol

A: Don't do a pull :

*

*do a fetch (the syntax is the same as git pull, but it doesn't automatically merge)

*do a diff between your dest branch and the other branch

*then do a merge if you want

A: You can use: git diff remote/my_topic_branch my_topic_branch
Where my_topic_branch is your topic branch.

A: To compare a local working directory against a remote branch, for example origin/master:

*

*git fetch origin master
This tells git to fetch the branch named 'master' from the remote named 'origin'.   git fetch will not affect the files in your working directory; it does not try to merge changes like git pull does.

*git diff --summary FETCH_HEAD
When the remote branch is fetched, it can be referenced locally via FETCH_HEAD.  The command above tells git to diff the working directory files against  FETCHed branch's HEAD and report the results in summary format. Summary format gives an overview of the changes, usually a good way to start. If you want a bit more info, use --stat instead of --summary.

*git diff FETCH_HEAD -- mydir/myfile.js
If you want to see changes to a specific file, for example myfile.js, skip the --summary option and reference the file you want (or tree).

As noted, origin references the remote repository and master references the branch within that repo.  By default, git uses the name origin for a remote, so if you do git clone <url> it will by default call that remote origin.  Use git remote -v to see what origin points to.
You may have more than one remote.  For example, if you "fork" a project on GitHub, you typically need a remote referencing the original project as well as your own fork.  Say you create https://github.com/yourusername/someproject as a fork of https://github.com/theoriginal/someproject.  By convention, you would name the remote to the original repo upstream, while your own fork would be origin.  If you make changes to your fork on GitHub and want to fetch those changes locally, you would use git fetch origin master. If the upstream has made changes that you need to sync locally before making more changes, you would use git fetch upstream master.

A: EG
git diff master origin/master

A: Important to remember:
Git diff will show you diferences between two commited branchs ( remote or local).
Step 1) - Commit local
So the first step to do is make sure you have commited your local repository. You can run git status to see if there is any file left.
If you need to add a file run a git add {filename} or to add all files git add .. Then you can run a  git commit -m "message" to commit you local files.
Step 2) - Fetch your branch from remote
You can fetch your remote using  git fetch origin master. If you see a message like below, you are good to go.
branch            master     -> FETCH_HEAD

Note that origin is the repository and master is the branch within
that repository.

Step 3 Check differences
Now you can either git diff --summary FETCH_HEAD or  git diff origin/master master --summary too see your changes.

A: I just had a related problem where I wanted to get a quick overview of changes in a GitHub PR before merging it.
Basically I was only interested in knowing how many files were added, modified, or deleted in that PR. The PR had thousands of changes, which made the GitHub web UI useless.
If anyone has a similar problem, try doing this on your local machine:

*

*git fetch origin branch as @HieroB suggested. This will get metadata about the latest changes in the remote branch without pulling all these changes locally.

*git diff --name-status FETCH_HEAD > difflog.txt. Git will create a list of all files that were changed in the remote branch, and save the list to a file. The structure of the resulting file will be like this:
M  files/file1.json
D  files/file2.json
A  files/file3.json

where the change marker M stands for "modified", D stands for "deleted", and A stands for "added. In each line, its change marker will be delimited from the file name with a tab character.

*Open the file in a text editor, copy each of the 3 change markers along with their adjacent tab characters, and use your text editor's Find in file functionality to search for the marker's occurrences.


text:
Q: Function Call in IF Condition I want to check the function call in "IF condition", but it's not working. I'm getting the output as "undefined "My program output supposed to be:
If user Select a car, then response will be accordingly.
Is my method to get value is wrong?

function carPickUp() {
  var pickedCar = document.getElementById("cars").value;
  return pickedCar;
}

function showCar() {
  var message;
  if (carPickUp() == "ROLLS") {
    message = "Great choice";
  } else if (carPickUp() == "AUDI") {
    message = "best choice";
  } else if (carPickUp() == "VOLVO") {
    message = "Good choice";
  } else if (carPickUp() == "FORD") {
    message = "Good choice";
  }
  document.getElementById("demo1").innerHTML = message;
}

The select Element

The select element defines a drop-down list:

<form action="/action_page.php">
  Choose a car:
  <select id="cars" name="cars">
    <option value="volvo">VOLVO</option>
    <option value="ford">FORD</option>
    <option value="rolls">ROLLS</option>
    <option value="audi">AUDI</option>
  </select>
  <input type="button" onclick="showCar()" value="Submit" />
</form>


text:
Q: Attach context for base object of kotlin extension function This question is specific for extension function of Kotlin used in Android development.
So Kotlin provides us capability to add certain extension behavior in to a class to extend the based class behavior.
Example:  (take from my current Android project, for viewAssertion in testing with Espresso)
fun Int.viewInteraction(): ViewInteraction {
    return onView(CoreMatchers.allOf(ViewMatchers.withId(this), ViewMatchers.isDisplayed()))
}

In my usecase, I can use it like:
R.id.password_text.viewInteraction().perform(typeText(PASSWORD_PLAIN_TEXT), pressDone())

All good, except this extension function gives the extended behavior to all Int objects, not just the View IDs in Android, which is not good at all.
The question is if there is any way to give context for this Int, like in Android we have @IdRes in Android support annotation for such given case above?

A: You can't differentiate between an Int from the resources and a normal Int. It is the same class and you are adding an extension to all the classes of the Int type.
An alternative could be to create your own wrapper of Int:
class IntResource(val resource: Int) {

    fun viewInteraction(): ViewInteraction {
        return onView(CoreMatchers.allOf(ViewMatchers.withId(resource), ViewMatchers.isDisplayed()))
    }
}

And then us it like this:
IntResource(R.id.password_text).viewInteraction().perform(typeText(PASSWORD_PLAIN_TEXT), pressDone())


text:
Q: Reordering a table based on non-numeric rownames I'm trying to reorder the rows in a table based on the row name to a custom order, but my row names are characters rather than numbers.
I created a table of my data in R from a larger data frame using the table tool:
data <- table(allcones$Type, allcones$Location)[,]
This gives me a table that looks like this:
>    Ada Alf   Lk  Lnd Myv Raud
  D    3   0   10    0  59    0
  H 3777   0    0    0   8    0
  L   11   0   34    4  34    5
  P    0   0    0    0 187    0
  S  585   0 1880    0 460  109
  T  100   0    0    0 233    0
  U  234 517  401 4057   9    0
The row names (D, H, L...) are currently ordered alphabetically, which I think is the default in R. However, they each reflect a different class of data so I want to put them into a custom order.
I tried using
reorder(row.names(data), new.order=c('L', 'D', 'S', 'T', 'H', 'P', 'U')) based on other questions on this site, but this doesn't work. It seems that row.names(data) is not a valid argument in the reorder function.
I don't want to create a new column to force the order because I'm using this data to make a stacked barplot of the table (using barplot(data, ...)) and I wouldn't know how to get rid of the extra column.
Any ideas?

A: This probably isn't the best solution but you could always use dplyr if the row order was based on one of the column names.
eg if you wanted them sorted by the 'Myv' order, you could use -
library('dplyr')
dataa <- arrange(data, Myv)

A: table() respects the ordering of the levels of the factors wither passed in as arguments or those arguments coerced to factors (in which case the default ordering of levels will be produced).
So, instead of
df <- data.frame(f1 = sample(LETTERS[1:5], 1000, replace = TRUE),
                 f2 = sample(letters[23:26], 1000, replace = TRUE))
with(df, table(f1, f2))

which gives
> with(df, table(f1, f2))
   f2
f1   w  x  y  z
  A 48 41 44 63
  B 35 50 35 49
  C 52 79 48 52
  D 49 51 50 55
  E 46 45 60 48

set the levels of the factor arguments explicitly to the ordering you want. For example here I just reverse the ordering but you could specify it explicitly:
df2 <- transform(df, f1 = factor(f1, levels = LETTERS[5:1]),
                     f2 = factor(f2, levels = letters[26:23]))
with(df2, table(f1, f2))

which gives
> with(df2, table(f1, f2))
   f2
f1   z  y  x  w
  E 48 60 45 46
  D 55 50 51 49
  C 52 48 79 52
  B 49 35 50 35
  A 63 44 41 48

In your specific example I would do
allcones <- transform(allcones,
                      Type = factor(Type, levels = c("L","D","S","T","H","P", "U"))
with(allcones, table(Type, Location))

A: If you look at the help file, reorder is used to reorder factor levels. Somewhat confusingly, order is used (among other things) to order rows of data.frames.
It is possible to use the factor function along with order to achieve your desired result.
dfMyOrder <- df[order(factor(row.names(df), levels=c('L', 'D', 'S', 'T', 'H', 'P', 'U'))),]

which returns
dfMyOrder

   Ada Alf   Lk  Lnd Myv Raud
L   11   0   34    4  34    5
D    3   0   10    0  59    0
S  585   0 1880    0 460  109
T  100   0    0    0 233    0
H 3777   0    0    0   8    0
P    0   0    0    0 187    0
U  234 517  401 4057   9    0

This will work for table objects as well as data.frames, but as @gavin-simpson discusses in his post, it would be preferable to perform the ordering prior to calculating the table.

A: The ordering from your row names is indeed alphabetical and it comes from the fact that your variable Type is a factor (or is being coerced into it). You can re-order the levels of your factors before using table.
Here is an example using the warpbreaks dataset that comes with R:
w <- warpbreaks
table(w$tension, w$wool)
# The default order here is L, M, H (not alphabetical)
#    A B
#  L 9 9
#  M 9 9
#  H 9 9
## let's redefine the order:
w$tension <- factor(w$tension, levels = c("H", "M", "L"))
table(w$tension, w$wool)
#    A B
#  H 9 9
#  M 9 9
#  L 9 9