text
stringlengths 27
775k
|
---|
class Helpdesk < Sinatra::Base
# Filter for authentication and authorization checks
# before /\/(?!(login|forgot\-password))/ do #With regex
# redirect '/login' unless session[:username] != nil
# end
# before do #Without regex
# pass if ['/', '/login', '/forgot-password'].include? request.path_info.split('/')[1]
# redirect '/login' unless session[:username] != nil
# end
#Process login inputs
post '/login' do
self.init_ctx
usr = @db[:users].find(
'username' => @params[:id],
'password' => Digest::SHA1.hexdigest(@params[:pw]),
'islocked' => 'false'
).limit(1).first
if usr == nil
redirect '/login?msg=Invalid+login'
return #redirect is supposed to stop execution of this method, but just to be sure
end
session[:rolename] = usr[:rolename]
session[:username] = usr[:username]
session[:ticket_details] = usr[:ticket_details]
redirect '/'
end
#Logout the user by clearing session information
get '/logout' do
#self.init_ctx
session[:username] = session[:rolename] = session[:ticket_details] = nil
@username = @rolename = session[:ticket_details] = nil
redirect '/'
end
#Displays the login page
get '/login' do
self.init_ctx
#if @params[:msg] != nil && @params[:msg] != ''
# @msg = @params[:msg]
#end
erb :login
end
#Displays the forgot password page
get '/forgot-password' do
self.init_ctx
#if @params[:msg] != nil && @params[:msg] != ''
# @msg = @params[:msg]
#end
erb :forgotpass
end
post '/forgot-password' do
self.init_ctx
usr = @db[:users].find(
'email' => @params[:email],
).limit(1).first
#TODO: There could be multiple user accounts with the same email address; we have to stop this from happening
if usr == nil
redirect '/login?msg=Invalid+login'
return #redirect is supposed to stop execution of this method, but just to be sure
end
#Send the user a link by email to confirm the password reset
usr[:reset_token] = Array.new(10){rand(36).to_s(36)}.join.downcase
code_exist = @db[:users].find(:reset_token => usr[:reset_token]).count()
while code_exist > 0
usr[:reset_token] = Array.new(10){rand(36).to_s(36)}.join.downcase
code_exist = @db[:users].find(:reset_token => usr[:reset_token]).count()
end
@db[:users].update_one(
{'username' => usr[:username]},
usr,
{:upsert => false}
)
send_email({
:recipient_name => usr[:display],
:recipient_email => usr[:email],
:subject => 'Password Reset',
:body => "Your ID is: #{usr[:username]} and your password reset code is: #{usr[:reset_token]}"
})
#Display a message conveying that the password reset email has been sent
redirect '/forgot-token?msg=Password+reset+email+has+been+sent'
end
get '/forgot-token' do
self.init_ctx
erb :forgottoken
end
post '/forgot-token' do
self.init_ctx
usr = @db[:users].find(
'reset_token' => @params[:token],
).limit(1).first
if usr == nil
redirect '/forgot-token?msg=Invalid+token'
end
newpwd = Array.new(10){rand(36).to_s(36)}.join.downcase
usr[:password] = Digest::SHA1.hexdigest(newpwd)
send_email({
:recipient_name => usr[:display],
:recipient_email => usr[:email],
:subject => 'New Password',
:body => "Your ID is: #{usr[:username]} and your new password is: #{newpwd}"
})
usr.delete(:reset_token) #Strangely enough, this is .delete and not .delete!
@db[:users].update_one(
{'username' => usr[:username]},
usr,
{:upsert => false}
)
redirect '/login?msg=Password+has+been+reset'
end
get '/change-password' do
self.init_ctx
erb :changepassword
end
post '/change-password' do
self.init_ctx
if @username == nil || @username == ''
redirect '/login'
end
if @params[:newpwd] != @params[:confirmpwd]
redirect '/change-password?msg=Password+confirmation+invalid'
return
end
usr = @db[:users].find(
'username' => @username
).limit(1).first
if Digest::SHA1.hexdigest(@params[:oldpwd]) != usr[:password]
redirect '/change-password?msg=Old+password+invalid'
return
end
usr[:password] = Digest::SHA1.hexdigest(@params[:newpwd])
# send_email({
# :recipient_name => usr[:display],
# :recipient_email => usr[:email],
# :subject => 'New Password',
# :body => "Your ID is: #{usr[:username]} and your new password is: #{newpwd}"
# })
@db[:users].update_one(
{'username' => usr[:username]},
usr,
{:upsert => false}
)
redirect '/login?msg=Password+has+been+reset'
end
end
|
select country from country where country like 'A%a';
select country from country where country like '_____n';
select title from film where title ilike '%T%%T%%T%';
select * from film where title like 'C%' and length > 90 and rental_rate = 2.99;
|
<?php
namespace Dan\Shopify\Laravel\Events\Products;
use Dan\Shopify\Laravel\Models\Product;
use Illuminate\Queue\SerializesModels;
/**
* Class AbstractProductEvent
*/
abstract class AbstractProductEvent
{
use SerializesModels;
/** @var Product $product */
protected $product;
/**
* AbstractProductEvent constructor.
*
* @param Product $product
*/
public function __construct(Product $product)
{
$this->product = $product->fresh();
}
/**
* @return Product
*/
public function getProduct()
{
return $this->product;
}
}
|
package lib
import (
"encoding/json"
)
type Message struct {
Game string
Player string
CardIndex int
MoveType int
HintPlayer string
HintInfoType int
HintNumber int
HintColor string
Token string
PushToken string
Result int
GameMode int
Public bool
StartingHints int
StartingBombs int
MaxHints int
LastTurn int
IgnoreTime bool
}
type MinimalGame struct {
ID string
Name string
Players string
Mode int
}
type GamesList struct {
OpenGames []MinimalGame
PlayersGames []MinimalGame
}
func EncodeList(gl GamesList) (string, string) {
b, err := json.Marshal(gl)
if err != nil {
return "", "Error encoding list to JSON string: " + err.Error()
}
return string(b), ""
}
func EncodeGame(g Game) (string, string) {
b, err := json.Marshal(g)
if err != nil {
return "", "Error encoding game to JSON string: " + err.Error()
}
return string(b), ""
}
func DecodeMove(s string) (Message, string) {
b := []byte(s)
var m Message
err := json.Unmarshal(b, &m)
if err != nil {
return Message{}, "Error decoding move from JSON string.\nDecoding message: " + s + "\nError: " + err.Error()
}
return m, ""
}
func EncodeLogEntry(le LogEntry) (string, string) {
b, err := json.Marshal(le)
if err != nil {
return "", "Error encoding log entry to JSON string: " + err.Error()
}
return string(b), ""
}
func DecodeLogEntry(s string) (LogEntry, string) {
b := []byte(s)
var le LogEntry
err := json.Unmarshal(b, &le)
if err != nil {
return LogEntry{}, "Error decoding log entry from JSON string.\nDecoding string: " + s + "\nError: " + err.Error()
}
return le, ""
}
func EncodeStatsLog(l Logger) (string, string) {
lm := LoggerMessage{Players: l.Players, Stats: l.Stats}
b, err := json.Marshal(lm)
if err != nil {
return "", "Error encoding stats log to JSON string: " + err.Error()
}
return string(b), ""
}
|
require 'gosu'
class Sierpinski < Gosu::Window
# def drawTriangle xco, yco, depth
# @lines <<
# end
def initialize
super 500, 500
self.caption = "Sierpinski Triangle Ruby Script"
@white = Gosu::Color::WHITE
@y = 400 - (200 * Math.sqrt(3))
@tris = []
createTriangle(50, 400, 1)
end
def createTriangle x, y, depth
tri = Triangle.new(x, y, depth)
@tris << tri
unless depth >= 6
createTriangle(x, y, depth+1)
createTriangle(tri.x2, tri.y2, depth+1)
createTriangle(tri.xco+tri.len, tri.yco, depth+1)
end
end
def draw
draw_line(50, 400, @white, 450, 400, @white, 0)
draw_line(50, 400, @white, 250, @y, @white, 0)
draw_line(250, @y, @white, 450, 400, @white, 0)
@tris.each do |tri|
tri.lines.each do |line|
draw_line(line[:x], line[:y], @white, line[:x2], line[:y2], @white, 0)
end
end
end
end
class Triangle
def initialize xco, yco, depth
@xco, @yco = xco, yco
@len = 400/(2**depth)
@angle = (Math::PI/3)
@x2 = xco + @len * Math.cos(@angle)
@y2 = yco - @len * Math.sin(@angle)
@lines = []
@lines << {:x => @x2, :y => @y2, :x2 => @x2+@len, :y2 => @y2}
@lines << {:x => @x2, :y => @y2, :x2 => @xco+@len, :y2 => @yco}
@lines << {:x => @x2+@len, :y => @y2, :x2 => @xco+@len, :y2 => @yco}
@trinews = []
end
attr_reader :x2, :y2, :xco, :yco, :len, :lines
end
window = Sierpinski.new
window.show |
#[macro_use]
extern crate derivative;
#[derive(Derivative, PartialEq)]
#[derivative(Eq)]
struct Foo {
foo: u8
}
#[derive(Derivative)]
#[derivative(Eq)]
struct WithPtr<T: ?Sized> {
#[derivative(Eq(bound=""))]
foo: *const T
}
impl<T: ?Sized> PartialEq for WithPtr<T> {
fn eq(&self, other: &Self) -> bool {
self.foo == other.foo
}
}
trait SomeTrait {}
struct SomeType {
#[allow(dead_code)]
foo: u8
}
impl SomeTrait for SomeType {}
fn assert_eq<T: Eq>(_: T) {}
#[test]
fn main() {
assert!(Foo { foo: 7 } == Foo { foo: 7 });
assert!(Foo { foo: 7 } != Foo { foo: 42 });
assert_eq(Foo { foo: 7 });
let ptr1: *const SomeTrait = &SomeType { foo: 0 };
let ptr2: *const SomeTrait = &SomeType { foo: 1 };
assert!(WithPtr { foo: ptr1 } == WithPtr { foo: ptr1 });
assert!(WithPtr { foo: ptr1 } != WithPtr { foo: ptr2 });
assert_eq(WithPtr { foo: ptr1 });
}
|
using System.Drawing;
namespace Code
{
public class BinaryCharLayout
{
public string Value { get; private set; }
public Point Location { get; private set; }
public BinaryCharLayout(string binaryString, BinaryFormatting formatting)
{
Value = binaryString;
int x = -formatting.FontSize / 2;
int y = formatting.FontSize * 2;
Location = formatting.GetLocation(x, y);
}
}
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "butil/mac/scoped_mach_port.h"
#include "butil/logging.h"
namespace butil {
namespace mac {
namespace internal {
// static
void SendRightTraits::Free(mach_port_t port) {
kern_return_t kr = mach_port_deallocate(mach_task_self(), port);
LOG_IF(ERROR, kr != KERN_SUCCESS) << "Fail to call mach_port_deallocate";
}
// static
void ReceiveRightTraits::Free(mach_port_t port) {
kern_return_t kr =
mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1);
LOG_IF(ERROR, kr != KERN_SUCCESS) << "Fail to call mach_port_mod_refs";
}
// static
void PortSetTraits::Free(mach_port_t port) {
kern_return_t kr =
mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_PORT_SET, -1);
LOG_IF(ERROR, kr != KERN_SUCCESS) << "Fail to call mach_port_mod_refs";
}
} // namespace internal
} // namespace mac
} // namespace butil
|
package com.mitteloupe.testit.terminal.mapper
import com.mitteloupe.testit.terminal.model.RunParameters
class ArgsToRunParameters {
fun toParameters(args: Array<String>) =
RunParameters(
filePath = getFilePath(args),
parameterized = getParameterizedFlag(args)
)
private fun getParameterizedFlag(args: Array<String>) =
if (args.size > 1) {
args.drop(1)
.any { it == "-p" }
} else {
false
}
private fun getFilePath(args: Array<String>) =
if (args.isNotEmpty()) {
args[0].trim()
} else {
null
}
}
|
#require 'fog/dropbox'
#require 'carrierwave'
#require 'dotenv/load'
#require 'dropbox_sdk'
#CarrierWave.configure do |config|
# config.storage = :fog
#config.fog_credentials = {
# :provider => 'dropbox',
# :APP_KEY => ENV["mak75scgpyokoxp"],
# :APP_SECRET => ENV["bezjb4csocrcakw"]
# :dropbox_oauth2_access_token => 'vP__0btMfhMAAAAAAAAB_cBtwv8RJBEDskwO6MNbkrjeksdc1iqm9qgJnRPh_dsV'
#}
#config.fog_directory = "To Bee"
#config.fog_public = false
#flow = DropboxOAuth2FlowNoRedirect.new(APP_KEY, APP_SECRET)
#authorize_url = flow.start()
#end |
package cn.edu.sdu.online.isdu.ui.fragments.message
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import cn.edu.sdu.online.isdu.R
import cn.edu.sdu.online.isdu.bean.Post
import cn.edu.sdu.online.isdu.interfaces.PostViewable
import cn.edu.sdu.online.isdu.ui.activity.PostDetailActivity
import cn.edu.sdu.online.isdu.util.WeakReferences
import java.lang.ref.WeakReference
class MessageFragment : Fragment(), PostViewable {
private var dataList: MutableList<Post> = arrayListOf()
private var adapter: MyAdapter? = null
private var loadingLayout: View? = null
private var recyclerView: RecyclerView? = null
private var blankView: TextView? = null
private var isLoadComplete = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_message, container, false)
initView(view)
loadData()
initRecyclerView()
return view
}
private fun initRecyclerView() {
recyclerView!!.layoutManager = LinearLayoutManager(context)
adapter = MyAdapter(dataList)
recyclerView!!.adapter = adapter
}
private fun initView(view: View) {
loadingLayout = view.findViewById(R.id.loading_layout)
recyclerView = view.findViewById(R.id.recycler_view)
blankView = view.findViewById(R.id.blank_view)
}
fun isLoadComplete(): Boolean {
return isLoadComplete
}
fun loadData() {
onLoading()
isLoadComplete = true
publishData()
}
override fun removeItem(item: Any?) {
// dataList.remove(item as Post)
// adapter?.notifyDataSetChanged()
}
fun publishData() {
if(dataList.size!= 0){
recyclerView!!.visibility = View.VISIBLE
loadingLayout!!.visibility = View.GONE
blankView!!.visibility = View.GONE
}else{
recyclerView!!.visibility = View.GONE
loadingLayout!!.visibility = View.GONE
blankView!!.visibility = View.VISIBLE
}
if(adapter!=null){
adapter!!.notifyDataSetChanged()
}
}
fun onLoading(){
recyclerView!!.visibility = View.GONE
loadingLayout!!.visibility = View.VISIBLE
blankView!!.visibility = View.GONE
}
inner class MyAdapter(mDataList: List<Post>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private var mDataList = mDataList
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.post_item, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int = mDataList.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val post = mDataList[position]
holder.itemLayout.setOnClickListener {
WeakReferences.postViewableWeakReference = WeakReference(this@MessageFragment)
activity!!.startActivity(Intent(activity, PostDetailActivity::class.java)
.putExtra("tag", TAG))
}
// holder.title_flag.text = post.title_flag
// holder.titleView.text = post.title
// holder.user_name.text = post.userName
// holder.comments_number.text = post.comments_numbers.toString()
val timeDelta:Long = System.currentTimeMillis()-post.time
if(((timeDelta/1000/60).toInt())<1){
holder.release_time.text ="刚刚"
}else if((timeDelta/1000/60)<60){
holder.release_time.text =(((timeDelta/1000/60).toInt()).toString()+"分钟前")
}else if((timeDelta/1000/60/60)<24){
holder.release_time.text =(((timeDelta/1000/60/60).toInt()).toString() + "小时前")
}else if((timeDelta/1000/60/60/24)<30){
holder.release_time.text =(((timeDelta/1000/60/60/24).toInt()).toString() + "天前")
}else if((timeDelta/1000/60/60/24/30)<12){
holder.release_time.text =(((timeDelta/1000/60/60/24/30).toInt()).toString() + "月前")
}else {
holder.release_time.text =(((timeDelta/1000/60/60/24/365).toInt()).toString() + "年前")
}
}
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val itemLayout: FrameLayout = view.findViewById(R.id.card_view)
var title_flag: TextView = view.findViewById(R.id.title_flag)
val titleView: TextView = view.findViewById(R.id.title_view)
val contentLayout: LinearLayout = view.findViewById(R.id.content_layout)
var user_name: TextView = view.findViewById(R.id.user_name)
var comments_number: TextView = view.findViewById(R.id.comments_number)
var release_time: TextView = view.findViewById(R.id.release_time)
}
}
companion object {
const val TAG = "MessageFragment"
}
} |
import { AlertImpactType } from '../enums/AlertImpactType'
import { AlertMutedByType } from '../enums/AlertMutedByType'
import { AlertViewType } from '../enums/AlertViewType'
import { AlertCardLayout } from '../interfaces/AlertCardLayout'
import { AlertExtraProperties } from '../interfaces/AlertExtraProperties'
import { IdAlert } from '../interfaces/IdAlert'
import { IdRevision } from '../interfaces/IdRevision'
import { Transform } from '../ot/Transform'
import { ResponseKind } from '../ResponseKind'
import { BaseResponse } from '../messages/BaseResponse'
export interface AlertEvent extends BaseResponse {
id: IdAlert
action: typeof ResponseKind.ALERT
rev: IdRevision
begin: number
end: number
highlightBegin: number
highlightEnd: number
text: string
pname: string
point: string
highlightText: string
category: string
categoryHuman: string
group: string
title: string
details: string
examples: string
explanation: string
transforms: string[]
replacements: string[]
free: boolean
extra_properties: AlertExtraProperties
hidden: boolean
impact: AlertImpactType
cardLayout: AlertCardLayout
sentence_no: number
todo: string
minicardTitle: string
cost?: number
updatable?: boolean
transformJson?: Transform
labels?: string[]
subalerts?: Array<{
transformJson: Transform
highlightText: string
label: string
}>
muted?: AlertMutedByType
view?: AlertViewType
}
|
from rest_framework import serializers
from .models import Follower
class FollowerSerializer(serializers.ModelSerializer):
class Meta:
model = Follower
fields = ['user', 'followed']
read_only = ('followed_at',)
def create(self, validated_data):
"""
Creates a record that depicts one user following another user
:param validated_data:
:return:
"""
return Follower.objects.create(**validated_data)
|
DROP TABLE IF EXISTS "candata";
CREATE TABLE "candata"
(
timestamp timestamp NOT NULL,
startup timestamp NOT NULL,
terminal character(17) NOT NULL,
can_str double precision,
can_vel double precision,
can_gas double precision,
can_brake double precision,
can_seatbelt double precision,
can_water_temperature double precision,
acc_x double precision,
acc_y double precision,
acc_z double precision,
lat double precision,
lon double precision,
roll double precision,
pitch double precision,
yaw double precision,
img text,
cal_orientation_x double precision,
cal_orientation_y double precision,
cal_orientation_z double precision,
gravity_x double precision,
gravity_y double precision,
gravity_z double precision,
gyroscope_x double precision,
gyroscope_y double precision,
gyroscope_z double precision,
light double precision,
linear_acc_x double precision,
linear_acc_y double precision,
linear_acc_z double precision,
magnetic_field_x double precision,
magnetic_field_y double precision,
magnetic_field_z double precision,
orientation_x double precision,
orientation_y double precision,
orientation_z double precision,
pressure double precision,
proximity double precision,
rotation_vector_x double precision,
rotation_vector_y double precision,
rotation_vector_z double precision,
rotation_vector_c double precision,
temperature double precision,
ambient_temperature double precision,
relative_humidity double precision,
bearing double precision,
altitude double precision,
accuracy double precision,
speed double precision,
env_battery double precision,
env_temperature double precision,
PRIMARY KEY (timestamp, startup, terminal)
)
WITH (
OIDS=FALSE
);
|
---
id: 165
title: cd/dvd cover html
date: 2008-03-17T14:56:38+00:00
author: bronto saurus
layout: post
guid: http://kravca.mu/glob/index.php?entry=entry080317-075638
permalink: /2008/03/cddvd-cover-html/
categories:
- web
---
enter some text and print out;
<a href="http://somestuff.org/cdcover/CDcover.htm" target="_blank" >http://somestuff.org/cdcover/CDcover.htm</a>
(both covers will print on one A4 page)
p.s. tested with firefox 3.0b4 |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
inorderDict = {num: i for i, num in enumerate(inorder)}
def helper(start, end):
if start > end:
return None
rootVal = postorder.pop()
root = TreeNode(rootVal)
idx = inorderDict[rootVal]
root.right = helper(idx + 1, end)
root.left = helper(start, idx - 1)
return root
return helper(0, len(inorder) - 1)
|
{-# LANGUAGE OverloadedStrings #-}
module Auth
( getAccessToken
) where
import Control.Lens
import Data.Aeson.Lens (_String, key, nth)
import Network.Wreq as Wreq
import Data.Text
import Data.Text.Encoding
import Data.ByteString
import Data.ByteString.Base64 as Base64
import Data.ByteString.Char8 as Char8
getAccessToken :: IO ByteString
getAccessToken = do
let url = "https://accounts.spotify.com/api/token"
let raw_client_token = Base64.encode("ecb1f82367e64c61aedfc4c549c73809:b62e0ec0451c460daab6598afe3ffb74")
let client_token = Char8.append (Char8.pack "Basic ") (raw_client_token)
let opts = defaults
& Wreq.header "Authorization" .~ [client_token]
& Wreq.header "Content-Type" .~ ["application/x-www-form-urlencoded"]
let grantType = "client_credentials" :: ByteString
r <- Wreq.postWith opts url ["grant_type" := grantType]
let access = (r ^? responseBody . key "access_token" . _String)
return $ encodeToken $ access
encodeToken :: Maybe Text -> ByteString
encodeToken token =
Char8.append (bearer) (maybe "" encodeUtf8 token)
where
bearer =
Char8.pack "Bearer " |
#!/bin/env ruby
#
# Author: Eric Power
# Imports
require_relative 'exceptions.rb'
# handle_flags
#
# Takes in an array of flags, and runs the appropriate files.
def gen_commands config, flags
unless flags.nil?
valid_flags = Dir["#{__dir__}/../flag_handlers/*"].map{ |path|
File.basename(path).split(".rb")[0]
}.filter{ |flag|
flag.to_s[/([a-z][A-Z]*)+/] or flag.to_s == "_"
}
commands = []
flags.each{ |flag|
if valid_flags.include? flag
load "#{__dir__}/../flag_handlers/#{flag}.rb"
config, new_commands = get_commands config
Object.remove_method(:get_commands)
Object.remove_method(:get_help)
Object.remove_method(:setup_config)
new_commands.each{ |cmd|
commands << cmd
}
else
raise NoFlagHandlerError flag
end
}
end
unless config[:state][:main_script]
load "#{__dir__}/../flag_handlers/_.rb"
config, commands = get_commands config
Object.remove_method(:get_commands)
Object.remove_method(:get_help)
Object.remove_method(:setup_config)
end
[config, commands]
end
|
module Graphdb
module Model
class TxIn < ActiveNodeBase
property :txid
property :vout, type: Integer
property :script_sig_asm
property :script_sig_hex
property :coinbase
property :sequence
has_one :out, :transaction, type: :transaction, model_class: 'Graphdb::Model::Transaction'
has_one :in, :out_point, origin: :out_point, model_class: 'Graphdb::Model::TxOut'
validates :sequence, :presence => true
after_create :add_out_point_rel
def self.create_from_hash(hash)
tx_in = new
tx_in.txid = hash['txid']
tx_in.vout = hash['vout']
if hash['scriptSig']
tx_in.script_sig_asm = hash['scriptSig']['asm']
tx_in.script_sig_hex = hash['scriptSig']['hex']
end
tx_in.coinbase = hash['coinbase']
tx_in.sequence = hash['sequence']
tx_in.save!
tx_in
end
private
def add_out_point_rel
return if self.txid.nil? && self.vout.nil?
tx_out = Graphdb::Model::TxOut.find_by_outpoint(self.txid, self.vout)
if tx_out
self.out_point = tx_out
save!
end
end
end
end
end |
<?php
namespace ZoiloMora\ElasticAPM\Tests\Events\Common;
use ZoiloMora\ElasticAPM\Tests\Utils\TestCase;
use ZoiloMora\ElasticAPM\Events\Common\Process;
class ProcessTest extends TestCase
{
/**
* @test
*/
public function given_no_data_when_instantiating_then_return_object()
{
$object = new Process(1);
self::assertInstanceOf('ZoiloMora\ElasticAPM\Events\Common\Process', $object);
}
/**
* @test
*/
public function given_no_data_when_try_to_discover_then_return_object()
{
$object = Process::discover();
self::assertInstanceOf('ZoiloMora\ElasticAPM\Events\Common\Process', $object);
}
/**
* @test
*/
public function given_invalid_argv_data_when_try_to_discover_then_throw_exception()
{
self::setExpectedException('InvalidArgumentException', 'All elements must be of string type.');
new Process(1, null, null, [1]);
}
/**
* @test
*/
public function given_data_when_instantiating_then_can_get_properties()
{
$pid = 1;
$ppid = 2;
$title = 'test';
$argv = [];
$object = new Process(
$pid,
$ppid,
$title,
$argv
);
self::assertSame($pid, $object->pid());
self::assertSame($ppid, $object->ppid());
self::assertSame($title, $object->title());
self::assertSame($argv, $object->argv());
}
/**
* @test
*/
public function given_a_process_when_serialize_then_right_serialization()
{
$pid = 1;
$ppid = 2;
$title = 'test';
$argv = [];
$object = new Process(
$pid,
$ppid,
$title,
$argv
);
$expected = json_encode([
'pid' => $pid,
'ppid' => $ppid,
'title' => $title,
'argv' => $argv,
]);
self::assertSame($expected, json_encode($object));
}
}
|
SUBROUTINE CGBTRF_F95( A, K, M, IPIV, RCOND, NORM, INFO )
!
! -- LAPACK95 interface driver routine (version 3.0) --
! UNI-C, Denmark; Univ. of Tennessee, USA; NAG Ltd., UK
! September, 2000
!
! .. USE STATEMENTS ..
USE LA_PRECISION, ONLY: WP => SP
USE LA_AUXMOD, ONLY: LSAME, ERINFO
USE F77_LAPACK, ONLY: GBTRF_F77 => LA_GBTRF, LANGB_F77 => LA_LANGB, &
GBCON_F77 => LA_GBCON
! .. IMPLICIT STATEMENT ..
IMPLICIT NONE
! .. SCALAR ARGUMENTS ..
CHARACTER(LEN=1), INTENT(IN), OPTIONAL :: NORM
INTEGER, INTENT(IN), OPTIONAL :: K, M
INTEGER, INTENT(OUT), OPTIONAL :: INFO
REAL(WP), INTENT( OUT ), OPTIONAL :: RCOND
! .. ARRAY ARGUMENTS ..
INTEGER, INTENT( OUT ), OPTIONAL, TARGET :: IPIV( : )
COMPLEX(WP), INTENT( INOUT ) :: A( :, : )
! .. PARAMETERS ..
CHARACTER(LEN=8), PARAMETER :: SRNAME = 'LA_GBTRF'
! .. LOCAL SCALARS ..
CHARACTER(LEN=1) :: LNORM
INTEGER :: LINFO, N, LD, ISTAT, ISTAT1, MINMN, LWORK, SIPIV, &
LK, KU, LM
REAL(WP) :: LANORM
! .. LOCAL POINTERS ..
INTEGER, POINTER :: LIPIV(:)
REAL(WP), POINTER :: RWORK(:)
COMPLEX(WP), POINTER :: WORK(:)
! .. INTRINSIC FUNCTIONS ..
INTRINSIC PRESENT, MIN, SIZE, TINY
! .. EXECUTABLE STATEMENTS ..
LD = SIZE(A,1); N = SIZE(A,2); LINFO = 0; ISTAT = 0
IF( PRESENT(K) ) THEN; LK = K; ELSE; LK = (LD-1)/3; ENDIF
IF( PRESENT(M) ) THEN; LM = M; ELSE; LM = N; ENDIF; MINMN = MIN(LM,N)
IF( PRESENT(IPIV) )THEN; SIPIV = SIZE(IPIV); ELSE; SIPIV = MINMN; ENDIF
IF ( PRESENT(NORM) ) THEN; LNORM = NORM; ELSE; LNORM = '1'; END IF
! .. TEST THE ARGUMENTS
IF( N < 0 .OR. LD < 0 )THEN; LINFO = -1
ELSE IF( LD - 2*LK -1 < 0 .OR. LK < 0 ) THEN; LINFO = -2
ELSE IF( LM < 0 )THEN; LINFO = -3
ELSE IF( SIPIV /= MINMN )THEN; LINFO = -4
ELSE IF( PRESENT(RCOND) .AND. M /= N )THEN; LINFO = -5
ELSE IF( ( .NOT.PRESENT(RCOND) .AND. PRESENT(NORM) ) .OR. &
( .NOT.LSAME(LNORM,'I') .AND. .NOT.LSAME(LNORM,'O') &
.AND. LNORM /= '1' ) ) THEN; LINFO = -6
ELSE IF( M > 0 .AND. N > 0 ) THEN
IF( PRESENT(RCOND) .AND. M == N ) THEN
! .. COMPUTE THE NORM OF THE MATRIX A
IF( LNORM == 'I' ) THEN; LWORK = MINMN; ELSE; LWORK = 1; END IF
ALLOCATE( RWORK(LWORK), STAT=ISTAT )
IF( ISTAT == 0 )THEN
LANORM = LANGB_F77( LNORM, MINMN, LK, KU, A, LD, RWORK )
ELSE
LINFO = -100
END IF
DEALLOCATE(RWORK, STAT=ISTAT1)
END IF
IF( LINFO == 0 ) THEN
IF( PRESENT(IPIV) )THEN; LIPIV => IPIV
ELSE; ALLOCATE( LIPIV( MINMN ), STAT=ISTAT ); ENDIF
IF( ISTAT /= 0 )LINFO = -100
END IF
IF( LINFO == 0 ) THEN
! .. COMPUTE THE LU FACTORS OF THE MATRIX A
CALL GBTRF_F77( LM, N, LK, KU, A, LD, LIPIV, LINFO )
IF( .NOT. PRESENT(IPIV) )DEALLOCATE( LIPIV, STAT=ISTAT )
IF( PRESENT(RCOND) ) THEN
! .. COMPUTE THE RECIPROCAL OF THE CONDITION NUMBER OF A
IF( LANORM <= TINY(1.0_WP) .OR. M /= N .OR. LINFO /= 0 ) THEN
RCOND = 0.0_WP
ELSE
ALLOCATE(WORK(2*MINMN), RWORK(MINMN), STAT=ISTAT)
IF( ISTAT == 0 )THEN
CALL GBCON_F77( LNORM, MINMN, LK, KU, A, LD, LIPIV, &
LANORM, RCOND, WORK, RWORK, LINFO )
ELSE
LINFO = -100
END IF
DEALLOCATE( WORK, RWORK, STAT=ISTAT1 )
END IF
END IF
END IF
ELSE IF( PRESENT(RCOND) ) THEN
IF( M == N )THEN
RCOND = 1.0_WP
ELSE
RCOND = 0.0_WP
END IF
END IF
CALL ERINFO(LINFO,SRNAME,INFO,ISTAT)
END SUBROUTINE CGBTRF_F95
|
// Code generated by "stringer -type=FeedCategory"; DO NOT EDIT.
package igdb
import "strconv"
const (
_FeedCategory_name_0 = "FeedPulseArticleFeedComingSoonFeedNewTrailer"
_FeedCategory_name_1 = "FeedUserContributedItemFeedUserContributionsItemFeedPageContributedItem"
)
var (
_FeedCategory_index_0 = [...]uint8{0, 16, 30, 44}
_FeedCategory_index_1 = [...]uint8{0, 23, 48, 71}
)
func (i FeedCategory) String() string {
switch {
case 1 <= i && i <= 3:
i -= 1
return _FeedCategory_name_0[_FeedCategory_index_0[i]:_FeedCategory_index_0[i+1]]
case 5 <= i && i <= 7:
i -= 5
return _FeedCategory_name_1[_FeedCategory_index_1[i]:_FeedCategory_index_1[i+1]]
default:
return "FeedCategory(" + strconv.FormatInt(int64(i), 10) + ")"
}
}
|
/**
* Check if two objects are equal w/ deep comparison
* @param {Object} a
* @param {Object} b
* @returns {boolean}
*/
function isEqualObject (a: Object, b: Object): Boolean {
if (Array.isArray(a) && Array.isArray(b)) return isEqualArray(a, b)
if (typeof a !== 'object' && typeof b !== 'object') return Object.is(a, b)
if (checkNullAndUndefined(a, b)) return false;
if (checkBothNullOrUndefined(a, b)) return true;
var aProps = Object.getOwnPropertyNames(a)
var bProps = Object.getOwnPropertyNames(b)
if (aProps.length !== bProps.length) return false
var i = 0
while (i < aProps.length) {
var propName = aProps[i]
if (typeof a[propName] == 'object' && typeof b[propName] == 'object') {
if (Array.isArray(a[propName]) && Array.isArray(b[propName])) {
if (!isEqualArray(a[propName], b[propName])) return false
} else if (!isEqualObject(a[propName], b[propName])) return false
} else if (
bProps.indexOf(propName) == -1 ||
!Object.is(a[propName], b[propName])
) {
return false
}
i++
}
return true
}
function checkNullAndUndefined(a, b) {
if (
a === null && b !== null ||
a !== null && b === null ||
a === undefined && b !== undefined ||
a !== undefined && b === undefined
) {
return true
}
return false
}
function checkBothNullOrUndefined(a, b) {
if (
a === null && b === null ||
a === undefined && b === undefined
) {
return true
}
return false
}
/**
* Check if two arrays are equal w/ deep comparison
* @param {Array.<*>} a
* @param {Array.<*>} b
* @returns {boolean}
*/
function isEqualArray (a: any[], b: any[]): Boolean {
if (checkNullAndUndefined(a, b)) return false
if (checkBothNullOrUndefined(a, b)) return true
if (a.length !== b.length) {
return false
}
var i = 0
while (i < a.length) {
if (typeof a[i] !== 'object' && b.indexOf(a[i]) === -1) return false
else if (
typeof a[i] === 'object' &&
!Array.isArray(a[i]) &&
!isEqualObject(a[i], b[i])
)
return false
else if (
Array.isArray(a[i]) &&
Array.isArray(b[i]) &&
!isEqualArray(a[i], b[i])
)
return false
i++
}
return true
}
export { isEqualObject, isEqualArray }
|
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::any('api',function(){
return ['version'=>0.1,'author'=>'James Kang'];
});
Route::any('api/signup',function(){
$user=new App\User;
return $user->signup();
});
Route::any('api/login',function(){
$user=new App\User;
return $user->login();
});
Route::any('api/logout',function(){
$user=new App\User;
return $user->logout();
});
Route::any('test',function(){
$user=new App\User;
dd($user->is_logged_in());
});
|
#require File.expand_path('../../../../spec_helper', __FILE__)
#require File.expand_path('../shared/random_bytes.rb', __FILE__)
require File.dirname(File.join(__rhoGetCurrentDir(), __FILE__)) + '/shared/random_bytes'
describe "OpenSSL::Random#random_bytes" do
it_behaves_like :openssl_random_bytes, :random_bytes
end
|
using System;
using System.Windows.Forms;
namespace TeknikServis
{
public partial class pnlSekreter : UserControl
{
public frmSekreter _frmSekreter;
public pnlYoneticiAsistanAnaMenu _pnlYoneticiAsistanAnaMenu;
public pnlSekreter()
{
InitializeComponent();
}
private void pnlSekreter_Load(object sender, EventArgs e)
{
pnlSekreterTemp.Controls.Clear();
pnlServistekiArizaliUrunler sa = new pnlServistekiArizaliUrunler();
sa._s = this;
pnlSekreterTemp.Controls.Add(sa);
}
//yeni kayıt
private void btn_auKayit_Click(object sender, EventArgs e)
{
pnlSekreterTemp.Controls.Clear();
pnlArizaKayit ak = new pnlArizaKayit();
ak._s = this;
pnlSekreterTemp.Controls.Add(ak);
}
//------------------
//servistekiler
private void btn_servistekiler_Click(object sender, EventArgs e)
{
pnlSekreterTemp.Controls.Clear();
pnlServistekiArizaliUrunler sa = new pnlServistekiArizaliUrunler();
sa._s = this;
pnlSekreterTemp.Controls.Add(sa);
}
//eski kayıtlar
private void btn_eskiKayitlar_Click(object sender, EventArgs e)
{
pnlSekreterTemp.Controls.Clear();
pnlSekreterTemp.Controls.Add(new pnlServisEski());
}
}
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
author: Rafael Picanço.
Import publications (zotero api) as csljson.
Hack to save them as html and translated by available locales (citeproc).
Do not recommended for production. Need better handling of unicode strings.
citeproc:
- UserWarning: The following arguments for Reference are unsupported: journalAbbreviation
- apa.csl is returns duplicates dots e.g.: '.. '
"""
from __future__ import (absolute_import, division, print_function,unicode_literals)
import os
import json
from libZotero import zotero # https://github.com/fcheslack/libZotero
import xml.etree.ElementTree as ET #read only operations on private lib, no security concerns
#from citeproc.py2compat import *
from citeproc import CitationStylesStyle, CitationStylesBibliography
from citeproc import Citation, CitationItem
from citeproc import formatter
from citeproc.source.json import CiteProcJSON
def warn(citation_item):
return "{}' not found.".format(citation_item.key)
def apa_html_utf8(json_data, alocale='en-US'):
# CiteProcJSON receives a [{}] not a {}
bib_source = CiteProcJSON([json_data])
apa = CitationStylesStyle('apa', locale=alocale, validate=False)
bibliography = CitationStylesBibliography(apa, bib_source, formatter.html)
citation = Citation([CitationItem(json_data['id'])])
bibliography.register(citation)
# handle python weird string type
return str(''.join(bibliography.bibliography()[0]).encode('utf-8'))
# weird chars hack
latin_chars = [('¡','¡'),('¢','¢'),('£','£'),('¤','¤'),
('¥','¥'),('¦','¦'),('§','§'),('¨','¨'),('©','©'),
('ª','ª'),('«','«'),('¬','¬'),('®','®'),('¯','¯'),
('°','°'),('±','±'),('²','²'),('³','³'),('´','´'),
('µ','µ'),('¶','¶'),('·','·'),('¸','¸'),('¹','¹'),
('º','º'),('»','»'),('¼','¼'),('½','½'),('¾','¾'),
('¿','¿'),('À','À'),('Á','Á'),('Â','Â'),('Ã','Ã'),
('Ä','Ä'),('Å','Å'),('Æ','Æ'),('Ç','Ç'),('È','È'),
('É','É'),('Ê','Ê'),('Ë','Ë'),('Ì','Ì'),('Í','Í'),
('Î','Î'),('Ï','Ï'),('Ð','Ð'),('Ñ','Ñ'),('Ò','Ò'),
('Ó','Ó'),('Ô','Ô'),('Õ','Õ'),('Ö','Ö'),('×','×'),
('Ø','Ø'),('Ù','Ù'),('Ú','Ú'),('Û','Û'),('Ü','Ü'),
('Ý','Ý'),('Þ','Þ'),('ß','ß'),('à','à'),('á','á'),
('â','â'),('ã','ã'),('ä','ä'),('å','å'),('æ','æ'),
('ç','ç'),('è','è'),('é','é'),('ê','ê'),('ë','ë'),
('ì','ì'),('í','í'),('î','î'),('ï','ï'),('ð','ð'),
('ñ','ñ'),('ò','ò'),('ó','ó'),('ô','ô'),('õ','õ'),
('ö','ö'),('ø','ø'),('ù','ù'),('ú','ú'),('û','û'),
('ü','ü'),('ý','ý'),('þ','þ'),('ÿ','ÿ'),('–','–'),
('—', '—'),('…', '…'),('“','“'),('”','”')]
publicati_path = os.path.join(os.sep, os.path.dirname(os.getcwd()), '_data', 'publications')
csljson_path = os.path.join(os.sep, os.getcwd(), 'csljson')
# credential
with open('.credential.json') as credential:
c = json.loads(credential.read())
# libZotero/zotero config
library = zotero.Library(c['libraryType'], c['libraryID'], c['librarySlug'], c['apiKey'])
# fetch some items
items = library.fetchItems({'collectionKey':c['collectionID'],'content':'json','sort':'date'})
for item in items:
yamlname = os.path.join(os.sep, publicati_path, item.get('date').replace('-', ''))
jsonname = os.path.join(os.sep, csljson_path, item.get('date').replace('-', ''))
# csljson must be fetched individually it is parsed as xml
itemFetched = library.fetchItem(item.itemKey,{'content':'csljson' })
# load json dictionary from xml
xmle = ET.fromstring(itemFetched.content.encode('utf-8'))
csljson = xmle.find('{https://www.w3.org/2005/Atom}content').text
for cs in latin_chars:
csljson = csljson.replace(cs[1],cs[0])
json_dict = json.loads(csljson)
# add 'date-parts' from 'raw'
y, _, _ = json_dict['issued']['raw'].split('-')
#json_dict['issued']['date-parts'] = [[y, m, d]]
json_dict['issued']['date-parts'] = [[y]]
# debug
# print(json_dict['id'])
# print('#######')
# save csljson
with open(jsonname+'.json', 'w+') as f:
json.dump(json_dict, f, indent=4, sort_keys=True, ensure_ascii=False)
# translate and save a reference as html into our custom yml
with open(yamlname+'.yml', 'w+') as f:
f.write('pt-BR:\n '.encode('utf-8'))
f.write('html: >\n '.encode('utf-8'))
f.write(apa_html_utf8(json_dict, alocale='pt-BR'))
f.write('\n\nen:\n '.encode('utf-8'))
f.write('html: >\n '.encode('utf-8'))
f.write(apa_html_utf8(json_dict))
if 'DOI' in json_dict:
f.write('\n\ndoi: >\n ')
f.write(json_dict['DOI'])
if 'URL' in json_dict:
f.write('\n\nurl: >\n ')
f.write(json_dict['URL'])
if 'type' in json_dict:
f.write('\n\ntype: ')
f.write(json_dict['type']) |
mongo = new Mongo("localhost");
expenseTrackerDB = mongo.getDB('expenseTracker');
expenseTrackerDB.createCollection("categories");
expenseTrackerDB.createCollection("categoryMappings");
expenseTrackerDB.createCollection("expenses");
|
<?php
/**
* @author Wizacha DevTeam <[email protected]>
* @author Karl DeBisschop <[email protected]>
* @copyright Copyright (c) Wizacha
* @license MIT
*/
declare(strict_types=1);
namespace Tests\Transformers;
use Tests\TestCase;
use Wizaplace\Etl\Row;
use Wizaplace\Etl\Transformers\FormatUnixTime;
class FormatUnixTimeTest extends TestCase
{
/**
* Row array to be transformed in testing.
*
* @var Row[]
*/
protected array $data;
protected function setUp(): void
{
parent::setUp();
$this->data = [
new Row(['id' => '1', 'timestamp' => '1', 'unixtime' => '1']),
new Row(['id' => '2', 'timestamp' => '2', 'unixtime' => '2']),
new Row(['id' => '3', 'timestamp' => '1606613796', 'unixtime' => '1606613796']),
];
}
/** @test */
public function setUtc(): void
{
$expected = [
new Row(['id' => '1', 'timestamp' => '19700101', 'unixtime' => '1']),
new Row(['id' => '2', 'timestamp' => '19700101', 'unixtime' => '2']),
new Row(['id' => '3', 'timestamp' => '20201129', 'unixtime' => '1606613796']),
];
$transformer = new FormatUnixTime();
$transformer->options(
[
$transformer::COLUMNS => ['timestamp'],
$transformer::TIMEZONE => 'UTC',
]
);
$this->execute($transformer, $this->data);
static::assertEquals($expected, $this->data);
}
/** @test */
public function setAmericaNewYork(): void
{
$expected = [
new Row(['id' => '1', 'timestamp' => '19691231', 'unixtime' => '1']),
new Row(['id' => '2', 'timestamp' => '19691231', 'unixtime' => '2']),
new Row(['id' => '3', 'timestamp' => '20201128', 'unixtime' => '1606613796']),
];
$transformer = new FormatUnixTime();
$transformer->options(
[
$transformer::COLUMNS => ['timestamp'],
$transformer::TIMEZONE => 'America/New_York',
]
);
$this->execute($transformer, $this->data);
static::assertEquals($expected, $this->data);
}
/** @test */
public function changeFormat(): void
{
$expected = [
new Row(['id' => '1', 'timestamp' => '1970-01-01 00:00:01', 'unixtime' => '1']),
new Row(['id' => '2', 'timestamp' => '1970-01-01 00:00:02', 'unixtime' => '2']),
new Row(['id' => '3', 'timestamp' => '2020-11-29 01:36:36', 'unixtime' => '1606613796']),
];
$transformer = new FormatUnixTime();
$transformer->options(
[
$transformer::COLUMNS => ['timestamp'],
$transformer::TIMEZONE => 'UTC',
$transformer::FORMAT => 'Y-m-d H:i:s',
]
);
$this->execute($transformer, $this->data);
static::assertEquals($expected, $this->data);
}
/** @test */
public function selectMultipleColumns(): void
{
$expected = [
new Row(['id' => '1', 'timestamp' => '19700101', 'unixtime' => '19700101']),
new Row(['id' => '2', 'timestamp' => '19700101', 'unixtime' => '19700101']),
new Row(['id' => '3', 'timestamp' => '20201129', 'unixtime' => '20201129']),
];
$transformer = new FormatUnixTime();
$transformer->options(
[
$transformer::COLUMNS => ['timestamp', 'unixtime'],
$transformer::TIMEZONE => 'UTC',
]
);
$this->execute($transformer, $this->data);
static::assertEquals($expected, $this->data);
}
/** @test */
public function systemDefaultTimezone(): void
{
$expected = [
new Row(['id' => '1', 'timestamp' => date_create()->setTimestamp(1)->format('Ymd'), 'unixtime' => '1']),
new Row(['id' => '2', 'timestamp' => date_create()->setTimestamp(2)->format('Ymd'), 'unixtime' => '2']),
new Row([
'id' => '3',
'timestamp' => date_create()->setTimestamp(1606613796)->format('Ymd'),
'unixtime' => '1606613796',
]),
];
$transformer = new FormatUnixTime();
$transformer->options([$transformer::COLUMNS => ['timestamp']]);
$this->execute($transformer, $this->data);
static::assertEquals($expected, $this->data);
}
}
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/cpp/private/isolated_file_system_private.h"
#include "ppapi/cpp/module_impl.h"
namespace pp {
namespace {
template <> const char* interface_name<PPB_IsolatedFileSystem_Private_0_2>() {
return PPB_ISOLATEDFILESYSTEM_PRIVATE_INTERFACE_0_2;
}
} // namespace
IsolatedFileSystemPrivate::IsolatedFileSystemPrivate()
: instance_(0), type_(PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_INVALID) {
}
IsolatedFileSystemPrivate::IsolatedFileSystemPrivate(
const InstanceHandle& instance,
PP_IsolatedFileSystemType_Private type)
: instance_(instance.pp_instance()), type_(type) {
}
IsolatedFileSystemPrivate::~IsolatedFileSystemPrivate() {
}
int32_t IsolatedFileSystemPrivate::Open(
const CompletionCallbackWithOutput<pp::FileSystem>& cc) {
if (!has_interface<PPB_IsolatedFileSystem_Private_0_2>())
return cc.MayForce(PP_ERROR_NOINTERFACE);
return get_interface<PPB_IsolatedFileSystem_Private_0_2>()->
Open(instance_, type_, cc.output(), cc.pp_completion_callback());
}
} // namespace pp
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FluentResult.Tests
{
[TestClass]
public class MapResultTests
{
[TestMethod]
public void MapMultiple()
{
var result = Result.Create(2)
.Map(t => t * 2) // 4
.Map(t => t + 2) // 6
.Validate(t => t == 6, ResultComplete.OperationFailed, "Test")
.Map(t => (t - 1).ToString());
Assert.AreEqual("5", result.Data);
}
[TestMethod]
public async Task MapAsync()
{
var result = await Result
.Create(2)
.MapAsync(t => Task.FromResult(t + 3)) // 5
.MapAsync(t => t + 1);
Assert.AreEqual(6, result.Data);
}
[TestMethod]
public void MapList()
{
var models = new[] { 3, 5 };
var result = Result
.Create(models)
.MapList(t => t * 2);
Assert.AreEqual(6, result.Data[0]);
Assert.AreEqual(10, result.Data[1]);
}
[TestMethod]
public void MapListEnumerable()
{
var models = Enumerable.Range(1, 3);
var result = Result
.Create(models)
.MapList(t => t * 2);
Assert.AreEqual(2, result.Data[0]);
Assert.AreEqual(4, result.Data[1]);
Assert.AreEqual(6, result.Data[2]);
}
[TestMethod]
public async Task MapAsyncAsync()
{
var result = await Result
.Create(5)
.MapAsync(t => Task.FromResult(t))
.MapAsync(async t => await Task.Run(() => t * 3));
Assert.AreEqual(15, result.Data);
}
[TestMethod]
public void Switch()
{
Result<int> secondFn(int model) =>
Result.Create(model).Map(it => it + 10);
var result = Result
.Create(3)
.Map(it => it * 2)
.Switch(secondFn);
Assert.AreEqual(16, result.Data);
}
[TestMethod]
public async Task SwitchAsync()
{
Task<Result<int>> secondFnAsync(int model) =>
Result.Create(model).MapAsync(it => Task.FromResult(it + 12));
var result = await Result
.Create(3)
.Map(it => it * 2)
.SwitchAsync(secondFnAsync);
Assert.AreEqual(18, result.Data);
}
[TestMethod]
public async Task SwitchAsyncToAsync()
{
Task<Result<int>> secondFnAsync(int model) =>
Result.Create(model).MapAsync(it => Task.FromResult(it + 15));
var result = await Result
.Create(3)
.MapAsync(it => Task.FromResult(it * 2))
.SwitchAsync(secondFnAsync);
Assert.AreEqual(21, result.Data);
}
[TestMethod]
public async Task CatchAsyncShouldCatchOnError()
{
var result = await Result
.Create(1)
.MapAsync(_ => Task.FromException<int>(new InvalidOperationException()))
.CatchAsync(ex => Result.Create(ex is InvalidOperationException ? 2 : 3))
.ValidateAsync(value => value == 2, ResultComplete.OperationFailed, string.Empty);
Assert.IsTrue(result.IsSuccessfulStatus());
Assert.AreEqual(2, result.Data);
}
[TestMethod]
public async Task CatchAsyncShouldBeSkippedWhenNoError()
{
var result = await Result
.Create(1)
.MapAsync(_ => Task.FromResult(5))
.CatchAsync(ex => Result.Create(ex is InvalidOperationException ? 2 : 3));
Assert.AreEqual(5, result.Data);
}
}
}
|
import 'package:meta/meta.dart';
import 'package:equatable/equatable.dart';
abstract class LoginState extends Equatable {
LoginState([List props = const []]) : super(props);
}
class LoginInitialState extends LoginState {
@override
String toString() => 'LoginInitial';
}
class LoginRedirectUrlGeneratedState extends LoginState {
final String url;
LoginRedirectUrlGeneratedState({@required this.url}) : super([url]);
@override
String toString() => 'LoginRedirectUriGeneratedState';
}
class LoginSucessfullyState extends LoginState {
@override
String toString() => 'LoginSuccessfullyState';
}
class LoginLoadingState extends LoginState {
@override
String toString() => 'LoginLoadingState';
} |
import React, { useState } from "react"
import { Box, Clickable, Flex, Text } from "@artsy/palette"
import { SectionContainer } from "./SectionContainer"
export const FAQ: React.FC = () => {
return (
<SectionContainer>
<Text width="100%" textAlign="left" mb={4} variant="largeTitle">
Frequently Asked Questions Read more about selling your artwork
</Text>
<Box>
<ToggleButton label="How does selling on Artsy work?">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
<ToggleButton label="What happens once I submit a work to Artsy Consignments?">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
<ToggleButton label="Where can I see my work on Artsy?">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
<ToggleButton label="Which auction houses and galleries are in Artsy’s consignment partner network?">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
<ToggleButton label="I’m an artist. Can I submit my own work to consign?">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
<ToggleButton label="How can I edit my submission?">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
<ToggleButton label="I have another question">
<TextItem>
Artsy helps you find the best sales solution for works in your
collection. We review the works you’re interested in selling,
determine the strength of the secondary market demand, and suggest
an appropriate sales strategy. <br />
<br />
This can involve matching you with the right seller (e.g., an
auction house or a gallery), selling qualified works via Artsy’s
online marketplace, or selling the work privately through our
network of trusted partners and collectors. <br />
<br />
This service is free, and the nominal, pre-agreed seller’s
commission is due only when your work sells. Artsy specialists guide
you along the way and help you choose the right sales strategy. To
get started, submit works you’re interested in selling here.
</TextItem>
</ToggleButton>
</Box>
</SectionContainer>
)
}
const ToggleButton: React.FC<{
expanded?: boolean
label: string
}> = ({ expanded, label, children }) => {
const [isExpanded, toggleExpand] = useState(expanded)
return (
<Box mb={2}>
<Clickable onClick={() => toggleExpand(!isExpanded)}>
<Flex alignContent="center" alignItems="baseline">
{isExpanded ? (
<PlusMinusIcon>-</PlusMinusIcon>
) : (
<PlusMinusIcon>+</PlusMinusIcon>
)}
<Text variant="subtitle" textAlign="left">
{label}
</Text>
</Flex>
</Clickable>
{isExpanded && (
<Box mt={2} ml="24px">
{children}
</Box>
)}
</Box>
)
}
const PlusMinusIcon: React.FC = ({ children }) => (
<Flex
width={13}
mr={1}
justifyContent="center"
alignContent="center"
textAlign="center"
>
<Text
variant="largeTitle"
fontWeight="medium"
color="black60"
position="relative"
top="2px"
>
{children}
</Text>
</Flex>
)
const TextItem: React.FC = ({ children }) => {
return (
<Text variant="text" color="black60" maxWidth={650}>
{children}
</Text>
)
}
|
#ifndef CONFIG_H
#define CONFIG_H
#include <stdint.h>
#define BASE_VER 200
#ifdef PRO
#define PRO_F 0x010000
#else
#define PRO_F 0
#endif
#ifdef DEMO
#define DEMO_F 0x080000
#else
#define DEMO_F 0
#endif
#ifdef EDU
#define EDU_F 0x200000
#else
#define EDU_F 0
#endif
#define VERSION (BASE_VER|PRO_F|DEMO_F|EDU_F)
#if INTPTR_MAX == INT64_MAX
#define BB64
typedef long bb_int_t;
typedef double bb_float_t;
#else
#define BB32
typedef int bb_int_t;
typedef float bb_float_t;
#endif
typedef bb_int_t bb_ptr_t;
#endif
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Parametrage extends Model
{
use HasFactory;
protected $fillable = [
'soldeSms',
'tauxPrelevement'
];
public static function getInstance(): Parametrage
{
$parametrages = Parametrage::all();
if (count($parametrages) > 0) {
return $parametrages[0];
}
$parametrage = new Parametrage(['soldeSms' => 0, 'tauxPrelevement' => 3]);
if (!$parametrage->save()) {
notify()->error("Une erreur est survenue lors de l'enregistrement du paramétre !!!");
}
return $parametrage;
}
public function getAdminsAttribute() {
return User::where('type','admin')->get();
}
}
|
package maserati.logging
import org.slf4j.LoggerFactory
class Logger(classType: Class[_]) {
private val logger = LoggerFactory.getLogger(classType)
def trace(format: String, args: Any*){
if (logger.isTraceEnabled()) {
val array = args.map(_.asInstanceOf[AnyRef]).toArray
logger.trace(format, array:_*)
}
}
def info(format: String, args: Any*){
if(logger.isInfoEnabled) {
val array = args.map(_.asInstanceOf[AnyRef]).toArray
logger.info(format, array:_*)
}
}
def debug(format: String, args: Any*){
if(logger.isDebugEnabled) {
val array = args.map(_.asInstanceOf[AnyRef]).toArray
logger.debug(format, array:_*)
}
}
def warn(format: String, args: Any*){
if(logger.isWarnEnabled) {
val array = args.map(_.asInstanceOf[AnyRef]).toArray
logger.warn(format, array:_*)
}
}
def error(format: String, args: Any*){
if(logger.isErrorEnabled) {
val array = args.map(_.asInstanceOf[AnyRef]).toArray
logger.error(format, array:_*)
}
}
}
|
import React, { useRef, forwardRef,useImperativeHandle, useEffect, useCallback } from "react";
import * as ROS3D from "ros3d";
// import * as ROSLIB from "roslib";
import { useDispatch } from "react-redux";
export const Viewer3D = forwardRef((props, ref) => {
const dispatch = useDispatch();
const viewRef = useRef(null);
const WindowSize = useCallback(() => {
if (viewRef.current !== null) {
viewRef.current.resize(window.innerWidth, window.innerHeight);
}
}, [viewRef]);
useEffect(() => {
if (viewRef.current === null ) {
// Create the main viewRef.current.
console.log("Create default viewRef.current.");
viewRef.current = new ROS3D.Viewer({
divID: "ros-viewers",
width: window.innerWidth,
height: window.innerHeight,
antialias: true,
});
}
window.addEventListener("resize", WindowSize);
WindowSize();
return () => {
window.removeEventListener("resize", WindowSize);
};
}, [dispatch, WindowSize]);
useImperativeHandle(ref, () => ({
getAlert() {
alert("getAlert from Viewer");
},
getCurrent(){
return viewRef.current;
},
getScene()
{
return viewRef.current.scene;
}
}));
return <div id="ros-viewers"></div>;
});
|
using System;
using System.Collections.Concurrent;
namespace Convey.MessageBrokers.RabbitMQ.Conventions;
public class ConventionsProvider : IConventionsProvider
{
private readonly ConcurrentDictionary<Type, IConventions> _conventions =
new();
private readonly IConventionsRegistry _registry;
private readonly IConventionsBuilder _builder;
public ConventionsProvider(IConventionsRegistry registry, IConventionsBuilder builder)
{
_registry = registry;
_builder = builder;
}
public IConventions Get<T>() => Get(typeof(T));
public IConventions Get(Type type)
{
if (_conventions.TryGetValue(type, out var conventions))
{
return conventions;
}
conventions = _registry.Get(type) ?? new MessageConventions(type, _builder.GetRoutingKey(type),
_builder.GetExchange(type), _builder.GetQueue(type));
_conventions.TryAdd(type, conventions);
return conventions;
}
} |
Sample configuration files for:
SystemD: nodebased.service
Upstart: nodebased.conf
OpenRC: nodebased.openrc
nodebased.openrcconf
CentOS: nodebased.init
have been made available to assist packagers in creating node packages here.
See doc/init.md for more information.
|
export interface Config {
apiUrl: string,
}
export const APP_CONFIG:Config = {
apiUrl: `http://api.astro.2muchcoffee.com/v1`,
}; |
package com.netaporter.uri
import com.netaporter.uri.encoding.{ChainedUriEncoder, UriEncoder}
import com.netaporter.uri.config.UriConfig
/**
* Date: 23/08/2013
* Time: 09:10
*/
package object dsl {
import scala.language.implicitConversions
implicit def uriToUriOps(uri: Uri) = new UriDsl(uri)
implicit def encoderToChainedEncoder(enc: UriEncoder) = ChainedUriEncoder(enc :: Nil)
implicit def stringToUri(s: String)(implicit c: UriConfig = UriConfig.default) = Uri.parse(s)(c)
implicit def stringToUriDsl(s: String)(implicit c: UriConfig = UriConfig.default) = new UriDsl(stringToUri(s)(c))
implicit def queryParamToUriDsl(kv: (String, Any))(implicit c: UriConfig = UriConfig.default) = new UriDsl(Uri.empty.addParam(kv._1, kv._2))
implicit def uriToString(uri: Uri)(implicit c: UriConfig = UriConfig.default): String = uri.toString(c)
}
|
# frozen_string_literal: true
module Repository
module Remote
##
# Destroy local repository
#
class Destroy < RepoCommand
def execute
return unless OpenWebslides.config.github.enabled
# Delete remote repository
Octokit.delete_repository "#{OpenWebslides.config.github.organization}/#{@receiver.canonical_name}"
end
end
end
end
|
package view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import controller.WorldController;
import model.World;
import observers.ButtonStart;
import observers.Table;
import observers.TextFieldTimer;
import observers.WorldTable;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
public class GUI extends JFrame{
private WorldController controller;
private WorldTableModel tableModel;
private Table worldTable;
private JPanel contentPane;
private JTable table;
private JPanel panel;
private JButton btnRefresh;
private JLabel lblTimer;
private JButton btnStart;
private JTextField textTimer;
private TextFieldTimer worldTextFieldTimer;
private ButtonStart worldButtonStart;
private JComboBox comboFilter;
/**
* Create the application.
*/
public GUI(WorldController controller) {
this.controller = controller;
tableModel = new WorldTable(new ArrayList<World>(), controller);
worldTable = new Table(controller, tableModel);
worldTextFieldTimer = new TextFieldTimer(controller);
worldButtonStart = new ButtonStart(controller);
setupUI();
createEvents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void setupUI() {
setTitle("World Tracker");
setBounds(100, 100, 541, 541); //541
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
table = worldTable.getTable();
table.setFillsViewportHeight(true);
//table.setPreferredSize(new Dimension(300, 541));
table.setAutoCreateRowSorter(true);
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(SwingConstants.LEFT);
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellRenderer(dtcr);
col = table.getColumnModel().getColumn(1);
col.setCellRenderer(dtcr);
col = table.getColumnModel().getColumn(2);
col.setCellRenderer(dtcr);
col = table.getColumnModel().getColumn(3);
col.setCellRenderer(dtcr);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, BorderLayout.CENTER);
panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
btnRefresh = new JButton("Refresh");
btnStart = worldButtonStart.getButton();
textTimer = worldTextFieldTimer.getTextField();
lblTimer = new JLabel("Timer:");
comboFilter = new JComboBox();
comboFilter.setModel(new DefaultComboBoxModel(new String[] {"All", "P2P", "F2P"}));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(lblTimer)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textTimer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnStart)
.addPreferredGap(ComponentPlacement.RELATED, 120, Short.MAX_VALUE)
.addComponent(comboFilter, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnRefresh)
.addContainerGap())
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnRefresh)
.addComponent(lblTimer)
.addComponent(textTimer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnStart)
.addComponent(comboFilter, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
panel.setLayout(gl_panel);
}
private void createEvents() {
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
controller.updateWorlds();
} catch (NumberFormatException | IOException e) {
JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
controller.handleTimer(textTimer.getText());
} catch (Exception e) {
JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
comboFilter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String filter;
if (cb.getSelectedItem().equals("All")) {
filter = ".*";
} else if (cb.getSelectedItem().equals("P2P")) {
filter = "Members";
} else {
filter = "Free";
}
RowFilter<String, Integer> rowFilter = RowFilter.regexFilter(filter, 3);
((TableRowSorter) table.getRowSorter()).setRowFilter(rowFilter);
}
});
}
}
|
```c++
#include <iostream>
using std::cin; using std::cout; using std::endl; using std::cerr;
#include <string>
using std::string;
#include <regex>
using std::regex; using std::regex_search; using std::smatch;
using std::sregex_iterator;
bool valid(const smatch &m){
if (m[0].matched){ //如果整个模式都匹配
return 1;
} else if (m[1].matched){ //如果前5位数字匹配
return !(m[2].matched && m[3].matched); //则不应出现-以及后面的数字
} else {
return 0;
}
}
int main() {
try {
string phone =
"((\\d{5})([-])?(\\d{4})?)";
regex r(phone); //regex对象,用于查找我们的模式
smatch m;
string s;
cout << "Please type the zipcode: \n";
//从输入文件中读取每条记录
while (getline(cin, s)){
//对每个匹配的电话号码
for (sregex_iterator it(s.begin(), s.end(), r), end_it; it != end_it; ++it){
//检查号码的格式是否合法
if (valid(*it))
cout << "valid: " << it->str() << endl;
else
cout << "not valid: " << it->str() << endl;
}
}
} catch (std::regex_error e){
cout << e.what() << "\ncode: " << e.code() << endl;
}
}
```
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview;
import org.chromium.android_webview.AwContents.VisualStateCallback;
import org.chromium.base.ThreadUtils;
import org.chromium.content_public.browser.WebContents;
import org.chromium.content_public.browser.WebContentsObserver;
import org.chromium.net.NetError;
import java.lang.ref.WeakReference;
/**
* Routes notifications from WebContents to AwContentsClient and other listeners.
*/
public class AwWebContentsObserver extends WebContentsObserver {
// TODO(tobiasjs) similarly to WebContentsObserver.mWebContents, mAwContents
// needs to be a WeakReference, which suggests that there exists a strong
// reference to an AwWebContentsObserver instance. This is not intentional,
// and should be found and cleaned up.
private final WeakReference<AwContents> mAwContents;
private final WeakReference<AwContentsClient> mAwContentsClient;
// Whether this webcontents has ever committed any navigation.
private boolean mCommittedNavigation;
// Temporarily stores the URL passed the last time to didFinishLoad callback.
private String mLastDidFinishLoadUrl;
// Temporarily stores the last committed url.
private String mLastCommittedUrl;
// Temporarily stores the last url that was committed when we started a navigation to an error
// page.
private String mLastCommittedUrlWhenNavigatingToErrorPage;
public AwWebContentsObserver(
WebContents webContents, AwContents awContents, AwContentsClient awContentsClient) {
super(webContents);
mAwContents = new WeakReference<>(awContents);
mAwContentsClient = new WeakReference<>(awContentsClient);
}
private AwContentsClient getClientIfNeedToFireCallback(String validatedUrl) {
AwContentsClient client = mAwContentsClient.get();
if (client != null) {
String unreachableWebDataUrl = AwContentsStatics.getUnreachableWebDataUrl();
if (unreachableWebDataUrl == null || !unreachableWebDataUrl.equals(validatedUrl)) {
return client;
}
}
return null;
}
@Override
public void didStartProvisionalLoadForFrame(long frameId, long parentFrameId,
boolean isMainFrame, String validatedUrl, boolean isErrorPage, boolean isIframeSrcdoc) {
if (isMainFrame && isErrorPage) {
// We are navigating to an error page - we should call onPageFinished for the last
// committed Url.
mLastCommittedUrlWhenNavigatingToErrorPage = mLastCommittedUrl;
}
}
@Override
public void didCommitProvisionalLoadForFrame(
long frameId, boolean isMainFrame, String url, int transitionType) {
if (isMainFrame) {
mLastCommittedUrl = url;
}
}
@Override
public void didFinishLoad(long frameId, String validatedUrl, boolean isMainFrame) {
if (isMainFrame && getClientIfNeedToFireCallback(validatedUrl) != null) {
mLastDidFinishLoadUrl = validatedUrl;
}
}
@Override
public void didStopLoading(String validatedUrl) {
if (validatedUrl.length() == 0) validatedUrl = "about:blank";
AwContentsClient client = getClientIfNeedToFireCallback(validatedUrl);
if (client != null
&& (validatedUrl.equals(mLastDidFinishLoadUrl)
|| validatedUrl.equals(mLastCommittedUrlWhenNavigatingToErrorPage))) {
client.getCallbackHelper().postOnPageFinished(validatedUrl);
mLastDidFinishLoadUrl = null;
mLastCommittedUrlWhenNavigatingToErrorPage = null;
mLastCommittedUrl = null;
}
}
@Override
public void didFailLoad(boolean isProvisionalLoad, boolean isMainFrame, int errorCode,
String description, String failingUrl, boolean wasIgnoredByHandler) {
AwContentsClient client = mAwContentsClient.get();
if (client == null) return;
String unreachableWebDataUrl = AwContentsStatics.getUnreachableWebDataUrl();
boolean isErrorUrl =
unreachableWebDataUrl != null && unreachableWebDataUrl.equals(failingUrl);
if (isMainFrame && !isErrorUrl && errorCode == NetError.ERR_ABORTED) {
// Need to call onPageFinished for backwards compatibility with the classic webview.
// See also AwContents.IoThreadClientImpl.onReceivedError.
client.getCallbackHelper().postOnPageFinished(failingUrl);
}
}
@Override
public void didNavigateMainFrame(final String url, String baseUrl,
boolean isNavigationToDifferentPage, boolean isFragmentNavigation, int statusCode) {
// Only invoke the onPageCommitVisible callback when navigating to a different page,
// but not when navigating to a different fragment within the same page.
if (isNavigationToDifferentPage) {
ThreadUtils.postOnUiThread(new Runnable() {
@Override
public void run() {
AwContents awContents = mAwContents.get();
if (awContents != null) {
awContents.insertVisualStateCallbackIfNotDestroyed(
0, new VisualStateCallback() {
@Override
public void onComplete(long requestId) {
AwContentsClient client = mAwContentsClient.get();
if (client == null) return;
client.onPageCommitVisible(url);
}
});
}
}
});
}
// This is here to emulate the Classic WebView firing onPageFinished for main frame
// navigations where only the hash fragment changes.
if (isFragmentNavigation) {
AwContentsClient client = mAwContentsClient.get();
if (client == null) return;
client.getCallbackHelper().postOnPageFinished(url);
}
}
@Override
public void didNavigateAnyFrame(String url, String baseUrl, boolean isReload) {
mCommittedNavigation = true;
final AwContentsClient client = mAwContentsClient.get();
if (client == null) return;
client.getCallbackHelper().postDoUpdateVisitedHistory(url, isReload);
}
public boolean didEverCommitNavigation() {
return mCommittedNavigation;
}
}
|
package handlers
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
time "time"
log "github.com/Sirupsen/logrus"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
//"reflect"
//"github.com/dgraph-io/dgo/y"
"net/http/httputil"
)
// AppNamespace used for only monitor assets in a specific namespace
// otherwise AppNamespace will refer to all namespaces that the controller has access to
var AppNamespace string
// ClusterName for running in a cluster
var ClusterName = os.Getenv("CLUSTER_NAME")
// RestSvcEndpoint the URL that k8s data will send to
var RestSvcEndpoint = os.Getenv("TARGET_URL")
// Handler interface contains the methods that are required
type Handler interface {
Init() error
ObjectCreated(obj interface{}) error
ObjectDeleted(obj interface{}, key string) error
ObjectUpdated(objOld, objNew interface{}) error
}
// SendJSONQuery send requests to REST api
func SendJSONQuery(obj interface{}, url string) (int, []byte) {
//url := "http://localhost:8011/create"
s, err := json.Marshal(obj)
if err != nil {
log.Error("failed to marshal object in SendJSONQuery")
log.Error(err)
}
log.Infof("sent to %s:\n %s", url, string(s))
payload := bytes.NewBuffer(s)
req, _ := http.NewRequest("POST", url, payload)
req.Close = true
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", os.Getenv("AUTH_HEADER"))
req.Header.Add("clustername", ClusterName)
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Error(err)
return 404, nil
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
log.Infof("%s response %+v\n", url, res)
log.Infof("%s body: %s\n", url, string(body))
log.Info("*************************************************************************")
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
}
log.Info(string(requestDump))
return res.StatusCode, body
}
// SendDeleteRequest send request to delete k8s objects
func SendDeleteRequest(url string) (int, []byte) {
req, _ := http.NewRequest("DELETE", url, nil)
req.Close = true
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", os.Getenv("AUTH_HEADER"))
// Fetch Request
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Error(err)
return 404, nil
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
log.Infof("%s response %+v\n", url, res)
log.Infof("%s body: %s\n", url, string(body))
log.Info("*************************************************************************")
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
}
log.Info(string(requestDump))
return res.StatusCode, body
}
// SendJSONQueryWithRetries retry requests if error occurs
func SendJSONQueryWithRetries(obj interface{}, url string) ([]byte, error) {
// try sending the query 5 times and if it fails
status, body := SendJSONQuery(obj, url)
maxTries := 5
cur := 0
for status != 200 && cur < maxTries {
time.Sleep(2000 * time.Millisecond)
status, body = SendJSONQuery(obj, url)
cur = cur + 1
}
fmt.Println()
time.Sleep(100 * time.Millisecond)
if status == 200 {
return body, nil
}
return nil, errors.New("sending object failed too many times")
}
// GetKubernetesClient retrieve the Kubernetes cluster client from outside of the cluster
func GetKubernetesClient() kubernetes.Interface {
// construct the path to resolve to `~/.kube/config`
kubeConfigPath := os.Getenv("HOME") + "/.kube/config"
var config *rest.Config
// create the config from the path
config, err := clientcmd.BuildConfigFromFlags("", kubeConfigPath)
if err != nil {
log.Infof("getClusterConfig: %v", err)
// if the container is running inside the cluster, use the incluster config
var err2 error
config, err2 = rest.InClusterConfig()
if err2 != nil {
panic(err.Error())
}
}
// generate the client based off of the config
client, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalf("getClusterConfig: %v", err)
}
log.Info("Successfully constructed k8s client")
return client
}
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent.STM (STM)
import Control.Monad (forever)
import Control.Monad.Managed (Managed, liftIO)
import Data.ByteString.Lazy (ByteString)
import Data.Monoid ((<>))
import qualified Control.Concurrent as Concurrent
import qualified Control.Concurrent.Async as Async
import qualified Control.Concurrent.STM as STM
import qualified Control.Concurrent.STM.TBQueue as TBQueue
import qualified Control.Monad.Managed as Managed
import qualified Network.HTTP.Types as HTTP
import qualified Network.Wai as Wai
import qualified Network.Wai.Handler.Warp as Warp
import qualified System.IO as IO
newtype Transaction a = Transaction { getTransaction :: STM a }
instance Monoid (Transaction a) where
mempty = Transaction STM.retry
mappend (Transaction l) (Transaction r) = Transaction (l `STM.orElse` r)
data Event = Tick | KeyPress Char | Message ByteString deriving (Show)
chars :: Managed (Transaction Event)
chars = do
queue <- liftIO (TBQueue.newTBQueueIO 100)
let thread = forever (do
char <- getChar
STM.atomically (TBQueue.writeTBQueue queue (KeyPress char)) )
_ <- Managed.managed (Async.withAsync thread)
return (Transaction (TBQueue.readTBQueue queue))
ticks :: Managed (Transaction Event)
ticks = do
queue <- liftIO (TBQueue.newTBQueueIO 100)
let thread = forever (do
Concurrent.threadDelay 1000000
STM.atomically (TBQueue.writeTBQueue queue Tick) )
_ <- Managed.managed (Async.withAsync thread)
return (Transaction (TBQueue.readTBQueue queue))
messages :: Managed (Transaction Event)
messages = do
queue <- liftIO (TBQueue.newTBQueueIO 100)
let application request respond = do
bytestring <- Wai.strictRequestBody request
STM.atomically (TBQueue.writeTBQueue queue (Message bytestring))
respond (Wai.responseBuilder HTTP.status200 [] "")
let thread = Warp.run 8080 application
_ <- Managed.managed (Async.withAsync thread)
return (Transaction (TBQueue.readTBQueue queue))
events :: Managed (Transaction Event)
events = chars <> ticks <> messages
main :: IO ()
main = do
IO.hSetBuffering IO.stdin IO.NoBuffering
IO.hSetEcho IO.stdin False
Managed.runManaged (do
transaction <- events
liftIO (forever (do
event <- STM.atomically (getTransaction transaction)
print event ) ))
|
using System;
namespace CSCore.DirectSound
{
internal static class DSUtils
{
public static readonly Guid AllObjects = new Guid("aa114de5-c262-4169-a1c8-23d698cc73b5");
public static DSResult DirectSoundCreate(DirectSoundDevice device, out IntPtr directSound)
{
Guid guid = device.Guid;
return NativeMethods.DirectSoundCreate(ref guid, out directSound, IntPtr.Zero);
}
public static DSResult DirectSoundCreate8(DirectSoundDevice device, out IntPtr directSound)
{
Guid guid = device.Guid;
return NativeMethods.DirectSoundCreate8(ref guid, out directSound, IntPtr.Zero);
}
public static IntPtr GetConsoleHandle()
{
return FindWindow(Console.Title);
}
public static IntPtr FindWindow(string atom, string windowTitle)
{
return NativeMethods.FindWindow(atom, windowTitle);
}
public static IntPtr FindWindow(string windowTitle)
{
return NativeMethods.FindWindow(null, windowTitle);
}
public static IntPtr GetDesktopWindow()
{
return NativeMethods.GetDesktopWindow();
}
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Gloudemans\Shoppingcart\Facades\Cart;
use App\Product;
class CartController extends Controller
{
public function index(){
return view('front.cart.index');
}
public function store(Request $request){
$duplicate=Cart::search(function($cartItem,$rowId) use($request){
return $cartItem->id===$request->id;
});
if($duplicate->isNotEmpty()){
return redirect()->back()->with('msg','Your item is already in the cart');
}
$product=new Product();
Cart::add($request->id,$request->name,1,$request->price)->associate($product);
session()->flash('msg','The item has been added to the cart');
return redirect('/');
}
public function destroy($id){
Cart::remove($id);
return redirect()->back()->with('msg','The item has been removed from the cart');
}
public function saveLater($id){
$item=Cart::get($id);
Cart::remove($id);
$duplicate=Cart::instance('saveForLater')->search(function($cartItem,$rowId) use($id){
return $cartItem->id===$id;
});
if($duplicate->isNotEmpty()){
return redirect()->back()->with('msg','Your item is already in the save for later');
}
Cart::instance('saveForLater')->add($item->id,$item->name,1,$item->price)->associate('App\Product');
return redirect()->back()->with('msg','Your item has been added to save For later');
}
}
|
class AddUniqueConstraintToSourceUid < ActiveRecord::Migration[5.1]
def change
add_index :sources, [:uid], :unique => true
change_column_null :sources, :uid, false
end
end
|
# Pocket
## Installation
Below on how to get the necessary information for the extension. Make sure you replace the
strings `YOUR_APP_CONSUMER_KEY`,
`YOUR_ACCESS_TOKEN` and `YOUR_REQUEST_TOKEN` with the actual values.
First you will need to create a Pocket app [here](https://getpocket.com/developer/apps/).
After that you will need to copy the consumer key:

Then run the following code in your terminal replacing `YOUR_APP_CONSUMER_KEY` with the value you got in the previous
step.
```shell
curl --location --request POST 'https://getpocket.com/v3/oauth/request' \
--header 'Content-Type: application/json' \
--data-raw '{
"consumer_key": "YOU_APP_CONSUMER_KEY",
"redirect_uri": "https://google.com"
}'
```
This will respond with the following:
```
code=YOUR_REQUEST_TOKEN
```
Copy the `YOUR_REQUEST_TOKEN` value and use it to open the following URL in our browser:
```
https://getpocket.com/auth/authorize?request_token=YOUR_REQUEST_TOKEN&redirect_uri=https://google.com
```
This will open an authorization screen, simply press the `Authorize`.

Finally, you just need to run the following code in your terminal to get the access token:
```shell
curl --location --request POST 'https://getpocket.com/v3/oauth/authorize' \
--header 'Content-Type: application/json' \
--data-raw '{
"consumer_key": "YOUR_APP_CONSUMER_KEY",
"code": "YOUR_REQUEST_TOKEN"
}'
```
This will respond you with the following:
```
access_token=YOUR_ACCESS_TOKEN&username=victor%40vimtor.io
```
Now you can fill all the necessary fields in the extension settings. |
//////////////////////////////////////////////////////////////////////////
// Cria��o...........: 17-05-2007
// Ultima modifica��o: 28-06-2007
// Sistema...........: Olimpo Cafe - Automa��o de Cafeterias
// Analistas.........: Marilene Esquiavoni & Denny Paulista Azevedo Filho
// Desenvolvedores...: Marilene Esquiavoni & Denny Paulista Azevedo Filho
// Copyright.........: Marilene Esquiavoni & Denny Paulista Azevedo Filho
//////////////////////////////////////////////////////////////////////////
unit UnitDetConta;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RXCtrls, fcButton, fcImgBtn, StdCtrls, Mask, DBCtrls, fcLabel,
JvComponent, JvTransBtn, LMDCustomControl, LMDCustomPanel,
LMDCustomBevelPanel, LMDCustomParentPanel, LMDBackPanel, Grids, DBGrids,
RXDBCtrl, EMsgDlg, JvEnterTab;
type
TFrmDetConta = class(TForm)
dbCliente: TDBEdit;
RxLabel13: TRxLabel;
Panel3: TLMDBackPanel;
btnSair: TJvTransparentButton;
LMDBackPanel2: TLMDBackPanel;
fcLabel2: TfcLabel;
LMDBackPanel1: TLMDBackPanel;
edCodCli: TEdit;
RxLabel1: TRxLabel;
RxDBGridMarca: TRxDBGrid;
RxLabel2: TRxLabel;
RxDBGrid1: TRxDBGrid;
MsgDlg: TEvMsgDlg;
RxLabel3: TRxLabel;
JvEnterAsTab1: TJvEnterAsTab;
procedure BtnlocCliClick(Sender: TObject);
procedure edCodCliExit(Sender: TObject);
procedure btnSairClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmDetConta: TFrmDetConta;
NovoItem : Boolean ;
implementation
uses unitDmDados, unitLocCliente, UnitPrincipal;
{$R *.dfm}
procedure TFrmDetConta.BtnlocCliClick(Sender: TObject);
begin
FrmLocCliente := TFrmLocCliente.Create(application);
FrmLocCliente.Showmodal;
edCodCli.Text := IntToStr(frmLocCliente.Resultado);
frmLocCliente.Free;
end;
procedure TFrmDetConta.edCodCliExit(Sender: TObject);
begin
if edCodCli.Text <> '' then
begin
if (not dmdados.tbCliente.Locate('CodCli',edcodCli.text,[])) then
begin
MsgDlg.MsgWarning('C�DIGO DO CLIENTE n�o cadastrado!');
edCodCli.SetFocus;
end;
end
end;
procedure TFrmDetConta.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TFrmDetConta.FormShow(Sender: TObject);
begin
dmDados.vTabStt := True ;
NovoItem := False;
dmDados.HabilitaTeclado := True ;
FrmPrincipal.StatusTeclas(True,'[Esc] Sair');
end;
procedure TFrmDetConta.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FrmPrincipal.StatusTeclas(False,'');
Action := caFree;
end;
procedure TFrmDetConta.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if dmdados.HabilitaTeclado then
case (key) of
// Teclas de a��o na tabela
VK_ESCAPE : btnSair.Click;
end;
end;
end.
|
import sys
import time
import torch
from torch.jit import script
from torchani.aev import neighbor_pairs, compute_shifts
import pointneighbor as pn
from common import random_particle, CellParameter, Pnt
def timeit(f):
s = time.time()
f()
e = time.time()
return e - s
def number(mod, pe: pn.PntFul):
adj = mod(pe)
vec_sod = pn.coo2_vec_sod(adj, pe.pos_xyz, pe.cel_mat)
sod = vec_sod.sod
assert (sod <= 6 * 6).all()
assert sod.unique(False).size(0) * 2 == sod.size(0)
return adj.adj.size(1)
def sort(mod, pe: pn.PntFul):
adj = mod(pe)
vec_sod = pn.coo2_vec_sod(adj, pe.pos_xyz, pe.cel_mat)
sod = vec_sod.sod
return sod.sort()[0]
def using_torchani(pe: pn.PntFul):
spc = pn.functional.get_pos_spc(pe.pos_cel, pe.pbc)
pos_cel = pn.functional.to_unit_cell(pe.pos_cel, spc)
assert ((pos_cel >= 0) & (pos_cel <= 1)).all()
pos_chk = pos_cel @ pe.cel_mat
pos = pn.functional.to_unit_cell(pe.pos_xyz, pe.spc_xyz)
pos_cel = pos @ pe.cel_inv
assert ((pos_cel >= 0) & (pos_cel <= 1)).all()
assert torch.allclose(pos, pos_chk, atol=1e-2)
print((pos - pos_chk).max())
shifts = compute_shifts(pe.cel_mat.squeeze(0), pe.pbc.squeeze(0), 6.0)
i, j, s = neighbor_pairs(~pe.ent, pos, pe.cel_mat.squeeze(0), shifts, 6.0,)
return len(j) * 2
def main():
if len(sys.argv) > 1:
torch.manual_seed(int(sys.argv[1]))
n_bch = 1
n_pnt = 160
n_dim = 3
rc = 6.0
params = [CellParameter(30.0, 30.0, 30.0, 1.0, 1.0, 1.0)
for _ in range(n_bch)]
pbc = torch.tensor([[True, True, True] for _ in range(n_bch)])
ful_simple = script(pn.Coo2FulSimple(rc))
ful_pntsft = script(pn.Coo2FulPntSft(rc))
cel = script(pn.Coo2Cel(rc))
bok = script(pn.Coo2BookKeeping(
pn.Coo2FulSimple(rc + 2.0), pn.StrictCriteria(2.0, debug=True), rc))
p = random_particle(n_bch, n_pnt, n_dim, params, pbc)
pe = pn.pnt_ful(p.cel, p.pbc, p.pos, p.ent)
for _ in range(1009):
noise = torch.randn_like(pe.pos_xyz) * 0.1
p = Pnt(
pos=pe.pos_xyz + noise,
cel=pe.cel_mat,
pbc=pe.pbc,
ent=pe.ent,
)
pe = pn.pnt_ful(p.cel, p.pbc, p.pos, p.ent)
n_fs = number(ful_simple, pe)
n_fp = number(ful_pntsft, pe)
n_cl = number(cel, pe)
n_ta = using_torchani(pe)
s_fs = sort(ful_simple, pe)
s_cl = sort(cel, pe)
# assert n_fs == n_fp == n_cl, (n_fs, n_fp, n_cl)
n_bk = number(bok, pe)
assert n_fs == n_fp == n_cl == n_bk, (n_fs, n_fp, n_cl, n_bk, n_ta)
assert (s_fs == s_cl).all()
print(n_cl, n_ta, pe.spc_cel.max())
if __name__ == "__main__":
main()
|
package org.beckn.one.sandbox.bap.message.services
import com.mongodb.MongoException
import io.kotest.assertions.arrow.either.shouldBeLeft
import io.kotest.assertions.arrow.either.shouldBeRight
import io.kotest.core.spec.style.DescribeSpec
import io.kotest.matchers.ints.shouldBeExactly
import org.beckn.one.sandbox.bap.errors.database.DatabaseError
import org.beckn.one.sandbox.bap.message.entities.OnSearchDao
import org.beckn.one.sandbox.bap.message.entities.OnSearchMessageDao
import org.beckn.one.sandbox.bap.message.factories.ProtocolCatalogFactory
import org.beckn.one.sandbox.bap.message.factories.ProtocolContextFactory
import org.beckn.one.sandbox.bap.message.mappers.OnSearchResponseMapper
import org.beckn.one.sandbox.bap.message.repositories.BecknResponseRepository
import org.beckn.protocol.schemas.ProtocolOnSearch
import org.beckn.protocol.schemas.ProtocolOnSearchMessage
import org.mockito.kotlin.mock
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.TestPropertySource
@SpringBootTest
@ActiveProfiles(value = ["test"])
@TestPropertySource(locations = ["/application-test.yml"])
internal class ResponseStorageServiceSpec @Autowired constructor(
val searchResponseMapper: OnSearchResponseMapper,
val searchResponseStorageService: ResponseStorageService<ProtocolOnSearch>,
val searchResponseRepo: BecknResponseRepository<OnSearchDao>
) : DescribeSpec() {
private val context = ProtocolContextFactory.fixed
val schemaSearchResponse = ProtocolOnSearch(
context = ProtocolContextFactory.fixed,
message = ProtocolOnSearchMessage(ProtocolCatalogFactory.create(2))
)
init {
describe("SearchResponseStore") {
val searchResponse = OnSearchDao(
context = ProtocolContextFactory.fixedAsEntity(context),
message = OnSearchMessageDao(
catalog = ProtocolCatalogFactory.createAsEntity(schemaSearchResponse.message?.catalog)
)
)
context("when save is called with search response") {
searchResponseRepo.clear()
val response = searchResponseStorageService.save(schemaSearchResponse)
it("should save response to store") {
searchResponseRepo.all().size shouldBeExactly 1
}
it("should respond with either.right to indicate success") {
response.shouldBeRight()
}
}
context("when findByMessageID is called with id") {
searchResponseRepo.clear()
searchResponseStorageService.save(schemaSearchResponse)
val response = searchResponseStorageService.findByMessageId(context.messageId)
it("should respond with either.right containing the search results") {
response.shouldBeRight(listOf(schemaSearchResponse))
}
}
context("when error is encountered while saving") {
val mockRepo = mock<BecknResponseRepository<OnSearchDao>> {
onGeneric { insertOne(searchResponse) }.thenThrow(MongoException("Write error"))
}
val failureSearchResponseService = ResponseStorageServiceImpl(mockRepo, searchResponseMapper)
val response = failureSearchResponseService.save(schemaSearchResponse)
it("should return a left with write error") {
response.shouldBeLeft(DatabaseError.OnWrite)
}
}
context("when error is encountered while fetching message by id") {
val mockRepo = mock<BecknResponseRepository<OnSearchDao>> {
onGeneric { findByMessageId(context.messageId) }.thenThrow(MongoException("Write error"))
}
val failureSearchResponseService = ResponseStorageServiceImpl(mockRepo, searchResponseMapper)
val response = failureSearchResponseService.findByMessageId(context.messageId)
it("should return a left with write error") {
response.shouldBeLeft(DatabaseError.OnRead)
}
}
}
}
} |
<?php
/**
* xts
* File: apple.php
* User: TingSong-Syu <[email protected]>
* Date: 2013-11-30
* Time: 14:49
*/
namespace xts;
use \Memcache;
use \Redis;
/**
* Class Cache
* @package xts
*/
abstract class Cache extends Component {
/**
* @param string $key
* @return mixed
*/
public abstract function get($key);
/**
* @param string $key
* @param mixed $value
* @param int $duration
* @return void
*/
public abstract function set($key, $value, $duration);
/**
* @param string $key
* @throws MethodNotImplementException
* @return boolean
*/
public function remove($key) {
throw new MethodNotImplementException(__METHOD__.' has not been implemented yet.');
}
/**
* @throws MethodNotImplementException
* @return void
*/
public function flush() {
throw new MethodNotImplementException(__METHOD__.' has not been implemented yet.');
}
/**
* @param string $key
* @param int $step
* @throws MethodNotImplementException
* @return int|boolean
*/
public function inc($key, $step=1) {
throw new MethodNotImplementException(__METHOD__.' has not been implemented yet.');
}
/**
* @param string $key
* @param int $step
* @throws MethodNotImplementException
* @return int
*/
public function dec($key, $step=1) {
throw new MethodNotImplementException(__METHOD__.' has not been implemented yet.');
}
}
/**
* Class MCache
* @package xts
* @property-read Memcache $cache
*/
class MCache extends Cache {
protected $_cache;
/**
* @varStatic array
*/
protected static $_conf = array(
'host' => 'localhost',
'port' => 11211,
'persistent' => false,
'keyPrefix' => '',
);
/**
* @param string $key
* @return mixed
*/
public function get($key) {
$key = $this->conf['keyPrefix'] . $key;
$s = $this->cache->get($key);
if($s === false) {
Toolkit::trace("MCache miss $key");
return false;
} else {
Toolkit::trace("MCache hit $key");
return is_numeric($s)?$s:unserialize($s);
}
}
/**
* @param string $key
* @param mixed $value
* @param int $duration
* @return void
*/
public function set($key, $value, $duration) {
$key = $this->conf['keyPrefix'] . $key;
Toolkit::trace("MCache set $key");
$s = is_numeric($value)?$value:serialize($value);
$this->cache->set($key, $s, 0, $duration);
}
/**
* @param string $key
* @return boolean
*/
public function remove($key) {
$key = $this->conf['keyPrefix'] . $key;
Toolkit::trace("MCache remove $key");
return $this->cache->delete($key);
}
/**
* @return void
*/
public function flush() {
Toolkit::trace("MCache flush");
$this->cache->flush();
}
/**
* @param string $key
* @param int $step
* @return int
*/
public function inc($key, $step=1) {
$key = $this->conf['keyPrefix'] . $key;
Toolkit::trace("MCache inc $key by $step");
return $this->cache->increment($key, $step);
}
/**
* @param string $key
* @param int $step
* @return int
*/
public function dec($key, $step=1) {
$key = $this->conf['keyPrefix'] . $key;
Toolkit::trace("MCache dec $key by $step");
return $this->cache->decrement($key, $step);
}
/**
* @return Memcache
*/
public function getCache() {
if(!$this->_cache instanceof Memcache) {
Toolkit::trace("MCache init");
$this->_cache = new Memcache();
if(static::$_conf['persistent']) {
$this->_cache->pconnect(static::$_conf['host'], static::$_conf['port']);
} else {
$this->_cache->connect(static::$_conf['host'], static::$_conf['port']);
}
}
return $this->_cache;
}
}
/**
* Class CCache
* @package xts
*/
class CCache extends Cache {
protected static $_conf = array(
'cacheDir' => '.',
);
public function init() {
Toolkit::trace('CCache init');
if(!is_dir(static::$_conf['cacheDir']))
mkdir(static::$_conf['cacheDir'], 0777, true);
}
private function key2file($key) {
return self::$_conf['cacheDir'].DIRECTORY_SEPARATOR.rawurlencode($key).'.php';
}
/**
* @param string $key
* @return mixed
*/
public function get($key) {
$file = $this->key2file($key);
if(is_file($file)) {
$r = require($file);
if(!empty($r) && $key === $r['key'] && ($r['expiration'] == 0 || time() <= $r['expiration'])) {
Toolkit::trace("CCache hit $key");
return $r['data'];
}
}
Toolkit::trace("CCache miss $key");
return false;
}
/**
* @param string $key
* @param mixed $value
* @param int $duration
* @return void
*/
public function set($key, $value, $duration) {
Toolkit::trace("CCache set $key");
$file = $this->key2file($key);
$content = array(
'key' => $key,
'expiration' => $duration>0?time()+$duration:0,
'data' => $value,
);
$phpCode = '<?php return '.Toolkit::compile($content).';';
file_put_contents($file, $phpCode, LOCK_EX);
}
/**
* @param string $key
* @return boolean
*/
public function remove($key) {
Toolkit::trace("CCache remove $key");
$file = $this->key2file($key);
if(is_file($file)) {
unlink($file);
return true;
}
return false;
}
}
/**
* Class RCache
* @package xts
* @property-read Redis $cache
*/
class RCache extends Cache {
/**
* @var Redis $_cache
*/
protected $_cache;
/**
* @varStatic array
*/
protected static $_conf = array(
'host' => 'localhost',
'port' => 6379, //int, 6379 by default
'timeout' => 0, //float, value in seconds, default is 0 meaning unlimited
'persistent' => false, //bool, false by default
'database' => 0, //number, 0 by default
'auth' => null, //string, null by default
'keyPrefix' => '',
);
/**
* @param string $key
* @return mixed
*/
public function get($key) {
$s = $this->cache->get($key);
if($s === false) {
Toolkit::trace("RCache Miss '$key'");
return false;
} else {
Toolkit::trace("RCache Hit '$key'");
return is_numeric($s)?$s:unserialize($s);
}
}
/**
* @param string $key
* @param mixed $value
* @param int $duration
* @return void
*/
public function set($key, $value, $duration=0) {
Toolkit::trace("RCache Set $key");
$s = is_numeric($value)?$value:serialize($value);
$this->cache->set($key, $s, $duration);
}
/**
* @param string $key
* @return boolean
*/
public function remove($key) {
Toolkit::trace("RCache remove '$key'");
return $this->_cache->delete($key);
}
/**
* @return void
*/
public function flush() {
Toolkit::trace("RCache flush");
$this->_cache->flushDB();
}
/**
* @param string $key
* @param int $step
* @return int
*/
public function inc($key, $step=1) {
Toolkit::trace("RCache inc '$key' by $step");
if($step > 1) {
return $this->cache->incrBy($key, $step);
} else {
return $this->cache->incr($key);
}
}
/**
* @param string $key
* @param int $step
* @return int
*/
public function dec($key, $step=1) {
Toolkit::trace("RCache dec '$key' by $step");
if($step > 1) {
return $this->cache->decrBy($key, $step);
} else {
return $this->cache->decr($key);
}
}
/**
* @return Redis
*/
public function getCache() {
if(!$this->_cache instanceof Redis) {
Toolkit::trace("RCache init");
$this->_cache = new Redis();
if(static::$_conf['persistent']) {
$this->_cache->pconnect(static::$_conf['host'], static::$_conf['port'], static::$_conf['timeout']);
} else {
$this->_cache->connect(static::$_conf['host'], static::$_conf['port'], static::$_conf['timeout']);
}
if(static::$_conf['auth']) {
$this->_cache->auth(static::$_conf['auth']);
}
if(static::$_conf['database']) {
$this->_cache->select(static::$_conf['database']);
}
if(static::$_conf['keyPrefix']) {
$this->_cache->setOption(Redis::OPT_PREFIX, static::$_conf['keyPrefix']);
}
}
return $this->_cache;
}
} |
// Inject node globals into React Native global scope.
global.Buffer = require('buffer').Buffer;
global.process = require('process');
global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production';
// Custom overrides for Web Client (src/utils/web-client) configuration
// Match to settings of API server you're hitting
//
// For example,
// global.process.env.API_HOST = 'http://localhost:4000';
// global.process.env.API_PREFIX = '/api';
// Needed so that 'stream-http' chooses the right default protocol.
global.location = {
protocol: 'file:'
};
|
import 'dart:io' show Platform;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import '../../styled_widgets/smooth_scroll.dart';
import '../../utils/utils.dart';
import '../navigation.dart';
class NavigationPanel extends StatefulWidget {
const NavigationPanel({
Key? key,
required this.categories,
this.onComponentSelected,
this.headerPadding,
this.header,
}) : super(key: key);
final List<Category> categories;
final void Function(ComponentState?)? onComponentSelected;
final Widget? header;
final EdgeInsetsGeometry? headerPadding;
@override
_NavigationPanelState createState() => _NavigationPanelState();
}
class _NavigationPanelState extends State<NavigationPanel> {
final ScrollController controller = ScrollController();
ComponentState? selectedComponent;
final TextEditingController search = TextEditingController();
String query = '';
void _onComponentSelected(ComponentState state) {
ComponentState? current = state;
if (current == selectedComponent) current = null;
widget.onComponentSelected?.call(current);
selectedComponent = current;
setState(() {});
}
Widget _buildCategories(BuildContext context, int i) {
final Category item = widget.categories[i];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding:
const EdgeInsets.only(top: 12.0, bottom: 4, left: 20, right: 20),
child: Text(
item.name,
style: context.textTheme.subtitle2!.copyWith(
fontWeight: FontWeight.w600,
letterSpacing: 2,
),
),
),
..._buildOrganizers(item, 1, query)
],
);
}
List<Widget> _buildOrganizers(Organizer category, int layer, String query) {
final List<Widget> organizers = <Widget>[];
final double layerPadding = layer * 6.0;
for (final Organizer item in category.organizers) {
final List<Widget> current = <Widget>[];
switch (item.type) {
case OrganizerType.folder:
current.add(
FolderTile(
organizers: _buildOrganizers(item, layer + 3, query),
padding: layerPadding,
item: item,
),
);
break;
case OrganizerType.component:
final lowerQuery = query.toLowerCase();
if (query.isEmpty || item.name.toLowerCase().contains(lowerQuery)) {
current.add(
ComponentTile(
states: (item as Component)
.states
.map(
(e) => ComponentStateTile(
isSelected: selectedComponent == e,
onSelected: _onComponentSelected,
padding: layerPadding,
item: e,
),
)
.toList(),
padding: layerPadding,
item: item,
),
);
}
break;
default:
}
organizers.add(Column(children: current));
}
return organizers;
}
void _searchOrganizers(String query) {
this.query = query;
setState(() {});
}
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(minWidth: 50, maxWidth: 250),
child: Column(
children: [
widget.header ?? const _NavigationHeader(),
SizedBox(
height: 50,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: Overlay(
initialEntries: [
OverlayEntry(
builder: (context) => CupertinoSearchTextField(
itemSize: 16,
controller: search,
onChanged: _searchOrganizers,
onSuffixTap: () {
search.text = '';
_searchOrganizers('');
},
),
),
],
),
),
),
Expanded(
child: Builder(
builder: (context) {
return ListView.separated(
controller: controller,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: widget.categories.length,
itemBuilder: _buildCategories,
padding: const EdgeInsets.only(bottom: 8),
separatorBuilder: (context, index) =>
const SizedBox(height: 8),
);
},
),
),
],
),
);
}
}
class _NavigationHeader extends StatelessWidget {
const _NavigationHeader({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
alignment: Alignment.center,
height: 50,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(FeatherIcons.bookOpen, color: Color(0xFFD689EF)),
const SizedBox(width: 8),
Text(
'Flutterbook',
style: context.textTheme.headline5!
.copyWith(fontWeight: FontWeight.bold),
),
],
),
),
Text(
'by MOONSDONTBURN',
style: context.textTheme.caption,
),
],
),
);
}
}
|
/*
* Copyright (C) 2020 Intel Corporation. All rights reserved. SPDX-License-Identifier: Apache-2.0
*/
package com.openiot.cloud.sdk.service;
import javax.jms.Destination;
public class JMSResponseSender implements IConnectResponseSender {
private Destination dest;
public JMSResponseSender(Destination dest) {
this.dest = dest;
}
public void send(IConnectResponse response) {
IConnect.getInstance().send(dest, response);
}
}
|
package net.corda.yo
import net.corda.core.identity.CordaX500Name
import net.corda.core.node.services.queryBy
import net.corda.core.node.services.vault.QueryCriteria.VaultCustomQueryCriteria
import net.corda.core.node.services.vault.builder
import net.corda.core.utilities.getOrThrow
import net.corda.testing.contracts.DummyContract
import net.corda.testing.contracts.DummyState
import net.corda.testing.core.DummyCommandData
import net.corda.testing.core.TestIdentity
import net.corda.testing.node.*
import net.corda.yo.YoState.YoSchemaV1.PersistentYoState
import org.junit.After
import org.junit.Before
import org.junit.Test
import kotlin.test.assertEquals
class YoFlowTests {
lateinit var network: MockNetwork
lateinit var a: StartedMockNode
lateinit var b: StartedMockNode
@Before
fun setup() {
network = MockNetwork(listOf("net.corda.yo"))
a = network.createPartyNode()
b = network.createPartyNode()
network.runNetwork()
}
@After
fun tearDown() {
network.stopNodes()
}
@Test
fun flowWorksCorrectly() {
val yo = YoState(a.info.legalIdentities.first(), b.info.legalIdentities.first())
val flow = YoFlow(b.info.legalIdentities.first())
val future = a.startFlow(flow)
network.runNetwork()
val stx = future.getOrThrow()
// Check yo transaction is stored in the storage service.
val bTx = b.services.validatedTransactions.getTransaction(stx.id)
assertEquals(bTx, stx)
print("bTx == $stx\n")
// Check yo state is stored in the vault.
b.transaction {
// Simple query.
val bYo = b.services.vaultService.queryBy<YoState>().states.single().state.data
assertEquals(bYo.toString(), yo.toString())
print("$bYo == $yo\n")
// Using a custom criteria directly referencing schema entity attribute.
val expression = builder { PersistentYoState::yo.equal("Yo!") }
val customQuery = VaultCustomQueryCriteria(expression)
val bYo2 = b.services.vaultService.queryBy<YoState>(customQuery).states.single().state.data
assertEquals(bYo2.yo, yo.yo)
print("$bYo2 == $yo\n")
}
}
}
class YoContractTests {
private val ledgerServices = MockServices(listOf("net.corda.yo", "net.corda.testing.contracts"))
private val alice = TestIdentity(CordaX500Name("Alice", "New York", "US"))
private val bob = TestIdentity(CordaX500Name("Bob", "Tokyo", "JP"))
private val miniCorp = TestIdentity(CordaX500Name("MiniCorp", "New York", "US"))
@Test
fun yoTransactionMustBeWellFormed() {
// A pre-made Yo to Bob.
val yo = YoState(alice.party, bob.party)
// Tests.
ledgerServices.ledger {
// Input state present.
transaction {
input(DummyContract.PROGRAM_ID, DummyState())
command(alice.publicKey, YoContract.Send())
output(YO_CONTRACT_ID, yo)
this.failsWith("There can be no inputs when Yo'ing other parties.")
}
// Wrong command.
transaction {
output(YO_CONTRACT_ID, yo)
command(alice.publicKey, DummyCommandData)
this.failsWith("")
}
// Command signed by wrong key.
transaction {
output(YO_CONTRACT_ID, yo)
command(miniCorp.publicKey, YoContract.Send())
this.failsWith("The Yo! must be signed by the sender.")
}
// Sending to yourself is not allowed.
transaction {
output(YO_CONTRACT_ID, YoState(alice.party, alice.party))
command(alice.publicKey, YoContract.Send())
this.failsWith("No sending Yo's to yourself!")
}
transaction {
output(YO_CONTRACT_ID, yo)
command(alice.publicKey, YoContract.Send())
this.verifies()
}
}
}
} |
---
title: Conditionally Display Columns
description: Conditionally show Edit and Delete buttons in the Kendo UI Grid.
type: how-to
page_title: Show Command Column Based on Conditions | Kendo UI Grid for ASP.NET MVC
slug: grid-show-edit-and-delete-buttons-conditionally
tags: grid, condition, hide, buttons, update, delete, destroy, column
ticketid: 1143185
res_type: kb
---
## Environment
<table>
<tr>
<td>Product</td>
<td>Progress Kendo UI Grid</td>
<td>UI for ASP.NET MVC</td>
</tr>
</tr>
</table>
## Description
How can I hide some of the Grid columns and conditionally display **Edit** and **Delete** buttons?
## Solution
The column configuration of the Grid for ASP.NET MVC has a `Hidden()` ([`columns.hidden`](https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/columns.hidden)) property that expects a Boolean value which can be used for such purposes.
The following example demonstrates how to pass a value in the ViewBag for a key and give it a `true` or `false` value in the controller, and then access it in the Razor template.
To individually fine-tune a command, use the [`command visible`](https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/columns.command.visible) function.
###### Razor Example
```
public ActionResult Index()
{
ViewBag.IsAdmin = true;
return View();
}
@(Html.Kendo()
.Grid<DetailGrids.Models.Inventory>()
.Name("InvGrid")
.Columns(columns =>
{
columns.Bound(p => p.OnOrder).Width(125).Hidden(ViewBag.IsAdmin);
columns.Command(command => { command.Edit(); command.Destroy(); }).Hidden(!ViewBag.IsAdmin);
})
)
```
###### JavaScript Example
```
var isAdmin = false;
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ command: [{ name: "edit" }], hidden: !isAdmin }
],
editable: "popup",
dataSource: [ { name: "Jane" }, { name: "Bill" } ]
});
```
|
<article class="markdown-body entry-content" itemprop="mainContentOfPage"><h1>
<a name="jqueryfreezeheader-" class="anchor" href="#jquerycookie-"><span class="mini-icon mini-icon-link"></span></a>
jquery.freezeheader
</h1>
<p> A simple jquery plugin to freeze header row in html table.</p>
<h2>
<a name="installation" class="anchor" href="#installation"><span class="mini-icon mini-icon-link"></span></a>Installation</h2>
<p>Include script <em>after</em> the jQuery library (unless you are packaging scripts somehow else):</p>
<pre><code><script src="/path/to/jquery.freezeheader.js"></script>
</code></pre>
<h2>
<a name="usage" class="anchor" href="#usage"><span class="mini-icon mini-icon-link"></span></a>Usage</h2>
<p>Create a table with fixed header in the top browser:</p>
```javascript
$(document).ready(function () {
$("#tableid").freezeHeader();
})
```
<p>Create a table with fixed header and scroll bar:</p>
```javascript
$(document).ready(function () {
$("#tableid").freezeHeader({ 'height': '300px' });
})
```
<p>Create a table with fixed header and offset:</p>
```javascript
$(document).ready(function () {
$("#tableid")freezeHeader({'offset' : '51px'})
.on("freeze:on", function( event ) {
//do something
}).on("freeze:off", function( event ) {
//do something
});
})
```
<h2>
<a name="demo" class="anchor" href="#demo"><span class="mini-icon mini-icon-link"></span></a>Demo</h2>
<p><strong><a href="http://laertejjunior.github.io/freezeheader/">http://laertejjunior.github.io/freezeheader/</a></strong> </p>
<h2>
<a name="development" class="anchor" href="#development"><span class="mini-icon mini-icon-link"></span></a>Development</h2>
<ul>
<li>Source hosted at <a href="https://github.com/laertejjunior">GitHub</a>
</li>
<li>Report issues, questions, feature requests on <a href="https://github.com/laertejjunior/freezeheader/issues">GitHub Issues</a>
</li>
</ul><p>Pull requests are very welcome! Make sure your patches are well tested. Please create a topic branch for every separate change you make.</p>
<h2>
<a name="authors" class="anchor" href="#authors"><span class="mini-icon mini-icon-link"></span></a>Authors</h2>
<p><a href="https://github.com/laertejjunior">Laerte Mercier Junior</a></p></article>
|
package org.mapdb.benchmark.elsa
import org.junit.Test
import org.mapdb.benchmark.Bench
import org.mapdb.benchmark.MapBenchmark
import org.mapdb.elsa.ElsaMaker
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.io.ObjectOutputStream
import java.io.Serializable
import java.util.*
class ElsaBench{
val size = MapBenchmark.size/1000
fun ser(name:String, e:Any?){
val elsa = ElsaMaker().make()
val out1 = ByteArrayOutputStream()
val out2 = DataOutputStream(out1)
Bench.bench("elsa-$name") {
Bench.stopwatch {
for (i in 0 until size) {
elsa.serialize(out2, e)
out1.reset()
}
}
}
val out3 = ObjectOutputStream(out1)
Bench.bench("obj-$name") {
Bench.stopwatch {
for (i in 0 until size) {
out3.writeObject(e)
out3.reset()
out1.reset()
}
}
}
}
@Test fun sernull() = ser("null", null)
@Test fun long() = ser("long", 1L)
@Test fun string_empty() = ser("string_empty", "")
@Test fun string() = ser("string", "3d29d023009329d23--032d23d3meoie")
@Test fun pojo() = ser("pojo", ElsaBenchPojo(1,2))
@Test fun map() {
val m = HashMap<Int,Int>()
for(i in 0 until 10000)
m[i] = i
ser("map", m)
}
}
data class ElsaBenchPojo(val a:Long, val b:Int): Serializable {
} |
package com.scau.mis.service;
/**
* 权限角色映射
* @author jodenhe
*
*/
public class RolePermissionService {
}
|
class Frontend::ScreensController < ApplicationController
# Allow cross-origin resource sharing for screens#show.
before_filter :allow_cors, only: [:show, :show_options]
before_filter :screen_api
layout 'frontend'
# GET /frontend/:id
def show
@preview = params.has_key?(:preview) && params[:preview] == "true"
begin
@screen = Screen.find(params[:id])
allow_screen_if_unsecured @screen
auth! action: (@preview ? :preview : :display)
rescue ActiveRecord::ActiveRecordError
# TODO: Could this just be a regular 404?
render text: "Screen not found.", status: 404
rescue CanCan::AccessDenied
if current_screen.nil?
headers['WWW-Authenticate']='Basic realm="Frontend Screen"'
render text: "Screen requires authentication.", status: 401
else
render text: "Incorrect authorization.", status: 403
end
else
@js_files = ['frontend.js']
@debug = false
if params[:debug]
@debug = true
@js_files = ['frontend_debug.js']
end
if params[:files]
@js_files = params[:files].split(",")
end
@screen.run_callbacks(:frontend_display)
respond_to do |format|
format.html
end
end
end
# OPTIONS /frontend/:id
# Requested by browser to find CORS policy
def show_options
head :ok
end
# GET /frontend
# Handles cases where the ID is not provided:
# public legacy screens screens - a MAC address is provided instead of an ID
# private screens - send to ID based on authentication token from cookie or GET param
# private screen setup - a short token is stored in the session or GET param
def index
if !current_screen.nil?
send_to_screen(current_screen)
elsif params[:mac]
screen = Screen.find_by_mac(params[:mac])
if screen
if screen.is_public?
redirect_to frontend_screen_path(screen), status: :moved_permanently
else
render text: 'Forbidden.', status: 403
end
else
render text: "Screen not found.", status: 404
end
elsif @temp_token = (session[:screen_temp_token] || params[:screen_temp_token])
screen = Screen.find_by_temp_token @temp_token
if screen.nil?
send_temp_token
else
sign_in_screen screen
complete_auth(screen)
end
else
# We're going to store the temporary token in the session for
# browser clients, and send it via the body for API requests.
# Currently, the token is spoofable during the setup window,
# but the consequences are limited.
@temp_token = Screen.generate_temp_token
session[:screen_temp_token] = @temp_token
send_temp_token
end
end
def send_to_screen(screen)
respond_to do |format|
format.html { redirect_to frontend_screen_path(screen), status: :moved_permanently }
format.json { render json: {
screen_id: screen.id,
screen_url: screen_url(screen),
frontend_url: frontend_screen_url(screen)
} }
end
end
def send_temp_token
respond_to do |format|
format.html { render 'sign_in', layout: "no-topmenu" }
format.json { render json: {screen_temp_token: @temp_token} }
end
end
def complete_auth(screen)
respond_to do |format|
format.html { redirect_to frontend_screen_path(screen), status: :moved_permanently }
format.json { render json: {
screen_auth_token: screen.screen_token
} }
end
end
# GET /frontend/1/setup.json
# Get information required to setup the screen
# and display the template with positions.
def setup
allow_cors unless !ConcertoConfig[:public_concerto]
@preview = params.has_key?(:preview) && params[:preview] == "true"
begin
@screen = Screen.find(params[:id])
allow_screen_if_unsecured @screen
auth! action: (@preview ? :preview : :display)
rescue ActiveRecord::ActiveRecordError
render json: {}, status: 404
rescue CanCan::AccessDenied
render json: {}, status: 403
else
field_configs = [] # Cache the field_configs
@screen.run_callbacks(:frontend_display) do
# Inject paths into fake attribute so they gets sent with the setup info.
# Pretend that it's better not to change the format of the image, so we detect it's upload extension.
if [email protected]?
template_format = File.extname(@screen.template.media.preferred.first.file_name)[1..-1]
@screen.template.path = frontend_screen_template_path(@screen, @screen.template, format: template_format)
else
template_format = nil
@screen.template.path = nil
end
css_media = @screen.template.media.where({key: 'css'})
if !css_media.empty?
@screen.template.css_path = media_path(css_media.first)
end
@screen.template.positions.each do |p|
p.field_contents_path = frontend_screen_field_contents_path(@screen, p.field, format: :json)
p.field.config = {}
FieldConfig.default.where(field_id: p.field_id).each do |d_fc|
p.field.config[d_fc.key] = d_fc.value
field_configs << d_fc
end
@screen.field_configs.where(field_id: p.field_id).each do |fc|
p.field.config[fc.key] = fc.value
field_configs << fc
end
end
end
Rails.logger.debug("--frontend screencontroller setup is sending setup-key of #{@screen.frontend_cache_key}")
response.headers["X-Concerto-Frontend-Setup-Key"] = @screen.frontend_cache_key
@screen.time_zone = ActiveSupport::TimeZone::MAPPING[@screen.time_zone]
if stale?(etag: @screen.frontend_cache_key, public: true)
respond_to do |format|
format.json {
render json: @screen.to_json(
only: [:name, :id, :time_zone],
include: {
template: {
include: {
positions: {
except: [:created_at, :updated_at, :template_id, :field_id],
methods: [:field_contents_path],
include: {
field: {
methods: [:config],
only: [:id, :name, :config]
}
}
},
},
only: [:id, :name],
methods: [:path, :css_path]
}
}
)
}
end
end
unless @preview
@screen.mark_updated
end
end
end
end
|
package es.upm.fi.dia.oeg.mappingpedia.model
import org.apache.jena.enhanced.EnhGraph
import org.apache.jena.ontology.OntClass
import org.apache.jena.ontology.impl.OntClassImpl
import org.apache.jena.vocabulary.RDFS
import scala.collection.JavaConverters._
import scala.collection.JavaConversions._
/**
* Created by fpriyatna on 6/7/17.
*/
class OntologyClass (val ontClass:OntClass, val clsSuperclasses:List[OntClass], val clsSubClasses:List[OntClass]){
def getLocalName = ontClass.getLocalName;
def getURI = ontClass.getURI
def getDescription = ontClass.getPropertyValue(RDFS.comment).toString
def getSuperClassesLocalNames = this.clsSuperclasses.map(superClass => superClass.getLocalName).mkString(",")
def getSuperClassesURIs = this.clsSuperclasses.map(superClass => superClass.getURI).mkString(",")
def getSubClassesLocalNames = this.clsSubClasses.map(subClass => subClass.getLocalName).mkString(",")
def getSubClassesURIs = this.clsSubClasses.map(subClass => subClass.getURI).mkString(",")
}
|
#[macro_use]
extern crate clap;
extern crate failure;
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate nom;
#[macro_use]
extern crate log;
extern crate env_logger;
mod errors;
mod keywords;
mod parser;
mod scc;
mod types;
use clap::{App, Arg};
use errors::Error;
use failure::ResultExt;
use std::path::{Path, PathBuf};
use types::{Config, FileDescriptor};
fn run() -> Result<(), ::failure::Error> {
let matches = App::new(crate_name!())
.about(crate_description!())
.author(crate_authors!("\n"))
.version(crate_version!())
.arg(
Arg::with_name("OUTPUT")
.required(false)
.long("output")
.short("o")
.takes_value(true)
.help("Generated file name, defaults to INPUT with 'rs' extension")
.validator(|x| extension_matches(x, "rs")),
)
.arg(
Arg::with_name("OUTPUT_DIR")
.required(false)
.long("output_directory")
.short("d")
.takes_value(true)
.help("Output directory of generated code"),
)
.arg(
Arg::with_name("INCLUDE_PATH")
.required(false)
.long("include")
.short("I")
.takes_value(true)
.help("Path to search for imported protobufs"),
)
.arg(
Arg::with_name("SINGLE_MOD")
.required(false)
.long("single-mod")
.short("s")
.help("Omit generation of modules for each package when there is only one package"),
)
.arg(
Arg::with_name("NO_OUTPUT")
.required(false)
.long("no-output")
.short("n")
.help(
"Show enums and messages in this .proto file, including those imported. \
No code generated",
),
)
.arg(
Arg::with_name("INPUT")
.multiple(true)
.help("The .proto files used to generate quick-protobuf code")
.validator(|x| extension_matches(x, "proto")),
)
.arg(
Arg::with_name("CYCLE")
.long("error-cycle")
.short("e")
.required(false)
.help("Error out if recursive messages do not have optional fields"),
)
.get_matches();
let in_files = path_vec(values_t!(matches, "INPUT", String));
if in_files.is_empty() {
return Err(Error::NoProto.into());
}
for f in &in_files {
if !f.exists() {
return Err(Error::InputFile(format!("{}", f.display())).into());
}
}
let mut include_path = path_vec(values_t!(matches, "INCLUDE_PATH", String));
let default = PathBuf::from(".");
if include_path.is_empty() || !include_path.contains(&default) {
include_path.push(default);
}
if in_files.len() > 1 && matches.value_of("OUTPUT").is_some() {
return Err(Error::OutputMultipleInputs.into());
}
for in_file in in_files {
let mut out_file = in_file.with_extension("rs");
if let Some(ofile) = matches.value_of("OUTPUT") {
out_file = PathBuf::from(ofile);
} else if let Some(dir) = matches.value_of("OUTPUT_DIR") {
let mut directory = PathBuf::from(dir);
if !directory.is_dir() {
return Err(Error::OutputDirectory(format!("{}", directory.display())).into());
}
directory.push(out_file.file_name().unwrap());
out_file = directory;
}
let config = Config {
in_file: in_file,
out_file: out_file,
single_module: matches.is_present("SINGLE_MOD"),
import_search_path: include_path.clone(),
no_output: matches.is_present("NO_OUTPUT"),
error_cycle: matches.is_present("CYCLE"),
};
FileDescriptor::write_proto(&config).context(format!(
"Could not convert {} into {}",
config.in_file.display(),
config.out_file.display()
))?;
}
Ok(())
}
fn extension_matches<P: AsRef<Path>>(path: P, expected: &str) -> std::result::Result<(), String> {
match path.as_ref().extension() {
Some(x) if x == expected => Ok(()),
Some(x) => Err(format!(
"Expected path with extension '{}', not: '{}'",
expected,
x.to_string_lossy()
)),
None => Err(format!("Expected path with extension '{}'", expected)),
}
}
fn path_vec(maybe_vec: std::result::Result<Vec<String>, clap::Error>) -> Vec<PathBuf> {
maybe_vec
.unwrap_or_else(|_| Vec::new())
.iter()
.map(|s| s.into())
.collect()
}
fn main() {
env_logger::init();
::std::process::exit({
if let Err(e) = run() {
eprintln!("pb-rs fatal error");
for e in e.iter_chain() {
eprintln!(" - {}", e);
}
1
} else {
0
}
});
}
|
package com.mathbot.pay.bitcoin
import com.mathbot.pay.bitcoin.TransactionCategory.TransactionCategory
import com.mathbot.pay.json.PlayJsonSupport
import play.api.libs.json.{Json, OFormat}
case class Detail(address: BtcAddress, amount: Btc, category: TransactionCategory, vout: Int)
object Detail extends PlayJsonSupport {
implicit val formatDetail: OFormat[Detail] = Json.format[Detail]
}
|
---
title: "How to: Programmatically create an email item"
description: Learn how you can programmatically create an email message in Microsoft Outlook by using Visual Studio.
ms.custom: SEO-VS-2020
ms.date: "02/02/2017"
ms.topic: "how-to"
dev_langs:
- "VB"
- "CSharp"
helpviewer_keywords:
- "e-mail [Office development in Visual Studio], creating"
- "Outlook [Office development in Visual Studio], creating e-mail"
- "mail items [Office development in Visual Studio], creating"
author: John-Hart
ms.author: johnhart
manager: jmartens
ms.workload:
- "office"
---
# How to: Programmatically create an email item
This example creates an email message in Microsoft Office Outlook.
[!INCLUDE[appliesto_olkallapp](../vsto/includes/appliesto-olkallapp-md.md)]
## Example
[!code-csharp[Trin_OL_CreateMailItem#1](../vsto/codesnippet/CSharp/Trin_OL_CreateMailItem/thisaddin.cs#1)]
## See also
- [Work with mail items](../vsto/working-with-mail-items.md)
- [Get started programming VSTO Add-ins](../vsto/getting-started-programming-vsto-add-ins.md)
|
#!/usr/bin/env bash
set -e
if command -v codecov > /dev/null 2>&1; then
echo The command codecov is available
else
echo The command codecov is not available, installing...
set -x
echo Importing Codecov PGP public keys...
curl https://keybase.io/codecovsecurity/pgp_keys.asc | gpg --import
echo Downloading codecov uploader...
curl -Os https://uploader.codecov.io/latest/linux/codecov
echo Downloading SHA signatures...
curl -Os https://uploader.codecov.io/latest/linux/codecov.SHA256SUM
curl -Os https://uploader.codecov.io/latest/linux/codecov.SHA256SUM.sig
echo Verifying package integrity...
sha256sum -c codecov.SHA256SUM
gpg --verify codecov.SHA256SUM.sig codecov.SHA256SUM
echo Validation successful, completing installation...
chmod +x codecov
rm codecov.SHA256SUM
rm codecov.SHA256SUM.sig
sudo mv codecov /usr/bin/
fi
|
package queue
import (
"encoding/json"
"fmt"
"math/rand"
"reflect"
)
type PermissionVerb string
const (
PermissionVerbSubmit PermissionVerb = "submit"
PermissionVerbCancel PermissionVerb = "cancel"
PermissionVerbReprioritize PermissionVerb = "reprioritize"
PermissionVerbWatch PermissionVerb = "watch"
)
// NewPermissionVerb returns PermissionVerb from input string. If input string doesn't match
// one of allowed verb values ["submit", "cancel", "reprioritize", "watch"], and error is returned.
func NewPermissionVerb(in string) (PermissionVerb, error) {
switch verb := PermissionVerb(in); verb {
case PermissionVerbSubmit, PermissionVerbCancel, PermissionVerbReprioritize, PermissionVerbWatch:
return verb, nil
default:
return "", fmt.Errorf("invalid queue permission verb: %s", in)
}
}
// UnmarshalJSON is implementation of https://pkg.go.dev/encoding/json#Unmarshaler interface.
func (verb *PermissionVerb) UnmarshalJSON(data []byte) error {
permissionVerb := ""
if err := json.Unmarshal(data, &permissionVerb); err != nil {
return err
}
out, err := NewPermissionVerb(permissionVerb)
if err != nil {
return fmt.Errorf("failed to unmarshal queue permission verb: %s", err)
}
*verb = out
return nil
}
// Generate is implementation of https://pkg.go.dev/testing/quick#Generator interface.
// This method is used for writing tests usign https://pkg.go.dev/testing/quick package
func (verb PermissionVerb) Generate(rand *rand.Rand, size int) reflect.Value {
values := AllPermissionVerbs()
return reflect.ValueOf(values[rand.Intn(len(values))])
}
type PermissionVerbs []PermissionVerb
// NewPermissionVerbs returns PermissionVerbs from string slice. Every string from
// slice is transformed into PermissionVerb. Error is returned if a string cannot
// be transformed to PermissionVerb.
func NewPermissionVerbs(verbs []string) (PermissionVerbs, error) {
result := make([]PermissionVerb, len(verbs))
for index, verb := range verbs {
validVerb, err := NewPermissionVerb(verb)
if err != nil {
return nil, fmt.Errorf("failed to map verb string with index: %d. %s", index, err)
}
result[index] = validVerb
}
return result, nil
}
// AllPermissionVerbs returns PermissionsVerbs containing all PermissionVerb values
func AllPermissionVerbs() PermissionVerbs {
return []PermissionVerb{
PermissionVerbSubmit,
PermissionVerbCancel,
PermissionVerbReprioritize,
PermissionVerbWatch,
}
}
|
; Tell NASM where the kernel expects to be loaded into
[org 0x1000]
; using 32-bit protected mode
[bits 32]
jmp _main
_main:
; Clear the screen
call clear_screen
; Write loaded message at (0x0, 0x0)
mov eax, 0x0
mov edx, 0x0
call get_offset
mov ebx, MSG_KERNEL_LOADED
call kprint_at
; Write inital message at (0x0, 0x1)
mov eax, 0x1
mov edx, 0x0
call get_offset
mov ebx, MSG_HELLO
call kprint_at
; Write OS Name at (0x0, 0x2)
mov eax, 0x2
mov edx, 0x0
call get_offset
mov ebx, OS_NAME
call kprint_at
;; Check keyboard register polling status
call refresh_kbd_status
call _disks
jmp _output
_user_input_loop:
;; Get the last key up
call get_kbd_keyup
cmp al, 0x90
je _exit
cmp al, 0xAE
je _user_input_clear
cmp al, 0x94
je _user_input_text
cmp al, 0x97
jne _output
mov eax, [PORT]
add eax, 4
test eax, 4
jnz _user_input_exit_f
add eax, 8
_user_input_exit_f:
mov [PORT], eax
jmp _output
_user_input_clear:
call clear_screen
jmp _output
_user_input_text:
_user_input_text_loop:
call get_kbd_keyup
cmp al, 0x81
je _output
call key_to_ascii
test cl, 1
jnz _user_input_text_loop
call kprint_ch
jmp _user_input_text_loop
_output:
;; output last keyup at (0x46, 0x9)
mov ecx, eax
mov eax, 0x9
mov edx, 0x46
call output_stack_32
;; output port to (0x46, 0x9)
mov dx, [PORT]
in eax, dx
mov ecx, eax
mov eax, 0xA
mov edx, 0x46
call output_stack_32
;; Output register contents (a,b,c,d,si,di,bp,sp)
;; at right edge at top of screen
mov ecx, ecx
mov eax, 0x2
mov edx, 0x46
call output_stack_32
mov ecx, ebx
mov eax, 0x1
mov edx, 0x46
call output_stack_32
mov ecx, eax
mov eax, 0x0
mov edx, 0x46
call output_stack_32
mov ecx, edx
mov eax, 0x3
mov edx, 0x46
call output_stack_32
mov ecx, esi
mov eax, 0x4
mov edx, 0x46
call output_stack_32
mov ecx, edi
mov eax, 0x5
mov edx, 0x46
call output_stack_32
mov ecx, esp
mov eax, 0x6
mov edx, 0x46
call output_stack_32
mov ecx, ebp
mov eax, 0x7
mov edx, 0x46
call output_stack_32
;; Wait
mov ebx, 0x03FFFFFF
call wait_b
jmp _user_input_loop
_exit:
;; Shutdown the machine
call shutdown
;; If the shutdown failed, return to bootloader (which goes to inf loop)
ret
; Messages
MSG_KERNEL_LOADED db "Eden Loaded!", 0 ; Zero Terminated String
MSG_HELLO db "In the beginning, God created the heavens and the earth", 0
BASE_HEX db "0x00000000", 0 ; Zero Terminated
OS_NAME db "LogOS", 0 ; Zero Terminated
LAST_KEY db 0
PORT dw 0x0000
; this is how constants are defined
VIDEO_MEMORY equ 0xb8000
VIDEO_MEMORY_MAX equ 0x7D0
WHITE_ON_BLACK equ 0x17 ; the color byte for each character
; Kernel modules
%include "Scrolls/print.asm"
%include "Scrolls/cursor.asm"
%include "Scrolls/keyboard.asm"
%include "Scrolls/sys.asm"
%include "Scrolls/mem.asm"
%include "Scrolls/screen.asm"
%include "Spirit/idt.asm"
_disks:
xor ax,ax
mov es,ax
WriteToMbr:
mov dx,1f6h ;Drive and head port
mov al,0a0h ;Drive 0, head 0
out dx,al
mov dx,1f2h ;Sector count port
mov al,1 ;Write one sector
out dx,al
mov dx,1f3h ;Sector number port
mov al,1 ;Wrote to sector one
out dx,al
mov dx,1f4h ;Cylinder low port
mov al,0 ;Cylinder 0
out dx,al
mov dx,1f5h ;Cylinder high port
mov al,0 ;The rest of the cylinder 0
out dx,al
mov dx,1f7h ;Command port
mov al,30h ;Write with retry.
out dx,al
_disk_waiting:
in al,dx
test al,8 ;Wait for sector buffer ready.
jz _disk_waiting
mov cx,512/2 ;One sector /2
mov si, 0x1000
mov dx,1f0h ;Data port - data comes in and out of here.
rep outsw
ret
|
using System;
using FluentValidation;
using FluxoDeCaixa.Domain.Lancamentos;
namespace FluxoDeCaixa.Application.Lancamentos
{
public class ValidadorCommandRecebimento : AbstractValidator<CriarRecebimentoCommand>
{
public ValidadorCommandRecebimento()
{
CascadeMode = CascadeMode.StopOnFirstFailure;
RuleFor(recebimento => recebimento.Descricao)
.NotEmpty()
.WithMessage("Descrição do recebimento é Obrigatória");
RuleFor(recebimento => recebimento.Documento)
.NotEmpty()
.WithMessage("Documento do recebimento é Obrigatório");
RuleFor(recebimento => recebimento.ContaDestino)
.NotNull()
.NotEmpty()
.WithMessage("Dados da conta de destino do recebimento são Obrigatórios");
RuleFor(recebimento => recebimento.ValorLancamento)
.GreaterThan(0)
.WithMessage("Valor do lançamento do recebimento deve ser maior que zero.");
RuleFor(recebimento => recebimento.ValorEncargos)
.GreaterThanOrEqualTo(0)
.WithMessage("Encargos de recebimento não podem ser menor que zero.");
RuleFor(recebimento => recebimento.DataDeLancamento)
.GreaterThanOrEqualTo(recebimento => DateTime.Now.Date)
.WithMessage("A data de lançamento do recebimento não pode ser retroativo.");
RuleFor(pagamento => pagamento.TipoDeConta)
.NotNull()
.NotEmpty()
.WithMessage("O Tipo de Conta informado para este pagamento está inválido");
}
}
} |
# Demo projects
## MIRNet with TensorRT in Python
https://github.com/NobuoTsukamoto/tensorrt-examples/blob/main/python/mirnet/README.md |
require "typhoeus"
require "adamantium"
require "concord"
require "anima"
require "json"
require "active_support/core_ext/hash/keys"
require "active_support/core_ext/hash/except"
require "active_support/core_ext/object/to_query"
require "active_support/core_ext/hash/conversions"
require "uri"
require "ostruct"
require "active_support/time_with_zone"
require "awesome_print"
require "digital_river/config"
module DigitalRiver
class BasicError < StandardError
# Create an exception base on the APIs error type
#
# @param [String] id
# @param [String] message
#
# @return [BasicError]
#
# @api public
#
# @example
# error = BasicError.build("system-error", "An internal server error occured")
def self.build(id, message)
case id
when "invalid_token"
InvalidTokenError
when "resource-not-found"
ResourceNotFound
when "invalid_client"
InvalidClient
else
BasicError
end.new(message)
end
end
class InvalidTokenError < BasicError; end;
class InvalidClient < BasicError; end;
class ResourceNotFound < BasicError; end;
class << self
# Holds an config instance
#
# @return [Config]
#
# @api public
#
# @example
# DigitalRiver.config.url
# DigitalRiver.config.oauth_url
def config
@config ||= Config.new
end
end
end
require "digital_river/auth/refresh_token"
require "digital_river/auth/token"
require "digital_river/resource"
require "digital_river/resource/response"
require "digital_river/product_resource"
require "digital_river/product_resource/search"
require "digital_river/request"
require "digital_river/request/raw"
require "digital_river/request/debug"
require "digital_river/response"
require "digital_river/response/json"
require "digital_river/response/xml"
require "digital_river/response/error"
require "digital_river/session"
require "digital_river/session/json"
require "digital_river/session/xml"
require "digital_river/session/token"
require "digital_river/session/requester"
require "digital_river/shopper_resource"
require "digital_river/shopper_resource/update"
require "digital_river/line_items_resource"
require "digital_river/line_items_resource/all"
require "digital_river/line_items_resource/add"
require "digital_river/line_items_resource/update"
require "digital_river/line_items_resource/destroy"
require "digital_river/checkout_resource"
require "digital_river/auth"
|
require 'rails_helper'
require './features/support/omniauth'
RSpec.describe User, type: :model do
let(:user) { create(:user) }
describe 'Database table' do
it { is_expected.to have_db_column :email }
it { is_expected.to have_db_column :encrypted_password }
it { is_expected.to have_db_column :role }
end
describe 'Validation' do
it { is_expected.to validate_presence_of :email }
it { is_expected.to validate_presence_of :password }
it { is_expected.to validate_presence_of :full_name }
end
describe "Associations" do
it { is_expected.to have_one :collection }
it { is_expected.to have_many :recipes }
it { is_expected.to have_many :comments }
end
describe 'Factory' do
it 'can create a valid instance' do
expect(user).to be_valid
end
end
describe 'OAuth methods' do
let(:auth_response) {OmniAuth::AuthHash.new(OmniAuthFixtures.facebook_response)}
it "creates an instance from an oauth hash" do
create_user = lambda {User.from_omniauth(auth_response)
}
expect{create_user.call}.to change{User.count}.from(0).to(1)
end
end
describe 'User roles' do
let(:admin) {create :user, email: '[email protected]', role: :admin}
let(:user_1) {create :user, email: '[email protected]', role: :user}
it '#admin? responds true if user role is admin' do
expect(admin.admin?).to eq true
end
it '#admin? responds false if user role is NOT admin' do
expect(user_1.admin?).to eq false
end
it '#user? responds true if user role is user' do
expect(user_1.user?).to eq true
end
it '#user? responds false if user role is NOT user' do
expect(admin.user?).to eq false
end
end
end
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MarsClientLauncher
{
public class KeybindManager
{
public const string INTERN_GUI = "{INTERNAL_TOGGLEGUI}";
public List<KeybindGame> availableKeybinds = new List<KeybindGame>();
public List<Keybind> keybinds = new List<Keybind>();
public KeybindManager()
{
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = INTERN_GUI,
gameName = "TOGGLE IN-GAME GUI"
});
availableKeybinds.Add(new KeybindGame() {
gameInternalName = "play solo_normal",
gameName = "Skywars - Solo Normal"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play solo_insane",
gameName = "Skywars - Solo Insane"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play teams_normal",
gameName = "Skywars - Teams Normal"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play teams_insane",
gameName = "Skywars - Teams Insane"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play blitz_solo_normal",
gameName = "Blitz SG - Solo"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play blitz_teams_normal",
gameName = "Blitz SG - Teams"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play bedwars_eight_one",
gameName = "Bed Wars - Solo"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play bedwars_eight_one",
gameName = "Bed Wars - Doubles"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play bedwars_four_three",
gameName = "Bed Wars - 3v3v3v3"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play bedwars_four_four",
gameName = "Bed Wars - 4v4v4v4"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play sb",
gameName = "Skyblock"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_classic_duel",
gameName = "Duels - Solo Classic"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_sw_duel",
gameName = "Duels - Solo Skywars"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_uhc_duel",
gameName = "Duels - Solo UHC"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_op_duel",
gameName = "Duels - Solo OP"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_sumo_duel",
gameName = "Duels - Sumo"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_bridge_duel",
gameName = "Duels - Solo The Bridge"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_classic_doubles",
gameName = "Duels - Doubles Classic"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_sw_doubles",
gameName = "Duels - Doubles Skywars"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_uhc_doubles",
gameName = "Duels - Doubles UHC"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_op_doubles",
gameName = "Duels - Doubles OP"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play duels_bridge_doubles",
gameName = "Duels - Doubles The Bridge"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play murder_classic",
gameName = "Murder Mystery - Classic"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play murder_assassins",
gameName = "Murder Mystery - Assassins"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "play murder_infection",
gameName = "Murder Mystery - Infection"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "tipall",
gameName = "GENERAL KEYBINDS - Tip All"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "pl",
gameName = "GENERAL KEYBINDS - Party List"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "fl",
gameName = "GENERAL KEYBINDS - Friends List"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "fl",
gameName = "GENERAL KEYBINDS - Friends List"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "fl",
gameName = "GENERAL KEYBINDS - Friends List"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "chat a",
gameName = "GENERAL KEYBINDS - All Chat Mode"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "chat p",
gameName = "GENERAL KEYBINDS - Party Chat Mode"
});
availableKeybinds.Add(new KeybindGame()
{
gameInternalName = "p warp",
gameName = "GENERAL KEYBINDS - Warp Party"
});
}
public void AddKeybind(string gameName, Keys key)
{
KeybindGame game = null;
foreach(var test in availableKeybinds)
{
if (test.gameName.Equals(gameName))
{
game = test; break;
}
}
if (game == null) return;
keybinds.Add(new Keybind()
{
game = game,
key = key
});
}
public void AddKeybind(Keybind kb)
{
keybinds.Add(kb);
}
public void ReplaceKeybind(Keybind a, Keybind b)
{
Keybind[] arr = keybinds.ToArray();
for(int i = 0; i < arr.Length; i++)
{
Keybind current = arr[i];
if(current.Equals(a))
arr[i] = b;
}
keybinds = arr.ToList();
}
public void DeleteKeybind(Keybind k)
{
keybinds.Remove(k);
}
public string Serialize()
{
List<string> serialized = new List<string>();
foreach(Keybind kb in keybinds)
serialized.Add(kb.game.gameName + "|" + ((int)kb.key));
return string.Join("#", serialized);
}
public static KeybindManager Deserialize(string input)
{
KeybindManager mgr = new KeybindManager();
string[] kbs = input.Split(new char[]{ '#' },
StringSplitOptions.RemoveEmptyEntries);
foreach(string kb in kbs)
{
string[] parts = kb.Split('|');
string gameName = parts[0];
Keys key = (Keys)int.Parse(parts[1]);
mgr.AddKeybind(gameName, key);
}
return mgr;
}
}
public class KeybindGame
{
public string gameName;
public string gameInternalName;
public override string ToString()
{
return gameName;
}
}
public class Keybind
{
public Keys key;
public KeybindGame game;
public override string ToString()
{
return "(" + game.ToString() + "), CTRL+" + key.ToString();
}
}
}
|
<?php
namespace Skvn\Crud\Models;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Model;
use Skvn\Crud\Traits\ModelAttachedTrait;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class CrudFile extends Model
{
use ModelAttachedTrait;
protected $table = 'crud_file';
protected $guarded = ['id'];
protected $app;
public function __construct(array $attributes = [])
{
parent :: __construct($attributes);
$this->app = Container :: getInstance();
}
public function setCreatedAtAttribute($value)
{
if (is_object($value)) {
$value = $value->timestamp;
} else {
$value = strtotime($value);
}
$this->attributes['created_at'] = $value;
}
public function setUpdatedAtAttribute($value)
{
if (is_object($value)) {
$value = $value->timestamp;
} else {
$value = strtotime($value);
}
$this->attributes['updated_at'] = $value;
}
public static function createFromUpload(UploadedFile $file)
{
$instance = new self();
$file_data = $instance->attachCreateFileInfo();
$instance->attachStoreFile($file_data);
// $dest = AttachmentHandler::generateSaveFilename($file_data);
// \File::makeDirectory(dirname($dest), 0755, true, true);
// if (file_exists($dest))
// {
// unlink($dest);
// }
//
// $file->move(dirname($dest), basename($dest));
//
// $instance->fill(['file_name' => $file_data['originalName'],
// 'mime_type' => $file_data['originalMime'],
// 'file_size' => $file_data['originalSize'],
// 'title' => (!empty($file_data['title'])?$file_data['title']:''),
// 'path' => $dest
// ]);
// $instance->save();
return $instance;
}
}
|
require 'spec_helper'
describe CdmBatch::ETDLoader do
before(:all) do
@etds = CdmBatch::ETDLoader.new(File.join(%W{fixtures etd-data etd_tab.txt}))
end
describe "how the data should be parsed" do
it 'parses ETD file into an aray item per row' do
expect(@etds.data.length).to eq(2)
end
it 'creates a hash for each row' do
@etds.data.each do |row|
expect(row).to be_an_instance_of Hash
end
end
describe "how the data for each record is stored" do
it 'has author date' do
expect(@etds.data[0][:author]).to eq "McTesterson, Test Y"
expect(@etds.data[1][:author]).to eq "Datapoint, Ima Mock"
end
it 'has title data' do
expect(@etds.data[0][:title]).to eq "Influences of Testing on Code Quality"
end
it 'has filename data' do
expect(@etds.data[0][:"file_name"]).to eq "TETDEDXMcTesterson-temple-12345-6789.pdf"
expect(@etds.data[1][:"file_name"]).to eq "TETDEDXDatapoint-temple-12345-6789.pdf"
end
end
end
describe 'how the path to the etd data and pdfs is exposed'
it 'exposes basepath attr' do
expect(@etds.basepath).to eq File.join(%W{fixtures etd-data})
end
describe '#file_check' do
it 'throws an error of a file is not present' do
missing_files = File.join(%W{fixtures etd-data etd_missing_files.txt})
expect {CdmBatch::ETDLoader.new(missing_files)}.to raise_exception(IOError)
end
end
end
|
<?php
/**
* Automated deletion of TrackBack pings that have not been approved
* within a certain time span.
*
* @category pearweb
* @author Tobias Schlitt <[email protected]>
* @copyright Copyright (c) 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License
* @version $Id$
*/
/**
* Get common settings.
*/
require_once dirname(__FILE__) . '/../include/pear-config.php';
/**
* Obtain the system's common functions and classes.
*/
require_once dirname(__FILE__) . '/../include/pear-database.php';
/**
* Get the database class.
*/
require_once 'DB.php';
$options = array(
'persistent' => false,
'portability' => DB_PORTABILITY_ALL,
);
$dbh =& DB::connect(PEAR_DATABASE_DSN, $options);
if (DB::isError($dbh)) {
die("Failed to connect: $dsn\n");
}
$sql = 'DELETE FROM trackbacks WHERE timestamp <= '.(time() - TRACKBACK_PURGE_TIME).' AND approved = "false"';
if (PEAR::isError($res = $dbh->query($sql))) {
die("SQL <" . $sql . "> returned error: <" . $res->getMessage() . ">.\n");
}
|
export default class Client {
constructor(pageSize: number) {
this.pageSize = pageSize;
}
pageSize: number;
}
|
-module(s5c_s2).
-export([main/2,
get_user/2, get_users/1,
create_user/3,
get_stats/1,
get_usage/2, get_access/2]).
main(["get", "user", KeyId], Opts) -> get_user(KeyId, Opts);
main(["get", "users"], Opts) -> get_users(Opts);
main(["create", "user", Name, Address], Opts) -> create_user(Name, Address, Opts);
main(["get", "stats"], Opts) -> get_stats(Opts);
main(["get", "usage" | User], Opts) -> get_usage(User, Opts);
main(["get", "access"| User], Opts) -> get_access(User, Opts).
get_user(_, _) -> ok.
get_users(_Opts) ->
URL = "http://riak-cs.s3.amazonaws.com/users",
Req = s5c_http:new_request(URL, [{header, "accept: application/json"},
{proxy, "localhost:8080"}]),
Req1 = s5c_s3:sign(Req, local),
{ok, Conn} = s5c_http:connect(Req1),
ok = s5c_http:send(Req1),
{ok, Res} = s5c_http:recv(Conn),
ok = s5c_http:disconnect(Conn),
{chunked, Chunks} = s5c_http:body(Res),
pp_header(Chunks),
[begin
case proplists:get_value('Content-Type', Hdrs) of
<<"application/json">> ->
lists:foreach(fun pp_user/1,
jsone:decode(Body));
_ ->
pass
end
end || {Hdrs, Body} <- Chunks].
create_user(_, _, _) -> ok.
get_stats(_) ->
URL = "http://riak-cs.s3.amazonaws.com/stats",
Req = s5c_http:new_request(URL, [{header, "accept: application/json"},
{proxy, "localhost:8080"}]),
Req1 = s5c_s3:sign(Req, local),
{ok, Conn} = s5c_http:send(Req1),
{ok, Res} = s5c_http:recv(Conn),
{raw, Json} = s5c_http:body(Res),
io:format("~p", [jsone:decode(Json)]).
get_usage("", _Opts) ->
error;
get_usage(User, _Opts) when is_list(User) ->
Start = "20150801T000000Z",
%%Start = proplists:get(
End = "20150901T000000Z",
Path = filename:join(["/", User, "bj", Start, End]),
URL = "http://riak-cs.s3.amazonaws.com/usage/" ++ Path,
Req = s5c_http:new_request(URL, [{header, "accept: application/json"},
{proxy, "localhost:8080"}]),
Req1 = s5c_s3:sign(Req, local),
{ok, Conn} = s5c_http:connect(Req),
ok = s5c_http:send(Conn, Req1),
{ok, Res} = s5c_http:recv(Conn),
io:format("~p", [s5c_http:body(Res)]).
get_access(_, _) -> ok.
%% Internal Functions
pp_header([]) -> pass;
pp_header(_Chunks) ->
io:format("~-20s\t~-10s\tname~n", [key_id, key_secret]).
-spec pp_user({proplists:proplist()}) -> no_return().
pp_user({User}) ->
%% io:format("~p~n", [User]),
KeyId = proplists:get_value(<<"key_id">>, User),
Name = proplists:get_value(<<"name">>, User),
KeySecret = proplists:get_value(<<"key_secret">>, User),
io:format("~-20s\t~-5s...\t~s~n", [KeyId, KeySecret, Name]).
|
import React from 'react';
export default function RoomListOptions({ selectedRoom, onJoinPressed, onCreatePressed, onLeavePreviousPressed }) {
const onJoin = () => onJoinPressed({ room: selectedRoom });
const onCreate = () => onCreatePressed({});
return (
<div className="d-flex flex-column align-items-center justify-content-around">
<div className="text-center">
<div className="display-4 text-orange qd-text-outline qd-text-title">
Guess the{' '}
<span className="text-pink">D</span>
<span className="text-teal">R</span>
<span className="text-indigo">A</span>
<span className="text-yellow">W</span>
<span className="text-cyan">I</span>
<span className="text-red">N</span>
<span className="text-green">G</span>!
</div>
by Veselin Karaganev
</div>
<div className="d-flex">
<button className="btn btn-primary mx-3" disabled={!selectedRoom} type="button" onClick={onJoin}>
Join Room
</button>
<button className="btn btn-secondary mx-3" type="button" onClick={onCreate}>
Create Room
</button>
</div>
<button className="btn btn-outline-secondary mx-3" type="button" onClick={onLeavePreviousPressed}>
Leave all rooms
</button>
</div>
);
}
|
from __future__ import absolute_import
from .helper import SolveBioTestCase
class LookupTests(SolveBioTestCase):
def setUp(self):
super(LookupTests, self).setUp()
self.dataset = self.client.Object.get_by_full_path(
self.TEST_DATASET_FULL_PATH)
def test_lookup_error(self):
# Check that incorrect lookup results in empty list.
lookup_one = self.dataset.lookup('test')
self.assertEqual(lookup_one, [])
lookup_two = self.dataset.lookup('test', 'nothing')
self.assertEqual(lookup_two, [])
def test_lookup_correct(self):
# Check that lookup with specific sbid is correct.
records = list(self.dataset.query(limit=2))
record_one = records[0]
record_two = records[1]
sbid_one = record_one['_id']
sbid_two = record_two['_id']
lookup_one = self.dataset.lookup(sbid_one)
self.assertEqual(lookup_one[0], record_one)
lookup_two = self.dataset.lookup(sbid_two)
self.assertEqual(lookup_two[0], record_two)
# Check that combining sbids returns list of correct results.
joint_lookup = self.dataset.lookup(sbid_one, sbid_two)
self.assertEqual(joint_lookup[0], record_one)
self.assertEqual(joint_lookup[1], record_two)
|
<?php
namespace Aws\CloudHSMV2;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS CloudHSM V2** service.
* @method \Aws\Result copyBackupToRegion( array $args = [] )
* @method \GuzzleHttp\Promise\Promise copyBackupToRegionAsync( array $args = [] )
* @method \Aws\Result createCluster( array $args = [] )
* @method \GuzzleHttp\Promise\Promise createClusterAsync( array $args = [] )
* @method \Aws\Result createHsm( array $args = [] )
* @method \GuzzleHttp\Promise\Promise createHsmAsync( array $args = [] )
* @method \Aws\Result deleteBackup( array $args = [] )
* @method \GuzzleHttp\Promise\Promise deleteBackupAsync( array $args = [] )
* @method \Aws\Result deleteCluster( array $args = [] )
* @method \GuzzleHttp\Promise\Promise deleteClusterAsync( array $args = [] )
* @method \Aws\Result deleteHsm( array $args = [] )
* @method \GuzzleHttp\Promise\Promise deleteHsmAsync( array $args = [] )
* @method \Aws\Result describeBackups( array $args = [] )
* @method \GuzzleHttp\Promise\Promise describeBackupsAsync( array $args = [] )
* @method \Aws\Result describeClusters( array $args = [] )
* @method \GuzzleHttp\Promise\Promise describeClustersAsync( array $args = [] )
* @method \Aws\Result initializeCluster( array $args = [] )
* @method \GuzzleHttp\Promise\Promise initializeClusterAsync( array $args = [] )
* @method \Aws\Result listTags( array $args = [] )
* @method \GuzzleHttp\Promise\Promise listTagsAsync( array $args = [] )
* @method \Aws\Result restoreBackup( array $args = [] )
* @method \GuzzleHttp\Promise\Promise restoreBackupAsync( array $args = [] )
* @method \Aws\Result tagResource( array $args = [] )
* @method \GuzzleHttp\Promise\Promise tagResourceAsync( array $args = [] )
* @method \Aws\Result untagResource( array $args = [] )
* @method \GuzzleHttp\Promise\Promise untagResourceAsync( array $args = [] )
*/
class CloudHSMV2Client extends AwsClient {
}
|
package com.badoo.ribs.example.rib.dialog_example
import android.os.Bundle
import android.os.Parcelable
import com.badoo.ribs.core.Router
import com.badoo.ribs.core.routing.action.DialogRoutingAction.Companion.showDialog
import com.badoo.ribs.core.routing.action.RoutingAction
import com.badoo.ribs.core.routing.action.RoutingAction.Companion.noop
import com.badoo.ribs.dialog.DialogLauncher
import com.badoo.ribs.example.rib.dialog_example.DialogExampleRouter.Configuration
import com.badoo.ribs.example.rib.dialog_example.DialogExampleRouter.Configuration.Content
import com.badoo.ribs.example.rib.dialog_example.DialogExampleRouter.Configuration.Overlay
import com.badoo.ribs.example.rib.dialog_example.dialog.LazyDialog
import com.badoo.ribs.example.rib.dialog_example.dialog.RibDialog
import com.badoo.ribs.example.rib.dialog_example.dialog.SimpleDialog
import kotlinx.android.parcel.Parcelize
class DialogExampleRouter(
savedInstanceState: Bundle?,
private val dialogLauncher: DialogLauncher,
private val simpleDialog: SimpleDialog,
private val lazyDialog: LazyDialog,
private val ribDialog: RibDialog
): Router<Configuration, Nothing, Content, Overlay, DialogExampleView>(
savedInstanceState = savedInstanceState,
initialConfiguration = Content.Default
) {
sealed class Configuration : Parcelable {
sealed class Content : Configuration() {
@Parcelize object Default : Content()
}
sealed class Overlay : Configuration() {
@Parcelize object SimpleDialog : Overlay()
@Parcelize object LazyDialog : Overlay()
@Parcelize object RibDialog : Overlay()
}
}
override fun resolveConfiguration(configuration: Configuration): RoutingAction<DialogExampleView> =
when (configuration) {
is Content.Default -> noop()
is Overlay.SimpleDialog -> showDialog(this, dialogLauncher, simpleDialog)
is Overlay.LazyDialog -> showDialog(this, dialogLauncher, lazyDialog)
is Overlay.RibDialog -> showDialog(this, dialogLauncher, ribDialog)
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;
using Topics.Radical.Win32;
using System.Windows.Interop;
namespace Topics.Radical.Windows.Behaviors
{
public sealed class WindowControlBoxBehavior : Behavior<Window>
{
//#region Dependency Property: AllowMaximize
//public static readonly DependencyProperty AllowMaximizeProperty = DependencyProperty.Register(
// "AllowMaximize",
// typeof( Boolean ),
// typeof( WindowControlBoxBehavior ),
// new PropertyMetadata( true ) );
//public Boolean AllowMaximize
//{
// get { return ( Boolean )this.GetValue( AllowMaximizeProperty ); }
// set { this.SetValue( AllowMaximizeProperty, value ); }
//}
//#endregion
public Boolean AllowMaximize
{
get;
set;
}
//#region Dependency Property: AllowMinimize
//public static readonly DependencyProperty AllowMinimizeProperty = DependencyProperty.Register(
// "AllowMinimize",
// typeof( Boolean ),
// typeof( WindowControlBoxBehavior ),
// new PropertyMetadata( true ) );
//public Boolean AllowMinimize
//{
// get { return ( Boolean )this.GetValue( AllowMinimizeProperty ); }
// set { this.SetValue( AllowMinimizeProperty, value ); }
//}
//#endregion
public Boolean AllowMinimize
{
get;
set;
}
EventHandler h;
/// <summary>
/// Initializes a new instance of the <see cref="WindowControlBoxBehavior"/> class.
/// </summary>
public WindowControlBoxBehavior()
{
h = ( s, e ) =>
{
var isDesign = DesignTimeHelper.GetIsInDesignMode();
var hWnd = new WindowInteropHelper( this.AssociatedObject ).Handle;
if( !isDesign && hWnd != IntPtr.Zero && ( !this.AllowMaximize || !this.AllowMinimize ) )
{
var windowLong = NativeMethods.GetWindowLong( hWnd, WindowLong.Style ).ToInt32();
if( !this.AllowMaximize )
{
windowLong = windowLong & ~Constants.WS_MAXIMIZEBOX;
}
if( !this.AllowMinimize )
{
windowLong = windowLong & ~Constants.WS_MINIMIZEBOX;
}
NativeMethods.SetWindowLong( hWnd, WindowLong.Style, ( IntPtr )windowLong );
}
};
}
/// <summary>
/// Called after the behavior is attached to an AssociatedObject.
/// </summary>
/// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.SourceInitialized += h;
}
/// <summary>
/// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
/// </summary>
/// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
protected override void OnDetaching()
{
this.AssociatedObject.SourceInitialized -= h;
base.OnDetaching();
}
}
}
|
# MyNewApp

## Description
An app that does amazing things!
## Table of Contents
* [Installation](#installation)
* [Usage](#usage)
* [Contributing](#contributing)
* [Tests](#tests)
* [Questions](#questions)
* [License](#license)
## Installation
To install MyNewApp:
1. Download the source code and copy to a new directory.
2. Open a terminal window and navigate to the new directory.
3. Run 'npm install'.
## Usage
1. Open a terminal window and navigate to the application directory.
2. Run 'node index.js'.
## Contributing
If you would like to contribute to this project please follow these guidelines:
Please read 'contribution-guidelines.md' for further information.
## Tests
Recommended testing procedures:
1. Open a terminal window and navigate to the application directory.
2. Run 'npm test'.
## Questions
Questions? Comments? Suggestions? Please get in touch.
Gitlab: https://github.com/myusername
Email: [[email protected]](mailto:[email protected])
## License
This project is licensed under the MIT License.
|
require File.dirname(__FILE__) + '/test_helper.rb'
Dir[File.dirname(__FILE__) + '/*_spec.rb'].each{ |f| require f} |
package org.jd.benoggl.models
enum class Suit {
ACORNS, LEAVES, HEARTS, BELLS
} |
import { configureStore } from '@reduxjs/toolkit';
import {
name as boardsReducerName,
reducer as boardsReducer,
} from './boardsSlice';
import {
name as columnsReducerName,
reducer as columnsReducer,
} from './columnsSlice';
import {
name as itemsReducerName,
reducer as itemsReducer,
} from './itemsSlice';
import {
name as likesReducerName,
reducer as likesReducer,
} from './likesSlice';
import { name as userReducerName, reducer as userReducer } from './userSlice';
const store = configureStore({
reducer: {
[boardsReducerName]: boardsReducer,
[columnsReducerName]: columnsReducer,
[itemsReducerName]: itemsReducer,
[likesReducerName]: likesReducer,
[userReducerName]: userReducer,
},
});
export default store;
|
class AddIndicies < ActiveRecord::Migration
def up
add_index :address_ranges, :geocode_id
add_index :coordinates, :assignment_zone_id
add_index :geocode_grade_walkzone_schools, :geocode_id
add_index :geocode_grade_walkzone_schools, :grade_level_id
add_index :geocode_grade_walkzone_schools, :school_id
add_index :geocodes, :assignment_zone_id
add_index :neighborhoods, :city_id
add_index :schools, :neighborhood_id
add_index :schools, :parcel_id
add_index :schools, :permalink
end
def down
remove_index :address_ranges, :geocode_id
remove_index :coordinates, :assignment_zone_id
remove_index :geocode_grade_walkzone_schools, :geocode_id
remove_index :geocode_grade_walkzone_schools, :grade_level_id
remove_index :geocode_grade_walkzone_schools, :school_id
remove_index :geocodes, :assignment_zone_id
remove_index :neighborhoods, :city_id
remove_index :schools, :neighborhood_id
remove_index :schools, :parcel_id
remove_index :schools, :permalink
end
end
|
package br.com.erudio.section08._0803
fun main() {
val students = getStudents()
val combos = students.map { a -> "${a.name} : ${a.age}"}
println("Combos: $combos")
println("The oldest student is: ${students.maxByOrNull { it.age }}")
println("Student with longest name is: ${students.filter { it.name.length > 5 }}")
} |
#!/usr/bin/env perl
use strict;
use warnings;
package Org::More::Utils;
sub trim($)
{
my $s = shift;
$s =~ s/^\s+//;
$s =~ s/\s+$//;
return $s;
}
1;
package Org::More::Tags;
use Exporter;
our @EXPORT_OK = qw(list_tags);
use Data::Dumper;
use Carp;
sub list_tags {
my $filename = shift;
my @collection = ();
open(my $fh, $filename) or carp "Could not open $filename: $!";
while(my $line = <$fh>) {
if ($line =~ m/^\#\+tags(\[\])?\:(.+)$/i) {
my $matches = Org::More::Utils::trim($2);
my @tags = split /\s/, $matches;
push @collection, @tags;
# print Dumper(@tags), "\n";
}
}
close $fh;
# print Dumper(@collection), "\n";
return @collection;
}
sub get_title {
my $filename = shift;
my $result = '';
open(my $fh, $filename) or die "Could not open $filename: $!";
while(my $line = <$fh>) {
if ($line =~ m/^\#\+title\:(.+)$/i) {
$result = Org::More::Utils::trim($1);
last;
}
}
close $fh;
return $result;
}
sub has_all {
my ($tags, $subset) = @_;
#print "Tags: ", Dumper($tags), "\n";
#print "Subset: ", Dumper($subset), "\n";
my $result = 1;
foreach my $t (@$subset) {
$result &&= scalar(grep { $_ eq $t } @$tags);
}
return $result != 0;
}
1;
package Org::More::Find;
use Exporter;
our @EXPORT_OK = qw(find_contains_all_in);
use File::Find qw(find);
sub find_contains_all_in {
die 'find_contains_all_in($dir, $tags_arr_ref)' if scalar @_ < 2;
my ($dir, $tags_arr_ref) = @_;
#print $dir, "\n";
#print @$tags_arr_ref, "\n";
find(sub{
# TODO skip `.git/**`?
# only `.org` files
if (!($_ =~ m/\.org$/)) {
return;
}
#print "[$File::Find::name]\n";
#
my $file = $File::Find::name;
my @tags = Org::More::Tags::list_tags($file);
if (Org::More::Tags::has_all(\@tags, $tags_arr_ref)){
my $title = Org::More::Tags::get_title($file);
print "[[file:$file]] :: $title\n";
}
}, $dir);
}
1;
package ::main;
use Data::Dumper;
{
die 'pls specify a mode in one of [find]' if scalar @ARGV < 1;
my $mode = $ARGV[0];
if ($mode eq 'find') {
my $dir = $ARGV[1] or die("pls specify a dir!");
my @tags = @ARGV[2..$#ARGV];
Org::More::Find::find_contains_all_in($dir, \@tags);
} else {
die "Unknown mode: $mode";
}
}
|
## Key Press event
When the user presses a key on the keyboard
### Javascript
```html
<script>
const input = document.getElementById("e3Js");
input.addEventListener("keypress", function (event) {
input.style.backgroundColor = "red";
});
</script>
```
#### Example:
Press a key inside the text field to set a red background color.
<input type="text" id="e3Js">
### jQuery
```html
<script>
$("#e3JQuery").on("keypress", function (event) {
$("#e3JQuery").css("backgroundColor", "blue");
});
</script>
```
#### Example:
Press a key inside the text field to set a blue background color.
<input type="text" id="e3JQuery">
|
import * as request from 'request-light';
import { Uri } from 'vscode';
import { configuration } from '../config';
import { Event, Issue, Organization, Project } from './interfaces';
import { getToken } from './rc';
async function xhr(options: request.XHROptions): Promise<request.XHRResponse> {
const serverUrl = configuration.getServerUrl();
const token = await getToken();
if (!token) {
throw new Error('Not authenticated with Sentry. Please provide an auth token.');
}
// Normalize the URL passed in options. If it is missing a scheme or
// serverUrl, the value configured in "sentry.serverUrl" is used instead.
const parsedUrl = Uri.parse(options.url || '');
const mergedUrl = Uri.parse(serverUrl).with(parsedUrl.toJSON());
return request.xhr({
...options,
headers: {
Authorization: `Bearer ${token}`,
...options.headers,
},
url: mergedUrl.toString(true),
});
// TODO: Handle common errors
}
async function get<T>(url: string): Promise<T> {
const response = await xhr({ type: 'GET', url });
return JSON.parse(response.responseText);
}
export async function searchIssues(input: string): Promise<Issue[]> {
// TODO: Allow customizing environments
const params = '&limit=25&sort=date&shortIdLookup=1';
const byProject = await Promise.all(
configuration.getProjects().map(project => {
const baseUrl = `/api/0/projects/${project}/issues/`;
const url = `${baseUrl}?query=${encodeURIComponent(input)}${params}`;
return get<Issue[]>(url);
}),
);
return byProject.reduce((all, next) => all.concat(next), []);
}
export async function loadLatestEvent(issue: Issue): Promise<Event> {
const url = `/api/0/issues/${issue.id}/events/latest/`;
return get<Event>(url);
}
export async function listProjects(): Promise<Project[]> {
const organizations = await get<Organization[]>('/api/0/organizations/');
if (organizations.length === 0) {
return [];
}
const orgs = await Promise.all(
organizations.map(async organization => {
const url = `/api/0/organizations/${organization.slug}/projects/`;
const projects = await get<Project[]>(url);
return projects.map(project => ({ ...project, organization }));
}),
);
return orgs.reduce((all, next) => all.concat(next), []);
}
|
package committee
import (
"fmt"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address/signaturescheme"
"github.com/iotaledger/goshimmer/dapps/waspconn/packages/waspconn"
"github.com/iotaledger/wasp/packages/sctransaction"
"github.com/iotaledger/wasp/packages/state"
"github.com/iotaledger/wasp/packages/util"
"io"
)
func (msg *NotifyReqMsg) Write(w io.Writer) error {
if err := util.WriteUint32(w, msg.StateIndex); err != nil {
return err
}
if err := util.WriteUint16(w, uint16(len(msg.RequestIds))); err != nil {
return err
}
for _, reqid := range msg.RequestIds {
if _, err := w.Write(reqid[:]); err != nil {
return err
}
}
return nil
}
func (msg *NotifyReqMsg) Read(r io.Reader) error {
err := util.ReadUint32(r, &msg.StateIndex)
if err != nil {
return err
}
var arrLen uint16
err = util.ReadUint16(r, &arrLen)
if err != nil {
return err
}
if arrLen == 0 {
return nil
}
msg.RequestIds = make([]sctransaction.RequestId, arrLen)
for i := range msg.RequestIds {
_, err = r.Read(msg.RequestIds[i][:])
if err != nil {
return err
}
}
return nil
}
func (msg *NotifyFinalResultPostedMsg) Write(w io.Writer) error {
if err := util.WriteUint32(w, msg.StateIndex); err != nil {
return err
}
if err := util.WriteBytes16(w, msg.Signature.Bytes()); err != nil {
return err
}
return nil
}
func (msg *NotifyFinalResultPostedMsg) Read(r io.Reader) error {
err := util.ReadUint32(r, &msg.StateIndex)
if err != nil {
return err
}
sigbytes, err := util.ReadBytes16(r)
if err != nil {
return err
}
msg.Signature, _, err = signaturescheme.BLSSignatureFromBytes(sigbytes)
if err != nil {
return err
}
return nil
}
func (msg *StartProcessingBatchMsg) Write(w io.Writer) error {
if err := util.WriteUint32(w, msg.StateIndex); err != nil {
return err
}
if err := util.WriteUint16(w, uint16(len(msg.RequestIds))); err != nil {
return err
}
for i := range msg.RequestIds {
if _, err := w.Write(msg.RequestIds[i][:]); err != nil {
return err
}
}
if _, err := w.Write(msg.RewardAddress[:]); err != nil {
return err
}
if err := waspconn.WriteBalances(w, msg.Balances); err != nil {
return err
}
return nil
}
func (msg *StartProcessingBatchMsg) Read(r io.Reader) error {
if err := util.ReadUint32(r, &msg.StateIndex); err != nil {
return err
}
var size uint16
if err := util.ReadUint16(r, &size); err != nil {
return err
}
msg.RequestIds = make([]sctransaction.RequestId, size)
for i := range msg.RequestIds {
if err := sctransaction.ReadRequestId(r, &msg.RequestIds[i]); err != nil {
return err
}
}
if err := util.ReadAddress(r, &msg.RewardAddress); err != nil {
return err
}
var err error
if msg.Balances, err = waspconn.ReadBalances(r); err != nil {
return err
}
return nil
}
func (msg *SignedHashMsg) Write(w io.Writer) error {
if err := util.WriteUint32(w, msg.StateIndex); err != nil {
return err
}
if err := util.WriteUint64(w, uint64(msg.OrigTimestamp)); err != nil {
return err
}
if _, err := w.Write(msg.BatchHash[:]); err != nil {
return err
}
if _, err := w.Write(msg.EssenceHash[:]); err != nil {
return err
}
if err := util.WriteBytes16(w, msg.SigShare); err != nil {
return err
}
return nil
}
func (msg *SignedHashMsg) Read(r io.Reader) error {
if err := util.ReadUint32(r, &msg.StateIndex); err != nil {
return err
}
var ts uint64
if err := util.ReadUint64(r, &ts); err != nil {
return err
}
msg.OrigTimestamp = int64(ts)
if err := util.ReadHashValue(r, &msg.BatchHash); err != nil {
return err
}
if err := util.ReadHashValue(r, &msg.EssenceHash); err != nil {
return err
}
var err error
if msg.SigShare, err = util.ReadBytes16(r); err != nil {
return err
}
return nil
}
func (msg *GetBatchMsg) Write(w io.Writer) error {
return util.WriteUint32(w, msg.StateIndex)
}
func (msg *GetBatchMsg) Read(r io.Reader) error {
return util.ReadUint32(r, &msg.StateIndex)
}
func (msg *BatchHeaderMsg) Write(w io.Writer) error {
if err := util.WriteUint32(w, msg.StateIndex); err != nil {
return err
}
if err := util.WriteUint16(w, msg.Size); err != nil {
return err
}
if _, err := w.Write(msg.StateTransactionId.Bytes()); err != nil {
return err
}
return nil
}
func (msg *BatchHeaderMsg) Read(r io.Reader) error {
if err := util.ReadUint32(r, &msg.StateIndex); err != nil {
return err
}
if err := util.ReadUint16(r, &msg.Size); err != nil {
return err
}
if _, err := r.Read(msg.StateTransactionId[:]); err != nil {
return err
}
return nil
}
func (msg *StateUpdateMsg) Write(w io.Writer) error {
if err := util.WriteUint32(w, msg.StateIndex); err != nil {
return err
}
if err := msg.StateUpdate.Write(w); err != nil {
return err
}
if err := util.WriteUint16(w, msg.BatchIndex); err != nil {
return err
}
return nil
}
func (msg *StateUpdateMsg) Read(r io.Reader) error {
if err := util.ReadUint32(r, &msg.StateIndex); err != nil {
return err
}
msg.StateUpdate = state.NewStateUpdate(nil)
if err := msg.StateUpdate.Read(r); err != nil {
return err
}
if err := util.ReadUint16(r, &msg.BatchIndex); err != nil {
return err
}
return nil
}
func (msg *TestTraceMsg) Write(w io.Writer) error {
if !util.ValidPermutation(msg.Sequence) {
panic(fmt.Sprintf("Write: wrong permutation %+v", msg.Sequence))
}
if err := util.WriteUint64(w, uint64(msg.InitTime)); err != nil {
return err
}
if err := util.WriteUint16(w, msg.InitPeerIndex); err != nil {
return err
}
if err := util.WriteUint16(w, uint16(len(msg.Sequence))); err != nil {
return err
}
for _, idx := range msg.Sequence {
if err := util.WriteUint16(w, idx); err != nil {
return err
}
}
if err := util.WriteUint16(w, msg.NumHops); err != nil {
return err
}
return nil
}
func (msg *TestTraceMsg) Read(r io.Reader) error {
var initTime uint64
if err := util.ReadUint64(r, &initTime); err != nil {
return err
}
msg.InitTime = int64(initTime)
if err := util.ReadUint16(r, &msg.InitPeerIndex); err != nil {
return err
}
var size uint16
if err := util.ReadUint16(r, &size); err != nil {
return err
}
msg.Sequence = make([]uint16, size)
for i := range msg.Sequence {
if err := util.ReadUint16(r, &msg.Sequence[i]); err != nil {
return err
}
}
if err := util.ReadUint16(r, &msg.NumHops); err != nil {
return err
}
if !util.ValidPermutation(msg.Sequence) {
panic(fmt.Sprintf("Read: wrong permutation %+v", msg.Sequence))
}
return nil
}
|
import { makeFactory } from '../.storybook/storyHelper';
export const atomStories = makeFactory('Atoms', { withInfo: true });
|
package commons
import (
"AccountManagement/conf"
"database/sql"
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
)
const (
BizMySQLConfPrefix = "bmysql."
mySQLUrlPattern = "%s:%s@tcp(%s:%d)/%s?charset=utf8mb4"
)
var (
dbMap map[string]*instrument.DB
)
func SetupMySQL() {
dbMap = make(map[string]*instrument.DB)
for _, instance := range conf.BizMySQLInstances {
config := conf.BizMySQL[instance]
db := newDBInstance(config.DbName, config)
//instance = BizMySQLConfPrefix + instance
dbMap[instance] = instrument.NewDB(db,
&instrument.Options{
Tag: instance,
LogVerbose: func(v ...interface{}) {
logger.Debug(nil, v...)
},
ObserveLatency: func(latency time.Duration) {
prometheus.MySQLHistogramVec.WithLabelValues(instance).Observe(float64(latency.Nanoseconds()) * 1e-6)
},
},
)
}
}
func newDBInstance(dbName string, config conf.MySQLConf) *sql.DB {
dbUrl := fmt.Sprintf(mySQLUrlPattern, config.Username, config.Password, config.Host, config.Port, dbName)
db, err := sql.Open("mysql", dbUrl)
if err != nil {
logger.Fatalf(nil, "open %s failed: %v", dbUrl, err)
}
db.SetMaxIdleConns(config.MaxIdle)
db.SetMaxOpenConns(config.MaxConn)
return db
}
func GetDB(name string) *instrument.DB {
return dbMap[name]
}
|
namespace Celestial.Units
{
public interface IUnitConvertable
{
double ToDouble();
}
} |
package afkt.demo.model
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class FragmentViewModel : ViewModel() {
val number = MutableLiveData<Int>()
init {
number.value = -100
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.