text
stringlengths
27
775k
/** * © 2019 Liferay, Inc. <https://liferay.com> * * SPDX-License-Identifier: BSD-3-Clause */ import ClayTooltip from './Tooltip'; import ClayTooltipProvider from './TooltipProvider'; export {ClayTooltipProvider}; export default ClayTooltip;
import { Quadrants as EightBittrQuadrants } from "eightbittr"; import { FullScreenPokemon } from "../FullScreenPokemon"; /** * Arranges game physics quadrants. */ export class Quadrants<Game extends FullScreenPokemon> extends EightBittrQuadrants<Game> { /** * Groups that should have their quadrants updated. */ public readonly activeGroupNames = ["Character", "Scenery", "Solid", "Terrain", "Text"]; /** * How many Quadrant columns there are in the game. */ public readonly numCols = 8; /** * How many Quadrant rows there are in the game. */ public readonly numRows = 8; }
# frozen_string_literal: true module UiRules class CartonsPerPalletRule < Base def generate_rules @repo = MasterfilesApp::PackagingRepo.new make_form_object apply_form_values common_values_for_fields common_fields set_show_fields if %i[show].include? @mode edit_label_fields if %i[edit].include? @mode form_name 'cartons_per_pallet' end def set_show_fields fields[:description] = { renderer: :label } fields[:cartons_per_pallet] = { renderer: :label } fields[:layers_per_pallet] = { renderer: :label } fields[:active] = { renderer: :label, as_boolean: true } edit_label_fields end def edit_label_fields fields[:pallet_format_id] = { renderer: :label, with_value: @form_object.pallet_formats_description, include_hidden_field: true, hidden_value: @form_object.pallet_format_id, caption: 'Pallet Format' } fields[:basic_pack_id] = { renderer: :label, with_value: @form_object.basic_pack_code, include_hidden_field: true, hidden_value: @form_object.basic_pack_id, caption: 'Basic Pack' } end def common_fields { description: {}, pallet_format_id: { renderer: :select, options: @repo.for_select_pallet_formats, disabled_options: @repo.for_select_inactive_pallet_formats, caption: 'Pallet Format', required: true }, basic_pack_id: { renderer: :select, options: MasterfilesApp::FruitSizeRepo.new.for_select_basic_packs, disabled_options: MasterfilesApp::FruitSizeRepo.new.for_select_inactive_basic_packs, caption: 'Basic Pack', required: true }, cartons_per_pallet: { renderer: :integer, required: true }, layers_per_pallet: { renderer: :integer, required: true } } end def make_form_object if @mode == :new make_new_form_object return end @form_object = @repo.find_cartons_per_pallet(@options[:id]) end def make_new_form_object @form_object = OpenStruct.new(description: nil, pallet_format_id: nil, basic_pack_id: nil, cartons_per_pallet: nil, layers_per_pallet: nil) end end end
using Abp.Authorization.Users; using Abp.NHibernate.EntityMappings; namespace Abp.Zero.NHibernate.EntityMappings { public class UserClaimMap : EntityMap<UserClaim> { public UserClaimMap() : base("AbpUserClaims") { Map(x => x.TenantId); Map(x => x.UserId); Map(x => x.ClaimType); Map(x => x.ClaimValue); this.MapCreationAudited(); } } }
package main import ( "os" controller "personal-blog/controller" middleware "personal-blog/middleware" docs "personal-blog/docs" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" ) func main() { docs.SwaggerInfo.Title = "Swagger Example API" docs.SwaggerInfo.Description = "This is a sample server Petstore server." docs.SwaggerInfo.Version = "1.0" docs.SwaggerInfo.Host = "petstore.swagger.io" docs.SwaggerInfo.BasePath = "/v2" docs.SwaggerInfo.Schemes = []string{"http", "https"} router := gin.Default() v1 := router.Group("/api/v1") { post := v1.Group("/posts") { post.POST("", middleware.TokenAuthMiddleware(), controller.CreatePost) post.PUT("", middleware.TokenAuthMiddleware(), controller.UpdatePost) post.GET("/id/:id", controller.GetPostById) post.GET("", controller.GetPosts) post.GET("/categoryid/:categoryid", controller.GetPostsByCategoryId) } login := v1.Group("/login") { login.POST("/login", controller.Login) } } port := os.Getenv("PORT") if port == "" { port = "8080" } router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) router.Run(":" + port) }
import camelCase from "./index.js"; import { addPrototype } from "../../utils.js"; declare global { interface String { camelCase(): string; } } /** * Converts the string to camelcase * @memberof String.prototype * @function camelCase * @returns {String} * @example * "some_database_field_name".camelCase(); // "someDatabaseFieldName" * "Some label that needs to be camelized".camelCase(); // "someLabelThatNeedsToBeCamelized" * "some-javascript-property".camelCase(); // "someJavascriptProperty" * "some-mixed_string with spaces_underscores-and-hyphens".camelCase(); * // "someMixedStringWithSpacesUnderscoresAndHyphens" */ addPrototype(String, "camelCase", camelCase);
pub trait Day { fn part1(&self, input:&str) -> String; fn part2(&self, input:&str) -> String; }
#!/bin/bash cd "$(dirname "${BASH_SOURCE[0]}")" \ && . "../utils.sh" export OH_MY_TMUX_LOCATION="$HOME/.local/oh-my-tmux" print_in_purple "\n Oh my tmux\n\n" if [ -f "$OH_MY_TMUX_LOCATION/.git/config" ]; then print_success "oh-my-tmux" else execute "git clone https://github.com/gpakosz/.tmux.git '$OH_MY_TMUX_LOCATION' \ && ln -s -f '$OH_MY_TMUX_LOCATION/.tmux.conf' ~/.tmux.conf" \ "\n oh-my-tmux\n\n" fi
:- dynamic running/2. :- dynamic jobid/1. jobid(0). resource(node1, 1, linux). resource(node2, 4, linux). resource(node3, 1, macos). current_jobs(Node, Jobs) :- findall(J, running(Node, J), Jobs). current_capacity(Node, Capacity) :- resource(Node, Max_C, _), current_jobs(Node, Jobs), length(Jobs, Num_J), Capacity is Max_C - Num_J. find_available(Tag, Node) :- resource(Node, _, Tag), current_capacity(Node, C), C >= 1. next_id(Id) :- jobid(OldId), retract(jobid(OldId)), Id is OldId + 1, assert(jobid(Id)). schedule(Tag, Handle) :- find_available(Tag, Node), !, next_id(Id), Handle = running(Node, Id), assert(Handle). shutdown :- retractall(running(_, _)), retractall(jobid(_)), assert(jobid(0)).
#!/bin/sh cd code git clone https://github.com/zhaomingli007/coinbase_price.git #Extract and Talend data pipeline scripts mkdir talend_runtime unzip coinbase_price/data_ingestion/batch/Talend_run/main_pipeline_0.1.zip -d ./talend_runtime chmod -R +rx ./talend_runtime talend_runtime/main_pipeline/main_pipeline_run.sh -> main_pipeline_run.log #schedule echo "0 23 * * * bash /workspace/code/talend_runtime/main_pipeline/main_pipeline_run.sh" > mycron crontab mycron rm mycron
class fun: a=2 def __init__(self): self.x=3 self.y=4 def display(self): print(self.x,self.y) def __del__(self): print("object is deleted ") def __cmp__(self,other): if(self.x==other.x): print("comparable") def __str__(self): return(str(f1.x)) def __repr__(self): return("string is returned") def compare(self,other): if(self.x==other.x): print("true") def __neg__(self,other): print(self.x-other.x) f1=fun() f2=fun() f1.display() print(f1.x) print(f1.__class__.a) print(f1.a) f1.age=4 print(f1) print(f1.age) #del f1.x #f1.display() #del f1 #f1.__class__.__del__() #cmp(f2,3) f1.__class__.__cmp__(f2,f1) print(str(f1)) print(repr(f1)) f1.compare(f1) f1.__cmp__(f2) f1.__neg__(f2)
package com.work.lazxy.writeaway.mvpframe.concrete.planning import android.util.Log import com.work.lazxy.writeaway.entity.PlanningEntity import com.work.lazxy.writeaway.mvpframe.base.BaseObserver /** * Created by Lazxy on 2017/2/22. */ class PlanningPresent : PlanningContract.Presenter() { override fun getPlanning() { observe(mModel.planning, object : BaseObserver<List<PlanningEntity>>(mView) { override fun onSuccess(plannings: List<PlanningEntity>) { mView.setPlanning(plannings) } }) } override fun savePlanning(plannings: List<PlanningEntity>) { observe(mModel.savePlanning(plannings), object : BaseObserver<String>(mView) { override fun onSuccess(s: String) { Log.i("DEBUG", "saved success") } }) } override fun addPlanning(planning: PlanningEntity) { observe(mModel.addPlanning(planning), object : BaseObserver<String>() { override fun onSuccess(s: String) { Log.i("DEBUG", "saved success") } }) } }
# rgooglefit 0.0.0.9000 * Add `get_sessions` to access sessions data.
// Copyright 2018 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 "chrome/browser/android/customtabs/client_data_header_web_contents_observer.h" #include "chrome/common/chrome_render_frame.mojom.h" #include "content/public/browser/render_frame_host.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" namespace customtabs { ClientDataHeaderWebContentsObserver::~ClientDataHeaderWebContentsObserver() = default; ClientDataHeaderWebContentsObserver::ClientDataHeaderWebContentsObserver( content::WebContents* web_contents) : WebContentsObserver(web_contents) {} void ClientDataHeaderWebContentsObserver::SetHeader(const std::string& header) { header_ = header; auto frames = web_contents()->GetAllFrames(); for (auto* frame : frames) UpdateFrameCCTHeader(frame); } void ClientDataHeaderWebContentsObserver::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { UpdateFrameCCTHeader(render_frame_host); } void ClientDataHeaderWebContentsObserver::UpdateFrameCCTHeader( content::RenderFrameHost* render_frame_host) { mojo::AssociatedRemote<chrome::mojom::ChromeRenderFrame> client; render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&client); client->SetCCTClientHeader(header_); } WEB_CONTENTS_USER_DATA_KEY_IMPL(ClientDataHeaderWebContentsObserver) } // namespace customtabs
struct FASTPIX3D_API Vertex { public: Vector3f Position; Vector3f Normals; Vector2f TextureCoordinates; Color VertexColor; Vertex(); Vertex(Vector3f position); Vertex(Vector3f position, Vector3f normals); Vertex(Vector3f position, Vector3f normals, Vector2f textureCoordinates); Vertex(Vector3f position, Vector3f normals, Vector2f textureCoordinates, Color vertexColor); };
using System; using System.Linq; using Isabelle.Ast; namespace Isabelle.IsaPrettyPrint { public class TypeIsaPrettyPrinter : TypeIsaVisitor<string> { public override string VisitVarType(VarType t) { return IsaPrettyPrinterHelper.Parenthesis("\'" + t.Name); } public override string VisitArrowType(ArrowType t) { var rArg = Visit(t.ArgType); var rRes = Visit(t.ResType); return IsaPrettyPrinterHelper.Parenthesis(rArg + " => " + rRes); } public override string VisitDataType(DataType t) { var rArgs = VisitList(t.Args); if (t.Args.Count == 0) return IsaPrettyPrinterHelper.Parenthesis(t.Name); return IsaPrettyPrinterHelper.Parenthesis(rArgs.SpaceAggregate() + t.Name); } public override string VisitPrimitiveType(PrimitiveType t) { switch (t.SimpleType) { case SimpleType.Bool: return "bool"; case SimpleType.Int: return "int"; case SimpleType.Nat: return "nat"; case SimpleType.String: return "string"; default: throw new NotImplementedException(); } } public override string VisitTupleType(TupleType t) { var rArgs = VisitList(t.Args); var aggr = rArgs.Aggregate((s1, s2) => s1 + " " + IsaPrettyPrinterHelper.TIMES + " " + s2); return IsaPrettyPrinterHelper.Parenthesis(aggr); } public override string VisitSumType(SumType t) { var rArgs = VisitList(t.Args); var aggr = rArgs.Aggregate((s1, s2) => s1 + " + " + s2); return IsaPrettyPrinterHelper.Parenthesis(aggr); } } }
require './views/base' module Views class BidBox < Base needs :current_player needs :game def content props = { id: 'bid_box', style: inline(margin_top: '1em'), } bid = game.current_bid game_form props do price_props = { id: 'bid_price', type: 'number', name: data('price'), min: 1, style: inline(width: '50px', margin: '0 5px'), placeholder: 'Price', } price_props[:value] = bid.price + 1 if bid label 'Price:' input price_props input type: 'hidden', id: 'bid_company', name: data('company') input type: 'hidden', name: data('player'), value: current_player.id input type: 'hidden', name: data('action'), value: 'bid' label(title: 'Automatically increments bid until max price is reached') { text 'Auto increment until max' } input type: 'checkbox', name: data('max') input id: 'bid_submit', type: 'submit', value: 'Make Bid', disabled: true end end end end
#include"RL_Voice68.h" VOICE_68::VOICE_68(uint8_t pin){ _pin=pin; } void VOICE_68::begin(){ pinMode(_pin, OUTPUT); } void VOICE_68::send_data(uint8_t addr) { int i; digitalWrite(_pin , LOW); delay(3); //>2ms for (i = 0; i < 8; i++) { digitalWrite(_pin, HIGH); if (addr & 1) { delayMicroseconds(2400); //>2400us digitalWrite(_pin, LOW); delayMicroseconds(800); } //>800us else { delayMicroseconds(800); //>800us digitalWrite(_pin , LOW); delayMicroseconds(2400); } //>2400us addr >>= 1; } //地址值右移一位 digitalWrite(_pin, HIGH); } void VOICE_68::set_volume(uint8_t addr){//0Xe0-e7 delay(100); send_data(0Xe0+addr); } void VOICE_68::set_cycle(){//0XF2 delay(100); send_data(0XF2); } void VOICE_68::set_stop(){//0XFE delay(100); send_data(0XFE); } void VOICE_68::broadcast_num(uint8_t x) { if (x == 0) { send_data(0x2C); delay(200); } else { send_data(0x22+x); delay(200); } } void VOICE_68::broadcast_int(uint16_t x){ uint8_t ge,shi,bai,qian; qian = x / 1000; bai = ((x / 100)) % (10); shi = ((x) % (100)) / 10; ge = (x) % (10); if (qian) { broadcast_num(qian); send_data(0x20); delay(200); } if (bai) { broadcast_num(bai); send_data(0x21); delay(200); } if (shi) { broadcast_num(shi); send_data(0x22); delay(200); } broadcast_num(ge); delay(1000); } void VOICE_68::broadcast_float(float y){ uint8_t ge,shi,bai,qian,xiaoshu1,xiaoshu2; int16_t zhengshu,xiaoshu; zhengshu=(int)y; xiaoshu=(int)((y-zhengshu)*100);//放大100倍 // Serial.println(xiaoshu); qian = zhengshu / 1000; bai = ((zhengshu / 100)) % (10); shi = ((zhengshu) % (100)) / 10; ge = (zhengshu) % (10); xiaoshu1=(xiaoshu) /10; xiaoshu2=(xiaoshu) % 10; if (qian) { broadcast_num(qian); send_data(0x20); delay(200); } if (bai) { broadcast_num(bai); send_data(0x21); delay(200); } if (shi) { broadcast_num(shi); send_data(0x22); delay(200); } broadcast_num(ge); delay(200); if(xiaoshu1|xiaoshu2){ send_data(0x1d); delay(200); broadcast_num(xiaoshu1); delay(200); broadcast_num(xiaoshu2); delay(200); } }
# Generated by Django 3.1.5 on 2021-02-05 14:37 from django.db import migrations def createFirstThread(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Thread = apps.get_model('backend', 'Thread') db_alias = schema_editor.connection.alias Thread.objects.using(db_alias).bulk_create([ Thread(name="All") ]) class Migration(migrations.Migration): dependencies = [ ('backend', '0001_initial'), ] operations = [ migrations.RunPython(createFirstThread), ]
#!/bin/bash # # Load project/RootBuild.scala and generates pom.xml for all the sub-projects. # This should NOT normally be run by developers. Rather it is to be run once in a while # by maintainers, and the resulting pom.xml checked into the repo for mvn use by developers. # BINDIR="`dirname $0`" cd "$BINDIR"/.. SBT="bin/sbt" $SBT make-pom TARGET_DIR=target # Project list is heuristically determined to be those dirs that have src/main/ under them PROJECTS=(`echo */src/main | sed -e 's/\/src\/main//g'`) for project in ${PROJECTS[*]} ; do # find the latest *.pom under $TARGET_DIR pom=`find $project -type f -name *.pom -exec ls -l {} \; 2> /dev/null | sort -t' ' -k +6,6 -k +7,7 -k+8,8 | tail -1 | sed -e 's/.* //g'` [ -z $pom ] && continue echo "Copying latest $pom to $project/pom.xml" # Notice there's a hack to pass the "*" exclusion wildcard from sbt to pom.xml. # This is because sbt refuses to generate "*" for pom.xml, citing that it's not supported/legal. # But in fact, mvn supports it, even though it's "bad practice". Here, we do it because # we need it to get out of the Shark jar hell. sed -e 's/_MAKE_POM_EXCLUDE_ALL_/\*/g' $pom > $project/pom.xml done
/* * Copyright 2018-2019 The NATS Authors * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cmd import ( "bytes" "errors" "fmt" "io/ioutil" "path/filepath" "sort" "github.com/nats-io/jwt" "github.com/nats-io/nsc/cmd/store" ) type MemResolverConfigBuilder struct { operator string claims map[string]string pubToName map[string]string dir string sysAccount string } func NewMemResolverConfigBuilder() *MemResolverConfigBuilder { cb := MemResolverConfigBuilder{} cb.claims = make(map[string]string) cb.pubToName = make(map[string]string) return &cb } func (cb *MemResolverConfigBuilder) SetOutputDir(fp string) error { cb.dir = fp return nil } func (cb *MemResolverConfigBuilder) SetSystemAccount(id string) error { cb.sysAccount = id return nil } func (cb *MemResolverConfigBuilder) Add(rawClaim []byte) error { token := string(rawClaim) gc, err := jwt.DecodeGeneric(token) if err != nil { return err } switch gc.Type { case jwt.OperatorClaim: oc, err := jwt.DecodeOperatorClaims(token) if err != nil { return err } cb.operator = token cb.pubToName[oc.Subject] = oc.Name cb.pubToName["__OPERATOR__"] = oc.Subject case jwt.AccountClaim: ac, err := jwt.DecodeAccountClaims(token) if err != nil { return err } cb.claims[ac.Subject] = token cb.pubToName[ac.Subject] = ac.Name } return nil } func (cb *MemResolverConfigBuilder) GenerateConfig() ([]byte, error) { var buf bytes.Buffer opk := cb.pubToName["__OPERATOR__"] if opk == "" { return nil, errors.New("operator is not set") } buf.WriteString(fmt.Sprintf("// Operator %q\n", cb.pubToName[opk])) buf.WriteString(fmt.Sprintf("operator: %s\n\n", cb.operator)) if cb.sysAccount != "" { buf.WriteString(fmt.Sprintf("system_account: %s\n\n", cb.sysAccount)) } var keys []string for k := range cb.claims { keys = append(keys, k) } sort.Strings(keys) buf.WriteString("resolver: MEMORY\n\n") buf.WriteString("resolver_preload: {\n") for _, k := range keys { v := cb.claims[k] buf.WriteString(fmt.Sprintf(" // Account %q\n", cb.pubToName[k])) buf.WriteString(fmt.Sprintf(" %s: %s\n\n", k, v)) } buf.WriteString("}\n") return buf.Bytes(), nil } func (cb *MemResolverConfigBuilder) writeFile(dir string, name string, token string) (string, error) { fp := filepath.Join(dir, store.JwtName(name)) err := ioutil.WriteFile(fp, []byte(token), 0666) return fp, err } func (cb *MemResolverConfigBuilder) GenerateDir() ([]byte, error) { var buf bytes.Buffer if err := MaybeMakeDir(cb.dir); err != nil { return nil, err } opk := cb.pubToName["__OPERATOR__"] if opk == "" { return nil, errors.New("operator is not set") } fn, err := cb.writeFile(cb.dir, cb.pubToName[opk], cb.operator) if err != nil { return nil, err } buf.WriteString(fmt.Sprintf("// Operator %q\n", cb.pubToName[opk])) buf.WriteString(fmt.Sprintf("operator: %q\n\n", filepath.Join(".", filepath.Base(fn)))) if cb.sysAccount != "" { buf.WriteString(fmt.Sprintf("system_account: %s\n\n", cb.sysAccount)) } var keys []string for k := range cb.claims { keys = append(keys, k) } sort.Strings(keys) buf.WriteString("resolver: MEMORY\n\n") buf.WriteString("resolver_preload: {\n") for _, k := range keys { v := cb.claims[k] n := cb.pubToName[k] buf.WriteString(fmt.Sprintf(" // Account %q\n", n)) fn, err := cb.writeFile(cb.dir, n, v) if err != nil { return nil, err } rel, err := filepath.Rel(cb.dir, fn) if err != nil { return nil, err } buf.WriteString(fmt.Sprintf(" %s: %q\n\n", k, rel)) } buf.WriteString("}\n") err = ioutil.WriteFile(filepath.Join(cb.dir, "resolver.conf"), buf.Bytes(), 0666) if err != nil { return nil, err } return nil, nil } func (cb *MemResolverConfigBuilder) Generate() ([]byte, error) { if cb.dir != "" { return cb.GenerateDir() } return cb.GenerateConfig() }
<!DOCTYPE html> <html lang="{{ config('app.locale') }}"> <head> <meta charset="utf-8"> </head> <body> <a href="{{ url('/') }}"> @if (TypiCMS::hasLogo()) @include('core::public._logo') @endif </a> <h2>@lang('Thank you for your contact request')</h2> @include('contacts::mails._detail', ['model' => $model]) <hr> {!! Blocks::render('signature-mail') !!} </body> </html>
package projection import ( "encoding/json" "io" "sort" "sync" "github.com/inklabs/rangedb" ) type aggregateTypeStatusData struct { TotalEventsByAggregateType map[string]uint64 `json:"totalEventsByAggregateType"` LatestGlobalSequenceNumber uint64 `json:"latestGlobalSequenceNumber"` TotalEvents uint64 `json:"totalEvents"` } // AggregateTypeStats contains data for this projection. type AggregateTypeStats struct { mux sync.RWMutex data aggregateTypeStatusData } // NewAggregateTypeStats constructs a projection for aggregate type statistics. func NewAggregateTypeStats() *AggregateTypeStats { return &AggregateTypeStats{ data: aggregateTypeStatusData{ TotalEventsByAggregateType: make(map[string]uint64), }, } } // Accept receives a Record. func (a *AggregateTypeStats) Accept(record *rangedb.Record) { a.mux.Lock() a.data.TotalEventsByAggregateType[record.AggregateType]++ a.data.LatestGlobalSequenceNumber = record.GlobalSequenceNumber a.data.TotalEvents++ a.mux.Unlock() } // SortedAggregateTypes returns distinct aggregate types sorted by key. func (a *AggregateTypeStats) SortedAggregateTypes() []string { a.mux.RLock() keys := make([]string, 0, len(a.data.TotalEventsByAggregateType)) for k := range a.data.TotalEventsByAggregateType { keys = append(keys, k) } a.mux.RUnlock() sort.Strings(keys) return keys } // TotalEventsByAggregateType returns the total number of received events by aggregate type. func (a *AggregateTypeStats) TotalEventsByAggregateType(aggregateType string) uint64 { a.mux.RLock() defer a.mux.RUnlock() return a.data.TotalEventsByAggregateType[aggregateType] } // TotalEvents returns the total number of received events. func (a *AggregateTypeStats) TotalEvents() uint64 { return a.data.TotalEvents } // LatestGlobalSequenceNumber returns the global sequence number from the last received event. func (a *AggregateTypeStats) LatestGlobalSequenceNumber() uint64 { a.mux.RLock() defer a.mux.RUnlock() return a.data.LatestGlobalSequenceNumber } // SnapshotName returns the name for snapshot purposes. func (a *AggregateTypeStats) SnapshotName() string { return "AggregateTypeStats" } // SaveSnapshot writes the projection data to an io.Writer. func (a *AggregateTypeStats) SaveSnapshot(w io.Writer) error { a.mux.RLock() defer a.mux.RUnlock() return json.NewEncoder(w).Encode(a.data) } // LoadFromSnapshot reads the projection data from an io.Reader and loads the state. func (a *AggregateTypeStats) LoadFromSnapshot(r io.Reader) error { var data aggregateTypeStatusData err := json.NewDecoder(r).Decode(&data) if err != nil { return err } a.mux.Lock() a.data.TotalEventsByAggregateType = data.TotalEventsByAggregateType a.data.LatestGlobalSequenceNumber = data.LatestGlobalSequenceNumber a.data.TotalEvents = data.TotalEvents a.mux.Unlock() return nil }
require "securerandom" require "double_bag_ftps" require "net/sftp" require "net/ftp" require 'streamio-ffmpeg' module RestFtpDaemon class InvalidWorkerNumber < BaseException; end class QueueCantCreateJob < BaseException; end class JobException < BaseException; end class JobNotFound < BaseException; end class Job # Common errors ERRORS = { # oops_invalid_argument: Errno::EINVAL, oops_runtime_error: RuntimeError, job_timeout: RestFtpDaemon::JobTimeout, source_not_supported: RestFtpDaemon::SourceUnsupported, source_not_found: RestFtpDaemon::SourceNotFound, target_file_exists: RestFtpDaemon::TargetFileExists, target_directory_error: RestFtpDaemon::TargetDirectoryError, target_permission_error: RestFtpDaemon::TargetPermissionError, target_not_supported: RestFtpDaemon::TargetUnsupported, assertion_failed: RestFtpDaemon::AssertionFailed, conn_socket_error: SocketError, conn_eof: EOFError, conn_failed: Errno::ENOTCONN, conn_host_is_down: Errno::EHOSTDOWN, conn_broken_pipe: Errno::EPIPE, conn_unreachable: Errno::ENETUNREACH, conn_reset_by_peer: Errno::ECONNRESET, conn_refused: Errno::ECONNREFUSED, conn_timed_out_1: Timeout::Error, conn_timed_out_2: Net::ReadTimeout, conn_timed_out_3: Errno::ETIMEDOUT, ftp_connection_error: Net::FTPConnectionError, ftp_perm_error: Net::FTPPermError, ftp_reply_error: Net::FTPReplyError, ftp_temp_error: Net::FTPTempError, ftp_proto_error: Net::FTPProtoError, ftp_error: Net::FTPError, sftp_exception: Net::SFTP::StatusException, sftp_key_mismatch: Net::SSH::HostKeyMismatch, sftp_auth_failed: Net::SSH::AuthenticationFailed, sftp_openssl_error: OpenSSL::SSL::SSLError, s3_no_such_waiter: Aws::Waiters::Errors::NoSuchWaiterError, s3_failure_state_error: Aws::Waiters::Errors::FailureStateError, s3_too_many_attempts: Aws::Waiters::Errors::TooManyAttemptsError, s3_waiter_unexpected: Aws::Waiters::Errors::UnexpectedError, s3_waiter_failed: Aws::Waiters::Errors::WaiterFailed, #s3_not_found: Aws::S3::Errors::NotFound, s3_permanent_redirect: Aws::S3::Errors::PermanentRedirect, s3_no_such_key: Aws::S3::Errors::NoSuchKey, s3_no_such_bucket: Aws::S3::Errors::NoSuchBucket, s3_no_such_upload: Aws::S3::Errors::NoSuchUpload, s3_error: Aws::S3::Errors::ServiceError, video_missing_binary: RestFtpDaemon::VideoMissingBinary, video_not_found: RestFtpDaemon::VideoNotFound, video_movie_error: RestFtpDaemon::VideoMovieError, video_ffmpeg_error: FFMPEG::Error, # rescue Encoding::UndefinedConversionError => exception # return oops :ended, exception, "encoding_error", true } end end
--- authorName: Xavier Abadia canDelete: false contentTrasformed: false from: '&quot;Xavier Abadia&quot; &lt;xabadiar@...&gt;' headers.inReplyToHeader: PGoyMDhjOStraTE2QGVHcm91cHMuY29tPg== headers.messageIdInHeader: PGoyMHNrMitiaDZkQGVHcm91cHMuY29tPg== headers.referencesHeader: .nan layout: email msgId: 2029 msgSnippet: Karo Myalee, Gratia de tu neo versio. In origi katalan versio, blau-grana semani blau & grana . [http://ca.wikipedia.org/wiki/Granat_(color) = nextInTime: 2030 nextInTopic: 2030 numMessagesInTopic: 4 postDate: '1313076674' prevInTime: 2028 prevInTopic: 2028 profile: xabadiar replyTo: LIST senderId: INacDRbBLZ3J0K6nXjLVv7XzlOcA6jTOSdahykuXAWwiGdf9JhhtyHClNkK78ANLYGNpumU2P0Kbu8ILBu_b1Sa4j3rR7cPXvb7g spamInfo.isSpam: false spamInfo.reason: '6' systemMessage: false title: 'Re: Barcelona' topicId: 2028 userId: 472762895 --- Karo Myalee, Gratia de tu neo versio. In origi katalan versio, "blau-= grana" semani "blau & grana". [http://ca.wikipedia.org/wiki/Granat_(color)= =3D http://en.wikipedia.org/wiki/Maroon_(color) =3D http://fr.wikipedia.or= g/wiki/Bordeaux_(couleur)] Mi fio grafo "ciano-plus-rubi" vice "ciano-rubi= ". Ka, iso, "rubi-plus-xanto" ne es rubi-xanto kroma. Plus-co, mi puta; "g= rana" kroma ne es rubi, sed fo-rubi. Plu Bar=E7a seqe-pe fo-hedo u-ci idio = kroma. Saluta, Xavi. --- In glosalist@yahoogroups.com, "myaleee n" <myalee= e@...> wrote: > > Karo glosa-ami, mi fo fru ex Barcelona Ludi himno; pardo,= mi re-grafo mi auto versio;-) > Ali sugesti sio place mi ;-) > ------ > = > Panto-pe in ludi-agri zelo pa klama, > Na es u ciano-rubi demo, > Ne impo= rta ex qo-lo na veni, > Ex sud alo ex nord, > Nu, na akorda, na akorda, > N= a insigni indika e sti auto fratri, > > Ciano-rubi a tempestu, > U koragi = klama, > Na habe u nomina; panto-pe ski, > Bar=E7a, Bar=E7a, Bar=E7a! > > = Plu ludi-pe, plu seqe-pe, > Panto na gene dina per unio > Poli zelo-ple an= ua, > Poli bola-buta; na pa klama, > Id es ge-proba, id es ge-proba; > Nuli= -tem nuli-pe fu pote bate na, > > Ciano-rubi a tempestu, >
using System; using System.Threading.Tasks; using Apollo.Api.Authorization; using Apollo.Api.Controllers.Base; using Apollo.Core.Dto; using Apollo.Core.Interfaces; using Apollo.Util; using Apollo.Util.Logger; using Microsoft.AspNetCore.Mvc; namespace Apollo.Api.Controllers { public class UserController : ApiControllerBase { private static readonly IApolloLogger<UserController> Logger = LoggerFactory.CreateLogger<UserController>(); private readonly IServiceFactory _service; public UserController(IServiceFactory service) { _service = service ?? throw new ArgumentNullException(nameof(service)); } /// <summary> /// Gets the specific role from a given JWT token. /// </summary> /// <remarks> /// Sample request: /// /// GET /v1/user/role /// /// </remarks> /// <returns>Return the role for the given JWT-token.</returns> /// <response code="200">Returns the role for the given JWT-token.</response> /// <response code="400">If role JWT is not valid.</response> [HttpGet("role")] [AuthorizeRole(ApolloRoles.All)] public async Task<ActionResult<RoleDto>> GetRole() { var uuid = JwtHelper.GetUuidFromClaims(HttpContext.User.Claims); if (uuid == null) { Logger.Here().Error("Request with invalid JWT"); return BadRequestResponse("JWT invalid"); } var user = await _service.CreateUserService().GetUserWithAddressByUuidAsync(uuid); Logger.Here().Info("{Role} extracted from claims for {user}", user.Role, user); return user.Role; } } }
package com.abilists.bean.model.join; import java.io.Serializable; public class MTechJoinUserTechModel implements Serializable { private static final long serialVersionUID = 1L; private int mtNo; private String mtSkill; private String mtName; private String utKind; private String utLevel; public int getMtNo() { return mtNo; } public void setMtNo(int mtNo) { this.mtNo = mtNo; } public String getMtSkill() { return mtSkill; } public void setMtSkill(String mtSkill) { this.mtSkill = mtSkill; } public String getMtName() { return mtName; } public void setMtName(String mtName) { this.mtName = mtName; } public String getUtKind() { return utKind; } public void setUtKind(String utKind) { this.utKind = utKind; } public String getUtLevel() { return utLevel; } public void setUtLevel(String utLevel) { this.utLevel = utLevel; } }
package RapidApp::Template::Controller; use strict; use warnings; use RapidApp::Util qw(:all); use Try::Tiny; use Template; use Module::Runtime; use Path::Class qw(file dir); use URI::Escape; # New unified controller for displaying and editing TT templates on a site-wide # basis. This is an experiment that breaks with the previous RapidApp 'Module' # design. It also is breaking away from DataStore2 for editing in order to support # nested templates (i.e. tree structure instead of table/row structure) use Moose; with 'RapidApp::Role::AuthController'; use namespace::autoclean; BEGIN { extends 'Catalyst::Controller' } use RapidApp::Template::Context; use RapidApp::Template::Provider; use RapidApp::Template::Access; ## ----- ## Setup Top-level alias URL paths: has 'read_alias_path', is => 'ro', default => '/tpl'; has 'edit_alias_path', is => 'ro', default => '/tple'; sub BUILD { my $self = shift; my $c = $self->_app; my $ns = $self->action_namespace($c); if($self->read_alias_path) { my $path = $self->read_alias_path; die "Bad read_alias_path '$path' - must start (but not end) with '/'" unless ( $path =~ /^\// && ! ($path =~ /\/$/) ); $c->dispatcher->register( $c => Catalyst::Action->new({ name => 'tpl', code => $self->can('tpl'), class => $self, namespace => $ns, reverse => join('/',$ns,'tpl'), attributes => { Path => [ $path ] } })); } if($self->edit_alias_path) { my $path = $self->edit_alias_path; die "Bad edit_alias_path '$path' - must start (but not end) with '/'" unless ( $path =~ /^\// && ! ($path =~ /\/$/) ); $c->dispatcher->register( $c => Catalyst::Action->new({ name => 'tple', code => $self->can('tple'), class => $self, namespace => $ns, reverse => join('/',$ns,'tple'), attributes => { Path => [ $path ] } })); } } sub tpl { #:Path('/tpl') { my ($self, $c) = @_; $c->forward('view'); } # Edit alias sub tple { #:Path('/tple') { my ($self, $c) = @_; $c->stash->{editable} = 1; $c->forward('view'); } sub tpl_path { my $self = shift; # Return the edit alias patgh first or fall back to the read alias: return $self->edit_alias_path || $self->read_alias_path; } ## ----- has 'context_class', is => 'ro', default => 'RapidApp::Template::Context'; has 'provider_class', is => 'ro', default => 'RapidApp::Template::Provider'; has 'access_class', is => 'ro', default => 'RapidApp::Template::Access'; has 'access_params', is => 'ro', isa => 'HashRef', default => sub {{}}; # -- # Only these TT plugins and filters will be allowed in Templates # This is *very* important for security if non-admin users will # have access to modify templates. These templates and filters # are from the built-in list and are known to be safe. Examples # of unsafe plugins are things like 'Datafile' and 'DBI', and # examples of unsafe filters are things like 'eval', 'redirect', etc. # It is critical that these types of things are never exposed # to web interfaces. It is also important to note that TT was # not originally designed with "limited" access in mind - it was # only meant to be used by the programmer, not users. In hindsight, # it might have been better to go with Text::Xslate for this reason # # (note: these get accessed/used within RapidApp::Template::Context) has 'allowed_plugins', is => 'ro', default => sub {[qw( Assert Date Dumper Format HTML Iterator Scalar String Table URL Wrap )]}, isa => 'ArrayRef'; has 'allowed_filters', is => 'ro', default => sub {[qw( format upper lower ucfirst lcfirst trim collapse html html_entity xml html_para html_break html_para_break html_line_break uri url indent truncate repeat remove replace null )]}, isa => 'ArrayRef'; # -- has 'default_template_extension', is => 'ro', isa => 'Maybe[Str]', default => 'tt'; # If true, mouse-over edit controls will always be available for editable # templates. Otherwise, query string ?editable=1 is required. Note that # editable controls are *only* available in the context of an AutoPanel tab has 'auto_editable', is => 'ro', isa => 'Bool', default => 0; has 'Access', is => 'ro', lazy => 1, default => sub { my $self = shift; Module::Runtime::require_module($self->access_class); return $self->access_class->new({ %{ $self->access_params }, Controller => $self }); }, isa => 'RapidApp::Template::Access'; # Maintain two separate Template instances - one that wraps divs and one that # doesn't. Can't use the same one because compiled templates are cached has 'Template_raw', is => 'ro', lazy => 1, default => sub { my $self = shift; return $self->_new_Template({ div_wrap => 0 }); }, isa => 'Template'; has 'Template_wrap', is => 'ro', lazy => 1, default => sub { my $self = shift; return $self->_new_Template({ div_wrap => 1 }); }, isa => 'Template'; sub _new_Template { my ($self,$opt) = @_; Module::Runtime::require_module($self->context_class); Module::Runtime::require_module($self->provider_class); return Template->new({ CONTEXT => $self->context_class->new({ Controller => $self, Access => $self->Access, # TODO: turn STRICT back on once I figure out how to make the errors useful: #STRICT => 1, LOAD_TEMPLATES => [ $self->provider_class->new({ Controller => $self, Access => $self->Access, #INCLUDE_PATH => $self->_app->default_tt_include_path, INCLUDE_PATH => [ dir($self->_app->config->{home},'root/templates')->stringify, dir(RapidApp->share_dir,'templates')->stringify ], CACHE_SIZE => 64, %{ $opt || {} } }) ] }) }) } # hook for RapidApp::Role::AuthController: # abort enforce_session for 'external' templates being accessed externally: around 'enforce_rapidapp_session' => sub { my ( $orig, $self, $c, @args ) = @_; my $template = join('/',@{$c->req->args}); return $self->$orig($c,@args) unless ( ! $c->req->header('X-RapidApp-RequestContentType') && $self->is_external_template($c,$template) ); }; sub get_Provider { my $self = shift; return $self->Template_raw->context->{LOAD_TEMPLATES}->[0]; } # request lifetime cached: sub _template_exists { my ($self, $c, $template) = @_; die "missing template arg" unless ($template); $c->stash->{_template_exists}{$template} = $self->get_Provider->template_exists($template) unless (exists $c->stash->{_template_exists}{$template}); return $c->stash->{_template_exists}{$template}; } # Checks if the editable toggle/switch is on for this request. Note that # this has *nothing* to do with actual editability of a given template, # just whether or not edit controls should be available for templates that # are allowed to be edited sub is_editable_request { my ($self, $c) = @_; # Never editable externally, unless this is an iframe request return 0 unless ( $c->req->header('X-RapidApp-RequestContentType') || (exists $c->req->params->{iframe} && $c->req->params->{iframe} eq 'request') ); # check several mechanisms to turn on editing (mouse-over edit controls) return ( $self->auto_editable || $c->req->params->{editable} || $c->req->params->{edit} || $c->stash->{editable} ); } sub is_iframe_request { my ($self, $c) = @_; return ( $c->req->params->{iframe} || $c->stash->{iframe} ); } # request lifetime cached: sub is_external_template { my ($self, $c, $template) = @_; die "missing template arg" unless ($template); $c->stash->{is_external_template}{$template} = do { # Allow params/stash override: return $c->req->params->{external} if (exists $c->req->params->{external}); return $c->stash->{external} if (exists $c->stash->{external}); my $external = ( # hard-coded external templates: $template =~ /^rapidapp\/public\// || $self->Access->template_external_tpl($template) ) ? 1 : 0; return ( $external && # don't treat non-existing templates as external $self->_template_exists($c,$template) ) ? 1 : 0; } unless (exists $c->stash->{is_external_template}{$template}); return $c->stash->{is_external_template}{$template}; } sub _resolve_template_name { my ($self, @args) = @_; return undef unless (defined $args[0]); my $template = join('/',@args); $template .= '.' . $self->default_template_extension if ( $self->default_template_extension && ! ( $template =~ /\./ ) #<-- doesn't contain a dot '.' ); return $template; } # TODO: see about rendering with Catalyst::View::TT or a custom View sub view :Local { my ($self, $c, @args) = @_; my $template = $self->_resolve_template_name(@args) or die "No template specified"; # Honor the existing status, if set, except for Ajax requests my $status = $c->res->status || 200; $status = 200 if ($c->is_ra_ajax_req); local $self->{_current_context} = $c; # Track the top-level template that is being viewed, in case the Access class # wants to treat top-level templates differently from nested templates # -- see currently_viewing_template() in RapidApp::Template::Access local $self->{_viewing_template} = $template; $self->Access->template_viewable($template) or die "Permission denied - template '$template'"; my $ra_req = $c->req->header('X-RapidApp-RequestContentType'); my $ra_client = ($ra_req && $ra_req eq 'JSON'); my $external = $self->is_external_template($c,$template); my $editable = $self->is_editable_request($c); # --- # New: for non-external templates which are being accessed externally, # (i.e. directly from browser) redirect to internal hashnav path: unless ($external || $ra_client) { my $pre = $editable ? $self->tpl_path : $self->read_alias_path; my $url = join('/','/#!',$pre,@args); my %params = %{$c->req->params}; if(keys %params > 0) { my $qs = join('&',map { $_ . '=' . uri_escape($params{$_}) } keys %params); $url .= '?' . $qs; } $c->response->redirect($url); return $c->detach; } #--- my $iframe = $external || $self->is_iframe_request($c); # <-- external must use iframe my ($output,$content_type); my @cls = ('ra-scoped-reset'); my $tpl_cls = $self->Access->template_css_class($template); push @cls, $tpl_cls if ($tpl_cls); if($ra_client) { # This is a call from within ExtJS, wrap divs to id the templates from javascript my $cnf = {}; if($iframe) { # This is an iframe request. Build an iframe panel which will make the request # again but without the X-RapidApp-RequestContentType header which will be # handled as a direct browser request (see logic further down) my %params = ( %{$c->req->params}, editable => $editable, iframe => 'request' ); my $qs = join('&',map { $_ . '=' . uri_escape($params{$_}) } keys %params); my $iframe_src = join('/','',$self->action_namespace($c),'view',$template) . '?' . $qs; $cnf = { xtype => 'iframepanel', plugins => ['ra-link-click-catcher'], tabTitle => join('', '<span style="color:purple;">', '[' . join('/',@args) . ']', #<-- not using $template to preserve the orig req name '</span>' ), tabIconCls => 'ra-icon-page-white', style => 'top: 0; left: 0; bottom: 0; right: 0;', autoScroll => \1, bodyStyle => 'border: 1px solid #D0D0D0;background-color:white;', loadMask => \1, defaultSrc => $iframe_src }; } else { my $html = $self->_render_template( $editable ? 'Template_wrap' : 'Template_raw', $template, $c ); $cnf = { xtype => 'panel', autoScroll => \1, bodyCssClass => join(' ',@cls), # try to set the title/icon by finding/parsing <title> in the 'html' autopanel_parse_title => \1, # These will only be the title/icon if there is no parsable <title> tabTitle => join('/',@args), #<-- not using $template to preserve the orig req name tabIconCls => 'ra-icon-page-white-world', html => $html, # Load any extra, template-specific configs from the Access class: %{ $self->Access->template_autopanel_cnf($template) || {} } }; } # No reason to load the plugin unless we're editable: if ($editable) { $cnf->{plugins} ||= []; push @{$cnf->{plugins}}, 'template-controller-panel'; $cnf->{template_controller_url} = '/' . $self->action_namespace($c); } # This is doing the same thing that the overly complex 'Module' controller does: $content_type = 'text/javascript; charset=utf-8'; $output = encode_json_utf8($cnf); } else { # This is a direct browser call: my $html = $self->_render_template( $editable ? 'Template_wrap' : 'Template_raw', $template, $c ); my @head = (); # If we're in an iframe tab, we want to make sure we set the base target # to prevent the chance of trying to load a link inside the frame (even # though local links are already hanlded/converted - we still need to # protect against external/global links). push @head, '<base target="_blank" />' if ( exists $c->req->params->{iframe} && $c->req->params->{iframe} eq 'request' ); if($external) { # If we're editable and external we need to include CSS for template edit controls: # TODO: basically including everything but ExtJS CSS. This is ugly and should # be generalized/available in the Asset system as a simpler function call: push @head, ( $c->controller('Assets::RapidApp::CSS')->html_head_tags, $c->controller('Assets::RapidApp::Icons')->html_head_tags, $c->controller('Assets::ExtJS')->html_head_tags( js => [ 'adapter/ext/ext-base.js', 'ext-all-debug.js', 'src/debug.js' ]), $c->controller('Assets::RapidApp::JS')->html_head_tags ) if $editable; } else { # Include all the ExtJS, RapidApp and local app CSS/JS push @head, $c->all_html_head_tags; } # Only include the RapidApp/ExtJS assets and wrap 'ra-scoped-reset' if # this is *not* an external template: $output = $external ? join("\n",@head,$html) : join("\n", '<head>', @head, '</head>', '<div class="' . join(' ',@cls) . '">', $html, '</div>' ); $content_type = 'text/html; charset=utf-8'; } # Decode as UTF-8 for user consumption: utf8::decode($output); return $self->_detach_response($c,$status,$output,$content_type); } # Read (not compiled/rendered) raw templates: sub get :Local { my ($self, $c, @args) = @_; my $template = $self->_resolve_template_name(@args) or die "No template specified"; local $self->{_current_context} = $c; $self->Access->template_readable($template) or return $self->_detach_response($c,403,"Permission denied - template '$template'"); my ($data, $error) = $self->get_Provider->load($template); return $self->_detach_response($c,400,"Failed to get template '$template'") unless (defined $data); # Decode as UTF-8 for user consumption: utf8::decode($data); return $self->_detach_response($c,200,$data); } # Update raw templates: sub set :Local { my ($self, $c, @args) = @_; my $template = $self->_resolve_template_name(@args) or die "No template specified"; local $self->{_current_context} = $c; exists $c->req->params->{content} or return $self->_detach_response($c,400,"Template 'content' required"); $self->Access->template_writable($template) or return $self->_detach_response($c,403,"Modify template '$template' - Permission denied"); my $content = $c->req->params->{content}; # Special status 418 means the supplied content is a bad template unless ($c->req->params->{skip_validate}) { my $err = $self->_get_template_error('Template_raw',\$content,$c); return $self->_detach_response($c,418,$err) if ($err); } # Encode the template content in UTF-8 utf8::encode($content); $self->get_Provider->update_template($template,$content); return $self->_detach_response($c,200,'Template Updated'); } sub create :Local { my ($self, $c, @args) = @_; my $template = $self->_resolve_template_name(@args) or die "No template specified"; local $self->{_current_context} = $c; $self->Access->template_creatable($template) or return $self->_detach_response($c,403,"Create template '$template' - Permission denied"); die "Create template '$template' - already exists" if $self->_template_exists($c,$template); $self->get_Provider->create_template($template) or die "Failed to create template '$template'"; return $self->_detach_response($c,200,"Created template '$template'"); } sub delete :Local { my ($self, $c, @args) = @_; my $template = $self->_resolve_template_name(@args) or die "No template specified"; local $self->{_current_context} = $c; $self->Access->template_deletable($template) or return $self->_detach_response($c,403,"Delete template '$template' - Permission denied"); die "Delete template '$template' - doesn't exists" unless $self->_template_exists($c,$template);; $self->get_Provider->delete_template($template) or die "Failed to delete template '$template'"; return $self->_detach_response($c,200,"Deleted template '$template'"); } sub _detach_response { my ($self, $c, $status, $body, $content_type) = @_; $content_type ||= 'text/plain; charset=utf-8'; $c->response->content_type($content_type); $c->response->status($status); $c->response->body($body); return $c->detach; } sub _render_template { my ($self, $meth, $template, $c) = @_; my $TT = $self->$meth; local $self->{_current_context} = $c; local $self->{_div_wrap} = 1 if ($meth eq 'Template_wrap'); my $vars = $self->get_wrapped_tt_vars($template); my $output; # TODO/FIXME: this is duplicate logic that has to be handled for the # top-level template which doesn't seem to go through process() in Context: $output = $self->Template_raw->context->_template_error_content( $template, $TT->error, ( $self->is_editable_request($c) && $self->Access->template_writable($template) ) ) unless $TT->process( $template, $vars, \$output ); return $output; } # Returns undef if the template is valid or the error sub _get_template_error { my ($self, $meth, $template, $c) = @_; my $TT = $self->$meth; local $self->{_current_context} = $c; local $self->{_div_wrap} = 1 if ($meth eq 'Template_wrap'); my $vars = $self->get_wrapped_tt_vars($template); my $output; local $self->{_no_exception_error_content} = 1; return $TT->process( $template, $vars, \$output ) ? undef : $TT->error; } # Internal render function - designed to be called interactively # from other parts of the application to render a template (i.e. # not associated with a Template::Controller request) # # TODO: This function will replace/merge with $c->template_render # in RapidApp::Role::CatalystApplication sub template_render { my ($self, $template, $vars, $c) = @_; $vars ||= {}; # The current context may not be available: # see DummyAccess in RapidApp::Template::Access: local $self->{_dummy_access} = 1 unless ($c); local $self->{_current_context} = $c || $self->_app; # The get_template_vars() API in the Access class expects # to have access to the catalyst context (i.e. request) so # we only call it and merge it in if we have $c, which is # optional in this method %$vars = (%{ $self->get_wrapped_tt_vars($template) }, %$vars) if ($c); my $TT = $self->Template_raw; my $out; $TT->process($template,$vars,\$out) or die $TT->error; return $out; } # Wraps all CodeRef vars to cleanly catch exceptions that may be # thrown by them. TT isn't able to handle them properly... sub get_wrapped_tt_vars { my ($self,$template) = @_; my $vars = $self->Access->get_template_vars($template); die "Access class method 'get_template_vars()' didn't return a HashRef!" unless (ref($vars) eq 'HASH'); for my $var (keys %$vars) { next unless (ref($vars->{$var}) eq 'CODE'); my $coderef = delete $vars->{$var}; $vars->{$var} = sub { my @args = @_; my $ret; try { $ret = $coderef->(@args); } catch { my $err_msg = "!! EXCEPTION IN CODEREF TEMPLATE VARIABLE '$var': $_"; # TODO/FIXME: # We set the return value with the exception as a string (i.e. as content) # instead of re-throwing because TT will display a useless and confusing # error message, something like: "...Useless bare catch()..." $ret = $err_msg; # We may not actually be able to see the error in the template rendering # but at least it will be printed on the console (an exception here isn't # actually a *Template* error, per-se ... its an error in the perl code # that is called by this CodeRef) warn RED.BOLD . $err_msg . CLEAR; }; return $ret; }; } return $vars; } 1;
set -euxo pipefail bash docker-build.sh pushd ../nakama bash docker-build.sh kubectl delete -f kubernetes/04-nakama-deployment.yml kubectl apply -f kubernetes/04-nakama-deployment.yml popd
#!/bin/bash ./analyze_xproduct.sh path/to/log_file_excluding_extension num_agents # eg for file pool3.log with a pool of 3 agents # ./analyze_xproduct.sh path/to/pool3 3
package org.deta.tinos.hash; import com.google.gson.Gson; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import org.json.JSONObject; import org.json.XML; public class HashSwap{ public static String hashTableToJson(Gson gson , Hashtable<String, Object> hashtable) { return gson.toJson(hashtable); } public static String hashTableToXml(Gson gson , Hashtable<String, Object> hashtable){ JSONObject jSONObject= new JSONObject(gson.toJson(hashtable)); return XML.toString(jSONObject); } public static List<Object> hashTableToList(Gson gson , Hashtable<String, Object> hashtable){ List<Object> list= new ArrayList<>(); Iterator<String> iterator= hashtable.keySet().iterator(); while(iterator.hasNext()) { list.add(hashtable.get(iterator.next())); } return list; } public static Object[] hashTableToObjectArray(Gson gson , Hashtable<String, Object> hashtable){ List<Object> list= new ArrayList<>(); Iterator<String> iterator= hashtable.keySet().iterator(); while(iterator.hasNext()) { list.add(hashtable.get(iterator.next())); } return list.toArray(); } }
namespace Dolittle.Serialization.Json.Specs.for_Serializer { using System; using System.Collections.Generic; using System.Linq; using Machine.Specifications; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Dolittle.PropertyBags; using Dolittle.Concepts; using Serialization.Json; public class Immutable : Value<Immutable> { public String Label { get; } public Guid Guid { get; } public Immutable(Guid guid, String label) { Label = label; Guid = guid; } } }
using System; using System.Collections; using NUnit.Framework; using NUnit.Framework.Constraints; #pragma warning disable 1584,1711,1572,1581,1580 namespace NUnit.StaticExpect { public static partial class Expectations { /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public static CollectionOrderedConstraint Ordered => Is.Ordered; /// Summary: /// <summary> /// Returns a ConstraintExpression that negates any following constraint. /// </summary> public static ConstraintExpression Not => Is.Not; /// <summary> /// Returns a ConstraintExpression, which will apply the following constraint to /// all members of a collection, succeeding if all of them succeed. /// </summary> public static ConstraintExpression All => Is.All; /// <summary> /// Returns a constraint that tests for null /// </summary> public static NullConstraint Null => Is.Null; /// <summary> /// Returns a constraint that tests for True /// </summary> public static TrueConstraint True => Is.True; /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public static GreaterThanConstraint Positive => Is.Positive; /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public static LessThanConstraint Negative => Is.Negative; /// <summary> /// Returns a constraint that tests for False /// </summary> public static FalseConstraint False => Is.False; /// <summary> /// Returns a constraint that tests for equality with zero /// </summary> public static EqualConstraint Zero => Is.Zero; /// <summary> /// Returns a constraint that tests for NaN /// </summary> public static NaNConstraint NaN => Is.NaN; /// <summary> /// Returns a constraint that tests for empty /// </summary> public static EmptyConstraint Empty => Is.Empty; /// <summary> /// Returns a constraint that tests whether a collection contains all unique items. /// </summary> public static UniqueItemsConstraint Unique => Is.Unique; #if NETSTANDARD1_4 #else /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary /// format. /// </summary> public static BinarySerializableConstraint BinarySerializable => Is.BinarySerializable; /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml /// format. /// </summary> public static XmlSerializableConstraint XmlSerializable => Is.XmlSerializable; #endif /// <summary> /// Returns a constraint that tests whether the actual value is assignable from the /// type supplied as an argument. /// </summary> /// <param name="expectedType"></param> /// <returns></returns> public static AssignableFromConstraint AssignableFrom(Type expectedType) { return Is.AssignableFrom(expectedType); } /// <summary> /// Returns a constraint that tests whether the actual value is assignable from the /// type supplied as an argument. /// </summary> /// <typeparam name="TExpected"></typeparam> /// <returns></returns> public static AssignableFromConstraint AssignableFrom<TExpected>() { return Is.AssignableFrom<TExpected>(); } /// <summary> /// Returns a constraint that tests whether the actual value is assignable to the /// type supplied as an argument. /// </summary> /// <param name="expectedType"></param> /// <returns></returns> public static AssignableToConstraint AssignableTo(Type expectedType) { return Is.AssignableTo(expectedType); } /// <summary> /// Returns a constraint that tests whether the actual value is assignable to the /// type supplied as an argument. /// </summary> /// <typeparam name="TExpected"></typeparam> /// <returns></returns> public static AssignableToConstraint AssignableTo<TExpected>() { return Is.AssignableTo<TExpected>(); } /// <summary> /// Returns a constraint that tests whether the actual value is greater than or equal /// to the supplied argument /// </summary> public static Func<object, GreaterThanOrEqualConstraint> AtLeast => Is.AtLeast; /// <summary> /// Returns a constraint that tests whether the provided values are /// </summary> public static Func<object[], AnyOfConstraint> AnyOf => Is.AnyOf; /// <summary> /// Returns a constraint that tests whether the actual value is less than or equal /// to the supplied argument /// </summary> public static Func<object, LessThanOrEqualConstraint> AtMost => Is.AtMost; /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public static Func<object, EqualConstraint> EqualTo => Is.EqualTo; /// <summary> /// Returns a constraint that tests whether the actual value is a collection containing /// the same elements as the collection supplied as an argument. /// </summary> public static Func<IEnumerable, CollectionEquivalentConstraint> EquivalentTo => Is.EquivalentTo; /// <summary> /// Returns a constraint that tests whether the actual value is greater than the /// supplied argument /// </summary> public static Func<object, GreaterThanConstraint> GreaterThan => Is.GreaterThan; /// <summary> /// Returns a constraint that tests whether the actual value is greater than or equal /// to the supplied argument /// </summary> public static Func<object, GreaterThanOrEqualConstraint> GreaterThanOrEqualTo => Is.GreaterThanOrEqualTo; /// <summary> /// Returns a constraint that tests whether the actual value falls inclusively within /// a specified range. /// <param name="from">Inclusive beginning of the range. Must be less than or equal to to.</param> /// <param name="to">Inclusive end of the range. Must be greater than or equal to from.</param> /// <remarks>from must be less than or equal to true</remarks> /// </summary> public static Func<Object, Object, RangeConstraint> InRange => Is.InRange; /// <summary> /// Returns a constraint that tests whether the actual value is of the type supplied /// as an argument or a derived type. /// </summary> /// <typeparam name="TExpected"></typeparam> /// <returns></returns> public static InstanceOfTypeConstraint InstanceOf<TExpected>() { return Is.InstanceOf<TExpected>(); } /// <summary> /// Returns a constraint that tests whether the actual value is of the type supplied /// as an argument or a derived type. /// </summary> /// <param name="expectedType"></param> /// <returns></returns> public static InstanceOfTypeConstraint InstanceOf(Type expectedType) { return Is.InstanceOf(expectedType); } /// <summary> /// Returns a constraint that tests whether the actual value is less than the supplied /// argument /// </summary> public static Func<object, LessThanConstraint> LessThan => Is.LessThan; /// <summary> /// Returns a constraint that tests whether the actual value is less than or equal /// to the supplied argument /// </summary> public static Func<object, LessThanOrEqualConstraint> LessThanOrEqualTo => Is.LessThanOrEqualTo; /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public static Func<object, SameAsConstraint> SameAs => Is.SameAs; /// <summary> /// Returns a constraint that tests whether the path provided is the same as an expected /// path after canonicalization. /// </summary> public static Func<string, SamePathConstraint> SamePath => Is.SamePath; /// <summary> /// Returns a constraint that tests whether the path provided is the same path or /// under an expected path after canonicalization. /// </summary> public static Func<string, SamePathOrUnderConstraint> SamePathOrUnder => Is.SamePathOrUnder; /// <summary> /// Returns a constraint that tests whether the path provided is a subpath of the /// expected path after canonicalization. /// </summary> public static Func<string, SubPathConstraint> SubPathOf => Is.SubPathOf; /// <summary> /// Returns a constraint that tests whether the actual value is a subset of the collection /// supplied as an argument. /// </summary> public static Func<IEnumerable, CollectionSubsetConstraint> SubsetOf => Is.SubsetOf; /// <summary> /// Returns a constraint that tests whether the actual value is a superset of the /// collection supplied as an argument. /// </summary> public static Func<IEnumerable, CollectionSupersetConstraint> SupersetOf => Is.SupersetOf; /// <summary> /// Returns a constraint that tests whether the actual value is of the exact type /// supplied as an argument. /// </summary> /// <typeparam name="TExpected"></typeparam> /// <returns></returns> public static ExactTypeConstraint TypeOf<TExpected>() { return Is.TypeOf<TExpected>(); } /// <summary> /// Returns a constraint that tests whether the actual value is of the exact type /// supplied as an argument. /// </summary> /// <param name="expectedType"></param> /// <returns></returns> public static ExactTypeConstraint TypeOf(Type expectedType) { return Is.TypeOf(expectedType); } } }
package net.slingspot.io import java.io.File import java.io.IOException public class DefaultFileSystem : FileSystem { override val separator: String = File.separator override fun fileAt(path: String): FileRef { return DefaultFileRef(path) } override fun textFileAt(path: String): TextFileRef { return DefaultTextFileRef(path) } override fun directoryAt(path: String): DirectoryRef { return DefaultDirectoryRef(path) } internal open class DefaultFileRef(final override val path: String) : FileRef { protected val file: File = File(path) override fun create() { file.createNewFile() } override fun delete() { file.delete() } override fun exists(): Boolean { return file.exists() } override fun length(): Long { return file.length() } override fun asDirectory(): DirectoryRef? { return if (file.isDirectory) DefaultDirectoryRef(path) else null } override fun compareTo(other: FileRef): Int { return file.compareTo((other as DefaultFileRef).file) } override fun equals(other: Any?) = this === other || (other is DefaultFileRef && file == other.file) override fun hashCode() = file.hashCode() } internal open class DefaultTextFileRef(path: String) : DefaultFileRef(path), TextFileRef { override fun append(text: String) { file.appendText(text) } } internal class DefaultDirectoryRef(path: String) : DefaultFileRef(path), DirectoryRef { override fun create() { file.mkdirs() } override fun contents(): List<FileRef> { return file.listFiles()?.sorted()?.map { DefaultFileRef(it.absolutePath) } ?: throw IOException("Directory does not exist") } } }
const ajax = require('./ajax') const FIX_URL = require('../utils').getFIX_URL() exports.login = (data) => ajax('/login', data) exports.getDynamic = (data) => ajax('/v2/getConditionDynamic', data) exports.getDetailDynamic = (data) => ajax('/v2/getDetailDynamic', data) exports.getConditionComment = (data) => ajax('/v2/getConditionComment', data) exports.sumitCommont = (data) => ajax('/v1/commont', data) exports.postDynamic = (data) => ajax('/v1/postDynamic', data) exports.joinYqy = (data) => ajax('/v1/joinYqy', data) exports.getUserJoinList = (data) => ajax('/v1/getUserJoinList', data) exports.getUserDynamicList = (data) => ajax('/v1/getUserDynamicList', data) exports.deleteUserDynamic = (data) => ajax('/v1/deleteUserDynamic', data) exports.loginUrl = `${FIX_URL}/v2/login` exports.uptokenURL = `${FIX_URL}/v2/qnUptoken`
package aic.gas.mas.model; import aic.gas.mas.model.metadata.DesireKey; /** * Contract defining method to be implemented by each class which wants enable user to get desire * key associated with class */ public interface DesireKeyIdentificationInterface { /** * Returns DesireKey associated with this instance */ DesireKey getDesireKey(); }
""" Senta model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import six import json import numpy as np import paddle.fluid as fluid class SentaConfig(object): """ Senta Config """ def __init__(self, config_path): self._config_dict = self._parse(config_path) def _parse(self, config_path): try: with open(config_path) as json_file: config_dict = json.load(json_file) except Exception: raise IOError("Error in parsing bert model config file '%s'" % config_path) else: return config_dict def __getitem__(self, key): return self._config_dict[key] def print_config(self): """ Print Config """ for arg, value in sorted(six.iteritems(self._config_dict)): print('%s: %s' % (arg, value)) print('------------------------------------------------')
// <Snippet1> #define _WINSOCKAPI_ #include <windows.h> #include <sal.h> #include <httpserv.h> // Create the module's global class. class MyGlobalModule : public CGlobalModule { public: GLOBAL_NOTIFICATION_STATUS OnGlobalPreBeginRequest( IN IPreBeginRequestProvider * pProvider ) { UNREFERENCED_PARAMETER( pProvider ); // Retrieve a pointer to the IHttpContext for the request. IHttpContext * pHttpContext = pProvider->GetHttpContext(); // Test for an error. if (NULL != pHttpContext) { // Retrieve a pointer to an IHttpSite class. IHttpSite * pHttpSite = pHttpContext->GetSite(); // Test for an error. if (NULL != pHttpSite) { // Retrieve the site name. PCWSTR pwszSiteName = pHttpSite->GetSiteName(); // Test for an error. if (NULL != pwszSiteName) { // Allocate storage for the site name. char * pszSiteName = (char *) pHttpContext->AllocateRequestMemory( (DWORD) wcslen(pwszSiteName)+1 ); // Test for an error. if (NULL != pszSiteName) { // Convert the site name. wcstombs(pszSiteName,pwszSiteName, wcslen(pwszSiteName)); // Create an array of strings. LPCSTR szBuffer[2] = {"Site Name",""}; // Store the site name. szBuffer[1] = pszSiteName; // Write the strings to the Event Viewer. WriteEventViewerLog(szBuffer,2); } } } } // Return processing to the pipeline. return GL_NOTIFICATION_CONTINUE; } VOID Terminate() { // Remove the class from memory. delete this; } MyGlobalModule() { // Open a handle to the Event Viewer. MyGlobalModule::m_hEventLog = RegisterEventSource( NULL,"IISADMIN" ); } ~MyGlobalModule() { // Test if the handle for the Event Viewer is open. if (NULL != MyGlobalModule::m_hEventLog) { DeregisterEventSource( MyGlobalModule::m_hEventLog ); MyGlobalModule::m_hEventLog = NULL; } } private: // Handle for the Event Viewer. HANDLE m_hEventLog; // Define a method that writes to the Event Viewer. BOOL WriteEventViewerLog(LPCSTR szBuffer[], WORD wNumStrings) { // Test whether the handle for the Event Viewer is open. if (NULL != MyGlobalModule::m_hEventLog) { // Write any strings to the Event Viewer and return. return ReportEvent( MyGlobalModule::m_hEventLog, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, wNumStrings, 0, szBuffer, NULL ); } return FALSE; } }; // Create the module's exported registration function. HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pGlobalInfo ) { UNREFERENCED_PARAMETER( dwServerVersion ); UNREFERENCED_PARAMETER( pGlobalInfo ); // Create an instance of the global module class. MyGlobalModule * pGlobalModule = new MyGlobalModule; // Test for an error. if (NULL == pGlobalModule) { return HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY); } // Set the global notifications and exit. return pModuleInfo->SetGlobalNotifications( pGlobalModule, GL_PRE_BEGIN_REQUEST ); } // </Snippet1>
package modbat.mbt import modbat.config.ConfigMgr import modbat.config.Version import modbat.log.Log object Main { val config = new Configuration() def main(args: Array[String]) { Modbat.isUnitTest = false System.exit(run(args)) } def run(args: Array[String]): Int = { var modelClassName: String = null val c = new ConfigMgr("scala modbat.jar", "CLASSNAME", config, new Version ("modbat.mbt")) /* delegate parsing args to config library */ try { val remainder = c.parseArgs(args) remainder match { case Some(remainingArgs) => { if (!remainingArgs.hasNext) { Log.error(c.header) Log.error("Model class argument missing. Try --help.") return 1 } modelClassName = remainingArgs.next if (remainingArgs.hasNext) { Log.error("Extra arguments starting at \"" + remainingArgs.next() + "\" are not supported.") return 1 } } case None => // nothing } } catch { case e: IllegalArgumentException => { Log.error(e.getMessage()) return 1 } } setup(modelClassName) // TODO: refactor into case code below once needed Modbat.init /* execute */ config.mode match { case "dot" => new Dotify(MBT.launch(null), modelClassName + ".dot").dotify() case _ => Modbat.explore(config.nRuns) } // TODO (issue #27): Dotify.dotify() and Modbat.explore() should use return code } def setup(modelClassName: String) { /* configure components */ Log.setLevel(config.logLevel) MBT.enableStackTrace = config.printStackTrace MBT.maybeProbability = config.maybeProbability MBT.configClassLoader(config.classpath) MBT.loadModelClass(modelClassName) MBT.setRNG(config.randomSeed) MBT.isOffline = false MBT.runBefore = config.setup MBT.runAfter = config.cleanup MBT.precondAsFailure = config.precondAsFailure } }
<?php /** @noinspection PhpUndefinedClassInspection */ namespace App\Http\Controllers; use App\Models\Configs; use App\Models\Logs; use App\Models\Photo; use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Illuminate\View\View; class ViewController extends Controller { /** * Just the constructor * This also shows how to apply a middlewear directly in a controller. * * ViewController constructor. */ public function __construct() { $this->middleware([]); } /** * View is only used when sharing a single picture. * * @param Request $request * * @return View|void */ public function view(Request $request) { $request->validate([ 'p' => 'required', ]); $photo = Photo::find($request->get('p')); if ($photo == null) { Logs::error(__METHOD__, __LINE__, 'Could not find photo in database'); return abort(404); } // is the picture public ? $public = $photo->public == '1'; // is the album (if exist) public ? if ($photo->album_id != null) { $public = $photo->album->public == '1' || $public; } // return 403 if not allowed if (!$public) { return abort(403); } if ($photo->medium == '1') { $dir = 'medium'; } else { $dir = 'big'; } $title = Configs::get_value('site_title', Config::get('defines.defaults.SITE_TITLE')); $url = config('app.url') . $request->server->get('REQUEST_URI'); $picture = config('app.url') . '/uploads/' . $dir . '/' . $photo->url; return view('view', [ 'url' => $url, 'photo' => $photo, 'picture' => $picture, 'title' => $title, ]); } }
import React, { useContext } from "react"; import { ActionTypes, ModalsContext } from "modules/explorer/ModalsContext"; import { useParams } from "react-router"; import { PrimaryButton } from "modules/explorer/components/styled/PrimaryButton"; import { TemplateHeader } from "modules/explorer/components/TemplateHeader"; export const RegistryHeader: React.FC = () => { const { id } = useParams<{ id: string }>(); const { dispatch } = useContext(ModalsContext); return ( <TemplateHeader template="registry"> <PrimaryButton variant="outlined" onClick={() => dispatch({ type: ActionTypes.OPEN_REGISTRY_PROPOSAL, payload: { isUpdate: false, daoAddress: id, }, }) } > NEW ITEM </PrimaryButton> </TemplateHeader> ); };
from color import get_color_from_screen_pixel,set_color_board_horizontal from . import utils def light_screen_rainbow_horizontal(board): color = get_color_from_screen_pixel() set_color_board_horizontal(board.board,color) utils.apply_light(board)
/* * Copyright 2016 Azavea * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package geotrellis.vector package summary.polygonal /** Companion object to [[PolygonalSummaryHandler]] */ object PolygonalSummaryHandler { def apply[G <: Geometry, D, T] (handleContainsFn: Feature[G, D] => T) (handleIntersectionFn: (Polygon, Feature[G, D]) => T) (combineOpFn: (T, T) => T): PolygonalSummaryHandler[G, D, T] = new PolygonalSummaryHandler[G, D, T] { def handleContains(feature: Feature[G, D]): T = handleContainsFn(feature) def handleIntersection(polygon: Polygon, feature: Feature[G, D]): T = handleIntersectionFn(polygon, feature) def combineOp(v1: T, v2: T): T = combineOpFn(v1, v2) } } /** This trait provides the scaffolding necessary to generate aggregations * which depend on [[Polygon]] and [[MultiPolygon]] instances. * * @note This trait specifies the type of operation to be carried out but *NOT* the "zero * element" which determines the beginning value for a chain of operations (like the * starting element in a fold) and *NOT* the [[Polygon]] or [[MultiPolygon]] to be * used during a summary. Instead, those are specified in a call to mergeOp which * returns the function used in an actual summarization. * * @tparam G the [[Geometry]] type against which containment and intersection checks are * carried out to determine the flow of aggregation logic * @tparam D the type of any data expected to be associated with G in [[Feature]] instances * @tparam T the type being aggregated to through summary mergeOp calls * * @param handleContains the function to be called on a feature when it is determined that * said feature is contained by the [[Polygon]] or [[MultiPolygon]] used * in this trait's mergeOp functions * @param handleIntersection the function to be called on a feature when it is determined that * said feature is not contained by the [[Polygon]] or * [[MultiPolygon]] used in this trait's mergeOp functions * @param combineOp the function to be called when combining intermedite aggregation results * */ trait PolygonalSummaryHandler[G <: Geometry, D, T] extends Serializable { def handleContains(feature: Feature[G, D]): T def handleIntersection(polygon: Polygon, feature: Feature[G, D]): T def combineOp(v1: T, v2: T): T /** Given a polygon and a zerovalue, this function returns a function * which can be used to compute aggregations */ def mergeOp(polygon: Polygon, zeroValue: T): (T, Feature[G, D]) => T = { def seqOp(v: T, feature: Feature[G, D]): T = { val rs: T = if (polygon.contains(feature.geom)) handleContains(feature) else { val polys = polygon.intersection(feature.geom) match { case intersectionPoly: Polygon => Seq(intersectionPoly) case mp: MultiPolygon => mp.polygons.toSeq case _ => Seq() } polys .map { polygon => handleIntersection(polygon, feature) } .fold(zeroValue) { (v1: T, v2: T) => combineOp(v1, v2) } } combineOp(v, rs) } seqOp } /** Given a polygon and a zerovalue, this function returns a function * which can be used to compute aggregations */ def mergeOp(multiPolygon: MultiPolygon, zeroValue: T): (T, Feature[G, D]) => T = { def seqOp(v: T, feature: Feature[G, D]): T = { val rs: T = if (multiPolygon.contains(feature.geom)) handleContains(feature) else { val polys = multiPolygon.intersection(feature.geom) match { case intersectionPoly: Polygon => Seq(intersectionPoly) case mp: MultiPolygon => mp.polygons.toSeq case _ => Seq() } polys .map { polygon => handleIntersection(polygon, feature) } .fold(zeroValue) { (v1: T, v2: T) => combineOp(v1, v2) } } combineOp(v, rs) } seqOp } }
import { Provider } from "react-redux"; import store from "store/index"; import "./Katip.scss"; import Navigation from "../layout/Navigation"; import Footer from "../layout/Footer"; import ActionsMenu from "./actions-menu/ActionsMenu"; import Cirak from "./Cirak"; import LHSWidgets from "./LHSWidgets"; import NoteSheetArea from "./NoteSheetArea"; const Katip = () => { return ( <Provider store={store}> <div className="page-grid"> <Navigation /> <LHSWidgets /> <main> <ActionsMenu /> <NoteSheetArea /> </main> <Cirak /> <Footer /> </div> </Provider> ); }; export default Katip;
export interface InterfaceAssetTest { id?: string | null; created_at?: Date; updated_at?: Date; completed_at?: Date; asset_id: string; answered_count: number; capabilities: {[category_capability_id: string]: string}; }
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ // Set translation strings $GLOBALS['strDeliveryEngine'] = "Teslimat Motoru"; $GLOBALS['strMaintenance'] = "Bakım"; $GLOBALS['strAdministrator'] = "Yönetici"; // Audit $GLOBALS['strDeleted'] = "Sil"; $GLOBALS['strDelete'] = "Sil"; $GLOBALS['strFilters'] = "Filtreler"; $GLOBALS['strAdvertiser'] = "Reklamveren"; $GLOBALS['strPublisher'] = "Web sitesi"; $GLOBALS['strCampaign'] = "Kampanya"; $GLOBALS['strZone'] = "Alan"; $GLOBALS['strType'] = "Tip"; $GLOBALS['strAction'] = "Eylem"; $GLOBALS['strParameter'] = "Değişkenler"; $GLOBALS['strValue'] = "Değer"; $GLOBALS['strAuditResultsNotFound'] = "Seçilen kriterlere uyan etkinlik bulunamadı"; $GLOBALS['strCollectedAllEvents'] = "Tüm etkinlikler"; if (!isset($GLOBALS['strUserlog'])) { $GLOBALS['strUserlog'] = array(); } $GLOBALS['strUserlog'][phpAds_actionActiveCampaign] = "{id} kampanyası etkinleştirildi"; $GLOBALS['strUserlog'][phpAds_actionActivationMailed] = "Veritabanını otomatik temizle";
Rails.application.routes.draw do mount Nestedcomments::Engine => "/nestedcomments" end
package exercises.part3concurrency object JvmThreadLiveLock extends App { case class Friend(name: String){ var side = "right" def switchSide(): Unit = { side = if (side == "right") "left" else "right" } def pass(other: Friend): Unit = { while(this.side == other.side) { println(s"$this: oh, but please, $other, feel free to pass...") switchSide() Thread.sleep(1000) } } } val sam = Friend("Sam") val pierre = Friend("Pierre") new Thread(() => sam.pass(pierre)).start() new Thread(() => pierre.pass(sam)).start() }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.retailcloud.Model.V20180313; namespace Aliyun.Acs.retailcloud.Transform.V20180313 { public class ListPersistentVolumeResponseUnmarshaller { public static ListPersistentVolumeResponse Unmarshall(UnmarshallerContext _ctx) { ListPersistentVolumeResponse listPersistentVolumeResponse = new ListPersistentVolumeResponse(); listPersistentVolumeResponse.HttpResponse = _ctx.HttpResponse; listPersistentVolumeResponse.RequestId = _ctx.StringValue("ListPersistentVolume.RequestId"); listPersistentVolumeResponse.Code = _ctx.IntegerValue("ListPersistentVolume.Code"); listPersistentVolumeResponse.PageSize = _ctx.IntegerValue("ListPersistentVolume.PageSize"); listPersistentVolumeResponse.PageNumber = _ctx.IntegerValue("ListPersistentVolume.PageNumber"); listPersistentVolumeResponse.TotalCount = _ctx.LongValue("ListPersistentVolume.TotalCount"); listPersistentVolumeResponse.ErrMsg = _ctx.StringValue("ListPersistentVolume.ErrMsg"); List<ListPersistentVolumeResponse.ListPersistentVolume_PersistentVolumeDetail> listPersistentVolumeResponse_data = new List<ListPersistentVolumeResponse.ListPersistentVolume_PersistentVolumeDetail>(); for (int i = 0; i < _ctx.Length("ListPersistentVolume.Data.Length"); i++) { ListPersistentVolumeResponse.ListPersistentVolume_PersistentVolumeDetail persistentVolumeDetail = new ListPersistentVolumeResponse.ListPersistentVolume_PersistentVolumeDetail(); persistentVolumeDetail.Name = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].Name"); persistentVolumeDetail.Capacity = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].Capacity"); persistentVolumeDetail.AccessModes = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].AccessModes"); persistentVolumeDetail.ReclaimPolicy = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].ReclaimPolicy"); persistentVolumeDetail.Status = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].Status"); persistentVolumeDetail.PvcName = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].PvcName"); persistentVolumeDetail.MountDir = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].MountDir"); persistentVolumeDetail.StorageClass = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].StorageClass"); persistentVolumeDetail.Reason = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].Reason"); persistentVolumeDetail.CreateTime = _ctx.StringValue("ListPersistentVolume.Data["+ i +"].CreateTime"); listPersistentVolumeResponse_data.Add(persistentVolumeDetail); } listPersistentVolumeResponse.Data = listPersistentVolumeResponse_data; return listPersistentVolumeResponse; } } }
using SSBHLib.IO; namespace SSBHLib.Formats.Meshes { public enum SsbVertexAttribFormat { Float = 0, Byte = 2, HalfFloat = 5, HalfFloat2 = 8, } [SsbhFile("HSEM")] public class Mesh : SsbhFile { public uint Magic { get; set; } = 0x4D455348; public ushort VersionMajor { get; set; } = 0x1;// 0x0001 public ushort VersionMinor { get; set; } = 0xA;// 0x000A and 0x0008 - Most use 0x000A public string ModelName { get; set; } = "";// unused public float BoundingSphereX { get; set; } public float BoundingSphereY { get; set; } public float BoundingSphereZ { get; set; } public float BoundingSphereRadius { get; set; } public float MinBoundingBoxX { get; set; } public float MinBoundingBoxY { get; set; } public float MinBoundingBoxZ { get; set; } public float MaxBoundingBoxX { get; set; } public float MaxBoundingBoxY { get; set; } public float MaxBoundingBoxZ { get; set; } public float ObbCenterX { get; set; } public float ObbCenterY { get; set; } public float ObbCenterZ { get; set; } public float M11 { get; set; } public float M12 { get; set; } public float M13 { get; set; } public float M21 { get; set; } public float M22 { get; set; } public float M23 { get; set; } public float M31 { get; set; } public float M32 { get; set; } public float M33 { get; set; } public float ObbSizeX { get; set; } public float ObbSizeY { get; set; } public float ObbSizeZ { get; set; } public float UnkBounding0 { get; set; } public MeshObject[] Objects { get; set; } public int[] BufferSizes { get; set; } public long PolygonIndexSize { get; set; } // seems to match index count? public MeshBuffer[] VertexBuffers { get; set; } public byte[] PolygonBuffer { get; set; } public MeshRiggingGroup[] RiggingBuffers { get; set; } public long UnknownOffset { get; set; } public long UnknownSize { get; set; } } }
; Copyright (c) Rich Hickey, Reid Draper, and contributors. ; All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.test.check.generators (:refer-clojure :exclude [int vector list hash-map map keyword char boolean byte bytes sequence shuffle not-empty symbol namespace set sorted-set uuid double let]) (:require [#?(:clj clojure.core :cljs cljs.core) :as core #?@(:cljs [:include-macros true])] [clojure.test.check.random :as random] [clojure.test.check.rose-tree :as rose] #?@(:cljs [[goog.string :as gstring] [clojure.string]]))) ;; Gen ;; (internal functions) ;; --------------------------------------------------------------------------- (defrecord Generator [gen]) (defn generator? "Test if `x` is a generator. Generators should be treated as opaque values." [x] (instance? Generator x)) (defn- make-gen [generator-fn] (Generator. generator-fn)) (defn call-gen {:no-doc true} [{generator-fn :gen} rnd size] (generator-fn rnd size)) (defn gen-pure {:no-doc true} [value] (make-gen (fn [rnd size] value))) (defn gen-fmap {:no-doc true} [k {h :gen}] (make-gen (fn [rnd size] (k (h rnd size))))) (defn gen-bind {:no-doc true} [{h :gen} k] (make-gen (fn [rnd size] (core/let [[r1 r2] (random/split rnd) inner (h r1 size) {result :gen} (k inner)] (result r2 size))))) (defn lazy-random-states "Given a random number generator, returns an infinite lazy sequence of random number generators." [rr] (lazy-seq (core/let [[r1 r2] (random/split rr)] (cons r1 (lazy-random-states r2))))) (defn- gen-seq->seq-gen "Takes a sequence of generators and returns a generator of sequences (er, vectors)." [gens] (make-gen (fn [rnd size] (mapv #(call-gen % %2 size) gens (random/split-n rnd (count gens)))))) ;; Exported generator functions ;; --------------------------------------------------------------------------- (defn fmap [f gen] (assert (generator? gen) "Second arg to fmap must be a generator") (gen-fmap #(rose/fmap f %) gen)) (defn return "Create a generator that always returns `value`, and never shrinks. You can think of this as the `constantly` of generators." [value] (gen-pure (rose/pure value))) (defn- bind-helper [k] (fn [rose] (gen-fmap rose/join (make-gen (fn [rnd size] (rose/fmap #(call-gen % rnd size) (rose/fmap k rose))))))) (defn bind "Create a new generator that passes the result of `gen` into function `k`. `k` should return a new generator. This allows you to create new generators that depend on the value of other generators. For example, to create a generator which first generates a vector of integers, and then chooses a random element from that vector: (gen/bind (gen/such-that not-empty (gen/vector gen/int)) ;; this function takes a realized vector, ;; and then returns a new generator which ;; chooses a random element from it gen/elements) " [generator k] (assert (generator? generator) "First arg to bind must be a generator") (gen-bind generator (bind-helper k))) ;; Helpers ;; --------------------------------------------------------------------------- (defn make-size-range-seq {:no-doc true} [max-size] (cycle (range 0 max-size))) (defn sample-seq "Return a sequence of realized values from `generator`." ([generator] (sample-seq generator 100)) ([generator max-size] (core/let [r (random/make-random) size-seq (make-size-range-seq max-size)] (core/map #(rose/root (call-gen generator %1 %2)) (lazy-random-states r) size-seq)))) (defn sample "Return a sequence of `num-samples` (default 10) realized values from `generator`." ([generator] (sample generator 10)) ([generator num-samples] (assert (generator? generator) "First arg to sample must be a generator") (take num-samples (sample-seq generator)))) (defn generate "Returns a single sample value from the generator, using a default size of 30." ([generator] (generate generator 30)) ([generator size] (core/let [rng (random/make-random)] (rose/root (call-gen generator rng size))))) ;; Internal Helpers ;; --------------------------------------------------------------------------- (defn- halfs [n] (take-while #(not= 0 %) (iterate #(quot % 2) n))) (defn- shrink-int [integer] (core/map #(- integer %) (halfs integer))) (defn- int-rose-tree [value] (rose/make-rose value (core/map int-rose-tree (shrink-int value)))) ;; calc-long is factored out to support testing the surprisingly tricky double math. Note: ;; An extreme long value does not have a precision-preserving representation as a double. ;; Be careful about changing this code unless you understand what's happening in these ;; examples: ;; ;; (= (long (- Integer/MAX_VALUE (double (- Integer/MAX_VALUE 10)))) 10) ;; (= (long (- Long/MAX_VALUE (double (- Long/MAX_VALUE 10)))) 0) (defn- calc-long [factor lower upper] ;; these pre- and post-conditions are disabled for deployment #_ {:pre [(float? factor) (>= factor 0.0) (< factor 1.0) (integer? lower) (integer? upper) (<= lower upper)] :post [(integer? %)]} ;; Use -' on width to maintain accuracy with overflow protection. #?(:clj (core/let [width (-' upper lower -1)] ;; Preserve long precision if the width is in the long range. Otherwise, we must accept ;; less precision because doubles don't have enough bits to preserve long equivalence at ;; extreme values. (if (< width Long/MAX_VALUE) (+ lower (long (Math/floor (* factor width)))) ;; Clamp down to upper because double math. (min upper (long (Math/floor (+ lower (* factor width))))))) :cljs (long (Math/floor (+ lower (- (* factor (+ 1.0 upper)) (* factor lower))))))) (defn- rand-range [rnd lower upper] {:pre [(<= lower upper)]} (calc-long (random/rand-double rnd) lower upper)) (defn sized "Create a generator that depends on the size parameter. `sized-gen` is a function that takes an integer and returns a generator." [sized-gen] (make-gen (fn [rnd size] (core/let [sized-gen (sized-gen size)] (call-gen sized-gen rnd size))))) ;; Combinators and helpers ;; --------------------------------------------------------------------------- (defn resize "Create a new generator with `size` always bound to `n`." [n generator] (assert (generator? generator) "Second arg to resize must be a generator") (core/let [{:keys [gen]} generator] (make-gen (fn [rnd _size] (gen rnd n))))) (defn scale "Create a new generator that modifies the size parameter by the given function. Intended to support generators with sizes that need to grow at different rates compared to the normal linear scaling." ([f generator] (sized (fn [n] (resize (f n) generator))))) (defn choose #?(:clj "Create a generator that returns long integers in the range `lower` to `upper`, inclusive." :cljs "Create a generator that returns numbers in the range `lower` to `upper`, inclusive.") [lower upper] ;; cast to long to support doubles as arguments per TCHECK-73 (core/let #?(:clj [lower (long lower) upper (long upper)] :cljs ;; does nothing, no long in cljs []) (make-gen (fn [rnd _size] (core/let [value (rand-range rnd lower upper)] (rose/filter #(and (>= % lower) (<= % upper)) (int-rose-tree value))))))) (defn one-of "Create a generator that randomly chooses a value from the list of provided generators. Shrinks toward choosing an earlier generator, as well as shrinking the value generated by the chosen generator. Examples: (one-of [gen/int gen/boolean (gen/vector gen/int)]) " [generators] (assert (every? generator? generators) "Arg to one-of must be a collection of generators") (bind (choose 0 (dec (count generators))) #(nth generators %))) (defn- pick [[h & tail] n] (core/let [[chance gen] h] (if (<= n chance) gen (recur tail (- n chance))))) (defn frequency "Create a generator that chooses a generator from `pairs` based on the provided likelihoods. The likelihood of a given generator being chosen is its likelihood divided by the sum of all likelihoods Examples: (gen/frequency [[5 gen/int] [3 (gen/vector gen/int)] [2 gen/boolean]]) " [pairs] (assert (every? (fn [[x g]] (and (number? x) (generator? g))) pairs) "Arg to frequency must be a list of [num generator] pairs") (core/let [total (apply + (core/map first pairs))] (gen-bind (choose 1 total) #(pick pairs (rose/root %))))) (defn elements "Create a generator that randomly chooses an element from `coll`. Examples: (gen/elements [:foo :bar :baz]) " [coll] (assert (seq coll) "elements cannot be called with an empty collection") (core/let [v (vec coll)] (gen-bind (choose 0 (dec (count v))) #(gen-pure (rose/fmap v %))))) (defn- such-that-helper [max-tries pred gen tries-left rng size] (if (zero? tries-left) (throw (ex-info (str "Couldn't satisfy such-that predicate after " max-tries " tries.") {})) (core/let [[r1 r2] (random/split rng) value (call-gen gen r1 size)] (if (pred (rose/root value)) (rose/filter pred value) (recur max-tries pred gen (dec tries-left) r2 (inc size)))))) (defn such-that "Create a generator that generates values from `gen` that satisfy predicate `pred`. Care is needed to ensure there is a high chance `gen` will satisfy `pred`. By default, `such-that` will try 10 times to generate a value that satisfies the predicate. If no value passes this predicate after this number of iterations, a runtime exception will be throw. You can pass an optional third argument to change the number of times tried. Note also that each time such-that retries, it will increase the size parameter. Examples: ;; generate non-empty vectors of integers ;; (note, gen/not-empty does exactly this) (gen/such-that not-empty (gen/vector gen/int)) " ([pred gen] (such-that pred gen 10)) ([pred gen max-tries] (assert (generator? gen) "Second arg to such-that must be a generator") (make-gen (fn [rand-seed size] (such-that-helper max-tries pred gen max-tries rand-seed size))))) (defn not-empty "Modifies a generator so that it doesn't generate empty collections. Examples: ;; generate a vector of booleans, but never the empty vector (gen/not-empty (gen/vector gen/boolean)) " [gen] (assert (generator? gen) "Arg to not-empty must be a generator") (such-that core/not-empty gen)) (defn no-shrink "Create a new generator that is just like `gen`, except does not shrink at all. This can be useful when shrinking is taking a long time or is not applicable to the domain." [gen] (assert (generator? gen) "Arg to no-shrink must be a generator") (gen-bind gen (fn [rose] (gen-pure (rose/make-rose (rose/root rose) []))))) (defn shrink-2 "Create a new generator like `gen`, but will consider nodes for shrinking even if their parent passes the test (up to one additional level)." [gen] (assert (generator? gen) "Arg to shrink-2 must be a generator") (gen-bind gen (comp gen-pure rose/collapse))) (def boolean "Generates one of `true` or `false`. Shrinks to `false`." (elements [false true])) (defn tuple "Create a generator that returns a vector, whose elements are chosen from the generators in the same position. The individual elements shrink according to their generator, but the value will never shrink in count. Examples: (def t (tuple gen/int gen/boolean)) (sample t) ;; => ([1 true] [2 true] [2 false] [1 false] [0 true] [-2 false] [-6 false] ;; => [3 true] [-4 false] [9 true])) " [& generators] (assert (every? generator? generators) "Args to tuple must be generators") (gen-bind (gen-seq->seq-gen generators) (fn [roses] (gen-pure (rose/zip core/vector roses))))) (def int "Generates a positive or negative integer bounded by the generator's `size` parameter. (Really returns a long)" (sized (fn [size] (choose (- size) size)))) (def nat "Generates natural numbers, starting at zero. Shrinks to zero." (fmap #(Math/abs (long %)) int)) (def pos-int "Generate positive integers bounded by the generator's `size` parameter." nat) (def neg-int "Generate negative integers bounded by the generator's `size` parameter." (fmap #(* -1 %) nat)) (def s-pos-int "Generate strictly positive integers bounded by the generator's `size` parameter." (fmap inc nat)) (def s-neg-int "Generate strictly negative integers bounded by the generator's `size` parameter." (fmap dec neg-int)) (defn vector "Create a generator whose elements are chosen from `gen`. The count of the vector will be bounded by the `size` generator parameter." ([generator] (assert (generator? generator) "Arg to vector must be a generator") (gen-bind (sized #(choose 0 %)) (fn [num-elements-rose] (gen-bind (gen-seq->seq-gen (repeat (rose/root num-elements-rose) generator)) (fn [roses] (gen-pure (rose/shrink core/vector roses))))))) ([generator num-elements] (assert (generator? generator) "First arg to vector must be a generator") (apply tuple (repeat num-elements generator))) ([generator min-elements max-elements] (assert (generator? generator) "First arg to vector must be a generator") (gen-bind (choose min-elements max-elements) (fn [num-elements-rose] (gen-bind (gen-seq->seq-gen (repeat (rose/root num-elements-rose) generator)) (fn [roses] (gen-bind (gen-pure (rose/shrink core/vector roses)) (fn [rose] (gen-pure (rose/filter (fn [v] (and (>= (count v) min-elements) (<= (count v) max-elements))) rose)))))))))) (defn list "Like `vector`, but generates lists." [generator] (assert (generator? generator) "First arg to list must be a generator") (gen-bind (sized #(choose 0 %)) (fn [num-elements-rose] (gen-bind (gen-seq->seq-gen (repeat (rose/root num-elements-rose) generator)) (fn [roses] (gen-pure (rose/shrink core/list roses))))))) (defn- swap [coll [i1 i2]] (assoc coll i2 (coll i1) i1 (coll i2))) (defn ^{:added "0.6.0"} shuffle "Create a generator that generates random permutations of `coll`. Shrinks toward the original collection: `coll`. `coll` will be turned into a vector, if it's not already." [coll] (core/let [index-gen (choose 0 (dec (count coll)))] (fmap #(reduce swap (vec coll) %) ;; a vector of swap instructions, with count between ;; zero and 2 * count. This means that the average number ;; of instructions is count, which should provide sufficient ;; (though perhaps not 'perfect') shuffling. This still gives us ;; nice, relatively quick shrinks. (vector (tuple index-gen index-gen) 0 (* 2 (count coll)))))) ;; NOTE cljs: Comment out for now - David #?(:clj (def byte "Generates `java.lang.Byte`s, using the full byte-range." (fmap core/byte (choose Byte/MIN_VALUE Byte/MAX_VALUE)))) #?(:clj (def bytes "Generates byte-arrays." (fmap core/byte-array (vector byte)))) (defn hash-map "Like clojure.core/hash-map, except the values are generators. Returns a generator that makes maps with the supplied keys and values generated using the supplied generators. Examples: (gen/hash-map :a gen/boolean :b gen/nat) " [& kvs] (assert (even? (count kvs))) (core/let [ks (take-nth 2 kvs) vs (take-nth 2 (rest kvs))] (assert (every? generator? vs) "Value args to hash-map must be generators") (fmap #(zipmap ks %) (apply tuple vs)))) ;; Collections of distinct elements ;; (has to be done in a low-level way (instead of with combinators) ;; and is subject to the same kind of failure as such-that) ;; --------------------------------------------------------------------------- (defn ^:private transient-set-contains? [s k] #? (:clj (.contains ^clojure.lang.ITransientSet s k) :cljs (some? (-lookup s k)))) (defn ^:private coll-distinct-by* "Returns a rose tree." [empty-coll key-fn shuffle-fn gen rng size num-elements min-elements max-tries] {:pre [gen (:gen gen)]} (loop [rose-trees (transient []) s (transient #{}) rng rng size size tries 0] (cond (and (= max-tries tries) (< (count rose-trees) min-elements)) (throw (ex-info "Couldn't generate enough distinct elements!" {:gen gen :max-tries max-tries :num-elements num-elements :so-far (->> rose-trees (persistent!) (core/map rose/root))})) (or (= max-tries tries) (= (count rose-trees) num-elements)) (->> (persistent! rose-trees) ;; we shuffle the rose trees so that we aren't biased ;; toward generating "smaller" elements earlier in the ;; collection (only applies to ordered collections) ;; ;; shuffling the rose trees is more efficient than ;; (bind ... shuffle) because we only perform the ;; shuffling once and we have no need to shrink the ;; shufling. (shuffle-fn rng) (rose/shrink #(into empty-coll %&))) :else (core/let [[rng1 rng2] (random/split rng) rose (call-gen gen rng1 size) root (rose/root rose) k (key-fn root)] (if (transient-set-contains? s k) (recur rose-trees s rng2 (inc size) (inc tries)) (recur (conj! rose-trees rose) (conj! s k) rng2 size 0)))))) (defn ^:private distinct-by? "Like clojure.core/distinct? but takes a collection instead of varargs, and returns true for empty collections." [f coll] (or (empty? coll) (apply distinct? (core/map f coll)))) (defn ^:private the-shuffle-fn "Returns a shuffled version of coll according to the rng. Note that this is not a generator, it is just a utility function." [rng coll] (core/let [empty-coll (empty coll) v (vec coll) card (count coll) dec-card (dec card)] (into empty-coll (first (reduce (fn [[v rng] idx] (core/let [[rng1 rng2] (random/split rng) swap-idx (rand-range rng1 idx dec-card)] [(swap v [idx swap-idx]) rng2])) [v rng] (range card)))))) (defn ^:private coll-distinct-by [empty-coll key-fn allows-dupes? ordered? gen {:keys [num-elements min-elements max-elements max-tries] :or {max-tries 10}}] (core/let [shuffle-fn (if ordered? the-shuffle-fn (fn [_rng coll] coll)) hard-min-elements (or num-elements min-elements 1)] (if num-elements (core/let [size-pred #(= num-elements (count %))] (assert (and (nil? min-elements) (nil? max-elements))) (make-gen (fn [rng gen-size] (rose/filter (if allows-dupes? ;; is there a smarter way to do the shrinking than checking ;; the distinctness of the entire collection at each ;; step? (every-pred size-pred #(distinct-by? key-fn %)) size-pred) (coll-distinct-by* empty-coll key-fn shuffle-fn gen rng gen-size num-elements hard-min-elements max-tries))))) (core/let [min-elements (or min-elements 0) size-pred (if max-elements #(<= min-elements (count %) max-elements) #(<= min-elements (count %)))] (gen-bind (if max-elements (choose min-elements max-elements) (sized #(choose min-elements (+ min-elements %)))) (fn [num-elements-rose] (core/let [num-elements (rose/root num-elements-rose)] (make-gen (fn [rng gen-size] (rose/filter (if allows-dupes? ;; same comment as above (every-pred size-pred #(distinct-by? key-fn %)) size-pred) (coll-distinct-by* empty-coll key-fn shuffle-fn gen rng gen-size num-elements hard-min-elements max-tries))))))))))) ;; I tried to reduce the duplication in these docstrings with a macro, ;; but couldn't make it work in cljs. (defn vector-distinct "Generates a vector of elements from the given generator, with the guarantee that the elements will be distinct. If the generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([gen] (vector-distinct gen {})) ([gen opts] (assert (generator? gen) "First arg to vector-distinct must be a generator!") (coll-distinct-by [] identity true true gen opts))) (defn list-distinct "Generates a list of elements from the given generator, with the guarantee that the elements will be distinct. If the generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([gen] (list-distinct gen {})) ([gen opts] (assert (generator? gen) "First arg to list-distinct must be a generator!") (coll-distinct-by () identity true true gen opts))) (defn vector-distinct-by "Generates a vector of elements from the given generator, with the guarantee that (map key-fn the-vector) will be distinct. If the generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([key-fn gen] (vector-distinct-by key-fn gen {})) ([key-fn gen opts] (assert (generator? gen) "First arg to vector-distinct-by must be a generator!") (coll-distinct-by [] key-fn true true gen opts))) (defn list-distinct-by "Generates a list of elements from the given generator, with the guarantee that (map key-fn the-list) will be distinct. If the generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([key-fn gen] (list-distinct-by key-fn gen {})) ([key-fn gen opts] (assert (generator? gen) "First arg to list-distinct-by must be a generator!") (coll-distinct-by () key-fn true true gen opts))) (defn set "Generates a set of elements from the given generator. If the generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([gen] (set gen {})) ([gen opts] (assert (generator? gen) "First arg to set must be a generator!") (coll-distinct-by #{} identity false false gen opts))) (defn sorted-set "Generates a sorted set of elements from the given generator. If the generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([gen] (sorted-set gen {})) ([gen opts] (assert (generator? gen) "First arg to sorted-set must be a generator!") (coll-distinct-by (core/sorted-set) identity false false gen opts))) (defn map "Create a generator that generates maps, with keys chosen from `key-gen` and values chosen from `val-gen`. If the key generator cannot or is unlikely to produce enough distinct elements, this generator will fail in the same way as such-that. Available options: :num-elements the fixed size of generated vectors :min-elements the min size of generated vectors :max-elements the max size of generated vectors :max-tries the number of times the generator will be tried before failing when it does not produce distinct elements (default 10)" ([key-gen val-gen] (map key-gen val-gen {})) ([key-gen val-gen opts] (coll-distinct-by {} first false false (tuple key-gen val-gen) opts))) ;; large integers ;; --------------------------------------------------------------------------- ;; This approach has a few distribution edge cases, but is pretty good ;; for expected uses and is way better than nothing. (def ^:private gen-raw-long "Generates a single uniformly random long, does not shrink." (make-gen (fn [rnd _size] (rose/pure (random/rand-long rnd))))) (def ^:private MAX_INTEGER #?(:clj Long/MAX_VALUE :cljs (dec (apply * (repeat 53 2))))) (def ^:private MIN_INTEGER #?(:clj Long/MIN_VALUE :cljs (- MAX_INTEGER))) (defn ^:private abs [x] #?(:clj (Math/abs (long x)) :cljs (Math/abs x))) (defn ^:private long->large-integer [bit-count x min max] (loop [res (-> x (#?(:clj bit-shift-right :cljs .shiftRight) (- 64 bit-count)) #?(:cljs .toNumber) ;; so we don't get into an infinite loop bit-shifting ;; -1 (cond-> (zero? min) (abs)))] (if (<= min res max) res (core/let [res' (- res)] (if (<= min res' max) res' (recur #?(:clj (bit-shift-right res 1) ;; emulating bit-shift-right :cljs (-> res (cond-> (odd? res) ((if (neg? res) inc dec))) (/ 2))))))))) (defn ^:private large-integer** "Like large-integer*, but assumes range includes zero." [min max] (sized (fn [size] (core/let [size (core/max size 1) ;; no need to worry about size=0 max-bit-count (core/min size #?(:clj 64 :cljs 54))] (gen-fmap (fn [rose] (core/let [[bit-count x] (rose/root rose)] (int-rose-tree (long->large-integer bit-count x min max)))) (tuple (choose 1 max-bit-count) gen-raw-long)))))) (defn large-integer* "Like large-integer, but accepts options: :min the minimum integer (inclusive) :max the maximum integer (inclusive) Both :min and :max are optional." [{:keys [min max]}] (core/let [min (or min MIN_INTEGER) max (or max MAX_INTEGER)] (assert (<= min max)) (such-that #(<= min % max) (if (<= min 0 max) (large-integer** min max) (if (< max 0) (fmap #(+ max %) (large-integer** (- min max) 0)) (fmap #(+ min %) (large-integer** 0 (- max min)))))))) (def large-integer "Generates a platform-native integer from the full available range (in clj, 64-bit Longs, and in cljs, numbers between -(2^53 - 1) and (2^53 - 1)). Use large-integer* for more control." (large-integer* {})) ;; doubles ;; --------------------------------------------------------------------------- ;; This code is a lot more complex than any reasonable person would ;; expect, for two reasons: ;; ;; 1) I wanted the generator to start with simple values and grow with ;; the size parameter, as well as shrink back to simple values. I ;; decided to define "simple" as numbers with simpler (closer to 0) ;; exponents, with simpler fractional parts (fewer lower-level bits ;; set), and with positive being simpler than negative. I also wanted ;; to take a optional min/max parameters, which complicates the hell ;; out of things ;; ;; 2) It works in CLJS as well, which has fewer utility functions for ;; doubles, and I wanted it to work exactly the same way in CLJS just ;; to validate the whole cross-platform situation. It should generate ;; the exact same numbers on both platforms. ;; ;; Some of the lower level stuff could probably be less messy and ;; faster, especially for CLJS. (def ^:private POS_INFINITY #?(:clj Double/POSITIVE_INFINITY, :cljs (.-POSITIVE_INFINITY js/Number))) (def ^:private NEG_INFINITY #?(:clj Double/NEGATIVE_INFINITY, :cljs (.-NEGATIVE_INFINITY js/Number))) (def ^:private MAX_POS_VALUE #?(:clj Double/MAX_VALUE, :cljs (.-MAX_VALUE js/Number))) (def ^:private MIN_NEG_VALUE (- MAX_POS_VALUE)) (def ^:private NAN #?(:clj Double/NaN, :cljs (.-NaN js/Number))) (defn ^:private uniform-integer "Generates an integer uniformly in the range 0..(2^bit-count-1)." [bit-count] {:assert [(<= 0 bit-count 52)]} (if (<= bit-count 32) ;; the case here is just for cljs (choose 0 (case (long bit-count) 32 0xffffffff 31 0x7fffffff (-> 1 (bit-shift-left bit-count) dec))) (fmap (fn [[upper lower]] #? (:clj (-> upper (bit-shift-left 32) (+ lower)) :cljs (-> upper (* 0x100000000) (+ lower)))) (tuple (uniform-integer (- bit-count 32)) (uniform-integer 32))))) (defn ^:private scalb [x exp] #?(:clj (Math/scalb ^double x ^int exp) :cljs (* x (.pow js/Math 2 exp)))) (defn ^:private fifty-two-bit-reverse "Bit-reverses an integer in the range [0, 2^52)." [n] #? (:clj (-> n (Long/reverse) (unsigned-bit-shift-right 12)) :cljs (loop [out 0 n n out-shifter (Math/pow 2 52)] (if (< n 1) (* out out-shifter) (recur (-> out (* 2) (+ (bit-and n 1))) (/ n 2) (/ out-shifter 2)))))) (def ^:private backwards-shrinking-significand "Generates a 52-bit non-negative integer that shrinks toward having fewer lower-order bits (and shrinks to 0 if possible)." (fmap fifty-two-bit-reverse (sized (fn [size] (gen-bind (choose 0 (min size 52)) (fn [rose] (uniform-integer (rose/root rose)))))))) (defn ^:private get-exponent [x] #? (:clj (Math/getExponent ^Double x) :cljs (if (zero? x) -1023 (core/let [x (Math/abs x) res (Math/floor (* (Math/log x) (.-LOG2E js/Math))) t (scalb x (- res))] (cond (< t 1) (dec res) (<= 2 t) (inc res) :else res))))) (defn ^:private double-exp-and-sign "Generates [exp sign], where exp is in [-1023, 1023] and sign is 1 or -1. Only generates values for exp and sign for which there are doubles within the given bounds." [lower-bound upper-bound] (letfn [(gen-exp [lb ub] (sized (fn [size] (core/let [qs8 (bit-shift-left 1 (quot (min 200 size) 8))] (cond (<= lb 0 ub) (choose (max lb (- qs8)) (min ub qs8)) (< ub 0) (choose (max lb (- ub qs8)) ub) :else (choose lb (min ub (+ lb qs8))))))))] (if (and (nil? lower-bound) (nil? upper-bound)) (tuple (gen-exp -1023 1023) (elements [1.0 -1.0])) (core/let [lower-bound (or lower-bound MIN_NEG_VALUE) upper-bound (or upper-bound MAX_POS_VALUE) lbexp (max -1023 (get-exponent lower-bound)) ubexp (max -1023 (get-exponent upper-bound))] (cond (<= 0.0 lower-bound) (tuple (gen-exp lbexp ubexp) (return 1.0)) (<= upper-bound 0.0) (tuple (gen-exp ubexp lbexp) (return -1.0)) :else (fmap (fn [[exp sign :as pair]] (if (or (and (neg? sign) (< lbexp exp)) (and (pos? sign) (< ubexp exp))) [exp (- sign)] pair)) (tuple (gen-exp -1023 (max ubexp lbexp)) (elements [1.0 -1.0])))))))) (defn ^:private block-bounds "Returns [low high], the smallest and largest numbers in the given range." [exp sign] (if (neg? sign) (core/let [[low high] (block-bounds exp (- sign))] [(- high) (- low)]) (if (= -1023 exp) [0.0 (-> 1.0 (scalb 52) dec (scalb -1074))] [(scalb 1.0 exp) (-> 1.0 (scalb 52) dec (scalb (- exp 51)))]))) (defn ^:private double-finite [ lower-bound upper-bound] {:pre [(or (nil? lower-bound) (nil? upper-bound) (<= lower-bound upper-bound))]} (core/let [pred (if lower-bound (if upper-bound #(<= lower-bound % upper-bound) #(<= lower-bound %)) (if upper-bound #(<= % upper-bound))) gen (fmap (fn [[[exp sign] significand]] (core/let [ ;; 1.0 <= base < 2.0 base (inc (/ significand (Math/pow 2 52))) x (-> base (scalb exp) (* sign))] (if (or (nil? pred) (pred x)) x ;; Scale things a bit when we have a partial range ;; to deal with. It won't be great for generating ;; simple numbers, but oh well. (core/let [[low high] (block-bounds exp sign) block-lb (cond-> low lower-bound (max lower-bound)) block-ub (cond-> high upper-bound (min upper-bound)) x (+ block-lb (* (- block-ub block-lb) (- base 1)))] (-> x (min block-ub) (max block-lb)))))) (tuple (double-exp-and-sign lower-bound upper-bound) backwards-shrinking-significand))] ;; wrapping in the such-that is necessary for staying in bounds ;; during shrinking (cond->> gen pred (such-that pred)))) (defn double* "Generates a 64-bit floating point number. Options: :infinite? - whether +/- infinity can be generated (default true) :NaN? - whether NaN can be generated (default true) :min - minimum value (inclusive, default none) :max - maximum value (inclusive, default none) Note that the min/max options must be finite numbers. Supplying a min precludes -Infinity, and supplying a max precludes +Infinity." [{:keys [infinite? NaN? min max] :or {infinite? true, NaN? true}}] (core/let [frequency-arg (cond-> [[95 (double-finite min max)]] (if (nil? min) (or (nil? max) (<= 0.0 max)) (if (nil? max) (<= min 0.0) (<= min 0.0 max))) (conj ;; Add zeros here as a special case, since ;; the `finite` code considers zeros rather ;; complex (as they have a -1023 exponent) ;; ;; I think most uses can't distinguish 0.0 ;; from -0.0, but seems worth throwing both ;; in just in case. [1 (return 0.0)] [1 (return -0.0)]) (and infinite? (nil? max)) (conj [1 (return POS_INFINITY)]) (and infinite? (nil? min)) (conj [1 (return NEG_INFINITY)]) NaN? (conj [1 (return NAN)]))] (if (= 1 (count frequency-arg)) (-> frequency-arg first second) (frequency frequency-arg)))) (def double "Generates 64-bit floating point numbers from the entire range, including +/- infinity and NaN. Use double* for more control." (double* {})) ;; Characters & Strings ;; --------------------------------------------------------------------------- (def char "Generates character from 0-255." (fmap core/char (choose 0 255))) (def char-ascii "Generate only ascii character." (fmap core/char (choose 32 126))) (def char-alphanumeric "Generate alphanumeric characters." (fmap core/char (one-of [(choose 48 57) (choose 65 90) (choose 97 122)]))) (def ^{:deprecated "0.6.0"} char-alpha-numeric "Deprecated - use char-alphanumeric instead. Generate alphanumeric characters." char-alphanumeric) (def char-alpha "Generate alpha characters." (fmap core/char (one-of [(choose 65 90) (choose 97 122)]))) (def ^{:private true} char-symbol-special "Generate non-alphanumeric characters that can be in a symbol." (elements [\* \+ \! \- \_ \?])) (def ^{:private true} char-keyword-rest "Generate characters that can be the char following first of a keyword." (frequency [[2 char-alphanumeric] [1 char-symbol-special]])) (def ^{:private true} char-keyword-first "Generate characters that can be the first char of a keyword." (frequency [[2 char-alpha] [1 char-symbol-special]])) (def string "Generate strings. May generate unprintable characters." (fmap clojure.string/join (vector char))) (def string-ascii "Generate ascii strings." (fmap clojure.string/join (vector char-ascii))) (def string-alphanumeric "Generate alphanumeric strings." (fmap clojure.string/join (vector char-alphanumeric))) (def ^{:deprecated "0.6.0"} string-alpha-numeric "Deprecated - use string-alphanumeric instead. Generate alphanumeric strings." string-alphanumeric) (defn- digit? [d] #?(:clj (Character/isDigit ^Character d) :cljs (gstring/isNumeric d))) (defn- +-or---digit? "Returns true if c is \\+ or \\- and d is non-nil and a digit. Symbols that start with +3 or -2 are not readable because they look like numbers." [c d] (core/boolean (and d (or (#?(:clj = :cljs identical?) \+ c) (#?(:clj = :cljs identical?) \- c)) (digit? d)))) (def ^{:private true} namespace-segment "Generate the segment of a namespace." (->> (tuple char-keyword-first (vector char-keyword-rest)) (such-that (fn [[c [d]]] (not (+-or---digit? c d)))) (fmap (fn [[c cs]] (clojure.string/join (cons c cs)))))) (def ^{:private true} namespace "Generate a namespace (or nil for no namespace)." (->> (vector namespace-segment) (fmap (fn [v] (when (seq v) (clojure.string/join "." v)))))) (def ^{:private true} keyword-segment-rest "Generate segments of a keyword (between \\:)" (->> (tuple char-keyword-rest (vector char-keyword-rest)) (fmap (fn [[c cs]] (clojure.string/join (cons c cs)))))) (def ^{:private true} keyword-segment-first "Generate segments of a keyword that can be first (between \\:)" (->> (tuple char-keyword-first (vector char-keyword-rest)) (fmap (fn [[c cs]] (clojure.string/join (cons c cs)))))) (def keyword "Generate keywords without namespaces." (->> (tuple keyword-segment-first (vector keyword-segment-rest)) (fmap (fn [[c cs]] (core/keyword (clojure.string/join ":" (cons c cs))))))) (def ^{:added "0.5.9"} keyword-ns "Generate keywords with optional namespaces." (->> (tuple namespace char-keyword-first (vector char-keyword-rest)) (fmap (fn [[ns c cs]] (core/keyword ns (clojure.string/join (cons c cs))))))) (def ^{:private true} char-symbol-first (frequency [[10 char-alpha] [5 char-symbol-special] [1 (return \.)]])) (def ^{:private true} char-symbol-rest (frequency [[10 char-alphanumeric] [5 char-symbol-special] [1 (return \.)]])) (def symbol "Generate symbols without namespaces." (frequency [[100 (->> (tuple char-symbol-first (vector char-symbol-rest)) (such-that (fn [[c [d]]] (not (+-or---digit? c d)))) (fmap (fn [[c cs]] (core/symbol (clojure.string/join (cons c cs))))))] [1 (return '/)]])) (def ^{:added "0.5.9"} symbol-ns "Generate symbols with optional namespaces." (frequency [[100 (->> (tuple namespace char-symbol-first (vector char-symbol-rest)) (such-that (fn [[_ c [d]]] (not (+-or---digit? c d)))) (fmap (fn [[ns c cs]] (core/symbol ns (clojure.string/join (cons c cs))))))] [1 (return '/)]])) (def ratio "Generates a `clojure.lang.Ratio`. Shrinks toward 0. Not all values generated will be ratios, as many values returned by `/` are not ratios." (fmap (fn [[a b]] (/ a b)) (tuple int (such-that (complement zero?) int)))) (def uuid "Generates a random type-4 UUID. Does not shrink." (no-shrink #?(:clj ;; this could be done with combinators, but doing it low-level ;; seems to be 10x faster (make-gen (fn [rng _size] (core/let [[r1 r2] (random/split rng) x1 (-> (random/rand-long r1) (bit-and -45057) (bit-or 0x4000)) x2 (-> (random/rand-long r2) (bit-or -9223372036854775808) (bit-and -4611686018427387905))] (rose/make-rose (java.util.UUID. x1 x2) [])))) :cljs ;; this could definitely be optimized so that it doesn't require ;; generating 31 numbers (fmap (fn [nibbles] (letfn [(hex [idx] (.toString (nibbles idx) 16))] (core/let [rhex (-> (nibbles 15) (bit-and 3) (+ 8) (.toString 16))] (core/uuid (str (hex 0) (hex 1) (hex 2) (hex 3) (hex 4) (hex 5) (hex 6) (hex 7) "-" (hex 8) (hex 9) (hex 10) (hex 11) "-" "4" (hex 12) (hex 13) (hex 14) "-" rhex (hex 16) (hex 17) (hex 18) "-" (hex 19) (hex 20) (hex 21) (hex 22) (hex 23) (hex 24) (hex 25) (hex 26) (hex 27) (hex 28) (hex 29) (hex 30)))))) (vector (choose 0 15) 31))))) (def simple-type (one-of [int large-integer double char string ratio boolean keyword keyword-ns symbol symbol-ns uuid])) (def simple-type-printable (one-of [int large-integer double char-ascii string-ascii ratio boolean keyword keyword-ns symbol symbol-ns uuid])) (defn container-type [inner-type] (one-of [(vector inner-type) (list inner-type) (map inner-type inner-type)])) (defn- recursive-helper [container-gen-fn scalar-gen scalar-size children-size height] (if (zero? height) (resize scalar-size scalar-gen) (resize children-size (container-gen-fn (recursive-helper container-gen-fn scalar-gen scalar-size children-size (dec height)))))) (defn ^{:added "0.5.9"} recursive-gen "This is a helper for writing recursive (tree-shaped) generators. The first argument should be a function that takes a generator as an argument, and produces another generator that 'contains' that generator. The vector function in this namespace is a simple example. The second argument is a scalar generator, like boolean. For example, to produce a tree of booleans: (gen/recursive-gen gen/vector gen/boolean) Vectors or maps either recurring or containing booleans or integers: (gen/recursive-gen (fn [inner] (gen/one-of [(gen/vector inner) (gen/map inner inner)])) (gen/one-of [gen/boolean gen/int])) " [container-gen-fn scalar-gen] (assert (generator? scalar-gen) "Second arg to recursive-gen must be a generator") (sized (fn [size] (bind (choose 1 5) (fn [height] (core/let [children-size (Math/pow size (/ 1 height))] (recursive-helper container-gen-fn scalar-gen size children-size height))))))) (def any "A recursive generator that will generate many different, often nested, values" (recursive-gen container-type simple-type)) (def any-printable "Like any, but avoids characters that the shell will interpret as actions, like 7 and 14 (bell and alternate character set command)" (recursive-gen container-type simple-type-printable)) ;; Macros ;; --------------------------------------------------------------------------- (defmacro let "Macro for building generators using values from other generators. Uses a binding vector with the same syntax as clojure.core/let, where the right-hand side of the binding pairs are generators, and the left-hand side are names (or destructuring forms) for generated values. Subsequent generator expressions can refer to the previously bound values, in the same way as clojure.core/let. The body of the let can be either a value or a generator, and does the expected thing in either case. In this way let provides the functionality of both `bind` and `fmap`. Examples: (gen/let [strs (gen/not-empty (gen/list gen/string)) s (gen/elements strs)] {:some-strings strs :one-of-those-strings s}) ;; generates collections of \"users\" that have integer IDs ;; from 0...N-1, but are in a random order (gen/let [users (gen/list (gen/hash-map :name gen/string-ascii :age gen/nat))] (->> users (map #(assoc %2 :id %1) (range)) (gen/shuffle)))" [bindings & body] (assert (vector? bindings) "First arg to gen/let must be a vector of bindings.") (assert (even? (count bindings)) "gen/let requires an even number of forms in binding vector") (if (empty? bindings) `(core/let [val# (do ~@body)] (if (generator? val#) val# (return val#))) (core/let [[binding gen & more] bindings] `(bind ~gen (fn [~binding] (let [~@more] ~@body))))))
<? $MESS["USER_TYPE_MONEY_NO_CURRENCY"] = "Empty currency"; $MESS["USER_TYPE_MONEY_NO_VALUE"] = "Empty sum"; ?>
--- layout: post title: Weekly Meeting Minutes 2020-11-20 date: 2020-11-20 12:00:01 -0600 category: minutes --- Weekly community meeting minutes. No new issues. Will propose idea of moving meeting time on dev@m.a.o
package org.jetbrains.plugins.scala.lang.resolve import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter import org.jetbrains.plugins.scala.project.settings.ScalaCompilerConfiguration import org.jetbrains.plugins.scala.{ScalaVersion, Scala_2_13} class YimportsResolveTest extends ScalaLightCodeInsightFixtureTestAdapter with SimpleResolveTestBase { import SimpleResolveTestBase._ override protected def supportedIn(version: ScalaVersion): Boolean = version >= Scala_2_13 private[this] def setUpDefaultImports(imports: String*): Unit = setCompilerOptions(s"-Yimports:${imports.mkString(",")}") private[this] def setCompilerOptions(options: String*): Unit = { val defaultProfile = ScalaCompilerConfiguration.instanceIn(getProject).defaultProfile val newSettings = defaultProfile.getSettings.copy( additionalCompilerOptions = options ) defaultProfile.setSettings(newSettings) } def testResolvePrimitiveTypesPos(): Unit = { setUpDefaultImports("java.lang", "scala") doResolveTest(s"val a: I${REFSRC}nt = 132") doResolveTest(s"val a: D${REFSRC}ouble = 2d") doResolveTest(s"""val s: Str${REFSRC}ing = "123" """) doResolveTest(s"val n: N${REFSRC}othing = ???") doResolveTest(s"val n: A${REFSRC}ny = 1") } def testResolvePrimitiveTypesNeg(): Unit = { setUpDefaultImports("-Yno-imports") testNoResolve(s"val a: I${REFSRC}nt = 132" -> "Int.scala") testNoResolve(s"val a: D${REFSRC}ouble = 2d" -> "Double.scala") testNoResolve(s"""val s: Str${REFSRC}ing = "123" """ -> "String.scala") testNoResolve(s"val n: N${REFSRC}othing = ???" -> "Nothing.scala") testNoResolve(s"val n: A${REFSRC}ny = 1" -> "Any.scala") } def testNoPredef(): Unit = { setCompilerOptions("-Yno-predef") testNoResolve(s"??$REFSRC?" -> "NoPredef1.scala") testNoResolve(s"""123 $REFSRC+ "123" """ -> "NoPredef2.scala") } def testImportPackage(): Unit = { setUpDefaultImports("scala.collection") doResolveTest(s"val x = mu${REFSRC}table.HashSet.empty[scala.Int]") doResolveTest(s"Buil${REFSRC}dFrom.buildFromView") } def testImportObject(): Unit = { setUpDefaultImports("scala.collection.BuildFrom") doResolveTest(s"b${REFSRC}uildFromView[scala.Int, java.lang.String]") } def testPriority(): Unit = { setUpDefaultImports("java.lang", "scala", "scala.Predef", "a.Bar", "b.Baz") myFixture.configureByText("Bar.scala", """ |package a |object Bar { | def x: Int = 123 | def y: Int = 456 | | def println(x: Any): Unit = ??? |} |""".stripMargin ) myFixture.configureByText("Baz.scala", """ |package b |object Baz { | def x: Int = 456 | | implicit class RichInt(val i: Int) extends AnyVal { | def times(n: Int): Int = i * n | } | | def times(n: Int, k: Int): Int = n * k |} |""".stripMargin ) doResolveTest(s"""println(${REFSRC}x)""" -> "FromB.scala") doResolveTest(s"123.t${REFSRC}imes(10)" -> "Times.scala") doResolveTest(s"""p${REFSRC}rintln(123)""" -> "FromA.scala") } }
#!/bin/bash #---------------------------------------- # OPTIONS #---------------------------------------- DAYS_TO_KEEP=3 # 0 to keep forever WWW_PATH='/var/www' BACKUP_PATH='/backup/www' #---------------------------------------- # Create the backup folder if [ ! -d $BACKUP_PATH ]; then mkdir -p $BACKUP_PATH fi # change into the web root directory cd "$WWW_PATH" if [ "$(pwd)" != "$WWW_PATH" ] ; then echo "Failed to change directory to root of web path" exit fi for website in * ; do if [[ -d $website && ! -L "$website" ]]; then echo "Found website folder: $website" date=$(date -I) tar -cvpzf $BACKUP_PATH/$date-$website.tar.gz $website fi done # Delete old backups if [ "$DAYS_TO_KEEP" -gt 0 ] ; then echo "Deleting backups older than $DAYS_TO_KEEP days" find $BACKUP_PATH/* -mtime +$DAYS_TO_KEEP -exec rm {} \; fi
namespace QFramework.GraphDesigner { public interface ICommandProgressEvent { void Progress(ICommand command, string message, float progress); } }
//------------------------------------------------------------------------------ // This file is part of the DarkGlass game engine project. // More information can be found here: http://chapmanworld.com/darkglass // // DarkGlass is licensed under the MIT License: // // Copyright 2018 Craig Chapman // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the “Software”), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. //------------------------------------------------------------------------------ unit darkio.stream.custom; interface uses darkio.streams; type /// <summary> /// Base class for classes which implement IStream. <br />You should not /// create an instance directly, but derrive from this class to provide /// streams with CopyFrom() and getEndOfStream() support. /// </summary> TCustomStream = class( TInterfacedObject, IStream ) private fName: string; protected //- IStream -// procedure Clear; virtual; procedure WriteBytes( value: array of uint8 ); virtual; procedure WriteByte( value: uint8 ); virtual; function ReadByte: uint8; virtual; function Read( p: pointer; Count: uint32 ): uint32; virtual; abstract; function Write( p: pointer; Count: uint32 ): uint32; virtual; abstract; function getSize: uint64; virtual; abstract; function getPosition: uint64; virtual; abstract; procedure setPosition( newPosition: uint64 ); virtual; abstract; function getRemainingBytes: uint64; function getName: string; procedure setName( value: string ); protected function CopyFrom( Source: IStream ): uint64; virtual; function getEndOfStream: boolean; virtual; public constructor Create; reintroduce; public property EndOfStream: boolean read getEndOfStream; property Position: uint64 read getPosition write setPosition; property Size: uint64 read getSize; end; implementation uses sysutils; function TCustomStream.getRemainingBytes: uint64; begin Result := (Self.Size - Self.Position); end; function TCustomStream.ReadByte: uint8; var b: uint8; begin Self.Read(@b,1); Result := B; end; procedure TCustomStream.setName(value: string); begin fName := value; end; procedure TCustomStream.WriteByte(value: uint8); var B: uint8; begin B := value; Self.Write(@b,1); end; procedure TCustomStream.WriteBytes(value: array of uint8); begin Self.Write(@value[0],Length(value)) end; procedure TCustomStream.Clear; begin raise Exception.Create('Stream does not support .Clear()'); end; function TCustomStream.CopyFrom(Source: IStream): uint64; const cCopyBlockSize = 1024; var Buffer: array of uint8; ReadBytes: uint32; WrittenBytes: uint32; begin Result := 0; Initialize(Buffer); try SetLength(Buffer,cCopyBlockSize); if not Source.getEndOfStream then begin repeat ReadBytes := Source.Read( @Buffer[0], cCopyBlockSize ); WrittenBytes := Write( @Buffer[0], ReadBytes ); Result := Result + WrittenBytes; until (ReadBytes<cCopyBlockSize) or (not WrittenBytes=ReadBytes) or (Source.getEndOfStream); end; finally Finalize(Buffer); end; end; constructor TCustomStream.Create; begin inherited Create; fName := ''; end; function TCustomStream.getEndOfStream: boolean; begin Result := getPosition()=getSize(); end; function TCustomStream.getName: string; begin Result := fName; end; end.
package org.babyfish.kimmer.sql.meta.config data class Column( val name: String = "", val length: Int? = null, val precision: Int? = null, val scale: Int? = null, val onDelete: OnDeleteAction = OnDeleteAction.NONE ): Storage
JSString* py2js_jsstring_c(JSContext* cx, PyObject* str) { PyObject* encoded = NULL; char* bytes; Py_ssize_t len; if(!PyUnicode_Check(str)) { return NULL; } encoded = PyUnicode_AsEncodedString(str, "utf-16", "strict"); if(encoded == NULL) { return NULL; } if(PyString_AsStringAndSize(encoded, &bytes, &len) < 0) { return NULL; } if(len < 4) { return NULL; } // No idea why python adds FFFE to encoded UTF-16 data. return JS_NewUCStringCopyN(cx, bytes+2, (len/2)-1); } PyObject* js2py_jsstring_c(JSString* str) { jschar* bytes; size_t len; if(str == NULL) { return NULL; } len = JS_GetStringLength(str); bytes = JS_GetStringChars(str); return PyUnicode_Decode((const char*) bytes, (size_t) (len * 2), "utf-16", "strict"); } void js_context_attach(JSContext* cx, PyObject* obj) { Py_XINCREF(obj); JS_SetContextPrivate(cx, (void*) obj); } JSBool js_context_has_data(JSContext* cx) { if(JS_GetContextPrivate(cx) == NULL) { return JS_FALSE; } return JS_TRUE; } PyObject* js_context_fetch(JSContext* cx) { PyObject* obj = (PyObject*) JS_GetContextPrivate(cx); Py_XINCREF(obj); return obj; } PyObject* js_context_destroy(JSContext* cx) { PyObject* ret = (PyObject*) JS_GetContextPrivate(cx); return ret; } void js_object_attach(JSContext* cx, JSObject* js_obj, PyObject* py_obj) { Py_XINCREF(py_obj); JS_SetPrivate(cx, js_obj, (void*) py_obj); } JSBool js_object_has_data(JSContext* cx, JSObject* js_obj) { JSClass* class = JS_GetClass(cx, js_obj); if(class == NULL) { return JS_FALSE; } if(!(class->flags & JSCLASS_HAS_PRIVATE)) { return JS_FALSE; } if(JS_GetPrivate(cx, js_obj) == NULL) { return JS_FALSE; } return JS_TRUE; } PyObject* js_object_fetch(JSContext* cx, JSObject* js_obj) { PyObject* py_obj = (PyObject*) JS_GetPrivate(cx, js_obj); Py_XINCREF(py_obj); return py_obj; } PyObject* js_object_destroy(JSContext* cx, JSObject* js_obj) { return (PyObject*) JS_GetPrivate(cx, js_obj); } void js_function_attach(JSContext* cx, JSObject* js_obj, PyObject* py_obj) { Py_XINCREF(py_obj); jsval slot = PRIVATE_TO_JSVAL(py_obj); JS_SetReservedSlot(cx, js_obj, 0, slot); } JSBool js_function_has_data(JSContext* cx, JSObject* js_obj) { jsval slot; if(JS_GetReservedSlot(cx, js_obj, 0, &slot) != JS_TRUE) { return JS_FALSE; } void* data = JSVAL_TO_PRIVATE(slot); if(data == NULL) { return JS_FALSE; } return JS_TRUE; } PyObject* js_function_fetch(JSContext* cx, JSObject* js_obj) { jsval slot; if(JS_GetReservedSlot(cx, js_obj, 0, &slot) != JS_TRUE) { return JS_FALSE; } PyObject* py_obj = (PyObject*) JSVAL_TO_PRIVATE(slot); Py_XINCREF(py_obj); return py_obj; } PyObject* js_function_destroy(JSContext* cx, JSObject* js_obj) { jsval slot; if(JS_GetReservedSlot(cx, js_obj, 0, &slot) != JS_TRUE) { return JS_FALSE; } PyObject* py_obj = (PyObject*) JSVAL_TO_PRIVATE(slot); return py_obj; } static JSClass js_global_class = { "RootObjectClass", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; JSObject * js_make_global_object(JSContext *cx) { return JS_NewObject(cx, &js_global_class, NULL, NULL); }
<?php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class WardDischargesRecordController extends Controller { public function index() { $ward_discharges= DB::table('ward_discharges') ->join('ward_admissions','ward_admissions.reg_number','ward_discharges.reg_number') ->join('patients','patients.kp_passport','ward_admissions.kp_passport') ->select('patients.name','ward_admissions.*','ward_discharges.*') ->orderBy('ward_discharges.reg_number','desc') ->get() ; return response()->json($ward_discharges); } public function show($id) { $ward_discharges= DB::table('ward_admissions')->where('ward_admissions.id',$id) ->join('patients','patients.kp_passport','ward_admissions.kp_passport') // ->join('case_samplings','patients.kp_passport','case_samplings.kp_passport') // ->select('patients.*','case_regs.*','case_samplings.*') ->select('patients.name','patients.phone','ward_admissions.*') ->orderBy('ward_admissions.date','desc') ->get() ; return response()->json($ward_discharges); } public function showbyWard(Request $request) { $ward_discharges= DB::table('bed__disciplines') ->join('ward_admissions','bed__disciplines.rn','ward_admissions.reg_number') ->join('patients','ward_admissions.kp_passport','patients.kp_passport') ->join('beds', 'beds.id', 'bed__disciplines.bed_id') ->join('wards','wards.id','beds.ward_id') ->join('disciplines','disciplines.id','bed__disciplines.discipline_id') ->join('ward_discharges','ward_admissions.reg_number','=','ward_discharges.reg_number') ->where('ward_discharges.date_dc', '=', $request -> datereporting) ->groupby('ward_admissions.reg_number') ->orderBy('ward_discharges.date_dc','desc') ->where('beds.ward_id', '=', $request -> ward_id) ->get() ; return response()->json($ward_discharges); } }
Switch Cover ============ Introduction ------------ This is a 3D printable switch cover that that covers a power strip switch and hopefully offers a strong enough message to prevent people with itchy fingers from turning them off. I built this after someone switched my office server off for the umpteenth time. If this cover fails to work, it will be extended to incorporate padlock holes. License ------- This piece is licensed under CC-BY 3.0. See [COPYING](COPYING) for the full text.
# bejson验证 json验证工具,同时可以json格式化操作。输入json数据,校验即可。 ![](/assets/BaiduHi_2017-1-15_17-56-41.png)
import { connect } from 'react-redux'; import { signIn, signUp, verifyUser, undoCodeVerification, verifyCode, forgotPassword, resetPassword, sendNewCode, toggleLoading, showNotification, } from '../../actions'; import { AuthWithStyles } from './AuthWithStyles'; const mapStateToProps = (state: any) => { return { auth: state.auth, }; }; const mapDispatchToProps = { signIn, signUp, verifyUser, undoCodeVerification, verifyCode, forgotPassword, resetPassword, sendNewCode, toggleLoading, showNotification, }; export const Auth = connect( mapStateToProps, mapDispatchToProps )(AuthWithStyles);
#include "coalitional_values_generator_trap.h" void coalitional_values_generator_trap::reset(uint32_t n_agents, uint32_t n_tasks, int seed) { if (seed >= 0) { generator.seed(seed); // Used to generate samples. } task_trap_generators.resize(n_tasks); for (uint32_t t = 0; t < n_tasks; ++t) { for (uint32_t i = 0; i <= n_agents; ++i) { /* f(x) = a + bx + cx ^ 2 _________________ f(0) = L f(n / 2) = 0 f(n) = H _________________ => a = L b = -2L / n - (H + L) / n c = 2(H + l) / n^2 _________________ */ float L = 0.01; float H = 10.0; float n = n_agents; float a = L; float b = (-2 * L / n) - (H + L) / n; float c = 2 * (H + L) / (n * n); float k = a + b * i + c * i * i; // Calculated according to formula above (derived on black board). trap_generators.push_back(std::normal_distribution<coalition::value_t>(i <= 1 ? L : k, 0.1f)); values.push_back(i <= 1 ? L : k); task_trap_generators[t].push_back(std::normal_distribution<coalition::value_t>(t * (i <= 1 ? L : k), 0.1f)); } } } coalition::value_t coalitional_values_generator_trap::generate_new_value( const coalition::coalition_t& coalition, const uint32_t task ) { coalition::value_t value{}; switch (MODE) { case 0: value = values[coalition.count_agents_in_coalition()]; break; case 1: { uint32_t x = coalition.count_agents_in_coalition(); float xf = x; float cost = -xf * xf; float steep = pow(xf, 2.1f); float val = xf + (xf > n_agents / 2.0f ? steep : 0.0f); float mean = cost + val; float trap_value = std::normal_distribution<float>(0.1 * mean, 0.1f)(generator); value = trap_value; } break; case 2: value = task_trap_generators[task][coalition.count_agents_in_coalition()](generator); break; default: break; } return value; } std::string coalitional_values_generator_trap::get_file_name() const { return "trap_" + std::to_string(seed) + "_" + std::to_string(n_agents) + "_" + std::to_string(n_tasks) + ".problem"; }
#include "processor.h" // Return the aggregate CPU utilization double Processor::Utilization() { std::vector<string> v = LinuxParser::CpuUtilization(); if (!v.empty()) { double total{1.0}, idle{1.0}; std::for_each(v.begin(), v.begin() + 8, [&](string s){ total += std::stod(s); }); std::for_each(v.begin() + 3, v.begin() + 5, [&](string s){ idle += std::stod(s); }); double utilization = ((total-prevTotal_) - (idle-prevIdle_)) / (total-prevTotal_); prevTotal_ = total; prevIdle_ = idle; return utilization; } return 0.0; }
# prequel-examples Source code examples written in [Prequel](https://prequel-lang.org).
(ns zookeeper-exp1.service-test (:require [zookeeper-exp1.test-util :as tu] [clojure.test :refer :all] [zookeeper :as zk] [zookeeper.util.zk :as util] [zookeeper-exp1.service :refer :all])) (use-fixtures :once tu/setup-embedded-zk) (deftest a-test (testing "FIXME, I succeed." (is (= 0 0))))
package DDG::Goodie::Constants; # ABSTRACT: Various Math and Physics constants. use DDG::Goodie; use YAML::XS qw( LoadFile ); zci answer_type => "constants"; zci is_cached => 1; name "Constants"; description "Provides the value, unit, symbol and other information for Mathematical and Scientific constants"; primary_example_queries "first example query", "second example query"; secondary_example_queries "optional -- demonstrate any additional triggers"; category "formulas"; topics "math"; code_url "https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/Constants.pm"; attribution github => ["Roysten", "Roy van der Vegt"], github => ["hemanth", "Hemanth.HM"], twitter => "gnumanth"; my $constants = LoadFile(share("constants.yml")); #loop through constants foreach my $name (keys %$constants) { #obtain to constant with name $keyword my $constant = $constants->{$name}; #add aliases as separate triggers foreach my $alias (@{$constant->{'aliases'}}) { $constants->{$alias} = $constant; } } my @triggers = keys %{$constants}; triggers startend => @triggers; # Handle statement handle query_lc => sub { my $constant = $constants->{$_}; return unless my $val = $constant->{'value'}; #fallback to plain answer if html is not present my $result = $val->{'html'} ? $val->{'html'} : $val->{'plain'}; return $result, structured_answer => { input => [], operation => $constant->{'name'}, result => $result }; }; 1;
const { createFixture } = require('spire-test-utils'); const { stat, readFile } = require('fs-extra'); const { join } = require('path'); const configWithEslintPlugin = (options = {}) => JSON.stringify({ name: 'spire-plugin-eslint6-test', spire: { plugins: [[require.resolve('spire-plugin-eslint6'), options]], }, }); describe('spire-plugin-eslint6', () => { test('adds lint command', async () => { const fixture = await createFixture({ 'package.json': configWithEslintPlugin(), }); await expect(fixture.run('spire', ['--help'])).resolves.toMatchObject({ stdout: /Commands:\s+spire lint/, }); await fixture.clean(); }); test('adds eslint linter', async () => { const fixture = await createFixture({ 'package.json': configWithEslintPlugin(), }); const { stdout } = await fixture.run('spire', [ 'hook', 'precommit', '--debug', ]); expect(stdout).toMatch(/Using linters:/); expect(stdout).toMatch(/\*\.\(js\|jsx\|mjs\|ts\|tsx\)/); await fixture.clean(); }); test('passes custom arguments to eslint', async () => { const fixture = await createFixture({ 'package.json': configWithEslintPlugin(), }); await expect( fixture.run('spire', ['lint', '--version']) ).resolves.toMatchObject({ stdout: /v\d\.\d\.\d/, }); await fixture.clean(); }); test('creates default eslint config for editors', async () => { const fixture = await createFixture({ 'package.json': configWithEslintPlugin(), }); await fixture.run('spire', ['hook', 'postinstall']); const eslintConfig = join(fixture.cwd, '.eslintrc.js'); expect(await stat(eslintConfig)).toBeTruthy(); expect(await readFile(eslintConfig, 'UTF-8')).toMatch( /spire-plugin-eslint6\/config/ ); await fixture.clean(); }); test('prints deprecation warning for glob option', async () => { const fixture = await createFixture({ 'package.json': configWithEslintPlugin({ glob: 'abc' }), }); await fixture.run('spire', ['hook', 'precommit']); await expect( fixture.run('spire', ['hook', 'precommit']) ).resolves.toMatchObject({ stdout: /The glob option is deprecated\. Use the option `fileExtensions` instead\./, }); await fixture.clean(); }); test('creates custom eslint config for editors', async () => { const fixture = await createFixture({ 'node_modules/eslint6-config-cool-test/package.json': JSON.stringify({ name: 'eslint6-config-cool-test', version: '1.0.0', main: 'index.js', }), 'node_modules/eslint6-config-cool-test/index.js': 'module.exports = {};', 'package.json': configWithEslintPlugin({ config: 'eslint6-config-cool-test', }), }); await fixture.run('spire', ['hook', 'postinstall']); const eslintConfig = join(fixture.cwd, '.eslintrc.js'); expect(await stat(eslintConfig)).toBeTruthy(); expect(await readFile(eslintConfig, 'UTF-8')).toMatch( /eslint6-config-cool-test/ ); await fixture.clean(); }); test('warns about custom eslint config not extending default config', async () => { const fixture = await createFixture({ 'package.json': configWithEslintPlugin(), '.eslintrc.json': '', }); await expect( fixture.run('spire', ['hook', 'postinstall']) ).resolves.toMatchObject({ stdout: expect.stringMatching( 'Attempted to set ESLint config but it already exists. Please ensure existing config re-exports' ), }); await fixture.clean(); }); });
#!/usr/bin/env python """Scans for pages content and checks for errors.""" import logging import requests from bs4 import BeautifulSoup import language_tool_python # Global settings logging.basicConfig(filename='mylog.log', encoding='utf-8') tool = language_tool_python.LanguageTool('en-US') # use a local server (automatically set up), language English # Data urls = [ 'https://github.com/.../wiki', ] """Logger function.""" def log(text): logging.info(text) print(text) """Main script function.""" def main(): for url in urls: log('\n###############################################################################') log('# ' + url) log('###############################################################################\n') # Download and extract text from webpage html_page = res.content res = requests.get(url) soup = BeautifulSoup(html_page, 'html.parser') #TODO: Remove divs with class=highlight to remove code samples try: soup.pre.decompose() except AttributeError: pass body = soup.find(id='wiki-body') #print(body.text) # Check text for problems matches = tool.check(body.text) for match in matches: # Print the context log(match.context) # Show error offset pointer = '' for i in range(match.offsetInContext): pointer += ' ' pointer += '^' for i in range(match.errorLength - 1): pointer += '^' log(pointer) # Print the problem log('>> ' + match.ruleIssueType + ': ' + match.message) # Replacements rep_amount = len(match.replacements) if rep_amount > 5: rep_amount = 5 reps = '>> solutions: ' for i in range(rep_amount): reps += match.replacements[i] + ' | ' reps = reps[:len(reps) - 3] log(reps) log('\n----------\n') if __name__ == '__main__': main()
MATCH (ty:TYPE {type: "schema:CodeRepository"}) MATCH (tyt:TYPE {type: "TextualBody"}) MATCH (mv:MOTIVATION) WHERE mv.term="linking" MATCH (aty:AGENTTYPE {type:"Person"}) MERGE (ob:OBJECT {id: toInteger($ghid), url: $ghurl, description: $ghdescription, name: $ghname}) ON CREATE SET ob.created = timestamp() WITH ty, tyt, ob, mv, aty MERGE (ty)<-[:isType]-(ob) CREATE (ob)<-[:Target]-(a:ANNOTATION { created: timestamp() }) MERGE (mv)<-[:hasMotivation]-(a) MERGE (a)-[:Body]->(obb:OBJECT {value: "Code repository contains a reference to the NSF Award."})-[:isType]->(tyt) WITH a, aty MATCH (ot:OBJECT) WHERE ot.AwardID=$otid MERGE (ot)<-[:Target]-(a) WITH a, aty MERGE (ag:AGENT { id:"0000-0002-2700-4605", name: "Simon Goring"}) ON CREATE SET ag.created = timestamp() MERGE (ag)<-[:isAgentType]-(aty) MERGE (ags:AGENT {name: "GitHub code linker", homepage: "https://github.com/throughput-ec/throughputdb"})<-[:isAgentType]- (aty) WITH a, ag, ags MERGE (ag)-[:Created {created: timestamp()}]->(a) MERGE (ags)-[:Generated {generated: timestamp()}]->(a)
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /** * Support for observing changes in model-view architectures. * * **Warning:** This library is experimental, and APIs are subject to change. * * This library is used to observe changes to [Observable] types. It also * has helpers to make implementing and using [Observable] objects easy. * * You can provide an observable object in two ways. The simplest way is to * use dirty checking to discover changes automatically: * * class Monster extends Unit with Observable { * @observable int health = 100; * * void damage(int amount) { * print('$this takes $amount damage!'); * health -= amount; * } * * toString() => 'Monster with $health hit points'; * } * * main() { * var obj = new Monster(); * obj.changes.listen((records) { * print('Changes to $obj were: $records'); * }); * // No changes are delivered until we check for them * obj.damage(10); * obj.damage(20); * print('dirty checking!'); * Observable.dirtyCheck(); * print('done!'); * } * * A more sophisticated approach is to implement the change notification * manually. This avoids the potentially expensive [Observable.dirtyCheck] * operation, but requires more work in the object: * * class Monster extends Unit with ChangeNotifier { * int _health = 100; * @reflectable get health => _health; * @reflectable set health(val) { * _health = notifyPropertyChange(#health, _health, val); * } * * void damage(int amount) { * print('$this takes $amount damage!'); * health -= amount; * } * * toString() => 'Monster with $health hit points'; * } * * main() { * var obj = new Monster(); * obj.changes.listen((records) { * print('Changes to $obj were: $records'); * }); * // Schedules asynchronous delivery of these changes * obj.damage(10); * obj.damage(20); * print('done!'); * } * * *Note*: it is good practice to keep `@reflectable` annotation on * getters/setters so they are accessible via reflection. This will preserve * them from tree-shaking. You can also put this annotation on the class and it * preserve all of its members for reflection. * * [Tools](https://www.dartlang.org/polymer-dart/) exist to convert the first * form into the second form automatically, to get the best of both worlds. */ library observe; export 'src/bind_property.dart'; export 'src/change_notifier.dart'; export 'src/change_record.dart'; export 'src/compound_path_observer.dart'; export 'src/list_path_observer.dart'; export 'src/list_diff.dart' show ListChangeRecord; export 'src/metadata.dart'; export 'src/observable.dart' hide notifyPropertyChangeHelper, objectType; export 'src/observable_box.dart'; export 'src/observable_list.dart'; export 'src/observable_map.dart'; export 'src/path_observer.dart'; export 'src/to_observable.dart';
- Use [[CloudFront]] as bridge between customer and [[Lambda]] ![[Pasted image 20210701115028.png]]
# Design Research This folder acts to collate and point to information and feedback about the Design of the platform.
package leo.modules.relevance_filter import leo.datastructures.tptp.Commons.AnnotatedFormula import scala.collection.mutable._ /** * Created by mwisnie on 3/9/16. */ class FuncFrequency { val symbols : Map[String, Int] = HashMap[String, Int]() /** * Updates every smybol in a formula. * * @param formula New formula from the problem */ def addFormula(formula: AnnotatedFormula) : Unit = { val it = formula.function_symbols.iterator while(it.hasNext){ val symb = it.next val freq = symbols.getOrElse(symb,0: Int) symbols.put(symb, freq+1) } } /** * Returns the number of formulas a symbol is occuring in * * @param symbol The symbol we want to know the number of occurences * @return The number of occurences */ def apply(symbol : String) : Int = symbols.getOrElse(symbol, 0 : Int) def clear() : Unit = symbols.clear() }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use DB; class AccountApproval extends Model { public function scopeGetAccount(){ $query = DB::table('users') ->where('is_approved', 0) ->select('user_id','first_name','last_name','email','created_at') ->get(); return $query; } }
import { composable } from '../compose' const prefix = composable('prefix', () => ({ $el: null })) export default prefix
#!/usr/bin/env perl # # Module to parse Affymetrix binary data files. # # Tim Rayner 2004, ArrayExpress team, European Bioinformatics Institute # # $Id: GDAC_CDF.pm 2081 2008-06-14 22:00:45Z tfrayner $ # =pod =begin html <div><a name="top"></a> <table class="layout"> <tr> <td class="whitetitle" width="100"> <a href="../../../../index.html"> <img src="../../../T2M_logo.png" border="0" height="50" alt="Tab2MAGE logo"></td> </a> <td class="pagetitle">Module detail: GDAC_CDF.pm</td> </tr> </table> </div> =end html =head1 NAME ArrayExpress::Datafile::Affymetrix::GDAC_CDF.pm - GDAC CDF data file parsing. =head1 SYNOPSIS use ArrayExpress::Datafile::Affymetrix::CDF::GDAC_CDF; my $cdf = ArrayExpress::Datafile::Affymetrix::CDF::GDAC_CDF->new({ input => 'HG-U133A.cdf', }); $cdf->parse(); =head1 DESCRIPTION This module implements parsing and export of data from Affymetrix GDAC CDF files. Please see L<ArrayExpress::Datafile::Affymetrix::Parser> for methods common to all the Affymetrix parser classes. =head1 METHODS Most accessors and methods are implemented in the superclass; see L<ArrayExpress::Datafile::Affymetrix::CDF>. =head1 AUTHOR Tim Rayner (rayner@ebi.ac.uk), ArrayExpress team, EBI, 2005. Acknowledgements go to the ArrayExpress curation team for feature requests, bug reports and other valuable comments. =begin html <hr> <a href="http://sourceforge.net"> <img src="http://sourceforge.net/sflogo.php?group_id=120325&amp;type=2" width="125" height="37" border="0" alt="SourceForge.net Logo" /> </a> =end html =cut package ArrayExpress::Datafile::Affymetrix::CDF::GDAC_CDF; use base 'ArrayExpress::Datafile::Affymetrix::CDF'; use strict; use warnings; use Carp; use Scalar::Util qw(openhandle); use Class::Std; use EBI::FGPT::Common qw( round ); use ArrayExpress::Datafile::Binary qw( get_integer get_DWORD get_unsigned_short get_unsigned_char get_signed_char get_float get_ascii ); sub START { my ( $self, $id, $args ) = @_; $self->set_required_magic(1178878811); return; } ############################# # GDAC CDF specific methods # ############################# sub parse_cdf : RESTRICTED { my ( $self, $fh ) = @_; openhandle($fh) or confess( 'Bad parameters passed to method' ); binmode( $fh, ":crlf" ); seek( $fh, 0, 0 ) or croak("Error rewinding filehandle for input: $!\n"); my $label = <$fh>; $label =~ s/[\r\n]* \z//xms; unless ( $label eq '[CDF]' ) { croak("Error: Unrecognized CDF file format: $label\n"); } my $version = <$fh>; # We just want the version string. $version =~ s{\A Version= ([^\r\n]*) [\r\n]*}{$1}xms; unless ( $version eq 'GC3.0' ) { croak("Error: Unrecognized CDF file version: $version\n"); } $self->set_version($version); my $line = q{}; until ( $line eq '[Chip]' ) { $line = $self->_get_line($fh); } $self->set_chip_type( ( split /=/, $self->_get_line($fh) )[1] ); $self->set_num_columns( ( split /=/, $self->_get_line($fh) )[1] ); $self->set_num_rows( ( split /=/, $self->_get_line($fh) )[1] ); $self->set_num_cells( ( split /=/, $self->_get_line($fh) )[1] ); my $max_cell = ( ( split /=/, $self->_get_line($fh) )[1] ); $self->set_num_qc_cells( ( split /=/, $self->_get_line($fh) )[1] ); # Here we skip all the QC info for now my $data; $data->[ $self->get_num_cells() - 1 ] = {}; # Generate a mapping of unit names and numbers foreach my $cell (@$data) { my ( $unitno, $unitname ); until ( $line =~ m{\[ Unit \d+ \]}xms ) { unless ( defined( $line = <$fh> ) ) { croak("Premature end of CDF file."); } } until ( ( $unitname ) = ( $line =~ m{\A Name= ([^\r\n]+) [\r\n]* \z}xms ) ) { unless ( defined( $line = <$fh> ) ) { croak("Premature end of CDF file."); } } until ( ( $unitno ) = ( $line =~ m{\A UnitNumber= (\d+) [\r\n]* \z}xms ) ) { unless ( defined( $line = <$fh> ) ) { croak("Premature end of CDF file."); } } # Expression CDFs don't keep the name in the unit, but in the blocks. if ( $unitname eq 'NONE' ) { $unitname = undef; until ( $line =~ m!\[Unit($unitno)_Block\d+\]! ) { unless ( defined( $line = <$fh> ) ) { croak("Premature end of CDF file."); } } until ( ($unitname) = ( $line =~ m/^Name=([^\r\n]+)[\r\n]*$/ ) ) { unless ( defined( $line = <$fh> ) ) { croak("Premature end of CDF file."); } } } unless ($unitname) { croak("Error: No name for unit $unitno.\n"); } $cell->{cell_no} = $unitno; $cell->{name} = $unitname; } $self->set_data($data); return; } 1;
#!/usr/bin/env bash (cd root-html-file && npm start) & (cd navbar && ng serve --port 4203 --publicHost http://localhost:4203 --disable-host-check) & (cd app1 && ng serve --port 4201 --publicHost http://localhost:4201 --disable-host-check) & (cd app2 && ng serve --port 4202 --publicHost http://localhost:4202 --disable-host-check) &
package client import ( "context" "fmt" "github.com/google/go-github/github" "github.com/pkg/errors" "golang.org/x/oauth2" ) type githubClient struct { client *github.Client } // NewGitHub returns a github client implementation func NewGitHub(token string) (Client, error) { ctx := context.Background() ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: token}, ) tc := oauth2.NewClient(ctx, ts) client := github.NewClient(tc) return &githubClient{client}, nil } // GetIssues gets the list of all closed issues for the username and project, and returns a map of them func (c *githubClient) GetIssues(userName, projectName string) ([]*github.Issue, error) { ctx := context.Background() // list all issues in the repo issueOpts := &github.IssueListByRepoOptions{ State: "closed", ListOptions: github.ListOptions{PerPage: 300}, } var allIssues []*github.Issue for { issues, resp, err := c.client.Issues.ListByRepo( ctx, userName, projectName, issueOpts, ) fmt.Print("* ") if err != nil { return nil, errors.Wrap(err, "GitHub issue list failed") } allIssues = append(allIssues, issues...) if resp.NextPage == 0 { break } issueOpts.Page = resp.NextPage } return allIssues, nil }
# docker-pytest-allure Dockerfile for creating docker image for runing pytest with allure ## Usage Example ```shell $ docker build -t pytest-alpine . $ docker run --rm pytest-alpine python3 -m pytest --version ``` Once you have run this command you will get pytest version. Or use it interactivelly: ```shell $ docker run -it --rm pytest-alpine python3 ``` >NOTE: pip/pip3 is also available in this image.
package astar import kotlin.test.Test import kotlin.test.assertEquals class GridTest { @Test fun testNeighbors() { val grid = GridMap(8, 8) grid.neighbors(GridNode(0,0)).let { assertEquals(3, it.size) assertEquals(setOf(GridNode(1,0), GridNode(1,1), GridNode(0,1)), it.toSet()) // any order } grid.neighbors(GridNode(7,0)).let { assertEquals(3, it.size) assertEquals(setOf(GridNode(6,0), GridNode(6,1), GridNode(7,1)), it.toSet()) // any order } grid.neighbors(GridNode(7,7)).let { assertEquals(3, it.size) assertEquals(setOf(GridNode(6,7), GridNode(6,6), GridNode(7,6)), it.toSet()) // any order } grid.neighbors(GridNode(0,7)).let { assertEquals(3, it.size) assertEquals(setOf(GridNode(0,6), GridNode(1,6), GridNode(1,7)), it.toSet()) // any order } grid.neighbors(GridNode(1, 1)).let { assertEquals(8, it.size) assertEquals(setOf( GridNode(0,0), GridNode(1,0), GridNode(2,0), GridNode(0, 1), GridNode(2, 1), GridNode(0, 2), GridNode(1, 2), GridNode(2, 2), ), it.toSet()) // any order } grid.addWall(GridNode(2,2)) grid.neighbors(GridNode(1, 1)).let { assertEquals(7, it.size) assertEquals(setOf( GridNode(0,0), GridNode(1,0), GridNode(2,0), GridNode(0, 1), GridNode(2, 1), GridNode(0, 2), GridNode(1, 2), // GridNode(2, 2), // no walls ), it.toSet()) // any order } } @Test fun testHeuristic() { val grid = GridMap(4, 4) assertEquals(3, grid.heuristic(GridNode(0,0), GridNode(3, 3))) } }
package io.stoys.spark.dq import io.stoys.scala.{Arbitrary, Jackson} import io.stoys.spark.test.SparkTestBase import org.apache.spark.sql.functions.monotonically_increasing_id class DqAggregatorTest extends SparkTestBase { import DqAggregator._ import sparkSession.implicits._ test("DqAggregator") { val inputRows = Seq( DqAggInputRow(1, Array("1", "foo", "extra"), Array(-1, 12, -1)), DqAggInputRow(2, Array("2", "bar", "extra"), Array(-1, -1, -1)), DqAggInputRow(3, Array("3", "invalid", "extra"), Array(-1, 32, 33)), DqAggInputRow(4, Array("4", null, "extra"), Array(-1, -1, 43)), ) val inputRowsDs = inputRows.toDS() val columnCount = inputRows.headOption.map(_.row.length).getOrElse(0) val ruleCount = inputRows.headOption.map(_.ruleHashes.length).getOrElse(0) val partitionCount = inputRowsDs.rdd.getNumPartitions val existingReferencedColumnIndexes = Seq(Seq(0), Seq(0), Seq(1)) val expected = DqAggOutputRow( rows = 4, rowViolations = 3, columnViolations = Array(2, 2, 0), ruleViolations = Array(0, 2, 2), rowSample = inputRows.filter(_.ruleHashes.exists(_ != -1)).toArray, ) val aggregator = new DqAggregator(columnCount, ruleCount, partitionCount, sensibleRowNumber = false, existingReferencedColumnIndexes, DqConfig.default) val actual = inputRowsDs.select(aggregator.toColumn).first() assert(Jackson.json.writeValueAsString(actual) === Jackson.json.writeValueAsString(expected)) val emptyDqConfigAggregator = new DqAggregator(columnCount, ruleCount, partitionCount, sensibleRowNumber = false, existingReferencedColumnIndexes, Arbitrary.empty[DqConfig]) assert(inputRowsDs.select(emptyDqConfigAggregator.toColumn).first().rowSample.length === 0) val singleRowSamplingAggregator = new DqAggregator(columnCount, ruleCount, partitionCount, sensibleRowNumber = false, existingReferencedColumnIndexes, DqConfig.default.copy(max_rows_per_rule = 1)) assert(inputRowsDs.select(singleRowSamplingAggregator.toColumn).first().rowSample.length === 2) } test("DqAggregator - sampling") { val rowIds = 0.until(8) val secondRuleHashes = Array(-1L, -1L, 4L, 3L, 2L, 1L, -1L, -1L) val inputRows = rowIds.map(i => DqAggInputRow(i, Array(i.toString, "foo"), Array(i, secondRuleHashes(i)))) val inputRowsDs = inputRows.toDS().repartition(3) val columnCount = inputRows.headOption.map(_.row.length).getOrElse(0) val ruleCount = inputRows.headOption.map(_.ruleHashes.length).getOrElse(0) val partitionCount = inputRowsDs.rdd.getNumPartitions val existingReferencedColumnIndexes = Seq(Seq(0), Seq(0, 1)) def run(config: DqConfig): Seq[Int] = { val aggregator = new DqAggregator(columnCount, ruleCount, partitionCount, sensibleRowNumber = false, existingReferencedColumnIndexes, config) inputRowsDs.select(aggregator.toColumn).first().rowSample.map(_.row.head.toInt) } assert(run(DqConfig.default) === rowIds) assert(run(DqConfig.default.copy(sample_rows = false)) === Seq.empty) assert(run(DqConfig.default.copy(max_rows_per_rule = 0, max_rows = 9)) === Seq.empty) assert(run(DqConfig.default.copy(max_rows_per_rule = 1, max_rows = 0)) === Seq.empty) assert(run(DqConfig.default.copy(max_rows_per_rule = 1, max_rows = 9)) === Seq(0, 5)) assert(run(DqConfig.default.copy(max_rows_per_rule = 2, max_rows = 9)) === Seq(0, 4, 5)) assert(run(DqConfig.default.copy(max_rows_per_rule = 2, max_rows = 2)) === Seq(0, 5)) assert(run(DqConfig.default.copy(max_rows_per_rule = 3, max_rows = 9)) === Seq(0, 1, 3, 4, 5)) assert(run(DqConfig.default.copy(max_rows_per_rule = 3, max_rows = 3)) === Seq(0, 1, 5)) assert(run(DqConfig.default.copy(max_rows_per_rule = 4, max_rows = 9)) === Seq(0, 1, 2, 3, 4, 5)) assert(run(DqConfig.default.copy(max_rows_per_rule = 9, max_rows = 9)) === rowIds) } test("DqAggregator - counting") { val rowIds = 0.until(8) val inputRowsDs = rowIds.map(i => DqAggInputRow(-1L, Array(i.toString), Array(i))).toDS() def run(sensibleRowNumber: Boolean, partitions: Int): DqAggOutputRow = { val patchedInputRowDf = inputRowsDs.repartition(partitions).withColumn("rowId", monotonically_increasing_id()) val aggregator = new DqAggregator(columnCount = 1, ruleCount = 1, partitionCount = partitions, sensibleRowNumber = sensibleRowNumber, existingReferencedColumnIndexes = Seq(Seq.empty), DqConfig.default) patchedInputRowDf.as[DqAggInputRow].select(aggregator.toColumn).first() } assert(run(sensibleRowNumber = true, partitions = 1).rowSample.map(_.row.last.toInt) === rowIds) assert(run(sensibleRowNumber = true, partitions = 3).rowSample.map(_.row.last.toInt) === rowIds) assert(run(sensibleRowNumber = false, partitions = 3).rowSample.map(_.row.last.toInt) !== rowIds) } }
'use strict'; require('./toggle.scss'); require('./toggle.html'); angular .module('app') .component('toggle', require('./toggle.component.js'));
# Video Text Scanner Scan a video file at defined frame or timespan for text. ## Algorithm 1. Read a video file to memory. 2. Declare an appendable data structure `FOUND_TEXT` for storing found text. 3. Iterate over the given timespan (single frame is handled as a timespan with length of 1) with the set time interval. 4. For each iteration, create a bitmap of the frame. 1. Apply possible image manipulations for improving text recognition. 5. Process the bitmap like an image, feeding it to a text recognition algorithm. 6. If any text is found, save it to `FOUND_TEXT` with the timestamp of the frame. 7. Print the found text to output (with timestamps if the option flag is provided). **Possible improvements and optimisation** - Step 1 could be improved by only reading the required part into working memory. - Step 4 might could be possibly streamlined by somehow processing the image data directly, without creating a new object. ## Roadmap / Implementation plan - Write a 'proof of concept' version in Python - OpenCV or Python Tesseract for text extraction - Write tests and create a testing workflow to ensure the program is working as intended. - Attempt to follow Python packaging conventions, so the package can possibly later be published and easily deployed.
<?php /** * @link https://github.com/ixocreate * @copyright IXOLIT GmbH * @license MIT License */ declare(strict_types=1); namespace Ixocreate\Admin\Config\Client; final class ClientConfig implements \JsonSerializable { /** * @var array */ private $config; public function __construct(array $config) { $this->config = $config; } public function config(): array { return $this->config; } public function hash(): string { return \sha1(\json_encode($this->config)); } /** * @return array */ public function jsonSerialize() { return $this->config; } }
#include <iostream> //#include <array> #include <typeinfo> using namespace std; class Base { public: Base() {} ~Base(){} void dis1() { cout<<"dis1"<<endl; } void dis2() { cout<<"dis2"<<endl; } }; class BaseA : private Base { public: using Base::dis1; //需要在BaseA的public下释放才能对外使用, void dis2show() { this->dis2(); } }; int main(int argc, char *argv[]) { BaseA ba; ba.dis1(); ba.dis2show(); return 0; }
duilib-Ex-Debug =============== DuiLib的Bug修正和扩展库,修正了原库中大量的bug和改善设计工具(提高其稳定性)。 @1:duilib-Ex-Debug 项目说明: http://blog.csdn.net/x356982611/article/details/38781403 @2:常见错误的排除 http://blog.csdn.net/x356982611/article/details/30217473 最近写了一个虚拟键盘的程序,可以在xp win7上用,鼠标进入编辑框可自动弹出。 https://github.com/CodeBees/virtualkeyboard 添加一个嵌入式浏览器的项目 https://github.com/CodeBees/CEFWebkitBrowser
use serde::{Deserialize, Serialize}; use std::convert::TryInto; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; use std::{ fmt::{Display, Formatter, Result}, mem::swap, ops::{Index, IndexMut, Neg}, panic, }; use crate::prelude::{transpose, Dot}; use super::super::utils::{dot, ipiv_parity}; use super::vops::*; use super::{broadcast_add, broadcast_div, broadcast_mul, broadcast_sub, Vector}; /// Matrix struct. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Matrix { pub data: Vector, pub nrows: usize, pub ncols: usize, } impl Matrix { pub fn empty() -> Self { Self { data: Vector::empty(), nrows: 0, ncols: 0, } } /// Make a matrix filled with zeros. pub fn zeros(nrows: usize, ncols: usize) -> Self { Self::new(Vector::zeros(nrows * ncols), nrows as i32, ncols as i32) } /// Make a matrix filled with ones. pub fn ones(nrows: usize, ncols: usize) -> Self { Self::new(Vector::ones(nrows * ncols), nrows as i32, ncols as i32) } /// Make an empty matrix with a certain capacity. pub fn with_capacity(nrows: usize, ncols: usize) -> Self { Self::new( Vector::with_capacity(nrows * ncols), nrows as i32, ncols as i32, ) } /// Make a matrix with a given shape, initialized with garbage values. pub fn with_shape(nrows: usize, ncols: usize) -> Self { Self::new(Vector::empty_n(nrows * ncols), nrows as i32, ncols as i32) } /// Make an identity matrix with size `dims`. pub fn eye(dims: usize) -> Self { let mut m = Self::zeros(dims, dims); for i in 0..dims { m.data[i * dims + i] = 1.; } m } /// Check whether the matrix is square. pub fn is_square(&self) -> bool { self.nrows == self.ncols } /// Invert the matrix. pub fn inv(&self) -> Self { assert!(self.is_square(), "matrix not square"); self.solve(&Matrix::eye(self.nrows)) } /// Check whether the matrix is symmetric. pub fn is_symmetric(&self) -> bool { if self.is_square() { for i in 0..self.nrows { for j in i..self.ncols { if (self.data[i * self.ncols + j] - self.data[j * self.nrows + i]).abs() > f64::EPSILON { return false; } } } true } else { false } } /// Check whether a matrix is close to another matrix within some tolerance. pub fn close_to(&self, other: &Matrix, tol: f64) -> bool { if self.shape() != other.shape() { return false; } self.data.close_to(&other.data, tol) } /// Check whether the matrix is positive definite. pub fn is_positive_definite(&self) -> bool { if self.is_symmetric() { for i in 0..self.ncols { if self.data[i * self.ncols + i] <= 0. { return false; } } true } else { false } } /// Solve a matrix equation of the form Lx=b, where L is a lower triangular matrix. /// See the [Wikipedia page](https://en.wikipedia.org/wiki/Triangular_matrix#Forward_and_back_substitution). pub fn forward_substitution(&self, b: &[f64]) -> Vector { assert!(self.is_lower_triangular(), "matrix not lower triangular"); assert_eq!(b.len(), self.nrows); let mut x = Vector::zeros(self.nrows); for i in 0..self.ncols { x[i] = (b[i] - dot(&self[i][0..i], &x[..i])) / self[[i, i]]; } x } /// Solve a matrix equation of the form Ux=b, where U is an upper triangular matrix. /// See the [Wikipedia page](https://en.wikipedia.org/wiki/Triangular_matrix#Forward_and_back_substitution). pub fn backward_substitution(&self, b: &[f64]) -> Vector { assert!(self.is_upper_triangular(), "matrix not upper triangular"); assert_eq!(b.len(), self.nrows); let mut x = Vector::zeros(self.nrows); for i in (0..self.ncols).rev() { x[i] = (b[i] - dot(&self[i][i + 1..self.ncols], &x[i + 1..])) / self[[i, i]]; } x } /// Return the Cholesky decomposition of the matrix. Resulting matrix is lower triangular. pub fn cholesky(&self) -> Matrix { assert!(self.is_positive_definite(), "matrix not positive definite"); let mut l = Matrix::zeros(self.nrows, self.ncols); for i in 0..self.ncols { for j in 0..(i + 1) { let s = l.get_row_as_vector(j).dot(l.get_row_as_vector(i)); if i == j { l[[i, j]] = (self[[i, i]] - s).sqrt(); } else { l[[i, j]] = (self[[i, j]] - s) / l[[j, j]]; } } } l } pub fn lu(&self) -> (Matrix, Vec<i32>) { assert!(self.is_square(), "matrix not square"); let mut lu = self.clone(); let n = self.nrows; let mut pivots: Vec<i32> = (0..n).map(|x| x as i32).collect(); for j in 0..n { for i in 0..n { let mut s = 0.; for k in 0..i.min(j) { s += lu[[i, k]] * lu[[k, j]]; } lu[[i, j]] -= s; } let mut p = j; for i in (j + 1)..n { if lu[[i, j]].abs() > lu[[p, j]].abs() { p = i; } } if p != j { for k in 0..n { lu.data.swap(p * n + k, j * n + k) } pivots.swap(p, j); } if j < n && lu[[j, j]] != 0. { for i in (j + 1)..n { lu[[i, j]] /= lu[[j, j]]; } } } (lu, pivots) } /// Calculates the determinant of the matrix using the LU decomposition. pub fn det(&self) -> f64 { let (lu, p) = self.lu(); lu.diag().prod() * ipiv_parity(&p) as f64 } /// Calculates the determinant of an LU decomposed matrix. pub fn lu_det(&self, piv: &[i32]) -> f64 { assert!(self.is_square(), "matrix not square"); self.diag().prod() * ipiv_parity(piv) as f64 } /// Check whether the matrix is upper triangular (i.e., all the entries below the diagonal are /// 0). pub fn is_upper_triangular(&self) -> bool { for i in 0..self.nrows { for j in 0..i { if self[i][j] != 0. { return false; } } } true } /// Check whether the matrix is lower triangular (i.e., all the entries above the diagonal are /// 0). pub fn is_lower_triangular(&self) -> bool { for i in 0..self.nrows { for j in (i + 1)..self.ncols { if self[i][j] != 0. { return false; } } } true } /// Get the diagonal elements of the matrix. pub fn diag(&self) -> Vector { let n = self.nrows.min(self.ncols); let mut diag = Vector::with_capacity(n); for i in 0..n { diag.push(self.data[i * n + i]); } diag } /// Make a new matrix with the given number of rows and columns. pub fn new<T>(data: T, nrows: impl TryInto<i32>, ncols: impl TryInto<i32>) -> Self where T: Into<Vector>, { let v = data.into(); let len = v.len(); let mut m = Self { data: v, nrows: 1, ncols: len, }; let nrows = match nrows.try_into() { Ok(v) => v, Err(_) => panic!("Could not understand nrows value."), }; let ncols = match ncols.try_into() { Ok(v) => v, Err(_) => panic!("Could not understand ncols value."), }; m.reshape_mut(nrows, ncols); m } /// Get the number of rows and columns in the matrix. pub fn shape(&self) -> [usize; 2] { [self.nrows, self.ncols] } /// Get the total number of elements in the matrix. pub fn size(&self) -> usize { self.nrows * self.ncols } /// Reshape the matrix in-place. A size of `-1` in either the rows or the columns means that the size /// for that dimension will be automatically determined if possible. pub fn reshape_mut(&mut self, nrows: i32, ncols: i32) -> &mut Self { let size = self.size(); if nrows > 0 && ncols > 0 { assert_eq!(nrows * ncols, size as i32, "invalid shape"); self.nrows = nrows as usize; self.ncols = ncols as usize; } else if nrows < 0 { assert!(nrows == -1 && ncols > 0, "invalid number of rows"); // automatically determine number of rows self.ncols = ncols as usize; self.nrows = size / ncols as usize; } else if ncols < 0 { assert!(ncols == -1 && nrows > 0, "invalid number of columns"); // automatically determine number of columns self.nrows = nrows as usize; self.ncols = size / nrows as usize; } else { panic!("invalid shape"); } self } /// Reshape the matrix. A size of `-1` in either the rows or the columns means that the size /// for that dimension will be automatically determined if possible. pub fn reshape(&self, nrows: i32, ncols: i32) -> Self { let size = self.size() as i32; let (newrows, newcols) = if nrows > 0 && ncols > 0 { assert_eq!(nrows * ncols, size as i32, "invalid shape"); (nrows, ncols) } else if nrows < 0 { assert!(nrows == -1 && ncols > 0, "invalid shape"); // automatically determine number of rows (size / ncols, ncols) } else if ncols < 0 { assert!(ncols == -1 && nrows > 0, "invalid shape"); // automatically determine number of columns (nrows, size / nrows) } else { panic!("invalid shape"); }; Matrix::new(self.data.clone(), newrows, newcols) } /// Apply a closure to every element in a row. The closure should take a value and return the /// value to replace it with. pub fn apply_along_row<F>(&mut self, row: usize, f: F) where F: Fn(f64) -> f64, { self[row].iter_mut().for_each(|x| *x = f(*x)); } /// Apply a closure to every element in a row. pub fn apply_along_col<F>(&mut self, col: usize, f: F) where F: Fn(f64) -> f64, { for row in self { row[col] = f(row[col]); } } /// Return a copy of the row of the matrix as a Vector. pub fn get_row_as_vector(&self, row: usize) -> Vector { assert!(row < self.nrows); Vector::from(&self[row]) } /// Return a copy of the column of the matrix as a Vector. pub fn get_col_as_vector(&self, col: usize) -> Vector { assert!(col < self.ncols); let mut v = Vector::zeros(self.nrows); for i in 0..self.nrows { v[i] = self[i][col]; } v } /// Sum the matrix across the rows. pub fn sum_rows(&self) -> Vector { let mut sums = Vector::zeros(self.nrows); for row in 0..self.nrows { sums[row] = Vector::from(&self[row]).sum(); } sums } /// Sum the matrix down the columns. pub fn sum_cols(&self) -> Vector { let mut sums = Vector::zeros(self.ncols); for row in 0..self.nrows { // sums = sums + Vector::from(&self[row]); for col in 0..self.ncols { sums[col] += self[row][col]; } } sums } /// Calculates the infinity norm of the matrix. pub fn inf_norm(&self) -> f64 { self.abs().sum_rows().max() } pub fn flat_idx(&self, idx: usize) -> f64 { assert!(idx < self.size()); (&self.data)[idx] } pub fn flat_idx_replace(&mut self, idx: usize, val: f64) -> &mut Self { assert!(idx < self.size()); self.data[idx] = val; self } /// Transpose the matrix. pub fn t(&self) -> Self { let t = transpose(&self.data, self.nrows); Matrix::new(t, self.ncols as i32, self.nrows as i32) } /// Transpose the matrix in-place. pub fn t_mut(&mut self) -> &mut Self { let t = transpose(&self.data, self.nrows); self.data = Vector::new(t); swap(&mut self.ncols, &mut self.nrows); self } /// Return a reference to the underlying Vector holding the data. pub fn data(&self) -> &Vector { &self.data } /// Return a mutable reference to the underlying Vector holding the data. pub fn data_mut(&mut self) -> &mut Vector { &mut self.data } /// Converts the matrix to a Vector. pub fn to_vec(self) -> Vector { self.data } /// Horizontal concatenation of matrices. Adds `other` to the right of the calling matrix. pub fn hcat(&self, other: Self) -> Self { assert_eq!(self.nrows, other.nrows); let mut new_vec = Vector::empty(); for i in 0..self.nrows { for j in 0..self.ncols { new_vec.push(self.data[i * self.ncols + j]); } for j in 0..other.ncols { new_vec.push(other.data[i * other.ncols + j]); } } Matrix::new( new_vec, self.nrows as i32, (self.ncols + other.ncols) as i32, ) } /// Vertical concatenation of matrices. Adds `other` below the calling matrix. pub fn vcat(&self, other: Self) -> Self { assert_eq!(self.ncols, other.ncols); let mut new_vec = self.data.clone(); new_vec.extend(other.data); Matrix::new( new_vec, (self.nrows + other.nrows) as i32, self.ncols as i32, ) } /// Repeat self horizontally. That is, make `n` total copies of self and horizontally /// concatenate them all together. pub fn hrepeat(&self, n: usize) -> Self { let total_cols = self.ncols * n; let mut new_vec = Vec::with_capacity(self.nrows * total_cols); for i in 0..self.nrows { for _ in 0..n { new_vec.extend(&self[i]); } } Matrix::new(new_vec, self.nrows as i32, total_cols as i32) } /// Repeat self vertically. That is, make `n` total copies of self and vertically /// concatenate them all together. pub fn vrepeat(&self, n: usize) -> Self { let total_rows = self.nrows * n; Matrix::new(self.data.repeat(n), total_rows as i32, self.ncols as i32) } /// Find the position of the smallest element in the matrix. Returns (row, column). pub fn argmin(&self) -> (usize, usize) { let am = self.data.argmin(); (am / self.ncols, am % self.ncols) } /// Find the position of the largest element in the matrix. Returns (row, column). pub fn argmax(&self) -> (usize, usize) { let am = self.data.argmax(); (am / self.ncols, am % self.ncols) } } pub trait Solve<T> { fn cholesky_solve(&self, system: &T) -> T; fn lu_solve(&self, pivots: &[i32], system: &T) -> T; fn solve(&self, system: &T) -> T; } impl Solve<Vector> for Matrix { fn cholesky_solve(&self, system: &Vector) -> Vector { assert!( self.is_lower_triangular(), "matrix not a cholesky decomposed matrix" ); assert_eq!(self.nrows, system.len()); let y = self.forward_substitution(system); // back substitution self.t().backward_substitution(&y) } /// Solve the linear system Ax = b given a LU decomposed matrix A. The first argument should be a /// tuple, where the first element is the LU decomposed matrix and the second element is the pivots /// P. fn lu_solve(&self, pivots: &[i32], system: &Vector) -> Vector { assert!(self.is_square(), "matrix not square"); assert_eq!(self.nrows, system.len()); let mut x = Vector::zeros(self.nrows); for i in 0..pivots.len() { x[i] = system[pivots[i] as usize]; } for k in 0..self.ncols { for i in (k + 1)..self.ncols { x[i] -= x[k] * self[[i, k]]; } } for k in (0..self.ncols).rev() { x[k] /= self[[k, k]]; for i in 0..k { x[i] -= x[k] * self[[i, k]]; } } x } /// Solve the linear system Ax = b using LU decomposition. fn solve(&self, system: &Vector) -> Vector { let (lu, piv) = self.lu(); lu.lu_solve(&piv, system) } } impl Solve<Matrix> for Matrix { fn cholesky_solve(&self, system: &Matrix) -> Matrix { let mut solutions = Vector::with_capacity(system.nrows * system.ncols); for i in 0..system.ncols { let x = system.get_col_as_vector(i); solutions.extend(self.cholesky_solve(&x)); } Matrix::new(solutions, system.ncols as i32, system.nrows as i32).t() } fn lu_solve(&self, pivots: &[i32], system: &Matrix) -> Matrix { let mut solutions = Vector::with_capacity(system.nrows * system.ncols); for i in 0..system.ncols { let x = system.get_col_as_vector(i); solutions.extend(self.lu_solve(pivots, &x)); } Matrix::new(solutions, system.ncols as i32, system.nrows as i32).t() } fn solve(&self, system: &Matrix) -> Matrix { let (lu, piv) = self.lu(); lu.lu_solve(&piv, system) } } impl Neg for Matrix { type Output = Self; fn neg(self) -> Self::Output { Matrix::new(-self.data, self.nrows as i32, self.ncols as i32) } } impl PartialEq<Matrix> for Matrix { fn eq(&self, other: &Matrix) -> bool { if self.shape() != other.shape() { return false; } self.data.eq(&other.data) } } impl Display for Matrix { fn fmt(&self, f: &mut Formatter) -> Result { for (rownum, row) in self.into_iter().enumerate() { let row_str = format!("{:?}", row); if rownum == 0 { writeln!(f, "[{},", row_str)? } else if rownum == self.nrows - 1 { writeln!(f, " {}]", row_str)? } else { writeln!(f, " {},", row_str)? } } Ok(()) } } impl<'a> IntoIterator for &'a Matrix { type Item = &'a [f64]; type IntoIter = std::slice::Chunks<'a, f64>; fn into_iter(self) -> Self::IntoIter { self.data.chunks(self.ncols) } } impl<'a> IntoIterator for &'a mut Matrix { type Item = &'a mut [f64]; type IntoIter = std::slice::ChunksMut<'a, f64>; fn into_iter(self) -> Self::IntoIter { self.data.chunks_mut(self.ncols) } } impl Default for Matrix { fn default() -> Self { Self::empty() } } impl Index<usize> for Matrix { type Output = [f64]; fn index(&self, i: usize) -> &Self::Output { assert!(i < self.nrows); &self.data[i * self.ncols..(i + 1) * self.ncols] } } impl Index<[usize; 2]> for Matrix { type Output = f64; fn index(&self, [i, j]: [usize; 2]) -> &Self::Output { assert!(i < self.nrows && j < self.ncols); &self.data[i * self.ncols + j] } } impl IndexMut<usize> for Matrix { fn index_mut(&mut self, i: usize) -> &mut Self::Output { assert!(i < self.nrows); &mut self.data[i * self.ncols..(i + 1) * self.ncols] } } impl IndexMut<[usize; 2]> for Matrix { fn index_mut(&mut self, [i, j]: [usize; 2]) -> &mut Self::Output { assert!(i < self.nrows && j < self.ncols); &mut self.data[i * self.ncols + j] } } // Functions to do Matrix + Matrix, Matrix - Matrix, etc. macro_rules! makefn_matops { ($fn: ident, $innerfn: ident) => { pub fn $fn(m1: &Matrix, m2: &Matrix) -> Matrix { assert_eq!(m1.shape(), m2.shape(), "matrix shapes not equal"); Matrix::new( $innerfn(&m1.data, &m2.data), m1.nrows as i32, m1.ncols as i32, ) } }; } // Make the Matrix-Matrix functions. makefn_matops!(matmatadd, vadd); makefn_matops!(matmatsub, vsub); makefn_matops!(matmatmul, vmul); makefn_matops!(matmatdiv, vdiv); // Helper macro to implement Matrix + Matrix, Matrix + &Matrix, etc... macro_rules! impl_mat_mat_op_helper { ($op: ident, $fn: ident, $innerfn: ident, $selftype: ty, $othertype: ty) => { impl $op<$othertype> for $selftype { type Output = Matrix; fn $fn(self, other: $othertype) -> Self::Output { $innerfn(&self, &other) } } }; } macro_rules! impl_mat_vec_op_helper { ($op: ident, $fn: ident, $innerfn: ident, $selftype: ty, $othertype: ty$(, $to_owned: ident)?) => { impl $op<$othertype> for $selftype { type Output = Matrix; fn $fn(self, other: $othertype) -> Self::Output { $innerfn(&self, &other$(.$to_owned())?.to_matrix()) } } }; } macro_rules! impl_vec_mat_op_helper { ($op: ident, $fn: ident, $innerfn: ident, $selftype: ty, $othertype: ty$(, $to_owned: ident)?) => { impl $op<$othertype> for $selftype { type Output = Matrix; fn $fn(self, other: $othertype) -> Self::Output { $innerfn(&self$(.$to_owned())?.to_matrix(), &other) } } }; } // Implement Matrix + Matrix, Matrix + &Matrix, etc... macro_rules! mat_mat_op { ($op:ident, $fn:ident, $innerfn:ident) => { impl_mat_mat_op_helper!($op, $fn, $innerfn, Matrix, Matrix); impl_mat_mat_op_helper!($op, $fn, $innerfn, Matrix, &Matrix); impl_mat_mat_op_helper!($op, $fn, $innerfn, &Matrix, Matrix); impl_mat_mat_op_helper!($op, $fn, $innerfn, &Matrix, &Matrix); }; } macro_rules! mat_vec_op { ($op:ident, $fn:ident, $innerfn:ident) => { impl_mat_vec_op_helper!($op, $fn, $innerfn, Matrix, Vector); impl_mat_vec_op_helper!($op, $fn, $innerfn, Matrix, &Vector, to_owned); impl_mat_vec_op_helper!($op, $fn, $innerfn, &Matrix, Vector); impl_mat_vec_op_helper!($op, $fn, $innerfn, &Matrix, &Vector, to_owned); }; } macro_rules! vec_mat_op { ($op:ident, $fn:ident, $innerfn:ident) => { impl_vec_mat_op_helper!($op, $fn, $innerfn, Vector, Matrix); impl_vec_mat_op_helper!($op, $fn, $innerfn, Vector, &Matrix); impl_vec_mat_op_helper!($op, $fn, $innerfn, &Vector, Matrix, to_owned); impl_vec_mat_op_helper!($op, $fn, $innerfn, &Vector, &Matrix, to_owned); }; } // Macro to implement Matrix += Matrix, Matrix += &Matrix, etc... macro_rules! mat_mat_opassign { ($op: ident, $fn:ident, $innerfn:ident) => { impl $op<Matrix> for Matrix { fn $fn(&mut self, other: Matrix) { assert_eq!(self.shape(), other.shape(), "matrix shapes not equal"); $innerfn(&mut self.data, &other.data); } } impl $op<&Matrix> for Matrix { fn $fn(&mut self, other: &Matrix) { assert_eq!(self.shape(), other.shape(), "matrix shapes not equal"); $innerfn(&mut self.data, &other.data); } } }; } // Macro to implement Matrix += Scalar macro_rules! mat_scalar_opassign { ($op: ident, $fn:ident, $innerfn:ident, $ty:ty) => { impl $op<$ty> for Matrix { fn $fn(&mut self, other: $ty) { $innerfn(&mut self.data, other); } } }; } // Helper macro to implement Matrix + Scalar, &Matrix + Scalar, Scalar + Matrix, Scalar + &Matrix macro_rules! impl_mat_scalar_op_for_type { ($op:ident, $fn:ident, $fn_vs:ident, $fn_sv:ident, $selftype:ty, $othertype: ty) => { impl $op<$othertype> for $selftype { type Output = Matrix; fn $fn(self, other: $othertype) -> Self::Output { Matrix::new( $fn_vs(&self.data, other), self.nrows as i32, self.ncols as i32, ) } } impl $op<$selftype> for $othertype { type Output = Matrix; fn $fn(self, other: $selftype) -> Self::Output { Matrix::new( $fn_sv(self, &other.data), other.nrows as i32, other.ncols as i32, ) } } }; } // Implement Matrix + Scalar, &Matrix + Scalar, Scalar + Matrix, Scalar + &Matrix macro_rules! mat_scalar_op { ($op:ident, $fn:ident, $fn_vs:ident, $fn_sv:ident, $ty:ty) => { impl_mat_scalar_op_for_type!($op, $fn, $fn_vs, $fn_sv, Matrix, $ty); impl_mat_scalar_op_for_type!($op, $fn, $fn_vs, $fn_sv, &Matrix, $ty); }; } // Implement Matrix-Scalar and Scalar-Matrix Op and OpAssign methods. macro_rules! mat_scalar_op_for { ($ty: ty) => { mat_scalar_op!(Add, add, vsadd, svadd, $ty); mat_scalar_op!(Sub, sub, vssub, svsub, $ty); mat_scalar_op!(Mul, mul, vsmul, svmul, $ty); mat_scalar_op!(Div, div, vsdiv, svdiv, $ty); mat_scalar_opassign!(AddAssign, add_assign, vsadd_mut, $ty); mat_scalar_opassign!(SubAssign, sub_assign, vssub_mut, $ty); mat_scalar_opassign!(MulAssign, mul_assign, vsmul_mut, $ty); mat_scalar_opassign!(DivAssign, div_assign, vsdiv_mut, $ty); }; } macro_rules! impl_mat_ops { ($($macro_name:ident),+) => { $( $macro_name!(Add, add, broadcast_add); $macro_name!(Sub, sub, broadcast_sub); $macro_name!(Mul, mul, broadcast_mul); $macro_name!(Div, div, broadcast_div); )+ }; } impl_mat_ops!(mat_mat_op, mat_vec_op, vec_mat_op); // Implement Matrix-Matrix assignment operations. mat_mat_opassign!(AddAssign, add_assign, vadd_mut); mat_mat_opassign!(SubAssign, sub_assign, vsub_mut); mat_mat_opassign!(MulAssign, mul_assign, vmul_mut); mat_mat_opassign!(DivAssign, div_assign, vdiv_mut); // Implement Matrix-Scalar (assignment) operations. mat_scalar_op_for!(f64); macro_rules! impl_unary_ops_matrix { ($($op: ident),+) => { $( impl Matrix { #[doc = "Apply the `f64` operation `"] #[doc = stringify!($op)] #[doc = "` element-wise to the matrix."] pub fn $op(&self) -> Self { Self::new(self.data.$op(), self.nrows as i32, self.ncols as i32) } } )+ }; } impl_unary_ops_matrix!( ln, ln_1p, log10, log2, exp, exp2, exp_m1, sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, asinh, acosh, atanh, sqrt, cbrt, abs, floor, ceil, to_radians, to_degrees, recip, round, signum ); macro_rules! impl_unaryops_with_arg_matrix { ($op: ident, $argtype: ident) => { impl Matrix { #[doc = "Apply the `f64` operation `"] #[doc = stringify!($op)] #[doc = "` element-wise to the matrix."] pub fn $op(&self, arg: $argtype) -> Self { Self::new(self.data.$op(arg), self.nrows as i32, self.ncols as i32) } } }; } impl_unaryops_with_arg_matrix!(powi, i32); impl_unaryops_with_arg_matrix!(powf, f64); macro_rules! impl_reduction_fns_matrix { ($($fn: ident),+) => { impl Matrix { $( pub fn $fn(&self) -> f64 { self.data.$fn() } )+ } }; } impl_reduction_fns_matrix!(norm, max, mean, min, std, sum, prod, var, sample_std, sample_var); #[cfg(test)] mod tests { use super::*; #[test] fn test_mat_vec_ops() { let a = Matrix::new( [ 1.69968, -1.48008, 0.66542, -0.60947, 1.6508, -0.15097, -0.11973, 0.21233, 0.80922, ], 3, 3, ); let b = Vector::new([1.93579, 0.43448, -0.73636]); let c = &a + &b; assert_eq!( c, Matrix::new( [ 3.6354699999999998, -1.0456, -0.07094, 1.32632, 2.08528, -0.88733, 1.8160599999999998, 0.64681, 0.07286000000000004 ], 3, 3 ) ); let d = &a / &b; assert_eq!( d, Matrix::new( [ 0.878029125060053, -3.406554962253729, -0.9036612526481612, -0.31484303565985977, 3.7994844411710553, 0.2050220001086425, -0.061850717278217164, 0.48869913459768, -1.0989461676353958 ], 3, 3 ) ); let e = &a.t() * &b; assert_eq!( e, Matrix::new( [ 3.2902235472, -0.26480252559999995, 0.08816438280000001, -2.8651240632, 0.717239584, -0.1563513188, 1.2881133818, -0.0655934456, -0.5958772392 ], 3, 3 ) ); } #[test] fn test_cholesky() { let a = Matrix::new( [ 8.97062104740134, 0.26943982630456786, -0.9534319972273332, 0.26943982630456786, 3.307274425269507, -1.5063311267171873, -0.9534319972273332, -1.5063311267171873, 1.5071780730242237, ], 3, 3, ); let ac = a.cholesky(); assert!(ac.close_to( &Matrix::new( [ 2.9950995054257112, 0., 0., 0.0899602253001844, 1.8163649366615309, 0., -0.3183306582970492, -0.813544678798316, 0.8625478077250766 ], 3, 3 ), 1e-10 )); let b = Vector::new([0.7220683901726338, -0.06367193965727952, 1.0077206300677382]); let x = ac.cholesky_solve(&b); assert!(x.close_to( &Vector::new([0.21181290359830895, 0.6039812818017399, 1.4062476574275615]), 1e-10 )); } #[test] fn test_matrix_argminmax() { let m = Matrix::new( [ -0.17927735, -0.81302638, -0.55424756, 0.68613317, -1.30208559, 1.37481722, -1.33316703, 1.4921796, -1.67213512, -1.42828313, -0.47680709, 1.30341714, -0.03714731, -1.74367455, 0.49485946, -1.03130816, ], 4, 4, ); let argmin = m.argmin(); let argmax = m.argmax(); assert_eq!(argmin, (3, 1)); assert_eq!(argmax, (1, 3)); } }
/*dependencies */ import React from 'react'; import { Route, Switch } from 'react-router-dom'; import 'bootstrap/dist/css/bootstrap.min.css'; /*components*/ import './App.css'; import LoginForm from './components/Login'; import PrivateRoute from './utils/PrivateRoute'; import Navigation from './components/Navigation'; import Home from './components/Home.js'; import ReceiptList from './components/ReceiptList'; import SignupForm from './components/SignUp'; import AddReceipt from './components/AddReceipt' import EditReceipt from './components/EditReceipt' function App() { return ( <div className='App'> <Navigation /> <Switch> <Route exact path='/' component={LoginForm} /> <PrivateRoute path ='/home' component={Home} /> <PrivateRoute path='/receipts' component={ReceiptList} /> <PrivateRoute path='/add-receipt' component={AddReceipt} /> <PrivateRoute path='/edit-receipt' component={EditReceipt} /> <Route path='/signup' component={SignupForm} /> <Route component={LoginForm} /> </Switch> </div> ); } export default App;
package com.momentolabs.app.security.applocker.ui.newpattern import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import com.andrognito.patternlockview.PatternLockView import com.momentolabs.app.security.applocker.R import com.momentolabs.app.security.applocker.databinding.ActivityCreateNewPatternBinding import com.momentolabs.app.security.applocker.ui.BaseActivity class CreateNewPatternActivity : BaseActivity<CreateNewPatternViewModel>() { private lateinit var binding: ActivityCreateNewPatternBinding override fun getViewModel(): Class<CreateNewPatternViewModel> = CreateNewPatternViewModel::class.java override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_create_new_pattern) binding.patternLockView.addPatternLockListener(object : SimplePatternListener() { override fun onComplete(pattern: MutableList<PatternLockView.Dot>?) { if (viewModel.isFirstPattern()) { viewModel.setFirstDrawedPattern(pattern) } else { viewModel.setRedrawnPattern(pattern) } binding.patternLockView.clearPattern() } }) viewModel.getPatternEventLiveData().observe(this, Observer { viewState -> binding.viewState = viewState binding.executePendingBindings() if (viewState.isCreatedNewPattern()) { onPatternCreateCompleted() } }) } private fun onPatternCreateCompleted() { setResult(Activity.RESULT_OK) finish() } companion object { fun newIntent(context: Context): Intent { return Intent(context, CreateNewPatternActivity::class.java) } } }
// // ValidationError.h // VrInteractiveTracking // // Created by 髙橋和成 on 11/10/18. // Copyright © 2018 VideoResearch. All rights reserved. // #import <Foundation/Foundation.h> /** 検証例外クラス */ @interface ValidationError : NSException /** Custom Exception @param msg メッセージ @return NSException */ + (NSException *)ValidationError:(NSString *)msg; @end
use expression::AsExpression; use expression::helper_types::AsExprOf; use expression::operators::{Escape, Like, NotLike}; use types::VarChar; /// Adds the `escape` method to `LIKE` and `NOT LIKE`. This is used to specify /// the escape character for the pattern. /// /// # Example /// /// ```rust /// # #[macro_use] extern crate diesel; /// # include!("src/doctest_setup.rs"); /// # /// # table! { /// # users { /// # id -> Integer, /// # name -> VarChar, /// # } /// # } /// # /// # fn main() { /// # use self::users::dsl::*; /// # use diesel::insert; /// # let connection = establish_connection(); /// # insert(&NewUser { name: "Ha%%0r".into() }).into(users) /// # .execute(&connection).unwrap(); /// let users_with_percent = users.select(name) /// .filter(name.like("%😀%%").escape('😀')) /// .load(&connection); /// let users_without_percent = users.select(name) /// .filter(name.not_like("%a%%").escape('a')) /// .load(&connection); /// assert_eq!(Ok(vec![String::from("Ha%%0r")]), users_with_percent); /// assert_eq!(Ok(vec![String::from("Sean"), String::from("Tess")]), users_without_percent); /// # } /// ``` pub trait EscapeExpressionMethods: Sized { fn escape(self, character: char) -> Escape<Self, AsExprOf<String, VarChar>> { Escape::new( self, AsExpression::<VarChar>::as_expression(character.to_string()), ) } } impl<T, U> EscapeExpressionMethods for Like<T, U> { } impl<T, U> EscapeExpressionMethods for NotLike<T, U> { }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class voteController extends Controller { public function __construct(){ $this->middleware('auth'); } public function index(){ return view('vote'); } public function vote(Request $request) { $rule = [ 'nim' => 'required|unique:vote' ]; $this -> validate($request, $rule); $insert = $request->all(); unset($insert['_token']); $status = DB::table('vote')->insert($insert); if($status){ return redirect('/home')->with('success', 'Terima Kasih telah menggunakan Hak Anda'); } // $insert = DB::table('vote')->insert([ // 'name'=>$request->nama, // 'nim'=>$request->nim, // 'voting'=>$request->kandidat, // ]); } }
<?php namespace Mitosis\Order\Models; use Konekt\Concord\Proxies\EnumProxy; class OrderStatusProxy extends EnumProxy { }
Create table If Not Exists Prices (product_id int, start_date date, end_date date, price int); Create table If Not Exists UnitsSold (product_id int, purchase_date date, units int); Truncate table Prices; insert into Prices (product_id, start_date, end_date, price) values ('1', '2019-02-17', '2019-02-28', '5'); insert into Prices (product_id, start_date, end_date, price) values ('1', '2019-03-01', '2019-03-22', '20'); insert into Prices (product_id, start_date, end_date, price) values ('2', '2019-02-01', '2019-02-20', '15'); insert into Prices (product_id, start_date, end_date, price) values ('2', '2019-02-21', '2019-03-31', '30'); Truncate table UnitsSold; insert into UnitsSold (product_id, purchase_date, units) values ('1', '2019-02-25', '100'); insert into UnitsSold (product_id, purchase_date, units) values ('1', '2019-03-01', '15'); insert into UnitsSold (product_id, purchase_date, units) values ('2', '2019-02-10', '200'); insert into UnitsSold (product_id, purchase_date, units) values ('2', '2019-03-22', '30');
<?php use yii\widgets\LinkPager; use yii\helpers\Url; use yii\helpers\Html; ?> <div class="col-md-12 manifestation_index_title"> <h2>Объявления</h2> </div> <?php foreach ($model as $row){ ?> <div class="col-md-12 manifestation_index_content"> <div class="col-md-3 manifestation_index_content_image"> <?=Html::img($row->image); ?> </div> <div class="col-md-9"> <div class="col-md-12"> <div class="col-md-8"></div> <div class="col-md-4 manifestation_index_content_info"> <!-- --><?/*=$row->user->username; */?> <?=Yii::$app->formatter->asDatetime($row->date, "php: H:i d.m.Y"); ?> </div> </div> <div class="col-md-12 manifestation_index_content_desctiption"><?=$row->description; ?></div> </div> </div> <?php } ?> <div class="col-md-12 manifestation_index_content_pagination"> <?=LinkPager::widget([ 'pagination' => $pages, ]); ?> </div>
# C3CTF 2017 [CTFtime Event](https://ctftime.org/event/544) [CTFtime Writeups](https://ctftime.org/event/544/tasks/) [CTFium](https://github.com/sajjadium/CTFium/tree/master/C3CTF/2017) | Challenge | Info | Exploitation | Links | |:-----------:|--------------------|----------------------|:---------:| | [simplegc](simplegc) | `x86_64` `NX` `Canary` `Partial RELRO` `ASLR` | `GOT` `fastbin` `glibc tcache` `heap` `use after free` | [Writeups](https://ctftime.org/task/5137) [CTFium](https://github.com/sajjadium/CTFium/tree/master/C3CTF/2017/simplegc) |
export async function postAnki(req: AnkiRequest): Promise<AnkiResponse> { // TODO: Make this configurable. const url = "http://localhost:8732/anki"; const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(req), }); return await response.json(); } interface AnkiRequest { readonly type: string; readonly target: string; } interface AnkiResponse { readonly basename: string; }
import { QueryRegistry, WorkerMessage } from '../messaging'; import { BaseContext } from './BaseContext'; import { Work } from './Work'; /* eslint-disable @typescript-eslint/no-explicit-any */ export type WorkerMessageMiddleware< TQueryRegistry extends QueryRegistry<{}>, TContext extends BaseContext<TQueryRegistry> > = ( req: Work<any>, context: TContext, next: (req: Work<any>, context: TContext) => Promise<WorkerMessage<any, any>> ) => Promise<WorkerMessage<any, any>>; /* eslint-enable @typescript-eslint/no-explicit-any */