2015年8月10日 星期一
2015年8月2日 星期日
2015年7月26日 星期日
ember filterExample
**html** <div class="col-sm-12">
{{input type="text" value=search placeholder="filter 'phone' field...."}}
</div> <ul class="list-group">
{{#each filterResult as |phone| }} {{#link-to 'phones.viewPhone' phone.objectId}}
<li {{ bindAttr class=":list-group-item" }}>
{{phone.phone}}
</li>
{{/link-to}} {{/each}}
<br>
</ul> **html**App.PhonesController = Ember.Controller.extend({
search: '',
filterResult: function() {
var model = this.get('model');
var search = this.get('search');
if (Ember.isEmpty(search)) {
return model;
}
Ember.Logger.log('PhonesController filterResult search:' + this.get('search'));
var result = model.filter(function(item, index, self) {
//Ember.Logger.log('PhonesController model.filter item:'+JSON.stringify(item));
//item:{"first":"544","last":"121","phone":"0938","objectId":"D61qwtLr6g","createdAt":"2015-07-25T13:18:33.600Z","updatedAt":"2015-07-25T13:18:33.600Z"}"
if (item['phone'].indexOf(search) >= 0) {
return true;
}
});
return result;//model is route's model not local var!!//if not in property then model change ,the filterResult can't trigger!!!
}.property('search','model'),
init: function() {
this._super();
Ember.Logger.log('PhonesController now init...');
},
actions: {
parseList: function() {
console.log("PhonesController send('parseListAction')");
return this.send('parseListAction');
},
filterResult: function() {
return this.filterResult();
},
addClick: function() {
this.transitionToRoute('phones.add');
}
}
});
emberjs object 繼承
http://xbingoz.com/emberguides/7.php#top App.ParseTool = Ember.Object.extend({
init:function () {
Parse.initialize("57ky0yYlGjtL93qWuMG2rYNt1HMBlO0CLLIhKmgb", "ISFeeGTcJ8fsvTX9NOrxRkj6MhnzPkNWOgqnLUsK");
},getQueryOfPhone:function () {
var Phone = Parse.Object.extend("Phone");
var query = new Parse.Query(Phone);
return query;
},log:function (str) {
Ember.Logger.log('ParseToolLogger:'+str);
}
});
App.PhonesHttp = App.ParseTool.extend({
logme:function (str) {
this.log(str);
}
});
DI in emberjs
if you are using cli you must use "ember generate 'service' and 'initializer' "
service as a object
http://emberjs.com/api/classes/Ember.Application.html#method_inject
service as a object
initializer:import Phonehttp from '../services/phone-http';
export default {
name: 'application',
initialize: function initialize( container, application ) {
application.register( 'phone-http:services', Phonehttp, { singleton: true } );
application.inject( 'route:index', 'Phonehttp', 'phone-http:services' );
}
};service: import Ember from 'ember';
export default Ember.Service.extend({
log(){
console.log('by Service log');
}
});route/index import Ember from 'ember';
export default Ember.Route.extend({
beforeModel:function () {
this.Phonehttp.log();
this.transitionTo('posts');
}
});
http://emberjs.com/api/classes/Ember.Application.html#method_inject
https://github.com/kelonye/ember-user/blob/master/lib/index.jshttp://balinterdi.com/2014/05/01/dependency-injection-in-ember-dot-js.htmlhttp://wrktg.com/articles/understanding-application-register-and-inject-methods/ http://guides.emberjs.com/v1.13.0/understanding-ember/dependency-injection-and-service-lookup/ex://register
container.register('alertTool:object', App.AlertTool, {
singleton: true
});
container.register('phonesHttp:object', App.PhonesHttp, {
singleton: true
});
container.register('controller:phones', App.PhonesController, {
singleton: true
});
//PhonesController
application.inject('route:phones', 'PhonesController', 'controller:phones');
//alertTool
application.inject('route:phones', 'AlertTool', 'alertTool:object');
application.inject('controller:phones.viewPhone', 'AlertTool', 'alertTool:object');
//phonesHttp
application.inject('route:phones', 'PhonesHttp', 'phonesHttp:object');
application.inject('controller:phones.viewPhone', 'PhonesHttp', 'phonesHttp:object');
} njections can be made onto all of Ember's major framework classes including components, controllers, routes, and the router.
App = Ember.Application.create();
App.Router.map(function() {
this.resource('about');
this.resource('calc');
this.resource('todo');
this.route('phones', function() {
this.route('viewPhone', {
path: "/viewPhone/:pathid"
});
});
});
Ember.Application.initializer({//must has name field 'name'
name:'init',
initialize: function(container, application) {
container.register('tool:object', App.Tool, { singleton: true });
application.inject('route:phones', 'Tool', 'tool:object');
}
});
App.Tool = Ember.Object.extend({
showAlertDivId:'',
fail: "<div class='alert alert-danger'> fail </div>",
sus: "<div class='alert alert-success'> sus </div>",
removeAlert: function() {
var id=this.get('showAlertDivId');
setTimeout(function () {
$('#'+id).empty();
}, 2000);
},
susAlert: function() {
$('#'+this.showAlertDivId).append(this.sus);
this.removeAlert();
},failAlert:function(){
$('#'+this.showAlertDivId).append(this.fail);
this.removeAlert();
},setShowAlertDivId:function (name) {
return this.set('showAlertDivId',name);
},getQueryOfPhone:function () {
var Phone = Parse.Object.extend("Phone");
var query = new Parse.Query(Phone);
return query;
}
});
App.PhonesRoute = Ember.Route.extend({
init: function() {
this._super();
Ember.Logger.log('PhonesRoute now init...');
},
model: function() {
//this.Logger.log('example');
return this.parseList();
},
parseList: function() {
var tool=this.Tool;
Ember.Logger.log('PhonesRoute parseList Ember.RSVP.Promise');
return new Ember.RSVP.Promise(function(resolve, reject) {
var resolve1 = resolve;
var reject2 = reject;
//var Phone = Parse.Object.extend("Phone");
//var query = new Parse.Query(Phone);
tool.setShowAlertDivId('status');
var query=tool.getQueryOfPhone();
query.find({
success: function(results) {
tool.susAlert();
//con.transitionTo('phones', results);
var strjson = JSON.stringify(results); //array to string
//Ember.Logger.log('parseList strjson:' + JSON.stringify(strjson));
var jsonobj = JSON.parse(strjson); //string to object
//Ember.Logger.log('PhonesRoute parseList jsonobj:' + JSON.stringify(jsonobj));
resolve1(jsonobj);
},
error: function(model, error) {
Ember.Logger.log('PhonesRoute parseList error:' + JSON.stringify(error));
tool.failAlert();
this.nowList = error;
reject2(error);
}
});
});
},
actions: {
loading: function(transition, originRoute) {
console.log("PhonesRoute loading");
},
parseListAction: function() {
console.log("PhonesRoute this.parseList()");
return this.parseList();
},invalidateModel: function() { Ember.Logger.log('PhonesRoute is now refreshing...'); this.refresh(); }
}
});
2015年7月25日 星期六
javascript JSON.parse
parse.com 傳回的array陣列
{"results":[{"avatar":"中文名稱","createdAt":"2015-07-22T12:58:04.722Z","first":"中文名稱","last":"中文名稱","name":"中文名稱","objectId":"Xu3nMRCjO0","phone":"1212","updatedAt":"2015-07-22T12:58:04.722Z"},{"avatar":"12","createdAt":"2015-07-25T04:23:37.618Z","first":"1231","last":"51","name":"12","objectId":"FjtkSEIM93","phone":"963","updatedAt":"2015-07-25T04:23:49.516Z"}]}
要轉為物件才可以給ember使用
var strjson = JSON.stringify (results);//array to string
Ember.Logger.log('parseList strjson:'+JSON.stringify(strjson));
var jsonobj = JSON.parse(strjson);//string to object
Ember.Logger.log('parseList res:'+JSON.stringify(jsonobj));
{"results":[{"avatar":"中文名稱","createdAt":"2015-07-22T12:58:04.722Z","first":"中文名稱","last":"中文名稱","name":"中文名稱","objectId":"Xu3nMRCjO0","phone":"1212","updatedAt":"2015-07-22T12:58:04.722Z"},{"avatar":"12","createdAt":"2015-07-25T04:23:37.618Z","first":"1231","last":"51","name":"12","objectId":"FjtkSEIM93","phone":"963","updatedAt":"2015-07-25T04:23:49.516Z"}]}
要轉為物件才可以給ember使用
var strjson = JSON.stringify (results);//array to string
Ember.Logger.log('parseList strjson:'+JSON.stringify(strjson));
var jsonobj = JSON.parse(strjson);//string to object
Ember.Logger.log('parseList res:'+JSON.stringify(jsonobj));
transitionToRoute the same route problem
http://stackoverflow.com/questions/18624601/correct-way-to-transitiontoroute/18642910
A route with a dynamic segment will only have its model hook called when it is entered via the URL. If the route is entered through a transition (e.g. when using the link-to Handlebars helper), then a model context is already provided and the hook is not executed. Routes without dynamic segments will always execute the model hook.
sol:
http://guides.emberjs.com/v1.10.0/routing/specifying-a-routes-model/
App = Ember.Application.create();
App.Router.map(function() {
this.resource('about');
this.resource('calc');
this.resource('todo');
this.resource('phones', function() {
this.route('viewPhone', {
path: "/viewPhone/:userid"
});
});
});
var varphones = [{
objectId: 0,
first: 'Ryan',
last: 'Florence',
avatar: 'https://si0.twimg.com/profile_images/3123276865/5c069e64eb7f8e971d36a4540ed7cab2.jpeg',
phone: '0938535359'
}, {
objectId: 1,
first: 'Tom',
last: 'Dale',
avatar: 'https://si0.twimg.com/profile_images/1317834118/avatar.png',
phone: '0938535349'
}, {
objectId: 2,
first: 'Yehuda',
last: 'Katz',
avatar: 'https://si0.twimg.com/profile_images/3250074047/46d910af94e25187832cb4a3bc84b2b5.jpeg',
phone: '0938535459'
}];
App.PhonesRoute = Ember.Route.extend({
model: function() {
return varphones;
},
actions: {
invalidateModel: function() {
Ember.Logger.log('Route is now refreshing...');
this.refresh();
}
}
});
App.PhonesViewPhoneRoute = Ember.Route.extend({
model: function(params) {
console.log(params);
return varphones[params.objectId];
}
});
App.PhonesController = Ember.Controller.extend({
name: '',
phone: '',
search: '',
init: function() {
this._super();
Parse.initialize("57ky0yYlGjtL93qWuMG2rYNt1HMBlO0CLLIhKmgb", "ISFeeGTcJ8fsvTX9NOrxRkj6MhnzPkNWOgqnLUsK");
var tool = Object.create(Tool);
tool.showAlertDivId = 'status';
},
actions: {
parseSave: function() {
if (this.phone.length <= 0) {
tool.failAlert();
return;
}
if (this.name.length <= 0) {
tool.failAlert();
return;
}
var Phone = Parse.Object.extend("Phone");
var phone = new Phone();
phone.set('name', this.get('name'));
phone.set('phone', this.get('phone'));
phone.set('first', this.get('name'));
phone.set('last', this.get('name'));
phone.set('avatar', this.get('name'));
phone.save(null, {
success: function(object) {
tool.susAlert();
},
error: function(model, error) {
tool.failAlert();
}
});
},
parseList: function() {
var tool = Object.create(Tool);
tool.showAlertDivId = 'status';
var Phone = Parse.Object.extend("Phone");
var query = new Parse.Query(Phone);
var con=this;
query.find({
success: function(results) {
varphones=results;
console.log("varphones:"+JSON.stringify(varphones));
tool.susAlert();
Ember.Logger.log('Controller requesting route to refresh...');
con.send('invalidateModel');//"Controller requesting route to refresh..."
},
error: function(model, error) {
tool.failAlert();
this.nowList = error;
}
}).then(function () {
});
}
}
});
Learning Ember
https://www.emberscreencasts.com/posts?free=true
http://www.smashingmagazine.com/2013/11/an-in-depth-introduction-to-ember-js/
http://www.smashingmagazine.com/2013/11/an-in-depth-introduction-to-ember-js/
2015年7月18日 星期六
difference fo '.resoure' and '.route' in route
import Ember from 'ember';
var Router = Ember.Router.extend({
});
Router.map(function() {
this.resource('posts', function() {
this.route('new');
this.route('edit');
this.route('post',{'path':'/:postId'});
});
});
export default Router;
ember will read template from
posts/newif you use resource will read template from new
rested and dynamic route example
http://guides.emberjs.com/v1.10.0/routing/defining-your-routes/
import Ember from 'ember';
var Router = Ember.Router.extend({
});
Router.map(function() {
this.resource('posts', function() {
this.resource('new');
this.resource('post',{'path':'/:postId'});
});
});
export default Router;
ember route index trap
if you use index
\templates\posts\index
there will only load index
but is you set to
\templates\posts
you can use
\templates\posts\new
\templates\posts\other
\templates\posts\index
there will only load index
but is you set to
\templates\posts
you can use
\templates\posts\new
\templates\posts\other
ui-icon addon
https://www.npmjs.com/package/ui-icon
http://daneden.github.io/animate.css
ember install ui-icon
bower install --save fontawesome
bower install --save
https://github.com/daneden/animate.css.githttp://daneden.github.io/animate.css
\components\list-button.jsimport Ember from 'ember';
//fa-pencil
export default Ember.Component.extend({
righttext: 'comright',
faIconName:'pencil',
actions: {
comfaCLick: function() {
console.log('comfaCLick');
},
select: function(post) {
this.sendAction('selectitem',post);//send to parent's controller
}
}
}); \templates\components\list-button.hbs<ul class="list-group posts">
{{#each listdata key="@index" as |post|}}
<li class="clearfix list-group-item" {{action 'select' post}} >
<div class="itemleft col-xs-7">
<span> {{post.title}}</span>
</div>
<div class="itemright col-xs-3">
<span {{action 'comfaCLick' post}}></span>
{{ui-icon icon= faIconName }}
</div>
</li>
{{/each}}
</ul>.
2015年7月12日 星期日
list-group-items 疊再一起
http://stackoverflow.com/questions/24285260/bootstrap-css-height-of-list-group-item
Since you are using Bootstrap you could add the
Since you are using Bootstrap you could add the
class="clearfix" to HTML for the list-group-items
2015年7月2日 星期四
print a list and bindclass
http://jsbin.com/aconeh/3/edit?html,js,output
http://ember101.com/videos/003-displaying-a-list-of-data
App = Ember.Application.create();
App.Router.map(function() {
this.resource('about');
this.resource('calc');
this.resource('todo');
this.resource('phones');
});
var users = [
{
id: 1,
first: 'Ryan',
last: 'Florence',
avatar: 'https://si0.twimg.com/profile_images/3123276865/5c069e64eb7f8e971d36a4540ed7cab2.jpeg'
,phone:'0938535359'
},
{
id: 2,
first: 'Tom',
last: 'Dale',
avatar: 'https://si0.twimg.com/profile_images/1317834118/avatar.png'
,phone:'0938535349'
},
{
id: 3,
first: 'Yehuda',
last: 'Katz',
avatar: 'https://si0.twimg.com/profile_images/3250074047/46d910af94e25187832cb4a3bc84b2b5.jpeg'
,phone:'0938535459'
}
];
App.PhonesRoute = Ember.Route.extend({
//modelis a reserved word can't write to smodel or xname or yname..etc
model: function() {
console.log(users);
return users;
}
});
App.PhonesController = Ember.Controller.extend({
search: '',
actions: {
query: function function_name() {
var str = this.get('search');
console.log(str);
}
}
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ember Starter Kit</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/ember.min.js"></script>
<script src="js/libs/ember-template-compiler.js"></script>
<script src="js/libs/ember.prod.js"></script>
<script src="js/libs/handlebars-v3.0.3.js"></script>
<script src="js/libs/bootstrap.min.js"></script>
<script type="text/javascript" src="ember-data.min.js"></script>
<script type="text/javascript" src="state.js"></script>
<script type="text/javascript" src="state_manager.js"></script>
<script src="js/app.js"></script>
<!-- to activate the test runner, add the "?test" query string parameter -->
<script src="tests/runner.js"></script>
<script type="text/x-handlebars" data-template-name="phones">
{{input type="text"value=search placeholder="text to query..." action="query"}}
<br>
<ul class="list-group">
<li class="list-group-item">1</li>
{{#each phone in model}}
//sould be ":list-group-item" not "list-group-item"
<li {{ bindAttr class=":list-group-item" }} >
{{phone.first}} , {{phone.last}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars">
<div id='top'>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">I am keith</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#/about">about</a></li>
<li><a href="#/calc">calc</a></li>
<li><a href="#/todo">todo</a></li>
<li><a href="#/phones">phones</a></li>
</ul>
</div>
</div>
</nav>
</div>
<div id='contents'>
{{outlet}}
</div>
<div id='footer'>
Copyright © 2015 LFO keith. All rights reserved
</div>
</script>
<script type="text/x-handlebars" data-template-name="about">
<div class="jumbotron">
<div class="container">
<h1>My ember website!</h1>
<p>This my pratices</p>
</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="calc">
this is calc
</script>
<script type="text/x-handlebars" data-template-name="todo">
this is todo
</script>
</body>
</html>
http://ember101.com/videos/003-displaying-a-list-of-data
App = Ember.Application.create();
App.Router.map(function() {
this.resource('about');
this.resource('calc');
this.resource('todo');
this.resource('phones');
});
var users = [
{
id: 1,
first: 'Ryan',
last: 'Florence',
avatar: 'https://si0.twimg.com/profile_images/3123276865/5c069e64eb7f8e971d36a4540ed7cab2.jpeg'
,phone:'0938535359'
},
{
id: 2,
first: 'Tom',
last: 'Dale',
avatar: 'https://si0.twimg.com/profile_images/1317834118/avatar.png'
,phone:'0938535349'
},
{
id: 3,
first: 'Yehuda',
last: 'Katz',
avatar: 'https://si0.twimg.com/profile_images/3250074047/46d910af94e25187832cb4a3bc84b2b5.jpeg'
,phone:'0938535459'
}
];
App.PhonesRoute = Ember.Route.extend({
//modelis a reserved word can't write to smodel or xname or yname..etc
model: function() {
console.log(users);
return users;
}
});
App.PhonesController = Ember.Controller.extend({
search: '',
actions: {
query: function function_name() {
var str = this.get('search');
console.log(str);
}
}
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ember Starter Kit</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="js/libs/jquery-1.10.2.js"></script>
<script src="js/libs/ember.min.js"></script>
<script src="js/libs/ember-template-compiler.js"></script>
<script src="js/libs/ember.prod.js"></script>
<script src="js/libs/handlebars-v3.0.3.js"></script>
<script src="js/libs/bootstrap.min.js"></script>
<script type="text/javascript" src="ember-data.min.js"></script>
<script type="text/javascript" src="state.js"></script>
<script type="text/javascript" src="state_manager.js"></script>
<script src="js/app.js"></script>
<!-- to activate the test runner, add the "?test" query string parameter -->
<script src="tests/runner.js"></script>
<script type="text/x-handlebars" data-template-name="phones">
{{input type="text"value=search placeholder="text to query..." action="query"}}
<br>
<ul class="list-group">
<li class="list-group-item">1</li>
{{#each phone in model}}
//sould be ":list-group-item" not "list-group-item"
<li {{ bindAttr class=":list-group-item" }} >
{{phone.first}} , {{phone.last}}
</li>
{{/each}}
</ul>
</script>
<script type="text/x-handlebars">
<div id='top'>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">I am keith</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#/about">about</a></li>
<li><a href="#/calc">calc</a></li>
<li><a href="#/todo">todo</a></li>
<li><a href="#/phones">phones</a></li>
</ul>
</div>
</div>
</nav>
</div>
<div id='contents'>
{{outlet}}
</div>
<div id='footer'>
Copyright © 2015 LFO keith. All rights reserved
</div>
</script>
<script type="text/x-handlebars" data-template-name="about">
<div class="jumbotron">
<div class="container">
<h1>My ember website!</h1>
<p>This my pratices</p>
</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="calc">
this is calc
</script>
<script type="text/x-handlebars" data-template-name="todo">
this is todo
</script>
</body>
</html>
2015年7月1日 星期三
angular js muti modules
var alert=angular.module('alert',['ui.bootstrap']).controller('AlertDemoCtrl', function ($scope) {
$scope.alerts = [
{ type: 'danger', msg: 'Oh snap! Change a few things up and try submitting again.' },
{ type: 'success', msg: 'Well done! You successfully read this important alert message.' }
];
$scope.addAlert = function() {
$scope.alerts.push({msg: 'Another alert!'});
};
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
});
//just add in your main app called phonecatApp
var phonecatApp = angular.module('phonecatApp', ['alert']);
phonecatApp.controller('PhoneListCtrl', function ($scope) {
$scope.phones = [
{'name': 'Nexus S',
'snippet': 'Fast just got faster with Nexus S.'},
{'name': 'Motorola XOOM™ with Wi-Fi',
'snippet': 'The Next, Next Generation tablet.'},
{'name': 'MOTOROLA XOOM™',
'snippet': 'The Next, Next Generation tablet.'}
];
});
2015年6月30日 星期二
bootstrap
Bootstrap可视化布局
http://www.bootcss.com/p/layoutit/bootstrap 中文
http://www.bootcss.com/
w3schools.
http://www.w3schools.com/bootstrap/bootstrap_images.asp
bootstrap 中文可以查
http://www.runoob.com/bootstrap/bootstrap-list-group.html
2015年6月16日 星期二
ember
Ember Components
omic.sfacg.com/HTML/MSDHL/jsbeautifier
http://jsbeautifier.org/
ember101
http://ember101.com/videos/006-adding-objects-to-a-list/
2015年6月15日 星期一
backbone require example AMD
https://packagecontrol.io/packages/AutoCompleteJS
http://backbonejs.org/#examples-todos
https://onedrive.live.com
http://www.ruanyifeng.com/blog/2012/11/require_js.html
'js/utils/utils.js'
define(function() {
var add = function(x, y) {
return x + y;
};
var sub = function(x, y) {
return x - y;
};
return {
add: add,
sub: sub
};
});
app.js
define([
'jquery',
'underscore',
'backbone',
'js/utils/utils.js'
], function($, _, Backbone,Utils) {
var num=Utils.add(1,2);
console.log("num:"+num);
var initializefun = function() {
console.log("initializefun");
}
var Human = Backbone.Model.extend({
defaults: {
humanname: '',
age: 0
},
initialize: function() {
this.on("change:humanname", function(model) {
console.log("change->humanname");
});
}
});
var hum = new Human();
hum.set({
humanname: "name"
});
var name = hum.get("humanname");
console.log(name);
hum.set({
humanname: "name2"
});
var Myview = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var template = _.template($("#search_template").html(), {});
this.$el.html(template);
},
events: {
"click input[type=button]": "dosearch"
},
dosearch: function(event) {
alert("Search for " + $("#search_input").val());
}
});
var sview = new Myview({
el: $("#search_container")
});
//write this that main.js can use initializefun() in require([
//return {
// initializefun: initializefun
//};
});
//$(function() {
//});
if you want muti method
http://www.ruanyifeng.com/blog/2012/10/javascript_module.html
http://backbonejs.org/#examples-todos
https://onedrive.live.com
http://www.ruanyifeng.com/blog/2012/11/require_js.html
'js/utils/utils.js'
define(function() {
var add = function(x, y) {
return x + y;
};
var sub = function(x, y) {
return x - y;
};
return {
add: add,
sub: sub
};
});
app.js
define([
'jquery',
'underscore',
'backbone',
'js/utils/utils.js'
], function($, _, Backbone,Utils) {
var num=Utils.add(1,2);
console.log("num:"+num);
var initializefun = function() {
console.log("initializefun");
}
var Human = Backbone.Model.extend({
defaults: {
humanname: '',
age: 0
},
initialize: function() {
this.on("change:humanname", function(model) {
console.log("change->humanname");
});
}
});
var hum = new Human();
hum.set({
humanname: "name"
});
var name = hum.get("humanname");
console.log(name);
hum.set({
humanname: "name2"
});
var Myview = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
var template = _.template($("#search_template").html(), {});
this.$el.html(template);
},
events: {
"click input[type=button]": "dosearch"
},
dosearch: function(event) {
alert("Search for " + $("#search_input").val());
}
});
var sview = new Myview({
el: $("#search_container")
});
//write this that main.js can use initializefun() in require([
//return {
// initializefun: initializefun
//};
});
//$(function() {
//});
if you want muti method
http://www.ruanyifeng.com/blog/2012/10/javascript_module.html
2015年5月20日 星期三
running second layout pass
W/View﹕ requestLayout() improperly called by android.widget.TextView{52fa954c V.ED.... ......ID 240,0-378,100 #7f100083 app:id/name} during layout: running second layout pass
// isfirst=false;//everytime you must findViewById otherwise you will get error: // requestLayout() improperly called by android.widget.TextView{52e78b8c V.ED.... ......ID 240,0-516,100 #7f100083 app:id/name} during layout: running second layout pass
2015年5月5日 星期二
robolectric
https://github.com/robolectric/deckard-gradle/blob/master/build.gradle
http://robolectric.org/getting-started/
http://robolectric.org/getting-started/
2015年5月2日 星期六
自訂 Annotation 型態 限制
http://openhome.cc/Gossip/Java/CustomizeAnnotation.html
在定義標註時,可使用
例如想將
在定義標註時,可使用
java.lang.annotation.Target限定標註使用位置,限定時可指定java.lang.annotation.ElementType的列舉值:package java.lang.annotation;
public enum ElementType {
TYPE, // 用於類別、介面、列舉等
FIELD, // 用於資料成員
METHOD, // 用於方法
PARAMETER, // 用於方法上的參數
CONSTRUCTOR, // 用於建構式
LOCAL_VARIABLE, // 用於區域變數
ANNOTATION_TYPE, // 用於標註型態
PACKAGE, // 適用套件
TYPE_PARAMETER, // 用於泛型宣告,JDK8新增
TYPE_USE // 用於各種型態,JDK8新增
}@Test8限定只能用於方法:package cc.openhome;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target({ElementType.METHOD})
public @interface Test8 {}
StockWheelAdapter extends AbstractWheelTextAdapter
package suntone.lfo.com.suntonehelper.adapter; import android.content.Context; import com.lfo.suntone.db.Stock;import com.lfo.suntone.db.Stocktype; import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.List; import kankan.wheel.widget.WheelView;import kankan.wheel.widget.adapters.AbstractWheelTextAdapter;import suntone.lfo.com.suntonehelper.tool.Utils;import suntone.lfo.com.suntonehelper.tool.WarehouseTool; /** * Created by user on 2015/4/27. */public class StockWheelAdapter extends AbstractWheelTextAdapter { private List<Stock> list; private List<Stock> originList; private List<Stock> filtlist; private Context context; private WheelView thiswheelView; protected StockWheelAdapter(Context context) { super(context); } public StockWheelAdapter(Context context, List list,WheelView thiswheelView) { super(context); this.context = context; this.list=new ArrayList(); originList=new ArrayList<>(); filtlist=new ArrayList<>(); this.list = list; this.thiswheelView=thiswheelView; this.originList.addAll(list); thiswheelView.setVisibleItems(list.size()); } public Boolean isListNullOrEmpty(){ if(this.list==null){ return true; } if(this.list.isEmpty()){ return true; } return false; } public Stock getSelected(WheelView v) { if(list.isEmpty()){ Utils.instance.logClaz(this,"getSelected() list.isEmpty"); return null; } if(list.size()==v.getCurrentItem()){ Utils.instance.logClaz(this,"getSelected() v.getCurrentItem():"+v.getCurrentItem()+",list.size():"+list.size()); return null; } return list.get(v.getCurrentItem()); } public int getSelectedId(WheelView v) { return list.get(v.getCurrentItem()).getId(); } @Override protected CharSequence getItemText(int index) { Stock stock = list.get(index); if (stock == null) { return ""; } Stocktype stocktype = WarehouseTool.instance.getStocktype(context, stock); if (stocktype == null) { return ""; } return stocktype.getName(); } public void clearAndFilterBystocktype(String methodname, int id) { this.list.clear(); this.list.addAll(originList); filterBystocktype(methodname, id); } public void filterBystocktype(String methodname, int id) { this. filtlist.clear(); List stocktypelist = WarehouseTool.instance.getListInStorage(context, Stocktype.class); // ArrayList flist=new ArrayList(this.list); Iterator< Stock> iter = this.list.iterator(); while (iter.hasNext()) { Stock t=iter.next(); int filterid = -1; Stocktype stocktypeOfStock = WarehouseTool.instance.getStocktypeInList(context, t, stocktypelist); if (stocktypeOfStock == null) { continue; } //example: filterid= stocktype.getCategoryId(); try { filterid = (int) Stocktype.class.getDeclaredMethod(methodname).invoke(stocktypeOfStock); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (filterid == id) { filtlist.add(t); } } changeList(filtlist); } public void filter(String methodname, int id) { this. filtlist.clear(); Iterator< Stock> iter = this.list.iterator(); while (iter.hasNext()) { Stock t=iter.next(); int inlistid = -1; try { inlistid = (int) Stock.class.getDeclaredMethod(methodname).invoke(t); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } if (inlistid == id) { filtlist.add(t); } } changeList(filtlist); } public void clearAndFilterOriginList(String methodname, int id) { this.list.clear(); this.list.addAll(originList); this.notifyDataChangedEvent(); filtlist.clear(); filter(methodname, id); } public void changeList(List list) { this.list.clear(); this.list.addAll(list); thiswheelView.invalidateWheel(true);//把CACHE清除 以免殘留 thiswheelView.setVisibleItems(list.size()); this.notifyDataChangedEvent(); } @Override public int getItemsCount() { if (list == null) { return 0; } return list.size(); } }
2015年5月1日 星期五
json 多形 抽象類別Polymorphic Deserialization
package com.lfo.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.lfo.suntone.db.CanGetName;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
@JsonSubTypes({
@Type(value = CommercialOutput.class, name = "CommercialOutput"),
@Type(value = ConsumptionOfRawMaterials.class, name = "ConsumptionOfRawMaterials") ,
@Type(value = ConsumptionOfWrapper.class, name = "ConsumptionOfWrapper") ,
@Type(value = SellingOut.class, name = "SellingOut")
})
public abstract class ManageItemOperationText implements CanGetName {
/*
產出商品commercial output
消耗原料consumption of raw materials
包裝消耗consumption of wrapper
賣出產品 selling-out
*/
//private int id=0;
//private String name="";
public String commercialOutput=" 產出商品";
public String consumptionOfRawMaterials="消耗原料";
public String consumptionOfWrapper="包裝消耗";
public String sellingOut="賣出產品";
/*
public Integer getId() {
return id;
}
public String getName() {
return name;
}
*/
}
package com.lfo.vo;
public class CommercialOutput extends ManageItemOperationText {
private int id=0;
private String name=super.commercialOutput;//"產出商品";
@Override
public String getName() {
return this.name;
}
@Override
public Integer getId() {
return this.id;
}
}
http://wiki.fasterxml.com/JacksonPolymorphicDeserialization
http://codelife.me/blog/2012/11/03/jackson-polymorphic-deserialization/
https://nickebbitt.wordpress.com/2014/01/31/handling-polymorphic-types-using-jackson-framework-for-json/
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.lfo.suntone.db.CanGetName;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
@JsonSubTypes({
@Type(value = CommercialOutput.class, name = "CommercialOutput"),
@Type(value = ConsumptionOfRawMaterials.class, name = "ConsumptionOfRawMaterials") ,
@Type(value = ConsumptionOfWrapper.class, name = "ConsumptionOfWrapper") ,
@Type(value = SellingOut.class, name = "SellingOut")
})
public abstract class ManageItemOperationText implements CanGetName {
/*
產出商品commercial output
消耗原料consumption of raw materials
包裝消耗consumption of wrapper
賣出產品 selling-out
*/
//private int id=0;
//private String name="";
public String commercialOutput=" 產出商品";
public String consumptionOfRawMaterials="消耗原料";
public String consumptionOfWrapper="包裝消耗";
public String sellingOut="賣出產品";
/*
public Integer getId() {
return id;
}
public String getName() {
return name;
}
*/
}
package com.lfo.vo;
public class CommercialOutput extends ManageItemOperationText {
private int id=0;
private String name=super.commercialOutput;//"產出商品";
@Override
public String getName() {
return this.name;
}
@Override
public Integer getId() {
return this.id;
}
}
http://wiki.fasterxml.com/JacksonPolymorphicDeserialization
http://codelife.me/blog/2012/11/03/jackson-polymorphic-deserialization/
https://nickebbitt.wordpress.com/2014/01/31/handling-polymorphic-types-using-jackson-framework-for-json/
2015年4月26日 星期日
String之HibernateTemplate经典查询
http://zhaoshijie.iteye.com/blog/836757
一、find(String queryString);
示例:this.getHibernateTemplate().find("from bean.User");
返回所有User对象
二、find(String queryString , Object value);
示例:this.getHibernateTemplate().find("from bean.User u where u.name=?", "test");
或模糊查询:this.getHibernateTemplate().find("from bean.User u where u.name like ?", "%test%");
返回name属性值为test的对象(模糊查询,返回name属性值包含test的对象)
三、find(String queryString, Object[] values);
示例:String hql= "from bean.User u where u.name=? and u.password=?"
this.getHibernateTemplate().find(hql, new String[]{"test", "123"});
返回用户名为test并且密码为123的所有User对象
---------------------------------
四、findByExample(Object exampleEntity)
示例:
User u=new User();
u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)
u.setName("bb");
list=this.getHibernateTemplate().findByExample(u,start,max);
返回:用户名为bb密码为123的对象
五、findByExample(Object exampleEntity, int firstResult, int maxResults)
示例:
User u=new User();
u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)
u.setName("bb");
list=this.getHibernateTemplate().findByExample(u,start,max);
返回:满足用户名为bb密码为123,自start起共max个User对象。(对象从0开始计数)
---------------------------------------------------
六、findByNamedParam(String queryString , String paramName , Object value)
使用以下语句查询:
String queryString = "select count(*) from bean.User u where u.name=:myName";
String paramName= "myName";
String value= "xiyue";
this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);
System.out.println(list.get(0));
返回name为xiyue的User对象的条数
七、findByNamedParam(String queryString , String[] paramName , Object[] value)
示例:
String queryString = "select count(*) from bean.User u where u.name=:myName and u.password=:myPassword";
String[] paramName= new String[]{"myName", "myPassword"};
String[] value= new String[]{"xiyue", "123"};
this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);
返回用户名为xiyue密码为123的User对象
八、findByNamedQuery(String queryName)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryAllUser"><!--此查询被调用的名字-->
<!--[CDATA[
from bean.User
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
this.getHibernateTemplate().findByNamedQuery("queryAllUser");
九、findByNamedQuery(String queryName, Object value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByName"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name = ?
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
this.getHibernateTemplate().findByNamedQuery("queryByName", "test");
十、findByNamedQuery(String queryName, Object[] value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByNameAndPassword"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =? and u.password =?
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
String[] values= new String[]{"test", "123"};
this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , values);
十一、findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByName"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =:myName
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
this.getHibernateTemplate().findByNamedQuery("queryByName" , "myName", "test");
十二、findByNamedQueryAndNamedParam(String queryName, String[] paramName, Object[] value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByNameAndPassword"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =:myName and u.password=:myPassword
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
String[] names= new String[]{"myName", "myPassword"};
String[] values= new String[]{"test", "123"};
this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , names, values);
十三、findByValueBean(String queryString , Object value);
示例:
1、定义一个ValueBean,属性名必须和HSQL语句中的:后面的变量名同名,此处必须至少有两个属性,分别为myName和
myPassword,使用setter方法设置属性值后
ValueBean valueBean= new ValueBean();
valueBean.setMyName("test");
valueBean.setMyPasswrod("123");
2、
String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";
this.getHibernateTemplate().findByValueBean(queryString , valueBean);
十四、findByNamedQueryAndValueBean(String queryName , Object value);
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByNameAndPassword"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =:myName and u.password=:myPassword
]]-->
</query>
</hibernate-mapping>
2、定义一个ValueBean,属性名必须和User.hbm.xml命名查询语句中的:后面的变量名同名,此处必须至少有两个属性,分别
为myName和myPassword,使用setter方法设置属性值后
ValueBean valueBean= new ValueBean();
valueBean.setMyName("test");
valueBean.setMyPasswrod("123");
3、
String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";
this.getHibernateTemplate().findByNamedQueryAndValueBean("queryByNameAndPassword", valueBean);
HibernateTemplate 需搭配SpringOpenSessionInViewFilter來關閉session
<filter>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
一、find(String queryString);
示例:this.getHibernateTemplate().find("from bean.User");
返回所有User对象
二、find(String queryString , Object value);
示例:this.getHibernateTemplate().find("from bean.User u where u.name=?", "test");
或模糊查询:this.getHibernateTemplate().find("from bean.User u where u.name like ?", "%test%");
返回name属性值为test的对象(模糊查询,返回name属性值包含test的对象)
三、find(String queryString, Object[] values);
示例:String hql= "from bean.User u where u.name=? and u.password=?"
this.getHibernateTemplate().find(hql, new String[]{"test", "123"});
返回用户名为test并且密码为123的所有User对象
---------------------------------
四、findByExample(Object exampleEntity)
示例:
User u=new User();
u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)
u.setName("bb");
list=this.getHibernateTemplate().findByExample(u,start,max);
返回:用户名为bb密码为123的对象
五、findByExample(Object exampleEntity, int firstResult, int maxResults)
示例:
User u=new User();
u.setPassword("123");//必须 符合的条件但是这两个条件时并列的(象当于sql中的and)
u.setName("bb");
list=this.getHibernateTemplate().findByExample(u,start,max);
返回:满足用户名为bb密码为123,自start起共max个User对象。(对象从0开始计数)
---------------------------------------------------
六、findByNamedParam(String queryString , String paramName , Object value)
使用以下语句查询:
String queryString = "select count(*) from bean.User u where u.name=:myName";
String paramName= "myName";
String value= "xiyue";
this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);
System.out.println(list.get(0));
返回name为xiyue的User对象的条数
七、findByNamedParam(String queryString , String[] paramName , Object[] value)
示例:
String queryString = "select count(*) from bean.User u where u.name=:myName and u.password=:myPassword";
String[] paramName= new String[]{"myName", "myPassword"};
String[] value= new String[]{"xiyue", "123"};
this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);
返回用户名为xiyue密码为123的User对象
八、findByNamedQuery(String queryName)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryAllUser"><!--此查询被调用的名字-->
<!--[CDATA[
from bean.User
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
this.getHibernateTemplate().findByNamedQuery("queryAllUser");
九、findByNamedQuery(String queryName, Object value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByName"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name = ?
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
this.getHibernateTemplate().findByNamedQuery("queryByName", "test");
十、findByNamedQuery(String queryName, Object[] value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByNameAndPassword"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =? and u.password =?
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
String[] values= new String[]{"test", "123"};
this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , values);
十一、findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByName"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =:myName
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
this.getHibernateTemplate().findByNamedQuery("queryByName" , "myName", "test");
十二、findByNamedQueryAndNamedParam(String queryName, String[] paramName, Object[] value)
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByNameAndPassword"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =:myName and u.password=:myPassword
]]>
</query>
</hibernate-mapping>
2、如下使用查询:
String[] names= new String[]{"myName", "myPassword"};
String[] values= new String[]{"test", "123"};
this.getHibernateTemplate().findByNamedQuery("queryByNameAndPassword" , names, values);
十三、findByValueBean(String queryString , Object value);
示例:
1、定义一个ValueBean,属性名必须和HSQL语句中的:后面的变量名同名,此处必须至少有两个属性,分别为myName和
myPassword,使用setter方法设置属性值后
ValueBean valueBean= new ValueBean();
valueBean.setMyName("test");
valueBean.setMyPasswrod("123");
2、
String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";
this.getHibernateTemplate().findByValueBean(queryString , valueBean);
十四、findByNamedQueryAndValueBean(String queryName , Object value);
示例:
1、首先需要在User.hbm.xml中定义命名查询
<hibernate-mapping>
<class>......</class>
<query name="queryByNameAndPassword"><!--此查询被调用的名字-->
<![CDATA[
from bean.User u where u.name =:myName and u.password=:myPassword
]]-->
</query>
</hibernate-mapping>
2、定义一个ValueBean,属性名必须和User.hbm.xml命名查询语句中的:后面的变量名同名,此处必须至少有两个属性,分别
为myName和myPassword,使用setter方法设置属性值后
ValueBean valueBean= new ValueBean();
valueBean.setMyName("test");
valueBean.setMyPasswrod("123");
3、
String queryString= "from bean.User u where u.name=:myName and u.password=:myPassword";
this.getHibernateTemplate().findByNamedQueryAndValueBean("queryByNameAndPassword", valueBean);
HibernateTemplate 需搭配SpringOpenSessionInViewFilter來關閉session
<filter>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
ERROR 2017 (HY000): Can't open named pipe to host: . pipe: MySQL (2)
I had the same problem with MySQL 5.0. I tried the other items suggested by other users (which didn't work).
To successfully install:
1) Go to control panel->add/remove programs and remove MySql
2) Go to c:\program files\ and delete the MySql directory
3) Reinstall and select "Standard Configuration" from the Server Instance Configuration Wizard. Do NOT choose "Detailed Configuration"
4) After the installation is complete (successfully this time) you can go to Start->Programs->MySql->MySql Server 5.0->MySQL Server Instance Configuration Wizard. Now you can configure the server as you wish...
To successfully install:
1) Go to control panel->add/remove programs and remove MySql
2) Go to c:\program files\ and delete the MySql directory
3) Reinstall and select "Standard Configuration" from the Server Instance Configuration Wizard. Do NOT choose "Detailed Configuration"
4) After the installation is complete (successfully this time) you can go to Start->Programs->MySql->MySql Server 5.0->MySQL Server Instance Configuration Wizard. Now you can configure the server as you wish...
WebMvcConfigurerAdapter
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-customize
OpenSessionInViewFilter 的配置及替代方案
http://justsee.iteye.com/blog/1174999
Spring 为我们提供了一个叫做 OpenSessionInViewFilter 的过滤器,他是标准的 Servlet Filter 所以我们把它按照规范配置到 web.xml 中方可使用。使用中我们必须配合使用 Spring 的 HibernateDaoSupport 来进行开发,也就是说,我们的dao层的类都要继承于 HibernateDaoSupport,从中由 Spring 来控制 Hibernate 的 Session 在请求来的时候开启,走的时候关闭,保证了我们访问数据对象时的稳定性。
Spring 为我们提供了一个叫做 OpenSessionInViewFilter 的过滤器,他是标准的 Servlet Filter 所以我们把它按照规范配置到 web.xml 中方可使用。使用中我们必须配合使用 Spring 的 HibernateDaoSupport 来进行开发,也就是说,我们的dao层的类都要继承于 HibernateDaoSupport,从中由 Spring 来控制 Hibernate 的 Session 在请求来的时候开启,走的时候关闭,保证了我们访问数据对象时的稳定性。
2015年4月18日 星期六
mysql Access denied for user
http://stackoverflow.com/questions/22508922/java-sql-sqlexception-access-denied-for-user-rootlocalhost-using-password
Access denied for user 'suntone'@'localhost' (using password: YES
sol:
GRANT ALL PRIVILEGES ON *.* TO 'suntone'@'localhost' IDENTIFIED BY 'suntone' WITH GRANT OPTION;
Access denied for user 'suntone'@'localhost' (using password: YES
sol:
GRANT ALL PRIVILEGES ON *.* TO 'suntone'@'localhost' IDENTIFIED BY 'suntone' WITH GRANT OPTION;
create table from pojo
http://openhome.cc/Gossip/HibernateGossip/HbmToTable.html
http://stackoverflow.com/questions/12054422/unsuccessful-alter-table-xxx-drop-constraint-yyy-in-hibernate-jpa-hsqldb-standa
package com.lfo.suntone.test;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class HbmToTable {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
System.out.println("Creating tables...");
SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true, true);
}
}
package com.lfo.suntone.test;
import org.hibernate.dialect.MySQL5InnoDBDialect;
public class ImprovedMySQLDialect extends MySQL5InnoDBDialect {
@Override
public String getDropSequenceString(String sequenceName) {
// Adding the "if exists" clause to avoid warnings
return "drop sequence if exists " + sequenceName;
}
@Override
public boolean dropConstraints() {
// We don't need to drop constraints before dropping tables, that just leads to error
// messages about missing tables when we don't have a schema in the database
return false;
}
}
DOWNLOAD
http://1drv.ms/1DRR8Bw
http://stackoverflow.com/questions/12054422/unsuccessful-alter-table-xxx-drop-constraint-yyy-in-hibernate-jpa-hsqldb-standa
package com.lfo.suntone.test;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class HbmToTable {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
System.out.println("Creating tables...");
SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true, true);
}
}
package com.lfo.suntone.test;
import org.hibernate.dialect.MySQL5InnoDBDialect;
public class ImprovedMySQLDialect extends MySQL5InnoDBDialect {
@Override
public String getDropSequenceString(String sequenceName) {
// Adding the "if exists" clause to avoid warnings
return "drop sequence if exists " + sequenceName;
}
@Override
public boolean dropConstraints() {
// We don't need to drop constraints before dropping tables, that just leads to error
// messages about missing tables when we don't have a schema in the database
return false;
}
}
DOWNLOAD
http://1drv.ms/1DRR8Bw
2015年4月11日 星期六
NotificationCompat
http://segmentfault.com/a/1190000000402154
private void sendNotification(String yourAwesomeUnicodeString) {
Stock stock= Utils.instance.readValueAsObject(yourAwesomeUnicodeString,new Stock());
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra(Config.gcmDateField,yourAwesomeUnicodeString);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle(stock.getStocktype().getName() + "缺貨通知").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("剩餘" + stock.getAmount())).setVibrate(new long[] { 1000, 1000 })
.setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private void sendNotification(String yourAwesomeUnicodeString) {
Stock stock= Utils.instance.readValueAsObject(yourAwesomeUnicodeString,new Stock());
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra(Config.gcmDateField,yourAwesomeUnicodeString);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentTitle(stock.getStocktype().getName() + "缺貨通知").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("剩餘" + stock.getAmount())).setVibrate(new long[] { 1000, 1000 })
.setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
訂閱:
意見 (Atom)