问:
python - readable list of objects
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

```<code><__main__.evolutions instance at 0x01B8EA08>
</code>```

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

答:
If you want to just display a particular attribute of each class instance, you can do

```<code>print([obj.attr for obj in my_list_of_objs])
</code>```

Which will print out the attr attribute of each object in the list my_list_of_objs.  Alternatively, you can define the __str__() method for your class, which specifies how to convert your objects into strings:

```<code>class evolutions:
    def __str__(self):
        # return string representation of self

print(my_list_of_objs)  # each object is now printed out according to its __str__() method
</code>```

Title: python - readable list of objects

Body:
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

<__main__.evolutions instance at 0x01B8EA08>

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

Body:
If you want to just display a particular attribute of each class instance, you can do

print([obj.attr for obj in my_list_of_objs])

Which will print out the attr attribute of each object in the list my_list_of_objs.  Alternatively, you can define the __str__() method for your class, which specifies how to convert your objects into strings:

class evolutions:
    def __str__(self):
        # return string representation of self

print(my_list_of_objs)  # each object is now printed out according to its __str__() method

OwnerDisplayName: Adam Rosenfield


来源: stackexchange

问:
How do I create a slug in Django?
I am trying to create a SlugField in Django.

I created this simple model:

```<code>from django.db import models

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()
</code>```

I then do this:

```<code>>>> from mysite.books.models import Test
>>> t=Test(q="aa a a a", s="b b b b")
>>> t.s
'b b b b'
>>> t.save()
>>> t.s
'b b b b'
</code>```

I was expecting b-b-b-b.

答:
If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False.  Otherwise you'll get an error when trying to save in Admin.

So a modification to the above example would be::

```<code>class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(null=True, blank=True) # Allow blank submission in admin.

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(test, self).save()
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I create a slug in Django?

Body:
I am trying to create a SlugField in Django.

I created this simple model:

from django.db import models

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

I then do this:

>>> from mysite.books.models import Test
>>> t=Test(q="aa a a a", s="b b b b")
>>> t.s
'b b b b'
>>> t.save()
>>> t.s
'b b b b'

I was expecting b-b-b-b.

Body:
If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False.  Otherwise you'll get an error when trying to save in Admin.

So a modification to the above example would be::

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField(null=True, blank=True) # Allow blank submission in admin.

    def save(self):
        if not self.id:
            self.s = slugify(self.q)

        super(test, self).save()

ContentLicense: CC BY-SA 2.5


问:
Asp.Net MVC 5 Angular Routing Not Working

It's showing error resource cannot found. it's work in MVC 4 project.
MVC Version issue or i'm missing something here? Please check screenshot for error details. Please help me to solve this problem . Thanks !

```<code>var APIURLPath = "http://localhost:51141/";
var SystemData;
var controllerProvider = null;
var LoadedMemberCards = [];
var AlfaCommApp = angular.module("AlfaCommApp", ['ngRoute', 'ngAvatar',
'angularFileUpload', 'angular-jquery-validate', 'ngDialog', 'ngSanitize',
'ui.bootstrap', 'ui.select'], function ($controllerProvider) {
controllerProvider = $controllerProvider;
}).config(function ($routeProvider)
{

$routeProvider.when('/Home',
 {
     templateUrl: '/AlfaUser/Home/Index'
 }).when('/AlfaUser/Connections',
 {
     templateUrl: '/AlfaUser/Home/Connections'
 }).when('/AlfaUser/Test123',
 {
     templateUrl: '/AlfaUser/Home/Test123'
 }).when('/AlfaUser/TestD',
 {
     templateUrl: '/AlfaUser/TestD/IndexA'
 }).otherwise({ redirectTo: '/Home' })
})
</code>```

Controller

```<code>public class TestDController : Controller
{
    public ActionResult IndexA()
    {
        return PartialView();
    }
}
</code>```

RouteConfig

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
using System.Web.Routing;

namespace AlfaCommUI
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

        routes.MapHttpRoute(
        name: "DefaultApiWithAction1",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Alfa", action = "Login", id = UrlParameter.Optional }
        );
    }
}
}
</code>```

答:
When you use AngularJS (version 1) with ASP MVC. Then Your angular Routing must as  same as ASP MVC routing.

Example:

ASP MVC Controller:

```<code>public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
</code>```

ASP MVC RouteConfig:

```<code>public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
</code>```

Angular App.js (I am Using ui-router for routing):

```<code>var myApp = angular.module('myApp', ['ngResource', 'ngSanitize', 'ngTouch', 'ui.router', 'ui.bootstrap']);

myApp.constant('appSettings', { serverPath: "http://localhost:13124" });

myApp.config([
    "$stateProvider", "$urlRouterProvider", "$locationProvider",
    function ($stateProvider, $urlRouterProvider, $locationProvider) {

        $stateProvider
            .state('/', {
                url: "/",
                templateUrl: "/Home/index"
                // ,controller: 'HomeController'
            })
            .state('/About', {
                url: "/Home/About",
                templateUrl: "/Home/About"
            })
            .state('/Contact', {
                url: "/Home/Contact",
                templateUrl: "/Home/Contact"
            })

        $urlRouterProvider.otherwise("/");
        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });
    }
]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It's showing error resource cannot found. it's work in MVC 4 project.
MVC Version issue or i'm missing something here? Please check screenshot for error details. Please help me to solve this problem . Thanks !

var APIURLPath = "http://localhost:51141/";
var SystemData;
var controllerProvider = null;
var LoadedMemberCards = [];
var AlfaCommApp = angular.module("AlfaCommApp", ['ngRoute', 'ngAvatar',
'angularFileUpload', 'angular-jquery-validate', 'ngDialog', 'ngSanitize',
'ui.bootstrap', 'ui.select'], function ($controllerProvider) {
controllerProvider = $controllerProvider;
}).config(function ($routeProvider)
{

$routeProvider.when('/Home',
 {
     templateUrl: '/AlfaUser/Home/Index'
 }).when('/AlfaUser/Connections',
 {
     templateUrl: '/AlfaUser/Home/Connections'
 }).when('/AlfaUser/Test123',
 {
     templateUrl: '/AlfaUser/Home/Test123'
 }).when('/AlfaUser/TestD',
 {
     templateUrl: '/AlfaUser/TestD/IndexA'
 }).otherwise({ redirectTo: '/Home' })
})

Controller

public class TestDController : Controller
{
    public ActionResult IndexA()
    {
        return PartialView();
    }
}

RouteConfig

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Http;
using System.Web.Routing;

namespace AlfaCommUI
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

        routes.MapHttpRoute(
        name: "DefaultApiWithAction1",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Alfa", action = "Login", id = UrlParameter.Optional }
        );
    }
}
}

Body:
When you use AngularJS (version 1) with ASP MVC. Then Your angular Routing must as  same as ASP MVC routing.

Example:

ASP MVC Controller:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

ASP MVC RouteConfig:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Angular App.js (I am Using ui-router for routing):

var myApp = angular.module('myApp', ['ngResource', 'ngSanitize', 'ngTouch', 'ui.router', 'ui.bootstrap']);

myApp.constant('appSettings', { serverPath: "http://localhost:13124" });

myApp.config([
    "$stateProvider", "$urlRouterProvider", "$locationProvider",
    function ($stateProvider, $urlRouterProvider, $locationProvider) {

        $stateProvider
            .state('/', {
                url: "/",
                templateUrl: "/Home/index"
                // ,controller: 'HomeController'
            })
            .state('/About', {
                url: "/Home/About",
                templateUrl: "/Home/About"
            })
            .state('/Contact', {
                url: "/Home/Contact",
                templateUrl: "/Home/Contact"
            })

        $urlRouterProvider.otherwise("/");
        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });
    }
]);


问:
How to adjust table for a plot? More space for table and graph matplotlib python
I want to separate or increase the distance of my table and my graph so they don't layover. I thought of increasing the size to right and put the table there but I can't seem to make it work, and I can't find a way to offset the table by 1 line.

Graph

```<code>global dataread
global top4
global iV
top4mod = [] #holder for table, combines amplitude and frequency (bin*3.90Hz)

plt.plot(x1, fy1, '-') #plot x-y
plt.axis([0, 500, 0, 1.2]) #range for x-y plot
plt.xlabel('Hz')

columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)] #top4
colors = 'C0'
print(len(rows))
print(len(str(top4)))
print(top4)

iV=[d*bins for d in iV]  # convert bins into frequency

i=0;
FirstCol = [4, 3, 2, 1]
while i < 4:
    Table.append([iV[i]] + [top4[i]])#[FirstCol[i]]
    i = i+1

cell_text = []
n_rows = len(Table)
index = np.arange(len(columns)) + 1  #0.3 orginal
bar_width = 0.4

y_offset = np.array([0.0] * len(columns))

for row in range(n_rows):
    #plt.bar(index, Table[row], bar_width, bottom=y_offset, color='C0')  #dont use this
    y_offset = y_offset + Table[row]
    cell_text.append(['%1.1f' % p for p in y_offset])

the_table = plt.table(cellText=Table,rowLabels=rows, colLabels=columns,loc='bottom')
#plt.figure(figsize=(7,8))

# Adjust layout to make room for the table:
plt.subplots_adjust(bottom=0.2) #left=0.2, bottom=0.2

plt.show() #display plot
</code>```

答:
Using bbox

You can set the position of the table using the bbox argument. It expects either a bbox instance or a 4-tuple of values (left, bottom, width, height), which are in axes coordinates. E.g.

```<code>plt.table(...,  bbox=[0.0,-0.5,1,0.3])
</code>```

produces a table that is as wide as the axes (left=0, width=1) but positionned below the axes (bottom=-0.5, height=0.3).

```<code>import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(4,2)
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)]

plt.plot(data[:,0], data[:,1], '-') #plot x-y
plt.axis([0, 1, 0, 1.2]) #range for x-y plot
plt.xlabel('Hz')

the_table = plt.table(cellText=data,rowLabels=rows, colLabels=columns,
                      loc='bottom', bbox=[0.0,-0.45,1,.28])
plt.subplots_adjust(bottom=0.3)
plt.show()
</code>```

Create dedicated axes

You can also create an axes (tabax) to put the table into. You would then set the loc to "center", turn the axis spines off and only use a very small subplots_adjust bottom parameter.

```<code>import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(4,2)
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)]

fig, (ax, tabax) = plt.subplots(nrows=2)

ax.plot(data[:,0], data[:,1], '-') #plot x-y
ax.axis([0, 1, 0, 1.2]) #range for x-y plot
ax.set_xlabel('Hz')

tabax.axis("off")
the_table = tabax.table(cellText=data,rowLabels=rows, colLabels=columns,
                      loc='center')
plt.subplots_adjust(bottom=0.05)
plt.show()
</code>```

Body:
I want to separate or increase the distance of my table and my graph so they don't layover. I thought of increasing the size to right and put the table there but I can't seem to make it work, and I can't find a way to offset the table by 1 line.

Graph

global dataread
global top4
global iV
top4mod = [] #holder for table, combines amplitude and frequency (bin*3.90Hz)

plt.plot(x1, fy1, '-') #plot x-y
plt.axis([0, 500, 0, 1.2]) #range for x-y plot
plt.xlabel('Hz')

columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)] #top4
colors = 'C0'
print(len(rows))
print(len(str(top4)))
print(top4)

iV=[d*bins for d in iV]  # convert bins into frequency

i=0;
FirstCol = [4, 3, 2, 1]
while i < 4:
    Table.append([iV[i]] + [top4[i]])#[FirstCol[i]]
    i = i+1

cell_text = []
n_rows = len(Table)
index = np.arange(len(columns)) + 1  #0.3 orginal
bar_width = 0.4

y_offset = np.array([0.0] * len(columns))

for row in range(n_rows):
    #plt.bar(index, Table[row], bar_width, bottom=y_offset, color='C0')  #dont use this
    y_offset = y_offset + Table[row]
    cell_text.append(['%1.1f' % p for p in y_offset])

the_table = plt.table(cellText=Table,rowLabels=rows, colLabels=columns,loc='bottom')
#plt.figure(figsize=(7,8))

# Adjust layout to make room for the table:
plt.subplots_adjust(bottom=0.2) #left=0.2, bottom=0.2

plt.show() #display plot

Body:
Using bbox

You can set the position of the table using the bbox argument. It expects either a bbox instance or a 4-tuple of values (left, bottom, width, height), which are in axes coordinates. E.g.

plt.table(...,  bbox=[0.0,-0.5,1,0.3])

produces a table that is as wide as the axes (left=0, width=1) but positionned below the axes (bottom=-0.5, height=0.3).

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(4,2)
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)]

plt.plot(data[:,0], data[:,1], '-') #plot x-y
plt.axis([0, 1, 0, 1.2]) #range for x-y plot
plt.xlabel('Hz')

the_table = plt.table(cellText=data,rowLabels=rows, colLabels=columns,
                      loc='bottom', bbox=[0.0,-0.45,1,.28])
plt.subplots_adjust(bottom=0.3)
plt.show()

Create dedicated axes

You can also create an axes (tabax) to put the table into. You would then set the loc to "center", turn the axis spines off and only use a very small subplots_adjust bottom parameter.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(4,2)
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)]

fig, (ax, tabax) = plt.subplots(nrows=2)

ax.plot(data[:,0], data[:,1], '-') #plot x-y
ax.axis([0, 1, 0, 1.2]) #range for x-y plot
ax.set_xlabel('Hz')

tabax.axis("off")
the_table = tabax.table(cellText=data,rowLabels=rows, colLabels=columns,
                      loc='center')
plt.subplots_adjust(bottom=0.05)
plt.show()


问:
TypeScript Default Value for property
I have defined an Interface in TypeScript like below:

```<code>export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;
    emailUserName?: string;
    emailPassword?: string;
}
</code>```

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name.
Update

```<code><div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
<label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />
</div>
<button (click)="goBack()">Back</button>
</div>
//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    }

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}
</code>```

goBack will output hero without location property if I do not enter any value for it in input.

答:
Cant you do?</p>

```<code>this.user.name?this.user.name:"";
</code>```

Title: TypeScript Default Value for property

Body:
I have defined an Interface in TypeScript like below:

export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;
    emailUserName?: string;
    emailPassword?: string;
}

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name.
Update

{{hero.name}} details!

id: {{hero.id}}

name:
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />

<button (click)="goBack()">Back</button>

//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    }

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}

goBack will output hero without location property if I do not enter any value for it in input.

Body:
Cant you do?

this.user.name?this.user.name:"";


问:
GNU Makefile wildcard for directory
I have several directories which may have subdirectories, and I'm going to compress each one to a file if any file in that directory is changed.

For example, I have 2 directories dir1 dir2, and I want to compress them to comp_dir1.tar.gz and comp_dir2.tar.gz.

I wrote the following code:

```<code>comp_%.tar.gz : %/$(shell find % -name "*")
    tar -czvf $@ $<
</code>```

But I got the error:

```<code>find: ‘%’: No such file or directory
</code>```

It is obvious that I can't use "%" in the shell command.

Is there any way to solve this?

答:
What you need in any case is a list of the directories you want to compress. Using that, you can use a GNU Make feature Remaking Makefiles to generate "dependency files" which include all files found in these directories. Here is a working example:

```<code>DIRECTORIES:=dir1 dir2
ARCHIVES:=$(addsuffix .tar.gz,$(addprefix comp_,$(DIRECTORIES)))

all: $(ARCHIVES)

comp_%.tar.gz.d: %
    echo $(@:.d=) $(@): $(shell find $< -name "*") > $(@)

# include the dependency files, this will cause GNU make to attempt creating
# them using the above pattern rule.
-include $(addsuffix .d,$(ARCHIVES))

comp_%.tar.gz: %
    tar czvf $@ $<

.PHONY: all
</code>```

Title: GNU Makefile wildcard for directory

Body:
I have several directories which may have subdirectories, and I'm going to compress each one to a file if any file in that directory is changed.

For example, I have 2 directories dir1 dir2, and I want to compress them to comp_dir1.tar.gz and comp_dir2.tar.gz.

I wrote the following code:

comp_%.tar.gz : %/$(shell find % -name "*")
    tar -czvf $@ $<

But I got the error:

find: ‘%’: No such file or directory

It is obvious that I can't use "%" in the shell command.

Is there any way to solve this?

Body:
What you need in any case is a list of the directories you want to compress. Using that, you can use a GNU Make feature Remaking Makefiles to generate "dependency files" which include all files found in these directories. Here is a working example:

DIRECTORIES:=dir1 dir2
ARCHIVES:=$(addsuffix .tar.gz,$(addprefix comp_,$(DIRECTORIES)))

all: $(ARCHIVES)

comp_%.tar.gz.d: %
    echo $(@:.d=) $(@): $(shell find $< -name "*") > $(@)

# include the dependency files, this will cause GNU make to attempt creating
# them using the above pattern rule.
-include $(addsuffix .d,$(ARCHIVES))

comp_%.tar.gz: %
    tar czvf $@ $<

.PHONY: all


问:
Loading wheel on initial webview loading
In android how can i show loading wheel on initial webview loading?

webview doesn't show loading when initializing webview in android.

答:
```<code>public class AppWebViewClients extends WebViewClient {
    private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}
</code>```

I think it help you.

Thanks.

Body:
public class AppWebViewClients extends WebViewClient {
    private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

I think it help you.

Thanks.


问:
Is there "Java Bean" like technology in PHP?
Is there something like the Java Bean stuff in PHP? Thank you.</p>

答: not by default... but frameworks are something similar because the framework (usually) allows you to to map the POST or GET, build forms and save the info into the db, according to a Model... Like when using beans.. =)</p>


问:
optimized rolling functions on irregular time series with time-based window
Is there some way to use rollapply (from zoo package or something similar) optimized functions (rollmean, rollmedian etc) to compute rolling functions with a time-based window, instead of one based on a number of observations? What I want is simple: for each element in an irregular time series, I want to compute a rolling function with a N-days window. That is, the window should include all the observations up to N days before the current observation. Time series may also contain duplicates.

Here follows an example. Given the following time series:

```<code>      date  value
 1/11/2011      5
 1/11/2011      4
 1/11/2011      2
 8/11/2011      1
13/11/2011      0
14/11/2011      0
15/11/2011      0
18/11/2011      1
21/11/2011      4
 5/12/2011      3
</code>```

A rolling median with a 5-day window, aligned to the right, should result in the following calculation:

```<code>> c(
    median(c(5)),
    median(c(5,4)),
    median(c(5,4,2)),
    median(c(1)),
    median(c(1,0)),
    median(c(0,0)),
    median(c(0,0,0)),
    median(c(0,0,0,1)),
    median(c(1,4)),
    median(c(3))
   )

 [1] 5.0 4.5 4.0 1.0 0.5 0.0 0.0 0.0 2.5 3.0
</code>```

I already found some solutions out there but they are usually tricky, which usually means slow. I managed to implement my own rolling function calculation. The problem is that for very long time series the optimized version of median (rollmedian) can make a huge time difference, since it takes into account the overlap between windows. I would like to avoid reimplementing it. I suspect there are some trick with rollapply parameters that will make it work, but I cannot figure it out. Thanks in advance for the help.

答:
Most of the answers suggest to insert NA to make the time series regular.
However, this can be slow in case of long time series. Additionally, it does not work for functions which can not be used with NA.

The width argument of rollapply (zoo package) can be a list (see help of rollapply for details). Based on this I wrote a function which creates a list to be used with rollapply as width parameter. The function extracts indexes for irregular zoo objects if the moving window is to be time and not index based. Therefore the index of the zoo object should be the actual time.

```<code># Create a zoo object where index represents time (e.g. in seconds)

d <- zoo(c(1,1,1,1,1,2,2,2,2,2,16,25,27,27,27,27,27,31),
         c(1:5,11:15,16,25:30,31))

# Create function

createRollapplyWidth = function(zoodata, steps, window ){

  mintime =  min(time(zoodata))

  maxtime =  max(time(zoodata))

  spotstime = seq(from = mintime , to = maxtime, by = steps)

  spotsindex = list()

    for (i in 1:length(spotstime)){
    spotsindex[[i]] =  as.numeric(which(spotstime[i]  <=  time(zoodata) & time(zoodata) < spotstime[i] + window))}

  rollapplywidth = list()
    for (i in 1:length(spotsindex)){
    if (!is.na(median(spotsindex[[i]])) ){
      rollapplywidth[[round(median(spotsindex[[i]]))]] = spotsindex[[i]] - round(median(spotsindex[[i]]))}
  }
  return(rollapplywidth)
  }

# Create width parameter for rollapply using function

rollwidth =  createRollapplyWidth(zoodata = d, steps = 5, window = 5)

# Use parameter in rollapply

result = rollapply(d, width = rollwidth , FUN =  sum, na.rm = T)
result
</code>```

Limitation: not based on dated but on time in seconds. Parameter "partial" of rollapply does not work.

Body:
Is there some way to use rollapply (from zoo package or something similar) optimized functions (rollmean, rollmedian etc) to compute rolling functions with a time-based window, instead of one based on a number of observations? What I want is simple: for each element in an irregular time series, I want to compute a rolling function with a N-days window. That is, the window should include all the observations up to N days before the current observation. Time series may also contain duplicates.

Here follows an example. Given the following time series:

      date  value
 1/11/2011      5
 1/11/2011      4
 1/11/2011      2
 8/11/2011      1
13/11/2011      0
14/11/2011      0
15/11/2011      0
18/11/2011      1
21/11/2011      4
 5/12/2011      3

A rolling median with a 5-day window, aligned to the right, should result in the following calculation:

> c(
    median(c(5)),
    median(c(5,4)),
    median(c(5,4,2)),
    median(c(1)),
    median(c(1,0)),
    median(c(0,0)),
    median(c(0,0,0)),
    median(c(0,0,0,1)),
    median(c(1,4)),
    median(c(3))
   )

 [1] 5.0 4.5 4.0 1.0 0.5 0.0 0.0 0.0 2.5 3.0

I already found some solutions out there but they are usually tricky, which usually means slow. I managed to implement my own rolling function calculation. The problem is that for very long time series the optimized version of median (rollmedian) can make a huge time difference, since it takes into account the overlap between windows. I would like to avoid reimplementing it. I suspect there are some trick with rollapply parameters that will make it work, but I cannot figure it out. Thanks in advance for the help.

Body:
Most of the answers suggest to insert NA to make the time series regular.
However, this can be slow in case of long time series. Additionally, it does not work for functions which can not be used with NA.

The width argument of rollapply (zoo package) can be a list (see help of rollapply for details). Based on this I wrote a function which creates a list to be used with rollapply as width parameter. The function extracts indexes for irregular zoo objects if the moving window is to be time and not index based. Therefore the index of the zoo object should be the actual time.

# Create a zoo object where index represents time (e.g. in seconds)

d <- zoo(c(1,1,1,1,1,2,2,2,2,2,16,25,27,27,27,27,27,31),
         c(1:5,11:15,16,25:30,31))

# Create function

createRollapplyWidth = function(zoodata, steps, window ){

  mintime =  min(time(zoodata))

  maxtime =  max(time(zoodata))

  spotstime = seq(from = mintime , to = maxtime, by = steps)

  spotsindex = list()

    for (i in 1:length(spotstime)){
    spotsindex[[i]] =  as.numeric(which(spotstime[i]  <=  time(zoodata) & time(zoodata) < spotstime[i] + window))}

  rollapplywidth = list()
    for (i in 1:length(spotsindex)){
    if (!is.na(median(spotsindex[[i]])) ){
      rollapplywidth[[round(median(spotsindex[[i]]))]] = spotsindex[[i]] - round(median(spotsindex[[i]]))}
  }
  return(rollapplywidth)
  }

# Create width parameter for rollapply using function

rollwidth =  createRollapplyWidth(zoodata = d, steps = 5, window = 5)

# Use parameter in rollapply

result = rollapply(d, width = rollwidth , FUN =  sum, na.rm = T)
result

Limitation: not based on dated but on time in seconds. Parameter "partial" of rollapply does not work.


问:
how do i connect to oracle with the info i have?
i have the info below from the oracle DBA and want to connect to oracle from a .net application. i just got done installing the oracle tools/ drivers for windows/ .net and now want to get a console app to connect tot he oracle DB and extract data from oracle into SQL server.

another solution would be to have SQL server pull from oracle all the records in the bugs table. i have no clue what the oracle connection string is and have tried to create a system DSN but failed at that prior to turning to the SO gurus...

ORACLE SQL user name is ‘USER_dev’,
  password is ‘welcome’.

Connection string is
  ‘jdbc:mercury:oracle://qct-ds2-p.apps.com:1139;sid=QCTRP1’

答:
go into your ORACLE_HOME\network\admin directory.  Create a file called tnsnames.ora if it is not there already.  Add this into it:

```<code>QCTRP1.WORLD =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = qct-ds2-p.apps.com)(PORT = 1139))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = QCTRP1)
    )
  )
</code>```

I'm making some assumptions here...

does qct-ds2-p.apps.com resolve?
looks like the DBA set it up the listener on port 1139... default is normally 1521 so you'll need to confirm.

You can then set up a connection string as follows:

```<code>Connection conn = DriverManager.getConnection
     ("jdbc:oracle:oci8:@QCTRP1.WORLD", "dev", "welcome");
</code>```

Body:
go into your ORACLE_HOME\network\admin directory.  Create a file called tnsnames.ora if it is not there already.  Add this into it:

QCTRP1.WORLD =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = qct-ds2-p.apps.com)(PORT = 1139))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = QCTRP1)
    )
  )

I'm making some assumptions here...

does qct-ds2-p.apps.com resolve?
looks like the DBA set it up the listener on port 1139... default is normally 1521 so you'll need to confirm.

You can then set up a connection string as follows:

Connection conn = DriverManager.getConnection
     ("jdbc:oracle:oci8:@QCTRP1.WORLD", "dev", "welcome");


问:
insert data into table that have one primary key, another foreign key using query
I wanna know how I can insert new fresh data into Doctor table that have one primary key another foreign key.

For example, I have I added values for person table as below, please show me how it's done on Doctor Table.

```<code>create table Doctor(
    DoctorID char(6) Primary Key,
    MedicalDegrees varchar(20),
    PersonID int not null REFERENCES Person (PersonID),
    check(DoctorID like '[a-z][a-z][0-9][0-9][0-9][0-9]'));
</code>```

```<code>create table Person(
    PersonID int Primary Key,
    FirstName varchar(15),
    LastName varchar(15),
    StreetAddress varchar(25),
    City varchar(15),
    State varchar(2),
    Zip varchar(5),
    PhoneNumber varchar(10),
    SSN varchar(9) UNIQUE);
</code>```

```<code>insert into person values('1', 'John', 'Smith', '2343 sdf', 'Tacoma', 'WA', 98001, 5268964563, 564657415)
</code>```

Much thanks in advance

答:
What do you mean by How to add data into Doctor table?

Just like you added records to person table, you can add the records to the Doctor table.

Because Doctor table has a reference column to person table you have to insert the record in person table first then into Doctor table and the value of PersonId in Doctor table must exists in Person table.

Please add the query and issues you are facing while inserting data into referenced table.

Body:
I wanna know how I can insert new fresh data into Doctor table that have one primary key another foreign key.

For example, I have I added values for person table as below, please show me how it's done on Doctor Table.

create table Doctor(
    DoctorID char(6) Primary Key,
    MedicalDegrees varchar(20),
    PersonID int not null REFERENCES Person (PersonID),
    check(DoctorID like '[a-z][a-z][0-9][0-9][0-9][0-9]'));

create table Person(
    PersonID int Primary Key,
    FirstName varchar(15),
    LastName varchar(15),
    StreetAddress varchar(25),
    City varchar(15),
    State varchar(2),
    Zip varchar(5),
    PhoneNumber varchar(10),
    SSN varchar(9) UNIQUE);

insert into person values('1', 'John', 'Smith', '2343 sdf', 'Tacoma', 'WA', 98001, 5268964563, 564657415)

Much thanks in advance


问:
Why does the serial value get printed twice along with a value that is not sent?
Using the code below, I am trying to print the value that is received through the Arduino serial. But the value gets printed twice. And one among the printed values is always 0.

byte b;
int i;

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(10);
}

void loop() {
  while(Serial.available() == 0) {}
  i = Serial.parseInt();
  Serial.println(i);
}

EXAMPLE: value sent is 15
Serial monitor output: 15
                       0

EXAMPLE: value sent is 99
Serial monitor output: 99
                       0
```

答:
That's because the first i = Serial.parseInt(); prints the read value and returns 0 to the i variable, which means that the value was printed successfully.

On the second Serial.println(i);, you just print the i value, which was 0.


问:
Biopython script is not working, it sends errortype generator
I am having a few errors I don't understand when trying to parse an xml file with biopython, can anyone help me to understand this, please?</p>

```<code>TypeError: object of type 'generator' has no len()

    from Bio import SearchIO
    blast_qresults=SearchIO.parse('my_file.xml', 'blast-xml')
    len(blast_qresults)

    or

    blast_qresults.hit

AttributeError: 'generator' object has no attribute 'hit
</code>```

答:
I believe this is the syntax you want:

```<code>from Bio import SearchIO

blast_qresults = SearchIO.parse('my_file.xml', 'blast-xml')

for hit in blast_qresults:
    print(hit)
</code>```

Since blast_qresults is a generator, you can only "walk" it once.

Body:
I am having a few errors I don't understand when trying to parse an xml file with biopython, can anyone help me to understand this, please?

TypeError: object of type 'generator' has no len()

    from Bio import SearchIO
    blast_qresults=SearchIO.parse('my_file.xml', 'blast-xml')
    len(blast_qresults)

    or

    blast_qresults.hit

AttributeError: 'generator' object has no attribute 'hit

Body:
I believe this is the syntax you want:

from Bio import SearchIO

blast_qresults = SearchIO.parse('my_file.xml', 'blast-xml')

for hit in blast_qresults:
    print(hit)

Since blast_qresults is a generator, you can only "walk" it once.


问:
In Java my array seems to only store my last added value
Hi I am fairly new at this as you can see but I am trying to make a very basic hang man game. If the users guess is correct I would like to make an array of what letters he has got right so far. But all I get is the last keyboard input saved in the array.

Here is the code.

```<code>do {
    System.out.println("Choose a letter: ");
    firstGuess = keyboard.next();
    String [] GuessedWordSoFar = new String[wordToGuess.length()];
    char[] wordToGuessInCharArray = wordToGuess.toCharArray();

    if((new String(wordToGuessInCharArray).contains(firstGuess))){
        int index = -1;
        char c = firstGuess.charAt(0);
        for(int z = 0; (z <wordToGuessInCharArray.length)&&
           (index == -1); z++){

            if( wordToGuessInCharArray[z] == c) {
                index = z;
                System.out.println("Correct");
                GuessedWordSoFar[index] = firstGuess;
            }
        }
        System.out.println(Arrays.asList(GuessedWordSoFar));
    }
</code>```

答:
The problem is that the initialization of the GuessedWordSoFar array is inside the do-while loop, so it gets reset each time the loop executes.
Try the code below, this should fix your error.</p>

```<code>String [] GuessedWordSoFar = new String[wordToGuess.length()];
do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();

char[] wordToGuessInCharArray = wordToGuess.toCharArray();

if((new String(wordToGuessInCharArray).contains(firstGuess))){
    int index = -1;
    char c = firstGuess.charAt(0);
    for(int z = 0; (z <wordToGuessInCharArray.length)&&
       (index == -1); z++){

        if( wordToGuessInCharArray[z] == c) {
            index = z;
            System.out.println("Correct");
            GuessedWordSoFar[index] = firstGuess;
        }
    }
    System.out.println(Arrays.asList(GuessedWordSoFar));
}
</code>```

Body:
Hi I am fairly new at this as you can see but I am trying to make a very basic hang man game. If the users guess is correct I would like to make an array of what letters he has got right so far. But all I get is the last keyboard input saved in the array.

Here is the code.

do {
    System.out.println("Choose a letter: ");
    firstGuess = keyboard.next();
    String [] GuessedWordSoFar = new String[wordToGuess.length()];
    char[] wordToGuessInCharArray = wordToGuess.toCharArray();

    if((new String(wordToGuessInCharArray).contains(firstGuess))){
        int index = -1;
        char c = firstGuess.charAt(0);
        for(int z = 0; (z <wordToGuessInCharArray.length)&&
           (index == -1); z++){

            if( wordToGuessInCharArray[z] == c) {
                index = z;
                System.out.println("Correct");
                GuessedWordSoFar[index] = firstGuess;
            }
        }
        System.out.println(Arrays.asList(GuessedWordSoFar));
    }

Body:
The problem is that the initialization of the GuessedWordSoFar array is inside the do-while loop, so it gets reset each time the loop executes.
Try the code below, this should fix your error.

String [] GuessedWordSoFar = new String[wordToGuess.length()];
do {
System.out.println("Choose a letter: ");
firstGuess = keyboard.next();

char[] wordToGuessInCharArray = wordToGuess.toCharArray();

if((new String(wordToGuessInCharArray).contains(firstGuess))){
    int index = -1;
    char c = firstGuess.charAt(0);
    for(int z = 0; (z <wordToGuessInCharArray.length)&&
       (index == -1); z++){

        if( wordToGuessInCharArray[z] == c) {
            index = z;
            System.out.println("Correct");
            GuessedWordSoFar[index] = firstGuess;
        }
    }
    System.out.println(Arrays.asList(GuessedWordSoFar));
}


问:
Class based impersonation
Is it possible for a class to impersonate its identity? For example, Class A attempts to access Class B methods. Class B methods uses getClass().getName() to attempt to check Class A to ensure it is who it is. Can impersonation take place ? e.g. Class C impersonates Class A to get pass the getclass().getName() Class B uses for checks?

If Class B wants to implement getClass().getName() for checks effective on the sample method below, how do I implement it properly in the sample code below ?

```<code>public byte[] getStoragePrivateKey(String application) {
    if (application.getClass().getName().equals("correctClass") {
        // Allow access to Private Key.
    } else {
        // Access denied
    }
}
</code>```

The above example is a simulation of a plugin applet in the system trying to access an internal key server database in the system.

答:
This won't work:
In your example application.getClass().getName() will always return "java.lang.String", as you are getting the type of the "application" parameter.

Moreover, in Java, the invoked method can not find out the type from where it's being invoked, so perhaps, you should check your design, implementing some other kind of access control.

EDIT: let me add an example, based on your code, on how you could try to check the type of the invoker, and how it would not avoid invocations from other sources:

```<code>//Change the String for an Object, to allow the invoker pass a
//reference to itself
public byte[] getStoragePrivateKey(Object application) {
    if (application.getClass().getName().equals("correctClass") {
        // Allow access to Private Key.
    } else {
        // Access denied
    }
}
</code>```

From the referencing type A, the invoking could be:

```<code>  B b=new B();
  byte[] key=b.getStoragePrivateKey(this);
</code>```

Calling it from a C "impersonator" class, would fail, as this is a C.class instance:

```<code>  B b=new B();
  byte[] key=b.getStoragePrivateKey(this);
</code>```

But, avoiding the validation it's as easy as:

```<code>  B b=new B();
  A a=new A();
  byte[] key=b.getStoragePrivateKey(a);
</code>```

Title: Class based impersonation

Body:
Is it possible for a class to impersonate its identity? For example, Class A attempts to access Class B methods. Class B methods uses getClass().getName() to attempt to check Class A to ensure it is who it is. Can impersonation take place ? e.g. Class C impersonates Class A to get pass the getclass().getName() Class B uses for checks?

If Class B wants to implement getClass().getName() for checks effective on the sample method below, how do I implement it properly in the sample code below ?

public byte[] getStoragePrivateKey(String application) {
    if (application.getClass().getName().equals("correctClass") {
        // Allow access to Private Key.
    } else {
        // Access denied
    }
}

The above example is a simulation of a plugin applet in the system trying to access an internal key server database in the system.

Body:
This won't work:
In your example application.getClass().getName() will always return "java.lang.String", as you are getting the type of the "application" parameter.

Moreover, in Java, the invoked method can not find out the type from where it's being invoked, so perhaps, you should check your design, implementing some other kind of access control.

EDIT: let me add an example, based on your code, on how you could try to check the type of the invoker, and how it would not avoid invocations from other sources:

//Change the String for an Object, to allow the invoker pass a
//reference to itself
public byte[] getStoragePrivateKey(Object application) {
    if (application.getClass().getName().equals("correctClass") {
        // Allow access to Private Key.
    } else {
        // Access denied
    }
}

From the referencing type A, the invoking could be:

  B b=new B();
  byte[] key=b.getStoragePrivateKey(this);

Calling it from a C "impersonator" class, would fail, as this is a C.class instance:

  B b=new B();
  byte[] key=b.getStoragePrivateKey(this);

But, avoiding the validation it's as easy as:

  B b=new B();
  A a=new A();
  byte[] key=b.getStoragePrivateKey(a);


问:
Jetty, force webapp to use different javax.mail from that one included in server lib/jndi
I'm quite newbie in Jetty, I've used Tomcat for many years, I would like to know the best practice to force my webapp to use javax.mail 1.5.5 since it is using javax.mail.glassfish-1.4.1.v201005082020.jar found on /srv/jetty/lib/jndi of jetty 9.3.10.

I don't believe it is safe replace that version with that one wanted by my webapplication, is it true?

At last if the best practice was to update the jar leaving it where it is, then should I remove that dependency from my webapp, in a way that in WEB-INF/lib it shouldn't be present?

Really thanks in advance

答:
To my knowledge there is no mechanism to force a servlet container like jetty to use the bundled mail-jar from your war file.

If You do not need the jetty jndi - mail - feature, documented here just get rid of the jar.

Interestingly Java Mail FAQ points this out regarding tomcat:

Q: How do I configure Tomcat to allow me to use JavaMail in my web
  application?  A: To run a web application using JavaMail, you can add
  the JavaMail javax.mail.jar file and, if you're not using JDK 1.6 or
  newer, the JavaBeans Activation Framework javax.activation.jar file to
  the lib directory under the directory in which you installed Tomcat.
  This will cause Tomcat to include these jar files in its classpath
  automatically. For details, see JNDI Resources HOW-TO in the Tomcat
  documentation. Alternatively, you can package the mail.jar file and
  activation.jar files in the lib directory of your web application
  package (war file).

So Java Mail points falsely out that you just need to bundle it with your war file.

Also from the FAQ

If you're running in a web server or application server, it may be
  providing its own version of mail.jar in one of its directories. You
  should only have one version of mail.jar available to your
  application.

https://javaee.github.io/javamail/FAQ


问:
PyQt5 5.8.2 QLineEdit has no attribute 'setPlaceHolderText'
I'm trying figure out whats wrong with my PyQt5 install, I've looked at all the documentation and I should be able to use placeHolderText and setPlaceHolderText() but it doesn't look like it does. The QtWidgets.QLineEdit() works and shows up on my gui but can get it to setPlaceHolderText. Also QLayout.setFixedSize also returns the same error. Importing PyQt5 doesn't return any errors so these should work too.

I installed PyQt5 through pip3 on python 3.5.2, has anyone had this issue before, I'm not sure what I've done wrong.

答:
so umm... sightly embarrassing,
setPlaceHolderText() is suppose to have a lowercase h -> setPlaceholderText()
and QLayout.setFixedSize is suppose to have uppercase S -> SetFixedSize()


问:
Router is not defined Node.js
I am new with Node.js, and I am trying to create an HTTP server, but for some reason, when I try to put the router for purchase URL request, it doesn't work.

My code :

Server.js

```<code>var url = require("url");
var http = require("http");

function start() {
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request received.");

    route(pathname);

    response.writeHead(200, {"Content-Type" : "text/plain"});
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started;");
}

exports.start = start;
</code>```

Index.js

```<code>var server = require("./server");
var router = require("./router");

server.start(router.route);
</code>```

Router.js

```<code>function route(pathname) {
    console.log("About to route a request for " + pathname);
}

exports.route = route;
</code>```

When trying to start the server through the Node.js, it says the follow error :

route is not defined

route(pathname);

How can I make this work ?

答:
You're passing the route to the start function but a parameter isn't defined, you need to add one.

```<code>function start(route) {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request received.");

        route(pathname);

        response.writeHead(200, {
            "Content-Type": "text/plain"
        });
        response.write("Hello World");
        response.end();
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server has started;");
}
</code>```

Title: Router is not defined Node.js

Body:
I am new with Node.js, and I am trying to create an HTTP server, but for some reason, when I try to put the router for purchase URL request, it doesn't work.

My code :

Server.js

var url = require("url");
var http = require("http");

function start() {
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request received.");

    route(pathname);

    response.writeHead(200, {"Content-Type" : "text/plain"});
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started;");
}

exports.start = start;

Index.js

var server = require("./server");
var router = require("./router");

server.start(router.route);

Router.js

function route(pathname) {
    console.log("About to route a request for " + pathname);
}

exports.route = route;

When trying to start the server through the Node.js, it says the follow error :

route is not defined

route(pathname);

How can I make this work ?

Body:
You're passing the route to the start function but a parameter isn't defined, you need to add one.

function start(route) {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request received.");

        route(pathname);

        response.writeHead(200, {
            "Content-Type": "text/plain"
        });
        response.write("Hello World");
        response.end();
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server has started;");
}


问:
Lagom: Asynchronous Operations in Command Handlers
In Lagom, what do you do when a command handler must perform some asynchronous operations? For example:

```<code>override def behavior = Actions().onCommand[MyCommand, Done] {
  case (cmd, ctx, state) =>
    // some complex code that performs asynchronous operations
    // (for example, querying other persistent entities or the read-side
    // by making calls that return Future[...] and composing those),
    // as summarized in a placeholder below:
    val events: Future[Seq[Event]] = ???
    events map {
      xs => ctx.thenPersistAll(xs: _*) { () => ctx.reply(Done) }
    }
}
</code>```

The problem with the code like that is that the compiler expects the command handler to return Persist, not Future[Persist].

Is this done on purpose, to make sure that the events are persisted in the correct order (that is, the events generated by a prior command must be saved before the events generated by a later command)? But can't that be handled by proper management of the event offsets, so that the journal always orders them correctly, regardless of when they are actually saved?

And what does one do in situations like this, when the command handling is complex enough to require making asynchronous calls from the command handler?

答:
What I've been doing in these cases is to pass the PersistentEntityRef to the asynchronous operation, so that it can issue commands to the entity and its those command-handlers (not the one that spawned the async computation) that then persist the events.

Just bear in mind that none of this is atomic, so you have to think about what happens if the asynchronous operation fails midway through issuing the commands or if some commands succeed and some fail, etc. Presumably you'll want some retry mechanism for systemic failures. If you build your command-handlers to be idempotent, it will help you deal with the duplicates.

Body:
In Lagom, what do you do when a command handler must perform some asynchronous operations? For example:

override def behavior = Actions().onCommand[MyCommand, Done] {
  case (cmd, ctx, state) =>
    // some complex code that performs asynchronous operations
    // (for example, querying other persistent entities or the read-side
    // by making calls that return Future[...] and composing those),
    // as summarized in a placeholder below:
    val events: Future[Seq[Event]] = ???
    events map {
      xs => ctx.thenPersistAll(xs: _*) { () => ctx.reply(Done) }
    }
}

The problem with the code like that is that the compiler expects the command handler to return Persist, not Future[Persist].

Is this done on purpose, to make sure that the events are persisted in the correct order (that is, the events generated by a prior command must be saved before the events generated by a later command)? But can't that be handled by proper management of the event offsets, so that the journal always orders them correctly, regardless of when they are actually saved?

And what does one do in situations like this, when the command handling is complex enough to require making asynchronous calls from the command handler?


问:
Extracting unique rows from a data table in R
I'm migrating from data frames and matrices to data tables, but haven't found a solution for extracting the unique rows from a data table.  I presume there's something I'm missing about the [,J] notation, though I've not yet found an answer in the FAQ and intro vignettes.  How can I extract the unique rows, without converting back to data frames?

Here is an example:

```<code>library(data.table)
set.seed(123)
a <- matrix(sample(2, 120, replace = TRUE), ncol = 3)
a <- as.data.frame(a)
b <- as.data.table(a)

# Confirm dimensionality
dim(a) # 40  3
dim(b) # 40  3

# Unique rows using all columns
dim(unique(a))  # 8 3
dim(unique(b))  # 34 3

# Unique rows using only a subset of columns
dim(unique(a[,c("V1","V2")]))   # 4 2
dim(unique(b[,list(V1,V2)]))    # 29 2
</code>```

Related question: Is this behavior a result of the data being unsorted, as with the Unix uniq function?

答:
As mentioned by Seth the data.table package has evolved and now proposes optimized functions for this.

To all the ones who don't want to get into the documentation, here is the fastest and most memory efficient way to do what you want :

```<code>uniqueN(a)
</code>```

And if you only want to choose a subset of columns you could use the 'by' argument :

uniqueN(a,by = c('V1','V2'))

EDIT : As mentioned in the comments this will only gives the count of unique rows. To get the unique values, use unique instead :

unique(a)

And for a subset :

unique(a[c('V1',"V2")], by=c('V1','V2'))

Body:
I'm migrating from data frames and matrices to data tables, but haven't found a solution for extracting the unique rows from a data table.  I presume there's something I'm missing about the [,J] notation, though I've not yet found an answer in the FAQ and intro vignettes.  How can I extract the unique rows, without converting back to data frames?

Here is an example:

library(data.table)
set.seed(123)
a <- matrix(sample(2, 120, replace = TRUE), ncol = 3)
a <- as.data.frame(a)
b <- as.data.table(a)

# Confirm dimensionality
dim(a) # 40  3
dim(b) # 40  3

# Unique rows using all columns
dim(unique(a))  # 8 3
dim(unique(b))  # 34 3

# Unique rows using only a subset of columns
dim(unique(a[,c("V1","V2")]))   # 4 2
dim(unique(b[,list(V1,V2)]))    # 29 2

Related question: Is this behavior a result of the data being unsorted, as with the Unix uniq function?

Body:
As mentioned by Seth the data.table package has evolved and now proposes optimized functions for this.

To all the ones who don't want to get into the documentation, here is the fastest and most memory efficient way to do what you want :

uniqueN(a)

And if you only want to choose a subset of columns you could use the 'by' argument :

uniqueN(a,by = c('V1','V2'))

EDIT : As mentioned in the comments this will only gives the count of unique rows. To get the unique values, use unique instead :

unique(a)

And for a subset :

unique(a[c('V1',"V2")], by=c('V1','V2'))


问:
bootstrap 3 show label and btn inline
The code below shows label and button in vertical, I want to show inline. It's necessary and important the first div.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Productos

    <button class="btn btn-success" type="button">Sleccione

                            </button>

HTML

CSS

Java

```

答:
You can add following code of style:</p>

```<code><style>
    .label-success{
         float:left;
    }
</style>
</code>```

Title: bootstrap 3 show label and btn inline

Body:
You can add following code of style:

<style>
    .label-success{
         float:left;
    }
</style>


问:
How to determine length of OGG file
I'm making a rhythm game and I need a quick way to get the length of an ogg file. The only way I could think would be to stream the file really fast without playing it but if I have hundreds of songs this would obviously not be practical. Another way would be to store the length of the file in some sort of properties file but I would like to avoid this. I know there must be some way to do this as most music players can tell you the length of a song. </p>

答:
I implemented the solution described by ioctlLR and it seems to work:

```<code>double calculateDuration(final File oggFile) throws IOException {
    int rate = -1;
    int length = -1;

    int size = (int) oggFile.length();
    byte[] t = new byte[size];

    FileInputStream stream = new FileInputStream(oggFile);
    stream.read(t);

    for (int i = size-1-8-2-4; i>=0 && length<0; i--) { //4 bytes for "OggS", 2 unused bytes, 8 bytes for length
        // Looking for length (value after last "OggS")
        if (
                t[i]==(byte)'O'
                && t[i+1]==(byte)'g'
                && t[i+2]==(byte)'g'
                && t[i+3]==(byte)'S'
        ) {
            byte[] byteArray = new byte[]{t[i+6],t[i+7],t[i+8],t[i+9],t[i+10],t[i+11],t[i+12],t[i+13]};
            ByteBuffer bb = ByteBuffer.wrap(byteArray);
            bb.order(ByteOrder.LITTLE_ENDIAN);
            length = bb.getInt(0);
        }
    }
    for (int i = 0; i<size-8-2-4 && rate<0; i++) {
        // Looking for rate (first value after "vorbis")
        if (
                t[i]==(byte)'v'
                && t[i+1]==(byte)'o'
                && t[i+2]==(byte)'r'
                && t[i+3]==(byte)'b'
                && t[i+4]==(byte)'i'
                && t[i+5]==(byte)'s'
        ) {
            byte[] byteArray = new byte[]{t[i+11],t[i+12],t[i+13],t[i+14]};
            ByteBuffer bb = ByteBuffer.wrap(byteArray);
            bb.order(ByteOrder.LITTLE_ENDIAN);
            rate = bb.getInt(0);
        }

    }
    stream.close();

    double duration = (double) (length*1000) / (double) rate;
    return duration;
}
</code>```

Beware, finding the rate this way will work only for vorbis OGG!

Feel free to edit my answer, it may not be perfect.

Title: How to determine length of OGG file

Body:
I implemented the solution described by ioctlLR and it seems to work:

double calculateDuration(final File oggFile) throws IOException {
    int rate = -1;
    int length = -1;

    int size = (int) oggFile.length();
    byte[] t = new byte[size];

    FileInputStream stream = new FileInputStream(oggFile);
    stream.read(t);

    for (int i = size-1-8-2-4; i>=0 && length<0; i--) { //4 bytes for "OggS", 2 unused bytes, 8 bytes for length
        // Looking for length (value after last "OggS")
        if (
                t[i]==(byte)'O'
                && t[i+1]==(byte)'g'
                && t[i+2]==(byte)'g'
                && t[i+3]==(byte)'S'
        ) {
            byte[] byteArray = new byte[]{t[i+6],t[i+7],t[i+8],t[i+9],t[i+10],t[i+11],t[i+12],t[i+13]};
            ByteBuffer bb = ByteBuffer.wrap(byteArray);
            bb.order(ByteOrder.LITTLE_ENDIAN);
            length = bb.getInt(0);
        }
    }
    for (int i = 0; i<size-8-2-4 && rate<0; i++) {
        // Looking for rate (first value after "vorbis")
        if (
                t[i]==(byte)'v'
                && t[i+1]==(byte)'o'
                && t[i+2]==(byte)'r'
                && t[i+3]==(byte)'b'
                && t[i+4]==(byte)'i'
                && t[i+5]==(byte)'s'
        ) {
            byte[] byteArray = new byte[]{t[i+11],t[i+12],t[i+13],t[i+14]};
            ByteBuffer bb = ByteBuffer.wrap(byteArray);
            bb.order(ByteOrder.LITTLE_ENDIAN);
            rate = bb.getInt(0);
        }

    }
    stream.close();

    double duration = (double) (length*1000) / (double) rate;
    return duration;
}

Beware, finding the rate this way will work only for vorbis OGG!

Feel free to edit my answer, it may not be perfect.


问:
firebase messages unexpectedly found nil
I have a tableviewcontroller that has a list of all the messages a logged in user has sent any user of hi/her choice in the app:

The messages between the logged in user and any other user of the app is appended and displayed in the tableviewcell using this code:

```<code>func loadData()
{

    FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

        if let postsDictionary = snapshot .value as? [String: AnyObject] {

            for post in postsDictionary {
                let messages = post.value as! [String: AnyObject]
                for (id, value) in messages {
                    let info = value as! [String: AnyObject]

                    let convoId = info["convoId"]
                    let toId = info["ReceiverId"] as! String!
                    let fromId = info["senderId"] as! String!

                    if (toId == self.loggedInUserUid  || fromId == self.loggedInUserUid) {

    let ref = FIRDatabase.database().reference().child("messages").child(convoId as! String)
    ref.observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let message = Message(dictionary: dictionary)
            //                self.messages.append(message)

            if let receiver = message.convoId {
                self.messagesDictionary[receiver] = message

                self.messages = Array(self.messagesDictionary.values)
                print(self.messages)
                self.messages.sort(by: { (message1, message2) -> Bool in

                    return (message1.timestamp?.int32Value)! > (message2.timestamp?.int32Value)!

                })
            }

            //this will crash because of background thread, so lets call this on dispatch_async main thread
            DispatchQueue.main.async(execute: {
                self.MessageTableView.reloadData()
            })
        }

    }, withCancel: nil)}
                }

            }}})

}
</code>```

However, when I click a cell, I would like to go to a detailed view controller that shows the messages between the logged in user and the user of the cell clicked, so i use this code to segue:

```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

             let message = messages[indexPath.row]

            if message.ReceiverId != self.loggedInUserUid {
                var newVariable = message.ReceiverId

                if let userpicuid =  newVariable {

                    let ref = FIRDatabase.database().reference().child("users").child(userpicuid)

                    ref.observeSingleEvent(of: .value, with: { (snapshot)
                        in

                        if let dictionary = snapshot.value as? [String: AnyObject]{
                            for post in dictionary {
                                let messages = post.value as! [String: AnyObject]
                                for (id, value) in messages {

                                    let username = messages["username"] as? String
                                    self.userpicuid = userpicuid
                                    self.username = username

                                }}}})}} else if message.senderId != self.loggedInUserUid {
                let newVariable = message.senderId

                if let userpicuid =  newVariable {

                    let ref = FIRDatabase.database().reference().child("users").child(userpicuid)

                    ref.observeSingleEvent(of: .value, with: { (snapshot)
                        in

                        if let dictionary = snapshot.value as? [String: AnyObject]{
                            for post in dictionary {
                                let messages = post.value as! [String: AnyObject]
                                for (id, value) in messages {

                                    let username = messages["username"] as? String
                                    self.userpicuid = userpicuid
                                    self.username = username
                                }}}})}

            }

       performSegue(withIdentifier: "MessageNow", sender: self)

    }

    override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "MessageNow", let chatVc = segue.destination as? SendMessageViewController else {
            return
        }

        print(self.userpicuid)

        chatVc.senderId = self.loggedInUser?.uid
        chatVc.receiverData = self.userpicuid
        chatVc.senderDisplayName = self.userpicuid
        chatVc.username = self.username

    }
</code>```

However, when I click on the cell, I get the error fatal error: unexpectedly found nil while unwrapping an Optional value So I included some print statements to find out where the nil is. Turns out userpicuid and username is returning nil. I am not sure what I am doing wrong especially because my code is checking the receiverId and the senderId and is one of them is not the logged in user's uid then that uid should be the senderId that segues to the detailed messages.

The error is on the let receiverId = receiverData! line in the detailed messages view controller:

```<code>var receiverData: String?

     override func viewDidLoad() {
            super.viewDidLoad()
    let receiverId = receiverData!
            let receiverIdFive = String(receiverId.characters.prefix(5))
            let senderIdFive = String(senderId.characters.prefix(5))
            if (senderIdFive > receiverIdFive)
            {
                self.convoId = senderIdFive + receiverIdFive
            }
            else
            {
                self.convoId = receiverIdFive + senderIdFive
            }
    }
</code>```

答:
I found the solution to the question using this:</p>

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageTableViewCell

    if message.ReceiverId != self.loggedInUserUid {
        var newVariable = message.ReceiverId

    if let imageName =  newVariable {

        let ref = FIRDatabase.database().reference().child("users").child(imageName)

        ref.observeSingleEvent(of: .value, with: { (snapshot)
            in

            if let dictionary = snapshot.value as? [String: AnyObject]{
                for post in dictionary {
                    let messages = post.value as! [String: AnyObject]
                    for (id, value) in messages {

                        self.username = messages["username"] as? String
                        self.userpicuid = messages["uid"] as? String

            }}}})}}else if message.senderId != self.loggedInUserUid {
        let newVariable = message.senderId

        if let imageName =  newVariable {

            let ref = FIRDatabase.database().reference().child("users").child(imageName)

            ref.observeSingleEvent(of: .value, with: { (snapshot)
                in

                if let dictionary = snapshot.value as? [String: AnyObject]{
                    for post in dictionary {
                        let messages = post.value as! [String: AnyObject]
                        for (id, value) in messages {

                            self.username = messages["username"] as? String
                            self.userpicuid = messages["uid"] as? String

                        }}}})}
    }
    return cell
}

  override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "MessageNow", let chatVc = segue.destination as? SendMessageViewController else {
            return
        }

                                chatVc.senderId = self.loggedInUser?.uid
                                chatVc.receiverData = self.userpicuid
                                chatVc.senderDisplayName = self.userpicuid
                                chatVc.username = self.username

    }
</code>```

Body:
I have a tableviewcontroller that has a list of all the messages a logged in user has sent any user of hi/her choice in the app:

The messages between the logged in user and any other user of the app is appended and displayed in the tableviewcell using this code:

func loadData()
{

    FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

        if let postsDictionary = snapshot .value as? [String: AnyObject] {

            for post in postsDictionary {
                let messages = post.value as! [String: AnyObject]
                for (id, value) in messages {
                    let info = value as! [String: AnyObject]

                    let convoId = info["convoId"]
                    let toId = info["ReceiverId"] as! String!
                    let fromId = info["senderId"] as! String!

                    if (toId == self.loggedInUserUid  || fromId == self.loggedInUserUid) {

    let ref = FIRDatabase.database().reference().child("messages").child(convoId as! String)
    ref.observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let message = Message(dictionary: dictionary)
            //                self.messages.append(message)

            if let receiver = message.convoId {
                self.messagesDictionary[receiver] = message

                self.messages = Array(self.messagesDictionary.values)
                print(self.messages)
                self.messages.sort(by: { (message1, message2) -> Bool in

                    return (message1.timestamp?.int32Value)! > (message2.timestamp?.int32Value)!

                })
            }

            //this will crash because of background thread, so lets call this on dispatch_async main thread
            DispatchQueue.main.async(execute: {
                self.MessageTableView.reloadData()
            })
        }

    }, withCancel: nil)}
                }

            }}})

}

However, when I click a cell, I would like to go to a detailed view controller that shows the messages between the logged in user and the user of the cell clicked, so i use this code to segue:

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

             let message = messages[indexPath.row]

            if message.ReceiverId != self.loggedInUserUid {
                var newVariable = message.ReceiverId

                if let userpicuid =  newVariable {

                    let ref = FIRDatabase.database().reference().child("users").child(userpicuid)

                    ref.observeSingleEvent(of: .value, with: { (snapshot)
                        in

                        if let dictionary = snapshot.value as? [String: AnyObject]{
                            for post in dictionary {
                                let messages = post.value as! [String: AnyObject]
                                for (id, value) in messages {

                                    let username = messages["username"] as? String
                                    self.userpicuid = userpicuid
                                    self.username = username

                                }}}})}} else if message.senderId != self.loggedInUserUid {
                let newVariable = message.senderId

                if let userpicuid =  newVariable {

                    let ref = FIRDatabase.database().reference().child("users").child(userpicuid)

                    ref.observeSingleEvent(of: .value, with: { (snapshot)
                        in

                        if let dictionary = snapshot.value as? [String: AnyObject]{
                            for post in dictionary {
                                let messages = post.value as! [String: AnyObject]
                                for (id, value) in messages {

                                    let username = messages["username"] as? String
                                    self.userpicuid = userpicuid
                                    self.username = username
                                }}}})}

            }

       performSegue(withIdentifier: "MessageNow", sender: self)

    }

    override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "MessageNow", let chatVc = segue.destination as? SendMessageViewController else {
            return
        }

        print(self.userpicuid)

        chatVc.senderId = self.loggedInUser?.uid
        chatVc.receiverData = self.userpicuid
        chatVc.senderDisplayName = self.userpicuid
        chatVc.username = self.username

    }

However, when I click on the cell, I get the error fatal error: unexpectedly found nil while unwrapping an Optional value So I included some print statements to find out where the nil is. Turns out userpicuid and username is returning nil. I am not sure what I am doing wrong especially because my code is checking the receiverId and the senderId and is one of them is not the logged in user's uid then that uid should be the senderId that segues to the detailed messages.

The error is on the let receiverId = receiverData! line in the detailed messages view controller:

var receiverData: String?

     override func viewDidLoad() {
            super.viewDidLoad()
    let receiverId = receiverData!
            let receiverIdFive = String(receiverId.characters.prefix(5))
            let senderIdFive = String(senderId.characters.prefix(5))
            if (senderIdFive > receiverIdFive)
            {
                self.convoId = senderIdFive + receiverIdFive
            }
            else
            {
                self.convoId = receiverIdFive + senderIdFive
            }
    }

Body:
I found the solution to the question using this:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageTableViewCell

    if message.ReceiverId != self.loggedInUserUid {
        var newVariable = message.ReceiverId

    if let imageName =  newVariable {

        let ref = FIRDatabase.database().reference().child("users").child(imageName)

        ref.observeSingleEvent(of: .value, with: { (snapshot)
            in

            if let dictionary = snapshot.value as? [String: AnyObject]{
                for post in dictionary {
                    let messages = post.value as! [String: AnyObject]
                    for (id, value) in messages {

                        self.username = messages["username"] as? String
                        self.userpicuid = messages["uid"] as? String

            }}}})}}else if message.senderId != self.loggedInUserUid {
        let newVariable = message.senderId

        if let imageName =  newVariable {

            let ref = FIRDatabase.database().reference().child("users").child(imageName)

            ref.observeSingleEvent(of: .value, with: { (snapshot)
                in

                if let dictionary = snapshot.value as? [String: AnyObject]{
                    for post in dictionary {
                        let messages = post.value as! [String: AnyObject]
                        for (id, value) in messages {

                            self.username = messages["username"] as? String
                            self.userpicuid = messages["uid"] as? String

                        }}}})}
    }
    return cell
}

  override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard segue.identifier == "MessageNow", let chatVc = segue.destination as? SendMessageViewController else {
            return
        }

                                chatVc.senderId = self.loggedInUser?.uid
                                chatVc.receiverData = self.userpicuid
                                chatVc.senderDisplayName = self.userpicuid
                                chatVc.username = self.username

    }


问:
Fast linq query with join and count
I have this SQL query witch is running fast if executed from TOAD in Oracle database where Jobs table contains more than 2 million records.

```<code>select * from Technicians  A
left join
  (select TechnicianCode,count(*)JobCount from Jobs
   where TxnCode in ('Jc','Jcd') group by TechnicianCode) B
on B.TechnicianCode =A.TechnicianCode
</code>```

Not able to translate it to linq in efficient way.
Can anybody help with it?

答:
To do the left join, modify @SAJ answer like this:</p>

```<code>var result =  from technician in Technicians
   join txn in txnDetails on technician.TechnicianCode equals
    txn.TechnicianCode
   into j
   from lj in j.DefaultIfEmpty()
 select lj;
</code>```

Title: Fast linq query with join and count

Body:
I have this SQL query witch is running fast if executed from TOAD in Oracle database where Jobs table contains more than 2 million records.

select * from Technicians  A
left join
  (select TechnicianCode,count(*)JobCount from Jobs
   where TxnCode in ('Jc','Jcd') group by TechnicianCode) B
on B.TechnicianCode =A.TechnicianCode

Not able to translate it to linq in efficient way.
Can anybody help with it?

Body:
To do the left join, modify @SAJ answer like this:

var result =  from technician in Technicians
   join txn in txnDetails on technician.TechnicianCode equals
    txn.TechnicianCode
   into j
   from lj in j.DefaultIfEmpty()
 select lj;


问:
Changing the default font family in TinyMCE
I've successfully changed the default font inside the editor using the documentation here but that leaves me with a problem. The original default font no longer works in the font drop down list.

Original default: Verdana

New default: MyCustomFont

When I type into the editor I see my MyCustomFont font by default. If I try to change that to Verdana (original default) nothing happens. I can change it to any font family except Verdana. I noticed also that when I select MyCustomFont in the drop down list the content gets surrounded with a span with inline styles. This does not happen with the original default font (hence why nothing happens).

It seems to me like there's a key piece of documentation missing - how to tell the editor (the font feature in particular) that the font I've defined by default in the css is the default font.

I've Googled quite a bit but had no results. Everybody else seems to be settling for the documentation mentioned above. Am I the only one having this problem? If not, please help! :)

Please note, the answers to this question do not answer my question.

答:
For TinyMCE 4.6.3 this seems to be the way to go:</p>

```<code>tinymce.init({
    setup: function (ed) {
        ed.on('init', function (e) {
            ed.execCommand("fontName", false, "Verdana");
        });
    }
});
</code>```

Body:
For TinyMCE 4.6.3 this seems to be the way to go:

tinymce.init({
    setup: function (ed) {
        ed.on('init', function (e) {
            ed.execCommand("fontName", false, "Verdana");
        });
    }
});


问:
How to convert buttons to a text box and button (Javascript)
I am in the process of learning Javascript and found a guide for a text based game. Currently I have a game that you are supposed to find a cat in a 10x10 area. I use 4 buttons (North, South, East, West) and was wondering if it is possible to convert this into a text-box (user typing in North and they will move up one space north) then click a button to submit the command. I also am not sure how to connect the textbox, button, and Javascript but I tried to do it with what I could find online.

HTML

```<code>   <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Text Based Game </title>

</head>
<body>
<h1>Find The Cat!</h1>
    <p> Can you find the cat somewhere in this 10x10 world?</p>

<p><img id="myImage" onclick="changeImage()" src="http://www.noonco.com/rc/java_art/picture_doorway.jpg" width="200" height="150">
</p>
    <p> You can type in any of these words: <br>
    north, east, south, west, hint, help</p>

    <div id="hint"></div>
    <div id="help"></div>
    <div id='none'></div>

<input id="choice" type="text">
<input id="submit" type="button" onclick="processInput" value="submit command">

<!--  <ul>
<p>
<button onclick="myFunction01()">North</button> <br>
<button onclick="myFunction02()">West</button> <br>
<button onclick="myFunction03()">East</button><br>
<button onclick="myFunction04()">South</button>
    </p>
</ul>-->
<p id="demo"></p>
<script src="TextGame.js"></script>

</body>

</html>
</code>```

JAVASCRIPT

```<code>    var north=0;
var south=0;
var west=0;
var east=0;
var position = "Central Room";
var worldsize=10;

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {

        myFunction01();
    }
    else if (command == "south") {

        myFunction04();
    }
    else if (command == "west") {

        myFunction02();
    }
    else if (command == "east") {

        myFunction03();
    }
    else if (command == "hint"){

        myfunction
    }
}

function myFunction01() {
if (north > worldsize){
return;
}
if (south < 1) {
        north = north + 1;
}else {
        south = south - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction02() {
if (west > worldsize){
return;
}
if (east < 1) {
        west = west + 1;
}else{
        east = east - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction03() {

if (east > worldsize){
return;
}
if (west < 1) {
        east = east + 1;
}else{
        west = west - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction04() {
if (south > worldsize){
return;
}
if (north > 0) {
        north = north - 1;
}else{
south = south + 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myposition() {
var image = document.getElementById('myImage');
if (north == 7 && east == 4){
position = "Cat Freak Out!";
image.src = "https://s-media-cache-ak0.pinimg.com/736x/32/ba/19/32ba192e9eb99068a91fd2e8a1e21189.jpg";
}

else{
position = "lost";
image.src = "http://www.noonco.com/rc/java_art/picture_field.jpg";
}
}
</code>```

答:
You can give an id to the text field, that will uniquely identify it. This way, you can get it's value and then call a function depending on what the input is:

```<code><input type="text" id="direction" />

<!-- The onclick calls the javascript function given to it -->
<button onclick="checkDirection();">Walk</button>
</code>```

The checkDirection()-function should look somewhat like this:

```<code>function checkDirection() {
    // select the input field with the id "direction"
    directionField = document.getElementById("direction");

    // get it's value
    direction = directionField.value;

    // check which value was entered

    // the toLowerCase()-function transforms the string to lower case
    // so that the check isn't case sensitive
    switch (direction.toLowerCase()) {
        case "north":
            /* do something to walk north */
            break;
        case "south":
            /* do something to walk south */
            break;
        case "east":
            /* do something to walk east */
            break;
        case "west":
            /* do something to walk west */
            break;
        default:
            /* get's executed if input doesn't match any of the above */
            alert("Please enter a valid direction");
    }
}
</code>```

Feel free to ask anything.

Body:
I am in the process of learning Javascript and found a guide for a text based game. Currently I have a game that you are supposed to find a cat in a 10x10 area. I use 4 buttons (North, South, East, West) and was wondering if it is possible to convert this into a text-box (user typing in North and they will move up one space north) then click a button to submit the command. I also am not sure how to connect the textbox, button, and Javascript but I tried to do it with what I could find online.

HTML

   <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Text Based Game </title>

Find The Cat!

 Can you find the cat somewhere in this 10x10 world?

 You can type in any of these words:

    north, east, south, west, hint, help

<input id="choice" type="text">
<input id="submit" type="button" onclick="processInput" value="submit command">

JAVASCRIPT

    var north=0;
var south=0;
var west=0;
var east=0;
var position = "Central Room";
var worldsize=10;

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {

        myFunction01();
    }
    else if (command == "south") {

        myFunction04();
    }
    else if (command == "west") {

        myFunction02();
    }
    else if (command == "east") {

        myFunction03();
    }
    else if (command == "hint"){

        myfunction
    }
}

function myFunction01() {
if (north > worldsize){
return;
}
if (south < 1) {
        north = north + 1;
}else {
        south = south - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myFunction02() {
if (west > worldsize){
return;
}
if (east < 1) {
        west = west + 1;
}else{
        east = east - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myFunction03() {

if (east > worldsize){
return;
}
if (west < 1) {
        east = east + 1;
}else{
        west = west - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myFunction04() {
if (south > worldsize){
return;
}
if (north > 0) {
        north = north - 1;
}else{
south = south + 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "
" + "Location: " + position;
}

function myposition() {
var image = document.getElementById('myImage');
if (north == 7 && east == 4){
position = "Cat Freak Out!";
image.src = "https://s-media-cache-ak0.pinimg.com/736x/32/ba/19/32ba192e9eb99068a91fd2e8a1e21189.jpg";
}

else{
position = "lost";
image.src = "http://www.noonco.com/rc/java_art/picture_field.jpg";
}
}

Body:
You can give an id to the text field, that will uniquely identify it. This way, you can get it's value and then call a function depending on what the input is:

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

<!-- The onclick calls the javascript function given to it -->
<button onclick="checkDirection();">Walk</button>

The checkDirection()-function should look somewhat like this:

function checkDirection() {
    // select the input field with the id "direction"
    directionField = document.getElementById("direction");

    // get it's value
    direction = directionField.value;

    // check which value was entered

    // the toLowerCase()-function transforms the string to lower case
    // so that the check isn't case sensitive
    switch (direction.toLowerCase()) {
        case "north":
            /* do something to walk north */
            break;
        case "south":
            /* do something to walk south */
            break;
        case "east":
            /* do something to walk east */
            break;
        case "west":
            /* do something to walk west */
            break;
        default:
            /* get's executed if input doesn't match any of the above */
            alert("Please enter a valid direction");
    }
}

Feel free to ask anything.


问:
Show bootstrap modal on the center of a scrolled down page
I am using ace admin template to develop a website, but I have problem placing bootstrap modal on the center of iframe page when I scrolled it down, like this.

```<code>$('#modalId').modal({
    show:true,
    backdrop:'static'
})
</code>```

how to make the modal pop up on the center of current view?

答:
```<code>var scrollTop = window.gui.getTopWindow(window).scrollY;
if(scrollTop > 200){
    $('#modalId').find('.modal-content').css('top',(scrollTop-50)+'px');
}
$('#modalId').modal({
    show:true,
})
</code>```

Body:
I am using ace admin template to develop a website, but I have problem placing bootstrap modal on the center of iframe page when I scrolled it down, like this.

$('#modalId').modal({
    show:true,
    backdrop:'static'
})

how to make the modal pop up on the center of current view?


问:
Manually encrypt user password in Symfony php
I have a need to manually encrypt the password in the same way Symfony does it.

```<code>$user->setPlainPassword($password);
$userManager->updateUser($user);
</code>```

This is application code that saves the user password. But it is obviously encrypted (not plain as method says).

How can I manually get the same result for given password?

EDIT1:

The problem is that I want to authenticate user manually in users controller code. I have readable username and password that comes as parameters. I want to return 401 if they to not exist in database.

答:
Try this in your controller action:</p>

```<code>$encoder = $this->get('security.encoder_factory')->getEncoder($userClass);
$encodedPassword = $encoder->encodePassword($plainPassword);
</code>```

Body:
I have a need to manually encrypt the password in the same way Symfony does it.

$user->setPlainPassword($password);
$userManager->updateUser($user);

This is application code that saves the user password. But it is obviously encrypted (not plain as method says).

How can I manually get the same result for given password?

EDIT1:

The problem is that I want to authenticate user manually in users controller code. I have readable username and password that comes as parameters. I want to return 401 if they to not exist in database.

Body:
Try this in your controller action:

$encoder = $this->get('security.encoder_factory')->getEncoder($userClass);
$encodedPassword = $encoder->encodePassword($plainPassword);


问:
How to connect to Oracle with Perl using LDAP?
I will be needing to connect to an Oracle server on a system that only supports LDAP for name lookup, rather than TNSNAMES.ora. Is this possible with perl? I am quite sure that I can install the Net::LDAP module and parse the connection information myself, but I was looking for a standard way.</p>

答:
Sounds like you are trying to connect to Oracle Internet Directory (OID) which is an LDAP implementation... not an Oracle database directly.  Correct?

If so, Net::LDAP all the way via Perl...

```<code>my $LSERV  = 'yourldaphost.yourdomain.com';
my $BASE_DN = 'cn=*,dc=*,dc=*';  # these * values must be filled in correctly for your LDAP
my $timeout = 10;                # How long to wait (in secs).
my $success; my $message;
my $ldap = Net::LDAP->new(
     $LSERV,
     timeout => $timeout
) or die "! Unable to connect to OID LDAP.";
</code>```

Body:
Sounds like you are trying to connect to Oracle Internet Directory (OID) which is an LDAP implementation... not an Oracle database directly.  Correct?

If so, Net::LDAP all the way via Perl...

my $LSERV  = 'yourldaphost.yourdomain.com';
my $BASE_DN = 'cn=*,dc=*,dc=*';  # these * values must be filled in correctly for your LDAP
my $timeout = 10;                # How long to wait (in secs).
my $success; my $message;
my $ldap = Net::LDAP->new(
     $LSERV,
     timeout => $timeout
) or die "! Unable to connect to OID LDAP.";


问:
Migrate repos between instances of Gitlab
Due to my old installation of Gitlab being too difficult to upgrade (Thread on TKL support forums: http://www.turnkeylinux.org/forum/support/20120913/upgrading-gitlab ), I have downloaded the current TKL Gitlab distro, and followed Gitlabs standard upgrade path so that I now have a fully upgraded Gitlab 6.1 installation running with TKLBAM and all that good stuff. So far so good.

But, it turns out that our old version of gitlab does not give HTTP urls to repos, so that means that I can't use the "Import existing repository" function in Gitlab 6.1

I know that i can simply copy the old Git repositories from the old VM to the new one, but how can I make these repositories visible in Gitlab on the new VM?

答: If your Gitlab is >= 8.9, then you can use export/import to migrate repos.</p>