问:
Problem with iPhone shakes: viewDidAppear isn't called when loading viewController
I'm trying to detect a shake on the iPhone device, so for what i've read I need to set my view controller as first responder on the viewDidAppear method. This method is supposed to be called automatically, but for some reason this method is never called. Only viewDidLoad is called.

this is my code (I put only the relevant parts):

BuildHouseViewController.h:

@interface BuildHouseViewController : UIViewController {

BuildHouseViewController.m:

```<code>- (void)viewDidLoad {
[super viewDidLoad];
[self.view becomeFirstResponder];}

-(void)viewDidAppear:(BOOL)animated{
[self becomeFirstResponder];
[super viewDidAppear:animated];}

-(BOOL)canBecomeFirstResponder {
return YES;}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{

NSLog(@"shake");
if ( event.subtype == UIEventSubtypeMotionShake )
{  }

if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
    [super motionEnded:motion withEvent:event];
}
</code>```

I added breakpoints on the viewDidAppear method and it is never called. Shakes are never detected, I suppose it is because as this methods are never called, so the view controller can never become first responder. I don't understand why this is happening.

Any help will be appreciated.

Edit:

I call the view from another view using:

```<code>[self.view addSubview:nextScreen.view];
</code>```

The view is displayed on screen

答:
Further to @Genericrich's comments, you can manually call viewDidAppear after you put the subview in yourself.

```<code>[self.view addSubview:theViewController.view];
[theViewController viewDidAppear:FALSE];
</code>```

This worked for me. Hope it helps someone else.

Body:
I'm trying to detect a shake on the iPhone device, so for what i've read I need to set my view controller as first responder on the viewDidAppear method. This method is supposed to be called automatically, but for some reason this method is never called. Only viewDidLoad is called.

this is my code (I put only the relevant parts):

BuildHouseViewController.h:

@interface BuildHouseViewController : UIViewController {

BuildHouseViewController.m:

- (void)viewDidLoad {
[super viewDidLoad];
[self.view becomeFirstResponder];}

-(void)viewDidAppear:(BOOL)animated{
[self becomeFirstResponder];
[super viewDidAppear:animated];}

-(BOOL)canBecomeFirstResponder {
return YES;}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{

NSLog(@"shake");
if ( event.subtype == UIEventSubtypeMotionShake )
{  }

if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
    [super motionEnded:motion withEvent:event];
}

I added breakpoints on the viewDidAppear method and it is never called. Shakes are never detected, I suppose it is because as this methods are never called, so the view controller can never become first responder. I don't understand why this is happening.

Any help will be appreciated.

Edit:

I call the view from another view using:

[self.view addSubview:nextScreen.view];

The view is displayed on screen

Body:
Further to @Genericrich's comments, you can manually call viewDidAppear after you put the subview in yourself.

[self.view addSubview:theViewController.view];
[theViewController viewDidAppear:FALSE];

This worked for me. Hope it helps someone else.


来源: stackexchange

问:
django display uploaded by user images
I have ImageUploadField
I save images at my_project/forum_attachments directory.

But when I try to display them and see by this link: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg
I get an error

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg

What do I do?

UPD: urls.py:

```<code>urlpatterns = [
    url(r'^polls/', include('some_app.urls')),
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^about/', views.about, name='about'),
    url(r'^login/$', auth_views.login, name='login'),

    url(r'^user_logout/$', views.user_logout, name='user_logout'),
    url(r'^index_old/', views.index_old, name='index_old'),
    url(r'^forum/', views.forum, name='forum'),
    url(r'^vip/', views.vip, name='vip'),
    url(r'^test/', views.test, name='test'),
    url(r'^forum_new/', views.forum_new, name='forum_new'),
]
</code>```

答:
In case you've not set your MEDIA_URL & MEDIA ROOT in settings or your local settings file, you should follow the below procedure.

Settings.py

```<code>import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

MEDIA_ROOT = os.path.join(PROJECT_PATH,'../media/')

MEDIA_URL = '/media/'

STATICFILES_DIRS = (
     os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')

STATIC_URL = '/static/'
</code>```

Now in your Urls.py, do this:

```<code>from django.conf.urls.static import static

urlpatterns = [
    url(r'^polls/', include('some_app.urls')),
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^about/', views.about, name='about'),
    url(r'^login/$', auth_views.login, name='login'),

    url(r'^user_logout/$', views.user_logout, name='user_logout'),
    url(r'^index_old/', views.index_old, name='index_old'),
    url(r'^forum/', views.forum, name='forum'),
    url(r'^vip/', views.vip, name='vip'),
    url(r'^test/', views.test, name='test'),
    url(r'^forum_new/', views.forum_new, name='forum_new'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

The 'static' was appended to the urlpatterns because your DEBUG might be set to True in your settings.py.

ContentLicense: CC BY-SA 3.0

Title: django display uploaded by user images

Body:
I have ImageUploadField
I save images at my_project/forum_attachments directory.

But when I try to display them and see by this link: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg
I get an error

Page not found (404) Request Method:  GET Request
  URL:  http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg

What do I do?

UPD: urls.py:

urlpatterns = [
    url(r'^polls/', include('some_app.urls')),
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^about/', views.about, name='about'),
    url(r'^login/$', auth_views.login, name='login'),

    url(r'^user_logout/$', views.user_logout, name='user_logout'),
    url(r'^index_old/', views.index_old, name='index_old'),
    url(r'^forum/', views.forum, name='forum'),
    url(r'^vip/', views.vip, name='vip'),
    url(r'^test/', views.test, name='test'),
    url(r'^forum_new/', views.forum_new, name='forum_new'),
]

Body:
In case you've not set your MEDIA_URL & MEDIA ROOT in settings or your local settings file, you should follow the below procedure.

Settings.py

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))

MEDIA_ROOT = os.path.join(PROJECT_PATH,'../media/')

MEDIA_URL = '/media/'

STATICFILES_DIRS = (
     os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')

STATIC_URL = '/static/'

Now in your Urls.py, do this:

from django.conf.urls.static import static

urlpatterns = [
    url(r'^polls/', include('some_app.urls')),
    url(r'^$', views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    url(r'^about/', views.about, name='about'),
    url(r'^login/$', auth_views.login, name='login'),

    url(r'^user_logout/$', views.user_logout, name='user_logout'),
    url(r'^index_old/', views.index_old, name='index_old'),
    url(r'^forum/', views.forum, name='forum'),
    url(r'^vip/', views.vip, name='vip'),
    url(r'^test/', views.test, name='test'),
    url(r'^forum_new/', views.forum_new, name='forum_new'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

The 'static' was appended to the urlpatterns because your DEBUG might be set to True in your settings.py.


问:
QSqlQuery.next() return false but has data in database. Why?
I have data in my sqlite database. Insert statement executed successfully. But when want to get data from db i found nothing and this error "QSqlError("", "", "")". I have checked my query is active and not valid. How to solve this issue ?

Here is my code:

```<code>void FindDialog::find()
{

    QString roll_number = ui->txt_RN->text ();

    int roll = roll_number.toInt ();

    const QString findstmnt = "SELECT Roll_Number, Name FROM student_info WHERE Roll_Number = :roll";

    scon->getQuery ()->prepare (findstmnt);

    scon->getQuery ()->bindValue ("roll", roll);

    if(scon->getQuery ()->exec ()){

        qDebug() << "Active: " << scon->getQuery ()->isActive ();

        qDebug() << "Valid: " << scon->getQuery ()->isValid ();

        if(scon->getQuery ()->isActive ()){
            if(scon->getQuery ()->next ()){
                qDebug() << "Has Data: " << scon->getQuery ()->next ();
            } else {
                qDebug() << scon->getQuery ()->lastError ();
            }
        }

    } else {
        qDebug() << scon->getQuery ()->lastError ();
    }
</code>```

答:
The name of the parameter is not roll but :roll.

When you bind the value to the wrong parameter name, the actual parameter has its initial value, which is NULL.
So the query will never find any row because no value compares equal to NULL.

Body:
I have data in my sqlite database. Insert statement executed successfully. But when want to get data from db i found nothing and this error "QSqlError("", "", "")". I have checked my query is active and not valid. How to solve this issue ?

Here is my code:

void FindDialog::find()
{

    QString roll_number = ui->txt_RN->text ();

    int roll = roll_number.toInt ();

    const QString findstmnt = "SELECT Roll_Number, Name FROM student_info WHERE Roll_Number = :roll";

    scon->getQuery ()->prepare (findstmnt);

    scon->getQuery ()->bindValue ("roll", roll);

    if(scon->getQuery ()->exec ()){

        qDebug() << "Active: " << scon->getQuery ()->isActive ();

        qDebug() << "Valid: " << scon->getQuery ()->isValid ();

        if(scon->getQuery ()->isActive ()){
            if(scon->getQuery ()->next ()){
                qDebug() << "Has Data: " << scon->getQuery ()->next ();
            } else {
                qDebug() << scon->getQuery ()->lastError ();
            }
        }

    } else {
        qDebug() << scon->getQuery ()->lastError ();
    }


问:
Java classes.jar' could not be found error when executing maven
I just installed java 8 and maven on Mac El Captain. I have set all the environment variables correctly and java -version does display the java version. But when I try to run maven from the terminal I get the following error:

```<code>File or url '/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Classes/classes.jar' could not be found
java.net.MalformedURLException: no protocol: /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Classes/classes.jar
    at java.net.URL.<init>(URL.java:593)
    at java.net.URL.<init>(URL.java:490)
    at java.net.URL.<init>(URL.java:439)
    at com.werken.forehead.Forehead.loadFileOrUrl(Forehead.java:403)
    at com.werken.forehead.Forehead.load(Forehead.java:322)
    at com.werken.forehead.Forehead.config(Forehead.java:245)
    at com.werken.forehead.Forehead.config(Forehead.java:131)
    at com.werken.forehead.Forehead.main(Forehead.java:579)
</code>```

any ideas?

答:
For Maven 1.x, I found the following bit of the bin/maven shell script caused the same error for me on a Mac:

```<code>if $darwin; then
    TOOLS_JAR="/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Classes/classes.jar"
fi
</code>```

I simply edited the bin/maven script file and commented out the if $darwin; then ... fi section and it is now working.

Body:
I just installed java 8 and maven on Mac El Captain. I have set all the environment variables correctly and java -version does display the java version. But when I try to run maven from the terminal I get the following error:

File or url '/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Classes/classes.jar' could not be found
java.net.MalformedURLException: no protocol: /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Classes/classes.jar
    at java.net.URL.<init>(URL.java:593)
    at java.net.URL.<init>(URL.java:490)
    at java.net.URL.<init>(URL.java:439)
    at com.werken.forehead.Forehead.loadFileOrUrl(Forehead.java:403)
    at com.werken.forehead.Forehead.load(Forehead.java:322)
    at com.werken.forehead.Forehead.config(Forehead.java:245)
    at com.werken.forehead.Forehead.config(Forehead.java:131)
    at com.werken.forehead.Forehead.main(Forehead.java:579)

any ideas?

Body:
For Maven 1.x, I found the following bit of the bin/maven shell script caused the same error for me on a Mac:

if $darwin; then
    TOOLS_JAR="/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Classes/classes.jar"
fi

I simply edited the bin/maven script file and commented out the if $darwin; then ... fi section and it is now working.


问:
NSAutolayoutConstraint - Apply constant before multiplier
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)
</code>```

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

```<code>let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)
</code>```

Because I end up losing the constraint.constant that comes from the storyboard.

答:
Why do you want to change a multiplier value? Change constant value instead..

declare inside the class

```<code>var yourViewWidthConstraint: NSLayoutConstraint?
</code>```

Instantiate this constraint

```<code>yourViewWidthConstraint = yourView.widthAnchor.constraint(self.view.widthAnchor)
yourViewWidthConstraint?.isActive = true
</code>```

Now, change yourViewWidthConstraint.constant anywhere..

Body:
Today the multiplier property is read-only. In order to change it, you have to remove the constraint and create a new one.

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constraint.constant
)

In this example, first the multiplier will be applied and then the constant. For example:

Imagine it's a width constraint to the superview.

This means we'll have view.width = superview.width * multiplier - 2.
(which also means that a multiplier = 0 will break).

What I need is view.width = (superview.width - 2) * multiplier. How do I create such constraint?

I also don't want to do something like:

let newConstraint = NSLayoutConstraint(
    item: constraint.firstItem,
    attribute: constraint.firstAttribute,
    relatedBy: constraint.relation,
    toItem: constraint.secondItem,
    attribute: constraint.secondAttribute,
    multiplier: newMultiplier,
    constant: constant * newMultiplier
)

Because I end up losing the constraint.constant that comes from the storyboard.

Body:
Why do you want to change a multiplier value? Change constant value instead..

declare inside the class

var yourViewWidthConstraint: NSLayoutConstraint?

Instantiate this constraint

yourViewWidthConstraint = yourView.widthAnchor.constraint(self.view.widthAnchor)
yourViewWidthConstraint?.isActive = true

Now, change yourViewWidthConstraint.constant anywhere..


问:
C# how to enable button from another class
I have a form1, there's a "download" button, and a "next" button. By default, the "next" button is disabled. When I click "download" button, I will call a method from download.cs, different from form1.cs. After downloading, I want the "next" button to be enabled, so in download.cs, after receiving all files, I put

form1.btnNext.Enabled = true;

But it doesn't work. I also put this in form1.cs

public void enableButton(bool enabled)

{
     btnNext.Enabled = enabled;
  }

and in download.cs I put:

private form1 form1;
  ...

form1.enableButton(true);

but it doesn't work either. Could any1 show me where I'm wrong? thanks in advance.

答:
I remember facing something like this , and you may try to make your (next) buttonpublic instead of private , but this is not a very adorable approach ,but I guess if you do hat then your first suggestion will work.

and if it doesn't you can try doing this :

Form1 myForm = new Form1;
myform.nxtButton.enabled = true;

it will definitely work

ContentLicense: CC BY-SA 2.5


问:
Authentication failed - Permission Denied with EmberFire
I'm trying to set up a basic datastore at firebase when following simple beginner tutorials on Ember js 2.0. For example I am following this tutorial:

https://medium.com/@jamesfuthey/a-gentle-introduction-to-ember-2-0-8ef1f378ee4#.d6umfj62j

I always seem to have a problem with authentication with the Firebase URL. That is, I've gotten to the bit where this tutorial tries to write information to my firebase project, but the Chrome Inspector shows I'm getting a 'permission denied' error from firebase.

FIREBASE WARNING: update at /posts/-KIpiNcp3WVRkCfwl_lW failed: permission_denied

I have installed emberfire with ember install emberfire. I have added my firebase URL to config/environment.js:

contentSecurityPolicy: { 'connect-src': "'self' HTTPREMOVED//auth.firebase.com wss://*.firebaseio.com" },
firebase: 'HTTPREMOVED//ember2-blog-ccb21.firebaseio.com',

Note: I had to remove the http element on these links to post here as I have a reputation less than 10.

Initially I did not change any authentication settings on my Firebase project (which I think is odd as I should need to authenticate to the Firebase project somehow). Then I tried adding my domains, firstly my IP and then the domain name associated with my IP.

I'm using:
ember-cli: 2.5.1

I'd love it someone could point me in the right direction. Thank you.

答:
In the Firebase console in your browser, go to Database -> Rules and edit the rules:

```<code>{
    "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
    }
}
</code>```

To:

```<code>{
    "rules": {
    ".read": "auth == null",
    ".write": "auth == null"
    }
}
</code>```

The above worked for me, it is baiscally the same as previous answer, however I kept the auth keyword so when i'm ready to secure the database the basic syntax is already there.

Body:
In the Firebase console in your browser, go to Database -> Rules and edit the rules:

{
    "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
    }
}

To:

{
    "rules": {
    ".read": "auth == null",
    ".write": "auth == null"
    }
}

The above worked for me, it is baiscally the same as previous answer, however I kept the auth keyword so when i'm ready to secure the database the basic syntax is already there.


问:
Delete TFS branch without downloading it
I am trying to delete a branch that has not been downloaded into my workspace via following command.

tf delete /lock:checkout /recursive $/TfsServerName/TfsFolder/Branch

I get following error message:

No matching items found in $/TfsServerName/TfsFolder/Branch in your workspace.

Is there a way to delete a TFS branch without actually downloading it?

答: In the Source Control Explorer, if you simply map the branch to a local path and hit OK, it will enable the "delete dropdown".


问:
IE11 cross domain popup window
I want to send messages from a popup window created by window.open('domainB.com') to a parent window at domainA.com in IE11. I read on the internet that this is basically not possible in IE11, but I think the google sign in button does exactly this. Any idea how they do this?

All I want is from javascript on domainA.com, popup a window to domainB.com in IE11 and then have domainB.com send messages to domainA.com using postMessage, localstorage, cookies, anything.

答:
https://github.com/krakenjs/post-robot

this library does exactly what I was describing

Title: IE11 cross domain popup window


问:
Webpack does not generate bundle file on npm run
Greetings one and all,

After having made a React application, I decided to dive in deeper into Webpack.
I am rather new at the whole npm automation scene and after having followed a cookbook and various tutorials, I just cannot let npm run dev bundle my application. It generates a bundle.js perfectly fine when I run webpack, but what appealed to me was having webpack generate a physical file whenever I change something. Gulp and Grunt can do this for me, but I'd like to get it to work with webpack as well.

So, without further ado, some code. I run npm run dev which is defined like so (package.json, just the scripts part*):

```<code>  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
  }
</code>```

With the following Webpack configuration:

```<code>var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'src/js/main.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '/js/bundle.js',
        publicPath: '/'
    },
    devServer: {
        inline: true,
        contentBase: './dist'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    plugins: [
        new webpack.ResolverPlugin([
                new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
            ], ["normal"], "loader")
    ]
};
</code>```

Cases:
webpack: Bundles my application into dist/js/bundle.js perfectly fine.
webpack-dev-server: Seems to stream a memory bundle from my JS perfectly fine, but does not generate a bundle on disk.
npm run dev: Starts the webpack server, but does not result in a bundle, nor does my application run, resulting in a Cannot GET/ error.

Can anyone point me in the right direction? I have tried variations on the config, but to no avail.. And just to be complete, I will show my directory structure:

```<code>./project
    ./dist
        ./js
            ./bundle.js
    ./src
        ./js
            ./main.js
./package.json
./webpack.config.js
</code>```

Once again, thanks for the assist!

答:
For me the problem was with package.json under that "scripts"

Here is the fix:

Inside your package.json file, under script add the following:

"scripts": {

     "start": "webpack-dev-server",

     "build": "webpack -p"
   }

First I ran the build then start.

yarn build

if you first build then your bundle.js file will be created and after that you can use this command:

yarn start

Instead of yarn, you can also use npm

Body:
Greetings one and all,

After having made a React application, I decided to dive in deeper into Webpack.
I am rather new at the whole npm automation scene and after having followed a cookbook and various tutorials, I just cannot let npm run dev bundle my application. It generates a bundle.js perfectly fine when I run webpack, but what appealed to me was having webpack generate a physical file whenever I change something. Gulp and Grunt can do this for me, but I'd like to get it to work with webpack as well.

So, without further ado, some code. I run npm run dev which is defined like so (package.json, just the scripts part*):

  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server --devtool eval --progress --colors --hot --content-base build"
  }

With the following Webpack configuration:

var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: path.resolve(__dirname, 'src/js/main.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '/js/bundle.js',
        publicPath: '/'
    },
    devServer: {
        inline: true,
        contentBase: './dist'
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    plugins: [
        new webpack.ResolverPlugin([
                new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
            ], ["normal"], "loader")
    ]
};

Cases:
webpack: Bundles my application into dist/js/bundle.js perfectly fine.
webpack-dev-server: Seems to stream a memory bundle from my JS perfectly fine, but does not generate a bundle on disk.
npm run dev: Starts the webpack server, but does not result in a bundle, nor does my application run, resulting in a Cannot GET/ error.

Can anyone point me in the right direction? I have tried variations on the config, but to no avail.. And just to be complete, I will show my directory structure:

./project
    ./dist
        ./js
            ./bundle.js
    ./src
        ./js
            ./main.js
./package.json
./webpack.config.js

Once again, thanks for the assist!


问:
Angular 2: Using service to share data between components
I am trying to use a service to define a shared resource client between several views.  I first select the client from an index and set it:

```<code>itemTapped(event, client) {
  this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
    .subscribe(
      data => {
        this.clientService.setClient(data)
        this.navCtrl.push(ClientGenericPage, {
          client_id: data['id'],
          tab: 'profile',
          current_user: this.current_user
        });
      },
      err => {
        this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
        this.clientService.hideLoader()
      },
      () => this.clientService.hideLoader()
    )
}

export class ClientService {

  private client = new Subject<any>();

  constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {

  }

  setClient(client) {
    this.client.next(client)
  }

  getClient() {
    return this.client.asObservable();
  }

  get(url, token):Observable<Response> {
    let headers = new Headers();
    headers.append("authentication", token );
    let options = new RequestOptions({ headers: headers });

    let final_url = `${this.baseUrl}${url}`

    return this.http.get(final_url, options)
      .map(this.extractData)
      .catch(this.handleError)
  }
}
</code>```

Then I try to get the client that was just set and subscribe to it so that I can detect changes to client in this view and its siblings:

```<code>this.clientService.getClient()
  .subscribe(
    val => {
      console.log(val)
      this.client = val
    },
    err => console.log(err),
    () => {}
)
</code>```

but this call to getClient() never returns an error or anything at all.  What am I doing wrong with my observable?

EDIT:  Here is the component:

```<code>@Component({
  selector: 'page-client-details',
  templateUrl: 'client-details.html',
  providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
  client:any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private filterObject: FilterObject,
    public http: Http,
    public modalController: ModalController,
    private clientService: ClientService,
    private app: App
  ) {

  this.clientService.getClient()
    .subscribe(
      val => {
        console.log(val)
        this.client = val
      },
      err => console.log(err),
      () => console.log("completed")
    )
}
</code>```

答: You can try using BehaviorSubject instead of Subject, the unique change it you need provide a default value. Same error I fixed with that, but with no problem found.</p>

Body:
I am trying to use a service to define a shared resource client between several views.  I first select the client from an index and set it:

itemTapped(event, client) {
  this.clientService.get(`/${client.id}?model=client`, this.current_user.auth_token)
    .subscribe(
      data => {
        this.clientService.setClient(data)
        this.navCtrl.push(ClientGenericPage, {
          client_id: data['id'],
          tab: 'profile',
          current_user: this.current_user
        });
      },
      err => {
        this.clientService.handleResponse("Ut oh.. Could not locate the client !"),
        this.clientService.hideLoader()
      },
      () => this.clientService.hideLoader()
    )
}

export class ClientService {

  private client = new Subject<any>();

  constructor (private http: Http, private toastCtrl: ToastController, public storage: Storage ) {

  }

  setClient(client) {
    this.client.next(client)
  }

  getClient() {
    return this.client.asObservable();
  }

  get(url, token):Observable<Response> {
    let headers = new Headers();
    headers.append("authentication", token );
    let options = new RequestOptions({ headers: headers });

    let final_url = `${this.baseUrl}${url}`

    return this.http.get(final_url, options)
      .map(this.extractData)
      .catch(this.handleError)
  }
}

Then I try to get the client that was just set and subscribe to it so that I can detect changes to client in this view and its siblings:

this.clientService.getClient()
  .subscribe(
    val => {
      console.log(val)
      this.client = val
    },
    err => console.log(err),
    () => {}
)

but this call to getClient() never returns an error or anything at all.  What am I doing wrong with my observable?

EDIT:  Here is the component:

@Component({
  selector: 'page-client-details',
  templateUrl: 'client-details.html',
  providers: [FilterObject, ClientService]
})
export class ClientDetailsPage {
  client:any;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private filterObject: FilterObject,
    public http: Http,
    public modalController: ModalController,
    private clientService: ClientService,
    private app: App
  ) {

  this.clientService.getClient()
    .subscribe(
      val => {
        console.log(val)
        this.client = val
      },
      err => console.log(err),
      () => console.log("completed")
    )
}


问:
Can't get picture veritcally centered in a div
Yet again, I can't get an image to center inside a specific div. The answers I've come across only center it horizontally, but not vertically

#wrap {
width: auto;
margin: 0 auto;
overflow: hidden;
float: left;
}
/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
width: 50%;
height: 500px;
background: #000;
float: left;
}

#leftBlock img {
display: block;
margin: auto;
transition: transform 4s;
}

#leftBlock img:hover {
transform: scale(1.8);
}

#rightBlock {
width: 50%;
height: 500px;
background: #8ab78f;
float: left;
}

#rightBlock img {
display: block;
margin: auto;
}

/*ignore footer*/
#footerBlock {
height: 200px;
background:  #29342a ;
clear: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrap">
<div id="headerBlock">
    <div class="headerText">blah blah blah so neat</div>
    <div class="headerImg"><img src="/yupyup.jpg" height="70" width="70">
    </div>
</div>

<div id="leftBlock">
    <img src="/leftside.jpg" height="250" width="250">
</div>

<div id="rightBlock"></div>
     <img src="/rightside.jpg" height="250" width="250">
<div id="footerBlock"></div>

</div></code>```

The issue I'm coming across is, it only likes to center it horizontally. The only solution i found was doing the following below, but all that's really doing is moving it all over the screen and me having to pin point where it goes (which should be inside that leftBlock div..) :

```<code>#leftBlock img {
position: absolute;
top: 50%;
margin-top: 305px;
left: 50%;
margin-left: -450px;
transition: transform 4s;
}
</code>```

答:
Hello I have a simple solution for you! make your body and html height 100%. also add height to the relevant div in which you want to make it vertical center and use this code below. its verified.

body,html{ height:100%; margin:0px; padding:0px;}

.display-table-container {
  display: table;
 height: 100%;
 margin: 0px auto
}

.display-cell-container {
 display: table-cell;
 vertical-align: middle;
 position: relative
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="display-table-container">

<div class="display-cell-container">Insert your image here</div>

</div></code>```

Body:
Yet again, I can't get an image to center inside a specific div. The answers I've come across only center it horizontally, but not vertically

#wrap {
width: auto;
margin: 0 auto;
overflow: hidden;
float: left;
}
/*header info if needed
#headerBlock {
height: 200px;
background:  #776b68;
display: flex;
align-items: center;
}

div.headerText {
display: inline-block;
padding-right: 90px;
}

div.headerImg {
display: inline-block;
}
*/

#leftBlock {
width: 50%;
height: 500px;
background: #000;
float: left;
}

#leftBlock img {
display: block;
margin: auto;
transition: transform 4s;
}

#leftBlock img:hover {
transform: scale(1.8);
}

#rightBlock {
width: 50%;
height: 500px;
background: #8ab78f;
float: left;
}

#rightBlock img {
display: block;
margin: auto;
}

/*ignore footer*/
#footerBlock {
height: 200px;
background:  #29342a ;
clear: left;
}

blah blah blah so neat

The issue I'm coming across is, it only likes to center it horizontally. The only solution i found was doing the following below, but all that's really doing is moving it all over the screen and me having to pin point where it goes (which should be inside that leftBlock div..) :

#leftBlock img {
position: absolute;
top: 50%;
margin-top: 305px;
left: 50%;
margin-left: -450px;
transition: transform 4s;
}

Body:
Hello I have a simple solution for you! make your body and html height 100%. also add height to the relevant div in which you want to make it vertical center and use this code below. its verified.

body,html{ height:100%; margin:0px; padding:0px;}

.display-table-container {
  display: table;
 height: 100%;
 margin: 0px auto
}

.display-cell-container {
 display: table-cell;
 vertical-align: middle;
 position: relative
}

<div class="display-table-container">

<div class="display-cell-container">Insert your image here</div>

</div>


问:
Have an Angular2 application to point to proper URL
I have a small Angular2 application that works fine locally where I reference localhost. The problem is when I try to provision the application in production (read: on any external host that has to be referenced by its own IP address and/or FQDN).

This is the main part of the app (and where I am struggling with):

```<code>public appserver = environment.appserver_env;

getvotes(): void {
    const url = `${this.appserver}/api/getvotes`;
    this.http.get(url)
                .map((res: Response) => res.json())
                .subscribe(res => {console.log(res); this.votes = res})
    }
</code>```

The appserver_env variable is set inside the Angular environments. Some of them uses localhost such as this and it works just fine:

```<code>export const environment = {
  production: false,
  envName: 'test',
  appserver_env: 'http://localhost:4567'
};
</code>```

Basically I am starting my application and my backend service on my laptop, everything is referenced as localhost and all is fine.

The problem is when I try to deploy onto an external infrastructure (aka host) that has a specific IP / FQDN. My current Angular 2 production environment configuration looks like this:

```<code>export const environment = {
  production: true,
  envName: 'prod',
  appserver_env: 'http://myappserver:4567'
};
</code>```

This only works when I have my client configured in a way that can resolve myappserver to a proper IP address.

The problem is that I may end up having to deploy this app on a server that doesn't have a FQDN (only an IP address). Or anyway in an environment where name resolution does not work.

Is there a particular pattern / feature in Angular 2 that allows me to solve this problem? Note that, to complicate things further, I am provisioning everything inside containers so the app itself does not even have visibility into what the actual server IP address I am pointing my browser to really is.

Thoughts?

答:
It turned out that the trick was to use window.location.host in the http string definition.

This version of the environment file seems to be working just fine:

```<code>export const environment = {
  production: true,
  envName: 'prod',
  appserver_env: 'http://' + window.location.host
};
</code>```

Body:
I have a small Angular2 application that works fine locally where I reference localhost. The problem is when I try to provision the application in production (read: on any external host that has to be referenced by its own IP address and/or FQDN).

This is the main part of the app (and where I am struggling with):

public appserver = environment.appserver_env;

getvotes(): void {
    const url = `${this.appserver}/api/getvotes`;
    this.http.get(url)
                .map((res: Response) => res.json())
                .subscribe(res => {console.log(res); this.votes = res})
    }

The appserver_env variable is set inside the Angular environments. Some of them uses localhost such as this and it works just fine:

export const environment = {
  production: false,
  envName: 'test',
  appserver_env: 'http://localhost:4567'
};

Basically I am starting my application and my backend service on my laptop, everything is referenced as localhost and all is fine.

The problem is when I try to deploy onto an external infrastructure (aka host) that has a specific IP / FQDN. My current Angular 2 production environment configuration looks like this:

export const environment = {
  production: true,
  envName: 'prod',
  appserver_env: 'http://myappserver:4567'
};

This only works when I have my client configured in a way that can resolve myappserver to a proper IP address.

The problem is that I may end up having to deploy this app on a server that doesn't have a FQDN (only an IP address). Or anyway in an environment where name resolution does not work.

Is there a particular pattern / feature in Angular 2 that allows me to solve this problem? Note that, to complicate things further, I am provisioning everything inside containers so the app itself does not even have visibility into what the actual server IP address I am pointing my browser to really is.

Thoughts?

Body:
It turned out that the trick was to use window.location.host in the http string definition.

This version of the environment file seems to be working just fine:

export const environment = {
  production: true,
  envName: 'prod',
  appserver_env: 'http://' + window.location.host
};


问:
Start, Pause and Stop a Node.js process/loop
I'm in the process of building a bot that basically fetches images based on a search query(simple string), this bot needs to run 24/7, however multiple bots must be 'spawned' for different accounts, I already have the bot done, it basically takes in a config file and starts looping, however what would be the best approach to pause and stop this process?

I have looked into Node's spawn child functions, i have looked into RxJs's scheduler, but I am not sure which is the best bet, to approach something like this. Any insight would be helpful, thank you!

答: My solution to this particular problem, was to use child_process.fork and fork the secondary automation script, and use the .on('message') to process information back and forth for the state of the process.


问:
Angular 2 router error
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

```<code>import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

2) Appmodule

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

3) AppComponentHTML

```<code><div class="page-wrapper" [ngClass]="{
                                    'sun-background': weatherDesc == 'Clear',
                                    'rain-background': weatherDesc == 'Rain',
                                    'clouds-background': weatherDesc == 'Clouds'
                                      }">
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-12">
        <header>
          <div class="header-wrapper">
            <h3 class=" text-left">Weather App</h3>
            <a routerLink="/city" routerLinkActive="active">cities</a>
            <a routerLink="/weather-list" routerLinkActive="active">weather</a>
            <app-weather-search></app-weather-search>
          </div>
        </header>
      </div>
    </div>
  </div>
  <!--<app-weather-list (notify)="background($event)"></app-weather-list>-->
  <!--<app-weather-list></app-weather-list>-->
  <router-outlet></router-outlet>

</div>
</code>```

答:
It looks as though your routerLinks are not setup correctly in the component html.

Try changing your link tags from ...

```<code><a routerLink="/city" routerLinkActive="active">cities</a>
<a routerLink="/weather-list" routerLinkActive="active">weather</a>
</code>```

To ...

```<code><a [routerLink]="['/city']" routerLinkActive="active">
<a [routerLink]="['/weather-list']" routerLinkActive="active">
</code>```

You might also try removing the .forRoot on your routing module import, I am not sure that it is necessary in this case.

Title: Angular 2 router error

Body:
I created Angular 2 router module but it doen't work at the moment and I get an error when I want to open link /city 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet
Error: Cannot activate an already activated outlet'

But I can open this link manually

Here is the code of:
Router module

import { NgModule }from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {WeatherListComponent} from "../weather-list/weather-list.component";
import {AddedCityComponent} from "../added-city/added-city.component";
import {AppComponent} from "../app.component";

const routes: Routes = [
    { path: '', redirectTo: '/weather-list', pathMatch: 'full'},
    { path: 'city', component: AddedCityComponent },
    { path: 'weather-list',  component: WeatherListComponent }

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

2) Appmodule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MdButtonModule, MdCheckboxModule, MdCardModule, MdInputModule} from '@angular/material';

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

import { AppComponent } from './app.component';
import { WeatherListComponent } from './weather-list/weather-list.component';

import { WeatherService } from './service/weather.service';
import { WeatherSearchComponent } from './weather-search/weather-search.component';
import { CloudsComponent } from './clouds/clouds.component';
import { SunComponent } from './sun/sun.component';
import { RainComponent } from './rain/rain.component';
import { AddedCityComponent } from './added-city/added-city.component';

import { AppRoutingModule } from './service/app.routing';

@NgModule({
  declarations: [
    AppComponent,
    WeatherListComponent,
    AddedCityComponent,
    WeatherSearchComponent,
    CloudsComponent,
    SunComponent,
    RainComponent

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    MdButtonModule,
    MdCardModule,
    MdInputModule,
    NgbModule.forRoot(),
    AppRoutingModule

  ],
  providers: [
    WeatherService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3) AppComponentHTML

Weather App

            cities
            weather
            <app-weather-search></app-weather-search>

  <router-outlet></router-outlet>

Body:
It looks as though your routerLinks are not setup correctly in the component html.

Try changing your link tags from ...

<a routerLink="/city" routerLinkActive="active">cities</a>
<a routerLink="/weather-list" routerLinkActive="active">weather</a>

To ...

<a [routerLink]="['/city']" routerLinkActive="active">
<a [routerLink]="['/weather-list']" routerLinkActive="active">

You might also try removing the .forRoot on your routing module import, I am not sure that it is necessary in this case.


问:
Sleep in JQuery?
greetings all
i want to make JQuery sleep/wait for a second between two functions

```<code>$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();
</code>```

how to do so ?

答:
Here ya go!</p>

```<code>$('#div1').hide();
//sleep or wait or for a sec
setTimeout('moomoo()', 1000);

function moomoo() {
  $("#div2").show();
}
</code>```

Title: Sleep in JQuery?

Body:
greetings all
i want to make JQuery sleep/wait for a second between two functions

$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();

how to do so ?

Body:
Here ya go!

$('#div1').hide();
//sleep or wait or for a sec
setTimeout('moomoo()', 1000);

function moomoo() {
  $("#div2").show();
}


问:
Carbon Difference in Time between two Dates in hh:mm:ss format
I'm trying to figure out how I can take two date time strings that are stored in our database and convert it to a difference in time format of hh:mm:ss.

I looked at diffForHumans, but that does give the format I'd like and returns things like after, ago, etc; which is useful, but not for what I'm trying to do.

The duration will never span days, only a max of a couple hours.

```<code>$startTime = Carbon::parse($this->start_time);
$finishTime = Carbon::parse($this->finish_time);

$totalDuration = $finishTime->diffForHumans($startTime);
dd($totalDuration);

// Have: "21 seconds after"
// Want: 00:00:21
</code>```

答:
```<code>$finishTime->diff($startTime)->format('%H:%I:%S');
// 00:00:21
</code>```

Body:
I'm trying to figure out how I can take two date time strings that are stored in our database and convert it to a difference in time format of hh:mm:ss.

I looked at diffForHumans, but that does give the format I'd like and returns things like after, ago, etc; which is useful, but not for what I'm trying to do.

The duration will never span days, only a max of a couple hours.

$startTime = Carbon::parse($this->start_time);
$finishTime = Carbon::parse($this->finish_time);

$totalDuration = $finishTime->diffForHumans($startTime);
dd($totalDuration);

// Have: "21 seconds after"
// Want: 00:00:21


问:
Subsetting data frame with list of times
I have a df with a time index structured as so:

```<code>                     Sensor  UnitNo
Time
2016-07-28 18:34:44    19.0     1.0
2016-07-28 19:27:39    19.0     1.0
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0
2016-07-21 01:23:30    19.0     1.0
...
</code>```

I want to subset this df with a Series with a time index and a boolean column:

```<code>    Time
2016-07-28    False
2016-07-21    False
2016-07-20     True
</code>```

I want to subset the original df for the True dates in the Series:

```<code>                     Sensor  UnitNo
Time
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0
</code>```

UPDATE
Apologies, when I first asked this question I thought I could easily convert the Series into a list of times, but I have found that problematic for several reasons. So, I updated the question above to resemble the current state of my data. Any help would be appreciated! Thanks in advance.

答:
Use .loc

```<code>df.loc[['2016-07-28', '2016-07-20'],:]
</code>```

UPDATE

Doesn't it work if you use that boolean Series directly as a boolean index to the Dataframe?

```<code>df.loc[bool_series, :]
</code>```

Body:
I have a df with a time index structured as so:

                     Sensor  UnitNo
Time
2016-07-28 18:34:44    19.0     1.0
2016-07-28 19:27:39    19.0     1.0
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0
2016-07-21 01:23:30    19.0     1.0
...

I want to subset this df with a Series with a time index and a boolean column:

    Time
2016-07-28    False
2016-07-21    False
2016-07-20     True

I want to subset the original df for the True dates in the Series:

                     Sensor  UnitNo
Time
2016-07-20 20:45:39    19.0     1.0
2016-07-20 23:05:29    19.0     1.0

UPDATE
Apologies, when I first asked this question I thought I could easily convert the Series into a list of times, but I have found that problematic for several reasons. So, I updated the question above to resemble the current state of my data. Any help would be appreciated! Thanks in advance.

Body:
Use .loc

df.loc[['2016-07-28', '2016-07-20'],:]

UPDATE

Doesn't it work if you use that boolean Series directly as a boolean index to the Dataframe?

df.loc[bool_series, :]


问:
Oracle Query to select only the text between two '-' characters
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

```<code>Description
------------------------------------------
Case 1 - Deleted - The case is closed
</code>```

What I want to have:

```<code>Description
------------------------------------------
Deleted
</code>```

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

```<code>select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );
</code>```

答:
Since INSTR function allows to set what occurrence of any character you want, you can use this to identify the pieces to erase based on the "-" character:

```<code>select  trim(
            replace(
                    replace(
                                description,
                                SUBSTR(description, 1, INSTR(description, '-',1,1)), -- <-- first occurrence of "-"
                                null),
                    SUBSTR(description, INSTR(description, '-',1,2), -- <-- second occurrence of "-"
                    length(description)),
                    null)
        ) as result
from all_cases;
</code>```

Assuming that all your rows follow the same pattern, update all in one call would look something like this:

```<code>update all_cases
set description = trim(
                    replace(
                        replace(description,
                                SUBSTR(description, 1, INSTR(description, '-',1,1)),
                                null),
                        SUBSTR(description, INSTR(description, '-',1,2), length(description)),
                        null)
                    );
</code>```

Which acts just identifying the left and right pieces based in the "-" character and replacing them with null.

ContentLicense: CC BY-SA 4.0

Body:
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

Description
------------------------------------------
Case 1 - Deleted - The case is closed

What I want to have:

Description
------------------------------------------
Deleted

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );

Body:
Since INSTR function allows to set what occurrence of any character you want, you can use this to identify the pieces to erase based on the "-" character:

select  trim(
            replace(
                    replace(
                                description,
                                SUBSTR(description, 1, INSTR(description, '-',1,1)), -- <-- first occurrence of "-"
                                null),
                    SUBSTR(description, INSTR(description, '-',1,2), -- <-- second occurrence of "-"
                    length(description)),
                    null)
        ) as result
from all_cases;

Assuming that all your rows follow the same pattern, update all in one call would look something like this:

update all_cases
set description = trim(
                    replace(
                        replace(description,
                                SUBSTR(description, 1, INSTR(description, '-',1,1)),
                                null),
                        SUBSTR(description, INSTR(description, '-',1,2), length(description)),
                        null)
                    );

Which acts just identifying the left and right pieces based in the "-" character and replacing them with null.


答:
No real sleep, but this will achieve the same goal:

```<code>$('#div1').hide();
//sleep or wait or for a sec
window.setTimeout(function() { $("#div2").show(); }, 1000);
</code>```

Edit: well, I now stand corrected about "real" sleep, however using the setTimeout is still valid "pure JS" solution - your choice. :)

Title: Sleep in JQuery?

Body:
No real sleep, but this will achieve the same goal:

$('#div1').hide();
//sleep or wait or for a sec
window.setTimeout(function() { $("#div2").show(); }, 1000);

Edit: well, I now stand corrected about "real" sleep, however using the setTimeout is still valid "pure JS" solution - your choice. :)


问:
Emit one List item at a time from a Flowable
I have a method which returns a Flowable<RealmResults<MyClass>>. For those not familiar with Realm, RealmResults is just a simple List of items.

Given a Flowable<RealmResults<MyClass>>, I'd like to emit each MyClass item so that I can perform a map() operation on each item.

I am looking for something like the following:

```<code>getItems() // returns a Flowable<RealmResults<MyClass>>
    .emitOneAtATime() // Example operator
    .map(obj -> obj + "")
    // etc
</code>```

What operator will emit each List item sequentially?

答:
The question is, do you want to keep the results as a Flowable<List<MyClass>> or as a Flowable<MyClass> with retained order?

If the first,

```<code>getItems()
.concatMap(results -> Flowable
   .fromIterable(results)
   .map(/* do your mapping */)
   .toList()
)
</code>```

If the second, this should suffice:

```<code>getItems()
.concatMap(Flowable::fromIterable)
.map(/* do your mapping */)
</code>```

Body:
I have a method which returns a Flowable<RealmResults<MyClass>>. For those not familiar with Realm, RealmResults is just a simple List of items.

Given a Flowable<RealmResults<MyClass>>, I'd like to emit each MyClass item so that I can perform a map() operation on each item.

I am looking for something like the following:

getItems() // returns a Flowable<RealmResults<MyClass>>
    .emitOneAtATime() // Example operator
    .map(obj -> obj + "")
    // etc

What operator will emit each List item sequentially?

Body:
The question is, do you want to keep the results as a Flowable<List<MyClass>> or as a Flowable<MyClass> with retained order?

If the first,

getItems()
.concatMap(results -> Flowable
   .fromIterable(results)
   .map(/* do your mapping */)
   .toList()
)

If the second, this should suffice:

getItems()
.concatMap(Flowable::fromIterable)
.map(/* do your mapping */)


问:
Connecting to TortoiseSVN repository using AnkhSVN on VS 2012
I am using AnkhSVN v2.5 and TortoiseSVN 1.9.4

I am not able to browse through the directories on my local drive.

Running as administrator didn't help either. However when using VisualSVN the issue is resolved.
Unfortunately, I can only use AnkhSVN, please help.

答:
TortoiseSVN 1.9.x is based on Subversion 1.9. Local repository it creates and that you access via file:/// has FSFS format 7, by default. This FSFS format is new in SVN 1.9; SVN 1.8 and older clients and servers will not be able to read this repository unless you dump-load its data into an clean repository with older format.

AnkhSVN 2.5.x is based on SVN 1.8 (via SharpSVN) and this explains why it is unable to access this repository. The problem is that AnkhSVN does not display full error message in your case. The error could help you find out what's going on. I'm not sure, but I guess that this is the error that AnkhSVN had to display in your case: svnadmin: E125006: 'REPOS\db\format' contains invalid filesystem format option 'addressing physical'.

These steps should help you solve the problem:

Install VisualSVN Server or another Subversion server on Windows and access your repositories via HTTP(S) or svnserve instead of local file:/// access. The repository internals will not matter for your client in this case as the client will communicate with the server, not with the repository directly. This will help you avoid such problems in future.

Update to AnkhSVN 2.6.x. It should be compatible with SVN 1.9.x and Visual Studio 2012. I guess will access that repository without errors. I'm not sure, but I guess that there is no practical reason to use older AnkhSVN builds.


问:
(Java) BufferedReader of a socket only takes one line at a time, requires client input before receiving the next line
I have a server and a client.

My issue is that my client can only receive one line from the BufferedReader in at a time. To receive the next line, the client must respond. How can I make the client receive all of the input at once? For instance, a multi-line input.

```<code>try (
        Socket socket = new Socket(hostName, portNumber);                   //Connect to server
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);  //The socket output stream sends an output to the server
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));                //The socket input stream receives an output from the server
    ) {
        BufferedReader stdIn =
            new BufferedReader(new InputStreamReader(System.in));           //The BufferedReader allows the client's input to be iterated through
        String fromServer,
               fromUser;

        while ((fromServer = in.readLine()) != null) {                      //while there is an input from the server
            System.out.println("Server: " + fromServer);                    //Print the input

            fromUser = stdIn.readLine();                                    //Receive a line of user input
            if (fromUser != null) {
                System.out.println("Client: " + fromUser);
                out.println(fromUser);                                      //Send it out to the server
            }
        }
    } catch [...]
</code>```

答:
You can use different threads - one to send messages and another to recieve messages.

Client side code:

```<code>class Client5 extends Thread{

static Socket s;
static int end=0;

public void run(){
    String str1;
    //read data coing from server
    try{
        BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
        while(end==0)//recieve from server
        {
            str1=br.readLine();
            System.out.println("from server:"+str1);
        }
        br.close();
    }
    catch(Exception e){
        System.out.println(e);
    }

}

public static void main(String[] args) throws Exception{

    s=new Socket("192.168.43.231",1111);
    //send data to server
    DataOutputStream dos=new DataOutputStream(s.getOutputStream());

    //read from keyboard
    BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));

    String str;

    Client5 read=new Client5();
    read.start();
    //reapea till exit is typed by client
    while(!(str=kb.readLine()).equals("exit")){

        dos.writeBytes(str+"\n");//send to server
    }
    dos.writeBytes(str+"\n");
    end=1;
    s.close();
    dos.close();
    kb.close();
}
</code>```

}

Body:
I have a server and a client.

My issue is that my client can only receive one line from the BufferedReader in at a time. To receive the next line, the client must respond. How can I make the client receive all of the input at once? For instance, a multi-line input.

try (
        Socket socket = new Socket(hostName, portNumber);                   //Connect to server
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);  //The socket output stream sends an output to the server
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));                //The socket input stream receives an output from the server
    ) {
        BufferedReader stdIn =
            new BufferedReader(new InputStreamReader(System.in));           //The BufferedReader allows the client's input to be iterated through
        String fromServer,
               fromUser;

        while ((fromServer = in.readLine()) != null) {                      //while there is an input from the server
            System.out.println("Server: " + fromServer);                    //Print the input

            fromUser = stdIn.readLine();                                    //Receive a line of user input
            if (fromUser != null) {
                System.out.println("Client: " + fromUser);
                out.println(fromUser);                                      //Send it out to the server
            }
        }
    } catch [...]

Body:
You can use different threads - one to send messages and another to recieve messages.

Client side code:

class Client5 extends Thread{

static Socket s;
static int end=0;

public void run(){
    String str1;
    //read data coing from server
    try{
        BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
        while(end==0)//recieve from server
        {
            str1=br.readLine();
            System.out.println("from server:"+str1);
        }
        br.close();
    }
    catch(Exception e){
        System.out.println(e);
    }

}

public static void main(String[] args) throws Exception{

    s=new Socket("192.168.43.231",1111);
    //send data to server
    DataOutputStream dos=new DataOutputStream(s.getOutputStream());

    //read from keyboard
    BufferedReader kb=new BufferedReader(new InputStreamReader(System.in));

    String str;

    Client5 read=new Client5();
    read.start();
    //reapea till exit is typed by client
    while(!(str=kb.readLine()).equals("exit")){

        dos.writeBytes(str+"\n");//send to server
    }
    dos.writeBytes(str+"\n");
    end=1;
    s.close();
    dos.close();
    kb.close();
}

}


问:
Read function arguments in decorator
I have written this decorator that saves intermediate results in a json file

```<code>import json
import os

def json_file(fname):
    def decorator(function):
        def wrapper(*args, **kwargs):
            if os.path.isfile(fname):
                with open(fname, 'r') as f:
                    ret = json.load(f)
            else:
                with open(fname,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator
</code>```

And usage is

```<code>@json_file("cached.json")
def some_calculation(n):
   return {"result": 2**n}
</code>```

And I want to augment in to use the function parameters like this:

```<code>@json_file("cached_{n}.json")
def calculation(n):
    return {"result": 2**n}
</code>```

Such that {n} is replaced with the value of n when calling the function.

I tried replacing fname with fname.format(**kwargs), without any success.

How can this be achieved ?

EDIT:

As Per @jonrshape's comment, this is the error I am getting after adding the .format(**kwargs)

```<code> <ipython-input-4-12b0c894b345> in wrapper(*args, **kwargs)
       5     def decorator(function):
       6         def wrapper(*args, **kwargs):
 ----> 7             fname = fname.format(**kwargs)
       8             if os.path.isfile(fname):
       9                 with open(fname, 'r') as f:

 UnboundLocalError: local variable 'fname' referenced before assignment
</code>```

答:
If n will sometimes be a positional and sometimes be a keyword argument, you can first search the keyword arguments kwargs, and if that fails, "fallback" to getting the value from args:

```<code>def json_file(fname):
    def decorator(function):
        def wrapper(*args, **kwargs):
            try:
                value = kwargs['n']
            except KeyError:
                value = args[0]
            fname.format(value)
            if os.path.isfile(fname):
                with open(fname, 'r') as f:
                    ret = json.load(f)
            else:
                with open(fname,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator
</code>```

Just for sake of completeness, I'll address your error.

The reason your getting an UnboundLocalError error is because of how Python sees your variable definition.

If a variable is already defined in the current scope, assiging the variable to a new value will simply rebind it to the new value. However, if the variable has not yet been defined, Python treats it as a variable definition, not a rebinding.

That is why your code fails. Python expects fname to have been defined in the current scope, not a parent scope. But since fname was never defined, it raised an error.

You can fix this error by using the nonlocal statement. From the docs:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Here is an example of the usage:

```<code>>>> def foo(arg):
    def bar():
        arg += 1
        return arg
    return bar

>>>
>>> foo(0)() # this will raise an error
Traceback (most recent call last):
  File "<pyshell#76>", line 1, in <module>
    foo(0)() # this will raise an error
  File "<pyshell#74>", line 3, in bar
    arg += 1
UnboundLocalError: local variable 'arg' referenced before assignment
>>>
>>> def foo(arg):
    def bar():
        nonlocal arg
        arg += 1
        return arg
    return bar

>>> foo(0)() # this will work
1
>>>
</code>```

Title: Read function arguments in decorator

Body:
I have written this decorator that saves intermediate results in a json file

import json
import os

def json_file(fname):
    def decorator(function):
        def wrapper(*args, **kwargs):
            if os.path.isfile(fname):
                with open(fname, 'r') as f:
                    ret = json.load(f)
            else:
                with open(fname,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator

And usage is

@json_file("cached.json")
def some_calculation(n):
   return {"result": 2**n}

And I want to augment in to use the function parameters like this:

@json_file("cached_{n}.json")
def calculation(n):
    return {"result": 2**n}

Such that {n} is replaced with the value of n when calling the function.

I tried replacing fname with fname.format(**kwargs), without any success.

How can this be achieved ?

EDIT:

As Per @jonrshape's comment, this is the error I am getting after adding the .format(**kwargs)

 <ipython-input-4-12b0c894b345> in wrapper(*args, **kwargs)
       5     def decorator(function):
       6         def wrapper(*args, **kwargs):
 ----> 7             fname = fname.format(**kwargs)
       8             if os.path.isfile(fname):
       9                 with open(fname, 'r') as f:

 UnboundLocalError: local variable 'fname' referenced before assignment

Body:
If n will sometimes be a positional and sometimes be a keyword argument, you can first search the keyword arguments kwargs, and if that fails, "fallback" to getting the value from args:

def json_file(fname):
    def decorator(function):
        def wrapper(*args, **kwargs):
            try:
                value = kwargs['n']
            except KeyError:
                value = args[0]
            fname.format(value)
            if os.path.isfile(fname):
                with open(fname, 'r') as f:
                    ret = json.load(f)
            else:
                with open(fname,'w') as f:
                    ret = function(*args, **kwargs)
                    json.dump(ret, f)
            return ret
        return wrapper
    return decorator

Just for sake of completeness, I'll address your error.

The reason your getting an UnboundLocalError error is because of how Python sees your variable definition.

If a variable is already defined in the current scope, assiging the variable to a new value will simply rebind it to the new value. However, if the variable has not yet been defined, Python treats it as a variable definition, not a rebinding.

That is why your code fails. Python expects fname to have been defined in the current scope, not a parent scope. But since fname was never defined, it raised an error.

You can fix this error by using the nonlocal statement. From the docs:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Here is an example of the usage:

>>> def foo(arg):
    def bar():
        arg += 1
        return arg
    return bar

>>>
>>> foo(0)() # this will raise an error
Traceback (most recent call last):
  File "<pyshell#76>", line 1, in <module>
    foo(0)() # this will raise an error
  File "<pyshell#74>", line 3, in bar
    arg += 1
UnboundLocalError: local variable 'arg' referenced before assignment
>>>
>>> def foo(arg):
    def bar():
        nonlocal arg
        arg += 1
        return arg
    return bar

>>> foo(0)() # this will work
1
>>>


问:
Workaround for lack of support for array constants?
Go doesn't have array constants.

My application receives messages containing several types of numeric codes which I need to display as phrases.

If array contants existed I could do something like:

func foo() {
   ...
   fmt.Println(facename[f])
   ...
}
const facename [...]string = "top", "bottom", "left", "right", "front", "back"
```

<p>But of course there's no way to do this. The first way around this that occurs to me, and maybe a reasonable efficient one is to use a <code>switch</code></p>

<pre class="lang-golang prettyprint-override"><code>func foo() {
   ...
   name := "unknown"
   switch f {
   case 0:
      name = "top"
   case 1:
      name = "bottom"
   case 2:
      name = "left"
   case 3:
      name = "right"
   case 4:
      name = "front"
   case 5:
      name = "back"
   }
   fmt.Println(name)
   ...
}
</code>```

The above is rather tedious if the number of values gets to be twenty or more.

It seems the most concise way is something like

func foo() {
   ...
   fmt.Println(strings.Split(facenames,",")[f])
   ...
}
const facenames = "top,bottom,left,right,front,back"
```

I will also have to check that the index is in range of course.
Although efficiency isn't a concern at the moment, it bugs me that
I'm using strings.Split() more than I want to.

Is there another way that is either idiomatic or both concise and efficient?

答:
It may not be a good fit, but it appears your use case is basically an enum with string equivalents. For this I usually do something along the lines of:

```<code>type Face uint8

const (
    FaceTop Face = iota
    FaceBottom
    FaceLeft
    FaceRight
    FaceFront
    FaceBack
)

func (f Face) String() string {
    switch f {
    case FaceTop: return "top"
    case FaceBottom: return "bottom"
    case FaceLeft: return "left"
    case FaceRight: return "right"
    case FaceFront: return "front"
    case FaceBack: return "back"
    default: return ""  // Or add an error return, or add a zero value to the enum
    }
}

func ParseFace(in string) (Face,error) {
    switch in {
    case "top": return FaceTop,nil
    case "bottom": return FaceBottom,nil
    case "left": return FaceLeft,nil
    case "right": return FaceRight,nil
    case "front": return FaceFront,nil
    case "back": return FaceBack,nil
    default: return "",errors.New("invalid face name"+in)
    }
}
</code>```

Body:
Go doesn't have array constants.

My application receives messages containing several types of numeric codes which I need to display as phrases.

If array contants existed I could do something like:

func foo() {
   ...
   fmt.Println(facename[f])
   ...
}
const facename [...]string = "top", "bottom", "left", "right", "front", "back"

But of course there's no way to do this. The first way around this that occurs to me, and maybe a reasonable efficient one is to use a switch

func foo() {
   ...
   name := "unknown"
   switch f {
   case 0:
      name = "top"
   case 1:
      name = "bottom"
   case 2:
      name = "left"
   case 3:
      name = "right"
   case 4:
      name = "front"
   case 5:
      name = "back"
   }
   fmt.Println(name)
   ...
}

The above is rather tedious if the number of values gets to be twenty or more.

It seems the most concise way is something like

func foo() {
   ...
   fmt.Println(strings.Split(facenames,",")[f])
   ...
}
const facenames = "top,bottom,left,right,front,back"

I will also have to check that the index is in range of course.
Although efficiency isn't a concern at the moment, it bugs me that
I'm using strings.Split() more than I want to.

Is there another way that is either idiomatic or both concise and efficient?

Body:
It may not be a good fit, but it appears your use case is basically an enum with string equivalents. For this I usually do something along the lines of:

type Face uint8

const (
    FaceTop Face = iota
    FaceBottom
    FaceLeft
    FaceRight
    FaceFront
    FaceBack
)

func (f Face) String() string {
    switch f {
    case FaceTop: return "top"
    case FaceBottom: return "bottom"
    case FaceLeft: return "left"
    case FaceRight: return "right"
    case FaceFront: return "front"
    case FaceBack: return "back"
    default: return ""  // Or add an error return, or add a zero value to the enum
    }
}

func ParseFace(in string) (Face,error) {
    switch in {
    case "top": return FaceTop,nil
    case "bottom": return FaceBottom,nil
    case "left": return FaceLeft,nil
    case "right": return FaceRight,nil
    case "front": return FaceFront,nil
    case "back": return FaceBack,nil
    default: return "",errors.New("invalid face name"+in)
    }
}


问:
In Boto3, how to create a Paginator for list_objects with additional keyword arguments?
I'm using a Paginator to iterate over the contents of an S3 bucket (following http://boto3.readthedocs.io/en/latest/guide/paginators.html#creating-paginators):

```<code>    client = boto3.client('s3')
    paginator = client.get_paginator('list_objects')
    page_iterator = paginator.paginate(Bucket=<my_bucket>)

    for page in page_iterator:
        for object in page['Contents']:
            key = object['Key']
</code>```

In this example, the method name 'list_objects' is passed as a string. However, I would actually like to use a 'partial' function list_objects with the keyword argument Prefix="files/", since the objects I'm interested in are in the files/ 'directory' (cf. http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects).

Is this possible? (It's not clear to me from the documentation how to do this; I could do an if key.startswith("files/") in the double for loop, but this does not seem like an elegant solution).

答:
Did you miss this in the same document? Filtering results

S3.Paginator.list_objects.paginate() accepts a Prefix parameter used to filter the paginated results by prefix server-side before sending them to the client:

```<code>client = boto3.client('s3', region_name='us-west-2')
paginator = client.get_paginator('list_objects')
operation_parameters = {'Bucket': 'my-bucket',
                        'Prefix': 'foo/baz'}
page_iterator = paginator.paginate(**operation_parameters)
for page in page_iterator:
    print(page['Contents'])
</code>```

Body:
I'm using a Paginator to iterate over the contents of an S3 bucket (following http://boto3.readthedocs.io/en/latest/guide/paginators.html#creating-paginators):

    client = boto3.client('s3')
    paginator = client.get_paginator('list_objects')
    page_iterator = paginator.paginate(Bucket=<my_bucket>)

    for page in page_iterator:
        for object in page['Contents']:
            key = object['Key']

In this example, the method name 'list_objects' is passed as a string. However, I would actually like to use a 'partial' function list_objects with the keyword argument Prefix="files/", since the objects I'm interested in are in the files/ 'directory' (cf. http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects).

Is this possible? (It's not clear to me from the documentation how to do this; I could do an if key.startswith("files/") in the double for loop, but this does not seem like an elegant solution).

Body:
Did you miss this in the same document? Filtering results

S3.Paginator.list_objects.paginate() accepts a Prefix parameter used to filter the paginated results by prefix server-side before sending them to the client:

client = boto3.client('s3', region_name='us-west-2')
paginator = client.get_paginator('list_objects')
operation_parameters = {'Bucket': 'my-bucket',
                        'Prefix': 'foo/baz'}
page_iterator = paginator.paginate(**operation_parameters)
for page in page_iterator:
    print(page['Contents'])