なかなかググっても解決できなかったが、Stuck over flowのこのページに答えがズバリ書いてあった。
裏でgradleのダウンロードが走っていてそれがstuckしてるように見えるようだ。
しかし10minも反応が帰ってこなければ、普通強制終了してしまうな。
「xxxダウンロード中」と表示させるだけで解決しそうな問題だ、UX, UI大事。
Get a full fake REST API with zero coding in less than 30 seconds (seriously)も嘘でなかった。
jun-mac:json-server jun-ishioka$ npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg> --save` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. name: (json-seerver-test) json-server-test version: (1.0.0) description: for test git repository: keywords: author: license: (ISC) About to write to /Users/jun-ishioka/temp/json-server/package.json: { "name": "json-server-test", "version": "1.0.0", "description": "for test", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this ok? (yes) yes
jun-mac:json-server jun-ishioka$ npm install --save-dev json-server
{
"users": [
{ "id": 1, "name": "kageki", "genger": "man" },
{ "id": 2, "name": "kageki_2", "genger": "man" }
]
}
jun-mac:json-server jun-ishioka$ node node_modules/json-server/bin/index.js -w db.json \{^_^}/ hi! Loading db.json Done Resources http://localhost:3000/users Home http://localhost:3000 Type s + enter at any time to create a snapshot of the database Watching...
jun-mac:~ jun-ishioka$ curl -O GET http://localhost:3000/users curl: Remote file name has no length! curl: try 'curl --help' or 'curl --manual' for more information [ { "id": 1, "name": "kageki", "genger": "man" }, { "id": 2, "name": "kageki_2", "genger": "man" } ]
cd ~/repos/kinsume_blog rbenv local install 2.2.7 gem install bundler bundle install
app_path = File.expand_path(File.dirname(__FILE__) + '/..')$ $ # workerをいくつ立ち上げるか。ここではCMSであまりアクセスないことを$ # 想定していて、メモリの空きもないので1にしている。$ worker_processes 1$ $ # どのソケットで連携するかNginxの設定ファイルにも書くので覚えておく$ listen app_path + '/tmp/kinsume_blog.sock', backlog: 64$ timeout 300$ working_directory app_path$ $ # この辺もすでに動いているアプリと被らないようにする$ pid app_path + '/tmp/kinsume_blog.pid'$ stderr_path app_path + '/log/kinsume_blog.log'$ stdout_path app_path + '/log/kinsume_blog.log'$ $ preload_app true$ $ GC.respond_to?(:copy_on_write_friendly=) &&$ GC.copy_on_write_friendly = true$ $ before_fork do |server, worker|$ defined?(ActiveRecord::Base) &&$ ActiveRecord::Base.connection.disconnect!$ end$ $ after_fork do |server, worker|$ defined?(ActiveRecord::Base) &&$ ActiveRecord::Base.establish_connection$ end$
# Specify a different Refinery::Core::Engine mount path than the default of "/".$ # Make sure you clear the `tmp/cache` directory after changing this setting.$ config.mounted_path = "/kinsume_blog"$
config.assets.prefix = '/static'$
upstream tagosaku{$ server unix:/home/ishioka/repos/tagosaku/tmp/tagosaku.sock fail_timeout=0;$ }$ # 先ほど作成したアプリのソケットファイルをここで指定 upstream kinsume_blog{$ server unix:/home/ishioka/repos/kinsume_blog/tmp/kinsume_blog.sock fail_timeout=0;$ }$ $ server {$ error_log /var/log/nginx/error.log debug;$ listen 80;$ $ root /home/ishioka/repos/tagosaku;$ index index.html index.htm;$ $ keepalive_timeout 300;$ client_max_body_size 4G;$ # kinsume_blogないで使っているgemから走るアクセスパスをどうしても変えられなかったので悲しみのrewriteで対応 rewrite ^/wymiframe$ /kinsume_blog/wymiframe last;$ $ # ここでもkinsume_blogないのgemから走るアクセスを変えられなかったので、いったんassetsを見てふぁいるがなければ/static/を見に行くように変更 location ~ ^/assets/(.*) {$ root /home/ishioka/repos/tagosaku/public/;$ try_files $uri /static/$1 =404;$ }$ $ # staticへのアクセスはkinsume_blogの静的ファイルへのアクセスなのでロケーションを変更 location /static/ {$ root /home/ishioka/repos/kinsume_blog/public/;$ }$ location / {$ # First attempt to serve request as file, then$ # as directory, then fall back to displaying a 404.$ #try_files $uri $uri/ =404;$ $ # Uncomment to enable naxsi on this location$ # include /etc/nginx/naxsi.rules$ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;$ proxy_set_header Host $http_host;$ proxy_set_header X-Forwarded_Proto $scheme;$ proxy_redirect off;$ $ # This passes requests to unicorn, as defined in /etc/nginx/nginx.conf$ proxy_set_header Host $http_host;$ proxy_pass http://tagosaku;$ proxy_read_timeout 300s;$ proxy_send_timeout 300s;$ }$ $ location /kinsume_blog {$ # First attempt to serve request as file, then$ # as directory, then fall back to displaying a 404.$ #try_files $uri $uri/ =404;$ $ # Uncomment to enable naxsi on this location$ # include /etc/nginx/naxsi.rules$ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;$ proxy_set_header Host $http_host;$ proxy_set_header X-Forwarded_Proto $scheme;$ proxy_redirect off;$ $ # This passes requests to unicorn, as defined in /etc/nginx/nginx.conf$ proxy_set_header Host $http_host;$ proxy_pass http://kinsume_blog;$ proxy_read_timeout 300s;$ proxy_send_timeout 300s;$ }$ $ error_page 500 502 503 504 /500.html;$ $ location = /500.html {$ root /home/ishioka/repos/tagosaku/public;$ }$ }
# ruby 2.2.7 のインストール rbenv install 2.2.7 rbenv rehash rbenv global 2.2.7 # 動作に必要なgem install gem install bundle gem install refinerycms # railsのプロジェクト作成 refinerycms blog_test cd blog_test # このフォルダは 2.2.7で動かしたいのでversion指定 touch .ruby-version; echo "2.2.7" > .ruby-version # 開発用サーバ動かす bundle exec rails s -b 0.0.0.0
Company.users.build(name: 'xxxxx')
rails g model Company name:string rails g model User company_id:integer name:string bundle exec rails db:migrate RAILS_ENV=development == 20170617020543 CreateUsers: migrating ====================================== -- create_table(:users) -> 0.0027s == 20170617020543 CreateUsers: migrated (0.0028s) ============================= == 20170617020644 CreateCompanies: migrating ================================== -- create_table(:companies) -> 0.0010s == 20170617020644 CreateCompanies: migrated (0.0015s) =========================
class Company < ApplicationRecord has_many :users def self.build_users binding.pry com = Company.find_or_create_by(name: 'test_company') com.users.build(name: 'test_user') com.users.where(name: 'test_company') end end
From: /home/ishioka/repos/rails/activerecord/lib/active_record/associations/collection_proxy.rb @ line 316 ActiveRecord::Associations::CollectionProxy#build: 315: def build(attributes = {}, &block) => 316: @association.build(attributes, &block) 317: end
[1] pry(#<User::ActiveRecord_Associations_CollectionProxy>)> @association User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."company_id" = ? [["company_id", 1]] => #<ActiveRecord::Associations::HasManyAssociation:0x007f752027be50 @association_scope=nil, @inversed=false, @loaded=false, @owner=#<Company:0x007f753ec2a668 id: 1, name: "test_company", created_at: Sat, 17 Jun 2017 02:30:35 UTC +00:00, updated_at: Sat, 17 Jun 2017 02:30:35 UTC +00:00>, @proxy=[], @reflection= #<ActiveRecord::Reflection::HasManyReflection:0x007f753f044988 @active_record=Company(id: integer, name: string, created_at: datetime, updated_at: datetime), @active_record_primary_key="id", @association_scope_cache= {true=> #<ActiveRecord::StatementCache:0x007f753efcb060 @bind_map= #<ActiveRecord::StatementCache::BindMap:0x007f753efcb5d8 @bound_attributes= [#<ActiveRecord::Relation::QueryAttribute:0x007f753efc5b10 @name="company_id", @original_attribute=nil, @type=#<ActiveModel::Type::Integer:0x007f753efa4a00 @limit=nil, @precision=nil, @range=-2147483648...2147483648, @scale=nil>, @value=#<ActiveRecord::StatementCache::Substitute:0x007f753efc6880>, @value_before_type_cast=#<ActiveRecord::StatementCache::Substitute:0x007f753efc6880>>], @indexes=[0]>, @query_builder=#<ActiveRecord::StatementCache::Query:0x007f753efcb088 @sql="SELECT \"users\".* FROM \"users\" WHERE \"users\".\"company_id\" = ?">>}, @automatic_inverse_of=false, @class_name="User", @constructable=true, @foreign_key="company_id", @foreign_type="users_type", @klass=User(id: integer, company_id: integer, name: string, created_at: datetime, updated_at: datetime), @name=:users, @options={}, @plural_name="users", @scope=nil, @scope_lock=#<Thread::Mutex:0x007f753f044618>, @type=nil>, @stale_state=nil, @target=[]>
From: /home/ishioka/repos/rails/activerecord/lib/active_record/inheritance.rb @ line 65 ActiveRecord::Inheritance::ClassMethods#new: 48: def new(*args, &block) 49: if abstract_class? || self == Base 50: raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated." 51: end 52: 53: attrs = args.first 54: if has_attribute?(inheritance_column) 55: subclass = subclass_from_attributes(attrs) 56: 57: if subclass.nil? && base_class == self 58: subclass = subclass_from_attributes(column_defaults) 59: end 60: end 61: 62: if subclass && subclass != self 63: subclass.new(*args, &block) 64: else => 65: super 66: end 67: end [9] pry(User)> self.parent => Object
From: /home/ishioka/repos/rails/activerecord/lib/active_record/associations/collection_association.rb @ line 281 ActiveRecord::Associations::CollectionAssociation#add_to_target: 277: def add_to_target(record, skip_callbacks = false, &block) 278: if association_scope.distinct_value 279: index = @target.index(record) 280: end => 281: replace_on_target(record, index, skip_callbacks, &block) 282: end [11] pry(#<ActiveRecord::Associations::HasManyAssociation>)> record => #<User:0x007f753e614440 id: nil, company_id: 1, name: "test_user", created_at: nil, updated_at: nil>
From: /home/ishioka/repos/rails/activerecord/lib/active_record/associations/collection_association.rb @ line 441 ActiveRecord::Associations::CollectionAssociation#replace_on_target: 440: def replace_on_target(record, index, skip_callbacks) => 441: callback(:before_add, record) unless skip_callbacks 442: 443: set_inverse_instance(record) 444: 445: @_was_loaded = true 446: 447: yield(record) if block_given? 448: 449: if index 450: target[index] = record 451: elsif @_was_loaded || !loaded? 452: target << record 453: end 454: 455: callback(:after_add, record) unless skip_callbacks 456: 457: record 458: ensure 459: @_was_loaded = nil 460: end
From: /home/ishioka/repos/rails/activerecord/lib/active_record/associations/collection_association.rb @ line 452 ActiveRecord::Associations::CollectionAssociation#replace_on_target: 440: def replace_on_target(record, index, skip_callbacks) 441: callback(:before_add, record) unless skip_callbacks 442: 443: set_inverse_instance(record) 444: 445: @_was_loaded = true 446: 447: yield(record) if block_given? 448: 449: if index 450: target[index] = record 451: elsif @_was_loaded || !loaded? => 452: target << record 453: end 454: 455: callback(:after_add, record) unless skip_callbacks 456: 457: record 458: ensure 459: @_was_loaded = nil 460: end [17] pry(#<ActiveRecord::Associations::HasManyAssociation>)> target => [] [19] pry(#<ActiveRecord::Associations::HasManyAssociation>)> target.class => Array
From: /home/ishioka/repos/CodeReading/app/models/company.rb @ line 9 Company.build_users: 5: def self.build_users 6: binding.pry 7: com = Company.find_or_create_by(name: 'test_company') 8: com.users.build(name: 'test_user') => 9: com.users.where(name: 'test_company') 10: end [24] pry(Company)> com.users => [#<User:0x007f753e614440 id: nil, company_id: 1, name: "test_user", created_at: nil, updated_at: nil>]
From: /home/ishioka/repos/rails/activerecord/lib/active_record/relation/query_methods.rb @ line 600 ActiveRecord::QueryMethods#where: 599: def where(opts = :chain, *rest) => 600: if :chain == opts 601: WhereChain.new(spawn) 602: elsif opts.blank? 603: self 604: else 605: spawn.where!(opts, *rest) 606: end 607: end
From: /home/ishioka/repos/rails/activerecord/lib/active_record/relation/query_methods.rb @ line 610 ActiveRecord::QueryMethods#where!: 609: def where!(opts, *rest) # :nodoc: => 610: opts = sanitize_forbidden_attributes(opts) 611: references!(PredicateBuilder.references(opts)) if Hash === opts 612: self.where_clause += where_clause_factory.build(opts, rest) 613: self 614: end
class Company < ApplicationRecord has_many :users def self.build_users binding.pry com = Company.find_or_create_by(name: 'test_company') com.users.build(name: 'test_user') users = com.users.where(name: 'test_company') _count_users = users.count end end ~
From: /home/ishioka/repos/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @ line 34 ActiveRecord::ConnectionAdapters::DatabaseStatements#select_all: 31: def select_all(arel, name = nil, binds = [], preparable: nil) 32: arel, binds = binds_from_relation arel, binds 33: sql = to_sql(arel, binds) => 34: if !prepared_statements || (arel.is_a?(String) && preparable.nil?) 35: preparable = false 36: else 37: preparable = visitor.preparable 38: end 39: if prepared_statements && preparable 40: select_prepared(sql, name, binds) 41: else 42: select(sql, name, binds) 43: end 44: end [2] pry(#<ActiveRecord::ConnectionAdapters::SQLite3Adapter>)> sql => "SELECT COUNT(*) FROM \"users\" WHERE \"users\".\"company_id\" = ? AND \"users\".\"name\" = ?"
From: /home/ishioka/repos/CodeReading/app/models/company.rb @ line 10 Company.build_users: 5: def self.build_users 6: binding.pry 7: com = Company.find_or_create_by(name: 'test_company') 8: com.users.build(name: 'test_user') 9: users = com.users.where(name: 'test_company') => 10: _count_users = users.count 11: end [1] pry(Company)> n (0.8ms) SELECT COUNT(*) FROM "users" WHERE "users"."company_id" = ? AND "users"."name" = ? [["company_id", 1], ["name", "test_company"]] From: /home/ishioka/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/pry-0.10.4/lib/pry/pry_instance.rb @ line 356 Pry#evaluate_ruby: 351: def evaluate_ruby(code) 352: inject_sticky_locals! 353: exec_hook :before_eval, code, self 354: 355: result = current_binding.eval(code, Pry.eval_path, Pry.current_line) => 356: set_last_result(result, code) 357: ensure 358: update_input_history(code) 359: exec_hook :after_eval, result, self 360: end [1] pry(#<Pry>)> c => 0
import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D from keras.utils import np_utils from keras import backend as K K.set_image_dim_ordering('th')
# fix random seed for reproducibility seed = 7 numpy.random.seed(seed)
# load data (X_train, y_train), (X_test, y_test) = mnist.load_data() # reshape to be [samples][pixels][width][height] X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32') X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
# normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1]
# create model model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(1, 28, 28), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(num_classes, activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Baseline Error: %.2f%%" % (100-scores[1]*100))
Train on 60000 samples, validate on 10000 samples Epoch 1/10 172s - loss: 0.2310 - acc: 0.9347 - val_loss: 0.0825 - val_acc: 0.9743 Epoch 2/10 170s - loss: 0.0736 - acc: 0.9780 - val_loss: 0.0467 - val_acc: 0.9841 Epoch 3/10 175s - loss: 0.0531 - acc: 0.9839 - val_loss: 0.0432 - val_acc: 0.9856 Epoch 4/10 165s - loss: 0.0401 - acc: 0.9878 - val_loss: 0.0406 - val_acc: 0.9869 Epoch 5/10 179s - loss: 0.0337 - acc: 0.9893 - val_loss: 0.0346 - val_acc: 0.9886 Epoch 6/10 156s - loss: 0.0275 - acc: 0.9916 - val_loss: 0.0309 - val_acc: 0.9893 Epoch 7/10 163s - loss: 0.0232 - acc: 0.9927 - val_loss: 0.0359 - val_acc: 0.9877 Epoch 8/10 158s - loss: 0.0204 - acc: 0.9937 - val_loss: 0.0324 - val_acc: 0.9887 Epoch 9/10 164s - loss: 0.0166 - acc: 0.9947 - val_loss: 0.0300 - val_acc: 0.9901 Epoch 10/10 178s - loss: 0.0143 - acc: 0.9958 - val_loss: 0.0310 - val_acc: 0.9905 Baseline Error: 0.95%
# Plot ad hoc mnist instances from keras.datasets import mnist import matplotlib.pyplot as plt # load (downloaded if needed) the MNIST dataset (X_train, y_train), (X_test, y_test) = mnist.load_data() # plot 4 images as gray scale plt.subplot(221) plt.imshow(X_train[0], cmap=plt.get_cmap('gray')) plt.subplot(222) plt.imshow(X_train[1], cmap=plt.get_cmap('gray')) plt.subplot(223) plt.imshow(X_train[2], cmap=plt.get_cmap('gray')) plt.subplot(224) plt.imshow(X_train[3], cmap=plt.get_cmap('gray')) # show the plot plt.show()
import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils
# fix random seed for reproducibility seed = 7 numpy.random.seed(seed)
# load data (X_train, y_train), (X_test, y_test) = mnist.load_data()
# flatten 28*28 images to a 784 vector for each image # print(type(X_train)) num_pixels = X_train.shape[1] * X_train.shape[2] # 28 * 28 X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') # 60000 , 784 # 784要素のArrayが60000個ある2次元配列になった。 # print(X_train.shape) X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
# normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255
# one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1]
# create model model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu')) model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=20, batch_size=200, verbose=2) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Baseline Error: %.2f%%" % (100-scores[1]*100))
Baseline Error: 1.61%が最終出力。つまり10000のイメージでテストしてみて、1.61%はこのモデルでの予想とはずれたが、98.4%は正解になったということ