text
stringlengths
27
775k
class AddPositionToMapElements < ActiveRecord::Migration def self.up add_column :map_standards, :position, :integer, default: 0 add_column :map_resources, :position, :integer, default: 0 add_column :map_objectives, :position, :integer, default: 0 add_column :map_assessments, :position, :integer, default: 0 # For each map element, add positions based of date of DESC create_date # User.all.each do |user| # counter = 0 # user.map_standards.each do |map_standard| # map_standard.position = counter # map_standard.save # counter += 1 # end # user.map_resources.each do |map_resource| # map_resource.position = counter # map_resource.save # counter += 1 # end # user.map_objectives.each do |map_objective| # map_objective.position = counter # map_objective.save # counter += 1 # end # user.map_assessments.each do |map_assessment| # map_assessment.position = counter # map_assessment.save # counter += 1 # end # end end def self.down remove_column :map_standards, :position remove_column :map_resources, :position remove_column :map_objectives, :position remove_column :map_assessments, :position end end
import mongoose from 'mongoose' import { isEmail, isURL, isMobilePhone } from 'validator' import { schemaComposer } from 'graphql-compose' import { composeWithMongoose } from 'graphql-compose-mongoose/node8' import { modifyResolver, setGlobalResolvers, grantAccessAdmin as admin, grantAccessAdminOrOwner as adminOwner } from '../middlewares' const Schema = mongoose.Schema const addressSchema = new Schema({ street: { type: String }, city: { type: String }, state: { type: String } }, { autoIndex: false }) const userSchema = new Schema({ socialId: { type: String, required: true, unique: true, match: /\d+/ }, displayName: { type: String, required: [true, 'displayName is required'], match: /^([A-Za-z]+((\s[A-Za-z]+)+)?)$/ }, emails: [{ value: { type: String, required: true, unique: true, validate: [{ validator: value => isEmail(value), message: 'email is invalid.' }] } }], photos: [{ value: { type: String, validate: { validator: isURL } } }], address: addressSchema, phone: { type: String, validate: [{ validator: value => isMobilePhone(value, this.address.country), message: 'phone is invalid.' }] }, roleId: { type: Schema.Types.ObjectId, ref: 'Role' }, vriTaken: { type: Boolean, default: false } }, { autoIndex: false }) const model = mongoose.model('User', userSchema) const modelTC = composeWithMongoose(model, { resolvers: { updateById: { record: { removeFields: ['socialId', 'roleId'] } } } }) setGlobalResolvers(model, modelTC, 'User') schemaComposer.rootQuery().addFields({ UserFindOne: modifyResolver(modelTC.getResolver('findOne'), admin), UserFindById: modifyResolver(modelTC.getResolver('findById'), adminOwner), UserFindByIds: modifyResolver(modelTC.getResolver('findByIds'), admin), UserFindMany: modifyResolver(modelTC.getResolver('findMany'), admin), UserCount: modifyResolver(modelTC.getResolver('count'), admin), UserConnection: modifyResolver( modelTC.getResolver('connection'), admin ), UserPagination: modifyResolver(modelTC.getResolver('pagination'), admin) }) schemaComposer.rootMutation().addFields({ UserUpdateById: modifyResolver(modelTC.getResolver('updateById'), adminOwner), UserRemoveById: modifyResolver(modelTC.getResolver('removeById'), adminOwner) }) const schema = schemaComposer.buildSchema() module.exports.modelTC = modelTC module.exports.model = model export default { model, modelTC, schema, addRelations (modelTCS) { modelTC.addRelation('responseMap', { description: 'the user response map', resolver: modelTCS.Response.getResolver('findMany'), args: { filter: source => ({ creatorId: source._id }), limit: (source, args) => args.limit }, projection: { _id: true } }) modelTC.addRelation('roleDetails', { description: 'the user role', resolver: modelTCS.Role.getResolver('findById'), prepareArgs: { _id: source => source.roleId }, projection: { roleId: true } }) } }
package nodes import ( "net/http" "strconv" "time" "github.com/BlooperDB/API/api" "github.com/BlooperDB/API/db" "github.com/BlooperDB/API/utils" "github.com/gorilla/mux" "github.com/wuman/firebase-server-sdk-go" ) type PrivateUserResponse struct { Id uint `json:"id"` Email string `json:"email"` Username string `json:"username"` Avatar string `json:"avatar"` CreatedAt time.Time `json:"register-date"` UpdatedAt time.Time `json:"register-date"` Blueprints []*BlueprintResponse `json:"blueprints,omitempty"` } type PublicUserResponse struct { Id uint `json:"id"` Username string `json:"username"` Avatar string `json:"avatar"` Blueprints []*BlueprintResponse `json:"blueprints,omitempty"` } func RegisterUserRoutes(router api.RegisterRoute) { router("POST", "/user/signin", signIn) router("GET", "/user/self", api.AuthHandler(getUserSelf, false)) router("PUT", "/user/self", api.AuthHandler(putUserSelf, false)) router("GET", "/user/self/blueprints", api.AuthHandler(getUserSelfBlueprints, false)) router("GET", "/user/{user}", getUser) router("GET", "/user/{user}/blueprints", getUserBlueprints) } type UserSignInResponse struct { BlooperToken string `json:"blooper-token"` FirstLogin bool `json:"first-login"` } type UserSignInRequest struct { FirebaseToken string `json:"firebase-token" validate:"nonzero"` } func signIn(r *http.Request) (interface{}, *utils.ErrorResponse) { var request UserSignInRequest e := utils.ValidateRequestBody(r, &request) if e != nil { return nil, e } auth, _ := firebase.GetAuth() decodedToken, err := auth.VerifyIDToken(request.FirebaseToken) if err != nil { return nil, &utils.ErrorResponse{ Code: utils.Error_user_token_invalid.Code, Message: utils.Error_user_token_invalid.Message + ": " + err.Error(), Status: utils.Error_user_token_invalid.Status, } } _, found := decodedToken.UID() if !found { return nil, &utils.Error_user_token_invalid } user, firstLogin := db.SignIn(decodedToken) return UserSignInResponse{ BlooperToken: user.BlooperToken, FirstLogin: firstLogin, }, nil } func getUser(r *http.Request) (interface{}, *utils.ErrorResponse) { userId, err := strconv.ParseUint(mux.Vars(r)["user"], 10, 32) if err != nil { return nil, &utils.Error_user_not_found } user := db.GetUserById(uint(userId)) if user == nil { return nil, &utils.Error_user_not_found } getBlueprints := len(r.URL.Query()["blueprints"]) > 0 var reBlueprint []*BlueprintResponse if getBlueprints { blueprints := user.GetUserBlueprints() reBlueprint = reBlueprintData(blueprints) } authUser := db.GetAuthUser(r) if authUser != nil && authUser.ID == uint(userId) { return PrivateUserResponse{ Id: uint(userId), Email: user.Email, Username: user.Username, Avatar: user.Avatar, CreatedAt: user.CreatedAt, UpdatedAt: user.UpdatedAt, Blueprints: reBlueprint, }, nil } return PublicUserResponse{ Id: uint(userId), Username: user.Username, Avatar: user.Avatar, Blueprints: reBlueprint, }, nil } func getUserSelf(u *db.User, r *http.Request) (interface{}, *utils.ErrorResponse) { blueprints := u.GetUserBlueprints() getBlueprints := len(r.URL.Query()["blueprints"]) > 0 var reBlueprint []*BlueprintResponse if getBlueprints { reBlueprint = reBlueprintData(blueprints) } return PrivateUserResponse{ Id: u.ID, Email: u.Email, Username: u.Username, Avatar: u.Avatar, CreatedAt: u.CreatedAt, UpdatedAt: u.UpdatedAt, Blueprints: reBlueprint, }, nil } type PutUserRequest struct { Username string `json:"username"` } func putUserSelf(u *db.User, r *http.Request) (interface{}, *utils.ErrorResponse) { var request PutUserRequest if e := utils.ValidateRequestBody(r, &request); e != nil { return nil, e } uname := request.Username if !utils.UsernameRegex.MatchString(uname) { return nil, &utils.Error_invalid_username } if existingUser := db.GetUserByUsername(request.Username); existingUser != nil { if u.ID != existingUser.ID { return nil, &utils.Error_username_taken } else { return nil, &utils.Error_nothing_changed } } u.Username = uname u.Save() return nil, nil } type UserBlueprintResponse struct { Blueprints []*BlueprintResponse `json:"blueprints"` } func getUserBlueprints(r *http.Request) (interface{}, *utils.ErrorResponse) { userId, err := strconv.ParseUint(mux.Vars(r)["user"], 10, 32) if err != nil { return nil, &utils.Error_user_not_found } user := db.GetUserById(uint(userId)) if user == nil { return nil, &utils.Error_user_not_found } return getBlueprintsUser(user) } func getUserSelfBlueprints(user *db.User, r *http.Request) (interface{}, *utils.ErrorResponse) { return getBlueprintsUser(user) } func getBlueprintsUser(user *db.User) (interface{}, *utils.ErrorResponse) { blueprints := user.GetUserBlueprints() reBlueprint := reBlueprintData(blueprints) return UserBlueprintResponse{ Blueprints: reBlueprint, }, nil }
-module(sm_gcm_api). -export([push/3]). -define(BASEURL, "https://gcm-http.googleapis.com/gcm/send"). -type header() :: {string(), string()}. -type headers() :: [header(),...]. -type regids() :: [binary(),...]. -type message() :: [tuple(),...]. -type result() :: {number(), non_neg_integer(), non_neg_integer(), non_neg_integer(), [any()]}. -spec push(regids(),message(),string()) -> {'error',any()} | {'noreply','unknown'} | {'ok',result()}. push(RegIds, {struct, MessageProps}, Key) -> Request = lists:flatten(sm:json_enc({struct, [{"registration_ids", {array, RegIds}}|MessageProps]})), ApiKey = string:concat("key=", Key), try httpc:request(post, {?BASEURL, [{"Authorization", ApiKey}], "application/json", Request}, [], []) of {ok, {{_, 200, _}, _Headers, Body}} -> Json = sm:json_dec(Body), %%error_logger:info_msg("Result was: ~p~n", [Json]), {ok, result_from(Json)}; {ok, {{_, 400, _}, _, Body}} -> error_logger:error_msg("Error in request. Reason was: Bad Request - ~p~n", [Body]), {error, Body}; {ok, {{_, 401, _}, _, _}} -> error_logger:error_msg("Error in request. Reason was: authorization error~n", []), {error, auth_error}; {ok, {{_, Code, _}, Headers, _}} when Code >= 500 andalso Code =< 599 -> RetryTime = retry_after_from(Headers), error_logger:error_msg("Error in request. Reason was: retry. Will retry in: ~p~n", [RetryTime]), {error, {retry, RetryTime}}; {ok, {{_StatusLine, _, _}, _, _Body}} -> error_logger:error_msg("Error in request. Reason was: timeout~n", []), {error, timeout}; {error, Reason} -> error_logger:error_msg("Error in request. Reason was: ~p~n", [Reason]), {error, Reason}; OtherError -> error_logger:error_msg("Error in request. Reason was: ~p~n", [OtherError]), {noreply, unknown} catch Exception -> error_logger:error_msg("Error in request. Exception ~p while calling URL: ~p~n", [Exception, ?BASEURL]), {error, Exception} end. -spec result_from([{struct,list()}]) -> result(). result_from({struct, Props}) -> { proplists:get_value("multicast_id", Props), proplists:get_value("success", Props), proplists:get_value("failure", Props), proplists:get_value("canonical_ids", Props), proplists:get_value("results", Props) }. -spec retry_after_from(headers()) -> 'no_retry' | non_neg_integer(). retry_after_from(Headers) -> case proplists:get_value("retry-after", Headers) of undefined -> no_retry; RetryTime -> case string:to_integer(RetryTime) of {Time, _} when is_integer(Time) -> Time; {error, no_integer} -> sm:parse_http_date(RetryTime) - sm:now() end end.
# frozen_string_literal: true class MockObserver < Observer def initialize super() @is_updated = false end def update(_board) @is_updated = true end attr_reader :is_updated end
use luminance_front::context::GraphicsContext as _; use luminance_front::tess::TessError; use luminance_glfw::GlfwSurface; use luminance_windowing::WindowOpt; pub fn fixture() { let mut surface = GlfwSurface::new_gl33("Tess no data", WindowOpt::default()).unwrap(); let tess = surface.new_tess().build(); assert!(matches!(tess, Err(TessError::NoData))); }
module Telegraphist class Model::User < Model attr_accessor :id, :first_name, :last_name, :username, :type def to_s [id, username, [first_name, last_name].compact.join(' ')].join(' :: ') end end end
/// @file unarch.h /// @author Nick Pershin #pragma once #ifndef UNARCH_H_20150506_122227 #define UNARCH_H_20150506_122227 #ifdef __cplusplus extern "C" { #endif // typedef char* (*TYPE_unarch)(const char*); // extern "C" char* Reverse(const char*); typedef char* (*TYPE_unarch)(void); const char* SaySomething(); #ifdef __cplusplus } #endif #endif /* #ifndef UNARCH_H_20150506_122227 */
Calculate the Hofstadter Q-sequence, using a big array rather than recursion. INTEGER ENUFF PARAMETER (ENUFF = 100000) INTEGER Q(ENUFF) !Lots of memory these days. Q(1) = 1 !Initial values as per the definition. Q(2) = 1 Q(3:) = -123456789!This will surely cause trouble! DO I = 3,ENUFF !For values beyond the second, Q(I) = Q(I - Q(I - 1)) + Q(I - Q(I - 2)) !Reach back according to the last two values. END DO Cast forth results as per the specification. WRITE (6,1) Q(1:10) !Should be 1 1 2 3 3 4 5 5 6 6... 1 FORMAT ("First ten values:",10I2) !Known to be one-digit numbers. WRITE (6,*) "Q(1000) =",Q(1000) !Should be 502. WRITE (6,3) ENUFF,COUNT(Q(2:ENUFF) < Q(1:ENUFF - 1)) !Please don't create a temporary array! 3 FORMAT ("Count of those elements 2:",I0, 1 " which are less than their predecessor: ",I0) !Should be 49798. Curry favour by allowing enquiries. 10 WRITE (6,11) ENUFF 11 FORMAT ("Nominate an index (in 1:",I0,"): ",$) !Obviously, the $ says don't start a new line. READ (5,*,END = 999, ERR = 999) I !Ask for a number, with precautions. IF (I.GT.0 .AND. I.LE.ENUFF) THEN !A good number, but, within range? WRITE (6,12) I,Q(I) !Yes. Reveal the requested value. 12 FORMAT ("Q(",I0,") = ",I0) !This should do. GO TO 10 !And ask again. END IF ! WHILE read(5,*) i & i > 0 & i < enuff DO write(6,*) "Q(",i,")=",Q(i); Closedown. 999 WRITE (6,*) "Bye." END
<?php namespace App\Http\Controllers; use App\Post; use App\Comment; use App\Project; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class CommentsController extends Controller { // public function index() { $test = 1; return view('comments.index', compact('test')); } public function store(Request $request) { //return 'here'; if($request->parent_type == "App\Post") { $parent = Post::where('id', $request->parent_id) ->get(); $parent = $parent[0]; } else { $parent = Comment::where('id', $request->parent_id) ->get(); $parent = $parent[0]; } $comment = $parent->child_comments()->create([ 'created_at' => now(), 'updated_at' => now(), 'content_md' => $request->content_md, 'parent_type' => $request->parent_type, 'level' => $request->level, 'parent_id' => $request->parent_id, 'creator_id' => Auth::user()->id, ]); $project = Project::where('id', $request->project_id) ->get(); $project = $project[0]; //return view('projects.show', compact('project')); return redirect()->route('projects.show', $project); } public function destroy(Comment $comment) { if(Auth::user()->id == $comment->creator_id) { $comment->update([ 'deleted'=>true, ]); } return redirect()->back(); } }
# frozen_string_literal: true require 'rails_helper' RSpec.describe UtilityHookup, type: :model do it { is_expected.to validate_presence_of(:utility_slug) } describe '.new' do it 'accepts nested attributes for the utility' do uh = UtilityHookup.new(utility_slug: :jitsi, utility_attributes: { meet_domain: 'asdf' }) expect(uh.utility.meet_domain).to eq('asdf') end end describe '#name' do it 'defaults to the humanized version of the hookup slug' do utility_hookup = UtilityHookup.new(utility_slug: :null_hookup) expect(utility_hookup.name).to eq('Null hookup') end end describe '#utility' do it 'exposes its configuration' do utility_hookup = UtilityHookup.new(utility_slug: :null_hookup, configuration: { a: :b }) expect(utility_hookup.utility).to be_a(Utilities::NullUtility) expect(utility_hookup.utility.configuration['a']).to eq('b') end end describe '#configuration' do it 'starts as an empty hash' do uh = FactoryBot.create(:utility_hookup, :jitsi) expect(uh.configuration).to eq({}) end it 'is encrypted' do utility_hookup = UtilityHookup.new(utility_slug: :null_hookup, configuration: { a: :b }) expect(utility_hookup.configuration).to eq('a' => 'b') expect(utility_hookup.configuration_ciphertext).not_to be_empty end end end
package com.octo.workerdecorator.processor import com.octo.workerdecorator.processor.entity.Configuration import com.octo.workerdecorator.processor.entity.HelperConfiguration import com.octo.workerdecorator.processor.entity.Implementation.EXECUTOR import com.octo.workerdecorator.processor.entity.Language.JAVA import com.octo.workerdecorator.processor.entity.Language.KOTLIN import com.octo.workerdecorator.processor.entity.Mutability.IMMUTABLE import com.octo.workerdecorator.processor.entity.Mutability.MUTABLE import com.octo.workerdecorator.processor.entity.ReferenceStrength.STRONG import com.octo.workerdecorator.processor.entity.ReferenceStrength.WEAK import com.octo.workerdecorator.processor.generator.* /** * Class responsible for creating the generators corresponding to the given configuration */ class GeneratorFactory { fun make(configuration: Configuration): Generator = when (configuration) { Configuration(KOTLIN, EXECUTOR, IMMUTABLE, STRONG) -> KotlinImmutableExecutorGenerator() Configuration(KOTLIN, EXECUTOR, IMMUTABLE, WEAK) -> KotlinImmutableWeakExecutorGenerator() Configuration(KOTLIN, EXECUTOR, MUTABLE, STRONG) -> KotlinMutableExecutorGenerator() Configuration(KOTLIN, EXECUTOR, MUTABLE, WEAK) -> KotlinMutableWeakExecutorGenerator() Configuration(JAVA, EXECUTOR, IMMUTABLE, STRONG) -> JavaImmutableExecutorGenerator() Configuration(JAVA, EXECUTOR, IMMUTABLE, WEAK) -> JavaImmutableWeakExecutorGenerator() Configuration(JAVA, EXECUTOR, MUTABLE, STRONG) -> JavaMutableExecutorGenerator() Configuration(JAVA, EXECUTOR, MUTABLE, WEAK) -> JavaMutableWeakExecutorGenerator() else -> throw Exception("No generator for $configuration") } fun makeAggregator(configuration: HelperConfiguration): HelperGenerator = when (configuration) { HelperConfiguration(KOTLIN, EXECUTOR) -> KotlinExecutorHelperGenerator() HelperConfiguration(JAVA, EXECUTOR) -> JavaExecutorHelperGenerator() else -> EmptyHelperGenerator() } }
require 'asciidoctor' require 'naturally' require 'awestruct/ibeams/errors' module Awestruct module IBeams module AsciidocSections # sections_from() will take the given # # @param [String] relative or absolute path to a directory containing # asciidoc files (`.ad`, `.adoc`) # @return [Array] Array of arrays containing: [section_title, filepath, # link_to_section, subsections] # @raise [Errors::InvalidPath] thrown when the provided +directory+ is # not a valid path to an existing directory def sections_from(directory) if directory.nil? raise Errors::InvalidPath.new("The provided `directory` was nil") end unless File.directory?(directory) raise Errors::InvalidPath.new("The provided `#{directory}` is not a valid directory") end # Generate a +Hash+ of all the pages in the site keyed by their path # for easy discovery pages_by_path = site.pages.map { |p| [p.source_path, p] }.to_h sections = [] Naturally.sort(Dir.glob(File.join(directory, '*.{ad,adoc}'))).each do |adoc| # Since all our documents are going to have front-matter so they render # properly, we need to look first at the Awestruct::Page and then # re-render to grab the sections from the asciidoc page = pages_by_path[adoc] url = page.url document = Asciidoctor.load(page.raw_content) document.sections.each do |section| sections << [ section.title, { :asciidoc => document, :path => adoc, :page => page, }, url, find_subsections_from(section, document) ] end end return sections end # This method will recurse through all the subsections of the given # +section+ to discover the full tree of subsections and compute a nested # array containing them. # # @param [Asciidoctor::Section] section to discover subsections from # @param [Asciidoctor::Document] Document objection the section anchor # belongs to, this is necessary to ensure the document's settinsg are # used to provide the appropriate anchors # @return [Array] of subsection arrays def find_subsections_from(section, in_document) found = [] section.sections.each do |subsection| title = subsection.title found << [ title, { :asciidoc => in_document, :path => in_document.file, }, section_anchor(title, in_document), find_subsections_from(subsection, in_document), ] end return found end # Compute an appropriate section anchor for the given title within the # given +Asciidoctor::Document+. This is effectively the same logic that # Asciidoctor itself inside the +Asciidoctor::Section#generate_id+ method # but extracted to be callable in an idempotent fashion # # @param [String] title of the section provided # @param [Asciidoctor::Document] Document objection the section anchor # belongs to, this is necessary to ensure the document's settinsg are # used to provide the appropriate anchor # @return [String] Computed section anchor def section_anchor(title, in_document) prefix = in_document.attributes['idprefix'] || '' separator = in_document.attributes['idseparator'] || '-' title = title.downcase.gsub(Asciidoctor::InvalidSectionIdCharsRx, '') return [ prefix, title.tr_s(" ._-", separator).chomp(separator).delete_prefix(separator), ].join('') end end end end
<?php namespace CSC\Model\Traits; /** * Trait SoftDeleteTrait */ trait SoftDeleteTrait { /** * @var bool */ protected $isDeleted = false; /** * @return $this */ public function delete() { $this->isDeleted = true; return $this; } /** * @return $this */ public function revert() { $this->isDeleted = false; return $this; } /** * @return bool */ public function isActive(): bool { return !$this->isDeleted; } }
using RabbitMQ.Client; namespace Mercury.Messaging.Abstractions { public interface IStructureInitializer { void Initialize(IModel channel); } }
module TDP.Synth.EventHandler where import Control.Concurrent.STM.TVar (TVar) import Graphics.Gloss.Interface.IO.Interact (Event (..), Key (..), KeyState (..)) import TDP.Note import TDP.Synth.Input import TDP.Synth.InputState import TDP.Synth.Keymapping handleEvent :: Keymapping -> TVar NoteQueue -> Event -> IO () handleEvent km nq (EventKey (Char c) Down _ _) = addNotes nq (applyKeymapping km [c]) handleEvent km nq (EventKey (Char c) Up _ _) = removeNotes nq (applyKeymapping km [c]) handleEvent _ _ _ = pure ()
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StarbuzzCoffee.ThirdDesignDecorator { public class Soy : CondimentDecorator { readonly Beverage beverage; public Soy(Beverage beverage) { this.beverage = beverage; } public override string Description => beverage.Description + " +Soy"; public override decimal Cost { get { return beverage.Size switch { ESize.TALL => beverage.Cost + .10M, ESize.GRANDE => beverage.Cost + .15M, ESize.VENTI => beverage.Cost + .20M, _ => beverage.Cost + .10M, }; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; [CustomEditor(typeof(EnemyLookAt))] [CanEditMultipleObjects] public class EnemyLookAtEditor : Editor { public void OnSceneGUI() { var lookAt = (target as EnemyLookAt); var handlePos = lookAt.transform.position; UnityEditor.Handles.color = new Color(1, 0, 0, 0.2f); UnityEditor.Handles.DrawSolidArc( handlePos, Vector3.back, Vector3.left, lookAt.m_lookatRotationLimit, UnityEditor.HandleUtility.GetHandleSize(handlePos)); UnityEditor.Handles.DrawSolidArc( handlePos, Vector3.back, Vector3.left, -lookAt.m_lookatRotationLimit, UnityEditor.HandleUtility.GetHandleSize(handlePos)); } }
@using OJS.Web.Areas.Administration.Controllers @using OJS.Web.Areas.Contests.Controllers @using Resource = Resources.Areas.Contests.Views.ListIndex @{ ViewBag.Title = Resource.Title; } @section Styles{ @Styles.Render("~/Content/contests/list/index") } <ol class="breadcrumb"> <li><a href="/">@Resource.Home</a></li> <li><a href="@(Url.Action<ListController>(c => c.Index()))">@Resource.Contests</a></li> </ol> <div class="row loading-mask-container"> <div class="col-md-3"> <h2>@ViewBag.Title</h2> @(Html.Kendo().TreeView() .Name("contestsCategories") .DataTextField("Name") .DataSource(dataSource => dataSource .Model(m => { m.Id("Id"); m.HasChildren("HasChildren"); }) .Read(read => read.Action("ReadCategories", "List", new {area = "Contests"}))) .Events(ev => { ev.Select("expander.categorySelected"); ev.DataBound("expander.onDataBound"); })) @if (User.IsAdmin()) { <br /> <p class="pull-left"><a class="btn btn-primary" href="@(Url.Action<ContestCategoriesController>(c => c.Index()))">@Resource.Categories &raquo;</a></p> <p class="pull-right"><a class="btn btn-primary" href="@(Url.Action<ContestCategoriesController>(c => c.Hierarchy()))">@Resource.Hierarchy &raquo;</a></p> <div class="clearfix"></div> } </div> <div class="col-md-9"> <div id="contestsList"> </div> </div> @Html.Partial("_LoadingMask", "contest-categories-loading-mask") </div> @section Scripts { @Scripts.Render("~/bundles/list-categories") }
#!/bin/bash g++ my.cpp -o my g++ std.cpp -o std g++ data.cpp -o data while true; do ./data > data.in ./std <data.in >std.out ./my <data.in >my.out if diff std.out my.out; then printf "AC\n" else cat data.in printf "Wa\n" exit 0 fi done
class Campaign{ final String campaignName; final String campaignAffiliation; final Location location; Campaign({this.campaignName,this.campaignAffiliation, this.location}); } class Location{ final double latitude; final double longitude; Location({this.latitude, this.longitude}); } List<Campaign> mockCampaigns = [ Campaign( campaignName: "London Tax Strike", campaignAffiliation: "Extiction Rebelion", location: Location( latitude: 51.5074, longitude: 0.1278 ), ), Campaign( campaignName: "Stop LNG Gas Export Depot", campaignAffiliation: "Extiction Rebelion", location: Location( latitude: 47.2529, longitude: 122.4443 ), ), Campaign( campaignName: "Shut Down Hambach Coal Mine", campaignAffiliation: "Extiction Rebelion", location: Location( latitude: 51.1657, longitude:10.4515 ), ), Campaign( campaignName: "NY State Shutdown Pipline", campaignAffiliation: "Extiction Rebelion", location: Location( latitude: 40.7128, longitude:74.0060 ), ), ];
# frozen_string_literal: true class Player attr_accessor :name, :bank, :cards, :score def initialize(name) @name = name @bank = 100 @cards = [] @score = 0 end def place_bet @bank -= 10 end def count_score score = 0 cards.map do |card| Cards::DECK.select do |k, v| next unless card.include?(k) score = if score + v[:value].max > 21 score + v[:value].min else score + v[:value].max end end end @score = score end end
package runner import ( "bytes" "encoding/json" "fmt" "log" "strings" "unicode/utf8" ) type Provider interface { Execute(*Job) error } type EventProvider interface { Register(func() *Job) } type Task struct { Title string Properties json.RawMessage Provider Provider } func (t Task) String() string { return fmt.Sprintf("Task{Title: %q, Properties: %q, Provider: %q}\n", t.Title, t.Properties, t.Provider) } type Job struct { ID int State map[string]func() interface{} Tasks []Task } func (j *Job) String() string { return fmt.Sprintf("Job{ID: %d, State: %v, Tasks[%s]}\n", j.ID, j.State, j.Tasks) } func (j *Job) Store(key string, fn func() interface{}) { j.State[key] = fn } func (j *Job) Run() { go func() { for _, t := range j.Tasks { log.Printf("Running task %s (%s) of job %d\n", t.Title, t.Provider, j.ID) err := t.Provider.Execute(j) if err != nil { fmt.Printf("Error while executing %s -> %v\n", t.Title, err) break } } }() } func JobFactory() func(int, []Task) func() *Job { id := 0 return func(i int, tasks []Task) func() *Job { return func() *Job { j := &Job{id, make(map[string]func() interface{}), tasks[i:]} id += 1 return j } } } type stateParser struct { input string output bytes.Buffer pos int lpos int width int start int exps int } func (s *stateParser) next() rune { if s.pos >= len(s.input) { return -1 } r, w := utf8.DecodeRuneInString(s.input[s.pos:]) s.width = w s.lpos = s.pos s.pos += s.width return r } func (s *stateParser) getStateProperty(exp string, j *Job) (property string, ok bool) { if val, exists := j.State[exp]; exists { ok = true property = fmt.Sprint(val()) return } return } func (s *stateParser) replaceExpression(j *Job) { property, ok := s.getStateProperty(s.input[s.start+2:s.pos-1], j) if !ok { s.output.WriteString(s.input[s.start:s.pos]) return } s.output.WriteString(property) } func (j *Job) InterpolateState(data string) []byte { var s stateParser s.input = data var insideExpression bool for { r := s.next() if r == -1 { break } switch { case strings.HasPrefix(s.input[s.lpos:], "$("): insideExpression = true s.start = s.lpos case r == ')' && insideExpression: s.replaceExpression(j) insideExpression = false case !insideExpression: s.output.WriteRune(r) } } return s.output.Bytes() }
/* Code generators for custom blocks. */ // ================ MOVE BLOCK ================ // Blockly.Blocks['move'] = { init: function() { this.jsonInit(miniblocks.move); } }; Blockly.Python['move'] = function(block) { // from blockly var dropdown_direction = block.getFieldValue('direction'); var number_speed = block.getFieldValue('speed'); //string representation of function var fcn = { fwd: "move_forward(", bkw: "move_backward(" }[dropdown_direction]; return [fcn+number_speed+")", Blockly.Python.ORDER_NONE]; }; // ================ TURN BLOCK ================ // Blockly.Blocks['turn'] = { init: function() { this.jsonInit(miniblocks.turn); } }; Blockly.Python['turn'] = function(block) { var dropdown_direction = block.getFieldValue('direction'); var number_power = block.getFieldValue('power'); var code = dropdown_direction+"("+number_power+")"; return [code, Blockly.Python.ORDER_NONE]; }; // ================ SET WHEELPOWER BLOCK ================ // Blockly.Blocks['setwheelpower'] = { init: function() { this.jsonInit(miniblocks.setwheelpower); } }; Blockly.Python['setwheelpower'] = function(block) { var wheels = ['FL', 'FR', 'BL', 'BR'] var power = [0,0,0,0]; // dealing with wrong inputs for(var i=0; i<4; i++){ power[i] = Blockly.Python.valueToCode(block, wheels[i], Blockly.Python.ORDER_ATOMIC) || 0; if(power[i] < 100) { } else if(power[i] > 100) { alert("Oops! Please insert a number between 0 and 100."); power[i] = 100; } else { alert("Oops! Please insert a number between 0 and 100."); power[i] = 0; } } var code = 'set_wheel_power(' + power[0] + ',' + power[1] + ',' + power[2] + ',' + power[3] + ')'; return [code, Blockly.Python.ORDER_NONE]; }; // ================== WAIT BLOCK ================== // Blockly.Blocks['wait'] = { init: function(){ this.jsonInit(miniblocks.wait); } }; Blockly.Python['wait'] = function(block) { var time = Blockly.Python.valueToCode(block, 'time', Blockly.Python.ORDER_ATOMIC) || 0; var code = 'wait(' + time + ')'; return [code, Blockly.Python.ORDER_NONE]; };
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: implicit_dynamic_parameter part of 'localize.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Localize _$LocalizeFromJson(Map<String, dynamic> json) => $checkedCreate( 'Localize', json, ($checkedConvert) { final val = Localize( en: $checkedConvert('en', (v) => v as String?), vi: $checkedConvert('vi', (v) => v as String?), ); return val; }, ); Map<String, dynamic> _$LocalizeToJson(Localize instance) => <String, dynamic>{ 'en': instance.en, 'vi': instance.vi, };
package com.at4wireless.spring.model.dto; import java.sql.Timestamp; import com.at4wireless.spring.model.GoldenUnit; public class GoldenUnitDT { public GoldenUnitDT(GoldenUnit gu, String category) { this.id = gu.getIdGolden().intValue(); this.name = gu.getName(); this.created = gu.getCreatedDate(); this.modified = gu.getModifiedDate(); this.category = category; this.manufacturer = gu.getManufacturer(); this.model = gu.getModel(); this.swVer = gu.getSwVer(); this.hwVer = gu.getHwVer(); this.description = gu.getDescription(); } private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private Timestamp created; public Timestamp getCreated() { return created; } public void setCreated(Timestamp created) { this.created = created; } private Timestamp modified; public Timestamp getModified() { return modified; } public void setModified(Timestamp modified) { this.modified = modified; } private String category; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } private String manufacturer; public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } private String model; public String getModel() { return model; } public void setModel(String model) { this.model = model; } private String swVer; public String getSwVer() { return swVer; } public void setSwVer(String swVer) { this.swVer = swVer; } private String hwVer; public String getHwVer() { return hwVer; } public void setHwVer(String hwVer) { this.hwVer = hwVer; } private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
import React from 'react'; import ClassNames from 'classnames'; import ReactFireMixin from 'reactfire'; import L10nSpan from '../shared/l10n-span'; import CommentForm from './comment/comment-form'; import CommentList from './comment/comment-list'; import Constants from '../../../modules/Constants'; import Firebase from '../../../modules/wrapper/Firebase'; let ChatroomContainer = React.createClass({ mixins: [ReactFireMixin], getInitialState: function() { return { shown: false, unreadMessageCount: 0, isRoomConnected: false, roomName: '', onlineUsers: [], userInfo: {}, comments: [] }; }, componentWillMount: function() { Firebase.on('meatadata-updated', (metadata) => { this.setState({ roomName: metadata.roomName }); }); // Great, if the room is opened Firebase.on('setup', (userInfo) => { // we can join to specifc room let commentsRef = Firebase.joinCommentsRoom(); this.bindAsArray(commentsRef, 'comments'); // if there is any comment coming when the chatroom is hidden, // we should show some UI for users about this commentsRef.on('value', (snapshot) => { // it will be triggered when initialized, so we need to check // there is indeed any value coming before keep the count. if (snapshot.val() && !this.state.shown) { this.setState({ unreadMessageCount: this.state.unreadMessageCount + 1 }); } }); let onlineUsersRef = Firebase.joinOnlineUsersRoom(); this.bindAsArray(onlineUsersRef, 'onlineUsers'); let currentUserRef = onlineUsersRef.push(); // http://stackoverflow.com/questions/15982215/firebase-count-online-users // // This is special, we need to join to this special room to make sure // we can reflect the count of online users let connectedRef = Firebase.joinConnectedRoom(); connectedRef.on('value', (snapshot) => { if (snapshot.val() === true) { // Keep current user's information to `onlineUsersRef` currentUserRef.set(userInfo); currentUserRef.onDisconnect().remove(); } }); // keep current users information this.setState({ isRoomConnected: true, userInfo: userInfo }); }); Firebase.on('room-left', (roomName, ref) => { if ('comments' === roomName) { this.unbind('comments'); } else if ('onlineUsers' === roomName) { this.unbind('onlineUsers'); } }); Firebase.on('room-left-all', () => { // do a final cleanup this.setState({ userInfo: {}, roomName: '', isRoomConnected: false }); }); }, _onHeaderClick: function() { let isShown = this.state.shown; let option = {}; option.shown = !isShown; // before clicking, it is hidden, so it means user is going to // open the chatroom, then we have to reset the unreadMessageCount if (!isShown) { option.unreadMessageCount = 0; } this.setState(option); }, _onCommentSubmit: function(comment) { let userName = this.state.userInfo.userName; this.firebaseRefs.comments.push({ userName: userName, comment: comment }); }, _getOnlineUsersCount: function() { let onlineUsers = this.state.onlineUsers; // unbind() will cause the value to `undefined` ... let onlineUsersCount = onlineUsers && onlineUsers.length; if (this.state.isRoomConnected) { return onlineUsersCount; } else { return 0; } }, render: function() { /* jshint ignore:start */ let headerSpan; let unreadCountSpan; let roomName = this.state.roomName; let comments = this.state.comments; let shown = this.state.shown; let isRoomConnected = this.state.isRoomConnected; let unreadMessageCount = this.state.unreadMessageCount; let onlineUsersCount = this._getOnlineUsersCount(); if (roomName) { headerSpan = <span>{roomName}</span>; } else { headerSpan = <L10nSpan l10nId="chatroom_header"/>; } if (unreadMessageCount > 0) { unreadCountSpan = <span className="unread-count label label-danger">{unreadMessageCount}</span>; } let chatroomClass = ClassNames({ 'chatroom': true, 'shown': shown, 'online': isRoomConnected, 'offline': !isRoomConnected, 'error': false }); return ( <div className={chatroomClass}> {unreadCountSpan} <h1 className="header" onClick={this._onHeaderClick}> {headerSpan} - ({onlineUsersCount}) </h1> <div className="comment-container"> <CommentList comments={comments}></CommentList> <CommentForm onSubmit={this._onCommentSubmit} shown={shown} connected={isRoomConnected}></CommentForm> </div> </div> ); /* jshint ignore:end */ } }); module.exports = ChatroomContainer;
module SpamEngine module Filter @@filters = [] @@default_filters = [] class << self def register_default(klass) @@default_filters << klass.name unless @@default_filters.include?(klass.name) end def register(klass) @@filters << klass.name unless @@filters.include?(klass.name) end def filters @@filters = @@default_filters if @@filters.empty? @@filters end def filters=(filters) @@filters = filters end def names filters.map &:demodulize end def create(type, options) "SpamEngine::Filter::#{type.to_s.classify}".constantize.new options end end end end
export default function(value: any) { if (value === 'NULL::character varying') { return null } return value }
import { IConsigneeInfo } from '../IConsigneeInfo'; import { IReceiverInfo } from '../IReceiverInfo'; import { IDropoffCoordinates } from '../IDropoffCoordinates'; export interface IDropoffLoad { receiverInfo: IReceiverInfo; dropoffStartDate: string; dropoffLocation: string; dropoffStartTime: string; dropoffCoordinates: IDropoffCoordinates; consigneeInfo: IConsigneeInfo; dropoffEndDate: string; dropoffEndTime: string; }
<?php namespace Xenon\LaravelBDSms\Helper; class Helper { /** * Mobile Number Validation * @param $number * @return bool * @since v1.0.12 * @version v1.0.12 */ public static function numberValidation($number): bool { $validCheckPattern = "/^(?:\+88|01)?(?:\d{11}|\d{13})$/"; if (preg_match($validCheckPattern, $number)) { if (preg_match('/^(?:01)\d+$/', $number)) { $number = '+88' . $number; } return true; } return false; } }
import * as ResBodies from "bodies/response-bodies" import * as ReqBodies from "bodies/request-bodies" import * as BaseService from "./base-service" export function signIn( nickname: string ): Promise<ResBodies.PlayerResponseBody> { const body: ReqBodies.SignInRequestBody = { nickname } return BaseService.post("/sign-in", body) }
import 'package:flutter/material.dart'; import '../animation.dart'; @immutable class InvalidInputAnimatedWidget extends StatelessWidget { final AnimationUIConfig config; final VoidCallback onAnimationEnded; final Widget child; const InvalidInputAnimatedWidget({ Key key, this.config = const AnimationUIConfig(), @required this.onAnimationEnded, @required this.child, }) : super(key: key); double shake(double animation) => 2 * (0.5 - (0.5 - config.curve.transform(animation)).abs()); @override Widget build(BuildContext context) { return TweenAnimationBuilder<double>( key: key, tween: Tween(begin: 0.0, end: 1.0), duration: config.duration, onEnd: onAnimationEnded, builder: (context, animation, child) => Transform.translate( offset: Offset(config.deltaX * shake(animation), 0), child: child, ), child: child, ); } }
const TRACE = haskey(ENV, "TRACE") "Display a trace message. Only results in actual printing if the TRACE environment variable is set." @inline function trace(io::IO, msg...; prefix="TRACE: ", line=true) @static if TRACE Base.print_with_color(:cyan, io, prefix, chomp(string(msg...))) if line println(io) end end end @inline trace(msg...; kwargs...) = trace(STDERR, msg...; kwargs...) const DEBUG = TRACE || haskey(ENV, "DEBUG") "Display a debug message. Only results in actual printing if the TRACE or DEBUG environment variable is set." @inline function debug(io::IO, msg...; prefix="DEBUG: ", line=true) @static if DEBUG Base.print_with_color(:green, io, prefix, chomp(string(msg...))) if line println(io) end end end @inline debug(msg...; kwargs...) = debug(STDERR, msg...; kwargs...) "Create an indented string from any value (instead of escaping endlines as \n)" function repr_indented(ex; prefix=" "^7, abbrev=true) io = IOBuffer() print(io, ex) str = takebuf_string(io) # Limit output if abbrev && length(str) > 256 if isa(ex, Array) T = eltype(ex) dims = join(size(ex), " by ") if isbits(T) && zeros(ex) == ex # NOTE: not all types have zero() defined str = "$T[$dims zeros]" else str = "$T[$dims elements]" end else if contains(strip(str), "\n") str = str[1:100] * "…\n\n[snip]\n\n…" * str[end-100:end] else str = str[1:100] * "…" * str[end-100:end] end end end lines = split(strip(str), '\n') if length(lines) > 1 for i = 1:length(lines) lines[i] = prefix * lines[i] end lines[1] = "\"\n" * lines[1] lines[length(lines)] = lines[length(lines)] * "\"" return join(lines, '\n') else return str end end function __init_logging__() # TODO: assign TRACE and DEBUG at run-time, not using the pre-compiled code # when the values are different? # or make it work like CPU_CORES dose after Julia/#16219 if TRACE trace("CUDAdrv.jl is running in trace mode, this will generate a lot of additional output") elseif DEBUG debug("CUDAdrv.jl is running in debug mode, this will generate additional output") debug("Run with TRACE=1 to enable even more output") end end
package com.example.composebasics.model import androidx.annotation.DrawableRes import com.example.composebasics.R data class Author(val name: String, @DrawableRes val picture: Int) { companion object { val pierre = Author(name = "Pierre Vieira", picture = R.drawable.pierre_vieira_profile) val android = Author(name = "Android", picture = R.drawable.android_18_profile_picture) } }
import { startNucleus} from "../Nucleus" ; import { IApi } from "../Plugin" ; declare var _nucleus_api: IApi; export async function start(){ const dataPath = (document.currentScript as HTMLScriptElement).getAttribute("data-path") || ""; // Start the core api expose it await startNucleus(); try { //Load the nucleus engine await _nucleus_api.Module.loadModule(`${dataPath}/nucleus.web.js`); } catch { /** Module does not exists */} // Check for the module.conf.json file try { const jsonConf = await(await fetch(`${dataPath}/modules.conf.web.json`)).json(); for(let i=0; i<jsonConf.modules.length; i++) { await _nucleus_api.Module.loadModule(`${dataPath}/${jsonConf.modules[i].path}`); } } catch(ex) { console.log(`modules.conf.web.json file was not found. Nucleus loading aborted.`); } }
require File.dirname(__FILE__) + '/utils' require File.dirname(__FILE__) + '/recurring_billing' require File.dirname(__FILE__) + '/am_extensions' Dir[File.dirname(__FILE__) + '/gateways/*.rb'].each{|g| require g}
#!/bin/sh export PATH=$PATH:/home/pi/.local/bin:/opt/rez/bin/rez: export LD_LIBRARY_PATH=/usr/local/lib
// import App from 'next/app' import '../static/css/prism.css' import GlobalStyle from '../src/styles/global'; import styled from 'styled-components'; import { Head } from 'next/document'; const Toolbar = styled.div` display: flex; flex-direction: row; justify-content: center; align-items: center; border-bottom: 1px solid blue; margin-bottom: 50px; width: 100%; height: 100px; ` function MyApp({ Component, pageProps }) { return ( <div> <GlobalStyle /> <Toolbar> <h1>Geus | Git Storm Server</h1> </Toolbar> <Component {...pageProps} /> </div> ) } // Only uncomment this method if you have blocking data requirements for // every single page in your application. This disables the ability to // perform automatic static optimization, causing every page in your app to // be server-side rendered. // // MyApp.getInitialProps = async (appContext) => { // // calls page's `getInitialProps` and fills `appProps.pageProps` // const appProps = await App.getInitialProps(appContext); // // return {...appProps} // } export default MyApp
module.exports = { extends: ['kirinus'], // This is an open source eslint definition. parserOptions: { project: ['./tsconfig.eslint.json', './packages/*/*/tsconfig.json'], tsconfigRootDir: __dirname, }, settings: { jest: { version: 'latest', }, react: { version: 'latest', }, }, ignorePatterns: ['**/storybook-static/*.js'], rules: { '@typescript-eslint/naming-convention': 'off', '@typescript-eslint/no-unsafe-return': 'off', 'ordered-imports/ordered-imports': [ 'error', { 'group-ordering': [ { name: 'current workspace', match: '^(\\$|#|\\.\\.?)/', order: 40, }, { name: 'monorepo packages', match: '^(lib|ui)-.*/src', order: 30, }, { name: 'third party', match: '.*', order: 20 }, { name: 'framework libraries', match: '^react.*', order: 10, }, ], }, ], 'eslint-comments/disable-enable-pair': 'off', 'react/jsx-sort-props': [ 'error', { callbacksLast: true, shorthandFirst: true, ignoreCase: false, reservedFirst: true, }, ], 'react-hooks/exhaustive-deps': 'off', 'unicorn/consistent-function-scoping': 'off', 'unicorn/filename-case': 'off', 'unicorn/prefer-add-event-listener': 'off', 'unicorn/prefer-node-protocol': 'off', 'unicorn/prevent-abbreviations': 'off', }, };
import * as React from 'react' type card = { heading: string paragraph: string imgUrl: string projectLink: string } const Card: React.FC<card> = ({ heading, paragraph, imgUrl, projectLink, }): JSX.Element => { return ( <div className='card' style={{ backgroundImage: 'linear-gradient(to bottom, rgba(245, 246, 252, 0), rgba(0, 0, 0, 0.2)),url(' + imgUrl + ')', }} > <div className='content'> <h1 className='header'>{heading}</h1> <p className='text'>{paragraph}</p> <a href={projectLink ? projectLink : '#'} target='_blank' rel='noopener noreferrer' className='btn' > Explore </a> </div> </div> ) } export default Card
package de.m7w3.signal.store.model import slick.jdbc.H2Profile.api._ object Schema { val schema = Addresses.addresses.schema ++ LocalIdentity.query.schema ++ PreKeys.preKeys.schema ++ PreKeys.idSequence.schema ++ Sessions.sessions.schema ++ SignedPreKeys.signedPreKeys.schema ++ SignedPreKeys.idSequence.schema ++ TrustedKeys.trustedKeys.schema ++ RegistrationData.registrationData.schema ++ Contacts.contacts.schema ++ Groups.groups.schema ++ GroupMembers.groupMembers.schema }
<?php /** * Combyna * Copyright (c) the Combyna project and contributors * https://github.com/combyna/combyna * * Released under the MIT license * https://github.com/combyna/combyna/raw/master/MIT-LICENSE.txt */ namespace Combyna\Component\Program\Validation\Validator; use Combyna\Component\App\Config\Act\AppNode; use Combyna\Component\Behaviour\Node\StructuredNodeInterface; use Combyna\Component\Validator\Context\RootValidationContextInterface; /** * Interface NodeValidatorInterface * * @author Dan Phillimore <dan@ovms.co> */ interface NodeValidatorInterface { /** * Validates an ACT node inside an app, populating a ValidationContext with any violations * * @param StructuredNodeInterface $node * @param AppNode $appNode * @return RootValidationContextInterface */ public function validate( StructuredNodeInterface $node, AppNode $appNode ); }
module Utils where -- | Get all adjacent elements paired up pairs :: [a] -> [(a, a)] pairs xs = zip xs (drop 1 xs) -- | Returns whether the list is in non-descending order inOrder :: Ord a => [a] -> Bool inOrder = all (uncurry (<=)) . pairs -- | Returns whether the value meets all given predicates meetsAll :: Foldable f => f (a -> Bool) -> a -> Bool meetsAll preds x = all ($ x) preds
context("pool checks") file.list=list( system.file("extdata", "test1.myCpG.txt", package = "methylKit"), system.file("extdata", "test2.myCpG.txt", package = "methylKit"), system.file("extdata", "control1.myCpG.txt", package = "methylKit"), system.file("extdata", "control2.myCpG.txt", package = "methylKit") ) myobj=methRead( file.list, sample.id=list("test1","test2","ctrl1","ctrl2"),assembly="hg18", pipeline="amp",treatment=c(1,1,0,0)) mydblist = suppressMessages(methRead( file.list, sample.id=list("t1","t2","c1","c2"),assembly="hg18", pipeline="amp",treatment=c(1,1,0,0),dbtype = "tabix",dbdir="methylDB")) # unite function methidh=unite(myobj) suppressMessages(methidhDB <- unite(mydblist)) test_that("test if output of unite is methylBase object", { expect_is(pool(methidh,sample.ids=c("test","control")), 'methylBase') expect_is(pool(methidhDB,sample.ids=c("test","control"),save.db = FALSE), 'methylBase') }) test_that("test if output of unite is methylBaseDB object", { expect_is(pool(methidhDB,sample.ids=c("test","control")), 'methylBaseDB') expect_is(pool(methidh,sample.ids=c("test","control"),save.db = TRUE,dbdir="methylDB"), 'methylBaseDB') }) test_that("wrong number of sample.ids lead to error", { expect_error(pool(methidhDB,sample.ids=c("test","control","onetoomuch"))) expect_error(pool(methidh,sample.ids=c("test","control","onetoomuch"))) }) unlink("tests/testthat/methylDB",recursive = TRUE)
FactoryGirl.define do factory :checklist do association :user, strategy: :create title "Title" factory :checklist_with_items do transient do items_count 5 end after(:create) do |checklist, evaluator| create_list(:checklist_item, evaluator.items_count, checklist: checklist) end end end end
import React from 'react'; import { render, screen } from '@testing-library/react'; import PriceBadge from './PriceBadge'; import PriceBadgeProps from './PriceBadge.types'; // renders a PriceBadge component test('renders a PriceBadge component', () => { const props: PriceBadgeProps = { price: 10, currency: 'USD', dataTestId: 'price-badge', }; render(<PriceBadge {...props} />); const priceBadge = screen.getByTestId('price-badge'); expect(priceBadge).toBeInTheDocument(); }); // renders a PriceBadge component with a price of 0 and currency of USD test('renders a PriceBadge component with a price of 0 and currency of USD', () => { const props: PriceBadgeProps = { price: 0, currency: 'USD', dataTestId: 'price-badge', }; render(<PriceBadge {...props} />); const priceBadge = screen.getByTestId('price-badge'); expect(priceBadge).toHaveTextContent('$0'); });
<?php namespace Ornament; use StdClass; use ReflectionProperty; /** * A container is a simple internal object representation of (part of) a model. */ class Container { /** @var Private Adapter storage. */ private $adapter; /** @var Private store for last check of model's state. */ private $lastCheck = []; /** * Constructor. Initialize with the Adapter to use. */ public function __construct(Adapter $adapter) { $this->adapter = $adapter; $this->lastCheck = $this->export(); } /** * Query multiple models in an Adapter-independent way. * * @param object $parent The actual parent model to load into. * @param array $parameters Key/value pair of parameters to query on (e.g., * ['parent' => 1]). * @param array $opts Optional hash of options. * @param array $ctor Optional contructor arguments. * @return array Array of models of the same type as $parent. */ public function query($parent, array $parameters, array $opts = [], array $ctor = []) { return $this->adapter->query($parent, $parameters, $opts, $ctor); } /** * (Re)load the model based on existing settings. */ public function load() { $this->adapter->load($this); } /** * Persist this model back to whatever storage Adapter it was constructed * with. * * @return boolean true on success, false on error. */ public function save() { if ($this->isNew()) { return $this->adapter->create($this); } else { return $this->adapter->update($this); } } /** * Delete this model from whatever storage Adapter it was constructed with. * * @return boolean true on success, false on error. */ public function delete() { return $this->adapter->delete($this); } /** * Internal helper method to export the model's public properties. * * @return array An array of key/value pairs. */ private function export() { $exported = new StdClass; foreach ($this as $name => $field) { if ((new ReflectionProperty($this, $name))->isPublic()) { if (is_object($field)) { $traits = class_uses($field); if (isset($traits['Ornament\Model']) || isset($traits['Ornament\JsonModel']) ) { $exported->$name = $field->getPrimaryKey(); } else { $exported->$name = "$field"; } } else { $exported->$name = $field; } } } return $exported; } /** * Marks this model as being "new" (i.e., save proxies to create, not * update). */ public function markNew() { $this->lastCheck = []; } /** * Marks this model as "deleted". The class will still contain old * properties and values, but deletion has taken place. */ public function markDeleted() { $this->lastCheck = null; } /** * Marks this model as "clean", i.e. set clean state to current state, * no questions asked. * * @see Ornament\Storage::markClean */ public function markClean() { $this->lastCheck = $this->export(); } /** * Checks if this model is "new". * * @return boolean true if new, otherwise false. */ public function isNew() { return $this->lastCheck == []; } /** * Checks if this model has been deleted. * * @return boolean true if deleted, otherwise false. */ public function isDeleted() { return !isset($this->lastCheck); } /** * Checks if this model is "dirty" compared to the last known "clean" * state. * * @return boolean true if dirty, otherwise false. */ public function isDirty() { return $this->lastCheck != $this->export(); } /** * Checks if a specific property is "dirty" compared to the last known * "clean" state. * * @param string $property The name of the property to check. * @return boolean true if dirty, otherwise false. */ public function isModified($property) { return $this->lastCheck[$property] != $this->$property; } }
<div class="tasks__item"> <div class="tasks__item-header"> <span class="tasks__item-status">{!! __('task-status.' . $task->status) !!}</span> @if ($task->trashed()) <span class="tasks__item-status deleted"> {!! __('Удалена') !!} </span> @endif <p class="tasks__item-name"> {!! $task->name !!} @include('icons.arrow', ['iClasses' => 'tasks__item-name-icon']) </p> <div class="tasks__item-actions"> @if (!$task->trashed()) @include('components.tasks.status-form', ['task' => $task]) @include('components.tasks.delete', ['task' => $task]) <a href="{{ route('page.tasks.edit', $task->id) }}" class="tasks__item-action"> @include('icons.edit', [ 'iClasses' => 'tasks__item-action-icon' ]) </a> @else @include('components.tasks.delete', ['task' => $task]) @include('components.tasks.restore', ['task' => $task]) @endif </div> </div> <div class="tasks__item-content"> {!! $task->content !!} </div> </div>
# Changelog ## 1.0.0 Released: 03/16/2022 Initial stable version as showed in [Examples.jpynb](examples/Examples_1_0_0.ipynb)
package com.vendas.model.dto.cliente; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; @JsonIgnoreProperties(ignoreUnknown = true) @Data public class ClienteUpdatePasswordDTO { private Long idCliente; private String senha; }
using UnityEngine; using Vectors.CustomProperty.Attribute; namespace Vectors._2D { public abstract class _2D_Base : MonoBehaviour { [SerializeField] protected bool _debugLines = true; protected GameObject _player; protected Vector2 _playerPosition; [Header("Player")] [_CA_Color(_Color.Red, order = 0)] [_CA_Range("X", -50, 50, order = 1)] [SerializeField] protected float _playerX; [_CA_Color(_Color.Green, order = 0)] [_CA_Range("Y", -50, 50, order = 1)] [SerializeField] protected float _playerY; // ----- protected GameObject _enemy; protected Vector2 _enemyPosition; protected readonly Vector2 _zero = Vector2.zero; protected virtual void LateUpdate() { if (_debugLines) { DebugLines(); } } protected virtual void UpdatePlayerPosition() { _playerPosition = new Vector2(_playerX, _playerY); _player.transform.position = _playerPosition; } protected virtual void UpdateEnemyPosition(float enemyX, float enemyY) { _enemyPosition = new Vector2(enemyX, enemyY); _enemy.transform.position = _enemyPosition; } protected virtual void DebugLines() { Debug.DrawLine(_zero, _playerPosition, Color.green); } } }
module Text.Help.GetOpt ( OptDescr(..) , ArgDescr(..) , ArgOrder(..) , getOpt ) where import Text.Help.Markup import System.Console.GetOpt (ArgOrder(..), ArgDescr(..)) import qualified System.Console.GetOpt as G data OptDescr a = Option [Char] [String] (ArgDescr a) Text getOpt :: ArgOrder a -> [OptDescr a] -> [String] -> ([a], [String], [String]) getOpt argOrder optDescr args = G.getOpt argOrder (map removeMarkup optDescr) args where removeMarkup :: OptDescr a -> G.OptDescr a removeMarkup (Option shortOpts longOpts argDescr descr) = G.Option shortOpts longOpts argDescr (textToString descr)
require 'simplecov' SimpleCov.start do add_filter 'spec/dummy' add_group 'Controllers', 'app/controllers' add_group 'Helpers', 'app/helpers' add_group 'Mailers', 'app/mailers' add_group 'Models', 'app/models' add_group 'Views', 'app/views' add_group 'Libraries', 'lib' end $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) ENV["RAILS_ENV"] = "test" require 'solidus_braintree' require_relative "dummy/config/environment" require 'vcr' require 'webmock' require 'pry' require 'byebug' require 'solidus_support/extension/feature_helper' require 'spree/testing_support/order_walkthrough' require 'spree/testing_support/controller_requests' module SolidusGateway module Helpers module BraintreeGateway def create_braintree_payment_method gateway = Solidus::Gateway::BraintreeGateway.create!( name: 'Braintree Gateway', active: true ) gateway.set_preference(:environment, 'sandbox') gateway.set_preference(:merchant_id, 'zbn5yzq9t7wmwx42') gateway.set_preference(:public_key, 'ym9djwqpkxbv3xzt') gateway.set_preference(:private_key, '4ghghkyp2yy6yqc8') gateway.save! gateway end end end end Braintree::Configuration.logger = Rails.logger FactoryBot.find_definitions VCR.configure do |c| c.cassette_library_dir = "spec/cassettes" c.hook_into :webmock c.ignore_localhost = true c.configure_rspec_metadata! end RSpec.configure do |config| config.use_transactional_fixtures = false config.include Spree::TestingSupport::ControllerRequests, type: :controller config.include Spree::TestingSupport::UrlHelpers, type: :controller config.include SolidusGateway::Helpers::BraintreeGateway config.before :suite do DatabaseCleaner.strategy = :transaction end config.before do |example| DatabaseCleaner.start end config.after do DatabaseCleaner.clean end end
export interface ExtConfig { isTimerEnabled: boolean; useAutoReset: boolean; timeBlockSitesOnly: boolean; useBreaks: boolean; useLogging: boolean; useBlockSitesAsLogSites: boolean; blockSiteList: Site[]; logSiteList: Site[]; } export interface Site { url: string; videoSiteData: VideoSiteData; } export interface EmbeddedSite extends Site { $iframe: any; $blockScreen: any; } export interface VideoSiteConfig { url: string; selector: string; activateOnSelectorFound: boolean; } export interface VideoSiteData extends VideoSiteConfig { timeVideoOnly: boolean; }
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:qrcodereader/localization/AppLocalizations.dart'; import 'package:qrcodereader/models/EventObject.dart'; import 'package:qrcodereader/models/Info.dart'; import 'package:qrcodereader/pages/detail.dart'; import 'package:qrcodereader/storage/MySharedPreferences.dart'; import 'package:qrcodereader/utils/constants.dart'; class History extends StatefulWidget { HistoryState createState() => HistoryState(); } class HistoryState extends State<History> { List<Info> qrScans = new List<Info>(); EventObject eventObject; Map<String, bool> mapScans = new Map<String, bool>(); @override void initState() { loadInfos(); super.initState(); } void loadInfos() { MySharedPreferences.getInfosPrefs().then((value) { if (value.id == Events.READ_INFOS_SUCCESSFULLY) setState(() { qrScans = value.object; }); else setState(() { qrScans = new List<Info>(); }); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context).historyQR), actions: <Widget>[ Builder( builder: (BuildContext context) { return IconButton( icon: Icon( Icons.clear, color: Colors.white, ), tooltip: AppLocalizations.of(context).deleteSelected, onPressed: () => deleteSelected(context), ); }, ) ], ), body: buildBody(), ); } Widget buildBody() { return Scaffold( body: ListView( padding: EdgeInsets.all(8.0), children: qrScans.map((info) => buildListItem(info)).toList()), ); } Widget buildListItem(Info info) { var myFormat = DateFormat('d-MM-yyyy hh:mm'); return Card( child: Column( children: <Widget>[ CheckboxListTile( title: Text(info.title), value: mapScans[info.id] ?? false, subtitle: Text( AppLocalizations.of(context).date + myFormat.format(info.date)), controlAffinity: ListTileControlAffinity.leading, onChanged: (val) { setState(() { mapScans[info.id] = val; }); }, secondary: Container( child: IconButton( icon: Icon(Icons.arrow_forward_ios), onPressed: () => { Navigator.push( context, MaterialPageRoute( builder: (context) => Detail( info: info, ))) }), ), ), ], ), ); } void deleteSelected(BuildContext appBarContext) async { if (mapScans.length > 0) { for (int i = 0; i < mapScans.length; i++) { if (mapScans.values.elementAt(i) == true) { await MySharedPreferences.deleteInfoPrefs(mapScans.keys.elementAt(i)); } } loadInfos(); //Reload infos } else if (!mapScans.values.any((val) => val == true)) { Scaffold.of(appBarContext).showSnackBar(SnackBar( content: Text(AppLocalizations.of(context).selectOneItem), )); } } }
#!/usr/bin/env sh # # 基于 Ubuntu18 64位 # 检查是否安装iptables pkgName="iptables" checkRes=`dpkg --get-selections | grep iptables | awk -F : "END{print NR}"` if [ ${checkRes} -lt 1 ] then echo "没有安装${pkgName}\n" sudo apt -y install iptables mkdir -p /etc/iptables touch /etc/iptables/rules.conf cat rules.conf > /etc/iptables/rules.conf else echo "已经安装${pkgName}\n iptables规则如下:" echo "=============================:" cat /etc/iptables/rules.conf fi
module RestrictedController def self.included(clazz) clazz.class_eval { protected def admin_only require_roles('admin') end def require_roles(*roles) redirect_home unless (current_user != nil && current_user.has_role?(*roles)) end def redirect_home(message = "Please log in as an administrator") flash[:notice] = "Please log in as an administrator" redirect_to(main_app.home_url) end } end end
#!/bin/bash project_dir=$(pwd) mkdir -p build cd build cmake $project_dir cd $project_dir
from typing import Dict, Any, Tuple, Callable from datetime import timedelta from spacy.util import registry from spacy.errors import Errors from wasabi import msg @registry.loggers("spacy-ray.ConsoleLogger.v1") def ray_console_logger(): def setup_printer( nlp: "Language", ) -> Tuple[Callable[[Dict[str, Any]], None], Callable]: score_cols = list(nlp.config["training"]["score_weights"]) score_widths = [max(len(col), 6) for col in score_cols] loss_cols = [f"Loss {pipe}" for pipe in nlp.pipe_names] loss_widths = [max(len(col), 8) for col in loss_cols] table_header = ["T", "E", "#", "W"] + loss_cols + score_cols + ["Score"] table_header = [col.upper() for col in table_header] table_widths = [8, 3, 6, 6] + loss_widths + score_widths + [6] table_aligns = ["r" for _ in table_widths] msg.row(table_header, widths=table_widths) msg.row(["-" * width for width in table_widths]) def log_step(info: Dict[str, Any]): try: losses = [ "{0:.2f}".format(float(info["losses"][pipe_name])) for pipe_name in nlp.pipe_names ] except KeyError as e: raise KeyError( Errors.E983.format( dict="scores (losses)", key=str(e), keys=list(info["losses"].keys()), ) ) from None try: scores = [ "{0:.2f}".format(float(info["other_scores"].get(col, 0.0)) * 100) for col in score_cols ] except KeyError as e: raise KeyError( Errors.E983.format( dict="scores (other)", key=str(e), keys=list(info["other_scores"].keys()), ) ) from None time = timedelta(seconds=info["seconds"]) data = ( [str(time), info["epoch"], info["step"], info["words"]] + losses + scores + ["{0:.2f}".format(float(info["score"]))] ) msg.row(data, widths=table_widths, aligns=table_aligns) def finalize(): pass return log_step, finalize return setup_printer
//! defines a common interface for an implementation of tokenized vaults that may or may not compound use anchor_lang::{prelude::*, solana_program::account_info::AccountInfo}; use anchor_spl::token::Mint; pub trait TokenizedShares { /// used to check if a withdraw attempt is locked. whether or /// not a vault is locked depends on the underlying implementation fn is_locked(&self, last_deposit_time: i64) -> bool; /// used to compound the underlying token represented by the shares /// returns true if the implementation supports compound operations /// and returns false if the implementation does not support compound operations fn compound(&mut self, balance_to_add: u64) -> bool; /// returns true if the implementation supports compound operations fn supports_compound(&self) -> bool; /// returns the amount of shares to give in exchange for depositing the amount /// of underlying asset fn shares_to_give(&self, amount: u64) -> u64; /// returns the amount of underlying to redeem in exchange for burning the amount of shares fn underlying_to_redeem(&self, amount: u64) -> u64; /// used to record the effects of depositing underlying asset into the vault fn record_deposit(&mut self, amount: u64) -> u64; /// used to record the effect of withdrawing and burning the shares for their /// underlying assets. note you will need to calculate the shares to burn /// and the corresponding balance to remove fn record_withdraw(&mut self, shares_to_burn: u64, balance_to_remove: u64); /// returns the total deposited underlying tokens fn total_deposited_tokens(&self) -> u64; /// returns the total shares issued, which should match /// the shares mint supply fn total_shares(&self) -> u64; /// returns the share's mint account address fn shares_mint(&self) -> Pubkey; /// returns the share's underlying asset mint account address fn underlying_mint(&self) -> Pubkey; /// used to issue the actual shares fn issue_shares<'info>( &mut self, mint: &AccountInfo<'info>, // token account which will receive the shares receiver: &AccountInfo<'info>, pda: &AccountInfo<'info>, token_program: &AccountInfo<'info>, signer_seeds: &[&[&[u8]]], // number of shares to mint amount: u64, ) -> Result<()>; /// used to burn the actual shares fn burn_shares<'info>( &mut self, // the shares token account from which we are burning funds shares_account: &AccountInfo<'info>, // the mint account of the shares we are burning shares_mint: &mut Box<Account<'info, Mint>>, authority: &AccountInfo<'info>, // the underlying token account for which we are transferring // the redeemed underlying assets to token_program: &AccountInfo<'info>, signer_seeds: &[&[&[u8]]], // amount of shares we are burning shares_to_burn: u64, // any additional signers, additional_signers: Option<Vec<AccountInfo<'info>>>, ) -> Result<()>; /// used to transfer underlying tokens fn transfer_underlying<'info>( &mut self, // account from which the underlying tokens will be sent from underlying_account: &AccountInfo<'info>, // token account which will receive the underlying asset receiver: &AccountInfo<'info>, pda: &AccountInfo<'info>, token_program: &AccountInfo<'info>, signer_seeds: &[&[&[u8]]], // number of shares to mint amount: u64, ) -> Result<()>; /// is used to check whether or not the incoming deposited amount /// will push the vault over the cap. if the deposit cap is reached, /// returns true, otherwise returns false fn deposits_capped(&self, incoming_deposit_amount: u64) -> bool; /// syncs the variable tracked by the vault with the shares supply of a mint fn sync_shares(&mut self, mint: &spl_token::state::Mint); /// returns the amount of underlying backing 1 share fn exchange_rate(&mut self, mint: &spl_token::state::Mint) -> f64; } /// implementation of a holder of tokenized vault shares #[cfg(not(tarpaulin_include))] pub trait TokenizedSharesHolder { /// returns the amount of shares to given in exchange for depositing the specified amount of underlying otkens fn shares_to_give(&self, vault: &impl TokenizedShares, amount: u64) -> u64; /// returns the amount of underlying to redeem in exchange for burning the amount of shares /// returns None if vault is locked for the share holder fn underlying_to_redeem(&self, vault: &impl TokenizedShares, amount: u64) -> Option<u64>; /// used to record the effects of depositing underlying asset into the vault fn record_deposit(&mut self, amount: u64, shares: u64); /// used to record the effect of withdrawing and burning the shares for their /// underlying assets. note you will need to calculate the shares to burn /// and the corresponding balance to remove fn record_withdraw(&mut self, vault: &impl TokenizedShares, amount: u64) -> u64; /// returns the current deposited underlying managed by this account, not considering /// compounding rewards fn deposited_balance(&self) -> u64; /// returns the current number of shares managed by this account fn issued_shares(&self) -> u64; /// returns the total amount of underlying that has been deposited into this account over time fn total_deposited_underlying(&self) -> u64; /// returns the total amount of underlying that has ever been withdrawn from this account over time fn total_withdrawn_underlying(&self) -> u64; /// withdraw shares from the deposit tracking account fn withdraw_shares<'info>( &mut self, deposit_account: &AccountInfo<'info>, hold_account: &AccountInfo<'info>, pda_account: &AccountInfo<'info>, receiving_shares_account: &AccountInfo<'info>, token_program: &AccountInfo<'info>, amount: u64, ) -> Result<()>; }
import styled from "styled-components"; import { mainColors } from "../../constants/colors"; export const Container = styled.nav` background-color: ${mainColors.primary}; color: white; `; export const ListContainer = styled.ul` list-style-type: none; margin: 0; padding: 30px; `; export const ListItem = styled.li` display: inline; margin: 0 15px; `; export const ListAnchor = styled.a` padding: 15px; `;
// // WHTextField.h // whisper // // Created by Bill Mers on 9/7/13. // Copyright (c) 2013 7x7 Labs. All rights reserved. // @interface WHTextField : UITextField @end
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using NuGet.Shared; namespace NuGet.Packaging.Core { /** * It is important that this type remains immutable due to the cloning of package specs **/ public class PackageType : IEquatable<PackageType>, IComparable<PackageType> { public static readonly Version EmptyVersion = new Version(0, 0); public static readonly PackageType Legacy = new PackageType("Legacy", version: EmptyVersion); public static readonly PackageType DotnetCliTool = new PackageType("DotnetCliTool", version: EmptyVersion); public static readonly PackageType Dependency = new PackageType("Dependency", version: EmptyVersion); public static readonly PackageType DotnetTool = new PackageType("DotnetTool", version: EmptyVersion); public static readonly PackageType SymbolsPackage = new PackageType("SymbolsPackage", version: EmptyVersion); public PackageType(string name, Version version) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(Strings.StringCannotBeNullOrEmpty, nameof(name)); } if (version == null) { throw new ArgumentNullException(nameof(version)); } Name = name; Version = version; } public string Name { get; } public Version Version { get; } public override bool Equals(object obj) { return Equals(obj as PackageType); } public static bool operator ==(PackageType a, PackageType b) { if (ReferenceEquals(a, b)) { return true; } if (((object)a == null) || ((object)b == null)) { return false; } return a.Equals(b); } public static bool operator !=(PackageType a, PackageType b) { return !(a == b); } public bool Equals(PackageType other) { if (other == null) { return false; } if (ReferenceEquals(this, other)) { return true; } return Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) && Version == other.Version; } public override int GetHashCode() { var combiner = new HashCodeCombiner(); combiner.AddObject(Name, StringComparer.OrdinalIgnoreCase); combiner.AddObject(Version); return combiner.CombinedHash; } public int CompareTo(PackageType other) { if (other == null) { return 1; } if (ReferenceEquals(this, other)) { return 0; } var res = StringComparer.OrdinalIgnoreCase.Compare(Name, other.Name); if (res != 0) { return res; } return Version.CompareTo(other.Version); } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Linq; public class SplatMapShaderGUI : ShaderGUI { void DrawLayer(MaterialEditor editor, int i, MaterialProperty[] props, string[] keyWords, Workflow workflow, bool hasGloss, bool hasSpec, bool isParallax, bool hasEmis, bool hasDistBlend) { EditorGUIUtility.labelWidth = 0f; var albedoMap = FindProperty ("_Tex" + i, props); var tint = FindProperty("_Tint" + i, props); var normalMap = FindProperty ("_Normal" + i, props); var smoothness = FindProperty("_Glossiness" + i, props); var glossinessMap = FindProperty("_GlossinessTex" + i, props, false); var metallic = FindProperty("_Metallic" + i, props, false); var emissionTex = FindProperty("_Emissive" + i, props); var emissionMult = FindProperty("_EmissiveMult" + i, props); var parallax = FindProperty("_Parallax" + i, props); var texScale = FindProperty("_TexScale" + i, props); var specMap = FindProperty("_SpecGlossMap" + i, props, false); var specColor = FindProperty("_SpecColor" + i, props, false); var distUVScale = FindProperty("_DistUVScale" + i, props, false); editor.TexturePropertySingleLine(new GUIContent("Albedo/Height"), albedoMap); editor.ShaderProperty(tint, "Tint"); editor.TexturePropertySingleLine(new GUIContent("Normal"), normalMap); if (workflow == Workflow.Metallic) { editor.TexturePropertySingleLine(new GUIContent("Metal(R)/Smoothness(A)"), glossinessMap); } else { editor.TexturePropertySingleLine(new GUIContent("Specular(RGB)/Gloss(A)"), specMap); } if (workflow == Workflow.Metallic && !hasGloss) { editor.ShaderProperty(smoothness, "Smoothness"); editor.ShaderProperty(metallic, "Metallic"); } else if (workflow == Workflow.Specular && !hasSpec) { editor.ShaderProperty(smoothness, "Smoothness"); editor.ShaderProperty(specColor, "Specular Color"); } editor.TexturePropertySingleLine(new GUIContent("Emission"), emissionTex); editor.ShaderProperty(emissionMult, "Emissive Multiplier"); editor.ShaderProperty(texScale, "Texture Scale"); if (hasDistBlend) { editor.ShaderProperty(distUVScale, "Distance UV Scale"); } if (isParallax) { editor.ShaderProperty(parallax, "Parallax Height"); } if (i != 1) { editor.ShaderProperty(FindProperty("_Contrast"+i, props), "Interpolation Contrast"); } } enum Workflow { Metallic = 0, Specular } enum FlowChannel { None = 0, One, Two, Three, Four, Five } string[] flowChannelNames = new string[] { "None", "One", "Two", "Three", "Four", "Five" }; public override void OnGUI (MaterialEditor materialEditor, MaterialProperty[] props) { // get the current keywords from the material Material targetMat = materialEditor.target as Material; string[] keyWords = targetMat.shaderKeywords; int layerCount = 1; Workflow workflow = Workflow.Metallic; if (targetMat.shader.name == "VertexPainter/SplatBlend_1Layer") { layerCount = 1; } else if (targetMat.shader.name == "VertexPainter/SplatBlend_2Layer") { layerCount = 2; } else if (targetMat.shader.name == "VertexPainter/SplatBlend_3Layer") { layerCount = 3; } else if (targetMat.shader.name == "VertexPainter/SplatBlend_4Layer") { layerCount = 4; } else if (targetMat.shader.name == "VertexPainter/SplatBlend_5Layer") { layerCount = 5; } else if (targetMat.shader.name == "VertexPainter/SplatBlendSpecular_1Layer") { workflow = Workflow.Specular; layerCount = 1; } else if (targetMat.shader.name == "VertexPainter/SplatBlendSpecular_2Layer") { workflow = Workflow.Specular; layerCount = 2; } else if (targetMat.shader.name == "VertexPainter/SplatBlendSpecular_3Layer") { workflow = Workflow.Specular; layerCount = 3; } else if (targetMat.shader.name == "VertexPainter/SplatBlendSpecular_4Layer") { workflow = Workflow.Specular; layerCount = 4; } else if (targetMat.shader.name == "VertexPainter/SplatBlendSpecular_5Layer") { workflow = Workflow.Specular; layerCount = 5; } FlowChannel fchannel = FlowChannel.None; if (keyWords.Contains("_FLOW1")) fchannel = FlowChannel.One; if (keyWords.Contains("_FLOW2")) fchannel = FlowChannel.Two; if (keyWords.Contains("_FLOW3")) fchannel = FlowChannel.Three; if (keyWords.Contains("_FLOW4")) fchannel = FlowChannel.Four; if (keyWords.Contains("_FLOW5")) fchannel = FlowChannel.Five; bool flowDrift = keyWords.Contains("_FLOWDRIFT"); bool flowRefraction = keyWords.Contains("_FLOWREFRACTION"); bool parallax = keyWords.Contains ("_PARALLAXMAP"); bool hasGloss = (HasTexture(layerCount, targetMat, "_GlossinessTex")); bool hasSpec = (HasTexture(layerCount, targetMat, "_SpecGlossMap")); bool hasEmis = (HasTexture(layerCount, targetMat, "_Emissive")); bool hasDistBlend = keyWords.Contains("_DISTBLEND"); EditorGUI.BeginChangeCheck(); Workflow oldWorkflow = workflow; workflow = (Workflow)EditorGUILayout.EnumPopup("Workflow", workflow); int oldLayerCount = layerCount; layerCount = EditorGUILayout.IntField("Layer Count", layerCount); if (oldLayerCount != layerCount || workflow != oldWorkflow) { if (layerCount < 1) layerCount = 1; if (layerCount > 5) layerCount = 5; if (workflow == Workflow.Metallic) { targetMat.shader = Shader.Find("VertexPainter/SplatBlend_" + layerCount + "Layer"); } else { targetMat.shader = Shader.Find("VertexPainter/SplatBlendSpecular_" + layerCount + "Layer"); } return; } parallax = EditorGUILayout.Toggle ("Parallax Offset", parallax); hasDistBlend = EditorGUILayout.Toggle("UV Scale in distance", hasDistBlend); var distBlendMin = FindProperty("_DistBlendMin", props); var distBlendMax = FindProperty("_DistBlendMax", props); if (hasDistBlend) { materialEditor.ShaderProperty(distBlendMin, "Distance Blend Min"); materialEditor.ShaderProperty(distBlendMax, "Distance Blend Max"); // make sure max is at least min if (distBlendMin.floatValue > distBlendMax.floatValue) { distBlendMax.floatValue = distBlendMin.floatValue; } // make sure max is at least 1 if (distBlendMax.floatValue <= 1) { distBlendMax.floatValue = 1; } } for (int i = 0; i < layerCount; ++i) { DrawLayer(materialEditor, i+1, props, keyWords, workflow, hasGloss, hasSpec, parallax, hasEmis, hasDistBlend); EditorGUILayout.Space(); } EditorGUILayout.Space(); fchannel = (FlowChannel)EditorGUILayout.Popup((int)fchannel, flowChannelNames); if (fchannel != FlowChannel.None) { var flowSpeed = FindProperty("_FlowSpeed", props); var flowIntensity = FindProperty("_FlowIntensity", props); var flowAlpha = FindProperty("_FlowAlpha", props); var flowRefract = FindProperty("_FlowRefraction", props); materialEditor.ShaderProperty(flowSpeed, "Flow Speed"); materialEditor.ShaderProperty(flowIntensity, "Flow Intensity"); materialEditor.ShaderProperty(flowAlpha, "Flow Alpha"); if (layerCount > 1) { flowRefraction = EditorGUILayout.Toggle("Flow Refraction", flowRefraction); if (flowRefraction) { materialEditor.ShaderProperty(flowRefract, "Refraction Amount"); } } flowDrift = EditorGUILayout.Toggle("Flow Drift", flowDrift); } if (EditorGUI.EndChangeCheck()) { var newKeywords = new List<string>(); newKeywords.Add("_LAYERS" + layerCount.ToString()); if (hasDistBlend) { newKeywords.Add("_DISTBLEND"); } if (parallax) { newKeywords.Add("_PARALLAXMAP"); } if (HasTexture(layerCount, targetMat, "_Normal")) { newKeywords.Add("_NORMALMAP"); } if (hasGloss && workflow == Workflow.Metallic) { newKeywords.Add("_METALLICGLOSSMAP"); } if (hasSpec && workflow == Workflow.Specular) { newKeywords.Add("_SPECGLOSSMAP"); } if (hasEmis) { newKeywords.Add("_EMISSION"); } if (fchannel != FlowChannel.None) { newKeywords.Add("_FLOW" + (int)fchannel); } if (flowDrift) { newKeywords.Add("_FLOWDRIFT"); } if (flowRefraction && layerCount > 1) { newKeywords.Add("_FLOWREFRACTION"); } targetMat.shaderKeywords = newKeywords.ToArray (); EditorUtility.SetDirty (targetMat); } } bool HasTexture(int numLayers, Material mat, string key) { for (int i = 0; i < numLayers; ++i) { int index = i+1; string prop = key + index; if (mat.HasProperty(prop) && mat.GetTexture(prop) != null) return true; } return false; } }
#include "rclcpp/rclcpp.hpp" #include "example_interfaces/srv/add_two_ints.hpp" #pragma once #ifndef ADD_TWO_INTS_SERVER_HPP #define ADD_TWO_INTS_SERVER_HPP namespace ISrv = example_interfaces::srv; class AddTwoIntsServerNode : public rclcpp::Node { private: rclcpp::Service<ISrv::AddTwoInts>::SharedPtr server_; void callbackAddTwoInt( const ISrv::AddTwoInts::Request::SharedPtr request, const ISrv::AddTwoInts::Response::SharedPtr response ); public: AddTwoIntsServerNode(); }; #endif
package io.tintoy.ebt.tests import akka.actor.{Actor, ActorSystem} import akka.testkit._ import com.typesafe.config.ConfigFactory import io.tintoy.ebt.{Envelope, HierarchicalEventBus} import org.scalatest.{BeforeAndAfterEach, WordSpecLike, Matchers, BeforeAndAfterAll} import scala.concurrent.duration.DurationInt /** * Tests for [[HierarchicalEventBus]]. */ class HierarchicalEventBusSpec extends TestKit( ActorSystem("HierarchicalEventBusSpec", ConfigFactory.defaultApplication() ) ) with DefaultTimeout with ImplicitSender with WordSpecLike with Matchers with BeforeAndAfterAll with BeforeAndAfterEach { var eventBus: HierarchicalEventBus = null "Hierarchical event bus with 1 subscriber for 1 topic" should { "send events to that subscriber if they are published with that topic" in { within(500.milliseconds) { eventBus.subscribe(self, to = "/topic1") eventBus.publish( Envelope( topic = "/topic1", message = "Test" ) ) expectMsg("Test") eventBus.unsubscribe(self) } } "not send events to that subscriber if they are published with a different topic" in { within(500.milliseconds) { eventBus.subscribe(self, to = "/topic1") eventBus.publish( Envelope( topic = "/topic1/sub-topic", message = "Test" ) ) expectMsg("Test") eventBus.unsubscribe(self) } } "not send events to that subscriber for a different topic" in { within(500.milliseconds) { eventBus.subscribe(self, to = "/topic1") eventBus.publish( Envelope( topic = "/topic2", message = "Test" ) ) expectNoMsg() eventBus.unsubscribe(self) } } } "Hierarchical event bus with 2 subscriber for 2 different topics" should { "send events only to the subscriber whose topic is in or under the one the event was published with" in { within(500.milliseconds) { val topic1Subscriber = TestProbe("topic-1-subscriber") val topic2Subscriber = TestProbe("topic-2-subscriber") eventBus.subscribe(topic1Subscriber.ref, to = "/topic1") eventBus.subscribe(topic2Subscriber.ref, to = "/topic2") eventBus.publish( Envelope( topic = "/topic1", message = "Test" ) ) topic1Subscriber.expectMsg("Test") topic2Subscriber.expectNoMsg(max = 100.milliseconds) eventBus.unsubscribe(topic1Subscriber.ref) eventBus.unsubscribe(topic2Subscriber.ref) } } } /** * Setup before any tests are run. */ override protected def beforeAll(): Unit = super.beforeAll() /** * Tear-down after all tests are run. */ override protected def afterAll(): Unit = { shutdown() super.afterAll() } /** * Setup before each test is run. */ override protected def beforeEach(): Unit = { super.beforeEach() eventBus = new HierarchicalEventBus() } /** * Tear-down after each test is run. */ override protected def afterEach(): Unit = { eventBus = null super.afterEach() } }
// RUN: %ocheck 0 %s extern _Noreturn void abort(void); int g(int a, int b) { if(b) abort(); if(a != 5) abort(); return 72; } dup(int x) { return x + 1; } f(int a, int b) { // bug here - register saving between jumps (?:) return g(a, b ? dup(b) : 0); } main() { #include "../ocheck-init.c" f(5, 0); } /* typedef struct opaque *id; id (*print_and_ret(id x, ...))(id, ...) { printf("%p\n", x); return print_and_ret; } extern id (*_imp(id x))() { return print_and_ret; } typedef char *SEL; id f(id self, SEL _cmd, id arg) { id local1, local2; return ( local1 = (id)self, _imp(local1)( local1, arg ? local2 = arg, _imp(local2)(local2) : (id)0)); } main() { #include "../ocheck-init.c" f(3, "hi", 42); } */
using GalacticOptimJL, GalacticOptimJL.Optim, GalacticOptim, ForwardDiff, Zygote, Random, ModelingToolkit using Test @testset "GalacticOptimJL.jl" begin rosenbrock(x, p) = (p[1] - x[1])^2 + p[2] * (x[2] - x[1]^2)^2 x0 = zeros(2) _p = [1.0, 100.0] l1 = rosenbrock(x0, _p) f = OptimizationFunction(rosenbrock, GalacticOptim.AutoForwardDiff()) prob = OptimizationProblem(f, x0, _p) Random.seed!(1234) sol = solve(prob, SimulatedAnnealing()) @test 10 * sol.minimum < l1 Random.seed!(1234) prob = OptimizationProblem(f, x0, _p, lb=[-1.0, -1.0], ub=[0.8, 0.8]) sol = solve(prob, SAMIN()) @test 10 * sol.minimum < l1 prob = OptimizationProblem(rosenbrock, x0, _p) sol = solve(prob, Optim.NelderMead(;initial_simplex=Optim.AffineSimplexer(;a = 0.025, b = 0.5))) @test 10 * sol.minimum < l1 cons = (x, p) -> [x[1]^2 + x[2]^2] optprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoForwardDiff(); cons=cons) optprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoModelingToolkit(); cons=cons) prob = OptimizationProblem(optprob, x0, _p) sol = solve(prob, Optim.BFGS()) @test 10 * sol.minimum < l1 sol = solve(prob, Optim.Newton()) @test 10 * sol.minimum < l1 sol = solve(prob, Optim.KrylovTrustRegion()) @test 10 * sol.minimum < l1 prob = OptimizationProblem(optprob, x0, _p, lcons=[-Inf], ucons=[Inf]) sol = solve(prob, IPNewton()) @test 10 * sol.minimum < l1 prob = OptimizationProblem(optprob, x0, _p, lcons=[-5.0], ucons=[10.0]) sol = solve(prob, IPNewton()) @test 10 * sol.minimum < l1 prob = OptimizationProblem(optprob, x0, _p, lcons=[-Inf], ucons=[Inf], lb=[-500.0, -500.0], ub=[50.0, 50.0]) sol = solve(prob, IPNewton()) @test sol.minimum < l1 function con2_c(x, p) [x[1]^2 + x[2]^2, x[2] * sin(x[1]) - x[1]] end optprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoForwardDiff(); cons=con2_c) prob = OptimizationProblem(optprob, x0, _p, lcons=[-Inf, -Inf], ucons=[Inf, Inf]) sol = solve(prob, IPNewton()) @test 10 * sol.minimum < l1 cons_circ = (x, p) -> [x[1]^2 + x[2]^2] optprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoForwardDiff(); cons=cons_circ) prob = OptimizationProblem(optprob, x0, _p, lcons=[-Inf], ucons=[0.25^2]) sol = solve(prob, IPNewton()) @test sqrt(cons(sol.u, nothing)[1]) ≈ 0.25 rtol = 1e-6 optprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoZygote()) prob = OptimizationProblem(optprob, x0, _p, lb=[-1.0, -1.0], ub=[0.8, 0.8]) sol = solve(prob, Optim.Fminbox()) @test 10 * sol.minimum < l1 Random.seed!(1234) prob = OptimizationProblem(optprob, x0, _p, lb=[-1.0, -1.0], ub=[0.8, 0.8]) sol = solve(prob, Optim.SAMIN()) @test 10 * sol.minimum < l1 optprob = OptimizationFunction((x, p) -> -rosenbrock(x, p), GalacticOptim.AutoZygote()) prob = OptimizationProblem(optprob, x0, _p; sense=GalacticOptim.MaxSense) sol = solve(prob, NelderMead()) @test 10 * sol.minimum < l1 sol = solve(prob, BFGS()) @test 10 * sol.minimum < l1 function g!(G, x) G[1] = -2.0 * (1.0 - x[1]) - 400.0 * (x[2] - x[1]^2) * x[1] G[2] = 200.0 * (x[2] - x[1]^2) end optprob = OptimizationFunction((x, p) -> -rosenbrock(x, p), GalacticOptim.AutoZygote(), grad=g!) prob = OptimizationProblem(optprob, x0, _p; sense=GalacticOptim.MaxSense) sol = solve(prob, BFGS()) @test 10 * sol.minimum < l1 optprob = OptimizationFunction(rosenbrock, GalacticOptim.AutoModelingToolkit()) prob = OptimizationProblem(optprob, x0, _p) sol = solve(prob, Optim.BFGS()) @test 10 * sol.minimum < l1 end
/*--------------------------------------------------------------------------------------------- * Copyright (c) 2008-2017 doLittle. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ using doLittle.Assemblies; using doLittle.Assemblies.Configuration; using doLittle.Assemblies.Rules; namespace doLittle.Read.DocumentDB { /// <summary> /// Reperesents an <see cref="ICanSpecifyAssemblies">assembly specifier</see> for client aspects /// </summary> public class AssemblySpecifier : ICanSpecifyAssemblies { #pragma warning disable 1591 // Xml Comments public void Specify(IAssemblyRuleBuilder builder) { builder.ExcludeAssembliesStartingWith( "Microsoft.Azure.DocumentDB.Core" ); } #pragma warning disable 1591 // Xml Comments } }
 namespace Acklann.Mockaroo { /// <summary> /// Represents a Mockaroo data-type. /// </summary> public enum DataType { /// <summary> /// Animal Common Name /// </summary> AnimalCommonName, /// <summary> /// Animal Scientific Name /// </summary> AnimalScientificName, /// <summary> /// App Bundle ID /// </summary> AppBundleID, /// <summary> /// App Name /// </summary> AppName, /// <summary> /// App Version /// </summary> AppVersion, /// <summary> /// Avatar /// </summary> Avatar, /// <summary> /// Base64 Image URL /// </summary> Base64ImageURL, /// <summary> /// Binomial Distribution /// </summary> BinomialDistribution, /// <summary> /// Bitcoin Address /// </summary> BitcoinAddress, /// <summary> /// Blank /// </summary> Blank, /// <summary> /// Boolean /// </summary> Boolean, /// <summary> /// Buzzword /// </summary> Buzzword, /// <summary> /// Car Make /// </summary> CarMake, /// <summary> /// Car Model /// </summary> CarModel, /// <summary> /// Car Model Year /// </summary> CarModelYear, /// <summary> /// Car VIN /// </summary> CarVIN, /// <summary> /// Catch Phrase /// </summary> CatchPhrase, /// <summary> /// Character Sequence /// </summary> CharacterSequence, /// <summary> /// City /// </summary> City, /// <summary> /// Color /// </summary> Color, /// <summary> /// Company Name /// </summary> CompanyName, /// <summary> /// Country /// </summary> Country, /// <summary> /// Country Code /// </summary> CountryCode, /// <summary> /// Credit Card # /// </summary> CreditCardNumber, /// <summary> /// Credit Card Type /// </summary> CreditCardType, /// <summary> /// Currency /// </summary> Currency, /// <summary> /// Currency Code /// </summary> CurrencyCode, /// <summary> /// Custom List /// </summary> CustomList, /// <summary> /// Dataset Column /// </summary> DatasetColumn, /// <summary> /// Date /// </summary> Date, /// <summary> /// Department (Corporate) /// </summary> DepartmentCorporate, /// <summary> /// Department (Retail) /// </summary> DepartmentRetail, /// <summary> /// Digit Sequence /// </summary> DigitSequence, /// <summary> /// Domain Name /// </summary> DomainName, /// <summary> /// Drug Company /// </summary> DrugCompany, /// <summary> /// Drug Name (Brand) /// </summary> DrugNameBrand, /// <summary> /// Drug Name (Generic) /// </summary> DrugNameGeneric, /// <summary> /// Dummy Image URL /// </summary> DummyImageURL, /// <summary> /// DUNS Number /// </summary> DUNSNumber, /// <summary> /// EIN /// </summary> EIN, /// <summary> /// Email Address /// </summary> EmailAddress, /// <summary> /// Encrypt /// </summary> Encrypt, /// <summary> /// Exponential Distribution /// </summary> ExponentialDistribution, /// <summary> /// Fake Company Name /// </summary> FakeCompanyName, /// <summary> /// Family Name (Chinese) /// </summary> FamilyNameChinese, /// <summary> /// FDA NDC Code /// </summary> FDANDCCode, /// <summary> /// File Name /// </summary> FileName, /// <summary> /// First Name /// </summary> FirstName, /// <summary> /// First Name (European) /// </summary> FirstNameEuropean, /// <summary> /// First Name (Female) /// </summary> FirstNameFemale, /// <summary> /// First Name (Male) /// </summary> FirstNameMale, /// <summary> /// Formula /// </summary> Formula, /// <summary> /// Frequency /// </summary> Frequency, /// <summary> /// Full Name /// </summary> FullName, /// <summary> /// Gender /// </summary> Gender, /// <summary> /// Gender (abbrev) /// </summary> GenderAbbreviated, /// <summary> /// Geometric Distribution /// </summary> GeometricDistribution, /// <summary> /// Given Name (Chinese) /// </summary> GivenNameChinese, /// <summary> /// GUID /// </summary> GUID, /// <summary> /// Hex Color /// </summary> HexColor, /// <summary> /// IBAN /// </summary> IBAN, /// <summary> /// ICD10 Diagnosis Code /// </summary> ICD10DiagnosisCode, /// <summary> /// ICD10 Dx Desc (Long) /// </summary> ICD10DxDescLong, /// <summary> /// ICD10 Dx Desc (Short) /// </summary> ICD10DxDescShort, /// <summary> /// ICD10 Proc Desc (Long) /// </summary> ICD10ProcDescLong, /// <summary> /// ICD10 Proc Desc (Short) /// </summary> ICD10ProcDescShort, /// <summary> /// ICD10 Procedure Code /// </summary> ICD10ProcedureCode, /// <summary> /// ICD9 Diagnosis Code /// </summary> ICD9DiagnosisCode, /// <summary> /// ICD9 Dx Desc (Long) /// </summary> ICD9DxDescLong, /// <summary> /// ICD9 Dx Desc (Short) /// </summary> ICD9DxDescShort, /// <summary> /// ICD9 Proc Desc (Long) /// </summary> ICD9ProcDescLong, /// <summary> /// ICD9 Proc Desc (Short) /// </summary> ICD9ProcDescShort, /// <summary> /// ICD9 Procedure Code /// </summary> ICD9ProcedureCode, /// <summary> /// IP Address v4 /// </summary> IPAddressV4, /// <summary> /// IP Address v4 CIDR /// </summary> IPAddressV4CIDR, /// <summary> /// IP Address v6 /// </summary> IPAddressV6, /// <summary> /// IP Address v6 CIDR /// </summary> IPAddressV6CIDR, /// <summary> /// ISBN /// </summary> ISBN, /// <summary> /// Job Title /// </summary> JobTitle, /// <summary> /// JSON Array /// </summary> JSONArray, /// <summary> /// Language /// </summary> Language, /// <summary> /// Last Name /// </summary> LastName, /// <summary> /// Latitude /// </summary> Latitude, /// <summary> /// LinkedIn Skill /// </summary> LinkedInSkill, /// <summary> /// Longitude /// </summary> Longitude, /// <summary> /// MAC Address /// </summary> MACAddress, /// <summary> /// MD5 /// </summary> MD5, /// <summary> /// MIME Type /// </summary> MIMEType, /// <summary> /// Money /// </summary> Money, /// <summary> /// MongoDB ObjectID /// </summary> MongoDBObjectID, /// <summary> /// Movie Genres /// </summary> MovieGenres, /// <summary> /// Movie Title /// </summary> MovieTitle, /// <summary> /// Nato Phonetic /// </summary> NatoPhonetic, /// <summary> /// Naughty String /// </summary> NaughtyString, /// <summary> /// NHS Number /// </summary> NHSNumber, /// <summary> /// Normal Distribution /// </summary> NormalDistribution, /// <summary> /// Number /// </summary> Number, /// <summary> /// Paragraphs /// </summary> Paragraphs, /// <summary> /// Password /// </summary> Password, /// <summary> /// Phone /// </summary> Phone, /// <summary> /// Plant Common Name /// </summary> PlantCommonName, /// <summary> /// Plant Family /// </summary> PlantFamily, /// <summary> /// Plant Scientific Name /// </summary> PlantScientificName, /// <summary> /// Poisson Distribution /// </summary> PoissonDistribution, /// <summary> /// Postal Code /// </summary> PostalCode, /// <summary> /// Product (Grocery) /// </summary> ProductGrocery, /// <summary> /// Race /// </summary> Race, /// <summary> /// Regular Expression /// </summary> RegularExpression, /// <summary> /// Repeating Element /// </summary> RepeatingElement, /// <summary> /// Row Number /// </summary> RowNumber, /// <summary> /// Scenario /// </summary> Scenario, /// <summary> /// Sentences /// </summary> Sentences, /// <summary> /// Sequence /// </summary> Sequence, /// <summary> /// SHA1 /// </summary> SHA1, /// <summary> /// SHA256 /// </summary> SHA256, /// <summary> /// Shirt Size /// </summary> ShirtSize, /// <summary> /// Short Hex Color /// </summary> ShortHexColor, /// <summary> /// Slogan /// </summary> Slogan, /// <summary> /// SQL Expression /// </summary> SQLExpression, /// <summary> /// SSN /// </summary> SSN, /// <summary> /// State /// </summary> State, /// <summary> /// State (abbrev) /// </summary> StateAbbreviated, /// <summary> /// Stock Industry /// </summary> StockIndustry, /// <summary> /// Stock Market /// </summary> StockMarket, /// <summary> /// Stock Market Cap /// </summary> StockMarketCap, /// <summary> /// Stock Name /// </summary> StockName, /// <summary> /// Stock Sector /// </summary> StockSector, /// <summary> /// Stock Symbol /// </summary> StockSymbol, /// <summary> /// Street Address /// </summary> StreetAddress, /// <summary> /// Street Name /// </summary> StreetName, /// <summary> /// Street Number /// </summary> StreetNumber, /// <summary> /// Street Suffix /// </summary> StreetSuffix, /// <summary> /// Suffix /// </summary> Suffix, /// <summary> /// Template /// </summary> Template, /// <summary> /// Time /// </summary> Time, /// <summary> /// Time Zone /// </summary> TimeZone, /// <summary> /// Title /// </summary> Title, /// <summary> /// Top Level Domain /// </summary> TopLevelDomain, /// <summary> /// University /// </summary> University, /// <summary> /// URL /// </summary> URL, /// <summary> /// User Agent /// </summary> UserAgent, /// <summary> /// Username /// </summary> UserName, /// <summary> /// Words /// </summary> Words, } }
import type { QueryType, Context } from 'gecs'; import type { ContextType } from '../../circles'; import { intersection } from '../utils'; export function IntersectionSystem(ctx: Context<ContextType>) { let index = 1; const entities = Array.from(ctx.$.circle.query.circles); for (const entity of entities) { entity.$.intersect.points = []; for (let i = index; i < entities.length; i++) { const intersect = intersection(entity.$.circle, entities[i].$.circle); if (intersect) { entity.$.intersect.points.push(intersect); } } index++; } }
# frozen_string_literal: true module FactoryTrace module MonkeyPatches module DefinitionProxy def factory(name, options = {}, &block) @child_factories << [name, Helpers::Caller.location, options, block] end def trait(name, &block) @definition.define_trait(FactoryBot::Trait.new(name, Helpers::Caller.location, &block)) end end end end
package io.gitlab.arturbosch.detekt.api.internal import io.gitlab.arturbosch.detekt.api.Notification data class SimpleNotification(override val message: String) : Notification
<?php /** * Project: PHP Light Framework * * @author Michal Szewczyk <ms@msworks.pl> * @copyright Michal Szewczyk * @license MIT */ declare(strict_types=1); namespace MS\LightFramework\Validator\Specific; /** * Class Alnum * * @package MS\LightFramework\Validator\Specific */ final class Alnum extends AbstractSpecific { const VALIDATOR_ERROR_ALNUM_NOT_VALID = 101; const VALIDATOR_ERROR_ALNUM_SPACES_NOT_VALID = 102; const VALIDATOR_ERROR_ALNUM_WHITESPACES_NOT_VALID = 103; const VALIDATOR_ERROR_ALNUM_SPACES_WHITESPACES_NOT_VALID = 104; protected $defaultOptions = [ 'allow-spaces' => false, 'allow-whitespaces' => false, 'utf-8' => true, ]; /** * Alnum constructor. * * @param array $options */ public function __construct(array $options = []) { $this->setOptions($options); } /** * Checks whether string is valid alnum string * * @return bool */ private function validateAlnum(): bool { $charClass = '[:alnum:]'; if ($this->options['allow-spaces'] === true) { $charClass .= '[:space:]'; } if ($this->options['allow-whitespaces'] === true) { $charClass .= '[:blank:]'; } $modifier = ''; if ($this->options['utf-8'] === true) { $modifier = 'u'; } $isValid = \preg_match('/^['.$charClass.']+$/'.$modifier, $this->value) ? true : false; if (!$isValid) { $this->setError(self::VALIDATOR_ERROR_ALNUM_NOT_VALID); if ($this->options['allow-whitespaces'] === true && $this->options['allow-spaces'] === true) { $this->setError(self::VALIDATOR_ERROR_ALNUM_SPACES_WHITESPACES_NOT_VALID); } elseif ($this->options['allow-whitespaces'] === true) { $this->setError(self::VALIDATOR_ERROR_ALNUM_WHITESPACES_NOT_VALID); } elseif ($this->options['allow-spaces'] === true) { $this->setError(self::VALIDATOR_ERROR_ALNUM_SPACES_NOT_VALID); } } return $isValid; } /** * Validates value * * @param null $value * @param array $options * @return bool */ public function isValid($value = null, array $options = []): bool { if (\count($options) > 0) { $this->setOptions($options); } $this->setValue($value); $this->errors = []; return $this->validateAlnum(); } }
package com.example.kotlin.network import com.example.kotlin.model.LoginResponse import com.example.kotlin.model.RegisterResponse import com.example.kotlin.model.TokenResponse import com.example.kotlin.util.Constants import okhttp3.ResponseBody import retrofit2.http.Body import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST /**Interface for user authentications*/ interface AuthHttpRequest : BaseApi { @POST(Endpoints.login) suspend fun login(@Body body: HashMap<String, String>): LoginResponse @POST(Endpoints.registration) suspend fun register(@Body body: HashMap<String, String>): RegisterResponse } interface TokenRefreshApi : BaseApi { @FormUrlEncoded @POST("auth/refresh-token/") suspend fun refreshAccessToken( @Field("refresh_token") refreshToken: String? ): TokenResponse } /**Interface for user related activities*/ interface UserApi : BaseApi { @POST("user") suspend fun loginUser(): LoginResponse @POST("/auth/registration/") suspend fun registerUser(): RegisterResponse } /**Interface to handle logout*/ interface BaseApi { @POST("auth/login/") suspend fun logout(): ResponseBody }
namespace Ridics.Authentication.Service.Configuration { // Maybe find better (more dynamically configurable) solution for password requirements public class PasswordRequirements { // When updating these values, it is also required to update password requirements specified on client app public const int MinLength = 8; public const bool RequireDigit = true; public const bool RequireLowercase = true; public const bool RequireUppercase = true; public const bool RequireNonAlphanumeric = false; public const string ValidationRegexOfViewModel = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}$"; public const string ErrorOfUserWithPasswordViewModel = "pswd-requirement"; public const string ErrorOfResetPasswordViewModel = "pswd-requirement"; } }
# frozen_string_literal: true # Copyright 2019 Google LLC # # 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 # # https://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. require "test_helper" require "google/showcase/v1beta1/echo" require "grpc" class PagedExpandTest < ShowcaseTest def setup @client = new_echo_client end def test_paged_expand request_content = "The quick brown fox jumps over the lazy dog" response_enum = @client.paged_expand content: request_content assert_kind_of Gapic::PagedEnumerable, response_enum responses_content_array = response_enum.to_a.map(&:content) assert_equal request_content, responses_content_array.join(" ") end def test_page_size request_content = "The quick brown fox jumps over the lazy dog" response_enum = @client.paged_expand content: request_content, page_size: 2 assert_kind_of Gapic::PagedEnumerable, response_enum assert_kind_of Google::Showcase::V1beta1::PagedExpandResponse, response_enum.page.response assert_equal ["The", "quick"], response_enum.page.response.responses.map(&:content) response_pages = response_enum.each_page.to_a responses_content_array = response_pages.map { |page| page.map(&:content) } assert_equal request_content, responses_content_array.join(" ") assert_instance_of GRPC::ActiveCall::Operation, response_pages.first.operation assert_instance_of GRPC::ActiveCall::Operation, response_pages.last.operation refute_equal response_pages.first.operation, response_pages.last.operation end def test_page_expand_with_block_and_metadata request_content = "The quick brown fox jumps over the lazy dog".split(" ").reverse.join(" ") options = Gapic::CallOptions.new metadata: { 'showcase-trailer': ["one", "two", "zhree"], garbage: ["baz"] } @client.paged_expand({ content: request_content, page_size: 2 }, options) do |response_enum, operation| assert_kind_of Gapic::PagedEnumerable, response_enum assert_equal ["dog", "lazy"], response_enum.page.response.responses.map(&:content) assert_instance_of GRPC::ActiveCall::Operation, response_enum.page.operation assert_equal operation, response_enum.page.operation response_pages = response_enum.each_page.to_a responses_content_array = response_pages.map { |page| page.map(&:content) } assert_equal request_content, responses_content_array.join(" ") assert_instance_of GRPC::ActiveCall::Operation, operation assert_instance_of GRPC::ActiveCall::Operation, response_pages.first.operation assert_instance_of GRPC::ActiveCall::Operation, response_pages.last.operation assert_equal operation, response_pages.first.operation refute_equal operation, response_pages.last.operation assert_equal( { 'showcase-trailer' => ["one", "two", "zhree"] }, operation.trailing_metadata ) end end end
import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core'; import { Subscription } from 'rxjs'; import { MytipService } from 'projects/sys/src-web/app/service/mytip.service'; import { I18nService } from 'projects/sys/src-web/app/service/i18n.service'; import { AxiosService, HttpService } from '../../../service'; import { GetTreeService } from '../service/get-tree.service'; import { MessageModalService } from '../../../service/message-modal.service'; import { LinkageManageService } from './service/linkage-manage.service'; import { LinkageTaskInfo } from './domain'; @Component({ selector: 'app-linkage-manage', templateUrl: './linkage-manage.component.html', styleUrls: ['./linkage-manage.component.scss'] }) export class LinkageManageComponent implements OnInit, OnDestroy { @Output() operateTask = new EventEmitter(); @Output() selectTask = new EventEmitter(); i18n: any; public status = 'abnormal'; public projerctName: any[]; public taskList: LinkageTaskInfo[] = []; public createLinkageTask: Subscription; public createTaskId: number; updateTaskListInterval: NodeJS.Timeout; constructor( public Axios: AxiosService, public http: HttpService, public timessage: MessageModalService, public getTreeService: GetTreeService, public mytip: MytipService, public i18nService: I18nService, private linkServe: LinkageManageService ) { this.i18n = this.i18nService.I18n(); } ngOnInit(): void { this.getProjerctName(); this.createLinkageTask = this.getTreeService.createLinkageTask.subscribe((val) => { if (val.status === 'success') { this.getProjerctName(); this.createTaskId = val.taskId; } }); if (!this.updateTaskListInterval) { this.updateTaskListInterval = setInterval(() => { this.getProjerctName(); }, 5000); } } ngOnDestroy() { this.createLinkageTask.unsubscribe(); clearInterval(this.updateTaskListInterval); } // 获取工程名 public async getProjerctName() { const resp = await this.Axios.axios.get( `/projects/?auto-flag=on&analysis-type=task_contrast`, { headers: { showLoading: false } } ); this.projerctName = (resp.data.projects ?? []).map((item: { projectName: any; }) => item.projectName); if (this.projerctName.length < 1) { return; } const projectList = await this.linkServe.pullLinkageProjectData(this.projerctName); const taskList = this.linkServe.transLinkageTaskList(projectList); // 任务列表按时逆序排序 this.taskList = taskList.sort((a, b) => { return b.createTime.getTime() - a.createTime.getTime(); }); this.taskList.forEach(task => { if (task.id === this.createTaskId) { this.getTreeService.linkageTaskInfo.next(task.taskInfo); } }); } // 新建任务 public addLinkageTask(): void { this.operateTask.emit({ type: 'addLinkage', task: 'linkagetask', scenes: '', }); } // 删除任务 public onTaskDelete(item: LinkageTaskInfo) { this.timessage.open({ type: 'warn', modalClass: 'project-del', title: this.i18n.common_term_delete_title_analysis, content: this.i18n.common_term_delete_content_analysis, okButton: { primary: false, autofocus: false, }, cancelButton: { primary: true, autofocus: true, }, close: () => { this.Axios.axios.delete(`/tasks/${item.id}/`).then((res: any) => { this.mytip.alertInfo({ type: 'success', content: this.i18n.tip_msg.delete_ok, time: 3500, }); this.getProjerctName(); this.taskList = this.taskList.filter(task => item.id !== task.id); this.operateTask.emit({ type: 'deleteTask', task: 'linkagetask', payload: item.id }); }); }, }); } // 打开任务详情页 public onTaskDetailsOpen(item: LinkageTaskInfo) { this.selectTask.emit(item.taskInfo); } trackByFn(index: number, task: LinkageTaskInfo) { return task.id; } }
# openocd -f ~/Documents/dev/STM32_dev/openocd-0.10.0/tcl/board/st_nucleo_f4.cfg openocd -f semihosting.cfg
#include "stralloc.h" unsigned int stralloc_copy(stralloc *to, const stralloc *from) { return stralloc_copyb(to, from->len, from->s); }
using System.Collections.Generic; namespace Nohwnd.Meteo.Core { public interface IWeatherService { Weather GetWeatherInCity(string city); IReadOnlyCollection<Weather> GetWeatherEverywhere(); } }
## 2015年1月26日4点 # 梦 梦里 我去你的学校找你 我们见了面 却跟未见面一样 我坐在教室里听一堂数学课 似乎我很喜欢这场面 两三个学生 意外地制造着混乱 课堂上 始终没有看到你 于是我醒了 于是我笑了 ## 4 o 'clock on January 26, 2015 In the dream I went to your school and looked for you We met but just like I haven't seen you I sat in the classroom and listen to a math class Its seems I like this scene Two or three students accidentally created a mess I didn't see you in the classroom So I woke up So I laughed
package io.realm.conference.data.entity import io.realm.RealmModel import io.realm.RealmObject import io.realm.annotations.Ignore import io.realm.annotations.RealmClass import io.realm.annotations.Required import io.realm.conference.util.format import java.util.* @RealmClass open class EventData : RealmModel { var title = "" var subtitle = "" var organizer = "" var timeZone = "" var _mainColor = "" var logoUrl: String? = "" fun displayTimeZone() : TimeZone { val eventTimezoneString = this.timeZone return TimeZone.getTimeZone(eventTimezoneString) ?: TimeZone.getDefault() } }
using System; using System.ComponentModel.DataAnnotations; using FDEV.Rules.Demo.Core.Utility; namespace FDEV.Rules.Demo.Domain.Common { /// <summary> /// Interface with the properties needed to setup persistence. /// Note that some values have default implementation on the interface. /// </summary> public interface IEntity { /// <summary> /// Get the unique Id for the Entity. /// </summary> /// <remarks> NOTE: Set in Entity class with a incrementing Guid method. </remarks> [Key] Guid Uid => GuidUtility.NewSequentialGuid(); /// <summary> /// Get the name of the entity. /// </summary> string Name { get; set; } /// <summary> /// DateTime of creation. /// </summary> /// <remarks> NOTE: Set by intersecting on context changes. </remarks> DateTime AddedAt { get; set; } /// <summary> /// DateTime of creation. /// </summary> /// <remarks> NOTE: Set by intersecting on context changes. </remarks> DateTime LastModifiedAt { get; set; } /// <summary> /// Version of the instance (ie. how many times changed in Db). /// </summary> /// <remarks> NOTE: Set by intersecting on context changes. </remarks> int Version { get; set; } #region Default Implementations /// <summary> /// Get if the Entity is persisted to database /// </summary> public bool IsPersisted => !IsTransient(this); private static bool IsTransient(IEntity obj) => obj != null && Equals(obj.Uid, default); /// <summary> /// Set to suppress PropertyChanged events. /// </summary> bool SuppressPropertyChanged => false; /// <summary> /// Set to suppress CollectionChanged events. /// </summary> bool SuppressCollectionChanged => false; #endregion Default Implementations } }
'use strict'; const customer = require('./customer'); const detail = require('./detail'); const product = require('./product'); module.exports = { customer, detail, product };
# this will require all my files, bundle them up and send them to the bin so they can communicate require_relative "./cats_cli/version" #this will load my gemfile, otherwise it will not know about my gems require 'bundler' Bundler.require require_relative "./cats_cli/cli" require_relative "./cats_cli/api" require_relative "./cats_cli/cat"
using System.Collections.Generic; using VMS.TPS.Common.Model.API; namespace DVHEvaluator_Main { /// <summary> /// Class to hold the DVH Evaluator results for a specific plan. /// </summary> public class PlanResult { // Properties public Patient Patient { get; set; } public PlanningItem PlanningItem { get; set; } public StructureSet StructureSet { get; set; } public Dictionary<string, Structure> StructureSetDict { get; set; } public string CourseName { get; set; } public string PlanName { get; set; } public string PlanType { get; set; } public List<StructureObjectiveResult> StructureObjectiveResults = new List<StructureObjectiveResult>(); // Create and evaluate plan-specific StructureObjectiveResults list public void ComputeResults(List<StructureObjective> objectives) { foreach (StructureObjective objective in objectives) { StructureObjectiveResult planObjective = new StructureObjectiveResult { Objective = objective, Plan = PlanningItem }; planObjective.EvaluateObjective(StructureSetDict); StructureObjectiveResults.Add(planObjective); } } } }
<?php namespace App\Http\Controllers; use App\Models\Animal; use Illuminate\Http\Request; use Carbon\Carbon; use Illuminate\Support\Arr; class AnimalController extends Controller { public function index() { $animales=Animal::all(); //return view("animales.index",["animales"=>$animales]); return view("animales.index",compact("animales")); } public function create() { return view("animales.create"); } public function show(Animal $animal) { return view("animales.show",compact("animal")); } public function edit(Animal $animal) { return view("animales.edit",compact("animal")); } public function store(Request $request){ $datos=$request->all(); $datos['imagen']=$request->imagen->store('','animales'); $nuevoAnimal=Animal::create($datos); return view("animales.show",['animal'=>$nuevoAnimal]); } public function update(Request $request,Animal $animal){ $animal->especie=$request->especie; $animal->peso=$request->peso; $animal->altura=$request->altura; $animal->fechaNac=$request->fechaNac; $animal->alimentacion=$request->alimentacion; $animal->descripcion=$request->descripcion; if(!empty($request->imagen) && $request->imagen->isValid()){ Storage::disk('animales')->delete($animal->imagen); $animal->imagen= $request->imagen->store('','animales'); } $animal->save(); return view("animales.show",['animal'=>$animal]); } }
#!/bin/bash # ACPC agent launching script. # This script is used to play game of poker with this agent through ACPC poker infrastructure. # # This general random agent launching script. It's 1st argument is full path to # random agent script for specific game. SCRIPT_DIR="$( cd "$(dirname "$1")" ; pwd -P )" SCRIPT_NAME="$(basename $1)" GAME_NAME="$(sed 's/agent_random.\(.*\).sh/\1/' <<< ${SCRIPT_NAME})" # Following file is to be found in acpc-python-client directory AGENT_FILE="../random_agent.py" if [ ! -f ${AGENT_FILE} ]; then AGENT_FILE="./random_agent.py" fi python ${AGENT_FILE} \ "${SCRIPT_DIR}/../../games/${GAME_NAME}.game" \ $2 $3
package org.mightyfrog.android.twitterapponlyauthsample.data.search import com.google.gson.annotations.SerializedName data class Metadata(@SerializedName("iso_language_code") var isoLanguageCode: String?, @SerializedName("result_type") var resultType: String?)
package io.burkard.cdk.services.iotwireless @SuppressWarnings(Array("org.wartremover.warts.DefaultArguments", "org.wartremover.warts.Null", "DisableSyntax.null")) object OtaaV11Property { def apply( appKey: String, nwkKey: String, joinEui: String ): software.amazon.awscdk.services.iotwireless.CfnWirelessDevice.OtaaV11Property = (new software.amazon.awscdk.services.iotwireless.CfnWirelessDevice.OtaaV11Property.Builder) .appKey(appKey) .nwkKey(nwkKey) .joinEui(joinEui) .build() }
import { Vue } from '../vue'; import { NAME_CARD } from '../constants/components'; import { PROP_TYPE_STRING } from '../constants/props'; import { makeProp, makePropsConfigurable } from '../utils/props'; // --- Props --- export var props = makePropsConfigurable({ bgVariant: makeProp(PROP_TYPE_STRING), borderVariant: makeProp(PROP_TYPE_STRING), tag: makeProp(PROP_TYPE_STRING, 'div'), textVariant: makeProp(PROP_TYPE_STRING) }, NAME_CARD); // --- Mixin --- // @vue/component export var cardMixin = Vue.extend({ props: props });
// Original bug: KT-25315 interface Publisher { fun getMessage(): String } inline class DefaultPublisher(private val messageToPublish: String) : Publisher { override fun getMessage() = messageToPublish } class SomethingThatPublishes : Publisher by DefaultPublisher("Hello")
# ms_datasheet mass spec injection datasheet plotting tool required libraries: * Gooey * Numpy * Pandas * Matplotlib * Comtypes * pyextractMS (jhdavislab) * MSFileReader from thermo
package com.eye.eye.ui.notification.push import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import androidx.lifecycle.liveData import com.eye.eye.logic.MainPageRepository import com.eye.eye.logic.model.PushMessage import com.eye.eye.logic.network.api.MainPageService class PushViewModel(private val repository: MainPageRepository):ViewModel() { var dataList = ArrayList<PushMessage.Message>() private var requestPragmaLiveData = MutableLiveData<String>() var nextPageUrl:String ?= null val dataListLiveData = Transformations.switchMap(requestPragmaLiveData){ url -> liveData { val result = try { val response = repository.refreshPushMessage(url) Result.success(response) } catch (e: Exception) { Result.failure<PushMessage>(e) } emit(result) } } fun onRefresh(){ requestPragmaLiveData.value = MainPageService.PUSHMESSAGE_URL } fun onLoadMore(){ requestPragmaLiveData.value = nextPageUrl ?: "" } }
/* * Copyright 2014 Google Inc. * * 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 org.gwtproject.resources.rg.gss; import com.google.common.base.Objects; import com.google.common.css.compiler.ast.*; import com.google.common.css.compiler.passes.BiDiFlipper; import java.util.List; /** Compiler pass that BiDi flips all the flippable nodes and records if nodes have been flipped. */ public class RecordingBidiFlipper extends DefaultTreeVisitor implements CssCompilerPass { /** This {@link MutatingVisitController} will record if an effective mutation is done. */ private static class RecordingMutatingVisitController implements MutatingVisitController { private MutatingVisitController delegate; private CssDeclarationNode visitingDeclarationNode; private boolean hasMutation; private RecordingMutatingVisitController(MutatingVisitController delegate) { this.delegate = delegate; } @Override public void removeCurrentNode() { delegate.removeCurrentNode(); } @Override public <T extends CssNode> void replaceCurrentBlockChildWith( List<T> replacementNodes, boolean visitTheReplacementNodes) { // In our case, the list of replacement node should contain only one CssDeclarationNode if (!hasMutation && visitingDeclarationNode != null && replacementNodes.size() == 1 && replacementNodes.get(0) instanceof CssDeclarationNode) { CssDeclarationNode newDeclarationNode = (CssDeclarationNode) replacementNodes.get(0); hasMutation |= isNotEqual(visitingDeclarationNode, newDeclarationNode); } delegate.replaceCurrentBlockChildWith(replacementNodes, visitTheReplacementNodes); } public void setVisitingDeclarationNode(CssDeclarationNode visitingDeclarationNode) { this.visitingDeclarationNode = visitingDeclarationNode; } @Override public void startVisit(CssTreeVisitor visitor) { delegate.startVisit(visitor); } @Override public void stopVisit() { delegate.stopVisit(); } private boolean compositeValueEqual(CssCompositeValueNode first, CssCompositeValueNode second) { return valueNodeListEqual(first.getValues(), second.getValues()); } private boolean functionNodeEqual(CssFunctionNode first, CssFunctionNode second) { return valueNodeListEqual( first.getArguments().getChildren(), second.getArguments().getChildren()); } private boolean isNotEqual(CssDeclarationNode first, CssDeclarationNode second) { return !propertyNameEqual(first.getPropertyName(), second.getPropertyName()) || !propertyValuesEqual(first.getPropertyValue(), second.getPropertyValue()); } private boolean numericNodeEqual(CssNumericNode first, CssNumericNode second) { return Objects.equal(first.getNumericPart(), second.getNumericPart()) && Objects.equal(first.getUnit(), second.getUnit()); } private boolean propertyNameEqual(CssPropertyNode first, CssPropertyNode second) { return Objects.equal(first.getPropertyName(), second.getPropertyName()); } private boolean propertyValuesEqual(CssPropertyValueNode first, CssPropertyValueNode second) { return valueNodeListEqual(first.getChildren(), second.getChildren()); } private boolean valueEqual(CssValueNode first, CssValueNode second) { if (first.getClass() != second.getClass()) { return false; } if (first instanceof CssCompositeValueNode) { return compositeValueEqual((CssCompositeValueNode) first, (CssCompositeValueNode) second); } else if (first instanceof CssFunctionNode) { return functionNodeEqual((CssFunctionNode) first, (CssFunctionNode) second); } else if (first instanceof CssNumericNode) { return numericNodeEqual((CssNumericNode) first, (CssNumericNode) second); } else { return Objects.equal(first.getValue(), second.getValue()); } } private boolean valueNodeListEqual( List<CssValueNode> firstValues, List<CssValueNode> secondValues) { if (firstValues.size() != secondValues.size()) { return false; } for (int i = 0; i < firstValues.size(); i++) { CssValueNode firstNode = firstValues.get(i); CssValueNode secondNode = secondValues.get(i); if (!valueEqual(firstNode, secondNode)) { return false; } } return true; } } private BiDiFlipper delegate; private RecordingMutatingVisitController mutatingVisitController; public RecordingBidiFlipper( MutatingVisitController visitController, boolean swapLtrRtlInUrl, boolean swapLeftRightInUrl, boolean shouldFlipConstantReferences) { this.mutatingVisitController = new RecordingMutatingVisitController(visitController); this.delegate = new BiDiFlipper( mutatingVisitController, swapLtrRtlInUrl, swapLeftRightInUrl, shouldFlipConstantReferences); } @Override public boolean enterDeclaration(CssDeclarationNode declaration) { mutatingVisitController.setVisitingDeclarationNode(declaration); return delegate.enterDeclaration(declaration); } /** return true if at least one node was flipped, false otherwise. */ public boolean nodeFlipped() { return mutatingVisitController.hasMutation; } @Override public void runPass() { mutatingVisitController.startVisit(this); } }
#!/bin/bash module load clustal_omega/1.2.4 clustalo -i /mnt/beegfs/home/aubcls65/final_project/Group_Kcd_7180/longest_peptide.fasta\ -o /mnt/beegfs/home/aubcls65/final_project/Group_Kcd_7180/orf_translate.aln --outfmt=clu --force clustalo -i /mnt/beegfs/home/aubcls65/final_project/Group_Kcd_7180/example_sequence.fasta\ -o /mnt/beegfs/home/aubcls65/final_project/Group_Kcd_7180/nucleotide_sequence.aln --outfmt=clu --force
include PostsHelper include AwsHelper class PostsController < ApplicationController prepend_before_filter :authenticate_admin!, :except => [:index, :show, :feed] before_filter :redirect_old_blog_url, :only => :index before_filter :redirect_published_posts, :only => :show def index @body_class = :split @posts = if params[:year].present? Post.where("permalink LIKE '#{Post.build_like_permalink params}'") elsif params[:author_id].present? Post.published.where(:author_id => params[:author_id]) elsif admin_signed_in? Post.scoped.order("posted_on DESC").order("created_at DESC") else Post.published.by_author_slug(params[:author_slug]) end.page(params[:page]).per(4) @display_author_info = params[:author_slug].present? end def new @post = Post.new end def create @post = Post.new(:author => current_admin, :title => params[:post][:title], :body => params[:post][:body]) if @post.save redirect_to admin_root_path, notice: 'Blog post saved.' else flash.now[:alert] = 'Error saving your blog post.' render :new end end def show @post ||= Post.where(:permalink => Post.build_permalink(params)).first raise ActiveRecord::RecordNotFound if @post.nil? end def edit @post = Post.find(params[:id]) end def update @post = Post.find(params[:id]) if @post.update_attributes(params[:post]) redirect_to @post, notice: 'Post was successfully updated.' else flash.now[:alert] = 'Error updating blog post.' render :edit end end def publish @post = Post.find(params[:id]) if @post.publish && @post.save redirect_to @post, notice: 'Post has been published.' else redirect_to blog_posts_path, alert: %(Could not publish "#{@post.title}".) end end def feed @title = "Coshx Labs Blog" @feed_url = feed_url @posts = Post.published end def upload_image data = Base64.decode64(params[:file].to_s) type = params[:mimeType].to_s extension = params[:extension].to_s name = generate_name extension directory = get_s3_directory("coshx-blog-images") url = get_s3_url(data, type, name, directory) render text: url end private def redirect_old_blog_url if params[:year].present? && params[:year].to_i < 1000 @post = Post.find params[:year] if @post.published? redirect_to show_post_path(@post.permalink_attributes), :status => :moved_permanently else redirect_to @post, :status => :moved_permanently end end end def redirect_published_posts if params[:id].present? @post = Post.find params[:id] if @post.published? redirect_to show_post_path(@post.permalink_attributes), :status => :moved_permanently end end end end
from .queue import Queue import random import unittest class QueueTests(unittest.TestCase): def test_enqueue_one(self): q = Queue() q.enqueue(1) self.assertTrue(q._first.value == 1 and q._last.value == 1) def test_enqueue_two(self): q = Queue() q.enqueue(1) q.enqueue(2) self.assertTrue(q._first.value == 1 and q._last.value == 2) def test_dequeue_one(self): q = Queue() q.enqueue("this is a string") self.assertEqual(q.dequeue(), "this is a string") def test_dequeue_two(self): q = Queue() q.enqueue(1) q.enqueue(2) self.assertTrue(q.dequeue() == 1 and q.dequeue() == 2) def test_too_many_dequeues_dont_error(self): q = Queue() q.enqueue("this is a string") q.dequeue() self.assertIsNone(q.dequeue()) def test_peek(self): q = Queue() for i in range(10): new_int = random.randint(0,10000) q.enqueue(new_int) self.assertEqual(q.peek(), new_int) def test_new_queue_dequeues_None(self): q = Queue() self.assertIsNone(q.dequeue()) def test_new_queue_isEmpty(self): q = Queue() self.assertTrue(q.isEmpty()) def test_emptied_stack_isEmpty(self): q = Queue() q.enqueue("This is a string") q.dequeue() self.assertTrue(q.isEmpty()) def test_length(self): q = Queue() for i in range(10): self.assertEqual(i, q.size()) q.enqueue(i) for i in range(10): self.assertEqual(10-i, q.size()) q.dequeue()