问:
How to change background color of UIDatePicker set as UITextField inputView?
Please do not mark as duplicate. The available answers haven't answered my issue.

I am using a UIDatePicker as UITextField's inputView (inside a UITableViewCell):

```<code>@IBOutlet weak var theTextField: UITextField!

func textFieldDidBeginEditing(_ textField: UITextField) {

        let picker = UIDatePicker()
        picker.setValue(Colors.CI2, forKeyPath: "textColor")

        picker.datePickerMode = .date

        textField.inputView = picker
        textField.inputView?.backgroundColor = Colors.CI1 // my desired color

        picker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)

}
</code>```

The problem: The color does only change, once the picker is called a second time.

I guess, that this issue occurs because the inputView is optional and only once the picker is called a second time, the inputView is instantiated at the moment where I want to change the color.

I have tried to subclass UITextField and observe inputView.

```<code>class DateTextField: UITextField {

    override var inputView: UIView? {

        didSet {

            self.inputView?.backgroundColor = Colors.CI1
            self.reloadInputViews()

        }

    }

}
</code>```

Unfortunately without success. Same behavior. What am I missing? Help is very appreciated.

答: create a function which holds the date picker colours, and call it in the textFieldDidBeginEditing. I think that should solve your issue.

Body:
Please do not mark as duplicate. The available answers haven't answered my issue.

I am using a UIDatePicker as UITextField's inputView (inside a UITableViewCell):

@IBOutlet weak var theTextField: UITextField!

func textFieldDidBeginEditing(_ textField: UITextField) {

        let picker = UIDatePicker()
        picker.setValue(Colors.CI2, forKeyPath: "textColor")

        picker.datePickerMode = .date

        textField.inputView = picker
        textField.inputView?.backgroundColor = Colors.CI1 // my desired color

        picker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)

}

The problem: The color does only change, once the picker is called a second time.

I guess, that this issue occurs because the inputView is optional and only once the picker is called a second time, the inputView is instantiated at the moment where I want to change the color.

I have tried to subclass UITextField and observe inputView.

class DateTextField: UITextField {

    override var inputView: UIView? {

        didSet {

            self.inputView?.backgroundColor = Colors.CI1
            self.reloadInputViews()

        }

    }

}

Unfortunately without success. Same behavior. What am I missing? Help is very appreciated.


来源: stackexchange

问:
MasterPage Load Theme
on asp.net C#,
i want to change the theme when page is load, this action requiers PreInit Event, Which Masterpage dont have. what is the solution for that issue?

thanks,

答: One way is to create an Http Module (Rick van den Bosch blogs)</p>

ContentLicense: CC BY-SA 2.5

Title: MasterPage Load Theme


问:
SQL Script works in phpAdmin but not on web site echo
The following SQL script works in SQL Editor in phpMyAdmin. However, in PHP I cannot get this script to display real content online. It is all blank. The problem is somewhere in my echo. I tried using $row['a.qty'] but that did not work.

```<code>$sql = "SELECT  a.qty + b.qty - c.qty as 'QTY', a.part_num as 'Part Num', a.part_desc as 'Description'
        FROM    Inv_Physical_Count a,
                Inv_Restock b,
                Inv_Orders c
        WHERE   a.part_id = b.part_id
        AND     a.part_id = c.part_id
        ORDER BY a.order_form_seq";

        $q = $pdo->prepare($sql);
        $q->execute(array());

        while ($row = $q->fetch(PDO::FETCH_ASSOC))
        {
            echo    '<tr>';
            echo    '<td>' . $row['qty'] . '</td>';
            echo    '<td>' . $row['part_num'] . '</td>';
            echo    '<td>' . $row['part_desc'] . '</td>';
        }
</code>```

答:
First, back tick (not quote) your AS values, especially if they are to contain spaces:

```<code>$sql = "SELECT  a.qty + b.qty - c.qty as `QTY`, a.part_num as `Part Num`, a.part_desc as `Description`
</code>```

You're telling the query these values should be the column names. Because of that use the AS values as your array identifiers:

```<code>while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
    echo    '<tr>';
    echo    '<td>' . $row['QTY'] . '</td>';
    echo    '<td>' . $row['Part Num'] . '</td>';
    echo    '<td>' . $row['Description'] . '</td>';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following SQL script works in SQL Editor in phpMyAdmin. However, in PHP I cannot get this script to display real content online. It is all blank. The problem is somewhere in my echo. I tried using $row['a.qty'] but that did not work.

$sql = "SELECT  a.qty + b.qty - c.qty as 'QTY', a.part_num as 'Part Num', a.part_desc as 'Description'
        FROM    Inv_Physical_Count a,
                Inv_Restock b,
                Inv_Orders c
        WHERE   a.part_id = b.part_id
        AND     a.part_id = c.part_id
        ORDER BY a.order_form_seq";

        $q = $pdo->prepare($sql);
        $q->execute(array());

        while ($row = $q->fetch(PDO::FETCH_ASSOC))
        {
            echo    '
';
            echo    '' . $row['qty'] . '	';
            echo    '' . $row['part_num'] . '	';
            echo    '' . $row['part_desc'] . '	';
        }

Body:
First, back tick (not quote) your AS values, especially if they are to contain spaces:

$sql = "SELECT  a.qty + b.qty - c.qty as `QTY`, a.part_num as `Part Num`, a.part_desc as `Description`

You're telling the query these values should be the column names. Because of that use the AS values as your array identifiers:

while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
    echo    '<tr>';
    echo    '<td>' . $row['QTY'] . '</td>';
    echo    '<td>' . $row['Part Num'] . '</td>';
    echo    '<td>' . $row['Description'] . '</td>';
}


问:
C# asp.net data annotation setting field to only number but not required
I have a viewmodel class which I set to validate with data annotations in my project like this:

```<code>[Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price (e.g. 20.00)")]

    public double MinPrice { get; set; }
    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid maximum price (e.g. 20.00)")]

    public double MaxPrice { get; set; }
</code>```

What I would like to do is to make the field trigger validation only if something is entered, and that something is not a valid double number... If the field is left empty I'd just like to ignore it...

The way I did it now if I enter firstly something and then try to leave the field empty, the validation triggers and says the field is required, which is not what I want...

What am I doing wrong here?

答:
You should use 'RegularExpression' instead of 'range'. Something like:</p>

```<code>[RegularExpression(@"^-?[0-9]\d{0,2}(\.\d{0,1})?$", ErrorMessage = "Invalid value")]
</code>```

Body:
I have a viewmodel class which I set to validate with data annotations in my project like this:

[Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price (e.g. 20.00)")]

    public double MinPrice { get; set; }
    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid maximum price (e.g. 20.00)")]

    public double MaxPrice { get; set; }

What I would like to do is to make the field trigger validation only if something is entered, and that something is not a valid double number... If the field is left empty I'd just like to ignore it...

The way I did it now if I enter firstly something and then try to leave the field empty, the validation triggers and says the field is required, which is not what I want...

What am I doing wrong here?

Body:
You should use 'RegularExpression' instead of 'range'. Something like:

[RegularExpression(@"^-?[0-9]\d{0,2}(\.\d{0,1})?$", ErrorMessage = "Invalid value")]


问:
How do you train LSTMs on time series data with too many time steps?
I am trainig LSTM/GRUs on time series data.

My input data's shape is (5000,12) i.e. 5000 time steps and at each time step has 12 dimensions.
When I am trying to run LSTM on this data taking each time step (dim: 12) at a time; this means I am unrolling LSTM 5000 times and I am unable to train the network on my laptop as it is exceeding 16gb ram.

One solution I can think of is can I combine, say, 10 time steps data and feed that data (dim: 10*12) to LSTM network (potentially unrolling only 500 times)...

Can this give me good results?

答: there are various ways to tackle this problem depending on the dataset you have, have a look at this: http://machinelearningmastery.com/handle-long-sequences-long-short-term-memory-recurrent-neural-networks/</p>


问:
Does Android Studio has a memory analyzer tool like MAT in Eclipse?
Eclipse has a powerful memory analyzer tool: MAT.

Does Android Studio have such a powerful tool, too ?

p.s.  I have found a "Allocation Tracking" in the Android DDMS page.
And I also know the "Memory Monitor".

But they seem very simple. Take "Memory Monitor" for example, it is only a wave graph. I don't even know which object are still connecting with the GC root.

答:
Android Studio 3.0 preview has much a much better tool, comparable to MAT, that also offers CPU and network activity profiling.

https://developer.android.com/studio/preview/features/android-profiler.html


问:
Download a file from userscloud
I'm trying to write a code so i can download files from the site www.userscloud.com (for example this one https://userscloud.com/nyp52eufhova).

This site has a Download button that has to be clicked in order to appear another button with the "real" url of the file (this url then appears inside the html code too).

So i thought i should use Selenium and PhantomJS to simulate the click and wrote this code:

```<code>from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.PhantomJS()
driver.get("https://userscloud.com/nyp52eufhova")
driver.find_element_by_xpath("//*[@id='btn_download']").click()
print (driver.page_source)
</code>```

The problem is that the returned page source doesn't contain the "real" URL. It is as if the button was not clicked.

I have tried to click the button using other elements like class name and id with no success. I also tried to wait with driver.implicitly_wait(10) before getting the page source but the outcome was the same.

Any ideas?

答:
It's not a Selenium solution but you actually don't need a browser to grab the file. You can just use requests. I just threw this little thing together. It has two functions - one that grabs the file name and one that grabs the file.

```<code># coding: utf-8
import requests
from bs4 import BeautifulSoup

def get_file_name(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, "html.parser")
    file_name = soup.h2.text
    return file_name

def get_zip_from_userscloud(url):
    headers = {
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4',
        'Cache-Control':'max-age=0',
        'Connection':'keep-alive',
        'Content-Type':'application/x-www-form-urlencoded',
        'Host':'userscloud.com',
        'Origin':'https://userscloud.com',
        'Referer':url,
        'Upgrade-Insecure-Requests':1,
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
    }

    payload = {
        'op':'download2',
        'id':url.split("/")[-1],
        'referer':url,
        'adblock_detected':0,
        'down_script':1
        }

    r = requests.post(url, data=payload, headers=headers)
    return r.content

url = 'https://userscloud.com/nyp52eufhova'
file_name = get_file_name(url)
content = get_zip_from_userscloud(url)
with open (file_name, 'wb') as f:
    f.write(content)
</code>```

So if you have a bunch of links from userscloud, that you'd iterate on, you'd just put them in a list an say:

```<code>for url in links_list:
    file_name = get_file_name(url)
    content = get_zip_from_userscloud(url)
    with open (file_name, 'wb') as f:
        f.write(content)
</code>```

Cheers...

Title: Download a file from userscloud

Body:
I'm trying to write a code so i can download files from the site www.userscloud.com (for example this one https://userscloud.com/nyp52eufhova).

This site has a Download button that has to be clicked in order to appear another button with the "real" url of the file (this url then appears inside the html code too).

So i thought i should use Selenium and PhantomJS to simulate the click and wrote this code:

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.PhantomJS()
driver.get("https://userscloud.com/nyp52eufhova")
driver.find_element_by_xpath("//*[@id='btn_download']").click()
print (driver.page_source)

The problem is that the returned page source doesn't contain the "real" URL. It is as if the button was not clicked.

I have tried to click the button using other elements like class name and id with no success. I also tried to wait with driver.implicitly_wait(10) before getting the page source but the outcome was the same.

Any ideas?

Body:
It's not a Selenium solution but you actually don't need a browser to grab the file. You can just use requests. I just threw this little thing together. It has two functions - one that grabs the file name and one that grabs the file.

# coding: utf-8
import requests
from bs4 import BeautifulSoup

def get_file_name(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, "html.parser")
    file_name = soup.h2.text
    return file_name

def get_zip_from_userscloud(url):
    headers = {
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4',
        'Cache-Control':'max-age=0',
        'Connection':'keep-alive',
        'Content-Type':'application/x-www-form-urlencoded',
        'Host':'userscloud.com',
        'Origin':'https://userscloud.com',
        'Referer':url,
        'Upgrade-Insecure-Requests':1,
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
    }

    payload = {
        'op':'download2',
        'id':url.split("/")[-1],
        'referer':url,
        'adblock_detected':0,
        'down_script':1
        }

    r = requests.post(url, data=payload, headers=headers)
    return r.content

url = 'https://userscloud.com/nyp52eufhova'
file_name = get_file_name(url)
content = get_zip_from_userscloud(url)
with open (file_name, 'wb') as f:
    f.write(content)

So if you have a bunch of links from userscloud, that you'd iterate on, you'd just put them in a list an say:

for url in links_list:
    file_name = get_file_name(url)
    content = get_zip_from_userscloud(url)
    with open (file_name, 'wb') as f:
        f.write(content)

Cheers...


问:
Run specific code when overloading C++ operators
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator):

```<code>... operator<(A a) { return *this; }
... operator<(B b) { return *this; }
... operator<(C c) { return *this; }
</code>```

A, B, C classes are not related in any way(if that, is of any matter).

Now In my program I only have the 2 following cases:

```<code>A a = new A();
B b = new B();
C c = new C();

(First Case): new Foo() < a < b;
</code>```

or

```<code>(Second Case): new Foo() < a < b < c;
</code>```

Whenever I have the first case (which ends with b), I want to execute a function run() when I have read(I know) the b instance. So the idea is that I would have the following code in the Foo class:

```<code>... operator<(B b)
{
    run();
}
</code>```

Now when I have the code of the first case, run() is being executed.

The problem is that when I have code like in the second case(which ends in c).
I want to execute the run() function again but NOT until I know what c is.
So If I have the previous piece of code run() will be called when doing < b
which is not what I want as I don't know c yet.
If I add run() in operator<(C c) I will call run() twice.

In a few words what I want to accomplish is when having the first case call run() at operator<(B b) and when I have the second case ONLY call run at operator<(C c).

Any ideas on how this can be solved(if it can)?

答:
```<code>class PreFoo {
public:
    PreFoo() { ... }
    PreFoo & operator<<(A a) { ...; return *this; }
    PreFoo & operator<<(B b) { ...; return *this; }
    PreFoo & operator<<(C c) { ...; return *this; }

    int aa, bb, cc; // save your information
};

PreFoo MakeFoo() { return PreFoo(); }

class Foo {
public:
    Foo(const PreFoo & pre) { run(); } // implicit conversion

    void run() {} // your run!!
};

void g() {
  A a; B b; C c;
  // implicit conversion at the end
  Foo foo1 = MakeFoo() << a << b;
  Foo foo2 = PreFoo() << a << b << c;
}
</code>```

Body:
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator):

... operator<(A a) { return *this; }
... operator<(B b) { return *this; }
... operator<(C c) { return *this; }

A, B, C classes are not related in any way(if that, is of any matter).

Now In my program I only have the 2 following cases:

A a = new A();
B b = new B();
C c = new C();

(First Case): new Foo() < a < b;

or

(Second Case): new Foo() < a < b < c;

Whenever I have the first case (which ends with b), I want to execute a function run() when I have read(I know) the b instance. So the idea is that I would have the following code in the Foo class:

... operator<(B b)
{
    run();
}

Now when I have the code of the first case, run() is being executed.

The problem is that when I have code like in the second case(which ends in c).
I want to execute the run() function again but NOT until I know what c is.
So If I have the previous piece of code run() will be called when doing < b
which is not what I want as I don't know c yet.
If I add run() in operator<(C c) I will call run() twice.

In a few words what I want to accomplish is when having the first case call run() at operator<(B b) and when I have the second case ONLY call run at operator<(C c).

Any ideas on how this can be solved(if it can)?


问:
How to use login_reuqired on Update/Create/Delete Views in Django
I am trying to use @login_reuqired decorator. For normal functions it is working fine, but when i try to use it in my UpdateView i am getting this error "AttributeError: 'function' object has no attribute 'as_view'"

This is my view.py

```<code>@login_required
class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`
</code>```

This is in my urls.py

```<code> url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'),
</code>```

Any suggestions ?

答:
For Django 1.9+ you can use a mixin:</p>

```<code>from django.contrib.auth.mixins import LoginRequiredMixin

class RoomUpdate(LoginRequiredMixin, UpdateView):
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`
</code>```

Body:
I am trying to use @login_reuqired decorator. For normal functions it is working fine, but when i try to use it in my UpdateView i am getting this error "AttributeError: 'function' object has no attribute 'as_view'"

This is my view.py

@login_required
class RoomUpdate(UpdateView):
    model = Room
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`

This is in my urls.py

 url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'),

Any suggestions ?

Body:
For Django 1.9+ you can use a mixin:

from django.contrib.auth.mixins import LoginRequiredMixin

class RoomUpdate(LoginRequiredMixin, UpdateView):
    fields = ['Name', 'RoomTypeID']
    template_name='WebApp/room_form.html'`


问:
fit size of parent layout
I have a simple linear layout and want to divide the screen into two equally sized parts.

In the upper one, I want to put a SurfaceView that has exactly the same size as its parent, i.e. half of the screen. Unfortunately, it always either takes all the screen or nothing (depending on the configuration).
Why is that and how can I change it?

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="2"
    android:orientation="vertical">

    <LinearLayout android:id="@+id/layoutUpperDaw"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#192832">

        <com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"

            android:layout_height="0pt"
            android:layout_weight="1"

            OR

            android:layout_height="match_parent"

            >

        </com.example.MySurvfaceView>

    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#193222">

        ...
    </LinearLayout>
</LinearLayout>
</code>```

答:
Programmatically:

Find the parent layout.

GridLayout gridLayout =(GridLayout)findViewById(R.id.gridLayout);`

Get measured height and Width of parent.

int height = gridLayout.measuredHeight();

int width = gridLayout.measuredWidth();

3.Calculate child view height and width.For example two child each taking 50% of height in the parent but taking full width of parent:

```<code>int childHeight = height/2;
int childWidth = width;
</code>```

4.Get instanceof LayoutParams depending on parent type.

```<code>GridLayout.LayoutParams params = new GridLayout.LayoutParams();
</code>```

5. Set height and width on layout params.

```<code> params.width = childWidth;
 params.height = childHeight;
</code>```

6.Create child view and set Layout params.

```<code>ImageView imageview = new ImageView();
imageview.setLayoutParams(params);
</code>```

7.Add child View to parent.

```<code> gridLayout.addView(ImageView);
</code>```

Title: fit size of parent layout

Body:
I have a simple linear layout and want to divide the screen into two equally sized parts.

In the upper one, I want to put a SurfaceView that has exactly the same size as its parent, i.e. half of the screen. Unfortunately, it always either takes all the screen or nothing (depending on the configuration).
Why is that and how can I change it?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="2"
    android:orientation="vertical">

    <LinearLayout android:id="@+id/layoutUpperDaw"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#192832">

        <com.example.MySurvfaceView
            android:id="@+id/id_mySurfaceView"
            android:layout_width="match_parent"

            android:layout_height="0pt"
            android:layout_weight="1"

            OR

            android:layout_height="match_parent"

            >

        </com.example.MySurvfaceView>

    </LinearLayout>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#193222">

        ...
    </LinearLayout>
</LinearLayout>

Body:
Programmatically:

Find the parent layout.

GridLayout gridLayout =(GridLayout)findViewById(R.id.gridLayout);`

Get measured height and Width of parent.

int height = gridLayout.measuredHeight();

int width = gridLayout.measuredWidth();

3.Calculate child view height and width.For example two child each taking 50% of height in the parent but taking full width of parent:

int childHeight = height/2;
int childWidth = width;

4.Get instanceof LayoutParams depending on parent type.

GridLayout.LayoutParams params = new GridLayout.LayoutParams();

5. Set height and width on layout params.

 params.width = childWidth;
 params.height = childHeight;

6.Create child view and set Layout params.

ImageView imageview = new ImageView();
imageview.setLayoutParams(params);

7.Add child View to parent.

 gridLayout.addView(ImageView);


问:
create corner arc with css
How would you create such corner arc using css?

This is starter template: https://codepen.io/anon/pen/rwraXG

I was hoping that I would be able to use black outer div and red inner div, and use border radius to leave just the top left corner showing through. I messed something midway.

.bar {
  width: 100px;
  height: 20px;
  background-color: red;
}

.outer {
  height: 100%;
  width: 8px;
  background-color: black;
}

.inner {
  height: 100%;
  width: 100%;
  background-color: red;
  border: 2px solid black;
  border-radius: 15px 0px 0px 0px:
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bar">
  <div class="outer">
    <div class="inner"></div>
  </div>
</div></code>```

答:
I suggest you to do it with 2 DIVs as below:
HTML :

```<code><div class="outer">
  <div class="inner"></div>
</div>
</code>```

CSS :

```<code>.outer,.inner{
  width:200px;
  height:80px;
}
.outer {
  background-color:black;
}
.inner {
  background-color:red;
  border-radius:20px 0 0 0; /* numbers are :  top left bottom right*/
}
</code>```

https://codepen.io/FaridNaderi/pen/pwZJyP

Hope it helps

Title: create corner arc with css

Body:
I suggest you to do it with 2 DIVs as below:
HTML :

<div class="outer">
  <div class="inner"></div>
</div>

CSS :

.outer,.inner{
  width:200px;
  height:80px;
}
.outer {
  background-color:black;
}
.inner {
  background-color:red;
  border-radius:20px 0 0 0; /* numbers are :  top left bottom right*/
}

https://codepen.io/FaridNaderi/pen/pwZJyP

Hope it helps


问:
VBA excel Application.getsaveasfilename error 13
I'm trying to create a macro to have the user save a backup of the workbook to a specific place. I tried my code below but got an error 13 message. I don't need it to be saved as a macro-enabled workbook, but I thought that would be easier.

```<code>Sub openSaveDialog()
'
' gives error 13 message when clicking save
'
Dim saveSuccess As Boolean
Dim fNameRec As String
Dim dateNow As String
Dim saveToDir As String
saveToDir = "Z:\location of save\Old Archive spreadsheets\"
dateNow = Format(Now(), "mmddyyyy")
fNameRec = saveToDir & "BinderArchiveBackup_" & dateNow
Sheets(3).Range("E25") = fNameRec
'check if backed up today
If (Sheets(3).Range("E22") = Date) Then
    MsgBox "backup already saved today no need to save again"
    Exit Sub
End If

'open save as window
saveSuccess = Application.GetSaveAsFilename(InitialFileName:=fNameRec, FileFilter:= _
"Excel Files (*.xlsx)," & "*.xlsx, Macro Enabled" & _
"Workbook (*.xlsm), *xlsm")
'if backup saved, update date of last backup
If saveSuccess Then
    Sheets(3).Range "E22" = Date
    MsgBox "save successful"
End If
'if backup not saved, inform user
If Not saveSuccess Then
    MsgBox "save canceled, please save backup before adding new items to the archive today"
End If
End Sub
</code>```

Things I tried tweaking

File filter to just macro enabled

File filter to just excel workbook

Blank file filter saving as type all files

Blank file filter with .xlsx at the end of the name

initial filename without directory but with ChDir so it opens in the right save location anyway

Any help would be great.

Save as window that opens

答:
GetSaveAsFilename returns a Variant, which will be a boolean False if the user cancelled the SaveAs dialog, or a string containing the filename that they chose if they didn't cancel the dialog.

Your line saying

```<code>Dim saveSuccess As Boolean
</code>```

will cause an issue if a non-boolean value is returned.  So use

```<code>Dim saveSuccess As Variant
</code>```

instead.

This will still leave you with other problems though:

Sheets(3).Range "E22" = Date is invalid, and is probably meant to be Sheets(3).Range("E22") = Date

*xlsm should probably be *.xlsm

At no point are you actually saving the file.  Your final bits of code should probably be something like:

```<code>If saveSuccess = False Then
    'if backup not saved, inform user
    MsgBox "save canceled, please save backup before adding new items to the archive today"
Else
    If UCase(Right(saveSuccess, 5)) = ".XLSM" Then
        ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbookMacroEnabled
        'if backup saved, update date of last backup
        Sheets(3).Range("E22") = Date
        MsgBox "save successful"
    ElseIf UCase(Right(saveSuccess, 5)) = ".XLSX" Then
        ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbook
        'if backup saved, update date of last backup
        Sheets(3).Range("E22") = Date
        MsgBox "save successful"
    Else
        MsgBox "Unrecognised file extension chosen - backup not created"
    End If
End If
</code>```

Body:
I'm trying to create a macro to have the user save a backup of the workbook to a specific place. I tried my code below but got an error 13 message. I don't need it to be saved as a macro-enabled workbook, but I thought that would be easier.

Sub openSaveDialog()
'
' gives error 13 message when clicking save
'
Dim saveSuccess As Boolean
Dim fNameRec As String
Dim dateNow As String
Dim saveToDir As String
saveToDir = "Z:\location of save\Old Archive spreadsheets\"
dateNow = Format(Now(), "mmddyyyy")
fNameRec = saveToDir & "BinderArchiveBackup_" & dateNow
Sheets(3).Range("E25") = fNameRec
'check if backed up today
If (Sheets(3).Range("E22") = Date) Then
    MsgBox "backup already saved today no need to save again"
    Exit Sub
End If

'open save as window
saveSuccess = Application.GetSaveAsFilename(InitialFileName:=fNameRec, FileFilter:= _
"Excel Files (*.xlsx)," & "*.xlsx, Macro Enabled" & _
"Workbook (*.xlsm), *xlsm")
'if backup saved, update date of last backup
If saveSuccess Then
    Sheets(3).Range "E22" = Date
    MsgBox "save successful"
End If
'if backup not saved, inform user
If Not saveSuccess Then
    MsgBox "save canceled, please save backup before adding new items to the archive today"
End If
End Sub

Things I tried tweaking

File filter to just macro enabled

File filter to just excel workbook

Blank file filter saving as type all files

Blank file filter with .xlsx at the end of the name

initial filename without directory but with ChDir so it opens in the right save location anyway

Any help would be great.

Save as window that opens

Body:
GetSaveAsFilename returns a Variant, which will be a boolean False if the user cancelled the SaveAs dialog, or a string containing the filename that they chose if they didn't cancel the dialog.

Your line saying

Dim saveSuccess As Boolean

will cause an issue if a non-boolean value is returned.  So use

Dim saveSuccess As Variant

instead.

This will still leave you with other problems though:

Sheets(3).Range "E22" = Date is invalid, and is probably meant to be Sheets(3).Range("E22") = Date

*xlsm should probably be *.xlsm

At no point are you actually saving the file.  Your final bits of code should probably be something like:

If saveSuccess = False Then
    'if backup not saved, inform user
    MsgBox "save canceled, please save backup before adding new items to the archive today"
Else
    If UCase(Right(saveSuccess, 5)) = ".XLSM" Then
        ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbookMacroEnabled
        'if backup saved, update date of last backup
        Sheets(3).Range("E22") = Date
        MsgBox "save successful"
    ElseIf UCase(Right(saveSuccess, 5)) = ".XLSX" Then
        ActiveWorkbook.SaveAs saveSuccess, xlOpenXMLWorkbook
        'if backup saved, update date of last backup
        Sheets(3).Range("E22") = Date
        MsgBox "save successful"
    Else
        MsgBox "Unrecognised file extension chosen - backup not created"
    End If
End If


问:
Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails
I'm getting this error:

Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails.

I have a standard add function to EF 6

```<code>    public Logs AddLog(Logs p)
    {
        Logs.Add(p);
        SaveChanges();
        return p;
    }
</code>```

I've defined the field in my class as:

```<code>    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime EntryDate { get; set; }
</code>```

Should I be populating this field in my controller at all?

答: Please note that column EntryDate in table does not allow NULL. Hence, you must ensure that object p got valid date. Other option could be to change table schema and modify EntryDate column to accept NULL.

Body:
I'm getting this error:

Cannot insert the value NULL into column 'EntryDate', table 'eApps.Logs.dbo.Logs'; column does not allow nulls. INSERT fails.

I have a standard add function to EF 6

    public Logs AddLog(Logs p)
    {
        Logs.Add(p);
        SaveChanges();
        return p;
    }

I've defined the field in my class as:

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime EntryDate { get; set; }

Should I be populating this field in my controller at all?


问:
How to use a C++ dll in Unity3D?
I am aware of this similar question, but it does not respond to my problem.

I have written two .dlls using Visual Studio 2010. One is in C++, and communicates with an SDK that was written in C++. The other is a C# wrapper for that C++ library, so that it can be used in C# contexts.

My plan was that this would let me use my code in Unity3D, but apparently that is not the case. It seems like Unity3D does not allow me to import .dlls as Assets if they are not a .NET assembly. So I can add my C# wrapper, but not the C++ dll.

This results in a DllNotFoundException whenever I try to access the C++ library. I have tried simply copying the C++ library into the Assets/Plugins folder, but that gives the same results.

Is there a way to do this properly? This is a very vital part of my project setup.

答:
Note that the DllNotFoundException can be caused by building your Unity DLL in Debug instead of Release!

A simple oversight that can cause a headache.

Title: How to use a C++ dll in Unity3D?


问:
Database change dont work
Im trying to update a whole lot of posts on my website through the database/phpmyadmin.

**My Mission:
I'd like to unpublish a bunch of posts which have a certain catergory (term).
Posts and terms have their own column in the database.
**

I've entered this SQL query:

```<code>Update posts
SET posts.post_status = 'draft'
WHERE terms.term_id = 4 and posts.post_type ='post'
</code>```

This should work,  but I get this message:
1054 -  unknown column in where clause (terms.term_id ).

This is very strange, because phpmyadmin suggests this column itself while entering the query. Any idea how to solve this?

答:
I had to add the inbetween tables in the query:</p>

```<code>Update posts
INNER JOIN terms, term_relationships, term_taxonomy
SET posts.post_status = 'draft'
WHERE terms.term_id = 4 and posts.post_type ='post'
</code>```

Title: Database change dont work

Body:
Im trying to update a whole lot of posts on my website through the database/phpmyadmin.

**My Mission:
I'd like to unpublish a bunch of posts which have a certain catergory (term).
Posts and terms have their own column in the database.
**

I've entered this SQL query:

Update posts
SET posts.post_status = 'draft'
WHERE terms.term_id = 4 and posts.post_type ='post'

This should work,  but I get this message:
1054 -  unknown column in where clause (terms.term_id ).

This is very strange, because phpmyadmin suggests this column itself while entering the query. Any idea how to solve this?

Body:
I had to add the inbetween tables in the query:

Update posts
INNER JOIN terms, term_relationships, term_taxonomy
SET posts.post_status = 'draft'
WHERE terms.term_id = 4 and posts.post_type ='post'


问:
nodejs json.parse preserve scientific notation
Can anyone help me figure out a JSON.parse() issue I'm facing?  This is utilizing Node.js v6.9.

Basically, I need to store some data within my database EXACTLY as I see it in a file.  While I have the vast majority of this working, there's a couple kinks I'm trying to iron out.

First issue is when I run across scientific notation within an array.  When I parse this, it does NOT preserve "e-n" unless it's greater than 6.  Thus, the result is that I get a non-scientific notation value stored in an array.  Is there some way to force the parse() function to preserve this?  See examples I ran from my debugger within Visual Studio Code:

```<code>JSON.parse('[3.908e-3, -5.775e-7]');
Array[2] [0.003908, -5.775e-7]

JSON.parse('[3.908e-4, -5.775e-7]');
Array[2] [0.0003908, -5.775e-7]

JSON.parse('[3.908e-5, -5.775e-7]');
Array[2] [0.00003908, -5.775e-7]

JSON.parse('[3.908e-6, -5.775e-7]');
Array[2] [0.000003908, -5.775e-7]

JSON.parse('[3.908e-7, -5.775e-7]');
Array[2] [3.908e-7, -5.775e-7]
</code>```

Second issue is another formatting issue.  JSON.parse doesn't seem to preserve the decimals.  Like the first issue above, is it possible to make JSON.parse() preserve the number notation exactly as its given?  Notice how the parse is chopping off the zero decimal.

```<code>JSON.parse('[1.0, 2.0]')
Array[2] [1, 2]
</code>```

Was reading up on reviver functions that you can pass as a second argument to the parse() function, but I'm a bit lost on these.  Do I need to write my own custom function to preserve the format as is?

Edit: More information provided:
I'm trying to take a complex JSON object as-is, and store the entire structure in my Postgresql database. The file itself is initially uploaded as a Uint8Array.  I then do a toString() on that, and do a JSON.parse on the result.  So if this was the original contents of the uploaded file, I can do this:

```<code>uploadedFile.toString();
"{
    "someKey": {
      "id": "COG32",
      "control_id": "00D2FFFF0000",
      "coefficients": [3.908e-3, -5.775e-7]
    }
}"
</code>```

Then I can do this:

```<code>JSON.parse(uploadedFile.toString());
{
    "someKey": {
      "id": "COG32",
      "control_id": "00D2FFFF0000",
      "coefficients": [3.00908, -5.775e-7]
    }
}
</code>```

Some of the properties in the file I'm given contain arrays of two scientific notation values.

In order to do this, I'm parsing the json string to an object and able to iterate the keys and all its properties to store everything within its own record in the database.  This all works great, except for the fact that JSON.parse is automatically transforming 3.908e-3 into 3.003908.

I also need to recreate this json object EXACTLY as it was given to me, from the database.  I understand that they are the "same" numbers.  But when it comes to diffing the files (the original json object and the one I re-create from the database...), they are very different.
.toExponential() seems to give me the exponential variant of the number, but in string format.  If I were to use that, I would wind up with:

```<code>["3.908e-3", "-5.775e-7"]
</code>```

When what I want is:

```<code>[3.908e-3, -5.775e-7]
</code>```

答:
In your JSON, the data is stored as a type NUMBER; when you write 3.908e-4 it is equal to 0.0003908.

You then have 2 choices:

store your data as a string so it keeps the format (which is ok if you do not want to perform calculations) JSON.parse('["3.908e-3", "-5.775e-7"]');

force a format when you print the data eg (0.0004345).toExponential() --> 4.345e-4 or (1).toFixed(1) --> 1.0;

Body:
Can anyone help me figure out a JSON.parse() issue I'm facing?  This is utilizing Node.js v6.9.

Basically, I need to store some data within my database EXACTLY as I see it in a file.  While I have the vast majority of this working, there's a couple kinks I'm trying to iron out.

First issue is when I run across scientific notation within an array.  When I parse this, it does NOT preserve "e-n" unless it's greater than 6.  Thus, the result is that I get a non-scientific notation value stored in an array.  Is there some way to force the parse() function to preserve this?  See examples I ran from my debugger within Visual Studio Code:

JSON.parse('[3.908e-3, -5.775e-7]');
Array[2] [0.003908, -5.775e-7]

JSON.parse('[3.908e-4, -5.775e-7]');
Array[2] [0.0003908, -5.775e-7]

JSON.parse('[3.908e-5, -5.775e-7]');
Array[2] [0.00003908, -5.775e-7]

JSON.parse('[3.908e-6, -5.775e-7]');
Array[2] [0.000003908, -5.775e-7]

JSON.parse('[3.908e-7, -5.775e-7]');
Array[2] [3.908e-7, -5.775e-7]

Second issue is another formatting issue.  JSON.parse doesn't seem to preserve the decimals.  Like the first issue above, is it possible to make JSON.parse() preserve the number notation exactly as its given?  Notice how the parse is chopping off the zero decimal.

JSON.parse('[1.0, 2.0]')
Array[2] [1, 2]

Was reading up on reviver functions that you can pass as a second argument to the parse() function, but I'm a bit lost on these.  Do I need to write my own custom function to preserve the format as is?

Edit: More information provided:
I'm trying to take a complex JSON object as-is, and store the entire structure in my Postgresql database. The file itself is initially uploaded as a Uint8Array.  I then do a toString() on that, and do a JSON.parse on the result.  So if this was the original contents of the uploaded file, I can do this:

uploadedFile.toString();
"{
    "someKey": {
      "id": "COG32",
      "control_id": "00D2FFFF0000",
      "coefficients": [3.908e-3, -5.775e-7]
    }
}"

Then I can do this:

JSON.parse(uploadedFile.toString());
{
    "someKey": {
      "id": "COG32",
      "control_id": "00D2FFFF0000",
      "coefficients": [3.00908, -5.775e-7]
    }
}

Some of the properties in the file I'm given contain arrays of two scientific notation values.

In order to do this, I'm parsing the json string to an object and able to iterate the keys and all its properties to store everything within its own record in the database.  This all works great, except for the fact that JSON.parse is automatically transforming 3.908e-3 into 3.003908.

I also need to recreate this json object EXACTLY as it was given to me, from the database.  I understand that they are the "same" numbers.  But when it comes to diffing the files (the original json object and the one I re-create from the database...), they are very different.
.toExponential() seems to give me the exponential variant of the number, but in string format.  If I were to use that, I would wind up with:

["3.908e-3", "-5.775e-7"]

When what I want is:

[3.908e-3, -5.775e-7]


答:
```<code>    [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price (e.g. 20.00)")]
    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price (e.g. 20.00)")]
    public double? dub { get; set; }
</code>```

Change your model to double? if you are going to allow nulls

Title: C# asp.net data annotation setting field to only number but not required

Body:
    [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price (e.g. 20.00)")]
    [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price (e.g. 20.00)")]
    public double? dub { get; set; }

Change your model to double? if you are going to allow nulls


问:
'Double join' nested MySQL query?
as a beginner, I'm struggling with this for a few hours now, any help is much appreciated :D

I have 3 tables:

```<code>threads (id, title)
tags (id, name)
tag_thread (thread_id, tag_id)
</code>```

The following, working code returns the 5 most used tags (names) of the latest 100 threads:

```<code>select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5
</code>```

Question: Given there is a $tagId, how would I have to change to query to filter the results so that only those tags show up, which are connected to threads that use tags with $tagId?

Thank you very much!

答:
Try adding a where clause before "group by": WHERE ta.id IS NOT NULL.

See: Not equal <> != operator on NULL

Title: 'Double join' nested MySQL query?

Body:
as a beginner, I'm struggling with this for a few hours now, any help is much appreciated :D

I have 3 tables:

threads (id, title)
tags (id, name)
tag_thread (thread_id, tag_id)

The following, working code returns the 5 most used tags (names) of the latest 100 threads:

select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5

Question: Given there is a $tagId, how would I have to change to query to filter the results so that only those tags show up, which are connected to threads that use tags with $tagId?

Thank you very much!


问:
Can't get state to update array inside of an object correctly in REACT/REDUX
I am going to break this down step by step for what I want to happen so hopefully people can understand what I am wanting.

Using React/Redux, Lodash

I have many post that are sent from a back end api as an array. Each post has an _id. When I call on the action getAllPost() it gives me back that array with all the post. This is working just fine.

I then dispatch type GET_ALL_POSTS and it triggers the reducer reducer_posts to change/update the state.

reducer:

```<code>export default function(state = {}, action) {
  switch(action.type) {
    case GET_ALL_POSTS:
    const postsState =  _.mapKeys(action.payload.data, '_id');
    //const newPostsState = _.map(postsState, post => {
      //const newComments = _.mapKeys(post.comments, '_id');
    //});
      return postsState;
    break;
    default:
      return state;
    break;
  }
}
</code>```

As you can see I change the array into one giant object that contains many post as objects with keys that are equal to their '_id'. This works just fine and returning this part of the state also works fine.

As I mentioned each of these posts has a comments value that is an array. I would like to change the comments array into one large object that holds each comment as an object with a key that is equal to their '_id' just like I did in the post.

Now I need to do this all at once and return the newly created state with One large object that contains all the post as objects and on each of those post there should be a comments object that contains all the comments as objects. I will try to write some example code to show what I am trying to do.

Example:

```<code>BigPostsObject {
1: SinglePostObject{},
2: SinglePostObject{},
3: SinglePostObject {
  _id: '3',
  author: 'Mike',
  comments: BigCommentObject{1: SingleCommentObject{}, 2: SingleCommentObject{}}
 }
}
</code>```

I hope that the example kind of clears up what I am trying to do. If it still is confusing as to what I am doing then please ask and also please do not say things like use an array instead. I know I can use an array, but that is not helpful to this post as if others want to do it this way that is not helpful information.

答:
I believe nowadays JS builtin function can do this without requiring external libraries. Anyway this should be the way to go. I will really encourage you getting back to js builtin functions.

```<code>var data = [
 {
  _id: '3',
  title: 'Going on vaccation',
  comments:[
    {_id: 1, comment: 'hello'},
    {_id: 2, comment: 'world'}
  ]
 },

 {
  _id: '2',
  title: 'Going to dinner',
  comments:[
    {_id: 1, comment: 'hello'},
    {_id: 2, comment: 'world'}
  ]
 }

]

//you can use JS builtin reduce for this
var transformedPost= _.reduce(data, function(posts, post) {
  var newPost = Object.assign({}, post)
  newPost._id=post._id
  //you can use js builtin map for this
  newPost.comments = _.mapKeys(post.comments, '_id')

  // if you are using es6, replace the last three line with this
  //return Object.assign({}, posts, {[newPost._id]: newPost})

  var item = {}
  item[newPost._id]=newPost
  return Object.assign({}, posts, item)
},{});

console.log(transformedPost)
</code>```

https://jsbin.com/suzifudiya/edit?js,console

Body:
I am going to break this down step by step for what I want to happen so hopefully people can understand what I am wanting.

Using React/Redux, Lodash

I have many post that are sent from a back end api as an array. Each post has an _id. When I call on the action getAllPost() it gives me back that array with all the post. This is working just fine.

I then dispatch type GET_ALL_POSTS and it triggers the reducer reducer_posts to change/update the state.

reducer:

export default function(state = {}, action) {
  switch(action.type) {
    case GET_ALL_POSTS:
    const postsState =  _.mapKeys(action.payload.data, '_id');
    //const newPostsState = _.map(postsState, post => {
      //const newComments = _.mapKeys(post.comments, '_id');
    //});
      return postsState;
    break;
    default:
      return state;
    break;
  }
}

As you can see I change the array into one giant object that contains many post as objects with keys that are equal to their '_id'. This works just fine and returning this part of the state also works fine.

As I mentioned each of these posts has a comments value that is an array. I would like to change the comments array into one large object that holds each comment as an object with a key that is equal to their '_id' just like I did in the post.

Now I need to do this all at once and return the newly created state with One large object that contains all the post as objects and on each of those post there should be a comments object that contains all the comments as objects. I will try to write some example code to show what I am trying to do.

Example:

BigPostsObject {
1: SinglePostObject{},
2: SinglePostObject{},
3: SinglePostObject {
  _id: '3',
  author: 'Mike',
  comments: BigCommentObject{1: SingleCommentObject{}, 2: SingleCommentObject{}}
 }
}

I hope that the example kind of clears up what I am trying to do. If it still is confusing as to what I am doing then please ask and also please do not say things like use an array instead. I know I can use an array, but that is not helpful to this post as if others want to do it this way that is not helpful information.

Body:
I believe nowadays JS builtin function can do this without requiring external libraries. Anyway this should be the way to go. I will really encourage you getting back to js builtin functions.

var data = [
 {
  _id: '3',
  title: 'Going on vaccation',
  comments:[
    {_id: 1, comment: 'hello'},
    {_id: 2, comment: 'world'}
  ]
 },

 {
  _id: '2',
  title: 'Going to dinner',
  comments:[
    {_id: 1, comment: 'hello'},
    {_id: 2, comment: 'world'}
  ]
 }

]

//you can use JS builtin reduce for this
var transformedPost= _.reduce(data, function(posts, post) {
  var newPost = Object.assign({}, post)
  newPost._id=post._id
  //you can use js builtin map for this
  newPost.comments = _.mapKeys(post.comments, '_id')

  // if you are using es6, replace the last three line with this
  //return Object.assign({}, posts, {[newPost._id]: newPost})

  var item = {}
  item[newPost._id]=newPost
  return Object.assign({}, posts, item)
},{});

console.log(transformedPost)

https://jsbin.com/suzifudiya/edit?js,console


问:
Using SQL & Perl together - Which should be used for common functions?
I didn't find any dupes of this question, but if there is one or more, I'm sorry - please comment with link.

The question is basic, as probably is the answer.  If I'm using Perl to execute & act upon a database, which avenue (Perl vs. SQL) should I place the burden on when shared functions are involved?

Functions like - LEN, IF/ELSE, CONCAT and many more as well as arithmetic functions, for example are common to both systems.

This SQL statement is loaded with case blocks and other operations that can be replicated with Perl.  So, if the same logic could be implemented in Perl, is it worth re-writing?  What conditions influence the decision to take the burden of one system and place it on the other?

```<code>SELECT DISTINCT     s.id stu_id,
                    stu_id.fullname stu_name,
                    p.major1 major,
                    p.minor1 minor,
                    s.reg_hrs,
                    NVL(st.cum_earn_hrs,0) ttl_hrs,
                    p.adv_id curr_adv_id,
                    adv_id.fullname curr_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    (1165)
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    (35808)
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    (9179)
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    (70897)
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    (52125)
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    (24702)
                            WHEN    (p.minor1 = 'NURS')                                     THEN    (51569)
                            WHEN    (p.major1 = 'LEG')                                      THEN    (13324)
                            WHEN    (p.major1 = 'CC')                                       THEN    (73837)
                            WHEN    (p.major1 = 'CCRE')                                     THEN    (1133)
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    (9238)
                            ELSE    (p.adv_id)
                    END     new_adv_id,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('Deborah')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('Naomi')
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    ('Staff')
                            ELSE    (adv_id.fullname)
                    END     new_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('NS majors not assigned to Veronica go to Debbie')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('NS majors stay with Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('DART majors stay with Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('RT-RESP minors go to Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('CDSC-CDSD majors go to Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('CA-CB majors go to Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('NURS minors go to Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('LEG majors go to Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('CC majors go to Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('CCRE majors go to Naomi')
                            WHEN    (p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                            THEN    ('Current advisor is inactive')
                            WHEN    (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                            THEN    ('Total credits for this student did not meet the advisor reqs for this major')
                            WHEN    (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                            THEN    ('This student did not attend '||si.prev_sess||si.prev_yr)
                            WHEN    ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE (stat <> 'A' OR max_stu <= 0)))
                            THEN    ('Current advisor is not advising students with this major')
                            WHEN    ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0))
                            THEN    ('Current advisor is not advising students with this major')
                            ELSE    ('Student will stay with current advisor')
                    END     change_comm
FROM                stu_acad_rec s,
                    prog_enr_rec p,
                    OUTER stu_stat_rec st,
                    id_rec stu_id,
                    id_rec adv_id,
                    sess_info si
WHERE               s.id = p.id
                    AND s.id = st.id
                    AND s.id = stu_id.id
                    AND p.adv_id = adv_id.id
                    AND s.yr = si.curr_yr
                    AND s.sess = si.curr_sess
                    AND s.reg_hrs > 0
                    AND s.reg_stat IN ('C','R')
                    AND s.prog = 'UNDG'
                    AND p.prog = 'UNDG'
                    AND st.prog = 'UNDG'
                    AND s.id NOT IN (3,287,9238,59999) {System test use IDs}
INTO TEMP           stu_list
WITH NO LOG;
</code>```

答:
There are 2 considerations here:

Performance and scalability:

If you only have a few (1-2) concurrent clients, SQL might be faster doing the same logic.

However, if you start scaling up, it is a LOT more complicated to scale up a web server than to add new clients (or app servers if your business logic lives in an app server). So for any significant scale of requests, performance-wise you should ALWAYS try to offload as much processing as possible off of SQL server.

Code reuse:

If you only have ONE Perl code piece that will do this logic, then you can equally well put it in SQL or Perl.

If you have >1 piece of Perl code that does this logic, you can either put it in SQL (but see performance tradeoff discussed above), or better yet, put it into a Perl module and use that module everywhere. Basically, data access object (DAO).

If you have code in MANY languages including Perl that needs this, then you need to decide for yourself whether the performance issues of keeping the code in SQL server outweigh the pain ofkeeping the correct DAO logic in sync between libraries in >1 language.

Obviously, if you go for SQL side logic, you MUST encapsulate it into a view or stored procedure to avoid code duplication in those multiple languages.

Body:
I didn't find any dupes of this question, but if there is one or more, I'm sorry - please comment with link.

The question is basic, as probably is the answer.  If I'm using Perl to execute & act upon a database, which avenue (Perl vs. SQL) should I place the burden on when shared functions are involved?

Functions like - LEN, IF/ELSE, CONCAT and many more as well as arithmetic functions, for example are common to both systems.

This SQL statement is loaded with case blocks and other operations that can be replicated with Perl.  So, if the same logic could be implemented in Perl, is it worth re-writing?  What conditions influence the decision to take the burden of one system and place it on the other?

SELECT DISTINCT     s.id stu_id,
                    stu_id.fullname stu_name,
                    p.major1 major,
                    p.minor1 minor,
                    s.reg_hrs,
                    NVL(st.cum_earn_hrs,0) ttl_hrs,
                    p.adv_id curr_adv_id,
                    adv_id.fullname curr_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    (1165)
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    (35808)
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    (9179)
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    (70897)
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    (52125)
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    (24702)
                            WHEN    (p.minor1 = 'NURS')                                     THEN    (51569)
                            WHEN    (p.major1 = 'LEG')                                      THEN    (13324)
                            WHEN    (p.major1 = 'CC')                                       THEN    (73837)
                            WHEN    (p.major1 = 'CCRE')                                     THEN    (1133)
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    (9238)
                            ELSE    (p.adv_id)
                    END     new_adv_id,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('Deborah')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('Naomi')
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    ('Staff')
                            ELSE    (adv_id.fullname)
                    END     new_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('NS majors not assigned to Veronica go to Debbie')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('NS majors stay with Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('DART majors stay with Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('RT-RESP minors go to Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('CDSC-CDSD majors go to Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('CA-CB majors go to Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('NURS minors go to Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('LEG majors go to Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('CC majors go to Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('CCRE majors go to Naomi')
                            WHEN    (p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                            THEN    ('Current advisor is inactive')
                            WHEN    (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                            THEN    ('Total credits for this student did not meet the advisor reqs for this major')
                            WHEN    (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                            THEN    ('This student did not attend '||si.prev_sess||si.prev_yr)
                            WHEN    ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE (stat <> 'A' OR max_stu <= 0)))
                            THEN    ('Current advisor is not advising students with this major')
                            WHEN    ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0))
                            THEN    ('Current advisor is not advising students with this major')
                            ELSE    ('Student will stay with current advisor')
                    END     change_comm
FROM                stu_acad_rec s,
                    prog_enr_rec p,
                    OUTER stu_stat_rec st,
                    id_rec stu_id,
                    id_rec adv_id,
                    sess_info si
WHERE               s.id = p.id
                    AND s.id = st.id
                    AND s.id = stu_id.id
                    AND p.adv_id = adv_id.id
                    AND s.yr = si.curr_yr
                    AND s.sess = si.curr_sess
                    AND s.reg_hrs > 0
                    AND s.reg_stat IN ('C','R')
                    AND s.prog = 'UNDG'
                    AND p.prog = 'UNDG'
                    AND st.prog = 'UNDG'
                    AND s.id NOT IN (3,287,9238,59999) {System test use IDs}
INTO TEMP           stu_list
WITH NO LOG;


问:
MongoDB backup -> tar -> gz -> gpg
I have a MongoDB server and I am using mongodump command to create backup. I run command mongodump --out ./mongo-backup then tar -czf ./mongo-backup.tar.gz ./mongo-backup then gpg --encrypt ./mongo-backup.tar.gz > ./mongo-backup.tar.gz.gpg and send this file to backup server.

My MongoDB database has 20GB with MongoDB show dbs command, MongoDB mongodump backup directory has only 3.8GB, MongoDB gzipped-tarball has only 118MB and my gpg file has only 119MB in size.

How is this possible to reduce 20GB database to 119MB file? Is it fault tolerant?

I tried to create new server ( clone of production ), enabled firewall to ensure that noone could connect and run this backup procedure. I create fresh new server and import data and there are some differences:

I ran same command from mongo shell use db1; db.db1_collection1.count(); and use db2; db.db2_collection1.count(); and results are:

807843 vs. 807831 ( db1.collection1 source server vs. db1.collection1 restored server )

3044401 vs. 3044284 ( db2.collection1 source server vs. db2.collection1 restored server )

答:
If you have validated the counts and size of documents/collections in your restored data, this scenario is possible although atypical in the ratios described.

My MongoDB database has 20GB with MongoDB show dbs command

This shows you the size of files on disk, including preallocated space that exists from deletion of previous data. Preallocated space is available for reuse, but some MongoDB storage engines are more efficient than others.

MongoDB mongodumpbackup directory has only 3.8GB

The mongodump tool (as at v3.2.11, which you mention using) exports an uncompressed copy of your data unless you specify the --gzip option. This total should represent your actual data size but does not include storage used for indexes. The index definitions are exported by mongodump and the indexes will be rebuilt when the dump is reloaded via mongorestore.

With WiredTiger the uncompressed mongodump output is typically larger than the size of files on disk, which are compressed by default. For future backups I would consider using mongodump's built-in archiving and compression options to save yourself an extra step.

Since your mongodump output is significantly smaller than the storage size, your data files are either highly fragmented or there is some other data that you have not accounted for such as indexes or data in the local database. For example, if you have previously initialised this server as a replica set member the local database would contain a large preallocated replication oplog which will not be exported by mongodump.

You can potentially reclaim excessive unused space by running the compact command for a WiredTiger collection. However, there is an important caveat: running compact on a collection will block operations for the database being operated on so this should only be used during scheduled maintenance periods.

MongoDB gzipped-tarball has only 118MB and my gpg file has only 119MB in size.

Since mongodump output is uncompressed by default, compressing can make a significant difference depending on your data. However, 3.8GB to 119MB seems unreasonably good unless there is something special about your data (large number of small collections? repetitive data?). I would double check that your restored data matches the original in terms of collection counts, document counts, data size, and indexes.

Title: MongoDB backup -> tar -> gz -> gpg


问:
iOS app, is there a way to subscribe to an event when an app is updated through AppStore?
I need to cleanup some properties stored in NSUserDefaults for iOS app when it is updated to new version.

Is there a way to be notified when such an app update is going to happen or has happened?

Also is my assumption correct that when application is updated, NSUserDefaults are not automatically cleaned?

答:
In my experience NSUserDefaults are kept on future versions unless the user reinstall the app from scratch.

You can achieve your goal by keeping track of a version number that you can update on the App Delegate once the app gets open.

Based on that you can check and call a function with your logic to reset the properties you want.


问:
Custom font not working in React Native
I want to use a font from google fonts in my app. Here is the font.

I have placed the .ttf file in app/fonts.

package.json:

```<code>{
    "name": "xxx",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "rnpm": {
        "assets": ["./app/fonts"]
    },
    "jest": {
        "preset": "react-native",
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
            "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
        }
    },
    "dependencies": {
        "flow-typed": "^2.0.0",
        "immutable": "^3.8.1",
        "react": "~15.4.1",
        "react-native": "0.42.0",
        "react-native-vector-icons": "^4.0.0",
        "react-redux": "^5.0.3",
        "redux": "^3.6.0",
        "redux-immutable": "^4.0.0",
        "redux-observable": "^0.14.1",
        "rxjs": "^5.2.0"
    },
    "devDependencies": {
        "babel-eslint": "^7.1.1",
        "babel-jest": "19.0.0",
        "babel-preset-react-native": "1.9.1",
        "eslint": "^3.17.0",
        "eslint-plugin-flowtype": "^2.30.3",
        "eslint-plugin-jsx": "^0.0.2",
        "eslint-plugin-react": "^6.10.0",
        "eslint-plugin-react-native": "^2.3.1",
        "flow-bin": "^0.42.0",
        "jest": "19.0.2",
        "jest-cli": "^19.0.2",
        "react-test-renderer": "~15.4.1",
        "redux-devtools": "^3.3.2",
        "remote-redux-devtools": "^0.5.7"
    }
}
</code>```

then ran react-native link.

Then use the font in my app:

```<code>import { View, Text } from 'react-native'
import React from 'react'
import Width from '../width/Width'
import Shape from '../shape/Shape'
import Height from '../height/Height'
import Thickness from '../thickness/Thickness'

export const Volcalc = () => (
  <View style={styles.container}>
    <Text style={styles.text}>SHAPE</Text>
    <Shape />
    <Text style={styles.text}>HEIGHT</Text>
    <Height />
    <Text style={styles.text}>WIDTH</Text>
    <Width />
    <Text style={styles.text}>THICKNESS</Text>
    <Thickness />
  </View>
)

const $mainColor = '#00d1b2'
const styles = {
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: $mainColor
  },
  text: {
    textAlign: 'center',
    color: 'rgba(255, 255, 255, 0.9)',
    fontSize: 15,
    fontFamily: 'Orbitron'
  }
}
</code>```

In android it doesn't show the new font but has no error. In ios it has error:

Unrecognised font family "Orbitron"

What am I doing wrong?

How do I find out the EXACT value to place in fontFamily: 'xxx'?

答:
To find the exact value to use as your fontFamily, you can run the project from xcode after adding the following code to your AppDelegate.m file in xcode. You'll see a list of fonts in the output section in xcode.

```<code>for (NSString* family in [UIFont familyNames])
{
    NSLog(@"%@", family);

    for (NSString* name in [UIFont fontNamesForFamilyName: family])
    {
        NSLog(@"  %@", name);
    }
}
</code>```

Helpful link for adding custom fonts: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/

Title: Custom font not working in React Native

Body:
I want to use a font from google fonts in my app. Here is the font.

I have placed the .ttf file in app/fonts.

package.json:

{
    "name": "xxx",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "rnpm": {
        "assets": ["./app/fonts"]
    },
    "jest": {
        "preset": "react-native",
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
            "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
        }
    },
    "dependencies": {
        "flow-typed": "^2.0.0",
        "immutable": "^3.8.1",
        "react": "~15.4.1",
        "react-native": "0.42.0",
        "react-native-vector-icons": "^4.0.0",
        "react-redux": "^5.0.3",
        "redux": "^3.6.0",
        "redux-immutable": "^4.0.0",
        "redux-observable": "^0.14.1",
        "rxjs": "^5.2.0"
    },
    "devDependencies": {
        "babel-eslint": "^7.1.1",
        "babel-jest": "19.0.0",
        "babel-preset-react-native": "1.9.1",
        "eslint": "^3.17.0",
        "eslint-plugin-flowtype": "^2.30.3",
        "eslint-plugin-jsx": "^0.0.2",
        "eslint-plugin-react": "^6.10.0",
        "eslint-plugin-react-native": "^2.3.1",
        "flow-bin": "^0.42.0",
        "jest": "19.0.2",
        "jest-cli": "^19.0.2",
        "react-test-renderer": "~15.4.1",
        "redux-devtools": "^3.3.2",
        "remote-redux-devtools": "^0.5.7"
    }
}

then ran react-native link.

Then use the font in my app:

import { View, Text } from 'react-native'
import React from 'react'
import Width from '../width/Width'
import Shape from '../shape/Shape'
import Height from '../height/Height'
import Thickness from '../thickness/Thickness'

export const Volcalc = () => (
  <View style={styles.container}>
    <Text style={styles.text}>SHAPE</Text>
    <Shape />
    <Text style={styles.text}>HEIGHT</Text>
    <Height />
    <Text style={styles.text}>WIDTH</Text>
    <Width />
    <Text style={styles.text}>THICKNESS</Text>
    <Thickness />
  </View>
)

const $mainColor = '#00d1b2'
const styles = {
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: $mainColor
  },
  text: {
    textAlign: 'center',
    color: 'rgba(255, 255, 255, 0.9)',
    fontSize: 15,
    fontFamily: 'Orbitron'
  }
}

In android it doesn't show the new font but has no error. In ios it has error:

Unrecognised font family "Orbitron"

What am I doing wrong?

How do I find out the EXACT value to place in fontFamily: 'xxx'?

Body:
To find the exact value to use as your fontFamily, you can run the project from xcode after adding the following code to your AppDelegate.m file in xcode. You'll see a list of fonts in the output section in xcode.

for (NSString* family in [UIFont familyNames])
{
    NSLog(@"%@", family);

    for (NSString* name in [UIFont fontNamesForFamilyName: family])
    {
        NSLog(@"  %@", name);
    }
}

Helpful link for adding custom fonts: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/


问:
Add new rows to existing column of excel in python

I want to add new records every week to this existing file without creating a new one.

For example, Next I want to add record on date 6/13/2016

Randy->(13,23,13)

Shaw->(13,15,13)

and many such entries next two months. How do I do that? I am beginner so having trouble to put it in syntax.

I could do only this much

```<code>import xlrd

#Opening the excel file
file_location= "C:/Users/agodgh1a/Desktop/Apurva/EPSON.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)
</code>```

Thank you!

答:
```<code>xlrd
</code>```

is for reading operations only. Since you want perform a write operation use
    xlwt
python module.

Refer to xlwt docs for the same

Body:
I want to add new records every week to this existing file without creating a new one.

For example, Next I want to add record on date 6/13/2016

Randy->(13,23,13)

Shaw->(13,15,13)

and many such entries next two months. How do I do that? I am beginner so having trouble to put it in syntax.

I could do only this much

import xlrd

#Opening the excel file
file_location= "C:/Users/agodgh1a/Desktop/Apurva/EPSON.xlsx"
workbook= xlrd.open_workbook(file_location)
sheet=workbook.sheet_by_index(0)

Thank you!

Body:
xlrd

is for reading operations only. Since you want perform a write operation use
    xlwt
python module.

Refer to xlwt docs for the same


问:
Convert Json to XML properly
I have following dictionary structure

```<code>[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]
</code>```

I wanted to use the dicttoxml library to get desired xml-output like:

<root>

        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>
```

<p>However, after applying the next code:</p>

```dicttoxml.dicttoxml(result, attr_type=False, root=True)
```

I got xml-structure like:

<?xml version="1.0" encoding="UTF-8" ?><root><item><item><Universal_Lift_Support><item>1"-9" Extended Length</item><item>10"-14.5" Extended Length</item><item>15"-19" Extended Length</item><item>

What options can help to format and get the output as descibed above?

答:
Consider using built-in Python libraries (json, xml.etree.ElementTree, and to pretty print, xml.dom.minidom) that traverses down json object and builds XML tree. One thing to note: XML nodes cannot contain spaces in names, so it should <UniversalLiftSupport>.

```<code>import json
import xml.etree.ElementTree as ET
import xml.dom.minidom

with open('BodyUniversal.json') as f:
    jsondata = json.load(f)

# INITIALIZING XML DOC AND PARENT TAGS
root = ET.Element('root')
body = ET.SubElement(root, 'Body')
uls = ET.SubElement(body, 'UniversalLiftSupport')
uls.text = ''

# ITERATE THROUGH LIST, APPENDING TO XML
for i in jsondata[0]['Body'][0]['Universal Lift Support']:
    uls.text = uls.text + '\n\t\t\t' + i

# OUTPUT AND PRETTY PRINT TREE
tree_out = ET.tostring(root, encoding="UTF-8")
newXML = xml.dom.minidom.parseString(tree_out.decode('UTF-8'))
pretty_xml = newXML.toprettyxml()

print(pretty_xml)
# <?xml version="1.0" ?>
# <root>
#         <Body>
#                 <UniversalLiftSupport>
#                         1"-9" Extended Length
#                         10"-14.5" Extended Length
#                         15"-19" Extended Length
#                         20" + Extended Length</UniversalLiftSupport>
#         </Body>
# </root>

# OUTPUT XML CONTENT TO FILE
with open('Output.xml','w') as f:
    f.write(pretty_xml)
</code>```

Title: Convert Json to XML properly

Body:
I have following dictionary structure

[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]

I wanted to use the dicttoxml library to get desired xml-output like:

<root>

        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>

However, after applying the next code:

dicttoxml.dicttoxml(result, attr_type=False, root=True)

I got xml-structure like:

<?xml version="1.0" encoding="UTF-8" ?><root><item><item><Universal_Lift_Support><item>1"-9" Extended Length</item><item>10"-14.5" Extended Length</item><item>15"-19" Extended Length</item><item>

What options can help to format and get the output as descibed above?

Body:
Consider using built-in Python libraries (json, xml.etree.ElementTree, and to pretty print, xml.dom.minidom) that traverses down json object and builds XML tree. One thing to note: XML nodes cannot contain spaces in names, so it should <UniversalLiftSupport>.

import json
import xml.etree.ElementTree as ET
import xml.dom.minidom

with open('BodyUniversal.json') as f:
    jsondata = json.load(f)

# INITIALIZING XML DOC AND PARENT TAGS
root = ET.Element('root')
body = ET.SubElement(root, 'Body')
uls = ET.SubElement(body, 'UniversalLiftSupport')
uls.text = ''

# ITERATE THROUGH LIST, APPENDING TO XML
for i in jsondata[0]['Body'][0]['Universal Lift Support']:
    uls.text = uls.text + '\n\t\t\t' + i

# OUTPUT AND PRETTY PRINT TREE
tree_out = ET.tostring(root, encoding="UTF-8")
newXML = xml.dom.minidom.parseString(tree_out.decode('UTF-8'))
pretty_xml = newXML.toprettyxml()

print(pretty_xml)
# <?xml version="1.0" ?>
# <root>
#         <Body>
#                 <UniversalLiftSupport>
#                         1&quot;-9&quot; Extended Length
#                         10&quot;-14.5&quot; Extended Length
#                         15&quot;-19&quot; Extended Length
#                         20&quot; + Extended Length</UniversalLiftSupport>
#         </Body>
# </root>

# OUTPUT XML CONTENT TO FILE
with open('Output.xml','w') as f:
    f.write(pretty_xml)


问:
eBay Trade API - AddFixedPriceListing (21919136 : Required Minimum Number Of Photos) But Photo Is Included
I have been trying to get this call working for hours and im suck. I am using UploadSiteHostedPictures in order to get the image uploaded to EPS. Once the image is uploaded i am calling addFixedPriceListing. The relivant xml looks like this:

```<code>   <PictureDetails>
         <PictureSource>EPS</PictureSource>
        <GalleryType>Gallery</GalleryType>
       <PictureURL>http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/llEAAOSwFqNZWmCo/$_1.JPG?set_id=8800005007</PictureURL>
     </PictureDetails
</code>```

My items were getting listed on the sandbox, but even then no photos were showing up. Any idea on what could be wrong?

答:
Although it wasn't in any of ebays sample code. You need to include <PhotoDisplay>None</PhotoDisplay> and <PhotoDisplay>PicturePack</PhotoDisplay>

```<code><PictureDetails>
     <PhotoDisplay>PicturePack</PhotoDisplay>
     <PictureURL>URL_HERE</PictureURL>
     <PhotoDisplay>None</PhotoDisplay>
</PictureDetails>
</code>```

Hope this helps some one else down the road

Body:
I have been trying to get this call working for hours and im suck. I am using UploadSiteHostedPictures in order to get the image uploaded to EPS. Once the image is uploaded i am calling addFixedPriceListing. The relivant xml looks like this:

   <PictureDetails>
         <PictureSource>EPS</PictureSource>
        <GalleryType>Gallery</GalleryType>
       <PictureURL>http://i.ebayimg.com/00/s/NTAwWDUwMA==/z/llEAAOSwFqNZWmCo/$_1.JPG?set_id=8800005007</PictureURL>
     </PictureDetails

My items were getting listed on the sandbox, but even then no photos were showing up. Any idea on what could be wrong?

Body:
Although it wasn't in any of ebays sample code. You need to include <PhotoDisplay>None</PhotoDisplay> and <PhotoDisplay>PicturePack</PhotoDisplay>

<PictureDetails>
     <PhotoDisplay>PicturePack</PhotoDisplay>
     <PictureURL>URL_HERE</PictureURL>
     <PhotoDisplay>None</PhotoDisplay>
</PictureDetails>

Hope this helps some one else down the road


问:
Using .BY, .GRP or other methods to add a multicolumn aggregation with data.table
Say we have this toy data.table example:

```<code>temp <- data.table(V=c("A", "B", "C", "D","A"), GR=c(1,1,1,2,2))
"V" "GR"
 A   1
 B   1
 C   1
 D   2
 A   2
</code>```

I would like to generate all ordered combinations with combn within each subset defined by GR and create with it a new data.table and with a new column with the grouping factor.

For example, for GR=1 we have (A,B),(A,C),(B,C)

for GR=2 we have (D,A)

If I create the result manually it would be

```<code>cbind(V=c(1,1,1,2),rbind(t(combn(c("A", "B", "C"),2)),t(combn(c( "D","A"),2))))

1  A  B
1  A  C
1  B  C
2  D  A
</code>```

But I would like to do it with data.table easily instead.

This two option don't work:

```<code>temp[,cbind(rep(.GRP,.N),as.data.frame(t(combn(V,2)))),by=GR]
temp[,cbind(rep(.BY,.N),as.data.frame(t(combn(V,2)))),by=GR]
</code>```

This one work, but I don't understand why. I'm afraid it could copy the whole B vector as is instead of the proper value.

```<code>temp[,.(GR,as.list(as.data.frame((combn(V,2))))),by=GR]
</code>```

And I guess it should be a shorter way to write it.

答:
This uses data.table, though not all within [] using .BY or .GRP.</p>

```<code>library(data.table)
temp <- data.table(V=c("A", "B", "C", "D","A"), GR=c(1,1,1,2,2))

tempfunc <- function(x){
  dat <- as.data.table(t(combn(temp[GR == x, V], 2)))
  dat[, GR := x]
  setcolorder(dat, c("GR", "V1", "V2"))
  dat[]
}

rbindlist(lapply(unique(temp$GR), tempfunc))

   GR V1 V2
1:  1  A  B
2:  1  A  C
3:  1  B  C
4:  2  D  A
</code>```

Body:
Say we have this toy data.table example:

temp <- data.table(V=c("A", "B", "C", "D","A"), GR=c(1,1,1,2,2))
"V" "GR"
 A   1
 B   1
 C   1
 D   2
 A   2

I would like to generate all ordered combinations with combn within each subset defined by GR and create with it a new data.table and with a new column with the grouping factor.

For example, for GR=1 we have (A,B),(A,C),(B,C)

for GR=2 we have (D,A)

If I create the result manually it would be

cbind(V=c(1,1,1,2),rbind(t(combn(c("A", "B", "C"),2)),t(combn(c( "D","A"),2))))

1  A  B
1  A  C
1  B  C
2  D  A

But I would like to do it with data.table easily instead.

This two option don't work:

temp[,cbind(rep(.GRP,.N),as.data.frame(t(combn(V,2)))),by=GR]
temp[,cbind(rep(.BY,.N),as.data.frame(t(combn(V,2)))),by=GR]

This one work, but I don't understand why. I'm afraid it could copy the whole B vector as is instead of the proper value.

temp[,.(GR,as.list(as.data.frame((combn(V,2))))),by=GR]

And I guess it should be a shorter way to write it.

Body:
This uses data.table, though not all within [] using .BY or .GRP.

library(data.table)
temp <- data.table(V=c("A", "B", "C", "D","A"), GR=c(1,1,1,2,2))

tempfunc <- function(x){
  dat <- as.data.table(t(combn(temp[GR == x, V], 2)))
  dat[, GR := x]
  setcolorder(dat, c("GR", "V1", "V2"))
  dat[]
}

rbindlist(lapply(unique(temp$GR), tempfunc))

   GR V1 V2
1:  1  A  B
2:  1  A  C
3:  1  B  C
4:  2  D  A


问:
Android Device Monitor
When trying to access android device monitor on android studio, and I keep getting the error message

Even though I added the new JDK to my project I still keep getting this.

答: Right click on android studio icon and choose run as administrator. This will probably solve the issue.</p>

Title: Android Device Monitor


问:
Using Google Cloud Source Repositories with service account
Is it possible to access a Google Cloud Source Repository in an automated way, i.e. from a GCE instance using a service account?

The only authentication method I am seeing in the docs is to use the gcloud auth login command, which will authenticate my personal user to access the repo, not the machine I am running commands from.

答:
Enable access to the "Cloud Source Repositories" Cloud API for the instance. You should do this while creating or editing the instance in the Admin console

From a shell inside the instance, execute gcloud source repos clone <repo_name_in_cloud_source> <target_path_to_clone_into>


问:
Heroku: Uploading a static site on Heroku?
I'm building my portfolio and made simple etch-a-sketch project with HTML/CSS and Javascript. I'm trying to host the site on Heroku but i'm getting this error:

```<code>remote:  !     No default language could be detected for this app.
remote:             HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:             See https://devcenter.heroku.com/articles/buildpacks
</code>```

This is basically a static site, I don't really need a buildpack, is there any way I can still push what I have to Heroku?

答:
Heroku is normally used for deploying apps, not static sites. I find using GitHub pages to be much easier for static site hosting. If your project is already on GitHub just go to the settings tab of your repo, scroll to the GitHub pages section, and select which branch of your repo you want to deploy. **edit - Just make sure your home html file is titled index.html

But if you do need to use Heroku for whatever reason, here is a guide on how to do so. It shows how to create the composer.json and index.php needed for a static site.

ContentLicense: CC BY-SA 4.0

Body:
I'm building my portfolio and made simple etch-a-sketch project with HTML/CSS and Javascript. I'm trying to host the site on Heroku but i'm getting this error:

remote:  !     No default language could be detected for this app.
remote:             HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:             See https://devcenter.heroku.com/articles/buildpacks

This is basically a static site, I don't really need a buildpack, is there any way I can still push what I have to Heroku?


问:
Is there a Rack or Sinatra based environment configuration utility?
Is there anything in the Sinatra / Rack world similar to Rails configuration loading scheme that loads one of the config\enviroments\*.rb files depending on Rails.env

I know I could develop one pretty easily, i was just wondering if there was something already in place.

答:
It turns out that there is something from Sinatra, that provides a similar, though limited, functionality.

See the code:
https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1120

So that you can do this:

```<code>class MyApp < Sinatra::Base
  configure :development, :test do
    #only executes this code when environment is equal to one of the passed arguments
    # I'm pretty sure Sinatra sets this based on ENV['RACK_ENV']
  end
end
</code>```

Body:
It turns out that there is something from Sinatra, that provides a similar, though limited, functionality.

See the code:
https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1120

So that you can do this:

class MyApp < Sinatra::Base
  configure :development, :test do
    #only executes this code when environment is equal to one of the passed arguments
    # I'm pretty sure Sinatra sets this based on ENV['RACK_ENV']
  end
end