问:
Connection issues implementing Django Custom Storage backend with Box Cloud Storage API
I am working on a legacy Django application that has a lot of third party dependencies, one of which is the storage backend for file uploads.  I was recently tasked with replacing our legacy third party cloud storage vendor with a newer cloud storage vendor (Box).

The cloud storage is implemented as a custom storage backend and used as the "storage" parameter in FileFields in models throughout the app.  I'm basically trying to figure out what exactly happens in storage if you have a FileField in a model and you create a ModelForm based on that model, then you call "save" on the form.

It seems that a lot of stuff is going on and some of it is causing connection problems with the cloud storage API.

I tried reading the Django source to follow it and got all the way down to where the model is deciding if it should do an update (by doing an "exists" check in storage) or an insert.

Once it decides to do an insert, I noticed a call to my cloud storage backend occurs to upload the file (presumably non blocking?) as the insert sql is being generated.

Somewhere in here, connections to the cloud storage begin to hang and become unresponsive. At least, all I see in logs is

INFO requests.packages.urllib3.connectionpool - Starting new HTTPS connection (1): upload.box.com"

and no further info or response.

Unlike the previous cloud storage, the new one issues JWT's per session instead of having a static auth token that you simply pass every time. If I do not use Django's ModelForm with its magical "save" method, but call methods directly on the models with the FileFields, I do not encounter the connection problem - I get responses just fine from the cloud storage API.

So, I'm thinking there must be some kind of concurrency issue when calling "save" on a form that affects a model with a FileField??  I'm a little stumped.  The code is involved, so it is hard to copy here, but basically it comes down to:

```<code>class CustomStorage:
    def __init__(self):
        set up storage API client,
        authenticate client instance, etc

    def _save(self, name):
        call storage API methods to upload file
        ** includes a retry loop with file renaming
           algorithm to avoid name conflicts, as
           cloud API does not allow duplicate file
           names

    def exists(self, name):
        call storage API methods to determine if file name conflict exists

    def _open(self, name):
        call storage API methods to download file

custom_storage = CustomStorage()

class ExampleModel(models.Model):
    name = models.CharField(maxlength=255)
    file_ref = FPFileField(upload_to="uploads", storage=custom_storage) #because we also have a dependency on FilePicker, now called FileStack

class ExampleModelForm(ModelForm):
    file_ref = CustomFilePickerField()
    class Meta:
        model = ExampleModel
        fields = ('name', 'file_obj')

form = ExampleModelForm()
model = form.save() # --> connection problem with
                    # cloud storage API starts here
                    # if I were to call ExampleModel.objects.create(...),
                    # the storage upload process would work fine
</code>```

Is there some gotcha I'm not aware of that Django experts would know about implementing custom storage backends for Django based on cloud storage APIs?

答: Turns out that the problem was our usage of a deprecated version of a FilePicker field for the uploaded document model field, combined with an old bug in a stale version of Requests.  Occasionally, this field would return a Django file instance wrapped around a cStringIO.StringIO object instead of a vanilla file object.  This ended up running into a bug in the Requests library which caused stalled responses when chunking for a multi-part POST when the payload is a StringIO instance.  Because upgrading is not an option, I solved the issue by detecting if the the underlying Django FileField File is not a file object and re-wrapping it in a ContentFile instance and seek-ing to 0, in order to play nice with the older version of Requests.  If anyone knows of a better alternative, by all means, please let me know.</p>

Body:
I am working on a legacy Django application that has a lot of third party dependencies, one of which is the storage backend for file uploads.  I was recently tasked with replacing our legacy third party cloud storage vendor with a newer cloud storage vendor (Box).

The cloud storage is implemented as a custom storage backend and used as the "storage" parameter in FileFields in models throughout the app.  I'm basically trying to figure out what exactly happens in storage if you have a FileField in a model and you create a ModelForm based on that model, then you call "save" on the form.

It seems that a lot of stuff is going on and some of it is causing connection problems with the cloud storage API.

I tried reading the Django source to follow it and got all the way down to where the model is deciding if it should do an update (by doing an "exists" check in storage) or an insert.

Once it decides to do an insert, I noticed a call to my cloud storage backend occurs to upload the file (presumably non blocking?) as the insert sql is being generated.

Somewhere in here, connections to the cloud storage begin to hang and become unresponsive. At least, all I see in logs is

INFO requests.packages.urllib3.connectionpool - Starting new HTTPS connection (1): upload.box.com"

and no further info or response.

Unlike the previous cloud storage, the new one issues JWT's per session instead of having a static auth token that you simply pass every time. If I do not use Django's ModelForm with its magical "save" method, but call methods directly on the models with the FileFields, I do not encounter the connection problem - I get responses just fine from the cloud storage API.

So, I'm thinking there must be some kind of concurrency issue when calling "save" on a form that affects a model with a FileField??  I'm a little stumped.  The code is involved, so it is hard to copy here, but basically it comes down to:

class CustomStorage:
    def __init__(self):
        set up storage API client,
        authenticate client instance, etc

    def _save(self, name):
        call storage API methods to upload file
        ** includes a retry loop with file renaming
           algorithm to avoid name conflicts, as
           cloud API does not allow duplicate file
           names

    def exists(self, name):
        call storage API methods to determine if file name conflict exists

    def _open(self, name):
        call storage API methods to download file

custom_storage = CustomStorage()

class ExampleModel(models.Model):
    name = models.CharField(maxlength=255)
    file_ref = FPFileField(upload_to="uploads", storage=custom_storage) #because we also have a dependency on FilePicker, now called FileStack

class ExampleModelForm(ModelForm):
    file_ref = CustomFilePickerField()
    class Meta:
        model = ExampleModel
        fields = ('name', 'file_obj')

form = ExampleModelForm()
model = form.save() # --> connection problem with
                    # cloud storage API starts here
                    # if I were to call ExampleModel.objects.create(...),
                    # the storage upload process would work fine

Is there some gotcha I'm not aware of that Django experts would know about implementing custom storage backends for Django based on cloud storage APIs?


来源: stackexchange

问:
Force focus on input-field on click with angularjs
I have a text-box to show a input field on click and  hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

```<code><div data-ng-init="editMode = false">
    <p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
    <span data-ng-show="editMode">
       <input data-ng-blur="editMode = false" data-ng-model="color">
    </span>
  </div>
</code>```

Thanks in advance for your help!

答:
You can apply "autofocus" for the input.

```<code><div data-ng-init="editMode = false; color='Green'">
<p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
<span data-ng-show="editMode">
   <input data-ng-blur="editMode = false" data-ng-model="color" autofocus>
</span>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a text-box to show a input field on click and  hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

{{color}}

       <input data-ng-blur="editMode = false" data-ng-model="color">

Thanks in advance for your help!

Body:
You can apply "autofocus" for the input.

<div data-ng-init="editMode = false; color='Green'">
<p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
<span data-ng-show="editMode">
   <input data-ng-blur="editMode = false" data-ng-model="color" autofocus>
</span>


问:
Everything now is XML - but programming is still done with some legacy files obeying complicated syntax
Why is this ? Gcc is now providing a "C-to-XML" conversion since XML is more easily parsed.

Couldn't we benefit if our source code was XML?

Of course, nobody want's to edit XML files manually - but that's what IDEs are made for.

Would some programming language with less syntax (LISP, Smalltalk) better map to XML?

答:
Couldn't we benefit if our source code was XML?

Let me take this question in its broader sense: suppose that our favorite programming language had a standard machine-readable form that admitted only well-formed trees.  Couldn't we benefit?

It was done with Ada in the 1980s, with a standard form for abstract-syntax trees (I believe it was called DIANA).  There was a modest benefit for those writing tools to analyze Ada.

Other experience gotten during the 1980s, with the Cornell Program Synthesizer and related tools, showed that for a developer, you must have the ability to edit a "thing" that is not a syntactically correct program.  Remember, we are typists first, programmers second, and what we learned from the Cornell Synthesizer experience was that using any IDE that forces you always to maintain a syntactically correct program (think: a well-formed XML tree) is like dragging around a ball and chain.

Good programmers are really, really good at typing text fast.  Any representation or IDE which takes away that advantage had better offer some compelling compensating advantages.  For XML, I don't see what those compensating advantages might look like.

The one thing you gain with XML is that it's easier to write a parser.  (You still have to write one, but it's easier.)  But with the computing power we have gained since the 1980s, and with the plethora of new parsing techniques that can exploit that power, parsing (converting linear text to tree form) is just not that big a deal any more.  All of the work in creating great tools is in analysis (type checking, pointer analysis, information flow, optimization, you name it) of the resulting trees.  XML doesn't buy anything there.

I made my reputation working on compilers and related tools, and while I see some very modest benefits to having a standard representation of abstract-syntax trees, and would be willing to accept XML as such a representation, I can't see that the benefits would be worth the cost of agreeing on a standard.

ContentLicense: CC BY-SA 2.5


问:
Create responsive top menu in angular or anything else (like Chrome uses with bookmarks bar when you resize the page)
Can you direct me or give me some advice please on how to create a navigation bar (Angular 1, jQuery, css, etc) that behaves like Google Chrome bookmarks bar when the page is resized. Basically as the page size gets smaller a new button/symbol (>>) appears on the bar. Buttons from the right that cannot fit due to the smaller resolution move under the >> symbol. If you press the symbol a drop down appears with the hidden buttons. When the page reaches mobile resolution of course I will switch to mobile menu, but I need this step between the full menu and the mobile.

Google Chrome browser manages bookmarks bar view when you resize the page in a great way. If in Chrome you have a lot of bookmarks two arrows (>>) appear on the right side and when you make the window smaller more bookmarks hide under these arrows.

Thanks a lot for your help.

答:
Making menu div overflow:auto would be simplest solution. Here's plunk for that
http://plnkr.co/edit/vAYTGgNnQtH1iE2vsIpS?p=preview

For your particular requirement, here is horizontal slider with arrows in the end to handle scroll
https://codepen.io/mahish/pen/RajmQw


问:
How to get a single key from user without pressing enter in python
I'm a total beginner so please excuse my ignorance.

What i want to do is basically get an input from the user, which is either a number from 1 to 9 or a space. I've come up with some code from looking around this website that I believe should work but doesn't. When I try to run it, it just does nothing, no error message or anything.

```<code>import msvcrt
numInput = 0
while numInput == 0 :
    if msvcrt.kbhit():
        if msvcrt.getch() == "1":
            numInput = "1"
        elif (msvcrt.getch() == "2"):
            numInput = "2"
        elif (msvcrt.getch() == "3"):
            numInput = "3"
        elif (msvcrt.getch() == "4"):
            numInput = "4"
        elif (msvcrt.getch() == "5"):
            numInput = "5"
        elif (msvcrt.getch() == "6"):
            numInput = "6"
        elif (msvcrt.getch() == "7"):
            numInput = "7"
        elif (msvcrt.getch() == "8"):
            numInput = "8"
        elif (msvcrt.getch() == "9"):
            numInput = "9"
        elif (msvcrt.getch() == " "):
            numInput = " "
</code>```

答:
msvcrt.getch() READS key. Also there's nothing you do with numInput value.

You've got:

```<code>if msvcrt.getch() == "1":
    numInput = "1"
elif (msvcrt.getch() == "2"):
    numInput = "2"
....
</code>```

First msvcrt.getch() reads the key you've detected with msvcrt.kbhit(). If its '1' then it'll exit the loop. If not, it'll go to second if and BLOCKS until you press key again. After you press the key python will check it against '2'. And so on. Thus if you press 1, your code will exit loop just fine. If you want to exit with 2, then you've to press 2 twice (because first you check for 1)... you get the drill. Try this one:

```<code>while numInput == 0 :
    if msvcrt.kbhit():
        v = msvcrt.getch()
        if v == "1":
            numInput = "1"
        ...
print(numInput)
</code>```

Note: this loop will also monopolize one core of your procesor, but that's another story.

Body:
I'm a total beginner so please excuse my ignorance.

What i want to do is basically get an input from the user, which is either a number from 1 to 9 or a space. I've come up with some code from looking around this website that I believe should work but doesn't. When I try to run it, it just does nothing, no error message or anything.

import msvcrt
numInput = 0
while numInput == 0 :
    if msvcrt.kbhit():
        if msvcrt.getch() == "1":
            numInput = "1"
        elif (msvcrt.getch() == "2"):
            numInput = "2"
        elif (msvcrt.getch() == "3"):
            numInput = "3"
        elif (msvcrt.getch() == "4"):
            numInput = "4"
        elif (msvcrt.getch() == "5"):
            numInput = "5"
        elif (msvcrt.getch() == "6"):
            numInput = "6"
        elif (msvcrt.getch() == "7"):
            numInput = "7"
        elif (msvcrt.getch() == "8"):
            numInput = "8"
        elif (msvcrt.getch() == "9"):
            numInput = "9"
        elif (msvcrt.getch() == " "):
            numInput = " "

Body:
msvcrt.getch() READS key. Also there's nothing you do with numInput value.

You've got:

if msvcrt.getch() == "1":
    numInput = "1"
elif (msvcrt.getch() == "2"):
    numInput = "2"
....

First msvcrt.getch() reads the key you've detected with msvcrt.kbhit(). If its '1' then it'll exit the loop. If not, it'll go to second if and BLOCKS until you press key again. After you press the key python will check it against '2'. And so on. Thus if you press 1, your code will exit loop just fine. If you want to exit with 2, then you've to press 2 twice (because first you check for 1)... you get the drill. Try this one:

while numInput == 0 :
    if msvcrt.kbhit():
        v = msvcrt.getch()
        if v == "1":
            numInput = "1"
        ...
print(numInput)

Note: this loop will also monopolize one core of your procesor, but that's another story.


问:
What can be the algorithm to find the max number that appear the most in an array?
I'm trying to find out an algorithm that returns the number that has more occurrences in an array that contains number from 0 to 9 and that has a complexity of n.
I though to using an HashMap but it would require n^2
If anyone can write the code down,i'd prefer in Java but pseudocode is the same

答:
Use ten counters (one per digit), scan the array and increment the counters corresponding to the digits. (You are actually computing the histogram of the digit frequencies.)

Report the digit with the largest counter.


问:
Is it safe to use integers as hash keys?
Is it safe to use integers as hash keys?</p>

```<code>my %hash;
my $str = ...

for $str.NFC {
    %hash{$_} = ...
}
</code>```

答:
A normal Hash coerces all its keys to strings:

my %a = '1' => 'foo', 2 => 'bar';

say %a.pairs.perl;  # ("1" => "foo", "2" => "bar").Seq
```

<p>Note how the second key became the string <code>"2"</code>, even though it was originally passed to the Hash as an integer.<br>
When you do hash look-ups, the subscript is also automatically converted to a string before it is used:</p>

<pre class="lang--perl6 prettyprint-override"><code>say %a{"2"}.perl;   # "bar"
say %a{2}.perl;     # "bar"
</code>```

Note how the subscript 2 correctly found the element with key "2".

The conversion from integers to strings is well-defined in Perl 6, yielding a unique string for each unique integer, so the example you gave is fine.

If you don't want your Hash keys to be converted to strings, you can override the key handling using the {} notation in the declaration:

my %b{Any} = '1' => 'foo', 2 => 'bar';

say %b.pairs.perl;  # ("1" => "foo", 2 => "bar").Seq

say %b{"1"}.perl;   # "foo"
say %b{1}.perl;     # Any

say %b{"2"}.perl;   # Any
say %b{2}.perl;     # "bar"
```

Note how in this case the second key 2 stays an integer, and doing a look-up with the string subscript "2" does not find it, nor does the subscript 1 find the entry with key "1".

%b{Any} means "accept keys of any type, and don't coerce them". This is sometimes called an 'object Hash' because it can map from any object to a value.

%b{Int} would mean "accept only Int keys, and don't coerce them". In this case you'll get an error if you even try to use anything that isn't already an Int.

Body:
Is it safe to use integers as hash keys?

my %hash;
my $str = ...

for $str.NFC {
    %hash{$_} = ...
}

Body:
A normal Hash coerces all its keys to strings:

my %a = '1' => 'foo', 2 => 'bar';

say %a.pairs.perl;  # ("1" => "foo", "2" => "bar").Seq

Note how the second key became the string "2", even though it was originally passed to the Hash as an integer.

When you do hash look-ups, the subscript is also automatically converted to a string before it is used:

say %a{"2"}.perl;   # "bar"
say %a{2}.perl;     # "bar"

Note how the subscript 2 correctly found the element with key "2".

The conversion from integers to strings is well-defined in Perl 6, yielding a unique string for each unique integer, so the example you gave is fine.

If you don't want your Hash keys to be converted to strings, you can override the key handling using the {} notation in the declaration:

my %b{Any} = '1' => 'foo', 2 => 'bar';

say %b.pairs.perl;  # ("1" => "foo", 2 => "bar").Seq

say %b{"1"}.perl;   # "foo"
say %b{1}.perl;     # Any

say %b{"2"}.perl;   # Any
say %b{2}.perl;     # "bar"

Note how in this case the second key 2 stays an integer, and doing a look-up with the string subscript "2" does not find it, nor does the subscript 1 find the entry with key "1".

%b{Any} means "accept keys of any type, and don't coerce them". This is sometimes called an 'object Hash' because it can map from any object to a value.

%b{Int} would mean "accept only Int keys, and don't coerce them". In this case you'll get an error if you even try to use anything that isn't already an Int.


问:
Reuse CSS style and apply to other HTML element
I would like to reuse given css formatting .parsley-errors-list > li and apply it to different HTML element than it it designed to be used for. I would like to apply it to  in order not to create another duplicated style and to be sure that span will always be of the same style as .parsley-errors-list > li.

```<code>.parsley-errors-list {
    display: none;
    margin: 0;
    padding: 0;
}

.parsley-errors-list > li {
    font-size: 12px;
    list-style: none;
    color: #f05050;
}
</code>```

EDIT:

Given CSS sample is part of an updatable theme, so I would like to avoid changing it for the maintainability.

答:
That's very easy to do. Just put a comma on the CSS selector like this:</p>

```<code>.parsley-errors-list > li, span {
    font-size: 12px;
    list-style: none;
    color: #f05050;
}
</code>```

Body:
I would like to reuse given css formatting .parsley-errors-list > li and apply it to different HTML element than it it designed to be used for. I would like to apply it to  in order not to create another duplicated style and to be sure that span will always be of the same style as .parsley-errors-list > li.

.parsley-errors-list {
    display: none;
    margin: 0;
    padding: 0;
}

.parsley-errors-list > li {
    font-size: 12px;
    list-style: none;
    color: #f05050;
}

EDIT:

Given CSS sample is part of an updatable theme, so I would like to avoid changing it for the maintainability.

Body:
That's very easy to do. Just put a comma on the CSS selector like this:

.parsley-errors-list > li, span {
    font-size: 12px;
    list-style: none;
    color: #f05050;
}


问:
How to Add Linux Compilation to Cmake Project in Visual Studio
Visual Studio has added lots of new features for C++ in the past year.

CMake
With the CMake support, I can do "Open Folder" and select a folder with a CMakeLists.txt file in it. Visual Studio does a lot of nice work in discovering and building it automatically.

Linux Compilation
Visual studio now supports remote compilation on Linux over SSH. Several tutorials show how users can create a new "Linux Console Application" in Visual Studio, and it will automatically ask to setup an SSH connection to be used for building it. I don't see any instructions for how to do this on an existing project of any kind.

Particularly with a CMake project, is it possible to open a CMake folder in Visual Studio 2017 and have it built over on a remote Linux machine?  IfSoHow?

答:
There is no build-in support for a VS "Linux Console Application" in CMake yet (as for CMake version 3.9).

Edit: Visual Studio 2017 15.4 now comes with something similar without generating actual .vcxproj files. See Visual C++ for Linux Development with CMake

With a standard CMake version besides the possibilities described here using existing .vcxproj files as a template, you can only trick CMake into generating those project types:

cmake_minimum_required(VERSION 3.7)

project(HelloLinux)

file(WRITE main.cpp [=[
#include <iostream>

int main()
{
    std::cout << "Hello from Linux Console!" << std::endl;
}
]=])

add_executable(HelloLinux "main.cpp")

set_target_properties(
    HelloLinux
    PROPERTIES
        VS_GLOBAL_KEYWORD "Linux"
        VS_GLOBAL_ApplicationType "Linux"
        VS_GLOBAL_ApplicationTypeRevision "1.0"
        VS_GLOBAL_TargetLinuxPlatform "Generic"
        VS_GLOBAL_LinuxProjectType "{D51BCBC9-82E9-4017-911E-C93873C4EA2B}"
)
```

This actually works and produces a Linux .vcxproj project that is accepted by VS. But since we sidestepped CMake here, none of the other compiler/linker options you define in your CMake script will be assigned.

So my recommendation is to raise a feature request for CMake itself to directly support this (e.g. via platform toolset option Remote_GCC_1_0).

Body:
There is no build-in support for a VS "Linux Console Application" in CMake yet (as for CMake version 3.9).

Edit: Visual Studio 2017 15.4 now comes with something similar without generating actual .vcxproj files. See Visual C++ for Linux Development with CMake

With a standard CMake version besides the possibilities described here using existing .vcxproj files as a template, you can only trick CMake into generating those project types:

cmake_minimum_required(VERSION 3.7)

project(HelloLinux)

file(WRITE main.cpp [=[
#include <iostream>

int main()
{
    std::cout << "Hello from Linux Console!" << std::endl;
}
]=])

add_executable(HelloLinux "main.cpp")

set_target_properties(
    HelloLinux
    PROPERTIES
        VS_GLOBAL_KEYWORD "Linux"
        VS_GLOBAL_ApplicationType "Linux"
        VS_GLOBAL_ApplicationTypeRevision "1.0"
        VS_GLOBAL_TargetLinuxPlatform "Generic"
        VS_GLOBAL_LinuxProjectType "{D51BCBC9-82E9-4017-911E-C93873C4EA2B}"
)

This actually works and produces a Linux .vcxproj project that is accepted by VS. But since we sidestepped CMake here, none of the other compiler/linker options you define in your CMake script will be assigned.

So my recommendation is to raise a feature request for CMake itself to directly support this (e.g. via platform toolset option Remote_GCC_1_0).


问:
How can I save setting of my menu_toggle using cookie?
I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

```<code>  <div class="nav toggle">
  <a id="menu_toggle"><i class="fa fa-bars"></i></a>
  </div>
</code>```

My Code

```<code> var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });
</code>```

答:
I used localStorage to solve my problem. It's really simple and easy way to store setting locally. I add these two lines.

Here is my code:

```<code> localStorage.setItem('Menu', 'Mini');

 localStorage.setItem('Menu', 'Larg');
</code>```

Then I added script in my page like this:

```<code><script>
if (localStorage.Menu === 'Mini') {
    $("body").addClass('nav-sm');

} else {
    $("body").addClass('nav-md');
}
</script>
</code>```

Body:
I want to toggle my menu and save its settings in the cookie. Here is my Jquery code for toggle button:

My HTML

My Code

 var $MENU_TOGGLE = $('#menu_toggle')
 $MENU_TOGGLE.on('click', function() {
    console.log('clicked - menu toggle');

    if ($BODY.hasClass('nav-md')) {
        $SIDEBAR_MENU.find('li.active ul').hide();
        $SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass('active');
    } else {
        $SIDEBAR_MENU.find('li.active-sm ul').show();
        $SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass('active-sm');
    }

$BODY.toggleClass('nav-md nav-sm');

setContentHeight();
 });

Body:
I used localStorage to solve my problem. It's really simple and easy way to store setting locally. I add these two lines.

Here is my code:

 localStorage.setItem('Menu', 'Mini');

 localStorage.setItem('Menu', 'Larg');

Then I added script in my page like this:

<script>
if (localStorage.Menu === 'Mini') {
    $("body").addClass('nav-sm');

} else {
    $("body").addClass('nav-md');
}
</script>


问:
Filetype Naming Convention for Angular Classes
Angular's Style Guide lists naming conventions for common file types, such as heroes.component.ts, or heroes.service.ts, etc. But what about classes that have no decorator symbols? For example, the Heroes tutorial creates a Hero class:

```<code>export class Hero {
  id: number;
  name: string;
}
</code>```

It then names this file hero.ts. A naming convention like this seems prone to chaos in the app directory. It seems logical to create a folder named classes (in the app directory), and then add a class.ts suffix to each file, such as hero.class.ts.

However, I have not seen anyone using this convention. I've seen people use a model.ts suffix, but it's unclear whether or not this is a best practice, and it is not mentioned in the Angular Style Guide.

Can anyone shed some light on this topic? Sorry if I've missed anything. Thank you advance.

答:
Angular Style Guide explicitly says to use .model for simple models. However, you should consider 2 things:

there is no convention for enums. Personally I keep them inside of service or model file, depending on how it supposed to be used

guide allows to create other entities, so in scope of your project - you can add other "types" (recource, config)

if class/model/interface (e.g. User) is used across application, guide suggests to keep it in shared module, which is logically right: SharedModule is supposed to be imported multiple times, while CoreModule - only once (in AppModule)

Body:
Angular's Style Guide lists naming conventions for common file types, such as heroes.component.ts, or heroes.service.ts, etc. But what about classes that have no decorator symbols? For example, the Heroes tutorial creates a Hero class:

export class Hero {
  id: number;
  name: string;
}

It then names this file hero.ts. A naming convention like this seems prone to chaos in the app directory. It seems logical to create a folder named classes (in the app directory), and then add a class.ts suffix to each file, such as hero.class.ts.

However, I have not seen anyone using this convention. I've seen people use a model.ts suffix, but it's unclear whether or not this is a best practice, and it is not mentioned in the Angular Style Guide.

Can anyone shed some light on this topic? Sorry if I've missed anything. Thank you advance.


问:
how to transform json into beans when msg received from the queue
Java 8 Apache camel

I have camel route which listens to the active MQ. my queue contains the JSON payload. i have crated the mapper bean wondering how can i convert json response into list of mapper objects.

```<code>from ("activemq:queue:my.queue")
.log("msg received").log("body" + ${body}");

class myMapper{
String name;
String addr;
}
</code>```

答: You'll want to review the Camel JSON page and associated example. Converting from JSON text -> Java object is referred to as 'unmarshalling' in Camel, and Java Object -> JSON text is 'marshalling'.</p>

Body:
Java 8 Apache camel

I have camel route which listens to the active MQ. my queue contains the JSON payload. i have crated the mapper bean wondering how can i convert json response into list of mapper objects.

from ("activemq:queue:my.queue")
.log("msg received").log("body" + ${body}");

class myMapper{
String name;
String addr;
}


问:
Extract the first paragraph from a Wikipedia article (Python)
How can I extract the first paragraph from a Wikipedia article, using Python?

For example, for Albert Einstein, that would be:

Albert Einstein (pronounced /ˈælbərt
  ˈaɪnstaɪn/; German: [ˈalbɐt ˈaɪnʃtaɪn]
  ( listen); 14 March 1879 – 18 April
  1955) was a theoretical physicist,
  philosopher and author who is widely
  regarded as one of the most
  influential and iconic scientists and
  intellectuals of all time. A
  German-Swiss Nobel laureate, Einstein
  is often regarded as the father of
  modern physics.[2] He received the
  1921 Nobel Prize in Physics "for his
  services to theoretical physics, and
  especially for his discovery of the
  law of the photoelectric effect".[3]

答:
As others have said, one approach is to use the wikimedia API and urllib or urllib2.  The code fragments below are part of what I used to extract what is called the "lead" section, which has the article abstract and the infobox.  This will check if the returned text is a redirect instead of actual content, and also let you skip the infobox if present (in my case I used different code to pull out and format the infobox. </p>

```<code>contentBaseURL='http://en.wikipedia.org/w/index.php?title='

def getContent(title):
    URL=contentBaseURL+title+'&action=raw&section=0'
    f=urllib.urlopen(URL)
    rawContent=f.read()
    return rawContent

infoboxPresent = 0
# Check if a redirect was returned.  If so, go to the redirection target
    if rawContent.find('#REDIRECT') == 0:
        rawContent = getFullContent(title)
        # extract the redirection title
        # Extract and format the Infobox
        redirectStart=rawContent.find('#REDIRECT[[')+11
        count = 0
        redirectEnd = 0
        for i, char in enumerate(rawContent[redirectStart:-1]):
            if char == "[": count += 1
            if char == "]}":
                count -= 1
                if count == 0:
                    redirectEnd = i+redirectStart+1
                    break
        redirectTitle = rawContent[redirectStart:redirectEnd]
        print 'redirectTitle is: ',redirectTitle
        rawContent = getContent(redirectTitle)

    # Skip the Infobox
    infoboxStart=rawContent.find("{{Infobox")   #Actually starts at the double {'s before "Infobox"
    count = 0
    infoboxEnd = 0
    for i, char in enumerate(rawContent[infoboxStart:-1]):
        if char == "{": count += 1
        if char == "}":
            count -= 1
            if count == 0:
                infoboxEnd = i+infoboxStart+1
                break

    if infoboxEnd <> 0:
        rawContent = rawContent[infoboxEnd:]
</code>```

<p>You'll be getting back the raw text including wiki markup, so you'll need to do some clean up.  If you just want the first paragraph, not the whole first section, look for the first new line character.       </p>

Body:
As others have said, one approach is to use the wikimedia API and urllib or urllib2.  The code fragments below are part of what I used to extract what is called the "lead" section, which has the article abstract and the infobox.  This will check if the returned text is a redirect instead of actual content, and also let you skip the infobox if present (in my case I used different code to pull out and format the infobox.

contentBaseURL='http://en.wikipedia.org/w/index.php?title='

def getContent(title):
    URL=contentBaseURL+title+'&action=raw&section=0'
    f=urllib.urlopen(URL)
    rawContent=f.read()
    return rawContent

infoboxPresent = 0
# Check if a redirect was returned.  If so, go to the redirection target
    if rawContent.find('#REDIRECT') == 0:
        rawContent = getFullContent(title)
        # extract the redirection title
        # Extract and format the Infobox
        redirectStart=rawContent.find('#REDIRECT[[')+11
        count = 0
        redirectEnd = 0
        for i, char in enumerate(rawContent[redirectStart:-1]):
            if char == "[": count += 1
            if char == "]}":
                count -= 1
                if count == 0:
                    redirectEnd = i+redirectStart+1
                    break
        redirectTitle = rawContent[redirectStart:redirectEnd]
        print 'redirectTitle is: ',redirectTitle
        rawContent = getContent(redirectTitle)

    # Skip the Infobox
    infoboxStart=rawContent.find("{{Infobox")   #Actually starts at the double {'s before "Infobox"
    count = 0
    infoboxEnd = 0
    for i, char in enumerate(rawContent[infoboxStart:-1]):
        if char == "{": count += 1
        if char == "}":
            count -= 1
            if count == 0:
                infoboxEnd = i+infoboxStart+1
                break

    if infoboxEnd <> 0:
        rawContent = rawContent[infoboxEnd:]

You'll be getting back the raw text including wiki markup, so you'll need to do some clean up.  If you just want the first paragraph, not the whole first section, look for the first new line character.


问:
Why are my android manifest not merging?
So I've an Android lib that I made, that library has an activity a service and some permissions declared in the lib manifest.
I also have a demo app which uses the lib jar. So what I want to do is to use that lib on that demo app or any other app without having to declare the activity, the service and if possible the permissions each time I use the lib.
If I don't declare the activity, the service and the permissions in the demo app my demo app crashes on runtime. As far as I know; Android merges the manifests but I don't thinks that its doing it.
Here is my lib manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mylib">

    <!-- This app records A/V content from camera and stores it to disk -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application>
        <activity android:theme="@style/Transparent"
            android:name="org.mylib.activities.CheckStoragePermissionsActivity"/>

        <service android:theme="@style/Transparent" android:name="org.mylib.services.BackgroundVideoRecorder"/>
    </application>

</manifest>
</code>```

and here is my demo app manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mx.mydemo">

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".activity.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activity.RegisterUserActivity" />
        <activity android:name=".activity.LogGameDataActivity" />
        <activity android:name=".activity.GameResultsActivity" />
        <activity android:name=".activity.PasswordResetActivity" />

    </application>

</manifest>
</code>```

Is there something wrong in any of my manifest that is not allowing them to be merged? Does the lib manifest package and the demo app manifest package needs to be the same package?

Greetings

答:
By the way the lib and the demo app are 2 different and separate projects I'am pasting the lib jar in the demo lib folder and then I'm telling android studio to import the jar as a library.

That is not going to work. The JAR is just Java code; it does not contain the manifest, resources, or assets from the library module.

Either:

Move these into one project as separate modules, then use compile project() syntax in the demo project to pull in the library module, or

Publish the library module as an AAR to an artifact repository (a local one on your development machine, Maven Central, JCenter, whatever), and have the demo app pull it in from there, or

Copy the AAR, not the JAR, from the library project into the demo project

I strongly recommend either of the first two options.

Body:
So I've an Android lib that I made, that library has an activity a service and some permissions declared in the lib manifest.
I also have a demo app which uses the lib jar. So what I want to do is to use that lib on that demo app or any other app without having to declare the activity, the service and if possible the permissions each time I use the lib.
If I don't declare the activity, the service and the permissions in the demo app my demo app crashes on runtime. As far as I know; Android merges the manifests but I don't thinks that its doing it.
Here is my lib manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mylib">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />

    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application>
        <activity android:theme="@style/Transparent"
            android:name="org.mylib.activities.CheckStoragePermissionsActivity"/>

        <service android:theme="@style/Transparent" android:name="org.mylib.services.BackgroundVideoRecorder"/>
    </application>

</manifest>

and here is my demo app manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mx.mydemo">

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".activity.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".activity.RegisterUserActivity" />
        <activity android:name=".activity.LogGameDataActivity" />
        <activity android:name=".activity.GameResultsActivity" />
        <activity android:name=".activity.PasswordResetActivity" />

    </application>

</manifest>

Is there something wrong in any of my manifest that is not allowing them to be merged? Does the lib manifest package and the demo app manifest package needs to be the same package?

Greetings


问:
React Native - Invalid prop source passed to Image
I am completely new to react native dev, and I am trying to display and <Image>.  I keep getting this error:

Warning: Failed prop type: Invalid prop source supplied to Image`

Here is what I have:
First, there is list of all images in project defined like this:

```<code>export const IMAGES = {
   ScreenStart1: require('../../assets/img/app/startScreen/start1.jpg'),
}
</code>```

This is the view which calls the image component:

```<code>import {IMAGES} from '../../shared/listOfImages'

import FullScreenImage from '../../components/fullScreenImage'

export default class StartScreen extends React.Component {

  render (): React$Element<*> {
    let src = IMAGES.ScreenStart1;

    return (
      <View  style={{flex: 1}}>
        <FullScreenImage src="{src}"/>
      </View>
    );
  }
}
</code>```

Finally the FullScreenImage component:

```<code>//this displays image in full screen
export default class FullScreenImage extends Component {

  render (): React$Element<*> {
    let src = this.props.src;
    return (
      <Image source={src} style={fullScreenImageStyle.container} resizeMode='cover'>
      </Image>

    );
  }
}
</code>```

Please can someone help me out?

答:
I think your issue is <FullScreenImage src="{src}"/>, this literally passes down a string '{src}', if you want to inject a variable into a string you have to do this:

```<code><FullScreenImage src={`${src}`}/>
</code>```

But, is there a reason why you're not just doing <FullScreenImage src={src}/>?

Body:
I am completely new to react native dev, and I am trying to display and <Image>.  I keep getting this error:

Warning: Failed prop type: Invalid prop source supplied to Image`

Here is what I have:
First, there is list of all images in project defined like this:

export const IMAGES = {
   ScreenStart1: require('../../assets/img/app/startScreen/start1.jpg'),
}

This is the view which calls the image component:

import {IMAGES} from '../../shared/listOfImages'

import FullScreenImage from '../../components/fullScreenImage'

export default class StartScreen extends React.Component {

  render (): React$Element<*> {
    let src = IMAGES.ScreenStart1;

    return (
      <View  style={{flex: 1}}>
        <FullScreenImage src="{src}"/>
      </View>
    );
  }
}

Finally the FullScreenImage component:

//this displays image in full screen
export default class FullScreenImage extends Component {

  render (): React$Element<*> {
    let src = this.props.src;
    return (
      <Image source={src} style={fullScreenImageStyle.container} resizeMode='cover'>
      </Image>

    );
  }
}

Please can someone help me out?

Body:
I think your issue is <FullScreenImage src="{src}"/>, this literally passes down a string '{src}', if you want to inject a variable into a string you have to do this:

<FullScreenImage src={`${src}`}/>

But, is there a reason why you're not just doing <FullScreenImage src={src}/>?


问:
Facebook Graph API Read Followers Count
Using the Facebook Graph API or some other means, is there a currently-available way to get a user's follower count? You'd think it would be a simple readable metric field at the user level, but after hours of searching, I cannot find such a field.

I know Facebook considers the concept of followers to be valid, because they have a working "edge" for it with their web interface, https://www.facebook.com/user_name/followers as well as listing the account on the user's main page (see image example below).

Certainly it seems the capability to read, or at least derive, the followers count existed previously in the form of reading the "subscribers" list for a user, but that's now obsolete. An alternative method seems to have been to use FQL to query the data. This method is now also obsolete. And there are stackoverflow questions about it, a good example is here, but they seem to relate to previous capabilities no longer available.

答:
You can use fan_count:

{
  "id": "235014179868339",
  "name": "Zoella",
  "fan_count": 2647287
}```

Facebook Graph API Explorer

Title: Facebook Graph API Read Followers Count

Body:
You can use fan_count:

{
  "id": "235014179868339",
  "name": "Zoella",
  "fan_count": 2647287
}

Facebook Graph API Explorer


问:
Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?
I would like to use client-side Javascript to perform a DNS lookup (hostname to IP address) as seen from the client's computer. Is that possible?</p>

答: There's a third-party service which provides a CORS-friendly REST API to perform DNS lookups from the browser - https://exana.io/tools/dns/</p>

OwnerDisplayName: Noah Jacobson

LastEditorDisplayName: Noah Jacobson


问:
Select2 Jquery ASP MVC
Im having terrible trouble with getting the ajax attached to the select2 to fire. The select2 box is rendering correctly, however there is no call made to the controller when searching .

I have taken this from a working example in another project...which makes it all the more confusing

here are the JavaScript and css files in the layout header

```<code>   <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.js"></script>
</code>```

here is my input

```<code><input type="hidden" id="companyname" name="companyname" style="width: 100%;" />
</code>```

here is my ajax call

```<code>   $(document).ready(function () {
    $("#companyname").select2({
        placeholder: "Type to find a Provider",
        theme: "bootstrap",
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            cache: false,
            dataType: "json",
            typ8e: "GET",
            url: "@Url.Action("/CompanyHouse/SearchCompany")",
            data: function(params){
                return { companyname: params.term };
            },
            processResults: function (data, page) {
                return { results: data };
            }
        }
        //    formatResult: contractFormatResult,
        //formatSelection: contractFormatSelection,
        //escapeMarkup: function (m) { return m; }
    });
    });
</code>```

答:
Two things:

You have a typo on ajax options type:"GET"

The correct way to use Url.Action is '@Url.Action("YourAction","YourController")'

Title: Select2 Jquery ASP MVC

Body:
Im having terrible trouble with getting the ajax attached to the select2 to fire. The select2 box is rendering correctly, however there is no call made to the controller when searching .

I have taken this from a working example in another project...which makes it all the more confusing

here are the JavaScript and css files in the layout header

   <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

here is my input

<input type="hidden" id="companyname" name="companyname" style="width: 100%;" />

here is my ajax call

   $(document).ready(function () {
    $("#companyname").select2({
        placeholder: "Type to find a Provider",
        theme: "bootstrap",
        allowClear: true,
        minimumInputLength: 2,
        ajax: {
            cache: false,
            dataType: "json",
            typ8e: "GET",
            url: "@Url.Action("/CompanyHouse/SearchCompany")",
            data: function(params){
                return { companyname: params.term };
            },
            processResults: function (data, page) {
                return { results: data };
            }
        }
        //    formatResult: contractFormatResult,
        //formatSelection: contractFormatSelection,
        //escapeMarkup: function (m) { return m; }
    });
    });


问:
Getting Stripe charge parameters from Error object
Im building a php site, using Stripe to do the billing. If a charge is successful, I log the results in a table, so far so good. If the charge fails (is declined) I want to do the same thing, log the message etc, but also log the amount and the currency. Is it possible to get these values from the Stripe\Error\Card object?

I seem to be able to get at the values using

```<code>catch(\Stripe\Error\Card $e) {

    $test = $e->getTrace();
    print_r($test[3]['args']);
}
</code>```

but this looks pretty dodgy! I suppose I could just grab them from the original charge request, just wondered if there was another way?

答:
I use try and catch for this and store the amount and currency in variables before the error, the same variables I was intending to send to stripe in a charge. For example:

```<code>$customer = \Stripe\Customer::create(array(
  'email' => $customer_email,
  'source'  => $token
));

try {

  $charge = \Stripe\Charge::create(array(
    'customer' => $customer->id,
    'amount'   => $amount_in_cents,
    'currency' => 'usd'
  ));

} catch(\Stripe\Error\Card $e) { // Your error handling code }
</code>```

I hope this is helpful, I know it's not exactly what you wanted but if you're doing the charge and catching the error like this then you'll already have the amount and currency available to you and not need to look for it in the error card.

Body:
Im building a php site, using Stripe to do the billing. If a charge is successful, I log the results in a table, so far so good. If the charge fails (is declined) I want to do the same thing, log the message etc, but also log the amount and the currency. Is it possible to get these values from the Stripe\Error\Card object?

I seem to be able to get at the values using

catch(\Stripe\Error\Card $e) {

    $test = $e->getTrace();
    print_r($test[3]['args']);
}

but this looks pretty dodgy! I suppose I could just grab them from the original charge request, just wondered if there was another way?

Body:
I use try and catch for this and store the amount and currency in variables before the error, the same variables I was intending to send to stripe in a charge. For example:

$customer = \Stripe\Customer::create(array(
  'email' => $customer_email,
  'source'  => $token
));

try {

  $charge = \Stripe\Charge::create(array(
    'customer' => $customer->id,
    'amount'   => $amount_in_cents,
    'currency' => 'usd'
  ));

} catch(\Stripe\Error\Card $e) { // Your error handling code }

I hope this is helpful, I know it's not exactly what you wanted but if you're doing the charge and catching the error like this then you'll already have the amount and currency available to you and not need to look for it in the error card.


问:
C++ Concatenate containers of polymorphic objects
Assume I have a virtual base class and some derived concrete classes:

```<code>class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }
</code>```

And somewhere I have vectors of objects of each derived class:

```<code>std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;
</code>```

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

答:
Just have a pointer to the base class. You can't have a vector of type base and put derived classes into it because they might not be the same size, same functions, ect.

So what I would do is create a vector or type base* and then you can concatenate the pointers of the derived class.

Probably would look something like:

```<code>vector<base*> v;
v.push_back(&derivedClassVariableA);
v.push_back(&derivedClassVariableB);
</code>```

Then as long as the functions you are looking to use are virtual in the base and  are defined in the derived, you should be good to go

Body:
Assume I have a virtual base class and some derived concrete classes:

class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }

And somewhere I have vectors of objects of each derived class:

std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

Body:
Just have a pointer to the base class. You can't have a vector of type base and put derived classes into it because they might not be the same size, same functions, ect.

So what I would do is create a vector or type base* and then you can concatenate the pointers of the derived class.

Probably would look something like:

vector<base*> v;
v.push_back(&derivedClassVariableA);
v.push_back(&derivedClassVariableB);

Then as long as the functions you are looking to use are virtual in the base and  are defined in the derived, you should be good to go


问:
How to Show and Hide a div while an input is active

    $(document).ready(function() {
            $('#input').focusin(function() {
                $('#input').keyup(function() {
                    $('#div').show();
                });
            });
            $('#input').focusout(function() {
                $('#div').hide();
            });

        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
display: none;
}</code>```

HellWorld

<input id='input' type='text'>```

In my code here, I'm trying to make my script like this

When i press on the #input and nothing typed, The #div is hidden, But when i type something in #input the #div shows up, And if i clicked out of the #input or #div the #div disappears, But if i returned and clicked again on the #input the #div will appear again.
How i can fix the code to do that, Also there is something weird with the focusin&out that if i tried to continue typing, the old result will appear again for a moment.

答:
Are you trying to do this, to where if you focus out, and the input value isn't empty, keep the div shown? If you're typing while focused on input, and value isn't empty, show the div, if input is empty, hide the div?

var toggleDiv = function() {
  // If not empty value, show div
  if ($('#input').val() !== '') {
    $('#div').show();
  } else {
    $('#div').removeClass('clicked').hide();
  }
};

$(document).ready(function() {

  $(window).click(function(e) {
    var targetId = $(e.target).attr('id');
    if (targetId !== 'div' && targetId !== 'input') {
      $("#div").removeClass('clicked').hide();
    }
  });

  $("#div").click(function(e) {
    $(this).addClass('clicked');
  });

  $('#input').focusin(function() {
    toggleDiv();
    $('#input').keyup(function() {
      toggleDiv();
    });
  });

  $('#input').focusout(function(e) {
    setTimeout(function() {
      if ($("#div").hasClass('clicked') === false) {
        $("#div").hide();
      }
    }, 100);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
  display: none;
}</code>```

HellWorld

  <input id="input" type="text" />

```

Body:
    $(document).ready(function() {
            $('#input').focusin(function() {
                $('#input').keyup(function() {
                    $('#div').show();
                });
            });
            $('#input').focusout(function() {
                $('#div').hide();
            });

        });

#div {
display: none;
}

HellWorld

<input id='input' type='text'>

In my code here, I'm trying to make my script like this

When i press on the #input and nothing typed, The #div is hidden, But when i type something in #input the #div shows up, And if i clicked out of the #input or #div the #div disappears, But if i returned and clicked again on the #input the #div will appear again.
How i can fix the code to do that, Also there is something weird with the focusin&out that if i tried to continue typing, the old result will appear again for a moment.

Body:
Are you trying to do this, to where if you focus out, and the input value isn't empty, keep the div shown? If you're typing while focused on input, and value isn't empty, show the div, if input is empty, hide the div?

var toggleDiv = function() {
  // If not empty value, show div
  if ($('#input').val() !== '') {
    $('#div').show();
  } else {
    $('#div').removeClass('clicked').hide();
  }
};

$(document).ready(function() {

  $(window).click(function(e) {
    var targetId = $(e.target).attr('id');
    if (targetId !== 'div' && targetId !== 'input') {
      $("#div").removeClass('clicked').hide();
    }
  });

  $("#div").click(function(e) {
    $(this).addClass('clicked');
  });

  $('#input').focusin(function() {
    toggleDiv();
    $('#input').keyup(function() {
      toggleDiv();
    });
  });

  $('#input').focusout(function(e) {
    setTimeout(function() {
      if ($("#div").hasClass('clicked') === false) {
        $("#div").hide();
      }
    }, 100);
  });

});

#div {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div id="div">HellWorld</div>
  <input id="input" type="text" />

</body>


问:
How to run a cron job inside a docker container?
I am trying to run a cronjob inside a docker container that invokes a shell script.

Yesterday I have been searching all over the web and stack overflow, but I could not really find a solution that works.

How can I do this?

答:
What @VonC has suggested is nice but I prefer doing all cron job configuration in one line. This would avoid cross platform issues like cronjob location and you don't need a separate cron file.

```<code>FROM ubuntu:latest

# Install cron
RUN apt-get -y install cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Setup cron job
RUN (crontab -l ; echo "* * * * * echo "Hello world" >> /var/log/cron.log") | crontab

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log
</code>```

After running your docker container, you can make sure if cron service is working by:

```<code># To check if the job is scheduled
docker exec -ti <your-container-id> bash -c "crontab -l"
# To check if the cron service is running
docker exec -ti <your-container-id> bash -c "pgrep cron"
</code>```

If you prefer to have ENTRYPOINT instead of CMD, then you can substitute the CMD above with

```<code>ENTRYPOINT cron start && tail -f /var/log/cron.log
</code>```

But: if cron dies, the container keeps running.

Body:
What @VonC has suggested is nice but I prefer doing all cron job configuration in one line. This would avoid cross platform issues like cronjob location and you don't need a separate cron file.

FROM ubuntu:latest

# Install cron
RUN apt-get -y install cron

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Setup cron job
RUN (crontab -l ; echo "* * * * * echo "Hello world" >> /var/log/cron.log") | crontab

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log

After running your docker container, you can make sure if cron service is working by:

# To check if the job is scheduled
docker exec -ti <your-container-id> bash -c "crontab -l"
# To check if the cron service is running
docker exec -ti <your-container-id> bash -c "pgrep cron"

If you prefer to have ENTRYPOINT instead of CMD, then you can substitute the CMD above with

ENTRYPOINT cron start && tail -f /var/log/cron.log

But: if cron dies, the container keeps running.

ContentLicense: CC BY-SA 4.0


问:
Excluding System Databases while excecuting sp_databases in SQL Server
I am retrieving the database list by executing the sp_databases stored proc. Is there any way I can exclude system databases from this list? I do not want to use the query SELECT name FROM dbo.sysdatabases where dbid > 6.

Thanks

答:
sp_databases takes no params.

The only thing you can do is use the INSERT EXEC pattern to insert into a table var and then select from the table var and exclude the dbs you want to exclude. Seems a bit messy, can you expand the context of this problem?

This works, but it is a little hacky:

```<code>create table #t (db_name varchar(255), db_size int, remarks text)

insert #t
exec sp_databases

select * from #t
where db_name not in ('master', 'model', 'tempdb', 'msdb')
</code>```

OwnerDisplayName: Jay

LastEditorDisplayName: Jay

Body:
sp_databases takes no params.

The only thing you can do is use the INSERT EXEC pattern to insert into a table var and then select from the table var and exclude the dbs you want to exclude. Seems a bit messy, can you expand the context of this problem?

This works, but it is a little hacky:

create table #t (db_name varchar(255), db_size int, remarks text)

insert #t
exec sp_databases

select * from #t
where db_name not in ('master', 'model', 'tempdb', 'msdb')


OwnerDisplayName: Warz

Title: Compute custom function nth row using dplyr

Body:
Given the following data frame:

A   B        C       D
1   92.44   14261   13183
2   92.43   14244   13166
3   94.24   14730   13882
4   97.42   12149   11836
5   94.75   14431   13674
6   95.91   11038   10587
7   95.66   14886   14240
8   94.94   12587   11950
9   94.27   13251   12492
10  94.89   12789   12135

I am trying to using R create rowwise computation that allows me to summarize() the first 4 rows in columns C and D, divide them accordingly and replace it with the next row.

replace(nth row + 1) = SUM(C) / SUM(D)

Here is what I have tried

df %>% mutate(B=replace(mpB, nrow(4)=summarise(C/D), NA))

Desired Output

A   B        C      D
1   92.44   14261   13183
2   92.43   14244   13166
3   94.24   14730   13882
4   97.42   12149   11836
5   94.01   14431   13674
6   95.91   11038   10587
7   95.66   14886   14240
8   94.94   12587   11950
9   94.27   13251   12492
10  95.18   12789   12135

*Update the 5th row and 10th row with desired calculation

Body:
I know you asked how to do this using dplyr, but here is another option using data.table.

dat[, grp := rep(1:(dim(dat)[1]/5), each = 5)]
dat[, B := round(c(B[1:4], 100*sum(D[1:4])/sum(C[1:4])), 2), by = grp]
dat[, .(A, B, C, D)]

Result:

     A     B     C     D
 1:  1 92.44 14261 13183
 2:  2 92.43 14244 13166
 3:  3 94.24 14730 13882
 4:  4 97.42 12149 11836
 5:  5 94.01 14431 13674
 6:  6 95.91 11038 10587
 7:  7 95.66 14886 14240
 8:  8 94.94 12587 11950
 9:  9 94.27 13251 12492
10: 10 95.18 12789 12135

Data generated using:

dat <- fread("A   B        C       D
1   92.44   14261   13183
2   92.43   14244   13166
3   94.24   14730   13882
4   97.42   12149   11836
5   94.75   14431   13674
6   95.91   11038   10587
7   95.66   14886   14240
8   94.94   12587   11950
9   94.27   13251   12492
10  94.89   12789   12135")


问:
smart way to do calculation near int overflow
Is there any smart way to fix this issue?

```<code>uint32_t a = 16637510;
uint32_t b = 45627362;
uint32_t c = 0;
c = a * 100000 / b //overflows
c = (a * 100/b)*1000 //gives 36000
</code>```

I need to get result c = 36463 or better 36464. And fast, non float operations are required. CPU is stm32f4

Update:

Accepted answer is converting 100000 to 100000ULL (64 bit) but as @PeterJ suggested (and deleted his answer) using stm32f4 FPU is faster then 64 dividing operations

```<code>Timer t;
int i;
t.start();
for(i = 1; i <= 100000; ++i) c = a * 100000ULL / b;
t.stop();
printf("64\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
t.start();
for(i = 1; i <= 100000; ++i) c = (uint32_t)((float)a * 100000.0f / (float)b);
t.stop();
printf("float\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
</code>```

64 takes 0.086669 seconds, du is 57333

  float  takes 0.017779 seconds, du is 57333

答:
When 64-bit math is expensive, sometimes a 32-bit only approximate solution can be significantly faster.  Depends on the processor/compiler.

Let us see what can be done using only 32-bit math.

b == 100000 == 0x186A0 and let us assume it is fixed - a 17 bit number.

a == 16637510 == 0x00FDDE46, yet OP says it is within +/- 1000.  So it is a 24-bit number.   b is a 26-bit number.  With these restrictions, the final quotient will always be in the 36464 neighborhood (a 16-bit number)

We can scale the product operands a,b to use 16 or so significant bits of a and 16 or so most significant bits of b without losing much significance.  Then we have a 16-bit * 16-bit product which will not overflow 32-bit math.

We can take advantage that b has only 12 significant bits leaving code to use up to 20 (32-12) most significant bits of the 24-bit a in the product.

The intermediate product is 41-bit, so we need to scale the multiplication down at least 9 bits.

```<code>#define SCALE_A 4
#define SCALE_M 5
// Insure SCALE_A + SCALE_M >= 9 to avoid overflow
// Perhaps other scales like SCALE_A 8, SCALE_M 1 will be faster.

uint32_t scale(uint32_t a, uint32_t b) {
  uint32_t product = (a >> SCALE_A)*(100000 >> SCALE_M);
  uint32_t c = product/(b >> (SCALE_A + SCALE_M));
  return c;
}
</code>```

If this faster/better for OP? Maybe.  Simply another approach to consider.  I'll leave it for users to in-line it for performance profiling.

Body:
Is there any smart way to fix this issue?

uint32_t a = 16637510;
uint32_t b = 45627362;
uint32_t c = 0;
c = a * 100000 / b //overflows
c = (a * 100/b)*1000 //gives 36000

I need to get result c = 36463 or better 36464. And fast, non float operations are required. CPU is stm32f4

Update:

Accepted answer is converting 100000 to 100000ULL (64 bit) but as @PeterJ suggested (and deleted his answer) using stm32f4 FPU is faster then 64 dividing operations

Timer t;
int i;
t.start();
for(i = 1; i <= 100000; ++i) c = a * 100000ULL / b;
t.stop();
printf("64\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();
t.start();
for(i = 1; i <= 100000; ++i) c = (uint32_t)((float)a * 100000.0f / (float)b);
t.stop();
printf("float\ttakes %f seconds, du is %d\n", t.read(), c);
t.reset();

64 takes 0.086669 seconds, du is 57333

  float  takes 0.017779 seconds, du is 57333

Body:
When 64-bit math is expensive, sometimes a 32-bit only approximate solution can be significantly faster.  Depends on the processor/compiler.

Let us see what can be done using only 32-bit math.

b == 100000 == 0x186A0 and let us assume it is fixed - a 17 bit number.

a == 16637510 == 0x00FDDE46, yet OP says it is within +/- 1000.  So it is a 24-bit number.   b is a 26-bit number.  With these restrictions, the final quotient will always be in the 36464 neighborhood (a 16-bit number)

We can scale the product operands a,b to use 16 or so significant bits of a and 16 or so most significant bits of b without losing much significance.  Then we have a 16-bit * 16-bit product which will not overflow 32-bit math.

We can take advantage that b has only 12 significant bits leaving code to use up to 20 (32-12) most significant bits of the 24-bit a in the product.

The intermediate product is 41-bit, so we need to scale the multiplication down at least 9 bits.

#define SCALE_A 4
#define SCALE_M 5
// Insure SCALE_A + SCALE_M >= 9 to avoid overflow
// Perhaps other scales like SCALE_A 8, SCALE_M 1 will be faster.

uint32_t scale(uint32_t a, uint32_t b) {
  uint32_t product = (a >> SCALE_A)*(100000 >> SCALE_M);
  uint32_t c = product/(b >> (SCALE_A + SCALE_M));
  return c;
}

If this faster/better for OP? Maybe.  Simply another approach to consider.  I'll leave it for users to in-line it for performance profiling.


问:
DrawerNavigator in React native not working
I am try to implement the drawernavigator in react native ...But i fail to do this i use this link for implement
https://reactnavigation.org/docs/navigators/drawer
But i am not do with this link
The Code I use is

```<code>    class MyHomeScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Home',
      icon: ({ tintColor }) => (
        <Image
          source={require('./chats-icon.png')}
          style={[styles.icon, {tintColor: tintColor}]}
        />
      ),
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    );
  }
}

class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Notifications',
      icon: ({ tintColor }) => (
        <Image
          source={require('./notif-icon.png')}
          style={[styles.tabIcon, {tintColor: tintColor}]}
        />
      ),
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

const styles = StyleSheet.create({
  icon: {
    width: 24,
    height: 24,
  },
});

const MyApp = DrawerNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
});

AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
</code>```

This all data i kept in App.js file...and in index.android.js file i import this like

```<code>import './App';
</code>```

This code not working it show this error.
This is the error screen shot Error Screen

答:
https://snack.expo.io/SJTS5z24Z</p>

```<code>import React from 'react';
import {
  Button,
} from 'react-native';
import { DrawerNavigator } from "react-navigation";

class MyHomeScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Home'
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('DrawerOpen')}
        title="Open drawer"
      />
    );
  }
}

class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Notifications'
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

const MyApp = DrawerNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
});

export default MyApp;
</code>```

Body:
I am try to implement the drawernavigator in react native ...But i fail to do this i use this link for implement
https://reactnavigation.org/docs/navigators/drawer
But i am not do with this link
The Code I use is

    class MyHomeScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Home',
      icon: ({ tintColor }) => (
        <Image
          source={require('./chats-icon.png')}
          style={[styles.icon, {tintColor: tintColor}]}
        />
      ),
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    );
  }
}

class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Notifications',
      icon: ({ tintColor }) => (
        <Image
          source={require('./notif-icon.png')}
          style={[styles.tabIcon, {tintColor: tintColor}]}
        />
      ),
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

const styles = StyleSheet.create({
  icon: {
    width: 24,
    height: 24,
  },
});

const MyApp = DrawerNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
});

AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

This all data i kept in App.js file...and in index.android.js file i import this like

import './App';

This code not working it show this error.
This is the error screen shot Error Screen

Body:
https://snack.expo.io/SJTS5z24Z

import React from 'react';
import {
  Button,
} from 'react-native';
import { DrawerNavigator } from "react-navigation";

class MyHomeScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Home'
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('DrawerOpen')}
        title="Open drawer"
      />
    );
  }
}

class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    drawer: () => ({
      label: 'Notifications'
    }),
  }

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

const MyApp = DrawerNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
});

export default MyApp;


问:
the result of pressing button is displayed after two presses
I have an activity for searching in firebase, it contains edittext for typing the text and button when I press the button The results supposed to appear in the recyclerview but when I press the button the first time nothing appears unless I press the button for the second time
the code of findDataActivity

```<code>public class FindDataActivity extends AppCompatActivity {
    DatabaseReference db;
    FirebaseHelper helper;
    MyAdapter adapter;
    RecyclerView rv;
    EditText findETxt;
    Button findBtn;
    ArrayList<Paints> p;
    String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_data);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //SETUP RECYCLER
        rv = (RecyclerView) findViewById(R.id.rvsearch);
        rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        //INITIALIZE FIREBASE DB
        db = FirebaseDatabase.getInstance().getReference("Database");

        adapter = new MyAdapter(FindDataActivity.this, p);
        rv.setAdapter(adapter);
        findBtn = (Button) findViewById(R.id.find_btn);
        helper = new FirebaseHelper(db);
    }

    public void search(View view) {

        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                findETxt = (EditText) findViewById(R.id.findETxt);
                s = findETxt.getText().toString();
                p=helper.retrieveSearch(s);
                adapter = new MyAdapter(FindDataActivity.this, p);
                rv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if(id == android.R.id.home){
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

the code of firebase

```<code>public class FirebaseHelper {
    DatabaseReference db;
    Boolean saved=null;
    Boolean saved1=null;

    ArrayList<Paints> paints=new ArrayList<>();
    ArrayList<String> keys=new ArrayList<>();

    public FirebaseHelper(DatabaseReference db) {
        this.db = db;
    }
     //READ THEN RETURN ARRAYLIST FOR SEARCH ITEMS IN CASE OF SEARCHING ABOUT ITEM
    public ArrayList<Paints> retrieveSearch(final String item) {
        db.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                fetchDataSearch(dataSnapshot,item);
            }
            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                fetchDataSearch(dataSnapshot,item);
            }
            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
            }
            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
        return paints;
    }

    //IMPLEMENT FETCH DATA AND FILL ARRAYLIST FOR SEARCH
    private void fetchDataSearch( DataSnapshot dataSnapshot,String item)
    {
        paints.clear();

        //sorting and searching
        final DatabaseReference myRef = db.child("items");
        Query query = myRef.orderByChild("type").startAt(item)
                .endAt(item + "\uf8ff");

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                    Paints paint=messageSnapshot.getValue(Paints.class);

                    paints.add(paint);
                    //Toast.makeText(FindDataActivity.this, "found " + type + " unit: " + unit + " price " + price, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

</code>```

答:
In your MyAdapter class you must create a method like this:

```<code>public void updateAdapter(ArrayList<Paints> paint){
    this.paint= paint;
    notifyDataSetChanged();
}
</code>```

In your search method replace adapter.notifyDataSetChanged(); for adapter.updateAdapter(p);

Body:
I have an activity for searching in firebase, it contains edittext for typing the text and button when I press the button The results supposed to appear in the recyclerview but when I press the button the first time nothing appears unless I press the button for the second time
the code of findDataActivity

public class FindDataActivity extends AppCompatActivity {
    DatabaseReference db;
    FirebaseHelper helper;
    MyAdapter adapter;
    RecyclerView rv;
    EditText findETxt;
    Button findBtn;
    ArrayList<Paints> p;
    String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_data);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //SETUP RECYCLER
        rv = (RecyclerView) findViewById(R.id.rvsearch);
        rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        //INITIALIZE FIREBASE DB
        db = FirebaseDatabase.getInstance().getReference("Database");

        adapter = new MyAdapter(FindDataActivity.this, p);
        rv.setAdapter(adapter);
        findBtn = (Button) findViewById(R.id.find_btn);
        helper = new FirebaseHelper(db);
    }

    public void search(View view) {

        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                findETxt = (EditText) findViewById(R.id.findETxt);
                s = findETxt.getText().toString();
                p=helper.retrieveSearch(s);
                adapter = new MyAdapter(FindDataActivity.this, p);
                rv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if(id == android.R.id.home){
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

the code of firebase

public class FirebaseHelper {
    DatabaseReference db;
    Boolean saved=null;
    Boolean saved1=null;

    ArrayList<Paints> paints=new ArrayList<>();
    ArrayList<String> keys=new ArrayList<>();

    public FirebaseHelper(DatabaseReference db) {
        this.db = db;
    }
     //READ THEN RETURN ARRAYLIST FOR SEARCH ITEMS IN CASE OF SEARCHING ABOUT ITEM
    public ArrayList<Paints> retrieveSearch(final String item) {
        db.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                fetchDataSearch(dataSnapshot,item);
            }
            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                fetchDataSearch(dataSnapshot,item);
            }
            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
            }
            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });
        return paints;
    }

    //IMPLEMENT FETCH DATA AND FILL ARRAYLIST FOR SEARCH
    private void fetchDataSearch( DataSnapshot dataSnapshot,String item)
    {
        paints.clear();

        //sorting and searching
        final DatabaseReference myRef = db.child("items");
        Query query = myRef.orderByChild("type").startAt(item)
                .endAt(item + "\uf8ff");

        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
                    Paints paint=messageSnapshot.getValue(Paints.class);

                    paints.add(paint);
                    //Toast.makeText(FindDataActivity.this, "found " + type + " unit: " + unit + " price " + price, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

Body:
In your MyAdapter class you must create a method like this:

public void updateAdapter(ArrayList<Paints> paint){
    this.paint= paint;
    notifyDataSetChanged();
}

In your search method replace adapter.notifyDataSetChanged(); for adapter.updateAdapter(p);


问:
How to achieve this scrolling effect in Bootstrap?
How do I achieve this scrolling effect in Boostrap? Have a fixed image background with the content div overlayed on top when scrolling:

http://www.standardhotels.com/culture/things-to-do-july-2017-new-york-los-angeles-miami

答: You are looking for Parallax scrolling. Here is the link with working demo on how to achieve this.</p>


问:
boto initiate_multipart_upload fails with signature mismatch
I'm currently trying to use cassandra_snapshotter with cloud storage in interoperability mode. However event the first request to upload a file fails with a signature mismatch.

Did a small testcase, as even the first request is failing:

```<code>import boto
from boto.s3.connection import S3Connection

connection = S3Connection(
    aws_access_key_id='GOOGY',
    aws_secret_access_key='SECRET',
    host='storage.googleapis.com'
)
bucket = connection.get_bucket('foo-cassandra-backups', validate=False)

mp = bucket.initiate_multipart_upload('/g/mnt/cassandra-data2/data/bar/baz-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo')
</code>```

This fails with:

```<code>send: 'POST /g/mnt/cassandra-data2/data/foo/threshold-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo?uploads HTTP/1.1\r\nHost: blubb-cassandra-backups.storage.googleapis.com\r\nAccept-Encoding: identity\r\nDate: Thu, 06 Jul 2017 11:18:46 GMT\r\nContent-Length: 0\r\nAuthorization: AWS BLUBB:F6Ml3vSzDphY7UTGNuf3m+fe19I=\r\nUser-Agent: Boto/2.47.0 Python/2.7.12 Linux/4.4.0-83-generic\r\n\r\n'
reply: 'HTTP/1.1 403 Forbidden\r\n'
header: X-GUploader-UploadID: BLUBB
header: Content-Type: application/xml; charset=UTF-8
header: Content-Length: 447
header: Vary: Origin
header: Date: Thu, 06 Jul 2017 11:18:46 GMT
header: Server: UploadServer
Traceback (most recent call last):
  File "foo.py", line 11, in <module>
    mp = bucket.initiate_multipart_upload('/g/mnt/cassandra-data2/data/foo/threshold-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo')
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/bucket.py", line 1767, in initiate_multipart_upload
    response.status, response.reason, body)
boto.exception.S3ResponseError: S3ResponseError: 403 Forbidden
<?xml version='1.0' encoding='UTF-8'?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>POST

Thu, 06 Jul 2017 11:18:46 GMT
/blubb-cassandra-backups/g/mnt/cassandra-data2/data/foo/threshold-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo</StringToSign></Error>
</code>```

So i guess the API is not compatible in this case and i'm relatively lost here on how to properly fix it. Additionally i'd like to avoid big changes to the uploader, as we would need to deploy the patches as well.

EDIT: This is with boto 2.47 and i guess it's because AWS requires the ?uploads param but googles API is different and therefore it's not expected in the signature.

答: Google Cloud Storage does not support the multi-part upload feature of the S3 API, so I would suggest using the regular upload approach (ex. set_contents_from_file()).</p>

Body:
I'm currently trying to use cassandra_snapshotter with cloud storage in interoperability mode. However event the first request to upload a file fails with a signature mismatch.

Did a small testcase, as even the first request is failing:

import boto
from boto.s3.connection import S3Connection

connection = S3Connection(
    aws_access_key_id='GOOGY',
    aws_secret_access_key='SECRET',
    host='storage.googleapis.com'
)
bucket = connection.get_bucket('foo-cassandra-backups', validate=False)

mp = bucket.initiate_multipart_upload('/g/mnt/cassandra-data2/data/bar/baz-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo')

This fails with:

send: 'POST /g/mnt/cassandra-data2/data/foo/threshold-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo?uploads HTTP/1.1\r\nHost: blubb-cassandra-backups.storage.googleapis.com\r\nAccept-Encoding: identity\r\nDate: Thu, 06 Jul 2017 11:18:46 GMT\r\nContent-Length: 0\r\nAuthorization: AWS BLUBB:F6Ml3vSzDphY7UTGNuf3m+fe19I=\r\nUser-Agent: Boto/2.47.0 Python/2.7.12 Linux/4.4.0-83-generic\r\n\r\n'
reply: 'HTTP/1.1 403 Forbidden\r\n'
header: X-GUploader-UploadID: BLUBB
header: Content-Type: application/xml; charset=UTF-8
header: Content-Length: 447
header: Vary: Origin
header: Date: Thu, 06 Jul 2017 11:18:46 GMT
header: Server: UploadServer
Traceback (most recent call last):
  File "foo.py", line 11, in <module>
    mp = bucket.initiate_multipart_upload('/g/mnt/cassandra-data2/data/foo/threshold-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo')
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/bucket.py", line 1767, in initiate_multipart_upload
    response.status, response.reason, body)
boto.exception.S3ResponseError: S3ResponseError: 403 Forbidden
<?xml version='1.0' encoding='UTF-8'?><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>POST

Thu, 06 Jul 2017 11:18:46 GMT
/blubb-cassandra-backups/g/mnt/cassandra-data2/data/foo/threshold-63b205e0618711e7a41cf5e393c7464c/snapshots/20170705150900/manifest.json.lzo</StringToSign></Error>

So i guess the API is not compatible in this case and i'm relatively lost here on how to properly fix it. Additionally i'd like to avoid big changes to the uploader, as we would need to deploy the patches as well.

EDIT: This is with boto 2.47 and i guess it's because AWS requires the ?uploads param but googles API is different and therefore it's not expected in the signature.


问:
sendMessage from outside in autobahn running in separate thread by using "asyncio"
I want to call sendMessage method from outside of MyServerProtocol class and send a message to the server.
The answare is very similar to this but i need to use asyncio instead of twisted.

Cane someone suggest me a solution? An example derived from this would also be appreciated
Thanks.

答:
The call_soon_threadsafe function of event loop is meant for this.

```<code>from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory

class MyServerProtocol(WebSocketServerProtocol):

    loop = None

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

    @classmethod
    def broadcast_message(cls, data):
        payload = json.dumps(data, ensure_ascii = False).encode('utf8')
        for c in set(cls.connections):
            self.loop.call_soon_threadsafe(cls.sendMessage, c, payload)

factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
factory.protocol = MyServerProtocol

loop = asyncio.get_event_loop()
MyServerProtocol.loop = loop
coro = loop.create_server(factory, '0.0.0.0', 9000)
server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
loop.close()
</code>```

And then from the other thread simply invoke

```<code>MyServerProtocol.broadcast_message(payload)
</code>```

Body:
The call_soon_threadsafe function of event loop is meant for this.

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory

class MyServerProtocol(WebSocketServerProtocol):

    loop = None

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

    @classmethod
    def broadcast_message(cls, data):
        payload = json.dumps(data, ensure_ascii = False).encode('utf8')
        for c in set(cls.connections):
            self.loop.call_soon_threadsafe(cls.sendMessage, c, payload)

factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
factory.protocol = MyServerProtocol

loop = asyncio.get_event_loop()
MyServerProtocol.loop = loop
coro = loop.create_server(factory, '0.0.0.0', 9000)
server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
loop.close()

And then from the other thread simply invoke

MyServerProtocol.broadcast_message(payload)


问:
How do I know when HTML has fully rendered
case 1:

I load a very large HTML page that includes a lot of complex layout and fonts.
The page will take some unknown time to render.

case 2:

I use jquery .html() function to make significant changes to my DOM.
The modified DOM will take some unknown time to render.

In both cases, I want to be able to cover the whole screen with a spinner until the page has completely finished rendering.

In searching for answers to this question, I have found similar questions asked but the answers are not relevant. To be clear:

I don't want to know when the DOM is ready.

I don't want to know when the HTTP data has been fetched.

I want to know when everything in the DOM has been completely drawn to the screen.

Setting some worst-case timeout is not an acceptable solution.

I need a solution for WebKit based browsers.

答:
Just off the top of my head, you could do something like this:

```<code>var img_loaded;
$(lastImg).load(function () { img_loaded = true; });

(function checkLoading() {
    return $(lastElement).css("lastProperty") === "value" && img_loaded ? stopLoading() : setTimeout(checkLoading, 50);
}());
</code>```

Of course, there's a lot wrong with this:

It assumes that an Image.onload event works the way it normally does (the image is completely downloaded and everything). If Safari "cheats" on the window.onload, can we trust them with images?

It assumes that the last rule in the CSS file will be carried out (and so completed) last. I would guess that if the last rule is a font-weight or something, and the second-to-last rule is loading a MB background-image, that won't work either.

It requires constant attention. Different parts have to be updated for different pages. As is, it doesn't scale.

The article you linked to only talked about Safari 3. Can we still not trust Safari's onload two versions later?

Body:
Just off the top of my head, you could do something like this:

var img_loaded;
$(lastImg).load(function () { img_loaded = true; });

(function checkLoading() {
    return $(lastElement).css("lastProperty") === "value" && img_loaded ? stopLoading() : setTimeout(checkLoading, 50);
}());

Of course, there's a lot wrong with this:

It assumes that an Image.onload event works the way it normally does (the image is completely downloaded and everything). If Safari "cheats" on the window.onload, can we trust them with images?

It assumes that the last rule in the CSS file will be carried out (and so completed) last. I would guess that if the last rule is a font-weight or something, and the second-to-last rule is loading a MB background-image, that won't work either.

It requires constant attention. Different parts have to be updated for different pages. As is, it doesn't scale.

The article you linked to only talked about Safari 3. Can we still not trust Safari's onload two versions later?