问:
Python urlparse -- extract domain name without subdomain
Need a way to extract a domain name without the subdomain from a url using Python urlparse.

For example, I would like to extract "google.com" from a full url like "http://www.google.com".

The closest I can seem to come with urlparse is the netloc attribute, but that includes the subdomain, which in this example would be www.google.com.

I know that it is possible to write some custom string manipulation to turn www.google.com into google.com, but I want to avoid by-hand string transforms or regex in this task.  (The reason for this is that I am not familiar enough with url formation rules to feel confident that I could consider every edge case required in writing a custom parsing function.)

Or, if urlparse can't do what I need, does anyone know any other Python url-parsing libraries that would?

答:
There are multiple Python modules which encapsulate the (once Mozilla) Public Suffix List in a library, several of which don't require the input to be a URL.  Even though the question asks about URL normalization specifically, my requirement was to handle just domain names, and so I'm offering a tangential answer for that.

The relative merits of publicsuffix2 over publicsuffixlist or publicsuffix are unclear, but they all seem to offer the basic functionality.

publicsuffix2:

```<code>>>> import publicsuffix  # sic
>>> publicsuffix.PublicSuffixList().get_public_suffix('www.google.co.uk')
u'google.co.uk'
</code>```

Supposedly more packaging-friendly fork of publicsuffix.

publicsuffixlist:

```<code>>>> import publicsuffixlist
>>> publicsuffixlist.PublicSuffixList().privatesuffix('www.google.co.uk')
'google.co.uk'
</code>```

Advertises idna support, which I however have not tested.

publicsuffix:

```<code>>>> import publicsuffix
>>> publicsuffix.PublicSuffixList(publicsuffix.fetch()).get_public_suffix('www.google.co.uk')
'google.co.uk'
</code>```

The requirement to handle the updates and caching the downloaded file yourself is a bit of a complication.

Body:
There are multiple Python modules which encapsulate the (once Mozilla) Public Suffix List in a library, several of which don't require the input to be a URL.  Even though the question asks about URL normalization specifically, my requirement was to handle just domain names, and so I'm offering a tangential answer for that.

The relative merits of publicsuffix2 over publicsuffixlist or publicsuffix are unclear, but they all seem to offer the basic functionality.

publicsuffix2:

>>> import publicsuffix  # sic
>>> publicsuffix.PublicSuffixList().get_public_suffix('www.google.co.uk')
u'google.co.uk'

Supposedly more packaging-friendly fork of publicsuffix.

publicsuffixlist:

>>> import publicsuffixlist
>>> publicsuffixlist.PublicSuffixList().privatesuffix('www.google.co.uk')
'google.co.uk'

Advertises idna support, which I however have not tested.

publicsuffix:

>>> import publicsuffix
>>> publicsuffix.PublicSuffixList(publicsuffix.fetch()).get_public_suffix('www.google.co.uk')
'google.co.uk'

The requirement to handle the updates and caching the downloaded file yourself is a bit of a complication.


来源: stackexchange

问:
Create a join out of two belongs_to relationships
Is there a way that I can have an AR relationship that encapsulates two belongs_to relationships that point to the same model?

```<code>class Transaction < ApplicationRecord
  belongs_to :sender, class_name: 'Account'
  belongs_to :recipient, class_name: 'Account'
end
</code>```

In essence, I want to be able to run queries that rely on nested joins like so with accounts referring to either the foreign key sender_id or recipient_id pointing to the events table:

```<code>Transaction.joins(accounts: :banks)...
</code>```

答:
```<code>Transaction.includes(sender: :banks, recipient: :banks).where(banks: {name: 'My Bank'})
</code>```

Tested working with a replicated schema of yours assuming I understood your question correctly

ContentLicense: CC BY-SA 3.0

Body:
Is there a way that I can have an AR relationship that encapsulates two belongs_to relationships that point to the same model?

class Transaction < ApplicationRecord
  belongs_to :sender, class_name: 'Account'
  belongs_to :recipient, class_name: 'Account'
end

In essence, I want to be able to run queries that rely on nested joins like so with accounts referring to either the foreign key sender_id or recipient_id pointing to the events table:

Transaction.joins(accounts: :banks)...

Body:
Transaction.includes(sender: :banks, recipient: :banks).where(banks: {name: 'My Bank'})

Tested working with a replicated schema of yours assuming I understood your question correctly


问:
Skip JavaScript 'Sys.WebForms..' function when a page doesn't have a ScriptManager
I'm using one JavaScript binds in Master Page for the entire project, and the Master Page doesn't include a ScriptManager, that is, some pages include Ajax components, like UpdatePanel, but some not. The 'Sys.WebForms..' functions set in the 'Global' JavaScript works fine with the page has a ScriptManager, but it will cause JS errors in non-ajax page, e.g. 'Sys is undefined, $find is undefined.'

The message is very annoying, though the it doesn't effect anything.

So any smart solutions?

Is adding ScriptManager to Master Page the best solution? (but need to remove all the ScriptManager in child pages).

Regards

答:
an if statement saves the day :)</p>

```<code>if ( Sys != null || Sys !='undefined')
 Sys.WebForms...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
an if statement saves the day :)

if ( Sys != null || Sys !='undefined')
 Sys.WebForms...


问:
Is it possible to Pivot data using LINQ?
I am wondering if it is possible to use LINQ to pivot data from the following layout:

```<code>CustID | OrderDate | Qty
1      | 1/1/2008  | 100
2      | 1/2/2008  | 200
1      | 2/2/2008  | 350
2      | 2/28/2008 | 221
1      | 3/12/2008 | 250
2      | 3/15/2008 | 2150
</code>```

into something like this:

```<code>CustID  | Jan- 2008 | Feb- 2008 | Mar - 2008 |
1       | 100       | 350       |  250
2       | 200       | 221       | 2150
</code>```

答:
The neatest approach for this, I think, is to use a lookup:</p>

```<code>var query =
    from c in myList
    group c by c.CustId into gcs
    let lookup = gcs.ToLookup(y => y.OrderDate.Month, y => y.Qty)
    select new
    {
        CustId = gcs.Key,
        Jan = lookup[1].Sum(),
        Feb = lookup[2].Sum(),
        Mar = lookup[3].Sum(),
    };
</code>```

OwnerDisplayName: Tim Lentine

ContentLicense: CC BY-SA 4.0

Body:
I am wondering if it is possible to use LINQ to pivot data from the following layout:

CustID | OrderDate | Qty
1      | 1/1/2008  | 100
2      | 1/2/2008  | 200
1      | 2/2/2008  | 350
2      | 2/28/2008 | 221
1      | 3/12/2008 | 250
2      | 3/15/2008 | 2150

into something like this:

CustID  | Jan- 2008 | Feb- 2008 | Mar - 2008 |
1       | 100       | 350       |  250
2       | 200       | 221       | 2150

Body:
The neatest approach for this, I think, is to use a lookup:

var query =
    from c in myList
    group c by c.CustId into gcs
    let lookup = gcs.ToLookup(y => y.OrderDate.Month, y => y.Qty)
    select new
    {
        CustId = gcs.Key,
        Jan = lookup[1].Sum(),
        Feb = lookup[2].Sum(),
        Mar = lookup[3].Sum(),
    };


问:
Change encoding of a csv file in php
I am trying to load a bunch of csv files into a database. Parsing the files and entering the data is all working great.....except some of the files encoding is giving me trouble.

UTF-8 files work fine and most files are this format. However some of the files are in ASCII and these files do not load properly.

Is there a way to check the file itself for its encoding, and convert the encoding before using the data? I have been playing with mb_convert_encoding and iconv but these all take a string as input.  would rather check the file and convert right off the bat instead of checking it line by line as I take in the data.

Thank you.

答:
Try below code:</p>

```<code><?php
$handle = fopen ("temp.csv","r");
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data);
}
?>
</code>```

Title: Change encoding of a csv file in php

Body:
Try below code:

<?php
$handle = fopen ("temp.csv","r");
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data);
}
?>


问:
Surrogate key in Oracle DB best practices
I have a few systems and I need to import data from these systems into a common table. But ID is unique only within source system. So I need to create my own primary key to uniquely identify this data in the target table.

What is best practice to resolve the problem? I don't want to create primary key  as character and I don't want to generate an ID  for instance by adding 1000000000. Concatenation with name of system will build character data type. Do you have an idea or some solution?

Thanks for help.

答:
There is no best practice, there is only opinion. But generally it is a bad idea to use source system keys as primary keys in a data warehouse (or whatever data store you're building).

Create new columns for the target table, at the very least surrogate primary key; something to identify the originating system is very useful too. Populate those when you load the data. You may want to enforce (source system key, source system name ) as a unique key, in which case you will need to add that originating system identifier column.


问:
converting a list of integers into range in python
Is there something existing in python that can convert an increasing list of integers into a range list

E.g. given the set {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get { {0,4}, {7,9}, {11,11} }.

I can write a program to do this, but want to know if there is an inbuilt function in python

答:
This is an improvement over the very elegant answer. This one covers non-unique and non-sorted input and is python3 compatible too:

```<code>import itertools

def to_ranges(iterable):
    iterable = sorted(set(iterable))
    for key, group in itertools.groupby(enumerate(iterable),
                                        lambda t: t[1] - t[0]):
        group = list(group)
        yield group[0][1], group[-1][1]
</code>```

Example:

```<code>>>> x
[44, 45, 2, 56, 23, 11, 3, 4, 7, 9, 1, 2, 2, 11, 12, 13, 45]

>>> print( list(to_ranges(x)))
[(1, 4), (7, 7), (9, 9), (11, 13), (23, 23), (44, 45), (56, 56)]
</code>```

Body:
This is an improvement over the very elegant answer. This one covers non-unique and non-sorted input and is python3 compatible too:

import itertools

def to_ranges(iterable):
    iterable = sorted(set(iterable))
    for key, group in itertools.groupby(enumerate(iterable),
                                        lambda t: t[1] - t[0]):
        group = list(group)
        yield group[0][1], group[-1][1]

Example:

>>> x
[44, 45, 2, 56, 23, 11, 3, 4, 7, 9, 1, 2, 2, 11, 12, 13, 45]

>>> print( list(to_ranges(x)))
[(1, 4), (7, 7), (9, 9), (11, 13), (23, 23), (44, 45), (56, 56)]


问:
docker - Restrictions regarding naming image
I have questions regarding restrictions about naming images. I search online and saw different issue and answers.

which special characters are not allowed in docker image name? (e.g. '*', '$', ',', '_' ...)
Is it possible to use uppercase char for image name?

答:
From https://github.com/docker/distribution/blob/master/reference/regexp.go:

// nameComponentRegexp restricts registry path component names to start

  // with at least one letter or number, with following parts able to be

  // separated by one period, one or two underscore and multiple dashes.

This applies to the image name itself.

The regex for the letters is all lower case, no upper case letters.

You can include a hostname and an optional port number after a colon at the very beginning.

You can include a path between the hostname and image name with slashes /, and each element of the path has the same restrictions as the image name itself.

After the image name, you can append a tag after a colon or a digest after an @.

Expressed with the common bracketed notation:

```<code>[somehost.com[:1234]][/some-path/to/the]image-name[:myTag1.2.3]
[somehost.com[:1234]][/some-path/to/the]image-name[@ca468b84b84846e84...]
</code>```

Body:
From https://github.com/docker/distribution/blob/master/reference/regexp.go:

// nameComponentRegexp restricts registry path component names to start

  // with at least one letter or number, with following parts able to be

  // separated by one period, one or two underscore and multiple dashes.

This applies to the image name itself.

The regex for the letters is all lower case, no upper case letters.

You can include a hostname and an optional port number after a colon at the very beginning.

You can include a path between the hostname and image name with slashes /, and each element of the path has the same restrictions as the image name itself.

After the image name, you can append a tag after a colon or a digest after an @.

Expressed with the common bracketed notation:

[somehost.com[:1234]][/some-path/to/the]image-name[:myTag1.2.3]
[somehost.com[:1234]][/some-path/to/the]image-name[@ca468b84b84846e84...]


问:
Loading app taking too long
I've build an small/simple app with ionic 2.
But when I try open  it on my phone it takes more than 10 seconds to load.

I don't know if this is an ionic2  issue for or has something to do with my code.

I tried using   enableProdMode(); but I get the same result: 10 second for loading.

my main.ts

```<code>{
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { AppModule } from './app.module';
    import {enableProdMode} from '@angular/core';
    enableProdMode();

    platformBrowserDynamic().bootstrapModule(AppModule);
}
</code>```

My technologies:

```<code>Cordova CLI: 6.4.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.1.4
</code>```

Is there a way to lower the loading time for my app?

Thanks in advance.

答: Did you built it like that: ionic build android --prod --release (or whatever platform you are using)? This should produce the best results.

Title: Loading app taking too long

Body:
I've build an small/simple app with ionic 2.
But when I try open  it on my phone it takes more than 10 seconds to load.

I don't know if this is an ionic2  issue for or has something to do with my code.

I tried using   enableProdMode(); but I get the same result: 10 second for loading.

my main.ts

{
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { AppModule } from './app.module';
    import {enableProdMode} from '@angular/core';
    enableProdMode();

    platformBrowserDynamic().bootstrapModule(AppModule);
}

My technologies:

Cordova CLI: 6.4.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.1.4

Is there a way to lower the loading time for my app?

Thanks in advance.


问:
How to get data from database to view page in laravel?
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

```<code><div class="table-responsive">
  <table class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th><strong>No</strong></th>
        <th><strong>Nama Petani</strong></th>
        <th><strong>Alamat</strong></th>
        <th><strong>No. Handphone</strong></th>
        <th><strong>Lokasi</strong></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </tbody>
  </table>
</div>
</code>```

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

```<code>Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});
</code>```

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

答:
**In side controller you pass this **:

```<code>$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));
</code>```

and Inside view you use petanidetail variable as follow:

```<code>foreach($petanidetail as $data)
{
echo $data;
}
</code>```

Body:
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

        No
        Nama Petani
        Alamat
        No. Handphone
        Lokasi

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

Body:
**In side controller you pass this **:

$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));

and Inside view you use petanidetail variable as follow:

foreach($petanidetail as $data)
{
echo $data;
}


问:
Swift App elements not loading in time from storyBoard
I'm running in to an issue where I have a home controller which checks if the user is logged in and the presents a login controller if this fails. The problem I'm facing is occasionally the elements and their attached classes from storyBoard failed to load in time. As mentioned this is occasional behaviour. Is this normal or will I have to have a delay function before hand to wait a second before presenting the login controller?

This is happening on device testing, not simulator. If I touch the screen the elements are shown. Weird behaviour

答: It is better to use AppDelegate to to check log in like task and redirect from there</p>


问:
Best practice for implementing frontend using laravel and vue
I'm developing a large scale application base on Laravel 5.4. I'm wondering what is the best practice for implementing fronend for large scale application? Implementing on laravel blade for all styling and html rendering and using vue for interactivity or using blade to call vue components and implementing all stuff is vue? Let's see some examples:

This is first approach:

In laravel blade:

```<code>@extends('layout')
@section('content')
  <customer-search></customer-search>
  <customer-table></customer-table>
@endsection
</code>```

then customer-search component would be:

```<code><template>
  <div>
    <form action="/customer" method="GET">
      <input type="text" name="name" @input="updateValue($event.target.value)" :value="name" />
      <submit @click="search">Search</button>
    </form>
  </div>
</template>
<script>
  export default {
    data: function () {
      return {
        name: '',
      }
    },
    methods: {
      search() {
        // Get data from server, update related data model for using in customer table, ...
      }
    }
  }
</script>
</code>```

and customer-table component:

```<code><template>
  <div>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Access</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="customer in customers">
          <td>{{ customer.name }}</td>
          <td><a href="#">Link</a></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
  export default {

  }
</script>
</code>```

Second approach:
blade:

```<code>@extends('layout')
@section('content')
  <customer-index>
    <form action="/customer" method="GET">
      <input type="text" name="name" @input="updateValue($event.target.value)" :value="name" />
      <submit @click="search">Search</button>
    </form>

    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Access</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="customer in customers">
          <td>{{ customer.name }}</td>
          <td><a href="#">Link</a></td>
        </tr>
      </tbody>
    </table>
  </customer-index>
@endsection
</code>```

and customer-index component:

```<code><tempalte>
  <div>
    <slot></slot>
  </div>
</template>
<script>
  export default {
    data: function () {
      return {
        name: '',
      }
    },
    methods: {
      search() {
        // Get data from server, update related data model for using in customer table, ...
      },
      // Other methods, ...
    }
  }
</script>
</code>```

Third possibility:
Third possibility is try to using second approach and go more in depth on components. For example using a component for tables, a component for forms, a component for inputs, a component for buttons, ...
Which one should i use to avid spending much time in fronend and also have a integrated frontend?

答:
Vue components should always be loosely coupled so they can be reused in other places and even in other projects.

You should use the minimal amount of markup possible in your vue components, so that they are portable and can be reused without requiring you to edit them.

Obviously this is an opinion based question, but the above is, in my opinion at least, best practice.

Body:
I'm developing a large scale application base on Laravel 5.4. I'm wondering what is the best practice for implementing fronend for large scale application? Implementing on laravel blade for all styling and html rendering and using vue for interactivity or using blade to call vue components and implementing all stuff is vue? Let's see some examples:

This is first approach:

In laravel blade:

@extends('layout')
@section('content')
  <customer-search></customer-search>
  <customer-table></customer-table>
@endsection

then customer-search component would be:

<template>

    <form action="/customer" method="GET">
      <input type="text" name="name" @input="updateValue($event.target.value)" :value="name" />
      <submit @click="search">Search</button>
    </form>

</template>

and customer-table component:

<template>

          Name
          Access

          {{ customer.name }}
          Link

</template>

Second approach:
blade:

@extends('layout')
@section('content')
  <customer-index>
    <form action="/customer" method="GET">
      <input type="text" name="name" @input="updateValue($event.target.value)" :value="name" />
      <submit @click="search">Search</button>
    </form>

          Name
          Access

          {{ customer.name }}
          Link

  </customer-index>
@endsection

and customer-index component:

<tempalte>

    <slot></slot>

</template>

Third possibility:
Third possibility is try to using second approach and go more in depth on components. For example using a component for tables, a component for forms, a component for inputs, a component for buttons, ...
Which one should i use to avid spending much time in fronend and also have a integrated frontend?


问:
CSS: Can I use the classes of nested elements to narrow css down?
Here is an example of what I have:

```<code><div class="node node-blog">
  <div class="field-item even">
    <img src="image.png"/>
  </div>
</div>
</code>```

What I would like to do is apply a style to the img element only when inside the node-blog and field-item divs, but this does not work:

```<code>.node-blog .field-item img {float:right;}
</code>```

Sure I am doing something wrong.

Thanks.

答:
Provided style's fine

Unless you have other errors in your CSS file, this line seems correct. It's most probably something very stupid. Maybe some typo in your actual code if you haven't actually copy-pasted it here...

As long as your img is contained within a subtree of .field-item that is in a subtree of .node-blog this should work. You don't have to provide the whole path.

Other rule overrides yours

Unless you have a different rule on img that sets float to it. CSS style of it

Must be more specific to the one provided to override yours.

Is less specific but sets float setting as !important.

Body:
Here is an example of what I have:

What I would like to do is apply a style to the img element only when inside the node-blog and field-item divs, but this does not work:

.node-blog .field-item img {float:right;}

Sure I am doing something wrong.

Thanks.


问:
How to get front camera, back camera and audio with AVCaptureDeviceDiscoverySession
Before iOS 10 came out I was using the following code to get the video and audio capture for my video recorder:

```<code> for device in AVCaptureDevice.devices()
 {
     if (device as AnyObject).hasMediaType( AVMediaTypeAudio )
     {
         self.audioCapture = device as? AVCaptureDevice
     }
     else if (device as AnyObject).hasMediaType( AVMediaTypeVideo )
     {
         if (device as AnyObject).position == AVCaptureDevicePosition.back
         {
             self.backCameraVideoCapture = device as? AVCaptureDevice
         }
         else
         {
             self.frontCameraVideoCapture = device as? AVCaptureDevice
         }
     }
 }
</code>```

When iOS 10 finally came out, I received the following warning when I was running my code. Note that my video recorder was still working smoothly for about 2 weeks.

'devices()' was deprecated in iOS 10.0: Use AVCaptureDeviceDiscoverySession instead.

As I was running my code this morning, my video recorder stopped working. xCode8 does not give me any errors but the previewLayer for the camera capture is completely white. When I then start recording I receive the following error:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x17554440 {Error Domain=NSOSStatusErrorDomain Code=-12780 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12780)}

I believe that has something to do with the fact that I am using the deprecated approach AVCaptureDevice.devices(). Hence, I was wondering how to use AVCaptureDeviceDiscoverySession instead?

Thank you for your help in advance!

答:
Try below code to get camera ID:</p>

```<code>NSString *cameraID = nil;

NSArray *captureDeviceType = @[AVCaptureDeviceTypeBuiltInWideAngleCamera];
AVCaptureDeviceDiscoverySession *captureDevice =
              [AVCaptureDeviceDiscoverySession
                discoverySessionWithDeviceTypes:captureDeviceType
                mediaType:AVMediaTypeVideo
                position:AVCaptureDevicePositionUnspecified];

cameraID = [captureDevice.devices.lastObject localizedName];
</code>```

Body:
Before iOS 10 came out I was using the following code to get the video and audio capture for my video recorder:

 for device in AVCaptureDevice.devices()
 {
     if (device as AnyObject).hasMediaType( AVMediaTypeAudio )
     {
         self.audioCapture = device as? AVCaptureDevice
     }
     else if (device as AnyObject).hasMediaType( AVMediaTypeVideo )
     {
         if (device as AnyObject).position == AVCaptureDevicePosition.back
         {
             self.backCameraVideoCapture = device as? AVCaptureDevice
         }
         else
         {
             self.frontCameraVideoCapture = device as? AVCaptureDevice
         }
     }
 }

When iOS 10 finally came out, I received the following warning when I was running my code. Note that my video recorder was still working smoothly for about 2 weeks.

'devices()' was deprecated in iOS 10.0: Use AVCaptureDeviceDiscoverySession instead.

As I was running my code this morning, my video recorder stopped working. xCode8 does not give me any errors but the previewLayer for the camera capture is completely white. When I then start recording I receive the following error:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x17554440 {Error Domain=NSOSStatusErrorDomain Code=-12780 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12780)}

I believe that has something to do with the fact that I am using the deprecated approach AVCaptureDevice.devices(). Hence, I was wondering how to use AVCaptureDeviceDiscoverySession instead?

Thank you for your help in advance!

Body:
Try below code to get camera ID:

NSString *cameraID = nil;

NSArray *captureDeviceType = @[AVCaptureDeviceTypeBuiltInWideAngleCamera];
AVCaptureDeviceDiscoverySession *captureDevice =
              [AVCaptureDeviceDiscoverySession
                discoverySessionWithDeviceTypes:captureDeviceType
                mediaType:AVMediaTypeVideo
                position:AVCaptureDevicePositionUnspecified];

cameraID = [captureDevice.devices.lastObject localizedName];


问:
regex for comma separated dates in php
I have a problem to set regular expression for multiple dates with comma separator.
I have dates like as :

```<code>2017-03-25, 2017-03-27, 2017-03-28
</code>```

please help me guys.....

i am trying to set php validation for selecting multi dates (jquery calender).

my regex is :

```<code>$value = "2017-03-25, 2017-03-27, 2017-03-28";
preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])([0-9])*$/",$value)
</code>```

答:
You are matching only a single date with 0+ digits after it with your regex.

You may use the following fix:

```<code>^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$
</code>```

See the regex demo

Details:

^ - start of string

([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])) - Group 1 matching and capturing a date-like substring

(?:,\s*(?1))* - zero or more sequences of:

,  - comma

\s* - 0+ whitespaces (remove * to only match one, or use ? to match 1 or 0 whitespaces)

(?1) - recurse Group 1 subpattern

$ - end of string.

Title: regex for comma separated dates in php

Body:
I have a problem to set regular expression for multiple dates with comma separator.
I have dates like as :

2017-03-25, 2017-03-27, 2017-03-28

please help me guys.....

i am trying to set php validation for selecting multi dates (jquery calender).

my regex is :

$value = "2017-03-25, 2017-03-27, 2017-03-28";
preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])([0-9])*$/",$value)

Body:
You are matching only a single date with 0+ digits after it with your regex.

You may use the following fix:

^([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]))(?:,\s*(?1))*$

See the regex demo

Details:

^ - start of string

([0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])) - Group 1 matching and capturing a date-like substring

(?:,\s*(?1))* - zero or more sequences of:

,  - comma

\s* - 0+ whitespaces (remove * to only match one, or use ? to match 1 or 0 whitespaces)

(?1) - recurse Group 1 subpattern

$ - end of string.


问:
Div ScrollLeft or Right on each click Jquery
How to scroll a div left or right on each click by 30px?
Pls help

```<code>$(document).ready(function(){
    $("button").click(function(){
        $("div").scrollLeft(30);
    });
});
</code>```

http://jsfiddle.net/stfzy/1835/

答:
First of you will need to get the current position of scroll.
use $("div").scrollLeft() for getting current position from left. and add 30 into it each time you click on button.

```<code>$(document).ready(function(){
  $("button").click(function(){
    let pos = parseFloat($("div").scrollLeft()) + 30;
    $("div").scrollLeft(pos);
  });
});
</code>```

Body:
How to scroll a div left or right on each click by 30px?
Pls help

$(document).ready(function(){
    $("button").click(function(){
        $("div").scrollLeft(30);
    });
});

http://jsfiddle.net/stfzy/1835/

Body:
First of you will need to get the current position of scroll.
use $("div").scrollLeft() for getting current position from left. and add 30 into it each time you click on button.

$(document).ready(function(){
  $("button").click(function(){
    let pos = parseFloat($("div").scrollLeft()) + 30;
    $("div").scrollLeft(pos);
  });
});


问:
How to scan a column for a certain word and when triggered, remove the first 4 characters
Hey everyone so here is my setup

My issue is regarding the "C" column and how to remove the "2nd|" and "3rd|" portions so it ONLY shows "Mikes Auto Shop" "Carls Auto Repair" etc

Like this

答:
Just a formula in D2 will do the trick

```<code>=RIGHT(C2,LEN(C2)-4)
</code>```

Body:
Just a formula in D2 will do the trick

=RIGHT(C2,LEN(C2)-4)


问:
white space in filename python 3.4.2
I have created this small prog to search all PDF's in a directory, determine if they are searchable or not and then move them to the appropriate directory.

I am new to Python and it is probably not the best way but it does work until the file name has White Space in it and I get the following returned.

Any help would be appreciated.

```<code>>>> os.system("pdffonts.exe " + pdfFile + "> output.txt")
99

import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory
numFiles = len(fileDir) # Lenght of list
startFile = 0 # Counter variable
seekWord = "TrueType"
while startFile < numFiles:
    pdfFile=fileDir[startFile]
    os.system("pdffonts.exe " + pdfFile + "> output.txt")
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else: shutil.move(pdfFile, "OCR")
    startFile = startFile + 1
</code>```

答:
It seems the problem doesn't come from python, but the Windows shell. You need to enclose in quotation mark. As I don't have your program pdffonts.exe, I cannot debug. I also made your code more pythonic</p>

```<code>import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory

seekWord = "TrueType"
for pdfFile in fileDir:
    os.system('pdffonts.exe "{0}"> output.txt'.format(pdfFile))
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else:
        shutil.move(pdfFile, "OCR")
</code>```

Title: white space in filename python 3.4.2

Body:
I have created this small prog to search all PDF's in a directory, determine if they are searchable or not and then move them to the appropriate directory.

I am new to Python and it is probably not the best way but it does work until the file name has White Space in it and I get the following returned.

Any help would be appreciated.

>>> os.system("pdffonts.exe " + pdfFile + "> output.txt")
99

import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory
numFiles = len(fileDir) # Lenght of list
startFile = 0 # Counter variable
seekWord = "TrueType"
while startFile < numFiles:
    pdfFile=fileDir[startFile]
    os.system("pdffonts.exe " + pdfFile + "> output.txt")
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else: shutil.move(pdfFile, "OCR")
    startFile = startFile + 1

Body:
It seems the problem doesn't come from python, but the Windows shell. You need to enclose in quotation mark. As I don't have your program pdffonts.exe, I cannot debug. I also made your code more pythonic

import os
import glob
import shutil
directory = os.chdir("C:\MyDir") # Change working directory
fileDir = glob.glob('*.pdf') # Create a list of all PDF's in declared   directory

seekWord = "TrueType"
for pdfFile in fileDir:
    os.system('pdffonts.exe "{0}"> output.txt'.format(pdfFile))
    file1output = open("output.txt","r")
    fileContent = file1output.read()
    if seekWord in fileContent:
        shutil.move(pdfFile , "NO_OCR")
    else:
        shutil.move(pdfFile, "OCR")


问:
Cocoa Touch: What to release, when to release it?
I'm trying hard to understand when and what I must relase in Cocoa Touch as it doesn't have garbage collection.

This code block is from apples iphone sample PeriodicElements and they release anElement and rawElementArray but not thePath, firstLetter, existingArray and tempArray?

I would have thought that at least tempArray and existingArray should be released.

Could some brainy person please explain to me why?

Thanks :)

```<code>- (void)setupElementsArray {
NSDictionary *eachElement;

// create dictionaries that contain the arrays of element data indexed by
// name
self.elementsDictionary = [NSMutableDictionary dictionary];
// physical state
self.statesDictionary = [NSMutableDictionary dictionary];
// unique first characters (for the Name index table)
self.nameIndexesDictionary = [NSMutableDictionary dictionary];

// create empty array entries in the states Dictionary or each physical state
[statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"];

// read the element data from the plist
NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Elements" ofType:@"plist"];
NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];

// iterate over the values in the raw elements dictionary
for (eachElement in rawElementsArray)
{
    // create an atomic element instance for each
    AtomicElement *anElement = [[AtomicElement alloc] initWithDictionary:eachElement];

    // store that item in the elements dictionary with the name as the key
    [elementsDictionary setObject:anElement forKey:anElement.name];

    // add that element to the appropriate array in the physical state dictionary
    [[statesDictionary objectForKey:anElement.state] addObject:anElement];

    // get the element's initial letter
    NSString *firstLetter = [anElement.name substringToIndex:1];
    NSMutableArray *existingArray;

    // if an array already exists in the name index dictionary
    // simply add the element to it, otherwise create an array
    // and add it to the name index dictionary with the letter as the key
    if (existingArray = [nameIndexesDictionary valueForKey:firstLetter])
    {
    [existingArray addObject:anElement];
    } else {
        NSMutableArray *tempArray = [NSMutableArray array];
        [nameIndexesDictionary setObject:tempArray forKey:firstLetter];
        [tempArray addObject:anElement];
    }

    // release the element, it is held by the various collections
    [anElement release];

}
// release the raw element data
[rawElementsArray release];

// create the dictionary containing the possible element states
// and presort the states data
self.elementPhysicalStatesArray = [NSArray arrayWithObjects:@"Solid",@"Liquid",@"Gas",@"Artificial",nil];
[self presortElementsByPhysicalState];

// presort the dictionaries now
// this could be done the first time they are requested instead

[self presortElementInitialLetterIndexes];

self.elementsSortedByNumber = [self presortElementsByNumber];
self.elementsSortedBySymbol = [self presortElementsBySymbol];
</code>```

}

答:
The convention is that when you create an object using a class method it should have been autoreleased. This means that at the end of the run loop when the autorelease pool is flushed these objects will be released. However, if you create something using +alloc] -init] or -copy, -mutableCopy or +new (which is the same as +alloc] -init]) then it will not have been autoreleased.

For example:

```<code>NSArray *array1 = [NSArray arrayWithObject:@"foo"];
NSArray *array2 = [[NSArray alloc] initWithObject:@"foo"];
</code>```

Array1 will be autoreleased and you don't need to worry about it. Array2 will need to be manually released. Or alternatively you could do:

```<code>NSArray *array2 = [[[NSArray alloc] initWithObject:@"foo"] autorelease];
</code>```

Which is pretty much what +arrayWithObject: does.

Of course this leads to an important consideration with the lifetime of instance variables. If you create the instance variable as with array2 then it will be fine as it has a retain count of 1. However, array1 will need to be retained otherwise it will be autoreleased at the end of the runloop, giving it a retain count of 0 and so it will be freed and you will be left with a dangling pointer.

OwnerDisplayName: BJ McKay

Body:
I'm trying hard to understand when and what I must relase in Cocoa Touch as it doesn't have garbage collection.

This code block is from apples iphone sample PeriodicElements and they release anElement and rawElementArray but not thePath, firstLetter, existingArray and tempArray?

I would have thought that at least tempArray and existingArray should be released.

Could some brainy person please explain to me why?

Thanks :)

- (void)setupElementsArray {
NSDictionary *eachElement;

// create dictionaries that contain the arrays of element data indexed by
// name
self.elementsDictionary = [NSMutableDictionary dictionary];
// physical state
self.statesDictionary = [NSMutableDictionary dictionary];
// unique first characters (for the Name index table)
self.nameIndexesDictionary = [NSMutableDictionary dictionary];

// create empty array entries in the states Dictionary or each physical state
[statesDictionary setObject:[NSMutableArray array] forKey:@"Solid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Liquid"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Gas"];
[statesDictionary setObject:[NSMutableArray array] forKey:@"Artificial"];

// read the element data from the plist
NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Elements" ofType:@"plist"];
NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];

// iterate over the values in the raw elements dictionary
for (eachElement in rawElementsArray)
{
    // create an atomic element instance for each
    AtomicElement *anElement = [[AtomicElement alloc] initWithDictionary:eachElement];

    // store that item in the elements dictionary with the name as the key
    [elementsDictionary setObject:anElement forKey:anElement.name];

    // add that element to the appropriate array in the physical state dictionary
    [[statesDictionary objectForKey:anElement.state] addObject:anElement];

    // get the element's initial letter
    NSString *firstLetter = [anElement.name substringToIndex:1];
    NSMutableArray *existingArray;

    // if an array already exists in the name index dictionary
    // simply add the element to it, otherwise create an array
    // and add it to the name index dictionary with the letter as the key
    if (existingArray = [nameIndexesDictionary valueForKey:firstLetter])
    {
    [existingArray addObject:anElement];
    } else {
        NSMutableArray *tempArray = [NSMutableArray array];
        [nameIndexesDictionary setObject:tempArray forKey:firstLetter];
        [tempArray addObject:anElement];
    }

    // release the element, it is held by the various collections
    [anElement release];

}
// release the raw element data
[rawElementsArray release];

// create the dictionary containing the possible element states
// and presort the states data
self.elementPhysicalStatesArray = [NSArray arrayWithObjects:@"Solid",@"Liquid",@"Gas",@"Artificial",nil];
[self presortElementsByPhysicalState];

// presort the dictionaries now
// this could be done the first time they are requested instead

[self presortElementInitialLetterIndexes];

self.elementsSortedByNumber = [self presortElementsByNumber];
self.elementsSortedBySymbol = [self presortElementsBySymbol];

}

Body:
The convention is that when you create an object using a class method it should have been autoreleased. This means that at the end of the run loop when the autorelease pool is flushed these objects will be released. However, if you create something using +alloc] -init] or -copy, -mutableCopy or +new (which is the same as +alloc] -init]) then it will not have been autoreleased.

For example:

NSArray *array1 = [NSArray arrayWithObject:@"foo"];
NSArray *array2 = [[NSArray alloc] initWithObject:@"foo"];

Array1 will be autoreleased and you don't need to worry about it. Array2 will need to be manually released. Or alternatively you could do:

NSArray *array2 = [[[NSArray alloc] initWithObject:@"foo"] autorelease];

Which is pretty much what +arrayWithObject: does.

Of course this leads to an important consideration with the lifetime of instance variables. If you create the instance variable as with array2 then it will be fine as it has a retain count of 1. However, array1 will need to be retained otherwise it will be autoreleased at the end of the runloop, giving it a retain count of 0 and so it will be freed and you will be left with a dangling pointer.

OwnerDisplayName: Martin Pilkington


问:
Are the decimal places in a CSS width respected?
Something I've been wondering for a while whilst doing CSS design.

Are decimal places in CSS widths respected? Or are they rounded?

.percentage {
  width: 49.5%;
}
```
<p>or</p>
<pre class="lang-css prettyprint-override"><code>.pixel {
  width: 122.5px;
}
</code>```

答:
Even when the number is rounded when the page is painted, the full value is preserved in memory and used for subsequent child calculation. For example, if your box of 100.4999px paints to 100px, it's child with a width of 50% will be calculated as .5*100.4999 instead of .5*100. And so on to deeper levels.

I've created deeply nested grid layout systems where parents widths are ems, and children are percents, and including up to four decimal points upstream had a noticeable impact.

Edge case, sure, but something to keep in mind.

Body:
Something I've been wondering for a while whilst doing CSS design.

Are decimal places in CSS widths respected? Or are they rounded?

.percentage {
  width: 49.5%;
}

or

.pixel {
  width: 122.5px;
}


问:
xcode 8.3 Could not launch application process launch failed: unspecified
I have new installed Xcode 8.3 with iOS 10.3.

My application ran on iOS as expected and suddenly Xcode fails to run application on device with error:

Could not launch "My app" process launch failed: unspecified

It runs on Simulators and on other device mini-pad (10.2)

答:
I tried plugging out-in the cable of iOS - doesn't help

I restarted iOS device and Xcode - everything works as expected

(hope it will help to someone)


问:
How do I install this package on a Linux (Centos) machine?
I found this package on GitHub (doctotext). I'd like to install it on my Centos-running dedicated server (x86_64), but I do not know how. Could someone offer instructions as to how I could do it. There are no instructions provided, unfortunately</p>

答:
If you are open to considering alternatives, which are actively maintained, I recommend

PDFMiner http://www.unixuser.org/~euske/python/pdfminer/index.html

It includes pdf2txt.py which may be a good solution for you.

If you are looking for other options or additional formats browse

https://pypi.org/search/?q=documents

I'm sure you'll find something.


问:
SQL Server: many-to-many relation
So I am having a brain meltdown when trying to figure this one out. What I have is a few database's like:

tblGenre

```<code>genreID
genreName
</code>```

tblArtist

```<code>artistID
artistName
genreID
</code>```

tblAlbum

```<code>albumID
albumName
artistID
</code>```

Everything is all well and good, and working fine. Ok, now with the question...

What I am trying to figure out is how to link an artist who has multiple names. I.e. the artist 'Prince'. I have albums from him, who I would catalog under 3 different bands; Prince (artistID=5), Prince and the new power generation (artistID=17, and "Symbol" (artistID=43)...

So, When I lookup the artist "Prince", who has a artistID of 5, how can I link the other 2 bands up to this one? Would I create a seperate database the has a comma-separated values of each artistID (i.e. 5,17,43) or is there an easier way to do this?

I don't want to go as far as the album level, of who played on every album in my database. I just want to create a link of artists who have been with multiple bands. Just a few more examples of how I would want "hooked together"...

Tom Petty (Classic Rock)

Tom Petty & the Heartbreakers (Classic Rock)

Tom Petty & the Heartbreakers (Soundtrack)

Prince (Funk)

Prince & the New Power Generation (Funk)

Mark Knopfler (Classic Rock)

Mark Knopfler (Soundtrack)

Dire Straits (Classic Rock)

Thanks for the input.

答:
You have two choices:

1) ARTISTS table and ARTISTS_ALIASES table, where artistid is a foreign key  in the ARTISTS_ALIASES table, and you would have an artist_aliasid in your ALBUM table, so you'd know under what name the artist appeared on that album; or

2) a single ARTISTS using recursion (like EMPLOYEE BOSS table):

```<code>                artistid
                artistname
                primaryartistid  (references artistid in this table
</code>```

When artistid and primaryartistid are the same, you treat that row as the "base" artist.

Title: SQL Server: many-to-many relation

Body:
So I am having a brain meltdown when trying to figure this one out. What I have is a few database's like:

tblGenre

genreID
genreName

tblArtist

artistID
artistName
genreID

tblAlbum

albumID
albumName
artistID

Everything is all well and good, and working fine. Ok, now with the question...

What I am trying to figure out is how to link an artist who has multiple names. I.e. the artist 'Prince'. I have albums from him, who I would catalog under 3 different bands; Prince (artistID=5), Prince and the new power generation (artistID=17, and "Symbol" (artistID=43)...

So, When I lookup the artist "Prince", who has a artistID of 5, how can I link the other 2 bands up to this one? Would I create a seperate database the has a comma-separated values of each artistID (i.e. 5,17,43) or is there an easier way to do this?

I don't want to go as far as the album level, of who played on every album in my database. I just want to create a link of artists who have been with multiple bands. Just a few more examples of how I would want "hooked together"...

Tom Petty (Classic Rock)

Tom Petty & the Heartbreakers (Classic Rock)

Tom Petty & the Heartbreakers (Soundtrack)

Prince (Funk)

Prince & the New Power Generation (Funk)

Mark Knopfler (Classic Rock)

Mark Knopfler (Soundtrack)

Dire Straits (Classic Rock)

Thanks for the input.

Body:
You have two choices:

1) ARTISTS table and ARTISTS_ALIASES table, where artistid is a foreign key  in the ARTISTS_ALIASES table, and you would have an artist_aliasid in your ALBUM table, so you'd know under what name the artist appeared on that album; or

2) a single ARTISTS using recursion (like EMPLOYEE BOSS table):

                artistid
                artistname
                primaryartistid  (references artistid in this table

When artistid and primaryartistid are the same, you treat that row as the "base" artist.


问:
Cast Enumeration Value to Integer in Delphi
Is it possible to cast/convert an Enumeration Value to Integer in Delphi?

If yes, then how?

答:
I see David has posted you a good answer while I was writing this, but I'll post it anyway:</p>

```<code>program enums;
{$APPTYPE CONSOLE}
uses
  SysUtils, typinfo;
type
  TMyEnum = (One, Two, Three);
var
  MyEnum : TMyEnum;
begin
  MyEnum := Two;
  writeln(Ord(MyEnum));  // writes 1, because first element in enumeration is numbered zero

  MyEnum := TMyEnum(2);  // Use TMyEnum as if it were a function
  Writeln (GetEnumName(TypeInfo(TMyEnum), Ord(MyEnum)));  //  Use RTTI to return the enum value's name
  readln;
end.
</code>```

Body:
I see David has posted you a good answer while I was writing this, but I'll post it anyway:

program enums;
{$APPTYPE CONSOLE}
uses
  SysUtils, typinfo;
type
  TMyEnum = (One, Two, Three);
var
  MyEnum : TMyEnum;
begin
  MyEnum := Two;
  writeln(Ord(MyEnum));  // writes 1, because first element in enumeration is numbered zero

  MyEnum := TMyEnum(2);  // Use TMyEnum as if it were a function
  Writeln (GetEnumName(TypeInfo(TMyEnum), Ord(MyEnum)));  //  Use RTTI to return the enum value's name
  readln;
end.


问:
Firebase Android : How to get list inside specific child?
I'm trying to retrieve inner list of specific child. Please refer following structure.

If I want to retrieve "servicesArrayList" for "recipient" where "billNo" is "135", What query I should be writing so that I can pass that query to FirebaseRecyclerAdapter (firebase -ui)

FirebaseRecyclerAdapter is for servicesArrayList for specific recipient.

```<code>    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String uid = user.getUid();

    Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid)
            .child("servicesArrayList")
            .orderByChild ?

recipient // parent Node

 2R1Q8qKEPHXFU1OiMq5TyxHBaZa2 // uId

   -KgJhMAWADwownv5tck6  // push Id
   -KgJhMAWADwownv5tck6
   -KgJoD77HQK-yACD_EuB
   -KgJoRXVUP_-Z0gLhIWy
   -KgJob82t47PvTjfTtig
   -KgK-N_Av_2kmmQS0Ulx

   -KgNu-fVWwFDLnRENj_b // Recipient Data
        billNo: 135
        billingMonth: "July 2017"
        childGender: "Ms."
        childName: "xyz"
        date: "29/03/2017"
        fineAmount: 0
        paymentStatus: "UNPAID"
        pushId: "-KgNu-fVWwFDLnRENj_b"
        receiptUrl:"https://firebasestorage.googleapis.com/v0/b/ngf..."
        recipientEmail: "abc@gmail.com"
        recipientName: "Abc C."
        servicesArrayList
                 -0
                    -amount: 1000
                    -charges: "1000"
                    -noOfSessions: 1
                    -serviceType: "Speech And Language Assessment"

        total: 1000
        vat: 0
</code>```

答:
TRY this:</p>

```<code>     Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid).orderByChild("billNo").equalTo(135);
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      Query query1= dataSnapshot.getRef().child("servicesArrayList");
       //pass this query to adapter of firebaseRecyclerAdapter
     FirebaseRecyclerAdapter  adapter = new FirebaseRecyclerAdapter<>(,,,query1){}
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        // ...
    }
});
</code>```

Body:
I'm trying to retrieve inner list of specific child. Please refer following structure.

If I want to retrieve "servicesArrayList" for "recipient" where "billNo" is "135", What query I should be writing so that I can pass that query to FirebaseRecyclerAdapter (firebase -ui)

FirebaseRecyclerAdapter is for servicesArrayList for specific recipient.

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String uid = user.getUid();

    Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid)
            .child("servicesArrayList")
            .orderByChild ?

recipient // parent Node

 2R1Q8qKEPHXFU1OiMq5TyxHBaZa2 // uId

   -KgJhMAWADwownv5tck6  // push Id
   -KgJhMAWADwownv5tck6
   -KgJoD77HQK-yACD_EuB
   -KgJoRXVUP_-Z0gLhIWy
   -KgJob82t47PvTjfTtig
   -KgK-N_Av_2kmmQS0Ulx

   -KgNu-fVWwFDLnRENj_b // Recipient Data
        billNo: 135
        billingMonth: "July 2017"
        childGender: "Ms."
        childName: "xyz"
        date: "29/03/2017"
        fineAmount: 0
        paymentStatus: "UNPAID"
        pushId: "-KgNu-fVWwFDLnRENj_b"
        receiptUrl:"https://firebasestorage.googleapis.com/v0/b/ngf..."
        recipientEmail: "abc@gmail.com"
        recipientName: "Abc C."
        servicesArrayList
                 -0
                    -amount: 1000
                    -charges: "1000"
                    -noOfSessions: 1
                    -serviceType: "Speech And Language Assessment"

        total: 1000
        vat: 0

Body:
TRY this:

     Query query = FirebaseDatabase.getInstance()
            .getReference(RECIPIENT_NODE)
            .child(uid).orderByChild("billNo").equalTo(135);
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
      Query query1= dataSnapshot.getRef().child("servicesArrayList");
       //pass this query to adapter of firebaseRecyclerAdapter
     FirebaseRecyclerAdapter  adapter = new FirebaseRecyclerAdapter<>(,,,query1){}
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

        // ...
    }
});


问:
When the coder runs an error appears saying that it is "None Type" object has no attribute 'save'
When the coder runs, I get the following error message:

```<code>“None Type” object has no attribute 'save'
</code>```

The script is as follows:

```<code>#Image.blend(image1, image2, alpha)

from PIL import Image
import PIL
import matplotlib.pyplot as plt # single use of plt is commented out
import os.path
import PIL.ImageDraw

def get_images(directory=None):
    """ Returns PIL.Image objects for all the images in directory.

    If directory is not specified, uses current directory.
        Returns a 2-tuple containing
    a list with a  PIL.Image object for each image file in root_directory,     and
    a list with a string filename for each image file in root_directory
    """

    if directory == None:
        directory = os.getcwd() # Use working directory if unspecified

    word_images = [] # Initialize aggregaotrs
    pic_list = []
    picture= []
    words= []

    directory_list = os.listdir('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\Project') #     Get list of files
    for entry in directory_list:
        absolute_filename = os.path.join('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\Project', entry)
        #print(absolute_filename)
        try:
            image = PIL.Image.open(absolute_filename)
            picture += [entry] # i am creating diffrent files one that contains the names of the files and the other that is the pictures
            pic_list += [image]
        except IOError:
            pass

    directory_list2 = os.listdir('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\1.4.5 Images') # Get list of files
    for entry in directory_list2:
        absolute_filename2 = os.path.join('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\1.4.5 Images', entry)
        try:
            image = PIL.Image.open(absolute_filename2)
            words += [entry] # i am creating diffrent files one that contains the names of the files and the other that is the pictures
            word_images += [image]
        except IOError:
            pass # do nothing with errors tying to open non-images

    return word_images, pic_list, words, picture #returns 3 lists, word_list and pic_list are lists containing the pictures
        #words contains the file names of the list of pictures that are transparent, pictures is a list of the names of the other pictures

def make_poster(img1,img2):
    width, hight= img1.size
    img2.resize((width,hight))
    img1.convert('RGBA')
    img2.convert('RGBA')
    new_image= Image.blend(img1, img2.resize((width,hight)), alpha=.5)
    new_image.show()
    return new_image

def make_all_poster(directory=None ):
     if directory == None:
        directory = os.getcwd() # Use working directory if unspecified

    # Create a new directory 'modified'
     new_directory = os.path.join(directory, 'modified')
     try:
        os.mkdir(new_directory)
     except OSError:
        pass
     word_imgs, pict_imgs, word_filenames, picture_filenames = get_images()
          number=0
     logo_img = PIL.Image.open('aclu.jpg')
     logo_w, logo_h = logo_img.size
     for x in range(len(pict_imgs)):
        for y in range(len(word_imgs)):
        # Parse the filenamefor n in range(len(image_list)):
        # Parse the filename
            filename, filetype = picture_filenames[x].split('.')

            new_image= make_poster(pict_imgs[x], word_imgs[y])
            w,h = new_image.size

            new_image_filename = os.path.join(new_directory, filename + str(number)+ '.png')
            new_image.save(new_image_filename)
            number+=1
</code>```

The error stems from around where the new img is made. This is when the code stopped working and started returning an error. For some reason it does not take the new img as a value and will not save it, however if I take out that part and ask it to save new image there is no error.

The problem lies with when I paste the image ontop of new_image.

答:
It appears that

```<code>make_poster(pict_imgs[x], word_imgs[y])
</code>```

May return None. Which makes new_image set to None.

That is likely why you get

```<code>“None Type” object has no attribute 'save'
</code>```

When you do new_image.save(<...>)

Body:
When the coder runs, I get the following error message:

“None Type” object has no attribute 'save'

The script is as follows:

#Image.blend(image1, image2, alpha)

from PIL import Image
import PIL
import matplotlib.pyplot as plt # single use of plt is commented out
import os.path
import PIL.ImageDraw

def get_images(directory=None):
    """ Returns PIL.Image objects for all the images in directory.

    If directory is not specified, uses current directory.
        Returns a 2-tuple containing
    a list with a  PIL.Image object for each image file in root_directory,     and
    a list with a string filename for each image file in root_directory
    """

    if directory == None:
        directory = os.getcwd() # Use working directory if unspecified

    word_images = [] # Initialize aggregaotrs
    pic_list = []
    picture= []
    words= []

    directory_list = os.listdir('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\Project') #     Get list of files
    for entry in directory_list:
        absolute_filename = os.path.join('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\Project', entry)
        #print(absolute_filename)
        try:
            image = PIL.Image.open(absolute_filename)
            picture += [entry] # i am creating diffrent files one that contains the names of the files and the other that is the pictures
            pic_list += [image]
        except IOError:
            pass

    directory_list2 = os.listdir('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\1.4.5 Images') # Get list of files
    for entry in directory_list2:
        absolute_filename2 = os.path.join('C:\\Users\\claudiahurtado\\Documents\\Python Programs\\1.4.5 Images', entry)
        try:
            image = PIL.Image.open(absolute_filename2)
            words += [entry] # i am creating diffrent files one that contains the names of the files and the other that is the pictures
            word_images += [image]
        except IOError:
            pass # do nothing with errors tying to open non-images

    return word_images, pic_list, words, picture #returns 3 lists, word_list and pic_list are lists containing the pictures
        #words contains the file names of the list of pictures that are transparent, pictures is a list of the names of the other pictures

def make_poster(img1,img2):
    width, hight= img1.size
    img2.resize((width,hight))
    img1.convert('RGBA')
    img2.convert('RGBA')
    new_image= Image.blend(img1, img2.resize((width,hight)), alpha=.5)
    new_image.show()
    return new_image

def make_all_poster(directory=None ):
     if directory == None:
        directory = os.getcwd() # Use working directory if unspecified

    # Create a new directory 'modified'
     new_directory = os.path.join(directory, 'modified')
     try:
        os.mkdir(new_directory)
     except OSError:
        pass
     word_imgs, pict_imgs, word_filenames, picture_filenames = get_images()
          number=0
     logo_img = PIL.Image.open('aclu.jpg')
     logo_w, logo_h = logo_img.size
     for x in range(len(pict_imgs)):
        for y in range(len(word_imgs)):
        # Parse the filenamefor n in range(len(image_list)):
        # Parse the filename
            filename, filetype = picture_filenames[x].split('.')

            new_image= make_poster(pict_imgs[x], word_imgs[y])
            w,h = new_image.size

            new_image_filename = os.path.join(new_directory, filename + str(number)+ '.png')
            new_image.save(new_image_filename)
            number+=1

The error stems from around where the new img is made. This is when the code stopped working and started returning an error. For some reason it does not take the new img as a value and will not save it, however if I take out that part and ask it to save new image there is no error.

The problem lies with when I paste the image ontop of new_image.

Body:
It appears that

make_poster(pict_imgs[x], word_imgs[y])

May return None. Which makes new_image set to None.

That is likely why you get

“None Type” object has no attribute 'save'

When you do new_image.save(<...>)


问:
Interpolating nested values from a scope variable in a view
So I have the following view:

```<code><p type="text" disabled='true' class="form-control" >
  {{selected.timerange}}
</p>
</code>```

The value of $scope.selected.timerange is:

{"available":false,"schedule_start_at":"2015-03-13T00:30:00","schedule_end_at":"2015-03-13T01:00:00"}

This works fine, but when I use the following view:

```<code><p type="text" disabled='true' class="form-control">
  {{selected.timerange.schedule_start_at}}
</p>
</code>```

the interpolation does not happen.

I'm unable to figure out why. Any help please?

答:
Late to the party here but in case anyone else runs into this issue:

Try initializing your timerange variable in the constructor.

this.selected.timerange = {} if that doesn't work go one step deeper

this.selected.timerange.schedule_start_at = "" (keeping the init from above)

Not sure the philosophy behind this, but I guess it has something to do with observables and/or promises if thats how you're getting your variables ( that was the issue in my case at least )

Body:
So I have the following view:

  {{selected.timerange}}

The value of $scope.selected.timerange is:

{"available":false,"schedule_start_at":"2015-03-13T00:30:00","schedule_end_at":"2015-03-13T01:00:00"}

This works fine, but when I use the following view:

  {{selected.timerange.schedule_start_at}}

the interpolation does not happen.

I'm unable to figure out why. Any help please?


问:
Setting index.html as default page in asp.net core
How can I get asp.net core to serve an index.html file from inside my wwwroot?

The reason I want to do this is because I an developing an angular 4 app using the angular CLI and it takes care of the entire build process.  I have set it up to build into the wwwroot directory of my asp.net core project but asp.net core doesn't want to serve it.

At first I tried to return the html file through a controller.  I tried this route:

```<code>app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}");
    });
</code>```

And then in the controller I return the html file like this:

```<code>public IActionResult Index()
{
    var webRoot = _env.WebRootPath;
    var path = System.IO.Path.Combine(webRoot, "index.html");

    return File(path, "text/html");
}
</code>```

This didn't work.  It returned a 404 not found exception and gave the path but the path it gave was the correct path to the index.html file (I cut and pasted it into explorer and the file opened).

I am also declaring these in startup:

```<code>app.UseStaticFiles();
app.UseDefaultFiles();
</code>```

I then tried removing the default route.  Now I am able to get to the index.html file but only if I type the filename in, i.e.:

localhost:58420/index.html

If I try to access the root of the domain without the "index.html" specified I get a 404 error.

What is the proper way to reference the index.html as the default page?  I am guessing doing it from a controller is probably better because then it will be compatible with angular routing without rewrites.

答:
I needed to declare UseDefaultFiles() before UseStaticFiles().</p>

```<code>app.UseDefaultFiles();
app.UseStaticFiles();
</code>```

Body:
How can I get asp.net core to serve an index.html file from inside my wwwroot?

The reason I want to do this is because I an developing an angular 4 app using the angular CLI and it takes care of the entire build process.  I have set it up to build into the wwwroot directory of my asp.net core project but asp.net core doesn't want to serve it.

At first I tried to return the html file through a controller.  I tried this route:

app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}");
    });

And then in the controller I return the html file like this:

public IActionResult Index()
{
    var webRoot = _env.WebRootPath;
    var path = System.IO.Path.Combine(webRoot, "index.html");

    return File(path, "text/html");
}

This didn't work.  It returned a 404 not found exception and gave the path but the path it gave was the correct path to the index.html file (I cut and pasted it into explorer and the file opened).

I am also declaring these in startup:

app.UseStaticFiles();
app.UseDefaultFiles();

I then tried removing the default route.  Now I am able to get to the index.html file but only if I type the filename in, i.e.:

localhost:58420/index.html

If I try to access the root of the domain without the "index.html" specified I get a 404 error.

What is the proper way to reference the index.html as the default page?  I am guessing doing it from a controller is probably better because then it will be compatible with angular routing without rewrites.

Body:
I needed to declare UseDefaultFiles() before UseStaticFiles().

app.UseDefaultFiles();
app.UseStaticFiles();


问:
Using a BufferedOutputStream causes application to halt
I have this line of code in my server/client pair:

```<code>BufferedOutputStream out = new BufferedOutputStream (clientSocket.getOutputStream());
</code>```

It works fine, the code works well, then if I modify it to:

```<code>BufferedOutputStream out = new BufferedOutputStream (new BufferedOutputStream(clientSocket.getOutputStream()));
</code>```

The execution of the application will halt where outputs are sent. I really only made that modification and am very new to streams in this manner, especially sockets.

Is there any obvious error?

答:
Yes, this would be consistent with the behaviour of BufferedOutputStream, which as its name suggests will buffer output before sending it.

When you write objects to the ObjectOutputStream, the bytes will be passed along to the BufferedOutputStream, which will only send them on to the socket when its buffer fills up. So your objects will be "hanging around" in the buffer, waiting to be flushed. So your outputs are not really "sent", since they haven't made it as far as the socket.

If you want to keep using BufferedOutputStream, then you may need to periodically flush() it, in order to keep things moving along. The flush() method on the ObjectOutputStream will in turn call flush() on the BufferedOutputStream, which will empty the buffer and send the objects down the pipe.

I have to ask, though, why you need to use BufferedOuputStream at all. Do you have a performance problem that needs buffering to solve? If not, then just leave it out, it adds complexity that you may not need.

Body:
I have this line of code in my server/client pair:

BufferedOutputStream out = new BufferedOutputStream (clientSocket.getOutputStream());

It works fine, the code works well, then if I modify it to:

BufferedOutputStream out = new BufferedOutputStream (new BufferedOutputStream(clientSocket.getOutputStream()));

The execution of the application will halt where outputs are sent. I really only made that modification and am very new to streams in this manner, especially sockets.

Is there any obvious error?


问:
Django Internationlization in Python2 not working (Unicode Decode Error)
I tried to implement Internationalize in Django
I followed this tutorial here: https://medium.com/@nolanphillips/a-short-intro-to-translating-your-site-with-django-1-8-343ea839c89b

But I got an UnicodeDecodeError like below whenever I executed “python manage.py makemessage -l en” command
“UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe9 in position 1: ordinal not in range(128)”

I also tried to change locale setting in both bashrc and environment files to:

```<code>LANG=en_US.UTF-8
LANGUAGE=en_US:en
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8
</code>```

But no luck, the error still there

Any idea? Thank you

答:
Thanks for your time. This is output from makemessages:</p>

```<code>Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 326, in handle
    potfiles = self.build_potfiles()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 356, in build_potfiles
    file_list = self.find_files(".")
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 411, in find_files
    for dirpath, dirnames, filenames in os.walk(root, topdown=True, followlinks=self.symlinks):
  File "/usr/lib/python2.7/os.py", line 286, in walk
    if isdir(join(top, name)):
  File "/usr/lib/python2.7/posixpath.py", line 80, in join
    path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 1: ordinal not in range(128)
</code>```

Body:
I tried to implement Internationalize in Django
I followed this tutorial here: https://medium.com/@nolanphillips/a-short-intro-to-translating-your-site-with-django-1-8-343ea839c89b

But I got an UnicodeDecodeError like below whenever I executed “python manage.py makemessage -l en” command
“UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe9 in position 1: ordinal not in range(128)”

I also tried to change locale setting in both bashrc and environment files to:

LANG=en_US.UTF-8
LANGUAGE=en_US:en
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

But no luck, the error still there

Any idea? Thank you

Body:
Thanks for your time. This is output from makemessages:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 326, in handle
    potfiles = self.build_potfiles()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 356, in build_potfiles
    file_list = self.find_files(".")
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 411, in find_files
    for dirpath, dirnames, filenames in os.walk(root, topdown=True, followlinks=self.symlinks):
  File "/usr/lib/python2.7/os.py", line 286, in walk
    if isdir(join(top, name)):
  File "/usr/lib/python2.7/posixpath.py", line 80, in join
    path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 1: ordinal not in range(128)


问:
Devise Error Validations not working for Login
I am using devise for login and signup etc.. My validations seem to work on my sign-up page but not my sign-in page. Here is what i'm using.

sessions/new.html.erb

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

<%= render 'shared/devisemes' %>

    <%= f.email_field :email, autofocus: true, :class => 'form-control', :placeholder => "Email" %>

        <%= f.password_field :password, :autocomplete => :off, :class => 'form-control', :placeholder => "Password" %>

  <% if devise_mapping.rememberable? -%>

      <%= f.check_box :remember_me %> Remember Me

  <% end -%>

    <%= f.submit "Log in", :class => "btn btn-primary" %>
    <% link_to "Forget Password", new_user_password_path, :class => "btn btn-primary" %>

<% end %>
```

<p>shared/_devisemes.html.erb</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><% unless resource.errors.empty? %>

<script type="text/javascript">
<% resource.errors.full_messages.each do |msg| %>
toastr.error("<%= msg %>")
<% end %>
</script>
<% end %></code>```

user.rb

  validates :username, :presence => true, length: { minimum: 4, maximum: 16 }, :uniqueness => { :case_sensitive => false }
  validates :email, :presence => true, length: { minimum: 6, maximum:45 }, :uniqueness => { :case_sensitive => false}

  validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
```

When i click submit when its blank or doesnt match a username it just reloads the page no error.

答:
Try to add this code at the end:

```<code><% if flash[:notice].present? %>
  <p><%= flash[:notice] %></p>
<% end %>

<% if flash[:alert].present? %>
  <p><%= flash[:alert] %></p>
<% end %>
</code>```

Also, have you tried simple html validation? like
<%= f.email_field :email, autofocus: true, :class => 'form-control', :placeholder => "Email", required="true" %>
 or something

Body:
I am using devise for login and signup etc.. My validations seem to work on my sign-up page but not my sign-in page. Here is what i'm using.

sessions/new.html.erb

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

<%= render 'shared/devisemes' %>

    <%= f.email_field :email, autofocus: true, :class => 'form-control', :placeholder => "Email" %>

        <%= f.password_field :password, :autocomplete => :off, :class => 'form-control', :placeholder => "Password" %>

  <% if devise_mapping.rememberable? -%>

      <%= f.check_box :remember_me %> Remember Me

  <% end -%>

    <%= f.submit "Log in", :class => "btn btn-primary" %>
    <% link_to "Forget Password", new_user_password_path, :class => "btn btn-primary" %>

<% end %>

shared/_devisemes.html.erb

<% unless resource.errors.empty? %>

<% end %>

user.rb

  validates :username, :presence => true, length: { minimum: 4, maximum: 16 }, :uniqueness => { :case_sensitive => false }
  validates :email, :presence => true, length: { minimum: 6, maximum:45 }, :uniqueness => { :case_sensitive => false}

  validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true

When i click submit when its blank or doesnt match a username it just reloads the page no error.

Body:
Try to add this code at the end:

<% if flash[:notice].present? %>
  <p><%= flash[:notice] %></p>
<% end %>

<% if flash[:alert].present? %>
  <p><%= flash[:alert] %></p>
<% end %>

Also, have you tried simple html validation? like
<%= f.email_field :email, autofocus: true, :class => 'form-control', :placeholder => "Email", required="true" %>
 or something


问:
how to pass error class object as a result in API?
I have create One API controller and i want to pass custom error class object as a response.

Can any one help me for that ?

Thanks in advance.

答:
Create one class for to store error information as shown below.

```<code>ErrorInformation objError = new ErrorInformation();

try
 {
    test(ref Token, ref SessionToken);
 }
catch (Exception ex)
{
    objError.ErrorMessage = ex.Message;
    objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
    objError.ErrorType = ex.GetType().ToString();
    objError.ErrorCode = "E01";

    throw new HttpResponseException(Request.CreateResponse<ErrorInformation>(HttpStatusCode.ExpectationFailed, objError));
}
</code>```

This will return whole object as result.

```<code>{
  "StatusCode": 417,
  "ErrorMessage": "Error Detail",
  "ErrorType": "System.DivideByZeroException",
  "ErrorCode": "E01"
}
</code>```

Body:
Create one class for to store error information as shown below.

ErrorInformation objError = new ErrorInformation();

try
 {
    test(ref Token, ref SessionToken);
 }
catch (Exception ex)
{
    objError.ErrorMessage = ex.Message;
    objError.StatusCode = Convert.ToInt16(HttpStatusCode.ExpectationFailed);
    objError.ErrorType = ex.GetType().ToString();
    objError.ErrorCode = "E01";

    throw new HttpResponseException(Request.CreateResponse<ErrorInformation>(HttpStatusCode.ExpectationFailed, objError));
}

This will return whole object as result.

{
  "StatusCode": 417,
  "ErrorMessage": "Error Detail",
  "ErrorType": "System.DivideByZeroException",
  "ErrorCode": "E01"
}


问:
Error 3027: No mapping specified for the following EntitySet/AssociationSet
I am using EntityFramework 6 and I used Update Model from Database after inserting table in the database, I got above error.Please state how to overcome this problem.

答:
Not too satisfying, but I solved it by removing and re-adding the model:

Right-click on edmx-diagram and select "Model browser"

Remove the entity type that's giving the problems

Save (just to be sure, regenerates files)

Add model from databasetable again and save.

The warning was gone afterwards.


问:
Echo PHP returned value with AJAX in span/div
Ok I have a following HTML, AJAX and PHP script below. I want to get the $deduct value to update
 field when the AJAX request is processed. How can I do so?

Example Form

```<code><form>
    <span id="mywallet">$<?php echo $wallet; ?></span>
</form>
</code>```

Example flip-process.php structure

```<code><?php
if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $msg = "success";
    }else{
       $msg = "fail";
    }
}
echo $msg;
?>
</code>```

Ajax Script

```<code>$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#process-flipping").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                setTimeout(function(){
                $(".message").html(html).fadeIn();
                    $("#process-flipping").show();
                    $(".coin-flip").hide();
                },3000);
            }
        });
        return false;
    });
});
</code>```

答:
The best way to do that is to use json

PHP

```<code><?php

$response = [];

if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $response["deduct"] = $deduct;
    }else{
       $response["msg"] = "your message here";
    }
}

header("Content-type:application/json; charset: UTF-8");
echo json_encode($response);
?>
</code>```

JS

```<code>$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
        dataType : "json",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#process-flipping").hide();
                $(".coin-flip").show();
      },
            success: function(json){
                //json.deduct will has the value you want
            }
        });
        return false;
    });
});
</code>```

Body:
Ok I have a following HTML, AJAX and PHP script below. I want to get the $deduct value to update
 field when the AJAX request is processed. How can I do so?

Example Form

<form>
    $<?php echo $wallet; ?>
</form>

Example flip-process.php structure

<?php
if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $msg = "success";
    }else{
       $msg = "fail";
    }
}
echo $msg;
?>

Ajax Script

$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#process-flipping").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                setTimeout(function(){
                $(".message").html(html).fadeIn();
                    $("#process-flipping").show();
                    $(".coin-flip").hide();
                },3000);
            }
        });
        return false;
    });
});

Body:
The best way to do that is to use json

PHP

<?php

$response = [];

if($_POST){
    //process everything

    $deduct = (something calculated);

    if(success){
       $response["deduct"] = $deduct;
    }else{
       $response["msg"] = "your message here";
    }
}

header("Content-type:application/json; charset: UTF-8");
echo json_encode($response);
?>

JS

$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
        dataType : "json",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#process-flipping").hide();
                $(".coin-flip").show();
      },
            success: function(json){
                //json.deduct will has the value you want
            }
        });
        return false;
    });
});


问:
Python how to print 0 if there are no negative numbers in a list?
I have to print the first negative number in a list, but if there are no negative numbers I have to return it as 0. I cannot for the life of me figure this out, I feel very dumb.

```<code>def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number
</code>```

Currently it works if there are negative numbers, but if there aren't, it'll return nothing. I can't seem to make it so it returns 0 instead of nothing

答:
Add return 0 outside of the for loop. The program arrives there only if it didn't find any negative number.

```<code>def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number
    return 0
</code>```

Body:
I have to print the first negative number in a list, but if there are no negative numbers I have to return it as 0. I cannot for the life of me figure this out, I feel very dumb.

def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number

Currently it works if there are negative numbers, but if there aren't, it'll return nothing. I can't seem to make it so it returns 0 instead of nothing

Body:
Add return 0 outside of the for loop. The program arrives there only if it didn't find any negative number.

def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number
    return 0


问:
convert array to hash and initialize to a value
what is the best way to convert an array of

```<code>arr = ["one", "two", "three", "four", "five"]
</code>```

to hash of

```<code>{"one"=>0, "two"=>0, "three"=>0, "four"=>0, "five"=>0}
</code>```

Iam planning to fillup the '0' with my own values later, I just need the technique now.

Thanks.

答:
You can also do

```<code>arr.each_with_object({}) {|v, h| h[v] = 1}
</code>```

where:

v is the value of each element in the array,

h represents the hash object

Body:
what is the best way to convert an array of

arr = ["one", "two", "three", "four", "five"]

to hash of

{"one"=>0, "two"=>0, "three"=>0, "four"=>0, "five"=>0}

Iam planning to fillup the '0' with my own values later, I just need the technique now.

Thanks.

Body:
You can also do

arr.each_with_object({}) {|v, h| h[v] = 1}

where:

v is the value of each element in the array,

h represents the hash object


问:
RAII in Ruby (Or, How to Manage Resources in Ruby)
I know it's by design that you can't control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.

However is the ruby idiom for C++'s RAII (Resources are initialized in constructor, closed in destructor)?   How do people manage resources used inside objects even when errors or exceptions happen?

Using ensure works:

```<code>f = File.open("testfile")
begin
  # .. process
rescue
  # .. handle error
ensure
  f.close unless f.nil?
end
</code>```

but users of the class have to remember to do the whole begin-rescue-ensure chacha everytime the open method needs to be called.

So for example, I'll have the following class:

```<code>class SomeResource
 def initialize(connection_string)
   @resource_handle = ...some mojo here...
 end

 def do_something()
   begin
    @resource_handle.do_that()
    ...
   rescue
    ...
   ensure
 end

 def close
  @resource_handle.close
 end

end
</code>```

The resource_handle won't be closed if the exception is cause by some other class and the script exits.

Or is the problem more of I'm still doing this too C++-like?

答:
Or is the problem more of I'm still doing this too C++-like?

Yes it is since in C++ resource deallocation happens implicitly for everything on the stack. Stack unwound = resource destroyed = destructors called and from there things can be released. Since Ruby has no destructors there is no "do that when everything else is done with" place since grabage collection can be delayed several cycles from where you are. You do have finalizers but they are called "in limbo" (not everything is available to them) and they get called on GC.

Therefore if you are holding a handle to some resource that better be released you need to release it explicitly. Indeed the correct idiom to handle this kind of situation is

```<code>def with_shmoo
  handle = allocate_shmoo
  yield(handle)
ensure
  handle.close
end
</code>```

OwnerDisplayName: moogs

Body:
I know it's by design that you can't control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.

However is the ruby idiom for C++'s RAII (Resources are initialized in constructor, closed in destructor)?   How do people manage resources used inside objects even when errors or exceptions happen?

Using ensure works:

f = File.open("testfile")
begin
  # .. process
rescue
  # .. handle error
ensure
  f.close unless f.nil?
end

but users of the class have to remember to do the whole begin-rescue-ensure chacha everytime the open method needs to be called.

So for example, I'll have the following class:

class SomeResource
 def initialize(connection_string)
   @resource_handle = ...some mojo here...
 end

 def do_something()
   begin
    @resource_handle.do_that()
    ...
   rescue
    ...
   ensure
 end

 def close
  @resource_handle.close
 end

end

The resource_handle won't be closed if the exception is cause by some other class and the script exits.

Or is the problem more of I'm still doing this too C++-like?

LastEditorDisplayName: John Millikin

Body:
Or is the problem more of I'm still doing this too C++-like?

Yes it is since in C++ resource deallocation happens implicitly for everything on the stack. Stack unwound = resource destroyed = destructors called and from there things can be released. Since Ruby has no destructors there is no "do that when everything else is done with" place since grabage collection can be delayed several cycles from where you are. You do have finalizers but they are called "in limbo" (not everything is available to them) and they get called on GC.

Therefore if you are holding a handle to some resource that better be released you need to release it explicitly. Indeed the correct idiom to handle this kind of situation is

def with_shmoo
  handle = allocate_shmoo
  yield(handle)
ensure
  handle.close
end


问:
Single tab bar item present different view controllers depending on a condition?
I am making an app that has a couple of different tabs using a tab bar controller.  I add items to a bag in the first tab, and update the cart in the next viewcontroller.  If the user goes to the second tab (the cart) without adding anything I want it to present a view controller saying the cart is empty.  If they go to it once they have added something then it will show a table view.  </p>

<p>Is there any way to tell a tab bar controller to present different view controllers depending on a condition? </p>

答:
You can actually present the same UITableViewController.
In that UITableViewController you must be knowing whether you have data or not. If you have a data for UITableViewController then you will show the items in cart in UITableViewController else you can have empty message in the same UITableViewController.
You can refer this post to show empty message on `UITableViewController?

If no Table View results, display "No Results" on screen .

Body:
I am making an app that has a couple of different tabs using a tab bar controller.  I add items to a bag in the first tab, and update the cart in the next viewcontroller.  If the user goes to the second tab (the cart) without adding anything I want it to present a view controller saying the cart is empty.  If they go to it once they have added something then it will show a table view.

Is there any way to tell a tab bar controller to present different view controllers depending on a condition?


答:
try this:</p>

```<code>def find_negative(list_numbers):
    first_index = 0
    for list_number in list_numbers:
        if list_number < 0:
            first_index = list_number
            break
    return first_index
</code>```

Title: Python how to print 0 if there are no negative numbers in a list?

Body:
try this:

def find_negative(list_numbers):
    first_index = 0
    for list_number in list_numbers:
        if list_number < 0:
            first_index = list_number
            break
    return first_index