ruby 杰奇中创建一个新的岗位文章

杰奇中创建一个新的岗位文章

article.rb
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
# 2018-11-07 15:40
task :newart,[:article,:title,:categories,:tags,:description] do |t,args|
        time = Time.new #Get new time
        timeinfos = time.to_s.split(" ")
        path ="_posts/"
        filename= args["article"].gsub(" ","-")
        suffix = ".markdown"
        newfile = path+timeinfos[0]+"-"+filename+suffix

        title =args["title"].nil?? "title-name" : args["title"]
        date = time.inspect
        categories =args["categories"].nil??  "articles" : args["categories"]
        tags = args["tags"].nil?? "notags" : args["tags"].split(" ")
        comments = true
        description = args["description"].nil?? "" : "desctiption: #{args["description"]}\n"
        inputContent = "---\nlayout: post\ntitle: #{title} \ndate: #{date} \ncategories: #{categories} \ntags: #{tags}\ncomments: #{comments}\n#{description}---\n"
        File.open(newfile,"w+") do |aFile|
                aFile.write(inputContent)
        end
end
# Learning other
time = Time.new
 
# Time 的组件
puts "当前时间 : " + time.inspect
puts time.year    # => 日期的年份
puts time.month   # => 日期的月份(1 到 12)
puts time.day     # => 一个月中的第几天(1 到 31)
puts time.wday    # => 一周中的星期几(0 是星期日)
puts time.yday    # => 365:一年中的第几天
puts time.hour    # => 23:24 小时制
puts time.min     # => 59
puts time.sec     # => 59
puts time.usec    # => 999999:微秒
puts time.zone    # => "UTC":时区名称

# 22:31
# filename = "test.markdown"
# File.open(filename, "w+") do |aFile|
#    aFile.write("test")
# end

ruby 修复了rake资产:预编译任务

修复了rake资产:预编译任务

assets.rake
desc "Compile all the assets named in config.assets.precompile"
task :precompile do
  # We need to do this dance because RAILS_GROUPS is used
  # too early in the boot process and changing here is already too late.
  if ENV["RAILS_GROUPS"].to_s.empty? || ENV["RAILS_ENV"].to_s.empty?
    ENV["RAILS_GROUPS"] ||= "assets"
    ENV["RAILS_ENV"]    ||= "production"
    Kernel.exec $0, *ARGV
  else
    Rake::Task["environment"].invoke

    # Ensure that action view is loaded and the appropriate sprockets hooks get executed
    ActionView::Base

    # Always calculate digests and compile files
    Rails.application.config.assets.digest = true
    Rails.application.config.assets.compile = true

    config = Rails.application.config
    env    = Rails.application.assets
    target = Pathname.new(File.join(Rails.public_path, config.assets.prefix))
    manifest = {}
    manifest_path = config.assets.manifest || target

    config.assets.precompile.each do |path|
      env.each_logical_path do |logical_path|
        if path.is_a?(Regexp)
          next unless path.match(logical_path)
        else
          next unless File.fnmatch(path.to_s, logical_path)
        end

        if asset = env.find_asset(logical_path)
          manifest[logical_path] = asset.digest_path
          filename = target.join(asset.digest_path)
          mkdir_p filename.dirname
          asset.write_to(filename)
          asset.write_to("#{filename}.gz") if filename.to_s =~ /\.(css|js)$/
        end
      end
    end

    File.open("#{manifest_path}/manifest.yml", 'w') do |f|
      YAML.dump(manifest, f)
    end
  end
end

ruby 简单线性模型ML

简单线性模型ML

ruby_linear_model.rb
class LinearModel
  attr_reader :slope, :y_intercept

  def initialize(learning_rate = 0.1, epoch = 100000)
      # Initialize y_intercept & slope
      @y_intercept = 0
      @slope = 1

      # How much will the error affect the change in parameters
      @learning_rate = learning_rate

      # How many times will we iterate through the dataset
      @epoch = epoch
  end
  
  def predict(x)
    # y = w1 * x1 + b
      return @slope * x + @y_intercept
  end

  def fit(dataset)
    @epoch.times do
      dataset.shuffle.each do |data_point|
        # Make a guess with current y-intercept & slope
        guess = predict(data_point[:input])

        # Calculate the error of that guess
        error = data_point[:output] - guess

        # Update y-intercept & slope using "stochastic gradient descent"
        @slope = @slope + ((error * data_point[:input]) * @learning_rate)
        @y_intercept = @y_intercept + (error * @learning_rate)
      end
    end
  end
end


dataset = [
  #{input: mass(g), output: length(cm)}
  {input: 0.50, output: 56}, 
  {input: 0.85, output: 119},
  {input: 0.99, output: 140}, 
  {input: 1.30, output: 190},
]
  
# Initialize our linear model
string_length_predictor = LinearModel.new()

# Ask it to fit it's y-intercept and slope to our dataset
string_length_predictor.fit(dataset)

# Output the results
predictions = dataset.map do |data_point|
  string_length_predictor.predict(data_point[:input]).round(3)
end

puts "Actual values: #{dataset.map{|point| point[:output]}}"
puts "Predictions: #{predictions}"
puts "Slope: #{string_length_predictor.slope}"
puts "y-intercept: #{string_length_predictor.y_intercept}"

ruby jsonapi_suite内存关联的侧载

jsonapi_suite内存关联的侧载

sideloading_in_memory.rb
# In-memory associations as jsonapi_suite sideloads
# Using the trick of memoization, assuming the parent known about the children
# 
# @example 
#   The parent could have a `field type_string, type: String`
#   and a method #type that calls and memoizes `self.type_string.camelize.constantize`
#

class Parent
  def association_in_memory
    @association_in_memory ||= code_to_get_all_association
  end

  def my_child?(child)
    # ...
  end
end

class Child
  # nothing particular
end

allow_sideload :association_in_memory, resource: InMemoryResource do
  # Read the association in memory, 
  # we flatten everything in the same array
  scope do |parents|
    parents.all.flat_map(&:association_in_memory) # before they get filtered or whatever
  end

  # Now our flattened array was just filtered, we need to "reassign" what was previously assigned to the right guy
  assign do |parents, children_in_memory_after_getting_filtered_or_whatever|
    tldr = children_in_memory_after_getting_filtered_or_whatever
    parents.each do |parent|
      children_belonging_to_parent = children_in_memory_after_getting_filtered_or_whatever.select do |child|
        parent.my_child?(child)
      end
      parent.instance_variable_set('@association_in_memory', children_belonging_to_parent)
    end
  end
end

ruby jsonapi_suite用于内存Iterables适配器

jsonapi_suite用于内存Iterables适配器

in_memory_iterable_adapter.rb
module Jsonapi
  module Adapters
    # Adapter for resources already loaded in memory
    # 
    # The scope is meant to be something like an Array or Iterable of objects
    # 
    # @example Time Series
    # 
    # scope = [
    #   OpenStruct.new(at: Time.now.noon, name: 'I ate'),
    #   OpenStruct.new(at: Time.now.midnight, name: 'I went to sleep')
    # ]
    # 
    # Sorting by time 
    #   scope.sort_by(&:at)
    # Filtering by event name
    #   scope.select { |i| i.name == 'I ate' }
    #
    # @author [Cyril]
    #
    class InMemoryIterableAdapter < TransactionlessMongoidAdapter
      # @override
      def resolve(scope)
        scope
      end

      # @override for array sort
      def filter(scope, attribute, value)
        scope.select do |item|
          item.send(attribute) == value
        end
      end

      # @Override
      def order(scope, attribute, direction)
        # return scope if attribute == :id # Seems broken
        if direction == :asc
          scope.sort_by { |i| i.public_send(attribute) }
        elsif direction == :desc
          scope.sort_by { |i| i.public_send(attribute) }.reverse
        end
      end

      # @Override
      def paginate(scope, current_page, per_page)
        pg_start = (current_page - 1) * per_page
        pg_eng = (current_page) * per_page - 1
        scope[pg_start..pg_eng]
      end

      # @Override
      def count(scope, _attr)
        scope.size
      end
    end
  end
end

ruby 佛祖保佑,永无BUG

佛祖保佑,永无BUG

index.js
//
//                       _oo0oo_
//                      o8888888o
//                      88" . "88
//                      (| -_- |)
//                      0\  =  /0
//                    ___/`---'\___
//                  .' \\|     |// '.
//                 / \\|||  :  |||// \
//                / _||||| -:- |||||- \
//               |   | \\\  -  /// |   |
//               | \_|  ''\---/''  |_/ |
//               \  .-\__  '-'  ___/-. /
//             ___'. .'  /--.--\  `. .'___
//          ."" '<  `.___\_<|>_/___.' >' "".
//         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//         \  \ `_.   \_ __\ /__ _/   .-` /  /
//     =====`-.____`.___ \_____/___.-`___.-'=====
//                       `=---='
//
//
//     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//               佛祖保佑         永无BUG
//
//
//
index.rb
#
#                       _oo0oo_
#                      o8888888o
#                      88" . "88
#                      (| -_- |)
#                      0\  =  /0
#                    ___/`---'\___
#                  .' \\|     |# '.
#                 / \\|||  :  |||# \
#                / _||||| -:- |||||- \
#               |   | \\\  -  #/ |   |
#               | \_|  ''\---/''  |_/ |
#               \  .-\__  '-'  ___/-. /
#             ___'. .'  /--.--\  `. .'___
#          ."" '<  `.___\_<|>_/___.' >' "".
#         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
#         \  \ `_.   \_ __\ /__ _/   .-` /  /
#     =====`-.____`.___ \_____/___.-`___.-'=====
#                       `=---='
#
#
#     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#               佛祖保佑         永无BUG
#
#
#

ruby 单个对象或数组迭代

当你需要迭代你想要成为一个数组的东西,但你不确定...

iterate.rb
stuff = 1
stuff_array = [1, 2, 3, 4]

# if you arent' sure what the type is and you need to iterate through it
[*stuff].each { |s| s} # even if its a single object, it will still iterate
[*stuff_array].each { |s| s}

# Alternatively ...
Array(stuff).each { |s| s}
Array(Stuff_array).each { |s| s}

ruby 表单中的JSONB字段

将jsonb文件添加到rails表单

model.rb
class User::Address < ActiveRecord::Base
  DELIVERY_METHODS = ['nova_poshta_office', 'nova_poshta_courier']
  JSONB_FIELDS = [:city, :office_id, :street, :building, :appartment]

  belongs_to :user, foreign_key: 'user_id'

  serialize :address_specs, ActiveRecord::Coders::JSON
  store_accessor :address_specs, :city, :office_id, :street, :building, :appartment

  validates_associated :user
  validates :delivery_method, :phone_number, :recipient_full_name, :user_id, presence: true
  validate :check_json_fields

  def self.nova_poshta_office_fields
    [
      'city',
      'office_id'
    ]
  end

  def self.nova_poshta_courier_fields
    [
      'city',
      'street',
      'building',
      'appartment'
    ]
  end

  def delivery_data
    delivery_data = ''
    if delivery_method == 'nova_poshta_office'
      delivery_data << "Отделение № #{address_specs["office_id"]}"
    else
      specs = address_specs
      street, building, appartment = specs["street"], specs["building"], specs["appartment"] || ""
      delivery_data << "ул. #{street}, #{building}#{" , кв. " + appartment unless appartment.empty?}"
    end
    delivery_data
  end

  private

  def check_json_fields
    binding.pry
    if delivery_method == 'nova_poshta_office'
      errors.add(:address_specs, "Заполните все поля") unless address_specs["city"].present? &&
                                                              address_specs["office_id"].present?
    end
    if delivery_method == 'nova_poshta_courier'
      errors.add(:address_specs, "Заполните все поля") unless address_specs["city"].present? &&
                                                              address_specs["street"].present? &&
                                                              address_specs["building"].present?
    end
  end

end
controller.rb
class Website::UserAddressesController < Website::ApplicationController
  before_filter :authenticate_user!
  before_filter :set_address, only: [:edit, :destroy]

  def index
    @addresses = current_user.addresses
  end

  def new
    @address = User::Address.new
  end

  def create
    @address = User::Address.new(address_params)
    if @address.save
      redirect_to addresses_path, notice: 'Адрес доставки успешно добавлен к вашей учетной записи'
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @address.update_attributes(address_params)
      redirect_to addresses_path, notice: 'Адрес #{@address.title } успешно обновлен'
    else
      render 'edit'
    end
  end

  def destroy
    @address.destroy

    redirect_to addresses_path, notice: "Адрес #{@address.title } удален из вашен учетной записи"
  end

  private

  def address_params
    params.require(:user_address).permit(:user_id, :delivery_method, :phone_number, :recipient_full_name, address_specs: User::Address::JSONB_FIELDS)
  end

  def set_address
    @address = User::Address.find(params[:id])
  end

end
new.slim
section.devise
  = render partial: 'devise/shared/top_line'
  section
    .container.clear
      = render partial: 'devise/shared/navigation'
      main.userdata_form
        div.container-fluid
          = simple_form_for @address, url: addresses_path, html: { method: :post } do |f|
            = f.text_field :user_id, value: current_user.id, type: 'hidden'
            label
              b Выберите способ доставки
              br
              = f.select :delivery_method, [[I18n.t(".user.address.delivery_method.nova_poshta_office"), 'nova_poshta_office'], [I18n.t(".user.address.delivery_method.nova_poshta_courier"), 'nova_poshta_courier']], { }, { "data-bind" => 'CreateSelect2' }
            br

            label
              b Укажите немер телефона
              br
              = f.text_field :phone_number
            br

            label
              b Ф.И.О. получателя
              br
              = f.text_field :recipient_full_name
            br

            label
              b Город
              br
              = f.text_field :address_specs, name: "user_address[address_specs][city]"
            br

            label
              b Номер отделения
              br
              = f.text_field :address_specs, name: "user_address[address_specs][office_id]"
            br

            label
              b Улица
              br
              = f.text_field :address_specs, name: "user_address[address_specs][street]"
            br

            label
              b Дом
              br
              = f.text_field :address_specs, name: "user_address[address_specs][building]"
            br

            label
              b Квартира
              br
              = f.text_field :address_specs, name: "user_address[address_specs][appartment]"
            br

            label
              b ТЕСТОВАЯ ХЕРНЯ
              br
              = f.text_field :address_specs, name: "user_address[address_specs][khernia]"
            br

            / Insert JS to render fields according to delivery method

            =f.submit "Сохранить", class: 'btn yellow', style: 'margin: 25px 0;'

ruby 在活动管理员中编辑没有密码的用户

将其添加到您的管理资源:

dd
controller do
  def update_resource(object, attributes)
    update_method = attributes.first[:password].present? ? :update_attributes : :update_without_password
    object.send(update_method, *attributes)
  end
end

ruby 网络会议加载

Cargar Citas basados en un script + csv

load_meetings.rb
total_errors = []
BusinessConferenceMeeting.transaction do
  index = 0
  file_path = '/home/ubuntu/citas.csv'
  CSV.foreach(file_path, headers: true, col_sep: ";") do |row|
    import_columns  = Hash[row.map{|header, value| [header.to_s.downcase.strip, value.to_s]}]
    index += 1

    participant_profile_display_name = import_columns["participant"]
    participant_profile_contact_name = import_columns["participant_contact"]
    host_profile_display_name = import_columns["host"]
    host_profile_contact_name = import_columns["host_contact"]
    participant = BusinessConferenceParticipant.where(profile_display_name: participant_profile_display_name, profile_contact_name: participant_profile_contact_name, business_conference_id: 3983, archived: false)
    host = BusinessConferenceParticipant.where(profile_display_name: host_profile_display_name, profile_contact_name: host_profile_contact_name, business_conference_id: 3983, archived: false)
  
    if participant.blank?
      puts "Participant in line #{index + 1} not found"
    end

    if host.blank?
      puts "Host in line #{index + 1} not found"
    end

    next if participant.blank? or host.blank?

    start_date = import_columns["date"]
    start_date = start_date.to_datetime
    start_date = start_date.to_i
    meeting, errors = BusinessConferenceMeeting.add_new(3983, host.first.id, participant.first.id, start_date, nil, User.find(4084), 4, true, false)
    if errors.present?
      total_errors << "#{index + 1} --- #{errors}"
    else
      meeting.update_columns(location: import_columns["table"])
      puts "Line #{index + 1}"
    end
  end
end
puts total_errors