问:
Disposing of database connection from within WCF
I have a WCF service hosted in IIS:

```<code>[WebServiceLogging]
public class ComplaintService : IComplaintService
</code>```

This service has the WebServiceLogging attribute that does straightforward request/response logging into the database:

```<code>public class WebServiceLoggingAttribute : Attribute, IServiceBehavior {
    SomeDatabaseConnection connection;        // unmanaged resource

    ... interface implementations

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) {
        IDispatchMessageInspector messageInspector = new WebServiceLogger(connection, _operations);
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            foreach (EndpointDispatcher endpointDispatcher in dispatcher.Endpoints)
            {
                DispatchRuntime dispatchRuntime = endpointDispatcher.DispatchRuntime;
                dispatchRuntime.MessageInspectors.Add(messageInspector);    // pass the logger into WCF.
            }
        }
    }
}
</code>```

Logging work is done from the WebServiceLogger, which uses the SomeDatabaseConnection unmanaged resource:

```<code>public class WebServiceLogger : IDispatchMessageInspector {
    public object AfterReceiveRequest {
        ... gather Request data.
    }
    public void BeforeSendReply {
        ... gather Request data.
        ... Log using ADO.NET
        ... Dispose of Command object. No Connection closing!
    }

}
</code>```

I need to close the connection within WebServiceLogger once I'm done with logging. Options I've identified are:

Implement an IDisposable on WebServiceLogging class and do a Dispose() there or

Dispose of SomeDatabaseConnection directly from WebServiceLogger.BeforeSendReply()

My questions here are:

IDispatchMessageInspectors (such as WebServiceLogger) passed into dispatchRuntime.MessageInspectors - I've noticed that this object is not recreated per each request, but rather only once on the first request towards my service. How are such objects disposed of? Does WCF call `Dispose()˙ on them or should I use some other approach here?

Since we're at it, I have a nagging thought that perhaps using unmanaged resources in an Attribute is not such a good idea. Googling for c# attribute dispose didn't yield any results (there is one result on destructor, though). Any critiques on this approach?

答:
Open and close a connection inside the BeforeSendReply method; i.e. make it a local variable (with a using-block, etc.).

Something like this:

```<code>public void BeforeSendReply {
    ... gather Request data.
    using (var conn = new SqlConnection(...)) {
        ... Log using ADO.NET
    }
}
</code>```

The overhead is usually irrelevant (as ADO.NET uses connection pooling and won't really open/close a brand new connection). Second, and most importantly, that way you don't have to think about how your interceptor instance is used/called in a multithreaded (parallel requests) scenario.

That also matches better the unit of work pattern, that would be typically used if you did the same thing in the implementation method of an OperationContract. If you think about it, the interceptor points (AfterReceiveRequest and BeforeSendReply) are really just extensions of such method implementations (kind of AOP).

Body:
I have a WCF service hosted in IIS:

[WebServiceLogging]
public class ComplaintService : IComplaintService

This service has the WebServiceLogging attribute that does straightforward request/response logging into the database:

public class WebServiceLoggingAttribute : Attribute, IServiceBehavior {
    SomeDatabaseConnection connection;        // unmanaged resource

    ... interface implementations

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) {
        IDispatchMessageInspector messageInspector = new WebServiceLogger(connection, _operations);
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            foreach (EndpointDispatcher endpointDispatcher in dispatcher.Endpoints)
            {
                DispatchRuntime dispatchRuntime = endpointDispatcher.DispatchRuntime;
                dispatchRuntime.MessageInspectors.Add(messageInspector);    // pass the logger into WCF.
            }
        }
    }
}

Logging work is done from the WebServiceLogger, which uses the SomeDatabaseConnection unmanaged resource:

public class WebServiceLogger : IDispatchMessageInspector {
    public object AfterReceiveRequest {
        ... gather Request data.
    }
    public void BeforeSendReply {
        ... gather Request data.
        ... Log using ADO.NET
        ... Dispose of Command object. No Connection closing!
    }

}

I need to close the connection within WebServiceLogger once I'm done with logging. Options I've identified are:

Implement an IDisposable on WebServiceLogging class and do a Dispose() there or

Dispose of SomeDatabaseConnection directly from WebServiceLogger.BeforeSendReply()

My questions here are:

IDispatchMessageInspectors (such as WebServiceLogger) passed into dispatchRuntime.MessageInspectors - I've noticed that this object is not recreated per each request, but rather only once on the first request towards my service. How are such objects disposed of? Does WCF call `Dispose()˙ on them or should I use some other approach here?

Since we're at it, I have a nagging thought that perhaps using unmanaged resources in an Attribute is not such a good idea. Googling for c# attribute dispose didn't yield any results (there is one result on destructor, though). Any critiques on this approach?

Body:
Open and close a connection inside the BeforeSendReply method; i.e. make it a local variable (with a using-block, etc.).

Something like this:

public void BeforeSendReply {
    ... gather Request data.
    using (var conn = new SqlConnection(...)) {
        ... Log using ADO.NET
    }
}

The overhead is usually irrelevant (as ADO.NET uses connection pooling and won't really open/close a brand new connection). Second, and most importantly, that way you don't have to think about how your interceptor instance is used/called in a multithreaded (parallel requests) scenario.

That also matches better the unit of work pattern, that would be typically used if you did the same thing in the implementation method of an OperationContract. If you think about it, the interceptor points (AfterReceiveRequest and BeforeSendReply) are really just extensions of such method implementations (kind of AOP).


来源: stackexchange

问:
PHPhotoLibrary - photoLibraryDidChange called multiple times in Swift
I have the following code:

```<code>override func viewDidLoad() {
    ........
    PHPhotoLibrary.shared().register(self)
}
</code>```

and I've implemented the PHPhotoLibraryDidChangeObserver.

My problem is, that the method photoLibraryDidChange gets called multiple times if something in the device's gallery changes.

Here is the code for that function:

```<code>func photoLibraryDidChange(_ changeInstance: PHChange) {
    DispatchQueue.main.async(execute: {
        self.updateFetchResult();
    })
}
</code>```

Do you know why this method gets executed multiple times?

答:
Did you find a solution?
This solve mi problem:

First, save your PHFetResult<PHAsset> when calling PHAsset.fetchAssets(with:options:) if your using this method.

After that, use your PHFetResult<PHAsset> variable to validate if the fetch result has changes in the photoLibraryDidChange: method. The first time this method is called, you have to update to collection view or table view. After that, your fetch result has not changes so... you have nothing to update.

This is my full code:

```<code>let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

self.fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

.
.
.

extension YourViewController: PHPhotoLibraryChangeObserver {

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        if let _fetchResult = self.fetchResult, let _ = changeInstance.changeDetails(for: _fetchResult) {
            DispatchQueue.main.async {
                self.getPhotos()
            }
        }
    }

}
</code>```

Hope this help you!

ContentLicense: CC BY-SA 3.0

Body:
I have the following code:

override func viewDidLoad() {
    ........
    PHPhotoLibrary.shared().register(self)
}

and I've implemented the PHPhotoLibraryDidChangeObserver.

My problem is, that the method photoLibraryDidChange gets called multiple times if something in the device's gallery changes.

Here is the code for that function:

func photoLibraryDidChange(_ changeInstance: PHChange) {
    DispatchQueue.main.async(execute: {
        self.updateFetchResult();
    })
}

Do you know why this method gets executed multiple times?

Body:
Did you find a solution?
This solve mi problem:

First, save your PHFetResult<PHAsset> when calling PHAsset.fetchAssets(with:options:) if your using this method.

After that, use your PHFetResult<PHAsset> variable to validate if the fetch result has changes in the photoLibraryDidChange: method. The first time this method is called, you have to update to collection view or table view. After that, your fetch result has not changes so... you have nothing to update.

This is my full code:

let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

self.fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

.
.
.

extension YourViewController: PHPhotoLibraryChangeObserver {

    func photoLibraryDidChange(_ changeInstance: PHChange) {
        if let _fetchResult = self.fetchResult, let _ = changeInstance.changeDetails(for: _fetchResult) {
            DispatchQueue.main.async {
                self.getPhotos()
            }
        }
    }

}

Hope this help you!


问:
How do I edit the Bot Code c# after its published in Azure
I created a bot in the Azure bot framework.  It's a Qna one.

It works, I can see it in the webchat, I can see it in my bots of bot framework page, I can see the qna data source in qnamaker.

When I go to azure and look at the resources and click on my bot service, it takes me to the Create Page,  well I don't want to create, I want to get to the code of the existing bot, I can't figure out how, some of the props are editable in the bot framework site, but not the code.

I did not configure continuous integration. Or download the code as it was boiler plate, but I want to poke at it now.

答:
Develop with Azure Bot Service > Set up continuous integration

Within your Azure bot, click the Settings tab and expand the Continuous integration section.

Click the link to download the zip file that contains the source code for your bot.

Extract the contents of the downloaded zip file to the local folder where you are planning to sync your deployment source.

(source: microsoft.com)

ContentLicense: CC BY-SA 4.0


问:
Checking OpenGL resource leaks
So I have a rather large openGL program going, and checking for normal memory leaks (those by new and delete) is rather trivial -- just run it on valgrind.

But what is the best way to check for potential opengl leaks? Is there an opengl utility that'll tell you how many resources (e.g framebuffers) are being used at the time, or such? Or is the only way to attach a counter to every glGenBlah and glDeleteBlah pairs?

答: glIntercept does check for textures that haven't been freed, perhaps it also checks framebuffers, but if not, maybe could be easily modified to do it.</p>

ContentLicense: CC BY-SA 2.5

Title: Checking OpenGL resource leaks


问:
MdDialog with Angular 4
I am trying to use MdDialog in Angular 4.

Dialog html:

```<code><div style="width: 100%">
    <h2>Dialog</h2>
    <button md-raised-button (click)="dialogRef.close()">Close dialog</button>
</div>
</code>```

Dialog Component:

```<code>import { Component, OnInit } from '@angular/core';
import { MdDialogRef } from "@angular/material";

@Component({
    selector: 'your-dialog-selector',
    templateUrl: './dialog.component.html'
})
export class DialogComponent {
    constructor(public dialogRef: MdDialogRef<any>) {
    }
}
</code>```

Calling html:

```<code><md-icon class="demo-dialog-open-button" (click)="open()">
                view_list
            </md-icon>
</code>```

Calling component function:

```<code>open() {
        this.dialogRef = this.dialog.open(DialogComponent);

        this.dialogRef.afterClosed().subscribe(result => {
            this.dialogRef = null;
        });
    }
</code>```

app.material.module:

```<code>import { NgModule } from '@angular/core';
import {
    MdToolbarModule,
    MdIconModule,
    MdMenuModule,
    MdButtonModule,
    MdSelectModule,
    MdSnackBarModule,
    MdSnackBar,
    MdInputModule,
    MdTooltipModule,
    MdCardModule,
    MdDialogModule
} from '@angular/material';

@NgModule({
    imports: [
        MdToolbarModule,
        MdButtonModule,
        MdIconModule,
        MdMenuModule,
        MdSelectModule,
        MdSnackBarModule,
        MdInputModule,
        MdTooltipModule,
        MdCardModule,
        MdDialogModule
    ],
    exports: [
        MdToolbarModule,
        MdButtonModule,
        MdIconModule,
        MdMenuModule,
        MdSelectModule,
        MdSnackBarModule,
        MdInputModule,
        MdTooltipModule,
        MdCardModule,
        MdDialogModule
    ],
    providers: [
        MdSnackBar
    ]
})
export class AppMaterialModule {}
</code>```

The problem I am having is that, the dialog opens as a vertical blank white box on the left of the screen. Inspect element shows this:

```<code><md-dialog-container class="mat-dialog-container ng-tns-c7-4 ng-trigger ng-trigger-slideDialog" role="dialog" style="transform: none; opacity: 1;"><!--bindings={
  "ng-reflect-portal": ""
}--></md-dialog-container>
</code>```

Why is it not showing the content of my dialog html?

答:
you should have forgotten to add DialogComponent as entryComponents in respective NgModule

```<code>  entryComponents:[DialogComponent]
</code>```

Check this Plunker!!

Title: MdDialog with Angular 4

Body:
I am trying to use MdDialog in Angular 4.

Dialog html:

Dialog

    <button md-raised-button (click)="dialogRef.close()">Close dialog</button>

Dialog Component:

import { Component, OnInit } from '@angular/core';
import { MdDialogRef } from "@angular/material";

@Component({
    selector: 'your-dialog-selector',
    templateUrl: './dialog.component.html'
})
export class DialogComponent {
    constructor(public dialogRef: MdDialogRef<any>) {
    }
}

Calling html:

<md-icon class="demo-dialog-open-button" (click)="open()">
                view_list
            </md-icon>

Calling component function:

open() {
        this.dialogRef = this.dialog.open(DialogComponent);

        this.dialogRef.afterClosed().subscribe(result => {
            this.dialogRef = null;
        });
    }

app.material.module:

import { NgModule } from '@angular/core';
import {
    MdToolbarModule,
    MdIconModule,
    MdMenuModule,
    MdButtonModule,
    MdSelectModule,
    MdSnackBarModule,
    MdSnackBar,
    MdInputModule,
    MdTooltipModule,
    MdCardModule,
    MdDialogModule
} from '@angular/material';

@NgModule({
    imports: [
        MdToolbarModule,
        MdButtonModule,
        MdIconModule,
        MdMenuModule,
        MdSelectModule,
        MdSnackBarModule,
        MdInputModule,
        MdTooltipModule,
        MdCardModule,
        MdDialogModule
    ],
    exports: [
        MdToolbarModule,
        MdButtonModule,
        MdIconModule,
        MdMenuModule,
        MdSelectModule,
        MdSnackBarModule,
        MdInputModule,
        MdTooltipModule,
        MdCardModule,
        MdDialogModule
    ],
    providers: [
        MdSnackBar
    ]
})
export class AppMaterialModule {}

The problem I am having is that, the dialog opens as a vertical blank white box on the left of the screen. Inspect element shows this:

<md-dialog-container class="mat-dialog-container ng-tns-c7-4 ng-trigger ng-trigger-slideDialog" role="dialog" style="transform: none; opacity: 1;"></md-dialog-container>

Why is it not showing the content of my dialog html?

Body:
you should have forgotten to add DialogComponent as entryComponents in respective NgModule

  entryComponents:[DialogComponent]

Check this Plunker!!


问:
How to format (really) big numbers in Javascript?
I want something like the library JavaScript BigNum and Numeral.js working together.

In Numeral.js, I can use strings like this:

```<code>var number = numeral('1110000000000000000000000000000000000000000000000000011100000000000000000011111111100');
</code>```

but the result of number.format(); is really disappointing:

```<code>"1.11e+84"
</code>```

Any way to format a (really) big number nicely?

EDIT: I don't want just avoid scientific notation, it was a wrong assumption. I want to "nicely" format, as I want, for example:

```<code>var number = numeral(1000);
numeral.defaultFormat('$0,0.00');

number.format();
// '$1,000.00'
</code>```

Well, if the number is big:

```<code>var number = numeral('100000000000000000000000000');
"$9.999999999999999e+25"
</code>```

This is a mess. I know JavaScript can't handle big numbers, but my question is exactly because that! I would like a library or a possible solution to this problem.

答:
If you are supporting only recent browsers, I think it might be enough for you to just use Intl.NumberFormat.

Although you it lose precision on big numbers, it will help you show big numbers and currencies pretty easily:

var number = 1234567890123456789012345678901234567890;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
// → 1.234.567.890.123.460.000.000.000.000.000.000.000.000,00 €

console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number));
// → ￥1,234,567,890,123,460,000,000,000,000,000,000,000,000```

Body:
I want something like the library JavaScript BigNum and Numeral.js working together.

In Numeral.js, I can use strings like this:

var number = numeral('1110000000000000000000000000000000000000000000000000011100000000000000000011111111100');

but the result of number.format(); is really disappointing:

"1.11e+84"

Any way to format a (really) big number nicely?

EDIT: I don't want just avoid scientific notation, it was a wrong assumption. I want to "nicely" format, as I want, for example:

var number = numeral(1000);
numeral.defaultFormat('$0,0.00');

number.format();
// '$1,000.00'

Well, if the number is big:

var number = numeral('100000000000000000000000000');
"$9.999999999999999e+25"

This is a mess. I know JavaScript can't handle big numbers, but my question is exactly because that! I would like a library or a possible solution to this problem.


问:
Nginx not logging all access in access.log (missing data of redirected requests)
In Nginx I have a redirection of all incoming http traffic to the same url but with https.
When I check the access log I only see the 301 error, but not the following petition, that can be a 200 or a 404 or whatever.

How can I see that information in the logs of Nginx?

All I want to see is what happen after you get redirected, because the redirection may work but the underlying url may not, and as of now I can only know what works by trying myself (and that doesn't mean that in a moment someone can get another different response because of who knows)

答:
The following requests should be in same access.log file. The only note is that they will not follow each other.

301 response is returned to browser and then it determine follow propose URL or not. And this is not happen imediately. So after initial 301 log record folowing request may be logged after 10, 100 or even 1000 non-related log message. All is depend on trafic and how many logs you have for single page.


问:
.htaccess rewrite rule case sensitive
I have the following rewrite rule:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ /pages/acticle.$1.php [L]
</code>```

Currently it is case sensitive. I need to remove this restriction. I've tried changing [L] to [NC,L] but it didn't work. What am I missing?

答:
Your pattern doesn't contain any cased characters, so adding NC will have no effect. If your RewriteRule was for ^abcde and you wanted it to also match ABCDE then adding NC to the rule would do this.

The pattern in your example matches any character that is not a . or / one or more times, and then adds it to the article.$1.php result. By default it will take whatever is matched directly so abc=article.abc.php, ABC=article.ABC.php, and so on.

I'm guessing that all of your article file names are in lowercase and that you want to rewrite ABC and AbC to abc, resulting in consistent naming for the files - both get article.abc.php. If so, there are a few options listed on this page - use a loop in .htaccess to replace uppercase with lowercase before continuing, use a RewriteMap in your http.conf, or use mod_speling.

Title: .htaccess rewrite rule case sensitive

Body:
I have the following rewrite rule:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ /pages/acticle.$1.php [L]

Currently it is case sensitive. I need to remove this restriction. I've tried changing [L] to [NC,L] but it didn't work. What am I missing?


问:
Mysql Join multiple Table error: not unique table/alias
Joins have always been touchy for me.
I am trying to grab multiple columns from multiple tables.
My left join for product p num table causes error: Error Code: 1066. Not unique table/alias: 'product p num'

I've seen this error show up for other stackoverflow examples. I tried modifying various versions but not sure what piece I am missing.

```<code>SELECT tbls.SNum,tblmar.AssemPart, tblmar.wifi, `product p num`.`Customer Name`

FROM floor.tbls, manu.tblmar, def.`product p num`

LEFT JOIN tblmar ON tbls.PartNum = tblmar.AssemPart
LEFT JOIN `product p num` on tblmar.AssemPart = `product p num`.`product p`

WHERE tblmar.AssemPart IS NOT NULL
AND `product p num`.`Customer Name` = 'Google'
AND tblmar.wifi = 1
ORDER BY `product p num`.`product p`;
</code>```

答:
You are doing a query that references the same table twice.

If you want to do this, you need to alias those tables. Example:

```<code>SELECT *
FROM table AS alias1
LEFT JOIN table AS alias2
</code>```

Body:
Joins have always been touchy for me.
I am trying to grab multiple columns from multiple tables.
My left join for product p num table causes error: Error Code: 1066. Not unique table/alias: 'product p num'

I've seen this error show up for other stackoverflow examples. I tried modifying various versions but not sure what piece I am missing.

SELECT tbls.SNum,tblmar.AssemPart, tblmar.wifi, `product p num`.`Customer Name`

FROM floor.tbls, manu.tblmar, def.`product p num`

LEFT JOIN tblmar ON tbls.PartNum = tblmar.AssemPart
LEFT JOIN `product p num` on tblmar.AssemPart = `product p num`.`product p`

WHERE tblmar.AssemPart IS NOT NULL
AND `product p num`.`Customer Name` = 'Google'
AND tblmar.wifi = 1
ORDER BY `product p num`.`product p`;

Body:
You are doing a query that references the same table twice.

If you want to do this, you need to alias those tables. Example:

SELECT *
FROM table AS alias1
LEFT JOIN table AS alias2


问:
Change the value of multiple h1 & h2 elements with Vanilla JS
I am looking to loop through and update the text within the  and  elements on the website. I have tried the below but it doesn't update the H1 tag.

```<code>document.getElementsByTagName("H1").innerHTML = "My New H1";

document.getElementsByTagName("H1")[0].innerHTML = "My New H1";
</code>```

I also need to be able to get the number of  elements on the page and also loop through each of them and update them? How would you do this within Vanilla JS? It cannot use jQuery.

答:
In case you have more of one tag Hx, use for() to iterate through the collection.

```<code>var tagsh1 = document.querySelectorAll('h1');
for(var i=0; i<tagsh1.length; i++){
  tagsh1[i].innerHTML ='some text';
}
</code>```

Body:
I am looking to loop through and update the text within the  and  elements on the website. I have tried the below but it doesn't update the H1 tag.

document.getElementsByTagName("H1").innerHTML = "My New H1";

document.getElementsByTagName("H1")[0].innerHTML = "My New H1";

I also need to be able to get the number of  elements on the page and also loop through each of them and update them? How would you do this within Vanilla JS? It cannot use jQuery.

Body:
In case you have more of one tag Hx, use for() to iterate through the collection.

var tagsh1 = document.querySelectorAll('h1');
for(var i=0; i<tagsh1.length; i++){
  tagsh1[i].innerHTML ='some text';
}


答:
```<code>document.getElementsByTagName("H1")[0].innerHTML = "My New H1";
</code>```

The above code should work on your first h1 tag node.

To loop through all the h1 elements, you could use forEach function.

```<code>var h1 = document.getElementsByTagName("h1");
h1.forEach((d,i)=>d.innerText = "New h1 text " + i);
</code>```

Title: Change the value of multiple h1 & h2 elements with Vanilla JS

Body:
document.getElementsByTagName("H1")[0].innerHTML = "My New H1";

The above code should work on your first h1 tag node.

To loop through all the h1 elements, you could use forEach function.

var h1 = document.getElementsByTagName("h1");
h1.forEach((d,i)=>d.innerText = "New h1 text " + i);


答:
May be you have error in other code. This should work

```<code>document.getElementsByTagName("h1")[0].innerHTML = "My New H1";
</code>```

You can also use querySelectorAll

```<code>document.querySelectorAll("h1")[0].innerHTML = "My New H1";
</code>```

querySelectorAll and getElementsByTagName are not case-sensitive so it should work H1 and h1

For looping you can use (ES5):

```<code>var elems = document.querySelectorAll('h1');
if (elems.length) {
  for(var i=0; i<elems.length; i++){
    elems[i].innerHTML = 'text';
  }
}
</code>```

Body:
May be you have error in other code. This should work

document.getElementsByTagName("h1")[0].innerHTML = "My New H1";

You can also use querySelectorAll

document.querySelectorAll("h1")[0].innerHTML = "My New H1";

querySelectorAll and getElementsByTagName are not case-sensitive so it should work H1 and h1

For looping you can use (ES5):

var elems = document.querySelectorAll('h1');
if (elems.length) {
  for(var i=0; i<elems.length; i++){
    elems[i].innerHTML = 'text';
  }
}


问:
Laravel morph belongs to?
I've got a situation where multiple tables have a belongsTo relationship to a category table in laravel 5.4.

So I thought about this structure:

User table:

```<code>id
name
email
category_id   <--
</code>```

Category table

```<code>id
model_type
name
</code>```

Is this possible with a morph relationship?

答:
This would not be since model_type is just a constraint of which categories are available for which models.  If you set it up like that you would add that constraint on each model's relation like:

```<code>class User extends Model
{
    // User class

    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}
</code>```

Or since you have many models that belong to Category you could take that one step further and use a trait for the relation and place the trait on each model that belongs to Category:

```<code>trait BelongsToCategory()
{
    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

class User extends Model
{
    use BelongsToCategory;

    // User class
}
</code>```

Title: Laravel morph belongs to?

Body:
I've got a situation where multiple tables have a belongsTo relationship to a category table in laravel 5.4.

So I thought about this structure:

User table:

id
name
email
category_id   <--

Category table

id
model_type
name

Is this possible with a morph relationship?

Body:
This would not be since model_type is just a constraint of which categories are available for which models.  If you set it up like that you would add that constraint on each model's relation like:

class User extends Model
{
    // User class

    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

Or since you have many models that belong to Category you could take that one step further and use a trait for the relation and place the trait on each model that belongs to Category:

trait BelongsToCategory()
{
    public function category()
    {
        return $this->belongsTo(Category::class)->where('model_type', '=', static::class);
    }
}

class User extends Model
{
    use BelongsToCategory;

    // User class
}


问:
.htaccess not working even with AllowOverride set to All
I have a project with codeigniter that works completely fine on the localhost, no errors at all. But after hosting it with Amazon EC2, i keep getting the "404 page not found" error. I have changed AllowOverride to All and I almost sure that my htaccess file is being used because I put jibberish in it and it resulted in an "Internal server error". I would appreciate any help i can get.</p>

答: I was able to fix my issue but i am not really sure what the problem might have been. All I did was re-download a new Codeigniter folder on my localhost and replace most of the folders in my project with the one i downloaded (apart from Application and vendor). I also changed the name of my controller from 'main.php' to 'Main.php'. Thats all i did and now it works. Thank you to those who tried to help.</p>


答:
The problem is because you're joining the same tables multiple times without aliasing any of them. Did you mean to join them twice? I can't see why you would have intentionally done that here.

The logic you want is likely this:

```<code>SELECT
  tbls.SNum
  , tblmar.AssemPart
  , tblmar.wifi
  , `product p num`.`Customer Name`
FROM
  floor.tbls
  LEFT JOIN tblmar
    ON tbls.PartNum = tblmar.AssemPart
  LEFT JOIN `product p num`
    on tblmar.AssemPart = `product p num`.`product p`
WHERE
  tblmar.AssemPart IS NOT NULL
  AND `product p num`.`Customer Name` = 'Google'
  AND tblmar.wifi = 1
ORDER BY
  `product p num`.`product p`;
</code>```

Title: Mysql Join multiple Table error: not unique table/alias

Body:
The problem is because you're joining the same tables multiple times without aliasing any of them. Did you mean to join them twice? I can't see why you would have intentionally done that here.

The logic you want is likely this:

SELECT
  tbls.SNum
  , tblmar.AssemPart
  , tblmar.wifi
  , `product p num`.`Customer Name`
FROM
  floor.tbls
  LEFT JOIN tblmar
    ON tbls.PartNum = tblmar.AssemPart
  LEFT JOIN `product p num`
    on tblmar.AssemPart = `product p num`.`product p`
WHERE
  tblmar.AssemPart IS NOT NULL
  AND `product p num`.`Customer Name` = 'Google'
  AND tblmar.wifi = 1
ORDER BY
  `product p num`.`product p`;


问:
How many users is too much when using session variables?
I'm currently using session variables as a cache to cut down the calls to the database.

I'm wondering at about how many concurrent users does this stop working at? 1,000, 10,000 ....100,000??? Also will iis start flaking out at a certain load? And are there
any alternatives?

I know it depends on how much data I'm storing per user, but I want to hear from other peoples experiences.

I do have it setup so that when the code tries to access a timed out session that it reloads from the database.

I'm currently using iis6 but I could easily use iis7 if it handles sessions better.

Edit: Yes I'm using application variables for non user specific data.

答:
How about using the Cache instead, it allows automatic cache invalidation.

Cache invalidation can be done both based on a timeout and due to it being "kicked out" due to ressources.

You can use the Cache on a per-user-basis by giving each item a user specific key.

OwnerDisplayName: Donny V

LastEditorDisplayName: Donny V

OwnerDisplayName: veggerby


问:
Deployment error
Hi all i am getting deployment error when i try to run my app in the device. it says "no provisioning ios devices are connected".
I have ios sdk 4.1 installed on my mac and in the device the version of ios is 4.2. I have conected my device to Mac.

Can i run my app under these conditions or i need to update ios sdk to 4.2 in Mac also.

if yes then is there any update available so that i can update my sdk from version 4.1 to 4.2 or i have to download the whole new version of 4.2 (almost 3.5 GB).

Please help.

答:
No. The testing device's version canNOT be higher than your Xcode's version.

I think you'll have to download the entire new one since Xcode doesn't provide a way to just update. (If I was wrong, please correct me)

Title: Deployment error


问:
Swagger-UI not appearing properly
Why does my Swagger UI look different?

This is what I have:

This is what I would like to have:

In order to get Swagger-UI working, all i did was download the project(https://github.com/swagger-api/swagger-ui), take all the contents in the dist folder and put it in the webapp folder of my dynamic web project. After doing this, I updated the index.html to point to my swagger.json. After this was done, I was able to see the first picture shown. However, the large execute button is not all that appealing :( How do i get my swagger page to look like the second picture shown?

答:
The first image is Swagger UI ver. 3.x or 4.x (the curent version). The second image is Swagger UI ver. 2 (old version, no longer developed).

If you want to use version 2 for some reason, you can download it from the 2.x branch of the Swagger UI repository:

https://github.com/swagger-api/swagger-ui/tree/2.x

Title: Swagger-UI not appearing properly


问:
How to "Unlock Jenkins"?
I am installing Jenkins 2 on windows,after installing,a page is opened,URL is:

http://localhost:8080/login?from=%2F

content of the page is like this:

Question:

How to "Unlock Jenkins"?

PS:I have looked for the answer in documentation and google.

答:
Use a lil shortcut to get to the folder:

cmd + shift + g

then insert /Users/Shared/Jenkins

there u can see the secrets folder - probably shows that it's locked.

to unlock it: right click on the folder and click info + click on the lock at the bottom. now u can change the rights shown at the bottom of the window

hope that helped :)

Greetings, Stefanie ^__^

Title: How to "Unlock Jenkins"?


问:
Condensing bunch of if-else statements in JS
I have a ton of if else statements, all changing the value of an object depending on their condition. I would like to know if there is another way to write this code so it can be condensed/simplified and doesn't take up do much space. I have the following code:

```<code>if (inputOne == "Yes") {
    inputOne = "517"
} else {
    inputOne = "518"
}
if (inputTwo == "Yes") {
    inputTwo = "518"
} else{
    inputTwo = "519"
}
if (inputThree == "Yes") {
    inputThree = "519"
} else {
    inputThree = "520"
}
if (inputFour == "Yes") {
    inputFour = "520"
} else {
    inputFour = "521"
}
</code>```

And so on... I will be changing the value of multiple objects based on their inputs. Are there any other ways to write this in JavaScript that could save time or make it look cleaner?

答:
To start you can use a ternary operator.

```<code>inputOne = inputOne == "Yes" ? "517" : "518";
</code>```

Then you could create a function that you can reuse, like...

```<code>function setInputValue(input, yes, no) {
    input = input == "Yes" ? yes : no;
}
</code>```

and invoke it like...

```<code>setInputValue(inputOne, "517", "518");
setInputValue(inputTwo, "518", "519");
</code>```

Body:
I have a ton of if else statements, all changing the value of an object depending on their condition. I would like to know if there is another way to write this code so it can be condensed/simplified and doesn't take up do much space. I have the following code:

if (inputOne == "Yes") {
    inputOne = "517"
} else {
    inputOne = "518"
}
if (inputTwo == "Yes") {
    inputTwo = "518"
} else{
    inputTwo = "519"
}
if (inputThree == "Yes") {
    inputThree = "519"
} else {
    inputThree = "520"
}
if (inputFour == "Yes") {
    inputFour = "520"
} else {
    inputFour = "521"
}

And so on... I will be changing the value of multiple objects based on their inputs. Are there any other ways to write this in JavaScript that could save time or make it look cleaner?

Body:
To start you can use a ternary operator.

inputOne = inputOne == "Yes" ? "517" : "518";

Then you could create a function that you can reuse, like...

function setInputValue(input, yes, no) {
    input = input == "Yes" ? yes : no;
}

and invoke it like...

setInputValue(inputOne, "517", "518");
setInputValue(inputTwo, "518", "519");


问:
iOS/Obj-C: Two MKMapViews, one MapView's annotations not executing?
I have two separate mapviews inside of one ViewController. Each mapview shows a different set of annotations - one map shows strangers locations, the other map shows friend locations. When I tap an annotation on the first mapview (mapView), I get a detail view with the correct user data. However, when I tap an annotation on the second map view (friendsMapView), the data is being pulled from the dictionary populating the first mapView. After logging the error, I discovered that didSelectAnnotation for friendsMapView is never executed? How can I fix this?

Code not being executed (EDIT):

```<code>- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {

    if (self.mapView == self.mapView) {
        // Do something specific to self.mapView

        PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

        NSMutableDictionary *dictionary = self.addressData[selectedPoint.index];
        yourViewController.mapuserData = dictionary;

        [self.navigationController pushViewController:yourViewController animated:YES];

    } else if (self.mapView == self.friendsMapView) {
        // Do something specific to self.friendsMapView

        PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

        NSMutableDictionary *dictionary = self.friendData[selectedPoint.index];
        yourViewController.mapuserData = dictionary;

        [self.navigationController pushViewController:yourViewController animated:YES];

    }

    }
</code>```

Full code: MapViewController.m

```<code>- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{

    if (self.mapView == self.mapView) {

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1300, 1300);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

    } else if (self.mapView == self.friendsMapView) {

        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1300, 1300);
        [self.friendsMapView setRegion:[self.friendsMapView regionThatFits:region] animated:YES];

    }

}

    - (NSString *)deviceLocation {
        return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
    }
    - (NSString *)deviceLat {
        return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.latitude];
    }
    - (NSString *)deviceLon {
        return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.longitude];
    }
    - (NSString *)deviceAlt {
        return [NSString stringWithFormat:@"%f", self.locationManager.location.altitude];
    }

        NSMutableDictionary *viewParams = [NSMutableDictionary new];
        [viewParams setValue:@"u000" forKey:@"view_name"];
        [DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {

            self.addressData = [responseObject mutableCopy];

            NSLog(@"%@", responseObject);

            int index = 0;   //Index to track the data source index while select the annotation call out view.

            for (NSMutableDictionary *multiplelocations in self.addressData) {

                NSString *location = multiplelocations[@"street_address"];
                NSLog(@"Pull addresses %@", location);
                NSString *userNames = multiplelocations[@"users_name"];
                NSString *userBio = multiplelocations[@"userbio"];

                CLGeocoder *geocoder = [[CLGeocoder alloc] init];

                [geocoder geocodeAddressString:location
                             completionHandler:^(NSArray* placemarks, NSError* error){
                                 if (placemarks && placemarks.count > 0) {
                                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];

                                     MKCoordinateRegion region = self.mapView.region;

                                     region.span.longitudeDelta /= 8.0;
                                     region.span.latitudeDelta /= 8.0;

                                     PointAnnotation *point = [[PointAnnotation alloc] init];
                                     point.coordinate = placemark.coordinate;
                                     point.title = userNames;
                                     point.subtitle = userBio;
                                     point.index = index;  // Store index here.

                                     [self.mapView addAnnotation:point];
                                 }
                             }
                 ];
                index = index + 1;
            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failure: %@", [error localizedDescription]);
        }];

        NSMutableDictionary *viewParamsFriend = [NSMutableDictionary new];
        [viewParamsFriend setValue:@"accepted_friends" forKey:@"view_name"];
        [DIOSView viewGet:viewParamsFriend success:^(AFHTTPRequestOperation *operation, id responseObject) {

            self.friendData = [responseObject mutableCopy];

            NSLog(@"THIS IS FRIEND DATA %@", self.friendData);

            int index = 0;

            for (NSMutableDictionary *multiplelocationsFriend in self.friendData) {

                NSString *location = multiplelocationsFriend[@"address2"];
                NSString *userNames = multiplelocationsFriend[@"node_title"];
                NSString *userBio = multiplelocationsFriend[@"body"];

                       NSLog(@"LOCATION IS HERE %@", location);

                CLGeocoder *geocoderFriend = [[CLGeocoder alloc] init];
                [geocoderFriend geocodeAddressString:location
                             completionHandler:^(NSArray* placemarks, NSError* error){
                                 if (placemarks && placemarks.count > 0) {
                                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];

                                     MKCoordinateRegion region = self.friendsMapView.region;

                                     region.span.longitudeDelta /= 8.0;
                                     region.span.latitudeDelta /= 8.0;

                                     PointAnnotation *point = [[PointAnnotation alloc] init];
                                     point.coordinate = placemark.coordinate;
                                     point.title = userNames;
                                     point.subtitle = userBio;
                                     point.index = index;  // Store index here.

                                     [self.friendsMapView addAnnotation:point];
                                 }
                             }
                 ];
                index = index + 1;
            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failure: %@", [error localizedDescription]);
        }];

    }

    -(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation {

        MKAnnotationView *view = nil;
        if (annotation != self.mapView.userLocation) {

            view = [self.mapView dequeueReusableAnnotationViewWithIdentifier:@"myAnnotationIdentifier"];
            if (!view) {

                static NSString* AnnotationIdentifier = @"AnnotationIdentifier";

                MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                                reuseIdentifier:AnnotationIdentifier];
                annotationView.canShowCallout = YES;
                annotationView.image = [UIImage imageNamed:@"mappaw.png"];
                UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

                annotationView.rightCalloutAccessoryView = rightButton;
                annotationView.canShowCallout = YES;
                annotationView.draggable = YES;
                return annotationView;

            }
        }
        return view;
    }

    - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {

            PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

            OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

            NSMutableDictionary *dictionary = self.addressData[selectedPoint.index];
            yourViewController.mapuserData = dictionary;

            [self.navigationController pushViewController:yourViewController animated:YES];

        }

    -(MKAnnotationView*)friendsMapView:(MKMapView*)friendsMapView viewForAnnotation:(id<MKAnnotation>)annotation {
        // If you are showing the users location on the map you don't want to change it
        MKAnnotationView *view2 = nil;
        if (annotation != self.friendsMapView.userLocation) {

            view2 = [self.friendsMapView dequeueReusableAnnotationViewWithIdentifier:@"myFriendAnnotationIdentifier"];
            if (!view2) {

                static NSString *AnnotationIdentifier = @"FriendAnnotationIdentifier";

                MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                                reuseIdentifier:AnnotationIdentifier];
                annotationView.canShowCallout = YES;
                annotationView.image = [UIImage imageNamed:@"mappaw.png"];
                UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

                annotationView.rightCalloutAccessoryView = rightButton;
                annotationView.canShowCallout = YES;
                annotationView.draggable = YES;
                return annotationView;

            }
        }
        return view2;
    }

    - (void)friendsMapView:(MKMapView *)friendsMapView didSelectAnnotationView:(MKAnnotationView *)view2
    {

        PointAnnotation *selectedPoint = (PointAnnotation *) view2.annotation;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

        NSMutableDictionary *dictionary = self.friendData[selectedPoint.index];

        yourViewController.mapuserData = dictionary;

        [self.navigationController pushViewController:yourViewController animated:YES];

        NSLog(@"Selected!");

    }
</code>```

答:
You can't makeup method signatures for the delegate methods.

The following is correct:

```<code>- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
</code>```

The following is some made up method that will never be seen as a delegate method:

```<code>- (void)friendsMapView:(MKMapView *)friendsMapView didUpdateUserLocation:(MKUserLocation *)userLocation
</code>```

Just implement the proper delegate methods. Both map views will use the same delegate methods. You act accordingly by using the mapView parameter.

For example, your two didUpdateUserLocation delegate methods become one as follows:

```<code>- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1300, 1300);
    [mapView setRegion:[mapView regionThatFits:region] animated:YES];
}
</code>```

That one delegate method will work for both map views.

If you actually need to do something different depending on which map view it is, you do something like the following:

```<code>- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    if mapView == self.mapView {
        // Do something specific to self.mapView
    } else if mapView == self.friendsMapView {
        // Do something specific to self.friendsMapView
    }
}
</code>```

Body:
I have two separate mapviews inside of one ViewController. Each mapview shows a different set of annotations - one map shows strangers locations, the other map shows friend locations. When I tap an annotation on the first mapview (mapView), I get a detail view with the correct user data. However, when I tap an annotation on the second map view (friendsMapView), the data is being pulled from the dictionary populating the first mapView. After logging the error, I discovered that didSelectAnnotation for friendsMapView is never executed? How can I fix this?

Code not being executed (EDIT):

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {

    if (self.mapView == self.mapView) {
        // Do something specific to self.mapView

        PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

        NSMutableDictionary *dictionary = self.addressData[selectedPoint.index];
        yourViewController.mapuserData = dictionary;

        [self.navigationController pushViewController:yourViewController animated:YES];

    } else if (self.mapView == self.friendsMapView) {
        // Do something specific to self.friendsMapView

        PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

        NSMutableDictionary *dictionary = self.friendData[selectedPoint.index];
        yourViewController.mapuserData = dictionary;

        [self.navigationController pushViewController:yourViewController animated:YES];

    }

    }

Full code: MapViewController.m

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{

    if (self.mapView == self.mapView) {

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1300, 1300);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

    } else if (self.mapView == self.friendsMapView) {

        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1300, 1300);
        [self.friendsMapView setRegion:[self.friendsMapView regionThatFits:region] animated:YES];

    }

}

    - (NSString *)deviceLocation {
        return [NSString stringWithFormat:@"latitude: %f longitude: %f", self.locationManager.location.coordinate.latitude, self.locationManager.location.coordinate.longitude];
    }
    - (NSString *)deviceLat {
        return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.latitude];
    }
    - (NSString *)deviceLon {
        return [NSString stringWithFormat:@"%f", self.locationManager.location.coordinate.longitude];
    }
    - (NSString *)deviceAlt {
        return [NSString stringWithFormat:@"%f", self.locationManager.location.altitude];
    }

        NSMutableDictionary *viewParams = [NSMutableDictionary new];
        [viewParams setValue:@"u000" forKey:@"view_name"];
        [DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {

            self.addressData = [responseObject mutableCopy];

            NSLog(@"%@", responseObject);

            int index = 0;   //Index to track the data source index while select the annotation call out view.

            for (NSMutableDictionary *multiplelocations in self.addressData) {

                NSString *location = multiplelocations[@"street_address"];
                NSLog(@"Pull addresses %@", location);
                NSString *userNames = multiplelocations[@"users_name"];
                NSString *userBio = multiplelocations[@"userbio"];

                CLGeocoder *geocoder = [[CLGeocoder alloc] init];

                [geocoder geocodeAddressString:location
                             completionHandler:^(NSArray* placemarks, NSError* error){
                                 if (placemarks && placemarks.count > 0) {
                                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];

                                     MKCoordinateRegion region = self.mapView.region;

                                     region.span.longitudeDelta /= 8.0;
                                     region.span.latitudeDelta /= 8.0;

                                     PointAnnotation *point = [[PointAnnotation alloc] init];
                                     point.coordinate = placemark.coordinate;
                                     point.title = userNames;
                                     point.subtitle = userBio;
                                     point.index = index;  // Store index here.

                                     [self.mapView addAnnotation:point];
                                 }
                             }
                 ];
                index = index + 1;
            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failure: %@", [error localizedDescription]);
        }];

        NSMutableDictionary *viewParamsFriend = [NSMutableDictionary new];
        [viewParamsFriend setValue:@"accepted_friends" forKey:@"view_name"];
        [DIOSView viewGet:viewParamsFriend success:^(AFHTTPRequestOperation *operation, id responseObject) {

            self.friendData = [responseObject mutableCopy];

            NSLog(@"THIS IS FRIEND DATA %@", self.friendData);

            int index = 0;

            for (NSMutableDictionary *multiplelocationsFriend in self.friendData) {

                NSString *location = multiplelocationsFriend[@"address2"];
                NSString *userNames = multiplelocationsFriend[@"node_title"];
                NSString *userBio = multiplelocationsFriend[@"body"];

                       NSLog(@"LOCATION IS HERE %@", location);

                CLGeocoder *geocoderFriend = [[CLGeocoder alloc] init];
                [geocoderFriend geocodeAddressString:location
                             completionHandler:^(NSArray* placemarks, NSError* error){
                                 if (placemarks && placemarks.count > 0) {
                                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];

                                     MKCoordinateRegion region = self.friendsMapView.region;

                                     region.span.longitudeDelta /= 8.0;
                                     region.span.latitudeDelta /= 8.0;

                                     PointAnnotation *point = [[PointAnnotation alloc] init];
                                     point.coordinate = placemark.coordinate;
                                     point.title = userNames;
                                     point.subtitle = userBio;
                                     point.index = index;  // Store index here.

                                     [self.friendsMapView addAnnotation:point];
                                 }
                             }
                 ];
                index = index + 1;
            }

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Failure: %@", [error localizedDescription]);
        }];

    }

    -(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id<MKAnnotation>)annotation {

        MKAnnotationView *view = nil;
        if (annotation != self.mapView.userLocation) {

            view = [self.mapView dequeueReusableAnnotationViewWithIdentifier:@"myAnnotationIdentifier"];
            if (!view) {

                static NSString* AnnotationIdentifier = @"AnnotationIdentifier";

                MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                                reuseIdentifier:AnnotationIdentifier];
                annotationView.canShowCallout = YES;
                annotationView.image = [UIImage imageNamed:@"mappaw.png"];
                UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

                annotationView.rightCalloutAccessoryView = rightButton;
                annotationView.canShowCallout = YES;
                annotationView.draggable = YES;
                return annotationView;

            }
        }
        return view;
    }

    - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {

            PointAnnotation *selectedPoint = (PointAnnotation *) view.annotation;

            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

            OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

            NSMutableDictionary *dictionary = self.addressData[selectedPoint.index];
            yourViewController.mapuserData = dictionary;

            [self.navigationController pushViewController:yourViewController animated:YES];

        }

    -(MKAnnotationView*)friendsMapView:(MKMapView*)friendsMapView viewForAnnotation:(id<MKAnnotation>)annotation {
        // If you are showing the users location on the map you don't want to change it
        MKAnnotationView *view2 = nil;
        if (annotation != self.friendsMapView.userLocation) {

            view2 = [self.friendsMapView dequeueReusableAnnotationViewWithIdentifier:@"myFriendAnnotationIdentifier"];
            if (!view2) {

                static NSString *AnnotationIdentifier = @"FriendAnnotationIdentifier";

                MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                                reuseIdentifier:AnnotationIdentifier];
                annotationView.canShowCallout = YES;
                annotationView.image = [UIImage imageNamed:@"mappaw.png"];
                UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];

                annotationView.rightCalloutAccessoryView = rightButton;
                annotationView.canShowCallout = YES;
                annotationView.draggable = YES;
                return annotationView;

            }
        }
        return view2;
    }

    - (void)friendsMapView:(MKMapView *)friendsMapView didSelectAnnotationView:(MKAnnotationView *)view2
    {

        PointAnnotation *selectedPoint = (PointAnnotation *) view2.annotation;

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OtherUserViewController *yourViewController = (OtherUserViewController *)[storyboard instantiateViewControllerWithIdentifier:@"OtherUserViewController"];

        NSMutableDictionary *dictionary = self.friendData[selectedPoint.index];

        yourViewController.mapuserData = dictionary;

        [self.navigationController pushViewController:yourViewController animated:YES];

        NSLog(@"Selected!");

    }

Body:
You can't makeup method signatures for the delegate methods.

The following is correct:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation

The following is some made up method that will never be seen as a delegate method:

- (void)friendsMapView:(MKMapView *)friendsMapView didUpdateUserLocation:(MKUserLocation *)userLocation

Just implement the proper delegate methods. Both map views will use the same delegate methods. You act accordingly by using the mapView parameter.

For example, your two didUpdateUserLocation delegate methods become one as follows:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 1300, 1300);
    [mapView setRegion:[mapView regionThatFits:region] animated:YES];
}

That one delegate method will work for both map views.

If you actually need to do something different depending on which map view it is, you do something like the following:

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    if mapView == self.mapView {
        // Do something specific to self.mapView
    } else if mapView == self.friendsMapView {
        // Do something specific to self.friendsMapView
    }
}


问:
rabbitmq-bundle - symfony3 - how to configure a topic exchange and queues?
I can't find a great configuration for old sound rabbitmq bundle to deal with topics and wildcard.

All I want is a unique exchange that post to multiple queue using wildcard.

Let says for example, i have my exchange name user.update, and i want to post the same message on user.update.address, user.update.profile for a microservice strategy.

do you know how to configure in the configuration file ?

Thx for reading.

答:
Just because you are looking for

... great configuration for old sound rabbitmq bundle ...

visit http://www.inanzzz.com/ and search for "rabbitmq" which will give you what you wish for.

To address your question, you can use config below (I haven't tested it but it should be fine). However, you still need to write whole functionality/classes/consumers/producers etc. so follow this example: RabbitMQ topic example with symfony including 1 Producer & 1 Exchange & 2 Queue & N Worker & 2 Consumer

```<code>old_sound_rabbit_mq:
    connections:
        default:
            host:     %rabbitmq.host%
            port:     %rabbitmq.port%
            user:     %rabbitmq.user%
            password: %rabbitmq.pswd%
            vhost:    /
            lazy:     true
    producers:
        user_update_producer:
            connection:       default
            exchange_options: { name: user.update, type: topic }
    consumers:
        user_update_consumer:
            connection:       default
            exchange_options: { name: user.update, type: topic }
            queue_options:
                name: user_update_queue
                routing_keys:
                    - 'user.update.address'
                    - 'user.update.profile'
            callback:         your_application.consumer.user_update_consumer
</code>```

It's flow: user.update (P) -> user.update (E) -> [user.update.address & user.update.profile] -> user_update_queue (Q)

Body:
Just because you are looking for

... great configuration for old sound rabbitmq bundle ...

visit http://www.inanzzz.com/ and search for "rabbitmq" which will give you what you wish for.

To address your question, you can use config below (I haven't tested it but it should be fine). However, you still need to write whole functionality/classes/consumers/producers etc. so follow this example: RabbitMQ topic example with symfony including 1 Producer & 1 Exchange & 2 Queue & N Worker & 2 Consumer

old_sound_rabbit_mq:
    connections:
        default:
            host:     %rabbitmq.host%
            port:     %rabbitmq.port%
            user:     %rabbitmq.user%
            password: %rabbitmq.pswd%
            vhost:    /
            lazy:     true
    producers:
        user_update_producer:
            connection:       default
            exchange_options: { name: user.update, type: topic }
    consumers:
        user_update_consumer:
            connection:       default
            exchange_options: { name: user.update, type: topic }
            queue_options:
                name: user_update_queue
                routing_keys:
                    - 'user.update.address'
                    - 'user.update.profile'
            callback:         your_application.consumer.user_update_consumer

It's flow: user.update (P) -> user.update (E) -> [user.update.address & user.update.profile] -> user_update_queue (Q)


问:
React native android error: cannot find symbol
I was trying to build an open source react native project example:

https://github.com/wix/react-native-wordpress-editor/tree/master/example

But i ran into this error after running
./react-native run-android

```<code>D:\e\example\node_modules\react-native-navigation\android\app\src\main\java\com\reactnativenavigation\NavigationApplica
ion.java:7: Error: cannot find symbol
import com.facebook.react.ReactApplication;
                          ^
</code>```

Anyone has any idea of whats going on?

答:
Should follow the third replay to this issue. Basically that helps in setting the rich editor up.

https://github.com/wix/react-native-wordpress-editor/issues/6

Body:
I was trying to build an open source react native project example:

https://github.com/wix/react-native-wordpress-editor/tree/master/example

But i ran into this error after running
./react-native run-android

D:\e\example\node_modules\react-native-navigation\android\app\src\main\java\com\reactnativenavigation\NavigationApplica
ion.java:7: Error: cannot find symbol
import com.facebook.react.ReactApplication;
                          ^

Anyone has any idea of whats going on?


问:
Is it possible to find out if some list is fixed size or not?
Is it possible to find out if some a list is fixed size or not?
I mean, for example this code:

```<code>String[] arr = {"a", "b"};
List<String> list = Arrays.asList(array);
</code>```

returns fixed size List backed by an array. But is it possible to understand programmatically if List is fixed-size or not without trying to add/remove elements and catching the exception? For example:

```<code>try {
    list.add("c");
}
catch(UnsupportedOperationException e) {
    // Fixed-size?
}
</code>```

答:
Is it possible to find out if some list is fixed size or not?

In theory - No.  Fixed sizedness is an emergent property of the implementation of a list class.  You can only determine if a list has that property  by trying to add an element.

And note that a simple behavioral test would not reliably distinguish between a fixed sized list and a bounded list or a list that was permanently or temporarily read-only.

In practice, a fixed sized list will typically have a different class to an ordinary one.  You can test the class of an object to see if it or isn't a specific class.  So if you understand what classes would be used to implement fixed sized lists in your code-base, then you can test if a specific list is fixed sized.

For example the Arrays.asList(...) method returns a List object whose actual class is java.util.Arrays.ArrayList.  That is a private nested class, but you could use reflection find it, and then use Object.getClass().equals(...) to test for it.

However, this approach is fragile.  Your code could break if the implementation of Arrays was modified, or if you started using other forms of fixed sized list as well.

Body:
Is it possible to find out if some a list is fixed size or not?
I mean, for example this code:

String[] arr = {"a", "b"};
List<String> list = Arrays.asList(array);

returns fixed size List backed by an array. But is it possible to understand programmatically if List is fixed-size or not without trying to add/remove elements and catching the exception? For example:

try {
    list.add("c");
}
catch(UnsupportedOperationException e) {
    // Fixed-size?
}


答:
Using ternary operator you can solve this.
Here is JS fiddle for this:
    http://jsfiddle.net/5fbvf5vy/

inputOne == "Yes" ? "517" : "518";
inputTwo == "Yes" ? "518" : "519";
inputThree == "Yes" ? "519" : "520";
inputFour == "Yes" ? "520" : "521";

Title: Condensing bunch of if-else statements in JS


答:
This is just the new look and feel of Swagger-UI from version 3. Just check their FAQ:

Hey, what happened to the UI?! I liked it much better in Swagger-X!

We took the the best of the existing projects, freshened things up and
  voila! We’re likely to make more changes in the upcoming weeks, and
  definitely more when we support the next version of the spec.

But I want the old look’n’feel!

That’s the great thing about the new projects – if you want to modify
  the UI to suit your needs that’s a lot easier now.

Title: Swagger-UI not appearing properly

Body:
Why does my Swagger UI look different?

This is what I have:

This is what I would like to have:

In order to get Swagger-UI working, all i did was download the project(https://github.com/swagger-api/swagger-ui), take all the contents in the dist folder and put it in the webapp folder of my dynamic web project. After doing this, I updated the index.html to point to my swagger.json. After this was done, I was able to see the first picture shown. However, the large execute button is not all that appealing :( How do i get my swagger page to look like the second picture shown?


问:
warning.js:36 Warning: Failed prop type: The prop `history` is marked as required in `Router`, but its value is `undefined`
Getting the error in the title based on the following code:

```<code>import React from 'react'
// import { browserHistory, hashHistory, Router } from 'react-router'
// import createMemoryHistory from 'history/lib/createMemoryHistory'
import { browserHistory, hashHistory, Router, Route, Switch } from 'react-router-dom'
import Portfolio from './portfolio/Portfolio'
import Home from './home/Home'
import NoMatch from './NoMatch'

// const history = createMemoryHistory(location);
// console.log('history', history);

const Routes = () => {
    return (
        <Router history={browserHistory}>
            <Route exact={ true } path="/" component={ Home }/>
            <Route exact={ true } path="/portfolio" component={ Portfolio }/>
            <Route component={ NoMatch } />
        </Router>
    );
}

export default Routes
</code>```

答:
Replace Router with BrowserRouter and use Switch as from react-router-dom version4.0, Router can not have more than one child.

```<code>import { browserHistory, hashHistory, BrowserRouter, Route, Switch } from 'react-router-dom';
</code>```

and replace routes with below code:

```<code>const Routes = () => {
        return (
            <BrowserRouter history={browserHistory}>
             <Switch>
                <Route exact={ true } path="/" component={ Home }/>
                <Route exact={ true } path="/portfolio"
                       component={ Portfolio }/>
                <Route component={ NoMatch } />
             </Switch>
            </BrowserRouter>
        );
    }
</code>```

Body:
Getting the error in the title based on the following code:

import React from 'react'
// import { browserHistory, hashHistory, Router } from 'react-router'
// import createMemoryHistory from 'history/lib/createMemoryHistory'
import { browserHistory, hashHistory, Router, Route, Switch } from 'react-router-dom'
import Portfolio from './portfolio/Portfolio'
import Home from './home/Home'
import NoMatch from './NoMatch'

// const history = createMemoryHistory(location);
// console.log('history', history);

const Routes = () => {
    return (
        <Router history={browserHistory}>
            <Route exact={ true } path="/" component={ Home }/>
            <Route exact={ true } path="/portfolio" component={ Portfolio }/>
            <Route component={ NoMatch } />
        </Router>
    );
}

export default Routes

Body:
Replace Router with BrowserRouter and use Switch as from react-router-dom version4.0, Router can not have more than one child.

import { browserHistory, hashHistory, BrowserRouter, Route, Switch } from 'react-router-dom';

and replace routes with below code:

const Routes = () => {
        return (
            <BrowserRouter history={browserHistory}>
             <Switch>
                <Route exact={ true } path="/" component={ Home }/>
                <Route exact={ true } path="/portfolio"
                       component={ Portfolio }/>
                <Route component={ NoMatch } />
             </Switch>
            </BrowserRouter>
        );
    }


问:
how to connect to CDH cluster from Remote python service
I have a CDH cluster running on aws . also have set of services running on different ec2 machines hooked to ECS cluster. all are in one VPN.
Use case that I have is to write data from my external service running on ec2 to CDH hadoop cluster.
I am trying to find out the best way for it . please suggest me possible ways in python as how to achieve this.</p>

答:
Apache Hadoop provides WebHDFS, which is an HTTP interface into HDFS operations.  This allows you to manipulate files in HDFS using any Python HTTP client library such as httplib, urllib or urllib2.  In fact, you can access WebHDFS using any programming language that provides an HTTP client library.

You could also use Pydoop, which provides a more direct integration between Python and HDFS.  The Pydoop implementation uses LibHDFS, which is a C wrapper over the standard HDFS Java client.  Thus, it would utilize the HDFS RPC protocol directly instead of HTTP.


问:
sharepoint 2013 term-driven page friendly url Using JSOM
How to get the term driven Page friendly url using jsom

currentTerm.get_localCustomProperties()['_Sys_Nav_FriendlyUrlSegment'])

// giving undefined

答:
To retrieve the friendly URL you could utilize SP.Publishing.Navigation.NavigationTerm object which:

Specifies navigation behavior and properties for a SP.Taxonomy.Term
  constructor (sp.taxonomy) object that is used to drive the
  navigation and friendly URLs for a website.

The specified class contains getWebRelativeFriendlyUrl method which

returns the friendly URL segments as a concatenated path.

Example

```<code>var scriptbase = _spPageContextInfo.webAbsoluteUrl+"/_layouts/15";

$.getScript(scriptbase +"/sp.runtime.js",function(){
    $.getScript(scriptbase + "/sp.js", function() {
        $.getScript(scriptbase + "/sp.publishing.js",function(){
            $.getScript(scriptbase+"/sp.taxonomy.js",function(){

                var termId = "--Term ID goes here--";

                var ctx = SP.ClientContext.get_current();
                var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);

                var term = taxSession.getTerm(termId);
                var navTerm = SP.Publishing.Navigation.NavigationTerm.getAsResolvedByWeb(ctx,term, ctx.get_web(), "CurrentNavigationTaxonomyProvider");
                var friendlyUrl = navTerm.getWebRelativeFriendlyUrl();

                ctx.executeQueryAsync(function() {
                   console.log(friendlyUrl.get_value());
                },
                function(sender,args) {
                   console.log(args.get_message());
                });
            })
        })
    })
});
</code>```

Body:
To retrieve the friendly URL you could utilize SP.Publishing.Navigation.NavigationTerm object which:

Specifies navigation behavior and properties for a SP.Taxonomy.Term
  constructor (sp.taxonomy) object that is used to drive the
  navigation and friendly URLs for a website.

The specified class contains getWebRelativeFriendlyUrl method which

returns the friendly URL segments as a concatenated path.

Example

var scriptbase = _spPageContextInfo.webAbsoluteUrl+"/_layouts/15";

$.getScript(scriptbase +"/sp.runtime.js",function(){
    $.getScript(scriptbase + "/sp.js", function() {
        $.getScript(scriptbase + "/sp.publishing.js",function(){
            $.getScript(scriptbase+"/sp.taxonomy.js",function(){

                var termId = "--Term ID goes here--";

                var ctx = SP.ClientContext.get_current();
                var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);

                var term = taxSession.getTerm(termId);
                var navTerm = SP.Publishing.Navigation.NavigationTerm.getAsResolvedByWeb(ctx,term, ctx.get_web(), "CurrentNavigationTaxonomyProvider");
                var friendlyUrl = navTerm.getWebRelativeFriendlyUrl();

                ctx.executeQueryAsync(function() {
                   console.log(friendlyUrl.get_value());
                },
                function(sender,args) {
                   console.log(args.get_message());
                });
            })
        })
    })
});


问:
How to put xampp localhost website online?
I am new to the WordPress. I have a made WordPress website in xampp localhost, now I want to show that site to my friend before making it online without using any hosting services, but can not show him because it is on localhost.</p>

答:
You can put your XAMPP server online without buying a hosting plan from web hosting provider, all you have to do is, get these followings.

Allow external connections to Apache HTTP server through the firewall on port 80.

Get a Static IP from your Internet Service Provider (ISP) (contact your ISP).

Share the static public IP which you've got from ISP to your friend.
you can access XAMPP locally using http://127.0.0.1/index.html now change the local IP with your public static IP lets say(http://10.123.53.X/index.html)


问:
Jquery: Is there some way to make val() return an empty string instead of 'undefined' for an empty list?
With Jquery, is there some way to make val() return an empty string instead of 'undefined' when called against an empty list of elements?

E.g., I have this code:

```<code>var x = $('#my-textbox-id').not('.watermark').val();
</code>```

The idea is that I want to get the value of my textbox, but I want an empty string if it is currently showing the watermark (i don't want the watermark value!).

The selector works, but i don't want 'undefined' - I want an empty string ''.

答:
```<code>var x = $('#my-textbox-id').not('.watermark').val() == undefined
? ''
: $('#my-textbox-id').not('.watermark').val();
</code>```

Body:
With Jquery, is there some way to make val() return an empty string instead of 'undefined' when called against an empty list of elements?

E.g., I have this code:

var x = $('#my-textbox-id').not('.watermark').val();

The idea is that I want to get the value of my textbox, but I want an empty string if it is currently showing the watermark (i don't want the watermark value!).

The selector works, but i don't want 'undefined' - I want an empty string ''.


问:
SQL Function to return sequential id's
Consider this simple INSERT

```<code>INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,123 FROM Customers
</code>```

That will obviously assign UserId=123 to all customers.

What I need to do is assign them to 3 userId's sequentially, so 3 users get one third of the accounts equally.

```<code>INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,fnGetNextId() FROM Customers
</code>```

Could I create a function to return sequentially from a list of 3 ID's?, i.e. each time the function is called it returns the next one in the list?

Thanks

答:
This is a strange requirement, but the modulus operator (%) should help you out without the need for functions, sequences, or altering your database structure.  This assumes that the IDs are integers.  If they're not, you can use ROW_NUMBER or a number of other tactics to get a distinct number value for each customer.

Obviously, you would replace the SELECT statement with an INSERT once you're satisfied with the code, but it's good practice to always select when developing before inserting.

SETUP WITH SAMPLE DATA:

```<code>DECLARE @Users TABLE (ID int, [Name] varchar(50))
DECLARE @Customers TABLE (ID int, [Name] varchar(50))
DECLARE @Assignment TABLE (CustomerID int, UserID int)

INSERT INTO @Customers
VALUES
(1, 'Joe'),
(2, 'Jane'),
(3, 'Jon'),
(4, 'Jake'),
(5, 'Jerry'),
(6, 'Jesus')

INSERT INTO @Users
VALUES
(1, 'Ted'),
(2, 'Ned'),
(3, 'Fred')
</code>```

QUERY:

```<code>SELECT C.Name AS [CustomerName], U.Name AS [UserName]
FROM @Customers C
JOIN @Users U
    ON
        CASE    WHEN C.ID % 3 = 0 THEN 1
                WHEN C.ID % 3 = 1 THEN 2
                WHEN C.ID % 3 = 2 THEN 3
        END = U.ID
</code>```

You would change the THEN 1 to whatever your first UserID is, THEN 2 with the second UserID, and THEN 3 with the third UserID.  If you end up with another user and want to split the customers 4 ways, you would do replace the CASE statement with the following:

```<code>        CASE    WHEN C.ID % 4 = 0 THEN 1
                WHEN C.ID % 4 = 1 THEN 2
                WHEN C.ID % 4 = 2 THEN 3
                WHEN C.ID % 4 = 3 THEN 4
        END = U.ID
</code>```

OUTPUT:

```<code>CustomerName                                       UserName
-------------------------------------------------- --------------------------------------------------
Joe                                                Ned
Jane                                               Fred
Jon                                                Ted
Jake                                               Ned
Jerry                                              Fred
Jesus                                              Ted

(6 row(s) affected)
</code>```

Lastly, you will want to select the IDs for your actual insert, but I selected the names so the results are easier to understand.  Please let me know if this needs clarification.

Title: SQL Function to return sequential id's

Body:
Consider this simple INSERT

INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,123 FROM Customers

That will obviously assign UserId=123 to all customers.

What I need to do is assign them to 3 userId's sequentially, so 3 users get one third of the accounts equally.

INSERT INTO Assignment (CustomerId,UserId)
SELECT CustomerId,fnGetNextId() FROM Customers

Could I create a function to return sequentially from a list of 3 ID's?, i.e. each time the function is called it returns the next one in the list?

Thanks

Body:
This is a strange requirement, but the modulus operator (%) should help you out without the need for functions, sequences, or altering your database structure.  This assumes that the IDs are integers.  If they're not, you can use ROW_NUMBER or a number of other tactics to get a distinct number value for each customer.

Obviously, you would replace the SELECT statement with an INSERT once you're satisfied with the code, but it's good practice to always select when developing before inserting.

SETUP WITH SAMPLE DATA:

DECLARE @Users TABLE (ID int, [Name] varchar(50))
DECLARE @Customers TABLE (ID int, [Name] varchar(50))
DECLARE @Assignment TABLE (CustomerID int, UserID int)

INSERT INTO @Customers
VALUES
(1, 'Joe'),
(2, 'Jane'),
(3, 'Jon'),
(4, 'Jake'),
(5, 'Jerry'),
(6, 'Jesus')

INSERT INTO @Users
VALUES
(1, 'Ted'),
(2, 'Ned'),
(3, 'Fred')

QUERY:

SELECT C.Name AS [CustomerName], U.Name AS [UserName]
FROM @Customers C
JOIN @Users U
    ON
        CASE    WHEN C.ID % 3 = 0 THEN 1
                WHEN C.ID % 3 = 1 THEN 2
                WHEN C.ID % 3 = 2 THEN 3
        END = U.ID

You would change the THEN 1 to whatever your first UserID is, THEN 2 with the second UserID, and THEN 3 with the third UserID.  If you end up with another user and want to split the customers 4 ways, you would do replace the CASE statement with the following:

        CASE    WHEN C.ID % 4 = 0 THEN 1
                WHEN C.ID % 4 = 1 THEN 2
                WHEN C.ID % 4 = 2 THEN 3
                WHEN C.ID % 4 = 3 THEN 4
        END = U.ID

OUTPUT:

CustomerName                                       UserName
-------------------------------------------------- --------------------------------------------------
Joe                                                Ned
Jane                                               Fred
Jon                                                Ted
Jake                                               Ned
Jerry                                              Fred
Jesus                                              Ted

(6 row(s) affected)

Lastly, you will want to select the IDs for your actual insert, but I selected the names so the results are easier to understand.  Please let me know if this needs clarification.


问:
Creating single object DataFrame for predictions
once I got my classification models trained, I'd like them to use in my web application to make classification predictions on the data that has been collected for a given session.
That is:
1) I have some session data structure that I need to map to a DataFrame row
2) feed tha DataFrame row into my ML model to predict the classification
3) use the prediction with the origination session to show it to the user in front of the browser.

The examples to create a DataFrame as input to a Spark pipeline that I've seen so far create it from a data source like a file. Now it seems a bit unwieldy to first create a single POJO or JsonNode, serialize it to file containing just on record and then use that file to create the DataFrame to feed the model.
Writing this I also get the feeling that it might not be a great idea to create and tear down the ML pipeline for each request, which seems to follow from this approach.

So maybe I should better think "Spark Streaming"?

Feed the mapped session data into some kind of message queue and feed that into my Spark pipeline? What kind of "stream" would be appropriate here?

I read somewhere that Spark streaming consumes the stream in micro batches and not record by record - that implies some delay until enough records have been collected to fill up the micro batch (or some preconfigured delay to wait until the micro batch is considered to be "full enough"). What does that mean for the responsiveness of the web application? Can I trigger the micro batches like every 100 milliseconds?

I would appreciate if someone could point me in the right direction.
Maybe Spark is not a good fit here and I should switch to Apache Flink?

Thanks in advance, Bernd

答:
Ok, by now I have found some ways to solve my problem, maybe that
  helps someone else:

Use a Sequence containing one tuple and name the columns separately

```<code>val df= spark.createDataFrame(
  Seq("val1", "val2")
).toDF("label1", "label2")
</code>```

Using a JSON-String

```<code>val sqlContext = spark.sqlContext
val jsonData= """{ "label1": "val1", "label2": "val2" }"""
val rdd= sparkSession.sparkContext.parallelize(Seq(jsonData))
val df= sqlContext.read.json(rdd)
</code>```

NOT Working: create from Sequence case class Objects:

```<code>val sqlContext = sparkSession.sqlContext
import sqlContext.implicits._

val myData= Seq(Feat("value1", "value2"))
val ds: Dataset[Feat]= myData.toDS()
ds.show(10, false)
</code>```

This compiles ok, but yields an Exception at runtime:

``` [error] a.a.OneForOneStrategy - java.lang.RuntimeException:
Error while encoding:  java.lang.ClassCastException:
es.core.recommender.Feat cannot be cast to es.core.recommender.Feat
```

I'd love to include more of the stacktrace, but this glorious editor
  won't let me...

It would be nice to know why this alternative did not work...

Body:
Ok, by now I have found some ways to solve my problem, maybe that
  helps someone else:

Use a Sequence containing one tuple and name the columns separately

val df= spark.createDataFrame(
  Seq("val1", "val2")
).toDF("label1", "label2")

Using a JSON-String

val sqlContext = spark.sqlContext
val jsonData= """{ "label1": "val1", "label2": "val2" }"""
val rdd= sparkSession.sparkContext.parallelize(Seq(jsonData))
val df= sqlContext.read.json(rdd)

NOT Working: create from Sequence case class Objects:

val sqlContext = sparkSession.sqlContext
import sqlContext.implicits._

val myData= Seq(Feat("value1", "value2"))
val ds: Dataset[Feat]= myData.toDS()
ds.show(10, false)

This compiles ok, but yields an Exception at runtime:

 [error] a.a.OneForOneStrategy - java.lang.RuntimeException:
Error while encoding:  java.lang.ClassCastException:
es.core.recommender.Feat cannot be cast to es.core.recommender.Feat

I'd love to include more of the stacktrace, but this glorious editor
  won't let me...

It would be nice to know why this alternative did not work...


答:
A list created from a String[] by

```<code>List<String> list = Arrays.asList(array);
</code>```

will have Arrays as enclosing class, while one created by for example new ArrayList() won't have the enclosing class. So the following should work to check if the List was produced as a result of calling Arrays.toList():

```<code>static <T> boolean wasListProducedAsAResultOfCallingTheFunctionArrays_asList(List<T> l) {
    return Arrays.class.equals(l.getClass().getEnclosingClass());
}
</code>```

Beware that this method relies on undocumented behavior. It will break if they added another nested List subclass to the Arrays class.

Title: Is it possible to find out if some list is fixed size or not?

Body:
A list created from a String[] by

List<String> list = Arrays.asList(array);

will have Arrays as enclosing class, while one created by for example new ArrayList() won't have the enclosing class. So the following should work to check if the List was produced as a result of calling Arrays.toList():

static <T> boolean wasListProducedAsAResultOfCallingTheFunctionArrays_asList(List<T> l) {
    return Arrays.class.equals(l.getClass().getEnclosingClass());
}

Beware that this method relies on undocumented behavior. It will break if they added another nested List subclass to the Arrays class.


问:
How To Read Line Numbers x Through (x+y) From A Very Large File
I have a very large text file where each line must be parsed.
I want to read lines x though x+100000 and add each line into a List such that list.size <= 100000.
The list will then be returned to the calling method for processing then the calling method will ask for the next 100k lines beginning where it left off last time.

The code below is one version using a BufferedReader. I returns the first 100k lines fine, but in the next call, starting at line 100k+1, it starts slowing down at around row 150k, and around line 165k it results in an OutOfMemoryError. I looked around for a way to empty the buffer once it gets to the line where I want to begin adding to the list, but I couldn't find any info on that. I also tried to find a way to skip x number of rows, but I couldn't find anything on that.

```<code>public List<MyModel> retrieve(File inputFile, int startLine, String checksum) throws DaoException {

    List<MyModel> result = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {

          String line = null;
          int row = 0;
          int iteration = 0;

          try {
              while (((line = br.readLine()) != null) && iteration < MAX_ROWS) {
                  row++;
                  LOGGER.info("row: " + row + ", iteration: " + iteration);
                  if (row > startLine && iteration < MAX_ROWS) {
                      MyModel model = this.fileReader.populateMyModel(line);
                      model.setFileChecksum(checksum);
                      result.add(model);
                      iteration++;
                  }
                  if (iteration >= MAX_ROWS) {
                      break;
                  }
              }
          } catch (Exception e) {

              throw new FileReaderException("Failed to read line " + iteration + " of " + inputFile.getAbsolutePath(), e);
          }
    } catch (FileNotFoundException e1) {
          throw new FileReaderException("Could not find file '" + inputFile.getAbsolutePath() + "'.", e1);
    } catch (IOException e1) {
          throw new FileReaderException("Could not read file '" + inputFile.getAbsolutePath() + "'.", e1);
    }

        return result;
}
</code>```

While trying to find out how to skip lines, I ran across the Java 8 Stream way of reading files and the code below is my attempt to deal with it that way. This one also works great on the first call, returning the first 100k lines. For the second call, where it begins with line 100k+1, it returns "java.lang.IllegalStateException: stream has already been operated upon or closed". Additionally, I ONLY want to read lines x thru x+100k then return, not cycle through all the lines of the file. I'm new to this Stream object, but it seems like using that should provide a solution.

```<code>public List<MyModel> retrieve(File inputFile, int startLine, String checksum) throws DaoException {
    List<MyModel> result = new ArrayList<>();

    try (Stream<String> lines = Files.lines(inputFile.toPath(), Charset.defaultCharset())) {
        lines.skip(startLine);
        lines
        .filter(line -> result.size() <= 100000)
        .forEach(line -> {
            result.add(this.fileReader.populateMyModel(line));
            if (result.size() % 10000 == 0) {
                LOGGER.info("result size: " + result.size());
            }
        });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}
</code>```

Any suggestions would be helpful.

答:
When you write:

```<code>lines.skip(startLine)
</code>```

you create a new stream, but you don't save a reference to it, so you lose the operation.

I suspect you want something like:

```<code>return lines.skip(startLine)
            .limit(100000)
            .map(fileReader::populateMyModel)
            .collect(toList());
</code>```

Body:
I have a very large text file where each line must be parsed.
I want to read lines x though x+100000 and add each line into a List such that list.size <= 100000.
The list will then be returned to the calling method for processing then the calling method will ask for the next 100k lines beginning where it left off last time.

The code below is one version using a BufferedReader. I returns the first 100k lines fine, but in the next call, starting at line 100k+1, it starts slowing down at around row 150k, and around line 165k it results in an OutOfMemoryError. I looked around for a way to empty the buffer once it gets to the line where I want to begin adding to the list, but I couldn't find any info on that. I also tried to find a way to skip x number of rows, but I couldn't find anything on that.

public List<MyModel> retrieve(File inputFile, int startLine, String checksum) throws DaoException {

    List<MyModel> result = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new FileReader(inputFile))) {

          String line = null;
          int row = 0;
          int iteration = 0;

          try {
              while (((line = br.readLine()) != null) && iteration < MAX_ROWS) {
                  row++;
                  LOGGER.info("row: " + row + ", iteration: " + iteration);
                  if (row > startLine && iteration < MAX_ROWS) {
                      MyModel model = this.fileReader.populateMyModel(line);
                      model.setFileChecksum(checksum);
                      result.add(model);
                      iteration++;
                  }
                  if (iteration >= MAX_ROWS) {
                      break;
                  }
              }
          } catch (Exception e) {

              throw new FileReaderException("Failed to read line " + iteration + " of " + inputFile.getAbsolutePath(), e);
          }
    } catch (FileNotFoundException e1) {
          throw new FileReaderException("Could not find file '" + inputFile.getAbsolutePath() + "'.", e1);
    } catch (IOException e1) {
          throw new FileReaderException("Could not read file '" + inputFile.getAbsolutePath() + "'.", e1);
    }

        return result;
}

While trying to find out how to skip lines, I ran across the Java 8 Stream way of reading files and the code below is my attempt to deal with it that way. This one also works great on the first call, returning the first 100k lines. For the second call, where it begins with line 100k+1, it returns "java.lang.IllegalStateException: stream has already been operated upon or closed". Additionally, I ONLY want to read lines x thru x+100k then return, not cycle through all the lines of the file. I'm new to this Stream object, but it seems like using that should provide a solution.

public List<MyModel> retrieve(File inputFile, int startLine, String checksum) throws DaoException {
    List<MyModel> result = new ArrayList<>();

    try (Stream<String> lines = Files.lines(inputFile.toPath(), Charset.defaultCharset())) {
        lines.skip(startLine);
        lines
        .filter(line -> result.size() <= 100000)
        .forEach(line -> {
            result.add(this.fileReader.populateMyModel(line));
            if (result.size() % 10000 == 0) {
                LOGGER.info("result size: " + result.size());
            }
        });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}

Any suggestions would be helpful.

Body:
When you write:

lines.skip(startLine)

you create a new stream, but you don't save a reference to it, so you lose the operation.

I suspect you want something like:

return lines.skip(startLine)
            .limit(100000)
            .map(fileReader::populateMyModel)
            .collect(toList());