repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
PopCap/GameIdea
Engine/Source/Runtime/Engine/Classes/GameFramework/DefaultPawn.h
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. //============================================================================= // DefaultPawns are simple pawns that can fly around the world. // //============================================================================= #pragma once #include "GameFramework/Pawn.h" #include "DefaultPawn.generated.h" class UFloatingPawnMovement; class USphereComponent; class UStaticMeshComponent; /** * DefaultPawn implements a simple Pawn with spherical collision and built-in flying movement. * @see UFloatingPawnMovement */ UCLASS(config=Game, Blueprintable, BlueprintType) class ENGINE_API ADefaultPawn : public APawn { GENERATED_UCLASS_BODY() // Begin Pawn overrides virtual UPawnMovementComponent* GetMovementComponent() const override; virtual void SetupPlayerInputComponent(UInputComponent* InInputComponent) override; virtual void UpdateNavigationRelevance() override; // End Pawn overrides /** * Input callback to move forward in local space (or backward if Val is negative). * @param Val Amount of movement in the forward direction (or backward if negative). * @see APawn::AddMovementInput() */ UFUNCTION(BlueprintCallable, Category="Pawn") virtual void MoveForward(float Val); /** * Input callback to strafe right in local space (or left if Val is negative). * @param Val Amount of movement in the right direction (or left if negative). * @see APawn::AddMovementInput() */ UFUNCTION(BlueprintCallable, Category="Pawn") virtual void MoveRight(float Val); /** * Input callback to move up in world space (or down if Val is negative). * @param Val Amount of movement in the world up direction (or down if negative). * @see APawn::AddMovementInput() */ UFUNCTION(BlueprintCallable, Category="Pawn") virtual void MoveUp_World(float Val); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ UFUNCTION(BlueprintCallable, Category="Pawn") void TurnAtRate(float Rate); /** * Called via input to look up at a given rate (or down if Rate is negative). * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ UFUNCTION(BlueprintCallable, Category="Pawn") void LookUpAtRate(float Rate); /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Pawn") float BaseTurnRate; /** Base lookup rate, in deg/sec. Other scaling may affect final lookup rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Pawn") float BaseLookUpRate; private: /** Input callback on pitch (look up) input. */ UFUNCTION(BlueprintCallable, Category="Pawn", meta=(DeprecatedFunction, DeprecationMessage="Use Pawn.AddControllerPitchInput instead.")) virtual void LookUp(float Val); /** Input callback on yaw (turn) input. */ UFUNCTION(BlueprintCallable, Category="Pawn", meta=(DeprecatedFunction, DeprecationMessage="Use Pawn.AddControllerYawInput instead.")) virtual void Turn(float Val); public: /** Name of the MovementComponent. Use this name if you want to use a different class (with ObjectInitializer.SetDefaultSubobjectClass). */ static FName MovementComponentName; private: /** DefaultPawn movement component */ UPROPERTY(Category = Pawn, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) UPawnMovementComponent* MovementComponent; public: /** Name of the CollisionComponent. */ static FName CollisionComponentName; private_subobject: /** DefaultPawn collision component */ DEPRECATED_FORGAME(4.6, "CollisionComponent should not be accessed directly, please use GetCollisionComponent() function instead. CollisionComponent will soon be private and your code will not compile.") UPROPERTY(Category = Pawn, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) USphereComponent* CollisionComponent; public: /** Name of the MeshComponent. Use this name if you want to prevent creation of the component (with ObjectInitializer.DoNotCreateDefaultSubobject). */ static FName MeshComponentName; private_subobject: /** The mesh associated with this Pawn. */ DEPRECATED_FORGAME(4.6, "MeshComponent should not be accessed directly, please use GetMeshComponent() function instead. MeshComponent will soon be private and your code will not compile.") UPROPERTY(Category = Pawn, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true")) UStaticMeshComponent* MeshComponent; public: /** If true, adds default input bindings for movement and camera look. */ UPROPERTY(Category=Pawn, EditAnywhere, BlueprintReadOnly) uint32 bAddDefaultMovementBindings:1; /** Returns CollisionComponent subobject **/ USphereComponent* GetCollisionComponent() const; /** Returns MeshComponent subobject **/ UStaticMeshComponent* GetMeshComponent() const; };
newtonjose/engenharia-software-ds
aql-analyzer/src/test/java/com/newtonjose/aqlanalyser/aqlparser/ObservationMicrobiologyQueryTest.java
package com.newtonjose.aqlanalyser.aqlparser; public class ObservationMicrobiologyQueryTest extends AbstractAqlQueryTest { @Override protected String aqlQueryString() { return "SELECT teste/data[at0002]/events[at0003]/data/items[at0015]/items[at0018]/name " + "FROM Ehr [uid=$ehrUid] CONTAINS Composition c CONTAINS Observation o [openEHR-EHR-OBSERVATION.microbiology.v1] " + "WHERE o/data[at0002]/events[at0003]/data/items[at0015]/items[at0018]/items[at0019]/items[at0021]/name/defining_code/code_string matches {'18919-1', '18961-3', '19000-9'};"; } }
ioplee/schoolv1.0
src/main/java/com/hzresp/commons/thread/constant/ThreadConstant.java
<gh_stars>1-10 package com.hzresp.commons.thread.constant; public class ThreadConstant { /** 线程默认的初始化时间 */ public final static int DEF_T_R_DELAY = 300 * 1000 ; public final static String THREAD_LOG_NAME = "com.shangban.thread.manager"; }
erard22/camel
components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/processor/HystrixProcessorCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.hystrix.processor; import java.util.concurrent.atomic.AtomicBoolean; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.exception.HystrixBadRequestException; import org.apache.camel.CamelExchangeException; import org.apache.camel.Exchange; import org.apache.camel.ExtendedExchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.support.ExchangeHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Hystrix Command for the Camel Hystrix EIP. */ public class HystrixProcessorCommand extends HystrixCommand { private static final Logger LOG = LoggerFactory.getLogger(HystrixProcessorCommand.class); private final Exchange exchange; private final Processor processor; private final Processor fallback; private final HystrixProcessorCommandFallbackViaNetwork fallbackCommand; private final AtomicBoolean fallbackInUse = new AtomicBoolean(); private final Object lock = new Object(); public HystrixProcessorCommand(Setter setter, Exchange exchange, Processor processor, Processor fallback, HystrixProcessorCommandFallbackViaNetwork fallbackCommand) { super(setter); this.exchange = exchange; this.processor = processor; this.fallback = fallback; this.fallbackCommand = fallbackCommand; } @Override protected Message getFallback() { // if bad request then break-out if (exchange.getException() instanceof HystrixBadRequestException) { return null; } // guard by lock as the run command can be running concurrently in case hystrix caused a timeout which // can cause the fallback timer to trigger this fallback at the same time the run command may be running // after its processor.process method which could cause both threads to mutate the state on the exchange synchronized (lock) { fallbackInUse.set(true); } if (fallback == null && fallbackCommand == null) { // no fallback in use throw new UnsupportedOperationException("No fallback available."); } // grab the exception that caused the error (can be failure in run, or from hystrix if short circuited) Throwable exception = getExecutionException(); if (exception != null) { LOG.debug("Error occurred processing. Will now run fallback. Exception class: {} message: {}.", exception.getClass().getName(), exception.getMessage()); } else { LOG.debug("Error occurred processing. Will now run fallback."); } // store the last to endpoint as the failure endpoint if (exchange.getProperty(Exchange.FAILURE_ENDPOINT) == null) { exchange.setProperty(Exchange.FAILURE_ENDPOINT, exchange.getProperty(Exchange.TO_ENDPOINT)); } // give the rest of the pipeline another chance exchange.setProperty(Exchange.EXCEPTION_HANDLED, true); exchange.setProperty(Exchange.EXCEPTION_CAUGHT, exception); exchange.setRouteStop(false); exchange.setException(null); // and we should not be regarded as exhausted as we are in a try .. catch block exchange.adapt(ExtendedExchange.class).setRedeliveryExhausted(false); // run the fallback processor try { // use fallback command if provided (fallback via network) if (fallbackCommand != null) { return fallbackCommand.execute(); } else { LOG.debug("Running fallback: {} with exchange: {}", fallback, exchange); // process the fallback until its fully done // (we do not hav any hystrix callback to leverage so we need to complete all work in this run method) fallback.process(exchange); LOG.debug("Running fallback: {} with exchange: {} done", fallback, exchange); } } catch (Exception e) { exchange.setException(e); } return exchange.getMessage(); } @Override protected Message run() throws Exception { LOG.debug("Running processor: {} with exchange: {}", processor, exchange); // prepare a copy of exchange so downstream processors don't cause side-effects if they mutate the exchange // in case Hystrix timeout processing and continue with the fallback etc Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false, false); try { // process the processor until its fully done // (we do not hav any hystrix callback to leverage so we need to complete all work in this run method) processor.process(copy); } catch (Exception e) { copy.setException(e); } // if hystrix execution timeout is enabled and fallback is enabled and a timeout occurs // then a hystrix timer thread executes the fallback so we can stop run() execution if (getProperties().executionTimeoutEnabled().get() && getProperties().fallbackEnabled().get() && isCommandTimedOut.get() == TimedOutStatus.TIMED_OUT) { LOG.debug("Exiting run command due to a hystrix execution timeout in processing exchange: {}", exchange); return null; } // when a hystrix timeout occurs then a hystrix timer thread executes the fallback // and therefore we need this thread to not do anymore if fallback is already in process if (fallbackInUse.get()) { LOG.debug("Exiting run command as fallback is already in use processing exchange: {}", exchange); return null; } // remember any hystrix execution exception which for example can be triggered by a hystrix timeout Throwable hystrixExecutionException = getExecutionException(); Exception camelExchangeException = copy.getException(); synchronized (lock) { // when a hystrix timeout occurs then a hystrix timer thread executes the fallback // and therefore we need this thread to not do anymore if fallback is already in process if (fallbackInUse.get()) { LOG.debug("Exiting run command as fallback is already in use processing exchange: {}", exchange); return null; } // execution exception must take precedence over exchange exception // because hystrix may have caused this command to fail due timeout or something else if (hystrixExecutionException != null) { exchange.setException(new CamelExchangeException( "Hystrix execution exception occurred while processing Exchange", exchange, hystrixExecutionException)); } // special for HystrixBadRequestException which should not trigger fallback if (camelExchangeException instanceof HystrixBadRequestException) { LOG.debug("Running processor: {} with exchange: {} done as bad request", processor, exchange); exchange.setException(camelExchangeException); throw camelExchangeException; } // copy the result before its regarded as success ExchangeHelper.copyResults(exchange, copy); // in case of an exception in the exchange // we need to trigger this by throwing the exception so hystrix will execute the fallback // or open the circuit if (hystrixExecutionException == null && camelExchangeException != null) { throw camelExchangeException; } LOG.debug("Running processor: {} with exchange: {} done", processor, exchange); return exchange.getMessage(); } } }
Ehtisham-Ayaan/aoo-ghr-bnain-update
node_modules/react-ionicons/lib/EyeOffSharp.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _SvgContainer = require('./SvgContainer'); var _SvgContainer2 = _interopRequireDefault(_SvgContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EyeOffSharp = function EyeOffSharp(props) { return _react2.default.createElement( _SvgContainer2.default, { height: props.height, width: props.width, color: props.color, onClick: props.onClick, rotate: props.rotate ? 1 : 0, shake: props.shake ? 1 : 0, beat: props.beat ? 1 : 0, className: props.className }, _react2.default.createElement( 'svg', { style: props.style, className: props.cssClasses, xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 512 512' }, props.title ? _react2.default.createElement( 'title', null, props.title ) : '', _react2.default.createElement('path', { d: 'M63.998 86.004l21.998-21.998L448 426.01l-21.998 21.998zM259.34 192.09l60.57 60.57a64.07 64.07 0 00-60.57-60.57zM252.66 319.91l-60.57-60.57a64.07 64.07 0 0060.57 60.57z' }), _react2.default.createElement('path', { d: 'M256 352a96 96 0 01-92.6-121.34l-69.07-69.08C66.12 187.42 39.24 221.14 16 256c26.42 44 62.56 89.24 100.2 115.18C159.38 400.92 206.33 416 255.76 416A233.47 233.47 0 00335 402.2l-53.61-53.6A95.84 95.84 0 01256 352zM256 160a96 96 0 0192.6 121.34L419.26 352c29.15-26.25 56.07-61.56 76.74-96-26.38-43.43-62.9-88.56-101.18-114.82C351.1 111.2 304.31 96 255.76 96a222.92 222.92 0 00-78.21 14.29l53.11 53.11A95.84 95.84 0 01256 160z' }) ) ); }; EyeOffSharp.defaultProps = { // style style: {}, color: '#000000', height: '22px', width: '22px', cssClasses: '', title: '', // animation shake: false, beat: false, rotate: false }; EyeOffSharp.propTypes = { // style style: _propTypes2.default.object, color: _propTypes2.default.string, height: _propTypes2.default.string, width: _propTypes2.default.string, cssClasses: _propTypes2.default.string, title: _propTypes2.default.string, // animation shake: _propTypes2.default.bool, beat: _propTypes2.default.bool, rotate: _propTypes2.default.bool, // functions onClick: _propTypes2.default.func }; exports.default = EyeOffSharp; module.exports = exports['default']; //# sourceMappingURL=EyeOffSharp.js.map
stackrox/stackrox
central/graphql/resolvers/node_vulnerabilities.go
<reponame>stackrox/stackrox package resolvers import ( "context" "time" "github.com/pkg/errors" "github.com/stackrox/rox/central/metrics" "github.com/stackrox/rox/generated/storage" "github.com/stackrox/rox/pkg/features" pkgMetrics "github.com/stackrox/rox/pkg/metrics" "github.com/stackrox/rox/pkg/search" "github.com/stackrox/rox/pkg/utils" ) func init() { schema := getBuilder() utils.Must( // NOTE: This list is and should remain alphabetically ordered schema.AddType("NodeVulnerability", append(commonVulnerabilitySubResolvers, "nodeComponentCount(query: String): Int!", "nodeComponents(query: String, pagination: Pagination): [NodeComponent!]!", "nodeCount(query: String): Int!", "nodes(query: String, pagination: Pagination): [Node!]!", )), schema.AddQuery("nodeVulnerability(id: ID): NodeVulnerability"), schema.AddQuery("nodeVulnerabilities(query: String, scopeQuery: String, pagination: Pagination): [NodeVulnerability!]!"), schema.AddQuery("nodeVulnerabilityCount(query: String): Int!"), ) } // NodeVulnerabilityResolver represents the supported API on node vulnerabilities // NOTE: This list is and should remain alphabetically ordered type NodeVulnerabilityResolver interface { CommonVulnerabilityResolver NodeComponentCount(ctx context.Context, args RawQuery) (int32, error) NodeComponents(ctx context.Context, args PaginatedQuery) ([]NodeComponentResolver, error) NodeCount(ctx context.Context, args RawQuery) (int32, error) Nodes(ctx context.Context, args PaginatedQuery) ([]*nodeResolver, error) } // NodeVulnerability resolves a single vulnerability based on an id func (resolver *Resolver) NodeVulnerability(ctx context.Context, args IDQuery) (NodeVulnerabilityResolver, error) { defer metrics.SetGraphQLOperationDurationTime(time.Now(), pkgMetrics.Root, "NodeVulnerability") if !features.PostgresDatastore.Enabled() { return resolver.nodeVulnerabilityV2(ctx, args) } // TODO : Add postgres support return nil, errors.New("Resolver NodeVulnerability does not support postgres yet") } // NodeVulnerabilities resolves a set of vulnerabilities based on a query. func (resolver *Resolver) NodeVulnerabilities(ctx context.Context, q PaginatedQuery) ([]NodeVulnerabilityResolver, error) { defer metrics.SetGraphQLOperationDurationTime(time.Now(), pkgMetrics.Root, "NodeVulnerabilities") if !features.PostgresDatastore.Enabled() { query := withNodeCveTypeFiltering(q.String()) return resolver.nodeVulnerabilitiesV2(ctx, PaginatedQuery{Query: &query, Pagination: q.Pagination}) } // TODO : Add postgres support return nil, errors.New("Resolver NodeVulnerabilities does not support postgres yet") } // NodeVulnerabilityCount returns count of all clusters across infrastructure func (resolver *Resolver) NodeVulnerabilityCount(ctx context.Context, args RawQuery) (int32, error) { defer metrics.SetGraphQLOperationDurationTime(time.Now(), pkgMetrics.Root, "NodeVulnerabilityCount") if !features.PostgresDatastore.Enabled() { query := withNodeCveTypeFiltering(args.String()) return resolver.vulnerabilityCountV2(ctx, RawQuery{Query: &query}) } // TODO : Add postgres support return 0, errors.New("Resolver NodeVulnerabilityCount does not support postgres yet") } // NodeVulnCounter returns a VulnerabilityCounterResolver for the input query.s func (resolver *Resolver) NodeVulnCounter(ctx context.Context, args RawQuery) (*VulnerabilityCounterResolver, error) { defer metrics.SetGraphQLOperationDurationTime(time.Now(), pkgMetrics.Root, "NodeVulnerabilityCounter") if !features.PostgresDatastore.Enabled() { query := withNodeCveTypeFiltering(args.String()) return resolver.vulnCounterV2(ctx, RawQuery{Query: &query}) } // TODO : Add postgres support return nil, errors.New("Resolver NodeVulnCounter does not support postgres yet") } // withNodeCveTypeFiltering adds a conjunction as a raw query to filter vulns by CVEType Node func withNodeCveTypeFiltering(q string) string { return search.AddRawQueriesAsConjunction(q, search.NewQueryBuilder().AddExactMatches(search.CVEType, storage.CVE_NODE_CVE.String()).Query()) }
thepassle/plugins
packages/commonjs/test/fixtures/function/strict-requires-exportmode-replace/replaceModuleExports.js
module.exports = { foo: 'foo' }; global.hasReplaceModuleExportsRun = true;
side-projects-42/INTERVIEW-PREP-COMPLETE
notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/Interview-Problems/LeetCode/ReverseBits.py
<reponame>side-projects-42/INTERVIEW-PREP-COMPLETE<filename>notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/Interview-Problems/LeetCode/ReverseBits.py class Solution: def reverseBits(self, n: int) -> int: s = str(bin(n)) s = s[2:] s = "0" * (32 - len(s)) + s s = int(s[::-1], 2) return s
peterolson/Project-Euler
38.js
function isPandigital(n) { var concat = ""; for (var i = 1; (concat + n * i).length <= 9; i++) { concat += n * i; } return [1, 2, 3, 4, 5, 6, 7, 8, 9].every(function (x) { return ~concat.indexOf(x); }) ? +concat : false; } var max = 0; for (var i = 1; i <= 9999; i++) { var product = isPandigital(i); if (product > max) max = product; } console.log(max);
MadAppGang/identifo
test/runner/login_test.go
package runner_test import ( "fmt" "testing" "github.com/madappgang/identifo/test/runner" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gstruct" ) // ============================================================ // Login with username and password // ============================================================ // test happy day login func TestLogin(t *testing.T) { data := fmt.Sprintf(` { "username": "%s", "password": <PASSWORD>", "scopes": ["offline"] }`, cfg.User1, cfg.User1Pswd) signature, _ := runner.Signature(data, cfg.AppSecret) request.Post("/auth/login"). SetHeader("X-Identifo-ClientID", cfg.AppID). SetHeader("Digest", "SHA-256="+signature). SetHeader("Content-Type", "application/json"). BodyString(data). Expect(t). // AssertFunc(dumpResponse). Type("json"). Status(200). JSONSchema("data/jwt_token_with_refresh_scheme.json"). Done() } // test happy day login, with no refresh token included func TestLoginWithNoRefresh(t *testing.T) { g := NewGomegaWithT(t) data := fmt.Sprintf(` { "username": "%s", "password": <PASSWORD>", "scopes": [] }`, cfg.User1, cfg.User1Pswd) signature, _ := runner.Signature(data, cfg.AppSecret) request.Post("/auth/login"). SetHeader("X-Identifo-ClientID", cfg.AppID). SetHeader("Digest", "SHA-256="+signature). SetHeader("Content-Type", "application/json"). BodyString(data). Expect(t). // AssertFunc(dumpResponse). AssertFunc(validateJSON(func(data map[string]interface{}) error { g.Expect(data).To(MatchKeys(IgnoreExtras|IgnoreMissing, Keys{ "access_token": Not(BeZero()), "refresh_token": BeZero(), })) return nil })). Type("json"). Status(200). JSONSchema("data/jwt_token_scheme.json"). Done() } // test wrong app ID login func TestLoginWithWrongAppID(t *testing.T) { g := NewGomegaWithT(t) request.Post("/auth/login"). SetHeader("X-Identifo-ClientID", "wrong_app_ID"). Expect(t). // AssertFunc(dumpResponse). AssertFunc(validateJSON(func(data map[string]interface{}) error { g.Expect(data["error"]).To(MatchAllKeys(Keys{ "id": Equal("error.api.request.app_id.invalid"), "message": Not(BeZero()), "detailed_message": Not(BeZero()), "status": BeNumerically("==", 400), })) return nil })). Type("json"). Status(400). Done() } // test wrong signature for mobile app func TestLoginWithWrongSignature(t *testing.T) { g := NewGomegaWithT(t) data := fmt.Sprintf(` { "username": "%s", "password": <PASSWORD>", "scopes": ["offline"] }`, cfg.User1, cfg.User1Pswd) signature, _ := runner.Signature(data, cfg.AppSecret) request.Post("/auth/login"). SetHeader("X-Identifo-ClientID", cfg.AppID). SetHeader("Digest", "SHA-256="+signature+"_wrong"). SetHeader("Content-Type", "application/json"). BodyString(data). Expect(t). // AssertFunc(dumpResponse). Status(400). AssertFunc(validateJSON(func(data map[string]interface{}) error { g.Expect(data["error"]).To(MatchAllKeys(Keys{ "id": Equal("error.api.request.signature.invalid"), "message": Not(BeZero()), "status": BeNumerically("==", 400), })) return nil })). Done() }
AndroidKotlinID/objectbox-java
objectbox-java/src/main/java/io/objectbox/query/QueryCondition.java
package io.objectbox.query; import io.objectbox.Property; /** * Allows building queries with a fluent interface. Use through {@link io.objectbox.Box#query(QueryCondition)} * and build a condition with {@link Property} methods. */ public interface QueryCondition<T> { /** * Combines this condition using AND with the given condition. * * @see #or(QueryCondition) */ QueryCondition<T> and(QueryCondition<T> queryCondition); /** * Combines this condition using OR with the given condition. * * @see #and(QueryCondition) */ QueryCondition<T> or(QueryCondition<T> queryCondition); }
BiBiServ/bibigrid
bibigrid-googlecloud/src/main/java/de/unibi/cebitec/bibigrid/googlecloud/HttpRequestLogHandler.java
<reponame>BiBiServ/bibigrid package de.unibi.cebitec.bibigrid.googlecloud; import com.google.api.client.http.HttpTransport; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; public class HttpRequestLogHandler extends Handler { static void attachToCloudHttpTransport() { Logger logger = Logger.getLogger(HttpTransport.class.getName()); // Check if already attached for (Handler handler : logger.getHandlers()) { if (handler.getClass() == HttpRequestLogHandler.class) { return; } } logger.setLevel(Level.CONFIG); logger.addHandler(new HttpRequestLogHandler()); } @Override public void publish(LogRecord record) { // Default ConsoleHandler will print >= INFO to System.err. if (record.getLevel().intValue() < Level.INFO.intValue()) { System.out.println(record.getMessage()); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }
dzma352/portainer
app/kubernetes/component-status/models.js
/** * KubernetesComponentStatus Model */ const _KubernetesComponentStatus = Object.freeze({ ComponentName: '', Healthy: false, ErrorMessage: '', }); export class KubernetesComponentStatus { constructor() { Object.assign(this, JSON.parse(JSON.stringify(_KubernetesComponentStatus))); } }
byegates/Algos
util/TreeNode.java
<gh_stars>1-10 package util; import java.util.*; import static util.Utils.numLength; public class TreeNode implements Iterable<TreeNode> { public int key; public TreeNode left; public TreeNode right; TreeNode(int key, TreeNode left, TreeNode right) { this.key = key; this.left = left; this.right = right; } public TreeNode(int key) { this(key, null, null); } public static TreeNode fromLevelOrder(Integer[] A) { if (A == null || A.length==0) return null; Queue<TreeNode> q = new LinkedList<>(); TreeNode root = new TreeNode(A[0]); q.offer(root); int idx = 1; while (idx < A.length){ Integer leftKey = A[idx++]; Integer rightKey = idx >= A.length ? null : A[idx++]; TreeNode cur = q.poll(); if (leftKey != null) { cur.left = new TreeNode(leftKey); q.offer(cur.left); } if (rightKey != null){ cur.right = new TreeNode(rightKey); q.offer(cur.right); } } return root; } public static TreeNode fromLevelOrderSpecial(String[] arr) { if (arr == null || arr.length == 0) return null; return fromLevelOrder(stringToIntArr(arr)); } static Integer[] stringToIntArr(String[] A) { Integer[] res = new Integer[A.length]; for (int i = 0; i < A.length; i++) res[i] = A[i].equals("#") ? null : Integer.parseInt(A[i]); return res; } public List<Integer> inOrder() { return inOrder(this); } public List<Integer> preOrder() { return preOrder(this); } public List<Integer> postOrder() { return postOrder(this); } public List<Integer> postOrderIterative() { return postOrderIterative(this); } public List<Integer> levelOrder() { return levelOrder(this); } public TreeNode insert(int key) { return insert(this, key); } public int getHeight() { return getHeight(this); } public boolean isCompleted() { return isCompleted(this); } public List<List<Integer>> layerByLayer() { return layerByLayer(this); } public TreeNode deleteNode(int key) { return deleteNode(this, key); } public boolean pathSumToTarget(int target) { return pathSumToTarget(this, target); } public String toString() { return TreePrinter.toString(this); } public static String toString(TreeNode root) { return levelOrder(root).toString(); } public int maxDigits() { return maxDigits(this); } public static TreeNode deleteNode(TreeNode root, int key) { if (root == null) return null; if (root.key == key) { if (root.left == null) return root.right; else if (root.right == null) return root.left; // left & right are both not null if (root.right.left == null) { // right tree and no left sub root.right.left = root.left; return root.right; } // now root.right has left sub, search for left most(smallest) as candidate TreeNode smallest = smallest(root.right); smallest.left = root.left; smallest.right = root.right; return smallest; } if (key < root.key) root.left = deleteNode(root.left, key); else root.right = deleteNode(root.right, key); // key < root.key return root; } private static TreeNode smallest(TreeNode root) { while (root.left.left != null) root = root.left; TreeNode smallest = root.left; root.left = root.left.right; return smallest; } public static boolean isCompleted(TreeNode root) { if (root == null) return true; Queue<TreeNode> q = new ArrayDeque<>(); q.offer(root); boolean sawBubble = false; while (!q.isEmpty()) { TreeNode cur = q.poll(); if (cur.left == null) sawBubble = true; else if (sawBubble) return false; else q.offer(cur.left); if (cur.right == null) sawBubble = true; else if (sawBubble) return false; else q.offer(cur.right); } return true; } public static List<List<Integer>> layerByLayer(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { int size = q.size(); List<Integer> res0 = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode cur = q.poll(); res0.add(cur.key); if (cur.left != null) q.offer(cur.left); if (cur.right != null) q.offer(cur.right); } res.add(res0); } return res; } //TC: O(n), SC: O(n) static int getHeight(TreeNode root) { return root == null ? 0 : 1 + Math.max(getHeight(root.left), getHeight(root.right)); } static TreeNode insert(TreeNode root, int key) {//insert into Binary tree, interactive I if (root == null) return new TreeNode(key); TreeNode cur = root, pre = root; while (cur != null && pre.key != key) { pre = cur; cur = key < cur.key ? cur.left : cur.right; } if (key < pre.key) pre.left = new TreeNode(key); else if (key > pre.key) pre.right = new TreeNode(key); return root; } static public List<Integer> levelOrder(TreeNode root){ List<Integer> res = new ArrayList<>(); if (root == null) return res; Deque<TreeNode> q = new ArrayDeque<>(); res.add(root.key); q.offerLast(root); while(!q.isEmpty()){ TreeNode cur = q.pollFirst(); res.add(cur.left == null ? null : cur.left.key); res.add(cur.right == null ? null : cur.right.key); if (cur.left != null) q.offerLast(cur.left); if (cur.right != null) q.offerLast(cur.right); } return trimTrailingNull(res); } public List<Integer> levelOrderWithoutNull(TreeNode root){ List<Integer> A = new ArrayList<>(); if(root == null){return A;} Deque<TreeNode> Q = new ArrayDeque<>(); Q.offerLast(root); while (!Q.isEmpty()) { TreeNode cur = Q.pollFirst(); A.add(cur.key); if (cur.left != null) Q.offerLast(cur.left); if (cur.right != null) Q.offerLast(cur.right); } return A; } public static List<Integer> trimTrailingNull (List<Integer> A) { int size = A.size(); for (int i = size - 1; i >= 0; i--) if (A.get(i) == null) A.remove(i); else break; return A; } static List<Integer> inOrder(TreeNode root) { List<Integer> res = new ArrayList<>(); inOrder(root, res); return res; } static List<Integer> preOrder(TreeNode root) { List<Integer> res = new ArrayList<>(); preOrder(root, res); return res; } public static List<Integer> postOrder(TreeNode root) { List<Integer> res = new ArrayList<>(); postOrder(root, res); return res; } private static void inOrder(TreeNode root, List<Integer> res) { if (root == null) return; inOrder(root.left, res); res.add(root.key); inOrder(root.right, res); } private static void preOrder(TreeNode root, List<Integer> res) { if (root == null) return; res.add(root.key); preOrder(root.left, res); preOrder(root.right, res); } private static void postOrder(TreeNode root, List<Integer> res) { if (root == null) return; postOrder(root.left, res); postOrder(root.right, res); res.add(root.key); } private static List<Integer> postOrderIterative(TreeNode root) { List<Integer> res = new ArrayList<>(); if (root == null) return res; Deque<TreeNode> stack = new ArrayDeque<>(); stack.offerFirst(root); TreeNode pre = null; while (!stack.isEmpty()) { TreeNode cur = stack.peekFirst(); if (pre == null || cur == pre.right || cur == pre.left) {//coming down for the first time, keep going down if (cur.left != null) stack.offerFirst(cur.left); // keep going left until no more left child else if (cur.right != null) stack.offerFirst(cur.right); //Will not execute until first left null met else { // Leaf nodes stack.pollFirst();//value was peeked and saved to cur already res.add(cur.key); } } else if (pre == cur.right || pre == cur.left && cur.right == null) {//coming back after traversal both sides stack.pollFirst(); res.add(cur.key); } else stack.offerFirst(cur.right); // pre == cur.left && cur.right != null, back from left or no right pre = cur; } return res; } public int maxPathSum2PlusNodes() {return maxPathSum2PlusNodes(this);} public static int maxPathSum2PlusNodes(TreeNode root) { int[] max = new int[]{Integer.MIN_VALUE}; maxPathSum2PlusNodes(root, max); return max[0]; } private static int maxPathSum2PlusNodes(TreeNode root, int[] max) { if (root == null) return Integer.MIN_VALUE; if (root.left == null && root.right == null) return root.key; int left = maxPathSum2PlusNodes(root.left, max); int right = maxPathSum2PlusNodes(root.right, max); int fromChildren = left >= 0 && right >= 0 ? left + right : Math.max(left, right); max[0] = Math.max(root.key + fromChildren, max[0]); return root.key + (left >= 0 || right >= 0 ? Math.max(left, right) : 0); } public static boolean pathSumToTarget(TreeNode root, int target) { // TC: O(n), SC:O(h) if (root == null) return false; Set<Integer> set = new HashSet<>(); set.add(0); return exist(root, target, 0, set); } private static boolean exist(TreeNode root, int target, int preSum, Set<Integer> set) { preSum += root.key; if (set.contains(preSum - target)) return true; boolean addedThisLevel = set.add(preSum); if (root.left != null && exist(root.left, target, preSum, set)) return true; if (root.right != null && exist(root.right, target, preSum, set)) return true; if (addedThisLevel) set.remove(preSum); return false; } public TreeNode fromInPre(int[] in, int[] pre) { // TC: O(3n) → O(n), SC: O(height) Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < in.length; i++) map.put(in[i], i); return reconstruct(in, 0, in.length - 1, pre, 0, pre.length - 1, map); } private TreeNode reconstruct(int[] in, int inL, int inR, int[] pre, int preL, int preR, Map<Integer, Integer> map) { if (inR < inL) return null; TreeNode root = new TreeNode(pre[preL]); int rootIdx = map.get(pre[preL]); int leftSize = rootIdx - inL; root.left = reconstruct(in, inL, rootIdx - 1, pre, preL + 1, preL + leftSize, map); root.right = reconstruct(in, rootIdx + 1, inR, pre, preL + leftSize + 1, preR, map); return root; } public static int maxDigits(TreeNode root) { int[] maxDigits = new int[1]; maxDigits(root, maxDigits); return maxDigits[0]; } private static void maxDigits(TreeNode root, int[] maxDigits) { if (root == null) return; maxDigits[0] = Math.max(maxDigits[0], numLength(root.key)); maxDigits(root.left, maxDigits); maxDigits(root.right, maxDigits); } private static TreeNode BST(int[] a, int l, int r) { if (l > r) return null; int mid = r - (r - l) / 2; TreeNode root = new TreeNode(a[mid]); root.left = BST(a, l, mid - 1); root.right = BST(a, mid + 1, r); return root; } public static TreeNode inOrderToBST(int[] a) { return BST(a, 0, a.length - 1); } static class Node { TreeNode node; int min, max; Node(TreeNode node, int min, int max) { this.node = node; this.min = min; this.max = max; } } public static List<TreeNode> sampleTrees() { List<TreeNode> res = new ArrayList<>(); res.add(TreeNode.fromLevelOrder(new Integer[]{5, null, 8, null, 4, 3, 4})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, 13, 14, 15, 16, 17, null, null, -108})); res.add(TreeNode.fromLevelOrder(new Integer[] {1, 2, 3, 4, 5, 6, 7})); res.add(TreeNode.fromLevelOrder(new Integer[] {1, 1, 2, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6})); res.add(TreeNode.fromLevelOrder(new Integer[] {1, 2, -3, 4, 5, 6, 7})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, 13, 14, 15, 16, 17})); res.add(TreeNode.fromLevelOrder(new Integer[] {11, 11, 12, 11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 30, 31, 32, 33, 34, 35, 36})); res.add(TreeNode.fromLevelOrder(new Integer[] {11, 11, 12, 11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27, 28, 31, null, 33, 34, null, 36, null, 38, 39, 30, null, 32, 33, null, 35, 36})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, -13, 14, 15, 16, 17})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, 13, 14, 15, 16, 17, null, null, -108})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, 14, null, 16, 17})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, 14, null, -108, 17})); res.add(TreeNode.fromLevelOrder(new Integer[] {10, 12, 14, null, 16, 17, -18, 27, null, 36, 48, null})); Integer[] arr2 = new Integer[] {111, 111, 112, 111, 112, 113, 114, 121, 122, 123, 224, 225, 226, 227, 228, 231, null, 333, 334, null, 336, null, 338, 339, 330, null, 332, 333, null, 335, 336}; // Add some negative numbers to arr2 Integer[] arr2b = new Integer[arr2.length]; for (int i = 0; i < arr2.length; i++) arr2b[i] = arr2[i] != null ? i % 2 == 0 ? arr2[i] : -arr2[i] : null; res.add(TreeNode.fromLevelOrder(arr2)); res.add(TreeNode.fromLevelOrder(arr2b)); res.add(TreeNode.fromLevelOrderSpecial(new String[]{"460","59","35","#","287","272","61","292","148","354","140","277","442","130","453","#","96","46","#","119","90","304","#","202","360","300","472","299","110","406","365","142","#","288","276","#","332","87","#","29"})); res.add(TreeNode.fromLevelOrder(new Integer[]{1, 3, 2, 4, null, null, 5})); res.add(TreeNode.fromLevelOrder(new Integer[]{31, 11, null, 7, 26, 2, 8, 16, 30, null, 6, null, 10, 13, 22, 27})); return res; } @Override public Iterator<TreeNode> iterator() { return new LevelOrderIterator(this); //return new InOrderIterator(this); //return new PreOrderIterator(this); //return new PostOrderIterator(this); } }
740326093/-
YBL365/Class/Home/New_Buttons/MillionMessage/MineMillionMessage/View/YBLCustomersLabel.h
// // YBLCustomersLabel.h // 手机云采 // // Created by 乔同新 on 2017/8/1. // Copyright © 2017年 乔同新. All rights reserved. // #import <UIKit/UIKit.h> @interface YBLCustomersLabel : UILabel @end
git4wht/cloudbreak
common/src/main/java/com/sequenceiq/cloudbreak/quartz/statuschecker/service/StatusCheckerJobService.java
package com.sequenceiq.cloudbreak.quartz.statuschecker.service; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.SecureRandom; import java.time.Duration; import java.time.ZonedDateTime; import java.util.Date; import java.util.Map; import java.util.Random; import javax.inject.Inject; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import com.sequenceiq.cloudbreak.auth.crn.Crn; import com.sequenceiq.cloudbreak.quartz.model.JobResource; import com.sequenceiq.cloudbreak.quartz.model.JobResourceAdapter; import com.sequenceiq.cloudbreak.quartz.statuschecker.StatusCheckerConfig; @Service public class StatusCheckerJobService { public static final String SYNC_JOB_TYPE = "syncJobType"; public static final String LONG_SYNC_JOB_TYPE = "longSyncJobType"; private static final String JOB_GROUP = "status-checker-jobs"; private static final String TRIGGER_GROUP = "status-checker-triggers"; private static final Logger LOGGER = LoggerFactory.getLogger(StatusCheckerJobService.class); private static final Random RANDOM = new SecureRandom(); @Inject private StatusCheckerConfig statusCheckerConfig; @Inject private Scheduler scheduler; @Inject private ApplicationContext applicationContext; public <T> void schedule(JobResourceAdapter<T> resource) { JobDetail jobDetail = buildJobDetail(resource); Trigger trigger = buildJobTrigger(jobDetail, resource.getJobResource(), RANDOM.nextInt(statusCheckerConfig.getIntervalInSeconds()), statusCheckerConfig.getIntervalInSeconds()); schedule(jobDetail, trigger, resource.getJobResource()); } public <T> void schedule(JobResourceAdapter<T> resource, int delayInSeconds) { JobDetail jobDetail = buildJobDetail(resource); Trigger trigger = buildJobTrigger(jobDetail, resource.getJobResource(), delayInSeconds, statusCheckerConfig.getIntervalInSeconds()); schedule(jobDetail, trigger, resource.getJobResource()); } public void schedule(Long id, Class<? extends JobResourceAdapter<?>> resourceAdapterClass) { try { Constructor<? extends JobResourceAdapter> c = resourceAdapterClass.getConstructor(Long.class, ApplicationContext.class); JobResourceAdapter resourceAdapter = c.newInstance(id, applicationContext); schedule(resourceAdapter); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { LOGGER.error("Error during scheduling quartz job: {}", id, e); } } public <T> void scheduleLongIntervalCheck(JobResourceAdapter<T> resource) { JobDetail jobDetail = buildJobDetail(resource, Map.of(SYNC_JOB_TYPE, LONG_SYNC_JOB_TYPE)); Trigger trigger = buildJobTrigger(jobDetail, resource.getJobResource(), statusCheckerConfig.getIntervalInSeconds(), statusCheckerConfig.getLongIntervalInSeconds()); schedule(jobDetail, trigger, resource.getJobResource()); } public <T> void scheduleLongIntervalCheck(Long id, Class<? extends JobResourceAdapter<?>> resourceAdapterClass) { try { Constructor<? extends JobResourceAdapter> c = resourceAdapterClass.getConstructor(Long.class, ApplicationContext.class); JobResourceAdapter resourceAdapter = c.newInstance(id, applicationContext); scheduleLongIntervalCheck(resourceAdapter); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { LOGGER.error("Error during scheduling long quartz job: {}", id, e); } } public void unschedule(String id) { try { JobKey jobKey = JobKey.jobKey(id, JOB_GROUP); LOGGER.info("Unscheduling status checker job for stack with key: '{}' and group: '{}'", jobKey.getName(), jobKey.getGroup()); scheduler.deleteJob(jobKey); LOGGER.info("Status checker job unscheduled with id: {}", id); } catch (SchedulerException e) { LOGGER.error(String.format("Error during unscheduling quartz job: %s", id), e); } } public void deleteAll() { try { scheduler.clear(); LOGGER.info("All scheduled tasks are cleared"); } catch (SchedulerException e) { LOGGER.error("Error during clearing quartz jobs", e); } } private void schedule(JobDetail jobDetail, Trigger trigger, JobResource jobResource) { try { JobKey jobKey = JobKey.jobKey(jobResource.getLocalId(), JOB_GROUP); if (scheduler.getJobDetail(jobKey) != null) { LOGGER.info("Unscheduling status checker job for stack with key: '{}' and group: '{}'", jobKey.getName(), jobKey.getGroup()); unschedule(jobResource.getLocalId()); } LOGGER.info("Scheduling status checker job for stack with key: '{}' and group: '{}'", jobKey.getName(), jobKey.getGroup()); scheduler.scheduleJob(jobDetail, trigger); LOGGER.info("Status checker job scheduled with id: {}, name: {}, crn: {}, type: {}", jobResource.getLocalId(), jobResource.getName(), jobResource.getRemoteResourceId(), jobDetail.getJobDataMap().get(SYNC_JOB_TYPE)); } catch (SchedulerException e) { LOGGER.error("Error during scheduling quartz job. id: {}, name: {}, crn: {}", jobResource.getLocalId(), jobResource.getName(), jobResource.getRemoteResourceId(), e); } } private <T> JobDetail buildJobDetail(JobResourceAdapter<T> resource) { return buildJobDetail(resource, Map.of()); } private <T> JobDetail buildJobDetail(JobResourceAdapter<T> resource, Map<String, String> dataMap) { JobDataMap jobDataMap = resource.toJobDataMap(); jobDataMap.putAll(dataMap); String resourceType = getResourceTypeFromCrnIfAvailable(resource.getJobResource()); return JobBuilder.newJob(resource.getJobClassForResource()) .withIdentity(resource.getJobResource().getLocalId(), JOB_GROUP) .withDescription(String.format("Checking %s status job", resourceType)) .usingJobData(jobDataMap) .storeDurably() .build(); } private <T> String getResourceTypeFromCrnIfAvailable(JobResource jobResource) { String remoteResourceId = jobResource.getRemoteResourceId(); String resourceType = "unknown"; if (Crn.isCrn(remoteResourceId)) { resourceType = Crn.safeFromString(remoteResourceId).getResource(); } return resourceType; } private Trigger buildJobTrigger(JobDetail jobDetail, JobResource jobResource, int delayInSeconds, int intervalInSeconds) { return TriggerBuilder.newTrigger() .forJob(jobDetail) .withIdentity(jobDetail.getKey().getName(), TRIGGER_GROUP) .withDescription(String.format("Checking %s status trigger", getResourceTypeFromCrnIfAvailable(jobResource))) .startAt(delayedStart(delayInSeconds)) .withSchedule(SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(intervalInSeconds) .repeatForever() .withMisfireHandlingInstructionNextWithRemainingCount()) .build(); } private Date delayedStart(int delayInSeconds) { return Date.from(ZonedDateTime.now().toInstant().plus(Duration.ofSeconds(delayInSeconds))); } }
Drakandes/Portfolio_NicolasPaulBonneau
Code en C++ de Mage War Online/AttackDamageBox.cpp
#include "stdafx.h" #include "AttackDamageBox.h" AttackDamageBox::AttackDamageBox() { if (!texture_ablaze_the_fire_box.loadFromFile("AttackDamageBox.png")) { std::cout << "Couldn't load balze the fire box correctly" << std::endl; } } AttackDamageBox::~AttackDamageBox() { } bool AttackDamageBox::GetInitStatus() { return been_init; } void AttackDamageBox::Init(sf::Vector2f position_player, std::shared_ptr<Player> player, float duration_boost_received, float value_received) { position_ablaze_the_fire_box = sf::Vector2f(35, -30); sf::Vector2f position_holder = sf::Vector2f(position_ablaze_the_fire_box.x + position_player.x, position_ablaze_the_fire_box.y + position_player.y); sprite = GlobalFunction::CreateSprite(position_holder, size_ablaze_the_fire_box, texture_ablaze_the_fire_box); been_init = true; duration_boost = duration_boost_received; player->GivePlayerChangeStat(type_of_the_box, duration_boost_received, value_received); } bool AttackDamageBox::IsNeedToDelete() { CheckToDelete(); return to_delete; } void AttackDamageBox::Initialized(int player_id_received, int type_box) { player_id = player_id_received; type_of_the_box = type_box; } void AttackDamageBox::Update(float DELTATIME, sf::Vector2f player_position) { sprite.setPosition(sf::Vector2f(player_position.x + position_ablaze_the_fire_box.x, player_position.y + position_ablaze_the_fire_box.y)); } void AttackDamageBox::CheckToDelete() { if (clock_timer_box_created.getElapsedTime().asSeconds() >= duration_boost) { to_delete = true; } } int AttackDamageBox::GetTypeBox() { return type_of_the_box; } sf::Vector2f AttackDamageBox::GetCurrentPosition() { return sprite.getPosition(); } void AttackDamageBox::Draw(sf::RenderWindow &window) { window.draw(sprite); }
ethanqtle/C_4_Everyone_Fund
ABC4/ch09/05_poker/swap.c
#include "poker.h" void swap(card *p, card *q) { card tmp; tmp = *p; *p = *q; *q = tmp; }
janlt/daqdb
lib/spdk/SpdkCore.cpp
/** * Copyright (c) 2019 Intel Corporation * * 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. */ #include <signal.h> #include <atomic> #include <chrono> #include <condition_variable> #include <cstdint> #include <iostream> #include <mutex> #include <pthread.h> #include <sstream> #include <string> #include <thread> #include <boost/filesystem.hpp> #include "spdk/conf.h" #include "spdk/cpuset.h" #include "spdk/env.h" #include "spdk/event.h" #include "spdk/ftl.h" #include "spdk/log.h" #include "spdk/queue.h" #include "spdk/stdinc.h" #include "spdk/thread.h" #include <daqdb/Options.h> #include "Poller.h" #include "Rqst.h" #include "SpdkBdevFactory.h" #include "SpdkCore.h" #include <Logger.h> #include <RTree.h> namespace DaqDB { const char *SpdkCore::spdkHugepageDirname = "/mnt/huge_1GB"; SpdkCore::SpdkCore(OffloadOptions _offloadOptions) : state(SpdkState::SPDK_INIT), offloadOptions(_offloadOptions), poller(0), _spdkThread(0), _loopThread(0), _ready(false), _cpuCore(1), _spdkConf(offloadOptions) { removeConfFile(); bool conf_file_ok = createConfFile(); spBdev = SpdkBdevFactory::getBdev(offloadOptions.devType); spBdev->enableStats(true); if (conf_file_ok == false) { if (spdkEnvInit() == false) state = SpdkState::SPDK_ERROR; else state = SpdkState::SPDK_READY; dynamic_cast<SpdkBdev *>(spBdev)->state = SpdkBdevState::SPDK_BDEV_NOT_FOUND; } else state = SpdkState::SPDK_READY; } SpdkCore::~SpdkCore() { if (_spdkThread != nullptr) _spdkThread->join(); } bool SpdkCore::spdkEnvInit(void) { spdk_env_opts opts; spdk_env_opts_init(&opts); opts.name = SPDK_APP_ENV_NAME.c_str(); /* * SPDK will use 1G huge pages when mem_size is 1024 */ opts.mem_size = 1024; opts.shm_id = 0; return (spdk_env_init(&opts) == 0); } bool SpdkCore::createConfFile(void) { if (!bf::exists(DEFAULT_SPDK_CONF_FILE)) { if (isNvmeInOptions()) { ofstream spdkConf(DEFAULT_SPDK_CONF_FILE, ios::out); if (spdkConf) { switch (offloadOptions.devType) { case OffloadDevType::BDEV: assert(offloadOptions._devs.size() == 1); spdkConf << "[Nvme]" << endl << " TransportID \"trtype:PCIe traddr:" << offloadOptions._devs[0].nvmeAddr << "\" " << offloadOptions._devs[0].nvmeName << endl; spdkConf.close(); break; case OffloadDevType::JBOD: spdkConf << "[Nvme]" << endl; for (auto b : offloadOptions._devs) { spdkConf << " TransportID \"trtype:PCIe traddr:" << b.nvmeAddr << "\" " << b.nvmeName << endl; } spdkConf.close(); break; case OffloadDevType::RAID0: std::cout << "RAID0 bdev configuration not supported yet" << std::endl; break; } DAQ_DEBUG("SPDK configuration file created"); return true; } else { DAQ_DEBUG("Cannot create SPDK configuration file"); return false; } } else { DAQ_DEBUG( "SPDK configuration file creation skipped - no NVMe device"); return false; } } else { DAQ_DEBUG("SPDK configuration file creation skipped"); return true; } } void SpdkCore::removeConfFile(void) { if (bf::exists(DEFAULT_SPDK_CONF_FILE)) { bf::remove(DEFAULT_SPDK_CONF_FILE); } } void SpdkCore::restoreSignals() { ::signal(SIGTERM, SIG_DFL); ::signal(SIGINT, SIG_DFL); ::signal(SIGSEGV, SIG_DFL); } /* * Start up Spdk, including SPDK thread, to initialize SPDK environemnt and a * Bdev */ void SpdkCore::startSpdk() { _spdkThread = new std::thread(&SpdkCore::_spdkThreadMain, this); DAQ_DEBUG("SpdkCore thread started"); if (_cpuCore) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(_cpuCore, &cpuset); const int set_result = pthread_setaffinity_np( _spdkThread->native_handle(), sizeof(cpu_set_t), &cpuset); if (!set_result) { DAQ_DEBUG("SpdkCore thread affinity set on CPU core [" + std::to_string(_cpuCore) + "]"); } else { DAQ_DEBUG("Cannot set affinity on CPU core [" + std::to_string(_cpuCore) + "] for OffloadReactor"); } } } /* * Callback function called by SPDK spdk_app_start in the context of an SPDK * thread. */ void SpdkCore::spdkStart(void *arg) { SpdkCore *spdkCore = reinterpret_cast<SpdkCore *>(arg); SpdkDevice *bdev = spdkCore->spBdev; SpdkBdevCtx *bdev_c = bdev->getBdevCtx(); bool rc = bdev->init(spdkCore->_spdkConf); if (rc == false) { DAQ_CRITICAL("Bdev init failed"); spdkCore->signalReady(); spdk_app_stop(-1); return; } bdev->setMaxQueued(bdev->getIoCacheSize(), bdev->getBlockSize()); auto aligned = bdev->getAlignedSize(spdkCore->offloadOptions.allocUnitSize); bdev->setBlockNumForLba(aligned / bdev_c->blk_size); spdkCore->poller->initFreeList(); bdev->initFreeList(); bool i_rc = spdkCore->poller->init(); if (i_rc == false) { DAQ_CRITICAL("Poller init failed"); spdkCore->signalReady(); spdk_app_stop(-1); return; } bdev->setRunning(1); spdkCore->poller->setRunning(1); bdev->setReady(); spdkCore->signalReady(); spdkCore->restoreSignals(); spdk_unaffinitize_thread(); for (;;) { if (SpdkCore::spdkCoreMainLoop(spdkCore) > 0) break; } } void SpdkCore::_spdkThreadMain(void) { struct spdk_app_opts daqdb_opts = {}; spdk_app_opts_init(&daqdb_opts); daqdb_opts.config_file = DEFAULT_SPDK_CONF_FILE.c_str(); daqdb_opts.name = "daqdb_nvme"; int rc = spdk_app_start(&daqdb_opts, SpdkCore::spdkStart, this); if (rc) { DAQ_CRITICAL("Error spdk_app_start[" + std::to_string(rc) + "]"); return; } DAQ_DEBUG("spdk_app_start[" + std::to_string(rc) + "]"); spdk_app_fini(); } int SpdkCore::spdkCoreMainLoop(SpdkCore *spdkCore) { Poller<OffloadRqst> *poller = spdkCore->poller; SpdkDevice *bdev = spdkCore->spBdev; poller->dequeue(); poller->process(); if (poller->isOffloadRunning() == false) { bdev->deinit(); spdk_app_stop(0); bdev->setRunning(0); return 1; } return 0; } void SpdkCore::signalReady() { std::unique_lock<std::mutex> lk(_syncMutex); _ready = true; _cv.notify_all(); } bool SpdkCore::waitReady() { const std::chrono::milliseconds timeout(10000); std::unique_lock<std::mutex> lk(_syncMutex); _cv.wait_for(lk, timeout, [this] { return _ready; }); return _ready; } } // namespace DaqDB
tsirif/cortex
cortex/_lib/__init__.py
<reponame>tsirif/cortex '''Cortex setup ''' import copy import glob import logging import os import pprint from . import config, exp, log_utils, models from .parsing import default_args, parse_args, update_args from .viz import init as viz_init __author__ = '<NAME>' __author_email__ = '<EMAIL>' logger = logging.getLogger('cortex.init') def setup_cortex(model=None): '''Sets up cortex Finds all the models in cortex, parses the command line, and sets the logger. Returns: TODO ''' args = parse_args(models.MODEL_PLUGINS, model=model) log_utils.set_stream_logger(args.verbosity) return args def find_autoreload(out_path, global_out_path, name): out_path = out_path or global_out_path out_path = os.path.join(out_path, name) binary_dir = os.path.join(out_path, 'binaries') binaries = glob.glob(os.path.join(binary_dir, '*.t7')) binaries.sort(key=os.path.getmtime) if len(binaries) > 0: return binaries[-1] else: logger.warning('No model found to auto-reload') return None def setup_experiment(args, model=None, testmode=False): '''Sets up the experiment Args: args: TODO ''' def update_nested_dicts(from_d, to_d): for k, v in from_d.items(): if (k in to_d) and isinstance(to_d[k], dict): if not isinstance(v, dict): raise ValueError('Updating dict entry with non-dict.') update_nested_dicts(v, to_d[k]) else: to_d[k] = v exp.setup_device(args.device) if model is None: model_name = args.command model = models.get_model(model_name) else: model_name = model.__class__.__name__ experiment_args = copy.deepcopy(default_args) update_args(experiment_args, exp.ARGS) if not testmode: viz_init(config.CONFIG.viz) for k, v in vars(args).items(): if v is not None: if '.' in k: head, tail = k.split('.') elif k in model.kwargs: head = 'model' tail = k else: continue exp.ARGS[head][tail] = v reload_nets = None if args.autoreload: reload_path = find_autoreload(args.out_path, config.CONFIG.out_path, args.name or model_name) elif args.reload: reload_path = args.reload else: reload_path = None if reload_path: d = exp.reload_model(reload_path) exp.INFO.update(**d['info']) exp.NAME = exp.INFO['name'] exp.SUMMARY.update(**d['summary']) update_nested_dicts(d['args'], exp.ARGS) if args.name: exp.INFO['name'] = exp.NAME if args.out_path or args.name: exp.setup_out_dir(args.out_path, config.CONFIG.out_path, exp.NAME, clean=args.clean) else: exp.OUT_DIRS.update(**d['out_dirs']) reload_nets = d['nets'] else: if args.load_networks: d = exp.reload_model(args.load_networks) keys = args.networks_to_reload or d['nets'] for key in keys: if key not in d['nets']: raise KeyError('Model {} has no network called {}' .format(args.load_networks, key)) reload_nets = dict((k, d['nets'][k]) for k in keys) exp.NAME = args.name or model_name exp.INFO['name'] = exp.NAME exp.setup_out_dir(args.out_path, config.CONFIG.out_path, exp.NAME, clean=args.clean) update_nested_dicts(exp.ARGS['model'], model.kwargs) exp.ARGS['model'].update(**model.kwargs) exp.configure_from_yaml(config_file=args.config_file) for k, v in exp.ARGS.items(): logger.info('Ultimate {} arguments: \n{}' .format(k, pprint.pformat(v))) return model, reload_nets
lostdragon/cobar
cobar-server/src/main/java/com/alibaba/cobar/CobarStartup.java
/* * Copyright 1999-2012 Alibaba Group. * * 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 com.alibaba.cobar; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.helpers.LogLog; /** * @author xianmao.hexm 2011-4-22 下午09:43:05 */ public final class CobarStartup { private static final String dateFormat = "yyyy-MM-dd HH:mm:ss"; public static void main(String[] args) { try { // init CobarServer server = CobarServer.getInstance(); server.beforeStart(dateFormat); // startup server.startup(); } catch (Throwable e) { SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); LogLog.error(sdf.format(new Date()) + " startup error", e); System.exit(-1); } } }
keymetrics/origa
test/plugins/test-trace-pg.js
<reponame>keymetrics/origa /** * Copyright 2017 Google Inc. All Rights Reserved. * * 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. */ 'use strict'; var common = require('./common.js'); var traceLabels = require('../../src/trace-labels.js'); var assert = require('assert'); describe('test-trace-pg', function() { var traceApi; var pool; var client; var releaseClient; before(function() { traceApi = require('../..').start({ samplingRate: 0, enhancedDatabaseReporting: true }); var pg = require('./fixtures/pg6'); pool = new pg.Pool(require('../pg-config.js')); }); beforeEach(function(done) { pool.connect(function(err, c, release) { client = c; releaseClient = release; assert(!err); client.query('CREATE TABLE t (name text NOT NULL, id text NOT NULL)', [], function(err, res) { assert(!err); common.cleanTraces(traceApi); done(); }); }); }); afterEach(function(done) { client.query('DROP TABLE t', [], function(err, res) { assert(!err); releaseClient(); common.cleanTraces(traceApi); done(); }); }); it('should perform basic operations', function(done) { common.runInTransaction(traceApi, function(endRootSpan) { client.query('INSERT INTO t (name, id) VALUES($1, $2)', ['test_name', 'test_id'], function(err, res) { endRootSpan(); assert(!err); var span = common.getMatchingSpan(traceApi, function (span) { return span.name === 'pg-query'; }); assert.equal(span.labels.query, 'INSERT INTO t (name, id) VALUES($1, $2)'); assert.equal(span.labels.values, '[ \'test_name\', \'test_id\' ]'); assert.equal(span.labels.row_count, '1'); assert.equal(span.labels.oid, '0'); assert.equal(span.labels.rows, '[]'); assert.equal(span.labels.fields, '[]'); done(); }); }); }); it('should remove trace frames from stack', function(done) { common.runInTransaction(traceApi, function(endRootSpan) { client.query('SELECT $1::int AS number', [1], function(err, res) { endRootSpan(); assert(!err); var span = common.getMatchingSpan(traceApi, function (span) { return span.name === 'pg-query'; }); var labels = span.labels; var stackTrace = JSON.parse(labels[traceLabels.STACK_TRACE_DETAILS_KEY]); // Ensure that our patch is on top of the stack assert( stackTrace.stack_frame[0].method_name.indexOf('query_trace') !== -1); done(); }); }); }); it('should work with events', function(done) { common.runInTransaction(traceApi, function(endRootSpan) { var query = client.query('SELECT $1::int AS number', [1]); query.on('row', function(row) { assert.strictEqual(row.number, 1); }); query.on('end', function() { endRootSpan(); var span = common.getMatchingSpan(traceApi, function (span) { return span.name === 'pg-query'; }); assert.equal(span.labels.query, 'SELECT $1::int AS number'); assert.equal(span.labels.values, '[ \'1\' ]'); done(); }); }); }); it('should work without events or callback', function(done) { common.runInTransaction(traceApi, function(endRootSpan) { client.query('SELECT $1::int AS number', [1]); setTimeout(function() { endRootSpan(); var span = common.getMatchingSpan(traceApi, function (span) { return span.name === 'pg-query'; }); assert.equal(span.labels.query, 'SELECT $1::int AS number'); assert.equal(span.labels.values, '[ \'1\' ]'); done(); }, 50); }); }); });
wibeasley/jbc-2016
1407-wallaby/KISS/Default User/omdanceparty/src/main.c
#include <kipr/botball.h> int main() { printf("Hello World\n"); printf("moving motors forward\n"); // start at -1 k motor(0,58); motor(3,50); msleep(1900); ao(); printf("moves servo 0 up\n"); enable_servos(0); set_servo_position(0,424); msleep(2001); disable_servos(0); printf("moves motors 360 degrees clockwise\n"); motor(0,-68); motor(3,60); msleep(5500); printf("moves motors 360 degrees couterclockwise\n"); motor(0,68); motor(3,-60); msleep(5500); ao(); printf("moves servo 0 down\n"); enable_servo(0); set_servo_position(0,1531); msleep(2500); disable_servos(0); printf("moves motors backwards\n"); motor(0,-58); motor(3,-50); msleep(1900); return 0; }
BigPapaChas/veneur
util/url.go
package util import ( "encoding/json" "net/url" ) type Url struct { Value *url.URL } func (u Url) MarshalJSON() ([]byte, error) { if u.Value == nil { return json.Marshal(nil) } return json.Marshal(u.Value.String()) } func (u Url) MarshalYAML() (interface{}, error) { if u.Value == nil { return "", nil } return u.Value.String(), nil } func (u *Url) UnmarshalYAML(unmarshal func(interface{}) error) error { var s string err := unmarshal(&s) if err != nil { return err } u.Value, err = url.Parse(s) return err } func (u *Url) Decode(s string) error { var err error u.Value, err = url.Parse(s) return err }
mikebrachmann/gprom
src/utility/sort_helpers.c
/*----------------------------------------------------------------------------- * * sort_helpers.c * * * AUTHOR: lord_pretzel * * * *----------------------------------------------------------------------------- */ #include "common.h" #include "model/expression/expression.h" #include "utility/sort_helpers.h" int compareConstInt (const Constant *c1, const Constant *c2) { int lV = INT_VALUE(c1); int rV = INT_VALUE(c2); return rV - lV; }
mythoss/midpoint
testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/authentication/TestOidcRestAuthByHMacModule.java
<gh_stars>0 /* * Copyright (c) 2016-2022 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.testing.rest.authentication; import com.evolveum.midpoint.common.rest.MidpointAbstractProvider; import com.evolveum.midpoint.common.rest.MidpointJsonProvider; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.testing.rest.RestServiceInitializer; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.apache.cxf.jaxrs.client.WebClient; import org.keycloak.authorization.client.AuthzClient; import org.keycloak.representations.AccessTokenResponse; import org.springframework.beans.factory.annotation.Autowired; import org.testng.annotations.Test; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.File; import java.io.FileInputStream; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; public class TestOidcRestAuthByHMacModule extends TestAbstractOidcRestModule { private static final File KEYCLOAK_HMAC_CONFIGURATION = new File(BASE_AUTHENTICATION_DIR, "keycloak-hmac.json"); @Autowired protected MidpointJsonProvider jsonProvider; private AuthzClient authzClient; @Override protected String getAcceptHeader() { return MediaType.APPLICATION_JSON; } @Override protected String getContentType() { return MediaType.APPLICATION_JSON; } @Override protected MidpointAbstractProvider getProvider() { return jsonProvider; } @Override public void initSystem(Task initTask, OperationResult result) throws Exception { super.initSystem(initTask, result); authzClient = AuthzClient.create(new FileInputStream(KEYCLOAK_HMAC_CONFIGURATION)); } public AuthzClient getAuthzClient() { return authzClient; } protected void assertForAuthByPublicKey(Response response) { assertUnsuccess(response); } @Override protected void assertForAuthByHMac(Response response) { assertSuccess(response); } }
KevinLu/pops
tools/spotters/vultr.js
import _ from "lodash"; import { chromium, firefox, webkit } from "playwright"; import toTelegram from "./lib/telegram.js"; import provider from "../../data/providers/vultr.js"; const asset = "vultr"; const spotter = async () => { const browser = await webkit.launch(); const page = await browser.newPage(); await page.goto("https://status.vultr.com/"); const data = await page.$eval( "body > div.site > section > div > div.box.box--lg.box--table.m-w-md > div > div > table > tbody", e => e.innerHTML ); browser.close(); return data; }; spotter() .then(value => value.match(/dist\/img\/flags/gm)) .then(x => { if (x.length === provider.pops.length) { console.log(`${asset}:success`); } else { toTelegram(asset); console.log(`${asset}:fail`); } });
scottwestover/intro-to-javascript-course
30 - scope/start/main.js
// scope
plzombie/ne
nyan/nyan_mem.h
<reponame>plzombie/ne /* Файл : nyan_mem.h Описание: Заголовок для nyan_mem.c История : 18.08.12 Создан */
shaojiankui/iOS10-Runtime-Headers
Frameworks/NetworkExtension.framework/NEIKEv2Rekey.h
<filename>Frameworks/NetworkExtension.framework/NEIKEv2Rekey.h /* Generated by RuntimeBrowser Image: /System/Library/Frameworks/NetworkExtension.framework/NetworkExtension */ @interface NEIKEv2Rekey : NSObject <NSObject> { PCSimpleTimer * _childLifetime; int _childLifetimeMinutes; id /* block */ _childRekeyHandler; PCSimpleTimer * _ikeLifetime; int _ikeLifetimeMinutes; id /* block */ _ikeRekeyHandler; } @property (retain) PCSimpleTimer *childLifetime; @property int childLifetimeMinutes; @property (copy) id /* block */ childRekeyHandler; @property (readonly, copy) NSString *debugDescription; @property (readonly, copy) NSString *description; @property (readonly) unsigned long long hash; @property (retain) PCSimpleTimer *ikeLifetime; @property int ikeLifetimeMinutes; @property (copy) id /* block */ ikeRekeyHandler; @property (readonly) Class superclass; - (void).cxx_destruct; - (id)childLifetime; - (int)childLifetimeMinutes; - (id /* block */)childRekeyHandler; - (void)clearTimers; - (void)dealloc; - (id)ikeLifetime; - (int)ikeLifetimeMinutes; - (id /* block */)ikeRekeyHandler; - (void)invokeChildRekeyHandler; - (void)invokeIKERekeyHandler; - (void)setChildLifetime:(id)arg1; - (void)setChildLifetimeMinutes:(int)arg1; - (void)setChildRekeyHandler:(id /* block */)arg1; - (void)setIkeLifetime:(id)arg1; - (void)setIkeLifetimeMinutes:(int)arg1; - (void)setIkeRekeyHandler:(id /* block */)arg1; - (void)startChildTimer:(int)arg1 timeoutHandler:(id /* block */)arg2; - (void)startIKETimer:(int)arg1 timeoutHandler:(id /* block */)arg2; @end
liuchao1986105/lambda-react
src/components/ShareButtons/index.js
<reponame>liuchao1986105/lambda-react import React,{Component,PropTypes} from 'react' import _ from 'lodash' import QRCode from 'qrcode.react' import "./sharebuttons.scss" export default class ShareButtons extends Component{ static propTypes = { url: PropTypes.string, title: PropTypes.string, description: PropTypes.string, sites: PropTypes.array, } render(){ const wechatQrcodeTitle = '微信扫一扫:分享' const {url, title, description, sites} = this.props const source = title const summary = description const image = '' const templates = { qq: `http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${url}&title=${title}&desc=${description}&summary=${summary}&site=${source}`, //qzone //qq: `http://connect.qq.com/widget/shareqq/index.html?url=${url}&title=${title}&source=${source}&desc=${description}`, weibo: `http://service.weibo.com/share/share.php?url=${url}&title=${title}&pic=${image}`, wechat: `javascript:`, douban: `http://shuo.douban.com/!service/share?href=${url}&name=${title}&text=${description}&image=${image}&starid=0&aid=0&style=11`, //linkedin: `http://www.linkedin.com/shareArticle?mini=true&ro=true&title=${title}&url=${url}&summary=${summary}&source=${source}&armin=armin`, //facebook: `https://www.facebook.com/sharer/sharer.php?u=${url}`, //twitter: `https://twitter.com/intent/tweet?text=${title}&url=${url}&via=${origin}`, //google: `https://plus.google.com/share?url=${url}` }; let html = _.map(sites, function (site, i) { if(site === "wechat"){ let doc = <div key={i} className='wechat-qrcode'> <h4>{wechatQrcodeTitle}</h4> <div className='qrcode'> <QRCode value={url} size={100} /> </div> </div> return ( <a key={i} className='share_title icon-wechat' target='_blank' href='javascript:'> <i className='fa fa-wechat'></i>{doc} </a> ) } else { let className = `fa fa-${site}` let iconClassName = `icon-${site}` if(site === "qq"){ return ( <a key={i} title='分享到QQ空间' className={'share_title ' + iconClassName} href={templates[site]} target="_blank"><i className={className} ></i></a> ) }else{ return ( <a key={i} title='分享到微博' className={'share_title ' + iconClassName} href={templates[site]} target="_blank"><i className={className} ></i></a> ) } } }) return ( <span className="social-share"> <span className="share_title">分享</span> {html} </span> ) } }
FraunhoferFITWirtschaftsinformatik/SmarDeSatWork
smardes-middleware/base/smardes-common/src/main/java/com/camline/projects/smardes/common/el/PedanticMapELResolver.java
/******************************************************************************* * Copyright (C) 2018-2019 camLine GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.camline.projects.smardes.common.el; import java.util.Map; import javax.el.ELContext; import javax.el.MapELResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A variant of MapELResolver which logs a warning if a non-existing property is accessed. * * @author matze * */ public class PedanticMapELResolver extends MapELResolver { private static final Logger logger = LoggerFactory.getLogger(PedanticMapELResolver.class); public PedanticMapELResolver() { super(); } public PedanticMapELResolver(boolean readOnly) { super(readOnly); } @SuppressWarnings("unlikely-arg-type") @Override public Object getValue(ELContext context, Object base, Object property) { Object result = super.getValue(context, base, property); if (result == null && context.isPropertyResolved() && !((Map<?, ?>) base).containsKey(property)) { logger.warn("Unknown EL property {}. Resolve to null", property); } return result; } }
jonogillettt/react-habitat
tests/index.spec.js
<reponame>jonogillettt/react-habitat<gh_stars>100-1000 /** * Copyright 2016-present, Deloitte Digital. * All rights reserved. * * This source code is licensed under the BSD-3-Clause license found in the * LICENSE file in the root directory of this source tree. */ import ReactHabitat from '../src'; import Bootstrapper from '../src/Bootstrapper'; import Container from '../src/Container'; import { createBootstrapper, _Mixin } from '../src/classic/createBootstrapper'; describe('Habitat API', () => { it('resolves a bootstrapper', () => { expect(ReactHabitat.Bootstrapper).toEqual(Bootstrapper); }); it('resolves a container', () => { expect(ReactHabitat.Container).toEqual(Container); }); it('resolves a classic mixin', () => { expect(ReactHabitat.createBootstrapper).toEqual(createBootstrapper); }); });
yaowfhhuc/dist
dist-task/src/test/java/me/test/dist/task/AsynchonousTaskTest.java
package me.test.dist.task; import me.test.dist.task.asynchronous.AsynchonousCallback; import me.test.dist.task.asynchronous.AsynchronousTask; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.concurrent.Future; @SpringBootTest(classes = Application.class) @RunWith(SpringRunner.class) public class AsynchonousTaskTest { @Autowired AsynchronousTask asynchronousTask; @Autowired AsynchonousCallback asynchonousCallback; @Test public void TestAsynchonous() throws Exception{ asynchronousTask.doTaskOne(); asynchronousTask.doTaskTwo(); asynchronousTask.doTaskThree(); } @Test public void TestAsynchonousCallBack() throws Exception { long start = System.currentTimeMillis(); Future<String> task1 = asynchonousCallback.doTaskOne(); Future<String> task2 = asynchonousCallback.doTaskTwo(); Future<String> task3 = asynchonousCallback.doTaskThree(); while(true) { if(task1.isDone() && task2.isDone() && task3.isDone()) { // 三个任务都调用完成,退出循环等待 break; } Thread.sleep(1000); } long end = System.currentTimeMillis(); System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒"); } }
marcomarasca/SynapseWebClient
src/main/java/org/sagebionetworks/web/client/widget/entity/tabs/AbstractTablesTab.java
<gh_stars>10-100 package org.sagebionetworks.web.client.widget.entity.tabs; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import org.sagebionetworks.repo.model.Entity; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.entitybundle.v2.EntityBundle; import org.sagebionetworks.repo.model.table.Dataset; import org.sagebionetworks.repo.model.table.Query; import org.sagebionetworks.web.client.DisplayUtils; import org.sagebionetworks.web.client.EntityTypeUtils; import org.sagebionetworks.web.client.PortalGinInjector; import org.sagebionetworks.web.client.events.EntityUpdatedEvent; import org.sagebionetworks.web.client.place.Synapse; import org.sagebionetworks.web.client.place.Synapse.EntityArea; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.breadcrumb.Breadcrumb; import org.sagebionetworks.web.client.widget.breadcrumb.LinkData; import org.sagebionetworks.web.client.widget.entity.EntityMetadata; import org.sagebionetworks.web.client.widget.entity.ModifiedCreatedByWidget; import org.sagebionetworks.web.client.widget.entity.WikiPageWidget; import org.sagebionetworks.web.client.widget.entity.controller.EntityActionControllerImpl; import org.sagebionetworks.web.client.widget.entity.controller.StuAlert; import org.sagebionetworks.web.client.widget.entity.file.BasicTitleBar; import org.sagebionetworks.web.client.widget.provenance.ProvenanceWidget; import org.sagebionetworks.web.client.widget.table.QueryChangeHandler; import org.sagebionetworks.web.client.widget.table.TableListWidget; import org.sagebionetworks.web.client.widget.table.v2.QueryTokenProvider; import org.sagebionetworks.web.client.widget.table.v2.TableEntityWidget; import org.sagebionetworks.web.client.widget.table.v2.results.QueryBundleUtils; import org.sagebionetworks.web.shared.WidgetConstants; import org.sagebionetworks.web.shared.WikiPageKey; import com.google.gwt.place.shared.Place; import com.google.inject.Inject; /** * Encapsulates shared logic between tabs that show tables. * Currently, we show Datasets and Tables/EntityViews/SubmissionViews in two different tabs. */ public abstract class AbstractTablesTab implements TablesTabView.Presenter, QueryChangeHandler { public static final String TABLE_QUERY_PREFIX = "query/"; Tab tab; TablesTabView view; TableListWidget tableListWidget; BasicTitleBar titleBar; Breadcrumb breadcrumb; EntityMetadata metadata; QueryTokenProvider queryTokenProvider; EntityBundle projectBundle; EntityBundle entityBundle; Throwable projectBundleLoadError; String projectEntityId; String areaToken; StuAlert synAlert; PortalGinInjector ginInjector; ModifiedCreatedByWidget modifiedCreatedBy; TableEntityWidget v2TableWidget; Map<String, String> configMap; CallbackP<String> entitySelectedCallback; Long version; WikiPageWidget wikiPageWidget; protected abstract EntityArea getTabArea(); protected abstract String getTabDisplayName(); protected abstract List<EntityType> getTypesShownInList(); protected abstract boolean isEntityShownInTab(Entity entity); @Inject public AbstractTablesTab(Tab tab, PortalGinInjector ginInjector) { this.tab = tab; this.ginInjector = ginInjector; } public void configure(EntityBundle entityBundle, Long versionNumber, String areaToken) { lazyInject(); this.areaToken = areaToken; synAlert.clear(); setTargetBundle(entityBundle, versionNumber); } protected CallbackP<EntityHeader> getTableListWidgetClickedCallback() { return entityHeader -> { areaToken = null; entitySelectedCallback.invoke(entityHeader.getId()); // selected a table/view, show title info immediately titleBar.configure(entityHeader); List<LinkData> links = new ArrayList<>(); Place projectPlace = new Synapse(projectEntityId, null, getTabArea(), null); links.add(new LinkData(getTabDisplayName(), EntityTypeUtils.getEntityType(entityHeader), projectPlace)); breadcrumb.configure(links, entityHeader.getName()); view.setTitle(getTabDisplayName()); view.setBreadcrumbVisible(true); view.setTitlebarVisible(true); }; } public void lazyInject() { if (view == null) { this.view = ginInjector.getTablesTabView(); this.tableListWidget = ginInjector.getTableListWidget(); this.titleBar = ginInjector.getBasicTitleBar(); this.breadcrumb = ginInjector.getBreadcrumb(); this.metadata = ginInjector.getEntityMetadata(); this.queryTokenProvider = ginInjector.getQueryTokenProvider(); this.synAlert = ginInjector.getStuAlert(); this.modifiedCreatedBy = ginInjector.getModifiedCreatedByWidget(); this.wikiPageWidget = ginInjector.getWikiPageWidget(); view.setTitle(getTabDisplayName()); view.setBreadcrumb(breadcrumb.asWidget()); view.setTableList(tableListWidget.asWidget()); view.setTitlebar(titleBar.asWidget()); view.setEntityMetadata(metadata.asWidget()); view.setSynapseAlert(synAlert.asWidget()); view.setModifiedCreatedBy(modifiedCreatedBy); view.setWikiPage(wikiPageWidget.asWidget()); tab.setContent(view.asWidget()); tableListWidget.setTableClickedCallback(getTableListWidgetClickedCallback()); initBreadcrumbLinkClickedHandler(); configMap = ProvenanceWidget.getDefaultWidgetDescriptor(); } } public void setEntitySelectedCallback(CallbackP<String> entitySelectedCallback) { this.entitySelectedCallback = entitySelectedCallback; } public void initBreadcrumbLinkClickedHandler() { CallbackP<Place> breadcrumbClicked = place -> { // if this is the project id, then just reconfigure from the project bundle Synapse synapse = (Synapse) place; String entityId = synapse.getEntityId(); entitySelectedCallback.invoke(entityId); }; breadcrumb.setLinkClickedHandler(breadcrumbClicked); } public void setTabClickedCallback(CallbackP<Tab> onClickCallback) { tab.addTabClickedCallback(onClickCallback); } public void setProject(String projectEntityId, EntityBundle projectBundle, Throwable projectBundleLoadError) { this.projectEntityId = projectEntityId; this.projectBundle = projectBundle; this.projectBundleLoadError = projectBundleLoadError; } public void resetView() { if (view != null) { synAlert.clear(); view.setEntityMetadataVisible(false); view.setBreadcrumbVisible(false); view.setTableListVisible(false); view.setTitlebarVisible(false); view.setWikiPageVisible(false); view.clearTableEntityWidget(); modifiedCreatedBy.setVisible(false); view.setTableUIVisible(false); } } public void showError(Throwable error) { resetView(); synAlert.handleException(error); } public Tab asTab() { return tab; } public void onQueryChange(Query newQuery) { if (newQuery != null && tab.isTabPaneVisible()) { String token = queryTokenProvider.queryToToken(newQuery); Long versionNumber = QueryBundleUtils.getTableVersion(newQuery.getSql()); String synId = QueryBundleUtils.getTableIdFromSql(newQuery.getSql()); if (token != null && !newQuery.equals(v2TableWidget.getDefaultQuery())) { areaToken = TABLE_QUERY_PREFIX + token; } else { areaToken = ""; } updateVersionAndAreaToken(synId, versionNumber, areaToken); tab.showTab(true); } } public Query getQueryString() { if (areaToken != null && areaToken.startsWith(TABLE_QUERY_PREFIX)) { String token = areaToken.substring(TABLE_QUERY_PREFIX.length()); return queryTokenProvider.tokenToQuery(token); } return null; } @Override public void onPersistSuccess(EntityUpdatedEvent event) { ginInjector.getEventBus().fireEvent(event); } protected void updateVersionAndAreaToken(String entityId, Long versionNumber, String areaToken) { boolean isVersionSupported = EntityActionControllerImpl.isVersionSupported(entityBundle.getEntity(), ginInjector.getCookieProvider()); Long newVersion = isVersionSupported ? versionNumber : null; Synapse newPlace = new Synapse(entityId, newVersion, getTabArea(), areaToken); // SWC-4942: if versions are supported, and the version has changed (the version in the query does // not match the entity bundle, for example), // then reload the entity bundle (to reconfigure the tools menu and other widgets on the page) by // doing a place change to the correct version of the bundle. if ((isVersionSupported && !Objects.equals(newVersion, version)) || !entityId.equals(entityBundle.getEntity().getId())) { ginInjector.getGlobalApplicationState().getPlaceChanger().goTo(newPlace); return; } metadata.configure(entityBundle, newVersion, tab.getEntityActionMenu()); tab.setEntityNameAndPlace(entityBundle.getEntity().getName(), newPlace); configMap.put(WidgetConstants.PROV_WIDGET_DISPLAY_HEIGHT_KEY, Integer.toString(FilesTab.WIDGET_HEIGHT_PX - 84)); configMap.put(WidgetConstants.PROV_WIDGET_ENTITY_LIST_KEY, DisplayUtils.createEntityVersionString(entityId, newVersion)); ProvenanceWidget provWidget = ginInjector.getProvenanceRenderer(); view.setProvenance(provWidget); provWidget.configure(configMap); version = newVersion; } public void showProjectLevelUI() { String title = projectEntityId; if (projectBundle != null) { title = projectBundle.getEntity().getName(); } else { showError(projectBundleLoadError); } tab.setEntityNameAndPlace(title, new Synapse(projectEntityId, null, getTabArea(), null)); tab.showTab(true); } public void setTargetBundle(EntityBundle bundle, Long versionNumber) { this.entityBundle = bundle; Entity entity = bundle.getEntity(); boolean isShownInTab = isEntityShownInTab(entity); boolean isDataset = entity instanceof Dataset; boolean isProject = entity instanceof Project; boolean isVersionSupported = EntityActionControllerImpl.isVersionSupported(entityBundle.getEntity(), ginInjector.getCookieProvider()); version = isVersionSupported ? versionNumber : null; view.setTitle(getTabDisplayName()); view.setEntityMetadataVisible(isShownInTab); view.setBreadcrumbVisible(isShownInTab); view.setTableListVisible(isProject); view.setTitlebarVisible(isShownInTab); view.clearTableEntityWidget(); modifiedCreatedBy.setVisible(false); view.setTableUIVisible(isShownInTab); view.setActionMenu(tab.getEntityActionMenu()); tab.getEntityActionMenu().setTableDownloadOptionsVisible(isShownInTab); boolean isCurrentVersion = version == null; if (isDataset && isCurrentVersion) { // SWC-5878 - On the current (non-snapshot) version of a dataset, only editors should be able to download tab.getEntityActionMenu().setTableDownloadOptionsEnabled(bundle.getPermissions().getCanCertifiedUserEdit()); } else { tab.getEntityActionMenu().setTableDownloadOptionsEnabled(true); } tab.configureEntityActionController(bundle, isCurrentVersion, null); if (isShownInTab) { final boolean canEdit = bundle.getPermissions().getCanCertifiedUserEdit(); updateVersionAndAreaToken(entity.getId(), version, areaToken); breadcrumb.configure(bundle.getPath(), getTabArea()); titleBar.configure(bundle); modifiedCreatedBy.configure(entity.getCreatedOn(), entity.getCreatedBy(), entity.getModifiedOn(), entity.getModifiedBy()); v2TableWidget = ginInjector.createNewTableEntityWidget(); view.setTableEntityWidget(v2TableWidget.asWidget()); v2TableWidget.configure(bundle, version, canEdit, this, tab.getEntityActionMenu()); // Configure wiki view.setWikiPageVisible(true); final WikiPageWidget.Callback wikiCallback = new WikiPageWidget.Callback() { @Override public void pageUpdated() { ginInjector.getEventBus().fireEvent(new EntityUpdatedEvent()); } @Override public void noWikiFound() { view.setWikiPageVisible(false); } }; wikiPageWidget.configure(new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), bundle.getRootWikiId(), versionNumber), canEdit, wikiCallback); CallbackP<String> wikiReloadHandler = new CallbackP<String>() { @Override public void invoke(String wikiPageId) { wikiPageWidget.configure(new WikiPageKey(entity.getId(), ObjectType.ENTITY.toString(), wikiPageId, versionNumber), canEdit, wikiCallback); } }; wikiPageWidget.setWikiReloadHandler(wikiReloadHandler); } else if (isProject) { areaToken = null; tableListWidget.configure(bundle, getTypesShownInList()); view.setWikiPageVisible(false); showProjectLevelUI(); } } }
RubenPX/django-orchestra
orchestra/contrib/webapps/backends/moodle.py
import os import textwrap from django.utils.translation import ugettext_lazy as _ from orchestra.contrib.orchestration import ServiceController, replace from .. import settings from . import WebAppServiceMixin class MoodleController(WebAppServiceMixin, ServiceController): """ Installs the latest version of Moodle available on download.moodle.org """ verbose_name = _("Moodle") model = 'webapps.WebApp' default_route_match = "webapp.type == 'moodle-php'" doc_settings = (settings, ('WEBAPPS_DEFAULT_MYSQL_DATABASE_HOST',) ) def save(self, webapp): context = self.get_context(webapp) self.append(textwrap.dedent("""\ if [[ $(ls "%(app_path)s" | wc -l) -gt 1 ]]; then echo "App directory not empty." 2> /dev/null exit 0 fi mkdir -p %(app_path)s # Prevent other backends from writting here touch %(app_path)s/.lock # Weekly caching moodle_date=$(date -r $(readlink %(cms_cache_dir)s/moodle) +%%s || echo 0) if [[ $moodle_date -lt $(($(date +%%s)-7*24*60*60)) ]]; then moodle_url=$(wget https://download.moodle.org/releases/latest/ -O - -q \\ | tr ' ' '\\n' \\ | grep 'moodle-latest.*.tgz"' \\ | sed -E 's#href="([^"]+)".*#\\1#' \\ | head -n 1 \\ | sed "s#download.php/#download.php/direct/#") filename=${moodle_url##*/} wget $moodle_url -O - --no-check-certificate \\ | tee %(cms_cache_dir)s/$filename \\ | tar -xzvf - -C %(app_path)s --strip-components=1 rm -f %(cms_cache_dir)s/moodle ln -s %(cms_cache_dir)s/$filename %(cms_cache_dir)s/moodle else tar -xzvf %(cms_cache_dir)s/moodle -C %(app_path)s --strip-components=1 fi mkdir %(app_path)s/moodledata && { chmod 750 %(app_path)s/moodledata echo -n 'order deny,allow\\ndeny from all' > %(app_path)s/moodledata/.htaccess } if [[ ! -e %(app_path)s/config.php ]]; then cp %(app_path)s/config-dist.php %(app_path)s/config.php sed -i "s#dbtype\s*= '.*#dbtype = '%(db_type)s';#" %(app_path)s/config.php sed -i "s#dbhost\s*= '.*#dbhost = '%(db_host)s';#" %(app_path)s/config.php sed -i "s#dbname\s*= '.*#dbname = '%(db_name)s';#" %(app_path)s/config.php sed -i "s#dbuser\s*= '.*#dbuser = '%(db_user)s';#" %(app_path)s/config.php sed -i "s#dbpass\s*= '.*#dbpass = '%(password)s';#" %(app_path)s/config.php sed -i "s#dataroot\s*= '.*#dataroot = '%(app_path)s/moodledata';#" %(app_path)s/config.php sed -i "s#wwwroot\s*= '.*#wwwroot = '%(www_root)s';#" %(app_path)s/config.php fi rm %(app_path)s/.lock chown -R %(user)s:%(group)s %(app_path)s # Run install moodle cli command on the background, because it takes so long... stdout=$(mktemp) stderr=$(mktemp) nohup su - %(user)s --shell /bin/bash << 'EOF' > $stdout 2> $stderr & php %(app_path)s/admin/cli/install_database.php \\ --fullname="%(site_name)s" \\ --shortname="%(site_name)s" \\ --adminpass="<PASSWORD>" \\ --adminemail="%(email)s" \\ --non-interactive \\ --agree-license \\ --allow-unstable EOF pid=$! sleep 2 if ! ps -p $pid > /dev/null; then cat $stdout cat $stderr >&2 exit_code=$(wait $pid) fi rm $stdout $stderr """) % context ) def get_context(self, webapp): context = super(MoodleController, self).get_context(webapp) contents = webapp.content_set.all() context.update({ 'db_type': 'mysqli', 'db_name': webapp.data['db_name'], 'db_user': webapp.data['db_user'], 'password': <PASSWORD>.data['password'], 'db_host': settings.WEBAPPS_DEFAULT_MYSQL_DATABASE_HOST, 'email': webapp.account.email, 'site_name': "%s Courses" % webapp.account.get_full_name(), 'cms_cache_dir': os.path.normpath(settings.WEBAPPS_CMS_CACHE_DIR), 'www_root': contents[0].website.get_absolute_url() if contents else 'http://empty' }) return replace(context, '"', "'")
spapulla/microgateway
kubernetes/edgemicroctl/samples/plugin/plugins/response-uppercase/index.js
module.exports.init = function(config, logger, stats) { return { ondata_response: function(req, res, data, next) { var transformed = data.toString().toUpperCase(); next(null, transformed); } }; }
honchardev/KPI
year_1/prog_base_sem2/labs/lab5/code/main.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include "../headers/socket.h" #include "../headers/http.h" #include "../headers/server.h" #include "../headers/list.h" #include "../headers/dbModule.h" #include "../headers/xmlModule.h" #ifndef TRUE #define TRUE 1 #endif // TRUE int main() { // Begin work with sockets. lib_init(); // Initialize server socket. socket_t *server = socket_new(); socket_bind(server, 5000); socket_listen(server); // Initialize database entity. db_t *directorsDB = database_new("src/data/Directors.db"); // Buffer for socket messages. char socketBuffer[10000] = "\0"; while(TRUE) { server_updateDirectorsXML(directorsDB); puts("Waiting for connection..."); // Get message from server. socket_t *client = socket_accept(server); socket_read(client, socketBuffer, sizeof(socketBuffer)); // Parse message from server to structure http_structure_t. http_request_t request = http_request_parse(socketBuffer); // Print formatted message from server. printf("Request method: %s\nRequest uri:%s\n", request.method, request.uri); puts(""); // Invoke certain http request method. if (!strcmp(request.method, "GET")) { server_analyzeGETRequest(&request, client, directorsDB); } else if (!strcmp(request.method, "DELETE")) { server_analyzeDELETERequest(&request, client, directorsDB); } else if (!strcmp(request.method, "POST")) { server_analyzePOSTRequest(&request, client, directorsDB); } else { http_sendHtml(client, "src/html/badhtmlrequest.html"); } socket_free(client); } // At the end of the program, free allocated memory; socket_free(server); lib_free(); return 0; }
Jean1dev/Especialista-JPA
iniciando-jpa/src/main/java/com/curso/model/NotaFiscal.java
<reponame>Jean1dev/Especialista-JPA package com.curso.model; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Lob; import javax.persistence.OneToOne; import java.util.Date; @Getter @Setter @Entity public class NotaFiscal extends EntidadeBaseInteger { @OneToOne private Pedido pedido; @Lob private byte[] xml; private Date dataEmissao; }
kangih90/egovAllinone
egovAllinone/src/main/java/egovframework/com/cop/cmt/service/impl/EgovArticleCommentServiceImpl.java
<gh_stars>1-10 package egovframework.com.cop.cmt.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import egovframework.com.cop.bbs.service.BoardMaster; import egovframework.com.cop.bbs.service.BoardMasterVO; import egovframework.com.cop.bbs.service.impl.BBSAddedOptionsDAO; import egovframework.com.cop.cmt.service.Comment; import egovframework.com.cop.cmt.service.CommentVO; import egovframework.com.cop.cmt.service.EgovArticleCommentService; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; import egovframework.rte.fdl.cmmn.exception.FdlException; import egovframework.rte.fdl.idgnr.EgovIdGnrService; @Service("EgovArticleCommentService") public class EgovArticleCommentServiceImpl extends EgovAbstractServiceImpl implements EgovArticleCommentService { @Resource(name = "BBSAddedOptionsDAO") private BBSAddedOptionsDAO addedOptionsDAO; @Resource(name = "EgovArticleCommentDAO") private EgovArticleCommentDAO egovArticleCommentDao; @Resource(name = "egovAnswerNoGnrService") private EgovIdGnrService egovAnswerNoGnrService; /** * 댓글 사용 가능 여부를 확인한다. */ public boolean canUseComment(String bbsId) throws Exception { //String flag = EgovProperties.getProperty("Globals.addedOptions"); //if (flag != null && flag.trim().equalsIgnoreCase("true")) {//2011.09.15 BoardMaster vo = new BoardMaster(); vo.setBbsId(bbsId); BoardMasterVO options = addedOptionsDAO.selectAddedOptionsInf(vo); if (options == null) { return false; } if (options.getCommentAt().equals("Y")) { return true; } //} return false; } @Override public Map<String, Object> selectArticleCommentList(CommentVO commentVO) { List<?> result = egovArticleCommentDao.selectArticleCommentList(commentVO); int cnt = egovArticleCommentDao.selectArticleCommentListCnt(commentVO); Map<String, Object> map = new HashMap<String, Object>(); map.put("resultList", result); map.put("resultCnt", Integer.toString(cnt)); return map; } @Override public void insertArticleComment(Comment comment) throws FdlException { comment.setCommentNo(egovAnswerNoGnrService.getNextLongId() + "");//2011.10.18 egovArticleCommentDao.insertArticleComment(comment); } @Override public void deleteArticleComment(CommentVO commentVO) { egovArticleCommentDao.deleteArticleComment(commentVO); } @Override public CommentVO selectArticleCommentDetail(CommentVO commentVO) { return egovArticleCommentDao.selectArticleCommentDetail(commentVO); } @Override public void updateArticleComment(Comment comment) { egovArticleCommentDao.updateArticleComment(comment); } }
gabehack/Pyro4
tests/PyroTests/testsupport.py
""" Support code for the test suite. There's some Python 2.x <-> 3.x compatibility code here. Pyro - Python Remote Objects. Copyright by <NAME> (<EMAIL>). """ import sys import pickle import Pyro4 __all__ = ["tobytes", "tostring", "unicode", "unichr", "basestring", "StringIO", "NonserializableError", "MyThingPartlyExposed", "MyThingFullExposed", "MyThingExposedSub", "MyThingPartlyExposedSub"] Pyro4.config.reset(False) # reset the config to default if sys.version_info < (3, 0): # noinspection PyUnresolvedReferences from StringIO import StringIO def tobytes(string, encoding=None): return string def tostring(bytes): return bytes unicode = unicode unichr = unichr basestring = basestring else: from io import StringIO def tobytes(string, encoding="iso-8859-1"): return bytes(string, encoding) def tostring(bytes, encoding="utf-8"): return str(bytes, encoding) unicode = str unichr = chr basestring = str class NonserializableError(Exception): def __reduce__(self): raise pickle.PicklingError("to make this error non-serializable") class MyThingPartlyExposed(object): c_attr = "hi" propvalue = 42 _private_attr1 = "hi" __private_attr2 = "hi" name = "" def __init__(self, name="dummy"): self.name = name def __eq__(self, other): if type(other) is MyThingPartlyExposed: return self.name == other.name return False def method(self, arg, default=99, **kwargs): pass @staticmethod def staticmethod(arg): pass @classmethod def classmethod(cls, arg): pass def __dunder__(self): pass def __private(self): pass def _private(self): pass @Pyro4.expose @property def prop1(self): return self.propvalue @Pyro4.expose @prop1.setter def prop1(self, value): self.propvalue = value @Pyro4.expose @property def readonly_prop1(self): return self.propvalue @property def prop2(self): return self.propvalue @prop2.setter def prop2(self, value): self.propvalue = value @Pyro4.oneway @Pyro4.expose def oneway(self, arg): pass @Pyro4.expose def exposed(self): pass __hash__ = object.__hash__ @Pyro4.expose class MyThingFullExposed(object): """this is the same as MyThingPartlyExposed but the whole class should be exposed""" c_attr = "hi" propvalue = 42 _private_attr1 = "hi" __private_attr2 = "hi" name = "" def __init__(self, name="dummy"): self.name = name # note: not affected by @expose, only real properties are def __eq__(self, other): if type(other) is MyThingFullExposed: return self.name == other.name return False def method(self, arg, default=99, **kwargs): pass @staticmethod def staticmethod(arg): pass @classmethod def classmethod(cls, arg): pass def __dunder__(self): pass def __private(self): pass def _private(self): pass @property def prop1(self): return self.propvalue @prop1.setter def prop1(self, value): self.propvalue = value @property def readonly_prop1(self): return self.propvalue @property def prop2(self): return self.propvalue @prop2.setter def prop2(self, value): self.propvalue = value @Pyro4.oneway def oneway(self, arg): pass def exposed(self): pass __hash__ = object.__hash__ @Pyro4.expose class MyThingExposedSub(MyThingFullExposed): def sub_exposed(self): pass def sub_unexposed(self): pass @Pyro4.oneway def oneway2(self): pass class MyThingPartlyExposedSub(MyThingPartlyExposed): @Pyro4.expose def sub_exposed(self): pass def sub_unexposed(self): pass @Pyro4.oneway def oneway2(self): pass
okalinin/drill
exec/java-exec/src/main/java/org/apache/drill/exec/planner/logical/ProjectComplexRexNodeCorrelateTransposeRule.java
<reponame>okalinin/drill /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.drill.exec.planner.logical; import com.google.common.collect.ImmutableList; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Correlate; import org.apache.calcite.rel.core.CorrelationId; import org.apache.calcite.rel.core.Uncollect; import org.apache.calcite.rel.logical.LogicalCorrelate; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexCorrelVariable; import org.apache.calcite.rex.RexFieldAccess; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexShuttle; import org.apache.calcite.tools.RelBuilder; import org.apache.calcite.util.ImmutableBitSet; import org.apache.calcite.util.trace.CalciteTrace; import org.apache.drill.common.exceptions.UserException; import java.util.ArrayList; import java.util.List; /** * Rule that moves non-{@link RexFieldAccess} rex node from project below {@link Uncollect} * to the left side of the {@link Correlate}. */ public class ProjectComplexRexNodeCorrelateTransposeRule extends RelOptRule { public static final RelOptRule INSTANCE = new ProjectComplexRexNodeCorrelateTransposeRule(); public ProjectComplexRexNodeCorrelateTransposeRule() { super(operand(LogicalCorrelate.class, operand(RelNode.class, any()), operand(Uncollect.class, operand(LogicalProject.class, any()))), DrillRelFactories.LOGICAL_BUILDER, "ProjectComplexRexNodeCorrelateTransposeRule"); } @Override public void onMatch(RelOptRuleCall call) { final Correlate correlate = call.rel(0); final Uncollect uncollect = call.rel(2); final LogicalProject project = call.rel(3); // uncollect requires project with single expression RexNode projectedNode = project.getProjects().iterator().next(); // check that the expression is complex call if (!(projectedNode instanceof RexFieldAccess)) { RelBuilder builder = call.builder(); RexBuilder rexBuilder = builder.getRexBuilder(); builder.push(correlate.getLeft()); // creates project with complex expr on top of the left side List<RexNode> leftProjExprs = new ArrayList<>(); String complexFieldName = correlate.getRowType().getFieldNames() .get(correlate.getRowType().getFieldNames().size() - 1); List<String> fieldNames = new ArrayList<>(); for (RelDataTypeField field : correlate.getLeft().getRowType().getFieldList()) { leftProjExprs.add(rexBuilder.makeInputRef(correlate.getLeft(), field.getIndex())); fieldNames.add(field.getName()); } fieldNames.add(complexFieldName); List<RexNode> topProjectExpressions = new ArrayList<>(leftProjExprs); // adds complex expression with replaced correlation // to the projected list from the left leftProjExprs.add(projectedNode.accept(new RexFieldAccessReplacer(builder))); RelNode leftProject = builder.project(leftProjExprs, fieldNames) .build(); CorrelationId correlationId = correlate.getCluster().createCorrel(); RexCorrelVariable rexCorrel = (RexCorrelVariable) rexBuilder.makeCorrel( leftProject.getRowType(), correlationId); builder.push(project.getInput()); RelNode rightProject = builder.project( ImmutableList.of(rexBuilder.makeFieldAccess(rexCorrel, leftProjExprs.size() - 1)), ImmutableList.of(complexFieldName)) .build(); int requiredColumnsCount = correlate.getRequiredColumns().cardinality(); if (requiredColumnsCount != 1) { throw UserException.planError() .message("Required columns count for Correlate operator " + "differs from the expected value:\n" + "Expected columns count is %s, but actual is %s", 1, requiredColumnsCount) .build(CalciteTrace.getPlannerTracer()); } RelNode newUncollect = uncollect.copy(uncollect.getTraitSet(), rightProject); Correlate newCorrelate = correlate.copy(uncollect.getTraitSet(), leftProject, newUncollect, correlationId, ImmutableBitSet.of(leftProjExprs.size() - 1), correlate.getJoinType()); builder.push(newCorrelate); switch(correlate.getJoinType()) { case LEFT: case INNER: // adds field from the right input of correlate to the top project topProjectExpressions.add( rexBuilder.makeInputRef(newCorrelate, topProjectExpressions.size() + 1)); // fall through case ANTI: case SEMI: builder.project(topProjectExpressions, correlate.getRowType().getFieldNames()); } call.transformTo(builder.build()); } } /** * Visitor for RexNode which replaces {@link RexFieldAccess} * with a reference to the field used in {@link RexFieldAccess}. */ private static class RexFieldAccessReplacer extends RexShuttle { private final RelBuilder builder; public RexFieldAccessReplacer(RelBuilder builder) { this.builder = builder; } @Override public RexNode visitFieldAccess(RexFieldAccess fieldAccess) { return builder.field(fieldAccess.getField().getName()); } } }
gautric/kogito-runtimes
kogito-codegen/src/test/java/org/kie/kogito/codegen/rules/IncrementalRuleCodegenTest.java
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.kie.kogito.codegen.rules; import java.io.File; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import org.drools.compiler.compiler.DecisionTableFactory; import org.drools.compiler.compiler.DecisionTableProvider; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.kie.api.internal.utils.ServiceRegistry; import org.kie.api.io.ResourceType; import org.kie.kogito.codegen.GeneratedFile; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class IncrementalRuleCodegenTest { @BeforeEach public void setup() { DecisionTableFactory.setDecisionTableProvider(ServiceRegistry.getInstance().get(DecisionTableProvider.class)); } @Test public void generateSingleFile() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/kie/kogito/codegen/rules/pkg1/file1.drl")), ResourceType.DRL); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); assertRules(3, 1, generatedFiles.size()); } @Test public void generateSinglePackage() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( asList(new File("src/test/resources/org/kie/kogito/codegen/rules/pkg1").listFiles()), ResourceType.DRL); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); assertRules(5, 1, generatedFiles.size()); } @Test public void generateSinglePackageSingleUnit() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( asList(new File("src/test/resources/org/kie/kogito/codegen/rules/multiunit").listFiles()), ResourceType.DRL); incrementalRuleCodegen.setPackageName("org.kie.kogito.codegen.rules.multiunit"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); assertRules(2, 1, 1, generatedFiles.size()); } @Test public void generateDirectoryRecursively() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofPath( Paths.get("src/test/resources/org/kie/kogito/codegen/rules"), ResourceType.DRL); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); assertRules(14, 5, 3, generatedFiles.size()); } @Test public void generateSingleDtable() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/drools/simple/candrink/CanDrink.xls"))); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); int externalizedLambda = 5; assertRules(2, 1, generatedFiles.size() - externalizedLambda); } @Test public void generateSingleUnit() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofPath( Paths.get("src/test/resources/org/kie/kogito/codegen/rules/myunit"), ResourceType.DRL); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); assertRules(1, 1, 1, generatedFiles.size()); } @Test public void generateCepRule() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/drools/simple/cep/cep.drl"))); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); int externalizedLambda = 2; assertRules(2, 1, generatedFiles.size() - externalizedLambda); } @Test public void raiseErrorOnSyntaxError() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/drools/simple/broken.drl"))); incrementalRuleCodegen.setPackageName("com.acme"); assertThrows(RuleCodegenError.class, incrementalRuleCodegen.withHotReloadMode()::generate); } @Test public void raiseErrorOnBadOOPath() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/kie/kogito/codegen/brokenrules/brokenunit/ABrokenUnit.drl"))); incrementalRuleCodegen.setPackageName("com.acme"); assertThrows(RuleCodegenError.class, incrementalRuleCodegen.withHotReloadMode()::generate); } @Test public void throwWhenDtableDependencyMissing() { DecisionTableFactory.setDecisionTableProvider(null); IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/drools/simple/candrink/CanDrink.xls"))); incrementalRuleCodegen.setPackageName("com.acme"); assertThrows(MissingDecisionTableDependencyError.class, incrementalRuleCodegen.withHotReloadMode()::generate); } @Test public void generateGrafanaDashboards() { IncrementalRuleCodegen incrementalRuleCodegen = IncrementalRuleCodegen.ofFiles( Collections.singleton( new File("src/test/resources/org/kie/kogito/codegen/unit/RuleUnitQuery.drl"))) .withMonitoring(true); incrementalRuleCodegen.setPackageName("com.acme"); List<GeneratedFile> generatedFiles = incrementalRuleCodegen.withHotReloadMode().generate(); assertEquals(2, generatedFiles.stream().filter(x -> x.getType() == GeneratedFile.Type.RESOURCE).count()); } private static void assertRules(int expectedRules, int expectedPackages, int expectedUnits, int actualGeneratedFiles) { assertEquals(expectedRules + expectedPackages * 2 + // package descriptor for rules + package metadata expectedUnits * 3, // ruleUnit + ruleUnit instance + unit model actualGeneratedFiles - 2); // ignore ProjectModel and ProjectRuntime classes } private static void assertRules(int expectedRules, int expectedPackages, int actualGeneratedFiles) { assertEquals(expectedRules + expectedPackages * 2, // package descriptor for rules + package metadata actualGeneratedFiles - 2); // ignore ProjectModel and ProjectRuntime classes } }
bloomberg/spark-flow
src/main/scala/com/bloomberg/sparkflow/components/Bundle.scala
/* * Copyright 2016 Bloomberg LP * * 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 com.bloomberg.sparkflow.components import com.bloomberg.sparkflow.dc.DC /** * Created by ngoehausen on 3/2/16. */ trait Bundle { private val keywords = Set("calcElements", "toString", "hashCode", "getClass", "elements") lazy val elements = calcElements() protected def calcElements() = { val c = getClass val res = c.getMethods.map { m => val name = m.getName val modifiers = m.getModifiers val types = m.getParameterTypes val isPD = classOf[DC[_]].isAssignableFrom(m.getReturnType) if (types.isEmpty && !java.lang.reflect.Modifier.isStatic(modifiers) && isPD) { m invoke this match { case pd: DC[_] => Some((name, pd)) case _ => None } } else { None } }.filter(_.isDefined).map(_.get).toList res } def getStuff(): List[Map[String, Any]] = { val c = getClass val res = c.getMethods.map { m => val map = Map( "name" -> m.getName, "modfiers" -> m.getModifiers, "parameterTypes" -> m.getParameterTypes.toList.mkString(" "), "returnType" -> m.getReturnType, "parameterCount" -> m.getParameterCount, "getDeclaringClass" -> m.getDeclaringClass, "isDefault" -> m.isDefault, "isSynthetic" -> m.isSynthetic, "isVarArgs" -> m.isVarArgs, "isAccessible" -> m.isAccessible, "getDefaultValue" -> m.getDefaultValue, "getGenericReturnType" -> m.getGenericReturnType, "toGenericString" -> m.toGenericString, "isBridge" -> m.isBridge, "getDeclaredAnnotations" -> m.getDeclaredAnnotations.mkString(" "), "getAnnotations" -> m.getAnnotations.mkString(" ") ) map }.toList res } def printStuff() = { val stuff = getStuff().filter(filterMaps) val filterFunc = (m: Map[String, Any]) => m.get("name") == Some("anInt") || m.get("name") == Some("nums") val stuffIWant = stuff.filter { filterFunc } val stuffIDontWant = stuff.filter { m => !filterFunc(m) } stuffIWant.foreach { map => println("-" * 40) map.foreach { case (name, thing) => println(s"$name -> $thing") } } println("\n\n") stuffIDontWant.foreach { map => println("-" * 40) map.foreach { case (name, thing) => println(s"$name -> $thing") } } } def filterMaps = (m: Map[String, Any]) => { m.get("parameterCount") == Some(0) && m.get("returnType") != Some(Void.TYPE) && !keywords.contains(m.get("name").get.toString) } }
zhong-lab/optics
lantz/lantz/drivers/linux-gpib-4.2.0/linux-gpib-kernel-4.2.0/drivers/gpib/sys/ibwait.c
/*************************************************************************** ibwait.c ------------------- begin : Dec 2001 copyright : (C) 2001, 2002 by <NAME> email : <EMAIL> ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "gpibP.h" #include "autopoll.h" #include <linux/sched.h> struct wait_info { gpib_board_t *board; struct timer_list timer; volatile int timed_out; unsigned long usec_timeout; }; static void wait_timeout( COMPAT_TIMER_ARG_TYPE t ) { struct wait_info *winfo = COMPAT_FROM_TIMER(winfo, t, timer); winfo->timed_out = 1; wake_up_interruptible( &winfo->board->wait ); } static void init_wait_info( struct wait_info *winfo ) { winfo->board = NULL; winfo->timed_out = 0; timer_setup_on_stack( &winfo->timer, wait_timeout, 0 ); } static int wait_satisfied( struct wait_info *winfo, gpib_status_queue_t *status_queue, int wait_mask, int *status, gpib_descriptor_t *desc ) { gpib_board_t *board = winfo->board; int temp_status; if(mutex_lock_interruptible( &board->big_gpib_mutex )) { return -ERESTARTSYS; } temp_status = general_ibstatus( board, status_queue, 0, 0, desc ); mutex_unlock(&board->big_gpib_mutex); if( winfo->timed_out ) temp_status |= TIMO; else temp_status &= ~TIMO; if( wait_mask & temp_status ) { *status = temp_status; return 1; } //XXX does wait for END work? return 0; } /* install timer interrupt handler */ static void startWaitTimer( struct wait_info *winfo ) /* Starts the timeout task */ { winfo->timed_out = 0; if( winfo->usec_timeout > 0 ) { mod_timer( &winfo->timer, jiffies + usec_to_jiffies( winfo->usec_timeout )); } } static void removeWaitTimer( struct wait_info *winfo ) { del_timer_sync( &winfo->timer ); destroy_timer_on_stack( &winfo->timer ); } /* * IBWAIT * Check or wait for a GPIB event to occur. The mask argument * is a bit vector corresponding to the status bit vector. It * has a bit set for each condition which can terminate the wait * If the mask is 0 then * no condition is waited for. */ int ibwait( gpib_board_t *board, int wait_mask, int clear_mask, int set_mask, int *status, unsigned long usec_timeout, gpib_descriptor_t *desc ) { int retval = 0; gpib_status_queue_t *status_queue; struct wait_info winfo; if( desc->is_board ) status_queue = NULL; else status_queue = get_gpib_status_queue( board, desc->pad, desc->sad ); if( wait_mask == 0 ) { *status = general_ibstatus( board, status_queue, clear_mask, set_mask, desc ); return 0; } mutex_unlock( &board->big_gpib_mutex ); init_wait_info( &winfo ); winfo.board = board; winfo.usec_timeout = usec_timeout; startWaitTimer( &winfo ); if( wait_event_interruptible( board->wait, wait_satisfied( &winfo, status_queue, wait_mask, status, desc ) ) ) { GPIB_DPRINTK( "wait interrupted\n" ); retval = -ERESTARTSYS; } removeWaitTimer( &winfo ); if(retval) return retval; if(mutex_lock_interruptible( &board->big_gpib_mutex )) { return -ERESTARTSYS; } /* make sure we only clear status bits that we are reporting */ if( *status & clear_mask || set_mask ) general_ibstatus( board, status_queue, *status & clear_mask, set_mask, 0 ); return 0; }
corewire/rocketbot
rocketbot/commands/catchall.py
from typing import Any, Awaitable, Callable, List, Tuple import rocketbot.commands as c import rocketbot.master as master import rocketbot.models as m class CatchAll(c.BaseCommand): """This is a catch all command It can be used as last command in the chain which is always applicable and will call the given function """ def __init__(self, callback: Callable[[master.Master, str, str, m.Message], Awaitable[None]], **kwargs: Any): super().__init__(**kwargs) self._callback = callback def usage(self) -> List[Tuple[str, str]]: return [] def can_handle(self, command: str) -> bool: """Catch all is always applicable """ return True async def handle(self, command: str, args: str, message: m.Message) -> None: """Handle the incoming message """ await self._callback(self.master, command, args, message) async def private_message_user( master: master.Master, command: str, args: str, message: m.Message) -> None: room = await master.ddp.create_direct_message(message.created_by.username) await master.ddp.send_message( room, f"Hey {message.created_by.name}, if you want me to do something contact me right here :)" )
Jakegogo/concurrent
concur/src-basesource/basesource/convertor/contansts/Configurations.java
<reponame>Jakegogo/concurrent<filename>concur/src-basesource/basesource/convertor/contansts/Configurations.java<gh_stars>10-100 package basesource.convertor.contansts; import java.io.*; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * 配置 * Created by Jake on 2015/6/6. */ public class Configurations { /** 文件保存名称 */ private static String SAVE_FILE_NAME = "config.properties"; /** * 实例 */ private static final Configurations instance = new Configurations(); /** * 配置的Map */ private final Map<String, Object> configures = new HashMap<String, Object>(); private Configurations() { } /** * 获取配置 * @param configKey 配置的KEY * @param <T> * @return */ public static <T> T getConfigure(String configKey) { return (T) getInstance().configures.get(configKey); } /** * 加载配置 */ public static void loadConfigure() { String dir = System.getProperty("user.dir"); String path = dir + File.separator + SAVE_FILE_NAME; Map<String, Object> configures = getInstance().configures; Properties properties = new Properties(); FileInputStream inStream; try { inStream = new FileInputStream(path); properties.load(inStream); configures.clear(); // 读取常量值 readContants(configures); for (String key : properties.stringPropertyNames()) { configures.put(key, properties.getProperty(key)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 读取常量值 private static void readContants(Map<String, Object> configures) { for (Field field : DefaultUIConstant.class.getDeclaredFields()) { try { configures.put(field.getName(), field.get(DefaultUIConstant.class)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } /** * 保存配置 * @param configKey * @param value */ public static void saveConfigure(String configKey, Serializable value) { Map<String, Object> configures = getInstance().configures; configures.put(configKey, value); outPutConfigure(configures); } /** * 输出配置到文件 * @param configures Map<String, Object> 键 - 值 */ private static void outPutConfigure(Map<String, Object> configures) { // 保存文件 Properties properties = new Properties(); for (Map.Entry<String, Object> entry : configures.entrySet()) { properties.setProperty(entry.getKey(), String.valueOf(entry.getValue())); } String dir = System.getProperty("user.dir"); String path = dir + File.separator + SAVE_FILE_NAME; try { FileOutputStream outputFile = new FileOutputStream(path); properties.store(outputFile, "用户配置"); outputFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * 获取实例 * @return Configurations Configurations */ public static Configurations getInstance() { return instance; } }
giger85/google-ads-java
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/KeywordPlanCampaignKeywordServiceProto.java
<gh_stars>1-10 // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/services/keyword_plan_campaign_keyword_service.proto package com.google.ads.googleads.v10.services; public final class KeywordPlanCampaignKeywordServiceProto { private KeywordPlanCampaignKeywordServiceProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_KeywordPlanCampaignKeywordOperation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_KeywordPlanCampaignKeywordOperation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordResult_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nMgoogle/ads/googleads/v10/services/keyw" + "ord_plan_campaign_keyword_service.proto\022" + "!google.ads.googleads.v10.services\032Fgoog" + "le/ads/googleads/v10/resources/keyword_p" + "lan_campaign_keyword.proto\032\034google/api/a" + "nnotations.proto\032\027google/api/client.prot" + "o\032\037google/api/field_behavior.proto\032\031goog" + "le/api/resource.proto\032 google/protobuf/f" + "ield_mask.proto\032\027google/rpc/status.proto" + "\"\325\001\n(MutateKeywordPlanCampaignKeywordsRe" + "quest\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022_\n\nopera" + "tions\030\002 \003(\0132F.google.ads.googleads.v10.s" + "ervices.KeywordPlanCampaignKeywordOperat" + "ionB\003\340A\002\022\027\n\017partial_failure\030\003 \001(\010\022\025\n\rval" + "idate_only\030\004 \001(\010\"\323\002\n#KeywordPlanCampaign" + "KeywordOperation\022/\n\013update_mask\030\004 \001(\0132\032." + "google.protobuf.FieldMask\022P\n\006create\030\001 \001(" + "\0132>.google.ads.googleads.v10.resources.K" + "eywordPlanCampaignKeywordH\000\022P\n\006update\030\002 " + "\001(\0132>.google.ads.googleads.v10.resources" + ".KeywordPlanCampaignKeywordH\000\022J\n\006remove\030" + "\003 \001(\tB8\372A5\n3googleads.googleapis.com/Key" + "wordPlanCampaignKeywordH\000B\013\n\toperation\"\272" + "\001\n)MutateKeywordPlanCampaignKeywordsResp" + "onse\0221\n\025partial_failure_error\030\003 \001(\0132\022.go" + "ogle.rpc.Status\022Z\n\007results\030\002 \003(\0132I.googl" + "e.ads.googleads.v10.services.MutateKeywo" + "rdPlanCampaignKeywordResult\"y\n&MutateKey" + "wordPlanCampaignKeywordResult\022O\n\rresourc" + "e_name\030\001 \001(\tB8\372A5\n3googleads.googleapis." + "com/KeywordPlanCampaignKeyword2\222\003\n!Keywo" + "rdPlanCampaignKeywordService\022\245\002\n!MutateK" + "eywordPlanCampaignKeywords\022K.google.ads." + "googleads.v10.services.MutateKeywordPlan" + "CampaignKeywordsRequest\032L.google.ads.goo" + "gleads.v10.services.MutateKeywordPlanCam" + "paignKeywordsResponse\"e\202\323\344\223\002F\"A/v10/cust" + "omers/{customer_id=*}/keywordPlanCampaig" + "nKeywords:mutate:\001*\332A\026customer_id,operat" + "ions\032E\312A\030googleads.googleapis.com\322A\'http" + "s://www.googleapis.com/auth/adwordsB\222\002\n%" + "com.google.ads.googleads.v10.servicesB&K" + "eywordPlanCampaignKeywordServiceProtoP\001Z" + "Igoogle.golang.org/genproto/googleapis/a" + "ds/googleads/v10/services;services\242\002\003GAA" + "\252\002!Google.Ads.GoogleAds.V10.Services\312\002!G" + "oogle\\Ads\\GoogleAds\\V10\\Services\352\002%Googl" + "e::Ads::GoogleAds::V10::Servicesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v10.resources.KeywordPlanCampaignKeywordProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.protobuf.FieldMaskProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), }); internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsRequest_descriptor, new java.lang.String[] { "CustomerId", "Operations", "PartialFailure", "ValidateOnly", }); internal_static_google_ads_googleads_v10_services_KeywordPlanCampaignKeywordOperation_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v10_services_KeywordPlanCampaignKeywordOperation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_KeywordPlanCampaignKeywordOperation_descriptor, new java.lang.String[] { "UpdateMask", "Create", "Update", "Remove", "Operation", }); internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsResponse_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordsResponse_descriptor, new java.lang.String[] { "PartialFailureError", "Results", }); internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordResult_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v10_services_MutateKeywordPlanCampaignKeywordResult_descriptor, new java.lang.String[] { "ResourceName", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.ads.googleads.v10.resources.KeywordPlanCampaignKeywordProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.protobuf.FieldMaskProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
bilektugrul/DiSky
src/main/java/info/itsthesky/DiSky/managers/cache/Messages.java
<filename>src/main/java/info/itsthesky/DiSky/managers/cache/Messages.java package info.itsthesky.DiSky.managers.cache; import info.itsthesky.DiSky.DiSky; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; /** * Made by ItsTheSky the 20/03/2021 <br> * Allow the JDA to cache message with simple wrapper. */ public class Messages extends ListenerAdapter { private static final List<CachedMessage> cachedMessages = new ArrayList<>(); public static void cacheMessage(Message message) { cachedMessages.add(new CachedMessage(message)); } public static CachedMessage retrieveMessage(String id) { AtomicReference<CachedMessage> finalMessage = new AtomicReference<>(); cachedMessages.forEach((cm) -> { if (cm.getMessageID().equalsIgnoreCase(id)) { finalMessage.set(cm); } }); if (finalMessage.get() == null) { DiSky.getInstance().getLogger().warning("DiSky can't retrieve the cached message '"+id+"', since it was not cached!"); } return finalMessage.get(); } @Override public void onGuildMessageReceived(GuildMessageReceivedEvent e) { cachedMessages.add(new CachedMessage(e.getMessage())); } @Override public void onGuildMemberJoin(GuildMemberJoinEvent e) { if (e.getUser().isBot() || e.getUser().getId().equalsIgnoreCase(e.getJDA().getSelfUser().getId())) { for (TextChannel channel : e.getGuild().getTextChannels()) { for (Message message : channel.getHistory().getRetrievedHistory()) { cachedMessages.add(new CachedMessage(message)); } } } } @Override public void onReady(ReadyEvent e) { for (Guild guild : e.getJDA().getGuilds()) { for (TextChannel channel : guild.getTextChannels()) { for (Message message : channel.getHistory().getRetrievedHistory()) { cachedMessages.add(new CachedMessage(message)); } } } } }
AntonioCesar96/livros-lembrete
livroslembreteapi/src/main/java/com/antonio/livroslembreteapi/services/LivroService.java
package com.antonio.livroslembreteapi.services; import java.util.List; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import com.antonio.livroslembreteapi.models.Livro; import com.antonio.livroslembreteapi.repository.LivroRepository; import com.antonio.livroslembreteapi.repository.LivroSpecification; @Service public class LivroService { @Autowired private LivroRepository livroRepository; public List<Livro> findAll(int page, int size, Long usuario) { Specification<Livro> specification = LivroSpecification.filtrar(usuario); Page<Livro> all = livroRepository.findAll(specification, new PageRequest(page, size)); return all.getContent(); } public Response save(Livro livro) { livro = livroRepository.save(livro); return Response.ok(livro).build(); } public Response findOne(Long id) { Livro livro = livroRepository.findOne(id); return Response.ok(livro).build(); } public Response update(Long id, Livro livro) { livro = livroRepository.save(livro); return Response.ok(livro).build(); } public Response delete(Long id) { livroRepository.delete(id); return Response.ok().build(); } }
boazsade/machine_learinig_models
src/libs/dataclean_mode_use/src/constmissingfix_task.cpp
#ifndef SUPPORT_FOR_MODEL_USE # define SUPPORT_FOR_MODEL_USE #endif // SUPPORT_FOR_MODEL_USE #include "libs/cleanup_operatiosn/constmissingfix_task.h" #include "details/constmissingfix_task.hpp"
DiyanKalaydzhiev23/JavaScript-Applications
MusicExam/node_modules/playwright-chromium/lib/utils/stackTrace.js
<gh_stars>1-10 "use strict"; /** * Copyright (c) Microsoft Corporation. * * 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. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.captureStackTrace = exports.rewriteErrorMessage = exports.getCallerFilePath = void 0; const path_1 = __importDefault(require("path")); const stack_utils_1 = __importDefault(require("stack-utils")); const utils_1 = require("./utils"); const stackUtils = new stack_utils_1.default(); function getCallerFilePath(ignorePrefix) { const frame = captureStackTrace().frames.find(f => !f.file.startsWith(ignorePrefix)); return frame ? frame.file : null; } exports.getCallerFilePath = getCallerFilePath; function rewriteErrorMessage(e, newMessage) { if (e.stack) { const index = e.stack.indexOf(e.message); if (index !== -1) e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length); } e.message = newMessage; return e; } exports.rewriteErrorMessage = rewriteErrorMessage; const PW_LIB_DIRS = [ 'playwright', 'playwright-chromium', 'playwright-firefox', 'playwright-webkit', ].map(packageName => path_1.default.join('node_modules', packageName, 'lib')); function captureStackTrace() { const stack = new Error().stack; const frames = []; for (const line of stack.split('\n')) { const frame = stackUtils.parseLine(line); if (!frame || !frame.file) continue; if (frame.file.startsWith('internal')) continue; const fileName = path_1.default.resolve(process.cwd(), frame.file); if (PW_LIB_DIRS.some(libDir => fileName.includes(libDir))) continue; // for tests. if (utils_1.isUnderTest() && fileName.includes(path_1.default.join('playwright', 'src'))) continue; if (utils_1.isUnderTest() && fileName.includes(path_1.default.join('playwright', 'test', 'coverage.js'))) continue; frames.push({ file: fileName, line: frame.line, column: frame.column, function: frame.function, }); } return { stack, frames }; } exports.captureStackTrace = captureStackTrace; //# sourceMappingURL=stackTrace.js.map
kkkkv/tgnms
tgnms/fbcnms-projects/tgnms/app/views/map/mappanels/NodeDetailsPanel/NodeSoftwareVersion.js
<reponame>kkkkv/tgnms<gh_stars>10-100 /** * Copyright 2004-present Facebook. All Rights Reserved. * * @format * @flow strict-local */ import React from 'react'; import Typography from '@material-ui/core/Typography'; import {makeStyles} from '@material-ui/styles'; import {shortenVersionString} from '@fbcnms/tg-nms/app/helpers/VersionHelper'; const useStyles = makeStyles(theme => ({ sectionHeading: { textAlign: 'center', fontSize: '0.85rem', color: theme.palette.grey[700], paddingTop: theme.spacing(1), }, })); type Props = { version: string, }; export default function NodeSoftwareVersion(props: Props) { const classes = useStyles(); const {version} = props; return ( <> <Typography variant="subtitle2" className={classes.sectionHeading}> Software Version </Typography> <Typography gutterBottom variant="body2"> <em>{shortenVersionString(version)}</em> </Typography> </> ); }
reels-research/iOS-Private-Frameworks
NanoTimeKitCompanion.framework/NTKPhotoAnalysis.h
<gh_stars>1-10 /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/NanoTimeKitCompanion.framework/NanoTimeKitCompanion */ @interface NTKPhotoAnalysis : NSObject <NSCopying, NSSecureCoding> { struct { bool isComplexBackground; bool isColoredText; float textHue; float textSaturation; float textBrightness; float bgHue; float bgSaturation; float bgBrightness; float shadowHue; float shadowSaturation; float shadowBrightness; } _data; unsigned int _version; } @property (nonatomic, readonly) float bgBrightness; @property (nonatomic, readonly) float bgHue; @property (nonatomic, readonly) float bgSaturation; @property (getter=isColoredText, nonatomic, readonly) bool coloredText; @property (getter=isComplexBackground, nonatomic, readonly) bool complexBackground; @property (nonatomic, readonly) float shadowBrightness; @property (nonatomic, readonly) float shadowHue; @property (nonatomic, readonly) float shadowSaturation; @property (nonatomic, readonly) struct { bool x1; bool x2; float x3; float x4; float x5; float x6; float x7; float x8; float x9; float x10; float x11; } structure; @property (nonatomic, readonly) float textBrightness; @property (nonatomic, readonly) float textHue; @property (nonatomic, readonly) float textSaturation; @property (nonatomic, readonly) unsigned int version; + (id)analysisWithImage:(id)arg1 alignment:(id)arg2; + (id)analysisWithImage:(id)arg1 alignment:(unsigned long long)arg2 deviceSizeClass:(unsigned long long)arg3; + (id)defaultAnalysis; + (id)invalidAnalysis; + (bool)supportsSecureCoding; - (float)bgBrightness; - (float)bgHue; - (float)bgSaturation; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (id)encodeAsDictionary; - (void)encodeWithCoder:(id)arg1; - (id)initFromDictionary:(id)arg1; - (id)initWithCoder:(id)arg1; - (id)initWithStructure:(struct { bool x1; bool x2; float x3; float x4; float x5; float x6; float x7; float x8; float x9; float x10; float x11; })arg1; - (bool)isColoredText; - (bool)isComplexBackground; - (float)shadowBrightness; - (float)shadowHue; - (float)shadowSaturation; - (struct { bool x1; bool x2; float x3; float x4; float x5; float x6; float x7; float x8; float x9; float x10; float x11; })structure; - (float)textBrightness; - (float)textHue; - (float)textSaturation; - (unsigned int)version; @end
icbcom/aistdap-sdk-java
src/test/java/ru/icbcom/aistdapsdkjava/impl/datastore/resttemplate/RestTemplateResponseErrorHandlerTest.java
<reponame>icbcom/aistdap-sdk-java<filename>src/test/java/ru/icbcom/aistdapsdkjava/impl/datastore/resttemplate/RestTemplateResponseErrorHandlerTest.java<gh_stars>1-10 /* * Copyright © 2018-2019 Icbcom * * 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 ru.icbcom.aistdapsdkjava.impl.datastore.resttemplate; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.client.ClientHttpResponse; import ru.icbcom.aistdapsdkjava.api.exception.AistDapBackendException; import ru.icbcom.aistdapsdkjava.impl.error.DefaultError; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import static java.util.Collections.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class RestTemplateResponseErrorHandlerTest { @Mock ObjectMapper objectMapper; @Mock ClientHttpResponse response; private RestTemplateResponseErrorHandler restTemplateResponseErrorHandler; @BeforeEach void setup() { restTemplateResponseErrorHandler = new RestTemplateResponseErrorHandler(objectMapper); } @Test void handleErrorShouldWorkProperly() throws IOException { String errorBody = "{\n" + " \"title\": \"Unauthorized\",\n" + " \"status\": 401,\n" + " \"detail\": \"Refresh token expired\"\n" + "}"; ByteArrayInputStream inputStream = new ByteArrayInputStream(errorBody.getBytes(StandardCharsets.UTF_8)); DefaultError defaultError = new DefaultError(); defaultError.setTitle("Unauthorized"); defaultError.setStatus(401); defaultError.setDetail("Refresh token expired"); when(response.getBody()).thenReturn(inputStream); when(objectMapper.readValue(any(String.class), eq(DefaultError.class))).thenReturn(defaultError); AistDapBackendException exception = assertThrows(AistDapBackendException.class, () -> restTemplateResponseErrorHandler.handleError(response)); assertThat(exception, allOf( hasProperty("title", is("Unauthorized")), hasProperty("status", is(401)), hasProperty("detail", is("Refresh token expired")), hasProperty("moreInfo", is(emptyMap())) )); InOrder inOrder = inOrder(objectMapper, response); inOrder.verify(response).getBody(); ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class); inOrder.verify(objectMapper).readValue(stringArgumentCaptor.capture(), eq(DefaultError.class)); assertEquals(errorBody, stringArgumentCaptor.getValue()); inOrder.verifyNoMoreInteractions(); } }
ishansarangi/MovieShowTimeRecommender
SERVER/src/main/java/com/asu/MovieRecommender/utility/Constants.java
package com.asu.MovieRecommender.utility; public class Constants { public final static String URL = "https://api.internationalshowtimes.com/v4"; public final static String URL_TMDB = "https://api.themoviedb.org/3/"; public final static String MOVIE = "movie"; public final static String NOWPLAYING = "now_playing"; public static final String PARAM_YEAR = "year"; public static final String PARAM_PAGE = "page"; public static final String PARAM_LANGUAGE = "language"; public static final String PARAM_ID = "id"; public static final String PARAM_ADULT = "include_adult"; public static final String PARAM_API_KEY = "api_key"; public static final String DATE_ATTRIBUTE = "dates"; public static final String PAGE_ATTRIBUTE = "page"; public static final String TOTAL_PAGES_ATTRIBUTE = "total_pages"; public static final String TOTAL_RESULTS_ATTRIBUTE ="total_results"; public static final int NO_OF_MOVIES = 3; public static final String PARAM_CINEMA_ID = "cinema_id"; public static final String PARAM_CINEMA_ID_VALUE = "40849"; public static final String API_KEY_STRING = "apikey"; public static final String CITY_ID = "city_ids"; public static final String MOVIE_ID = "movie_id"; public static final String TEMPE = "1901"; public static final String MOVIES = "/movies"; public static final String SHOWTIMES = "/showtimes"; public static final String TMDB_ID = "tmdb_id"; public static final String PARAMETERS = "parameters"; public static final String SEARCH_QUERY = "search_query"; public static final String SEARCH_FIELD = "search_field"; public static final String CINEMA_MOVIE_TITLE = "cinema_movie_title"; public static final String VIDEOS = "videos"; /*Status Codes*/ public final static String STATUS_OK = "200"; public static final Object CINEMAS = "/cinemas"; public static final Object POPULAR = "popular"; public static final Object TOPRATED = "top_rated"; public static final Object RECOMMENDATIONS = "recommendations"; }
hieo/shopping
src/test/java/cn/effine/lru/TestLRUCache.java
/** * @Date 2015年3月12日 上午10:00:36 * @author effine * @email <EMAIL> */ package cn.effine.lru; import java.util.Iterator; import java.util.Map; //Test program for the LRUCache class. public class TestLRUCache { public static void main(String[] args) { LRUCacheDemo<String, String> c = new LRUCacheDemo<String, String>(3); c.put("1", "one"); // 1 c.put("2", "two"); // 2 1 c.put("3", "three"); // 3 2 1 c.put("4", "four"); // 4 3 2 if (c.get("2") == null) throw new Error(); // 2 4 3 c.put("5", "five"); // 5 2 4 c.put("4", "second four"); // 4 5 2 System.err.println(c.get("5")); //5 4 2 // Verify cache content. if (c.usedEntries() != 3) throw new Error(); if (!c.get("4").equals("second four")) // 4 5 2 throw new Error(); if (!c.get("5").equals("five")) //5 4 2 throw new Error(); if (!c.get("2").equals("two")) // 2 5 4 throw new Error(); Iterator<?> iterator = c.getAll().iterator(); while (iterator.hasNext()) { System.err.println(iterator.next()); } // LIST cache content. for (Map.Entry<String, String> e : c.getAll()) System.out.println(e.getKey() + " : " + e.getValue()); } } // end class TestLRUCache
wilseypa/ROSS
ross/models/airport/other/3-simple-airport.c
<reponame>wilseypa/ROSS #include <ross.h> /* This is a modify verison of airport.c which was done by <NAME> */ int A = 60; int R = 10; int G = 45; int NumLanded = 0; enum events { ARRIVAL, LAND, DEPARTURE}; typedef struct { enum events event_type; } Msg_Data; typedef struct { int OnTheGround; int InTheAir; int RunwayFree; int NumLanded; } Airport_State; void Airport_StartUp(Airport_State *, tw_lp *); void Airport_EventHandler(Airport_State *, tw_bf *, Msg_Data *, tw_lp *); void Airport_RC_EventHandler(Airport_State *, tw_bf *, Msg_Data *, tw_lp *); void Airport_Statistics_CollectStats(Airport_State *, tw_lp *); #define AIR_LP 1 tw_lptype airport_lps[] = { { AIR_LP, sizeof(Airport_State), (init_f) Airport_StartUp, (event_f) Airport_EventHandler, (revent_f) Airport_RC_EventHandler, (final_f) Airport_Statistics_CollectStats, (statecp_f) NULL }, { 0 }, }; int main(int argc, char * argv[]) { int NumPE = 0; int i = 0; tw_lp *lp; tw_kp *kp; g_tw_ts_end = 300; g_tw_gvt_interval = 16; printf("Please enter the number of processors: "); scanf("%d",&NumPE); if(NumPE < 1 && NumPE > 4){ printf("Invalid number of processors %d\n", NumPE); exit(0); } /* tw_lptype NumPE NumKP NumLP Message_Size*/ tw_init(airport_lps, NumPE, 3, 3, sizeof(Msg_Data)); for(i = 0; i < 3; i++){ lp = tw_getlp(i); kp = tw_getkp(i); tw_lp_settype(lp, AIR_LP); tw_lp_onkp(lp, kp); if(i >= NumPE){ tw_lp_onpe(lp, tw_getpe(NumPE - 1)); tw_kp_onpe(kp, tw_getpe(NumPE - 1)); } else { tw_lp_onpe(lp, tw_getpe(i)); tw_kp_onpe(kp, tw_getpe(i)); } } tw_run(); printf("Number of Landings: %d\n", NumLanded); return 0; } void Airport_StartUp(Airport_State *SV, tw_lp * lp) { int i; tw_event *CurEvent; tw_stime ts; Msg_Data *NewM; SV->OnTheGround = 0; SV->InTheAir = 0 ; SV->RunwayFree = 1; SV->NumLanded = 0; for(i = 0; i < 5; i++) { ts = tw_rand_exponential(lp->id, A); CurEvent = tw_event_new(lp, ts, lp); NewM = (Msg_Data *) tw_event_data(CurEvent); NewM->event_type = ARRIVAL; tw_event_send(CurEvent); } } void Airport_EventHandler(Airport_State *SV, tw_bf *CV, Msg_Data *M, tw_lp *lp) { tw_stime ts; tw_event *CurEvent; Msg_Data *NewM; *(int *)CV = (int)0; switch(M->event_type) { case ARRIVAL: // Schedule a landing in the future SV->InTheAir++; if((CV->c1 = (SV->RunwayFree == 1))){ SV->RunwayFree = 0; ts = tw_rand_exponential(lp->id, R); CurEvent = tw_event_new(lp, ts, lp); NewM = (Msg_Data *)tw_event_data(CurEvent); NewM->event_type = LAND; tw_event_send(CurEvent); } break; case LAND: SV->InTheAir--; SV->OnTheGround++; SV->NumLanded++; ts = tw_rand_exponential(lp->id, G); CurEvent = tw_event_new(lp, ts, lp); NewM = (Msg_Data *)tw_event_data(CurEvent); NewM->event_type = DEPARTURE; tw_event_send(CurEvent); if ((CV->c1 = (SV->InTheAir > 0))){ ts = tw_rand_exponential(lp->id, R); CurEvent = tw_event_new(lp, ts, lp); NewM = (Msg_Data *)tw_event_data(CurEvent); NewM->event_type = LAND; tw_event_send(CurEvent); } else SV->RunwayFree = 1; break; case DEPARTURE: SV->OnTheGround--; ts = tw_rand_exponential(lp->id, A); CurEvent = tw_event_new(tw_getlp((lp->id + 1) % 3) , ts, lp); NewM = (Msg_Data *) tw_event_data(CurEvent); NewM->event_type = ARRIVAL; tw_event_send(CurEvent); break; } } void Airport_RC_EventHandler(Airport_State *SV, tw_bf *CV, Msg_Data *M, tw_lp *lp) { switch(M->event_type) { case ARRIVAL: SV->InTheAir--; if(CV->c1){ SV->RunwayFree = 1; tw_rand_reverse_unif(lp->id); } break; case LAND: SV->InTheAir++; SV->OnTheGround--; SV->NumLanded--; tw_rand_reverse_unif(lp->id); if(CV->c1) tw_rand_reverse_unif(lp->id); else SV->RunwayFree = 0; break; case DEPARTURE: SV->OnTheGround++; tw_rand_reverse_unif(lp->id); break; } } void Airport_Statistics_CollectStats(Airport_State *SV, tw_lp * lp) { NumLanded += SV->NumLanded; }
GrrriiiM/rubik-js
src/components/scan/scan.component.js
<reponame>GrrriiiM/rubik-js import { COLORS, SIDES } from "../../objs/constants.js"; import { patternColors } from "../../objs/creator.js"; import { findMovementFromTo } from "../../objs/finder.js"; import { MOVEMENTS } from "../../objs/movements.js"; import { rotateMovementsFromTo, rotateSide } from "../../objs/rotator.js"; import { inverseKeyValue } from "../../objs/transformer.js"; import { pallete, rgbToColor } from "./color-converter.js"; export function scanComponent(scanOrderSides, onFinished) { let self = { className: "scan", element: null, render, onFinished: null, close }; let videoElement; let canvasElement; let canvasContext; let videoWidth = Math.min(window.screen.width - 40, window.screen.width*0.6); let videoHeight = videoWidth; let mediaStream; let scanColorElements = []; // let scanOrderSides = [SIDES.FRONT, SIDES.RIGHT, SIDES.BACK, SIDES.LEFT, SIDES.UP, SIDES.DOWN]; let scanColors = scanOrderSides.map(_ => [0, 0, 0, 0, 0, 0]); let scanSidePosition = 0; let colorEntries = inverseKeyValue(COLORS); let sideEntries = inverseKeyValue(SIDES); let colorsClass = Object.entries(colorEntries).map(_ => _[1].toLowerCase()); let tempContext; async function render(parentElement) { let response = await fetch("./components/scan/scan.component.html"); self.element = parentElement.querySelector(`.${self.className}`); self.element.innerHTML = await response.text(); videoElement = self.element.querySelector(".video"); canvasElement = self.element.querySelector(".canvas"); canvasElement.height = videoHeight; canvasElement.width = videoWidth; canvasContext = canvasElement.getContext('2d'); [...Array(9).keys()].forEach(_ => { scanColorElements.push(self.element.querySelector(`.scan-color-${_}`)); }) self.element.querySelector(".button-next").onclick = nextScanSide; let a = [...Array(4).keys()]; let hexs = Object.keys(pallete); for (let r = 0; r <= 5; r++) { for (let g = 0; g <= 5; g++) { for (let b = 0; b <= 5; b++) { let r1 = r * 51; let g1 = g * 51; let b1 = b * 51; let hex = `#${r1.toString(16).padStart(2, "0").toUpperCase()}${g1.toString(16).padStart(2, "0").toUpperCase()}${b1.toString(16).padStart(2, "0").toUpperCase()}`; if (!hexs.includes(hex)) { let div = document.createElement("div"); div.style.backgroundColor = hex; div.classList.add("teste"); div.innerHTML = hex; self.element.querySelector(".teste-area").appendChild(div); } } } } updateScanSide(); await openCamera(); } async function close() { videoElement.pause(); mediaStream.getTracks().forEach(function(track) { track.stop(); }); } function nextScanSide() { scanSidePosition+=1; if (scanSidePosition >= scanOrderSides.length) { onFinished && onFinished(scanColors); // videoElement.pause(); // mediaStream.getTracks().forEach(function(track) { // track.stop(); // }); return; }; updateScanSide(); // if (actualSide >= 5) { // let pcolors = inverseKeyValue(patternColors); // let cubePattern = scanSides[0].map(_ => pcolors[_]).join(""); // cubePattern += scanSides[4].map(_ => pcolors[_]).join(""); // cubePattern += scanSides[3].map(_ => pcolors[_]).join(""); // cubePattern += scanSides[2].map(_ => pcolors[_]).join(""); // cubePattern += scanSides[5].map(_ => pcolors[_]).join(""); // cubePattern += scanSides[1].map(_ => pcolors[_]).join(""); // self.onFinished && self.onFinished(cubePattern) // return; // } // actualSide += 1; // ["center", "up", "left", "down", "right"].forEach((_, i) => { // let sidElement = self.element.querySelector(`.scan-overlay>.${_}`); // sidElement.classList.remove(...colorsClass); // sidElement.classList.add(sidesColors[actualSide][i]); // }); } function updateScanSide() { let movements = findMovementFromTo(SIDES.FRONT, scanOrderSides[scanSidePosition]); let sides = Object.values(SIDES); sides.forEach((side, i) => { movements.forEach(_ => sides[i] = rotateSide(_.axis, sides[i], _.clock)) }); self.element.querySelectorAll(`.scan-overlay>div`).forEach(_ => _.classList.remove(...colorsClass)); [SIDES.FRONT, SIDES.RIGHT, SIDES.LEFT, SIDES.UP, SIDES.DOWN].forEach(side => { let colorName = colorEntries[sides[side]].toLowerCase(); let sideName = sideEntries[side].toLowerCase(); self.element.querySelector(`.scan-overlay>.${sideName}`).classList.add(colorName); }); } async function openCamera() { let constraints = { audio: false, video: { height: videoHeight, width: videoWidth, facingMode: "environment" } }; try { mediaStream = await navigator.mediaDevices.getUserMedia(constraints) videoElement.onplay = async () => { while (!videoElement.paused && !videoElement.ended) { canvasContext.drawImage(videoElement, 0, 0); let scanColor = scanColors[scanSidePosition]; scanColor[0] = getColor(0, 0); scanColor[1] = getColor(1, 0); scanColor[2] = getColor(2, 0); scanColor[3] = getColor(0, 1); scanColor[4] = getColor(1, 1); scanColor[5] = getColor(2, 1); scanColor[6] = getColor(0, 2); scanColor[7] = getColor(1, 2); scanColor[8] = getColor(2, 2); scanColor.forEach((_, i) => { let scanColorElement = scanColorElements[i] let colorClass = colorEntries[_].toLowerCase() scanColorElement.classList.remove(...colorsClass); scanColorElement.classList.add(colorClass); }) // tempContext.drawImage(canvasElement, sourceX, sourceY, sourceSize, sourceSize, 0, 0, videoWidth, videoHeight) await new Promise(resolve => setTimeout(resolve, 1000 / 30)) } } videoElement.srcObject = mediaStream; videoElement.onloadedmetadata = function (e) { videoElement.play(); }; } catch (error) { alert(error.name + ": " + error.message); } } function getColor(x, y) { try { let sourceRange = 0.2; let borderSize = videoWidth * 0.2; let overlaySize = videoWidth; let sourceSize = overlaySize * 0.2; let sourceX = borderSize + x * sourceSize + sourceSize / 2 - sourceSize * sourceRange / 2; let sourceY = borderSize + y * sourceSize + sourceSize / 2 - sourceSize * sourceRange / 2;; sourceSize = sourceSize * sourceRange; let imageData = canvasContext.getImageData(sourceX, sourceY, sourceSize, sourceSize); // self.element.querySelector(".tempcanvas").height = sourceSize; // self.element.querySelector(".tempcanvas").width = sourceSize; // self.element.querySelector(".tempcanvas").getContext("2d").drawImage(canvasElement, sourceX, sourceY, sourceSize, sourceSize, 0,0,sourceSize,sourceSize); let imageDataColors = imageData.data; let colors = {}; let color = 0; for (let i = 0; i < imageDataColors.length; i += 4) { let imageDataColor = rgbToColor(imageDataColors[i], imageDataColors[i + 1], imageDataColors[i + 2]); colors[imageDataColor] = (colors[color] || 0) + 1; if (colors[imageDataColor] > (colors[color] || 0)) { color = imageDataColor; } } return color; } catch (error) { // alert(error.name + ": " + error.message); } } return self; }
xzel23/meja
src/swing/java/com/dua3/meja/ui/swing/CellEditor.java
/* * Copyright 2015 <NAME> (<EMAIL>). * * 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 com.dua3.meja.ui.swing; import javax.swing.JComponent; import com.dua3.meja.model.Cell; /** * * @author <NAME> (<EMAIL>) */ public interface CellEditor { /** * Check editing state. * * @return true if CellEditor is currently used to edit a cell */ boolean isEditing(); /** * Start editing. * * @param cell the cell to be edited * @return the component that is used for editing */ JComponent startEditing(Cell cell); /** * Stop editing. * * @param commit if true, changes will be applied to the edited cell */ void stopEditing(boolean commit); }
truthiswill/intellij-community
python/testData/refactoring/move/baseClass/after/src/a.py
<reponame>truthiswill/intellij-community from b import B class C(B): def __init__(self): super(C, self).__init__()
moutainhigh/taotao-cloud-parent
taotao-cloud-bigdata/taotao-cloud-java/src/main/java/com/taotao/cloud/java/proxy/proxyclass/ProxyBoss.java
package com.taotao.cloud.java.proxy.proxyclass; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyBoss { /** * 对接口方法进行代理 */ @SuppressWarnings("unchecked") public static <T> T getProxy(final int discountCoupon, final Class<?> interfaceClass, final Class<?> implementsClass) throws Exception { return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Integer returnValue = (Integer) method.invoke(implementsClass.newInstance(), args);// 调用原始对象以后返回的值 return returnValue - discountCoupon; } }); } }
kelu124/pyS3
org/apache/poi/ss/formula/ptg/RefNPtg.java
package org.apache.poi.ss.formula.ptg; import org.apache.poi.util.LittleEndianInput; import org.apache.poi.util.LittleEndianOutput; public final class RefNPtg extends Ref2DPtgBase { public static final byte sid = (byte) 44; public /* bridge */ /* synthetic */ void write(LittleEndianOutput littleEndianOutput) { super.write(littleEndianOutput); } public RefNPtg(LittleEndianInput in) { super(in); } protected byte getSid() { return sid; } }
vega113/Wiab.pro
src/org/waveprotocol/wave/client/wavepanel/WavePanel.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.waveprotocol.wave.client.wavepanel; import org.waveprotocol.wave.client.common.util.LogicalPanel; import org.waveprotocol.wave.client.wavepanel.event.EventHandlerRegistry; import org.waveprotocol.wave.client.wavepanel.event.KeySignalRouter; import org.waveprotocol.wave.client.wavepanel.view.TopConversationView; import org.waveprotocol.wave.client.wavepanel.view.dom.DomAsViewProvider; import org.waveprotocol.wave.model.wave.SourcesEvents; /** * A UI component for interacting with a wave. * <p> * This interface does not expose features; rather, it exposes mechanisms * through which features can be implemented. * * @author <EMAIL> (<NAME>) */ public interface WavePanel extends SourcesEvents<WavePanel.LifecycleListener> { /** * Observer of events affecting this panel's lifecycle. */ public interface LifecycleListener { /** * Notifies this listener that the wave panel is now showing a wave. */ void onInit(); /** * Notifies this listener that the wave panel it no longer showing a wave * and has been discarded. */ void onReset(); /** * Primitive implementation. */ public class Impl implements LifecycleListener { @Override public void onInit() { } @Override public void onReset() { } } } /** * This method is intended to be visible only to subpackages. * * @return the provider of views of dom elements. */ DomAsViewProvider getViewProvider(); /** * This method is intended to be visible only to subpackages. * * @return the registry against which event handlers are registered. */ EventHandlerRegistry getHandlers(); /** * This method is intended to be visible only to subpackages. * * @return the registry of key handlers for when focus is on the wave panel. */ KeySignalRouter getKeyRouter(); /** * This method is intended to be visible only to subpackages. * * @return the panel for connecting GWT widgets. */ LogicalPanel getGwtPanel(); /** * This method is intended to be visible only to subpackages. * * @return true if this panel has contents. This will be true between, and * only between, {@link LifecycleListener#onInit} and * {LifecycleListener#onReset} events. */ boolean hasContents(); /** * This method is intended to be visible only to subpackages. * * @return the UI of the main conversation in this panel. Never returns null. * @throws IllegalStateException if this panel has no contents. It is safe to * call this method between {@link LifecycleListener#onInit} and * {@link LifecycleListener#onReset}. If unsure, calls to this method * should be guarded with {@link #hasContents()}. */ TopConversationView getContents(); }
Al3x76/cpp
Pbinfo/nZero.cpp
<gh_stars>1-10 #include <iostream> #include <math.h> using namespace std; int main() { int n, a; cin>>n>>a; cout<<n; for(int i=1; i<=a; i++) cout<<"0"; return 0; }
globocom/container-broker
app/models/task_tag.rb
<filename>app/models/task_tag.rb # frozen_string_literal: true class TaskTag include Mongoid::Document include Mongoid::Uuid field :name, type: String field :values, type: Array, default: [] index({ name: 1 }, unique: true) end
sw-ashai/ashaimall
mall-product/src/main/java/icu/ashai/mall/product/service/SpuInfoService.java
package icu.ashai.mall.product.service; import com.baomidou.mybatisplus.extension.service.IService; import icu.ashai.common.utils.PageUtils; import icu.ashai.mall.product.entity.SpuInfoEntity; import icu.ashai.mall.product.vo.SpuSaveVo; import java.util.Map; /** * spu信息 * * @author Ashai * @email <EMAIL> * @date 2021-11-19 01:15:33 */ public interface SpuInfoService extends IService<SpuInfoEntity> { PageUtils queryPage(Map<String, Object> params); /** * 保存spu信息 * * @param vo 保存数据 */ void saveSpuInfo(SpuSaveVo vo); /** * 保存spu基础信息 * * @param spuInfoEntity 需要保存数据 */ void saveBaseSpuInf(SpuInfoEntity spuInfoEntity); /** * 根据限定条件查询列表 * * @param params 查询参数 * @return result */ PageUtils queryPageByCondition(Map<String, Object> params); }
enfoTek/tomato.linksys.e2000.nvram-mod
tools-src/gnu/gcc/gcc/config/ia64/unwind-ia64.h
/* Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc. Contributed by <NAME> <<EMAIL>> <NAME> <<EMAIL>> This file is part of GNU CC. GNU CC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU CC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU CC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ struct unw_table_entry { unsigned long start_offset; unsigned long end_offset; unsigned long info_offset; }; extern struct unw_table_entry * _Unwind_FindTableEntry (void *pc, unsigned long *segment_base, unsigned long *gp);
vznncv/vznncv-cubemx-tools
tests/fixtures/stm32f1_project/Drivers/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_conf_template.h
Stub content: Drivers/STM32F1xx_HAL_Driver/Inc/stm32f1xx_hal_conf_template.h
shubham1206agra/mlpack
src/mlpack/methods/ann/layer/linear_no_bias_impl.hpp
/** * @file methods/ann/layer/linear_no_bias_impl.hpp * @author <NAME> * * Implementation of the LinearNoBias class also known as fully-connected layer * or affine transformation without the bias term. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_ANN_LAYER_LINEAR_NO_BIAS_IMPL_HPP #define MLPACK_METHODS_ANN_LAYER_LINEAR_NO_BIAS_IMPL_HPP // In case it hasn't yet been included. #include "linear_no_bias.hpp" namespace mlpack { namespace ann /** Artificial Neural Network. */ { template<typename MatType, typename RegularizerType> LinearNoBiasType<MatType, RegularizerType>::LinearNoBiasType() : Layer<MatType>(), inSize(0), outSize(0) { // Nothing to do here. } template<typename MatType, typename RegularizerType> LinearNoBiasType<MatType, RegularizerType>::LinearNoBiasType( const size_t outSize, RegularizerType regularizer) : Layer<MatType>(), inSize(0), // This will be set by ComputeOutputDimensions(). outSize(outSize), regularizer(regularizer) { // Nothing to do. } template<typename MatType, typename RegularizerType> LinearNoBiasType<MatType, RegularizerType>::LinearNoBiasType( const LinearNoBiasType& layer) : Layer<MatType>(layer), inSize(layer.inSize), outSize(layer.outSize), regularizer(layer.regularizer) { // Nothing to do here. } template<typename MatType, typename RegularizerType> LinearNoBiasType<MatType, RegularizerType>::LinearNoBiasType( LinearNoBiasType&& layer) : Layer<MatType>(std::move(layer)), inSize(0), outSize(0), regularizer(std::move(layer.regularizer)) { // Nothing to do here. } template<typename MatType, typename RegularizerType> LinearNoBiasType<MatType, RegularizerType>& LinearNoBiasType<MatType, RegularizerType>::operator=( const LinearNoBiasType& layer) { if (this != &layer) { Layer<MatType>::operator=(layer); inSize = layer.inSize; outSize = layer.outSize; regularizer = layer.regularizer; } return *this; } template<typename MatType, typename RegularizerType> LinearNoBiasType<MatType, RegularizerType>& LinearNoBiasType<MatType, RegularizerType>::operator=( LinearNoBiasType&& layer) { if (this != &layer) { Layer<MatType>::operator=(std::move(layer)); inSize = std::move(layer.inSize); outSize = std::move(layer.outSize); regularizer = std::move(layer.regularizer); } return *this; } template<typename MatType, typename RegularizerType> void LinearNoBiasType<MatType, RegularizerType>::SetWeights( typename MatType::elem_type* weightsPtr) { MakeAlias(weight, weightsPtr, outSize, inSize); } template<typename MatType, typename RegularizerType> void LinearNoBiasType<MatType, RegularizerType>::Forward( const MatType& input, MatType& output) { output = weight * input; } template<typename MatType, typename RegularizerType> void LinearNoBiasType<MatType, RegularizerType>::Backward( const MatType& /* input */, const MatType& gy, MatType& g) { g = weight.t() * gy; } template<typename MatType, typename RegularizerType> void LinearNoBiasType<MatType, RegularizerType>::Gradient( const MatType& input, const MatType& error, MatType& gradient) { gradient.submat(0, 0, weight.n_elem - 1, 0) = arma::vectorise( error * input.t()); regularizer.Evaluate(weight, gradient); } template<typename MatType, typename RegularizerType> void LinearNoBiasType<MatType, RegularizerType>::ComputeOutputDimensions() { inSize = this->inputDimensions[0]; for (size_t i = 1; i < this->inputDimensions.size(); ++i) inSize *= this->inputDimensions[i]; this->outputDimensions = std::vector<size_t>(this->inputDimensions.size(), 1); this->outputDimensions[0] = outSize; } template<typename MatType, typename RegularizerType> template<typename Archive> void LinearNoBiasType<MatType, RegularizerType>::serialize( Archive& ar, const uint32_t /* version */) { ar(cereal::base_class<Layer<MatType>>(this)); ar(CEREAL_NVP(inSize)); ar(CEREAL_NVP(outSize)); ar(CEREAL_NVP(regularizer)); } } // namespace ann } // namespace mlpack #endif
cdsnyder/esp-idf
components/soc/src/esp32s2/touch_sensor_hal.c
// Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD // // 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. // The HAL layer for Touch Sensor (common part) #include "hal/touch_sensor_hal.h" #include "hal/touch_sensor_types.h" void touch_hal_init(void) { touch_ll_intr_disable(TOUCH_PAD_INTR_ALL); touch_ll_clear_channel_mask(SOC_TOUCH_SENSOR_BIT_MASK_MAX); touch_ll_clear_trigger_status_mask(); touch_ll_set_meas_times(TOUCH_PAD_MEASURE_CYCLE_DEFAULT); touch_ll_set_sleep_time(TOUCH_PAD_SLEEP_CYCLE_DEFAULT); touch_ll_set_voltage_high(TOUCH_PAD_HIGH_VOLTAGE_THRESHOLD); touch_ll_set_voltage_low(TOUCH_PAD_LOW_VOLTAGE_THRESHOLD); touch_ll_set_voltage_attenuation(TOUCH_PAD_ATTEN_VOLTAGE_THRESHOLD); touch_ll_set_inactive_connect(TOUCH_PAD_INACTIVE_CONNECT_DEFAULT); } void touch_hal_deinit(void) { touch_hal_stop_fsm(); touch_hal_clear_trigger_status_mask(); touch_ll_intr_disable(TOUCH_PAD_INTR_ALL); } void touch_hal_filter_set_config(const touch_filter_config_t *filter_info) { touch_ll_filter_set_filter_mode(filter_info->mode); touch_ll_filter_set_debounce(filter_info->debounce_cnt); touch_ll_filter_set_hysteresis(filter_info->hysteresis_thr); touch_ll_filter_set_noise_thres(filter_info->noise_thr); touch_ll_filter_set_neg_noise_thres(filter_info->noise_neg_thr); touch_ll_filter_set_baseline_reset(filter_info->neg_noise_limit); touch_ll_filter_set_jitter_step(filter_info->jitter_step); } void touch_hal_filter_get_config(touch_filter_config_t *filter_info) { touch_ll_filter_get_filter_mode(&filter_info->mode); touch_ll_filter_get_debounce(&filter_info->debounce_cnt); touch_ll_filter_get_hysteresis(&filter_info->hysteresis_thr); touch_ll_filter_get_noise_thres(&filter_info->noise_thr); touch_ll_filter_get_neg_noise_thres(&filter_info->noise_neg_thr); touch_ll_filter_get_baseline_reset(&filter_info->neg_noise_limit); touch_ll_filter_get_jitter_step(&filter_info->jitter_step); } void touch_hal_denoise_set_config(const touch_pad_denoise_t *denoise) { touch_ll_denoise_set_cap_level(denoise->cap_level); touch_ll_denoise_set_grade(denoise->grade); } void touch_hal_denoise_get_config(touch_pad_denoise_t *denoise) { touch_ll_denoise_get_cap_level(&denoise->cap_level); touch_ll_denoise_get_grade(&denoise->grade); } void touch_hal_denoise_enable(void) { touch_ll_clear_channel_mask(1U << SOC_TOUCH_DENOISE_CHANNEL); touch_ll_denoise_enable(); } void touch_hal_waterproof_set_config(const touch_pad_waterproof_t *waterproof) { touch_ll_waterproof_set_guard_pad(waterproof->guard_ring_pad); touch_ll_waterproof_set_sheild_driver(waterproof->shield_driver); } void touch_hal_waterproof_get_config(touch_pad_waterproof_t *waterproof) { touch_ll_waterproof_get_guard_pad(&waterproof->guard_ring_pad); touch_ll_waterproof_get_sheild_driver(&waterproof->shield_driver); } void touch_hal_waterproof_enable(void) { touch_ll_clear_channel_mask(1U << SOC_TOUCH_SHIELD_CHANNEL); touch_ll_waterproof_enable(); } void touch_hal_proximity_set_config(const touch_pad_proximity_t *proximity) { touch_ll_proximity_set_channel_num(proximity->select_pad); touch_ll_proximity_set_meas_times(proximity->meas_num); } void touch_hal_proximity_get_config(touch_pad_proximity_t *proximity) { touch_ll_proximity_get_channel_num(proximity->select_pad); touch_ll_proximity_get_meas_times(&proximity->meas_num); } void touch_hal_sleep_channel_config(const touch_pad_sleep_channel_t *slp_config) { touch_ll_sleep_set_channel_num(slp_config->touch_num); touch_ll_sleep_set_threshold(slp_config->sleep_pad_threshold); if (slp_config->en_proximity) { touch_ll_sleep_enable_approach(); } else { touch_ll_sleep_disable_approach(); } }
UKHomeOffice/passenger
modules/module-data-passenger/src/test/java/org/gov/uk/homeoffice/digital/permissions/passenger/domain/visa/VisaTypeServiceBeanTest.java
<gh_stars>0 package org.gov.uk.homeoffice.digital.permissions.passenger.domain.visa; import org.gov.uk.homeoffice.digital.permissions.passenger.domain.*; import org.gov.uk.homeoffice.digital.permissions.passenger.utils.Tuple; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.time.LocalDateTime; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static com.google.common.collect.Lists.newArrayList; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class VisaTypeServiceBeanTest { @Mock private VisaTypeRepository mockVisaTypeRepository; @Mock private VisaRuleLookupRepository mockVisaRuleLookupRepository; @InjectMocks private VisaTypeServiceBean underTest; @Test public void noVisaRuleFound() { VisaRecord visaRecord = new VisaRecord(VisaStatus.ISSUED, VisaType.createVisaType("None"), tier4GeneralStudentRules()); when(mockVisaTypeRepository.findAll()).thenReturn(visaTypeCollection()); final Tuple<Optional<VisaTypeRule>, List<String>> visaTypeRule = underTest.findVisaTypeRule(visaRecord); Assert.assertThat(visaTypeRule.get_1().isPresent(), CoreMatchers.is(false)); Assert.assertThat(visaTypeRule.get_2().get(0), CoreMatchers.is("No rules matched for input type None")); } @Test public void shouldFindSingleVisaRule() { VisaRecord visaRecord = new VisaRecord(VisaStatus.ISSUED, VisaType.createVisaType("Tier 4 (General) Student"), tier4GeneralStudentRules()); when(mockVisaTypeRepository.findAll()).thenReturn(visaTypeCollection()); when(mockVisaRuleLookupRepository.findByVisaType(1L)).thenReturn(toVisaRules(tier4GeneralStudentRules())); final Tuple<Optional<VisaTypeRule>, List<String>> visaTypeRule = underTest.findVisaTypeRule(visaRecord); Assert.assertThat(visaTypeRule.get_1().isPresent(), CoreMatchers.is(true)); } @Test public void shouldResolveMultipleVisaRules() { final VisaRecord visaRecord = new VisaRecord(VisaStatus.ISSUED, VisaType.createVisaType("Tier 4 (General) Dependent Child"), tier4GeneralDependentChild12MonthsMinusRules()); when(mockVisaTypeRepository.findAll()).thenReturn(visaTypeCollection()); when(mockVisaRuleLookupRepository.findByVisaType(6L)).thenReturn(toVisaRules(tier4GeneralDependentChild12MonthsPlusRules())); when(mockVisaRuleLookupRepository.findByVisaType(7L)).thenReturn(toVisaRules(tier4GeneralDependentChild12MonthsMinusRules())); final Tuple<Optional<VisaTypeRule>, List<String>> visaTypeRule = underTest.findVisaTypeRule(visaRecord); visaTypeRule.get_1().ifPresentOrElse(rule -> { assertTrue(rule.hasVisaRule("VALID_UNTIL")); assertTrue(rule.hasVisaRule("VISA_TYPE")); assertTrue(rule.hasVisaRule("NAME")); assertTrue(rule.hasVisaRule("PASSPORT_NUMBER")); assertTrue(rule.hasVisaRule("NATIONALITY")); assertTrue(rule.hasVisaRule("DATE_OF_BIRTH")); assertTrue(rule.hasVisaRule("CODE_3")); assertTrue(rule.hasVisaRule("ADDITIONAL_ENDORSEMENT")); assertTrue(rule.hasVisaRule("SPX_NUMBER")); assertTrue(rule.hasVisaRule("SPORTS")); assertTrue(rule.hasVisaRule("POLICE_REGISTRATION_VN")); }, () -> fail("Expected a visa type rule.")); } private Collection<VisaType> visaTypeCollection() { return newArrayList( new VisaType(1L, "Tier 4 (General) Student", null, null, true, LocalDateTime.now()), new VisaType(2L, "Tier 4 (Child(S))", null, null, true, LocalDateTime.now()), new VisaType(3L, "Tier 4 (Child) Student 16-", null, null, true, LocalDateTime.now()), new VisaType(4L, "Tier 4 (Child) Student 16+", null, null, true, LocalDateTime.now()), new VisaType(5L, "Tier 4 (General(S)) Student", null, null, true, LocalDateTime.now()), new VisaType(6L, "Tier 4 (General) Dependent Child", "12 Months+", null, true, LocalDateTime.now()), new VisaType(7L, "Tier 4 (General) Dependent Child", "12 Months-", null, true, LocalDateTime.now()) ); } private Collection<Tuple<VisaRule, Collection<VisaRuleContent>>> tier4GeneralStudentRules() { return newArrayList( new Tuple<>(new VisaRule("VALID_UNTIL"), null), new Tuple<>(new VisaRule("VISA_TYPE"), null), new Tuple<>(new VisaRule("NAME"), null), new Tuple<>(new VisaRule("PASSPORT_NUMBER"), null), new Tuple<>(new VisaRule("NATIONALITY"), null), new Tuple<>(new VisaRule("DATE_OF_BIRTH"), null), new Tuple<>(new VisaRule("CODE_3"), null), new Tuple<>(new VisaRule("CAS_NUMBER"), null), new Tuple<>(new VisaRule("SPX_NUMBER"), null), new Tuple<>(new VisaRule("POLICE_REGISTRATION_VN"), null) ); } private Collection<Tuple<VisaRule, Collection<VisaRuleContent>>> tier4GeneralDependentChild12MonthsPlusRules() { return newArrayList( new Tuple<>(new VisaRule("VALID_UNTIL"), null), new Tuple<>(new VisaRule("VISA_TYPE"), null), new Tuple<>(new VisaRule("NAME"), null), new Tuple<>(new VisaRule("PASSPORT_NUMBER"), null), new Tuple<>(new VisaRule("NATIONALITY"), null), new Tuple<>(new VisaRule("DATE_OF_BIRTH"), null), new Tuple<>(new VisaRule("CODE_1"), null), new Tuple<>(new VisaRule("ADDITIONAL_ENDORSEMENT"), null), new Tuple<>(new VisaRule("SPX_NUMBER"), null), new Tuple<>(new VisaRule("SPORTS"), null), new Tuple<>(new VisaRule("POLICE_REGISTRATION_VN"), null) ); } private Collection<Tuple<VisaRule, Collection<VisaRuleContent>>> tier4GeneralDependentChild12MonthsMinusRules() { return newArrayList( new Tuple<>(new VisaRule("VALID_UNTIL"), null), new Tuple<>(new VisaRule("VISA_TYPE"), null), new Tuple<>(new VisaRule("NAME"), null), new Tuple<>(new VisaRule("PASSPORT_NUMBER"), null), new Tuple<>(new VisaRule("NATIONALITY"), null), new Tuple<>(new VisaRule("DATE_OF_BIRTH"), null), new Tuple<>(new VisaRule("CODE_3"), null), new Tuple<>(new VisaRule("ADDITIONAL_ENDORSEMENT"), null), new Tuple<>(new VisaRule("SPX_NUMBER"), null), new Tuple<>(new VisaRule("SPORTS"), null), new Tuple<>(new VisaRule("POLICE_REGISTRATION_VN"), null) ); } private Collection<VisaRule> toVisaRules(Collection<Tuple<VisaRule, Collection<VisaRuleContent>>> visaRules) { return visaRules.stream().map(Tuple::get_1).collect(Collectors.toList()); } }
lazurcavali/chunky
web/packager/webPlugin.js
'use strict' let chalk = require('chalk') let path = require('path') let Ora = require('ora') let ejs = require('ejs') const emotions = require('./emotions.json') class Plugin { constructor (context) { this._context = context this._spinner = new Ora({ text: chalk.green('Chunky is getting ready to start packing'), spinner: 'dots', color: 'yellow', stream: process.stdout }) } emotion (type) { if (!emotions || !emotions[type]) { return 'Chunky is confused.' } const expression = emotions[type].expression const moods = emotions[type].moods const mood = moods[Math.floor(Math.random() * Math.floor(moods.length - 1))] return { expression, mood } } get happy () { return this.emotion('happy') } get context () { return this._context } get spinner () { return this._spinner } get startTime () { return this._startTime } onStart () { this._startTime = new Date().getTime() this.spinner.start() } onModuleStart (module) { } onModuleFailure (module) { if (!module.resource) { // Ignore context logging return } var resource = module.resource.substring(path.resolve('.').length + 1) this.spinner.fail(module.resource) this.spinner.fail(module.error) } onModuleSuccess (module) { if (module.errors && module.errors.length > 0) { var resource = module.resource.substring(path.resolve('.').length + 1) this.spinner.fail(resource) this.spinner.fail(module.errors[0]) return } if (!module.resource) { // Ignore context logging return } var resource = module.resource.substring(path.resolve('.').length + 1) this.spinner.text = `${chalk.white('Chunky is packing')} ${chalk.green(resource)}` } endTime (startTime) { const time = new Date().getTime() - startTime return (time < 1000 ? time + 'ms' : (parseFloat(time / 1000).toFixed(2) + 's')) } resolveHtml (data, html) { const route = Object.assign({}, data.plugin.options.route, html ? { html } : {}) const info = this.context.config.info const web = this.context.config.web const vars = JSON.stringify({ route: data.plugin.options.route }) const chunky = { route, info, web, vars } data.html = ejs.render(data.html, { chunky }) return data } onPageGeneration (compilation, data, done) { done(null, this.resolveHtml(data)) } onDone (stats) { if (stats.compilation.errors && stats.compilation.errors.length > 0) { stats.compilation.errors.map(error => { this.spinner.fail(error) }) this.spinner.fail(`${chalk.red('Chunky failed packing. And he is devastated.')}`) return } const time = this.endTime(this.startTime) this.spinner.succeed(`${chalk.green('Chunky finished packing in')} ${chalk.bold(time)} ${chalk.gray(this.happy.expression)} ${chalk.gray(this.happy.mood)}`) } apply (compiler) { compiler.plugin('compile', (params) => this.onStart()) compiler.plugin('compilation', (compilation) => { compilation.plugin('html-webpack-plugin-before-html-processing', (data, done) => this.onPageGeneration(compilation, data, done)) compilation.plugin('build-module', (module) => this.onModuleStart(module)) compilation.plugin('failed-module', (module) => this.onModuleFailure(module)) compilation.plugin('succeed-module', (module) => this.onModuleSuccess(module)) }) compiler.plugin('done', (stats) => this.onDone(stats)) } } module.exports = Plugin
figurefix/prac
src/test/java/figurefix/prac/test/logging/sample/package-info.java
<filename>src/test/java/figurefix/prac/test/logging/sample/package-info.java<gh_stars>0 /** * */ /** * @author XZF * */ package figurefix.prac.test.logging.sample;
PrakulSmarty/Code
database/alinosql/alinosql.go
package alinosql //ListTables list tables func (alinosql *Alinosql) ListTables(request interface{}) (resp interface{}, err error) { return resp, err } //DeleteTables delete tables func (alinosql *Alinosql) DeleteTables(request interface{}) (resp interface{}, err error) { return resp, err } //DescribeTables Describe tables func (alinosql *Alinosql) DescribeTables(request interface{}) (resp interface{}, err error) { return resp, err } //CreateTables create tables func (alinosql *Alinosql) CreateTables(request interface{}) (resp interface{}, err error) { return resp, err }
marcus8448/Mekanism
Mekanism/src/main/java/mekanism/common/lib/math/Plane.java
<reponame>marcus8448/Mekanism<filename>Mekanism/src/main/java/mekanism/common/lib/math/Plane.java package mekanism.common.lib.math; import java.util.Random; import mekanism.common.lib.math.voxel.VoxelCuboid; import mekanism.common.lib.math.voxel.VoxelCuboid.CuboidSide; import net.minecraft.util.math.Vec3d; // can add to this as we see necessary public class Plane { private final Vec3d minPos; private final Vec3d maxPos; public Plane(Vec3d minPos, Vec3d maxPos) { this.minPos = minPos; this.maxPos = maxPos; } public static Plane getInnerCuboidPlane(VoxelCuboid cuboid, CuboidSide side) { int minX = cuboid.getMinPos().getX() + 1, minY = cuboid.getMinPos().getY() + 1, minZ = cuboid.getMinPos().getZ() + 1; int maxX = cuboid.getMaxPos().getX(), maxY = cuboid.getMaxPos().getY(), maxZ = cuboid.getMaxPos().getZ(); switch (side) { case NORTH: return new Plane(new Vec3d(minX, minY, minZ), new Vec3d(maxX, maxY, minZ)); case SOUTH: return new Plane(new Vec3d(minX, minY, maxZ), new Vec3d(maxX, maxY, maxZ)); case WEST: return new Plane(new Vec3d(minX, minY, minZ), new Vec3d(minX, maxY, maxZ)); case EAST: return new Plane(new Vec3d(maxX, minY, minZ), new Vec3d(maxX, maxY, maxZ)); case BOTTOM: return new Plane(new Vec3d(minX, minY, minZ), new Vec3d(maxX, minY, maxZ)); case TOP: return new Plane(new Vec3d(minX, maxY, minZ), new Vec3d(maxX, maxY, maxZ)); } return null; } public Vec3d getRandomPoint(Random rand) { return new Vec3d(minPos.x + rand.nextDouble() * (maxPos.x - minPos.x), minPos.y + rand.nextDouble() * (maxPos.y - minPos.y), minPos.z + rand.nextDouble() * (maxPos.z - minPos.z)); } }
hmrc/essttp-backend
cor-journey/src/main/scala/essttp/journey/model/OriginatedSjRequest.scala
<reponame>hmrc/essttp-backend /* * Copyright 2022 HM Revenue & Customs * * 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 essttp.journey.model /** * A temporary structure which binds both [[Origin]] and [[SjRequest]] of the same "type" * (Vat to Vat, Sdil to Sdil, Cds to Cds, etc) */ sealed trait OriginatedSjRequest { def origin: Origin def sjRequest: SjRequest } object OriginatedSjRequest { final case class Epaye( override val origin: Origins.Epaye, override val sjRequest: SjRequest.Epaye ) extends OriginatedSjRequest }
programmerraja/discussy
routes/users.js
<reponame>programmerraja/discussy const express = require("express"); const router = express.Router(); //controller const userController = require("../controllers/userController.js"); //middleware const Auth = require("../middleware/auth.js"); const checkMailVerified = require("../middleware/checkMailVerified.js"); //user routes router.post("/signin", userController.signIn); router.post("/signup", userController.signUp); router.get("/verifiyMyEmail/:userId", userController.verifiyMyEmail); router.get("/getMyProfile", Auth.isAuthenticatedUser(), userController.getMyProfile); router.post("/updateMyProfile", Auth.isAuthenticatedUser(), userController.updateMyProfile); router.post("/forgetMyPassword", userController.forgetMyPassword); router.post("/resetMyPassword", userController.resetMyPassword); //user question routes router.get("/getMyQuestions", Auth.isAuthenticatedUser(), userController.getMyQuestions); router.get("/getMySortedQuestions", Auth.isAuthenticatedUser(), userController.getMySortedQuestions); router.get("/getMyQuestion/:questionId", Auth.isAuthenticatedUser(), userController.getMyQuestion); router.get("/likeMyQuestion/:questionId", Auth.isAuthenticatedUser(), checkMailVerified, userController.likeMyQuestion); router.post("/addMyQuestion", Auth.isAuthenticatedUser(), checkMailVerified, userController.addMyQuestion); router.post("/updateMyQuestion", Auth.isAuthenticatedUser(), checkMailVerified, userController.updateMyQuestion); router.get("/deleteMyQuestion/:questionId/", Auth.isAuthenticatedUser(), userController.deleteMyQuestion); //user answer routes router.get("/getMyAnswers", Auth.isAuthenticatedUser(), userController.getMyAnswers); router.get("/getMyAnswer/:answerId", Auth.isAuthenticatedUser(), userController.getMyAnswer); router.get("/likeMyAnswer/:answerId", Auth.isAuthenticatedUser(), checkMailVerified, userController.likeMyAnswer); router.post("/addMyAnswer", Auth.isAuthenticatedUser(), checkMailVerified, userController.addMyAnswer); router.post("/updateMyAnswer", Auth.isAuthenticatedUser(), userController.updateMyAnswer); router.get("/deleteMyAnswer/:answerId/", Auth.isAuthenticatedUser(), userController.deleteMyAnswer); module.exports = router;
mcfongtw/LostInCompilation
docs/doxygen/shacat/html/search/classes_2.js
<reponame>mcfongtw/LostInCompilation var searchData= [ ['hackprivate',['HackPrivate',['../structHackPrivate.html',1,'']]], ['hackproxy',['HackProxy',['../structHackProxy.html',1,'']]] ];
janakamarasena/carbon-business-process
components/bpel/org.wso2.carbon.bpel.cluster.notifier/src/main/java/org/wso2/carbon/bpel/cluster/notifier/BPELClusterNotifier.java
<filename>components/bpel/org.wso2.carbon.bpel.cluster.notifier/src/main/java/org/wso2/carbon/bpel/cluster/notifier/BPELClusterNotifier.java<gh_stars>1-10 package org.wso2.carbon.bpel.cluster.notifier; import org.apache.axis2.AxisFault; import org.apache.axis2.clustering.state.Replicator; import org.apache.axis2.clustering.state.StateClusteringCommand; import org.apache.axis2.engine.AxisConfiguration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.bpel.cluster.notifier.internal.BPELClusterNotifierServiceComponent; /** * Send Clustering Commands. * * We have introduce a separate bundle for this, in order to isolate the ConfigurationContext OSGI * service from the BPEL Core bundle. So that we can have * <Axis2RequiredServices>org.wso2.carbon.bpel.core.BPELEngineService</Axis2RequiredServices> * element in the BPEL deployers pom */ public final class BPELClusterNotifier { public static final String PARAM_PARENT_PROCESS_STORE = "bpel.process-store"; private static Log log = LogFactory.getLog(BPELClusterNotifier.class); private BPELClusterNotifier() { } public static void sendClusterNotification(StateClusteringCommand command, Object processStore) throws AxisFault { if (log.isDebugEnabled()) { log.debug("Sending clustering command."); } AxisConfiguration axisConfig = BPELClusterNotifierServiceComponent.getAxisConfiguration(); axisConfig.addParameter(PARAM_PARENT_PROCESS_STORE, processStore); Replicator.replicateState(command, axisConfig); } }
OpenTouhou/OpenTouhouAndroid
math/src/main/java/com/scarlet/math/CubicBezierCurve.java
<filename>math/src/main/java/com/scarlet/math/CubicBezierCurve.java package com.scarlet.math; public class CubicBezierCurve { private Vector3f[] points; /* * Constructor(s). */ public CubicBezierCurve(Vector3f[] points) { this.points = points; } /* * Getter(s). */ public Vector3f getStart() { return points[0]; } public Vector3f getEnd() { return points[3]; } public Vector3f getPoint(float t) { float diff = 1 - t; float c_0 = diff * diff * diff; float c_1 = 3 * diff * diff * t; float c_2 = 3 * diff * t * t; float c_3 = t * t * t; return points[0].multiply(c_0).add(points[1].multiply(c_1).add(points[2].multiply(c_2).add(points[3].multiply(c_3)))); } /* * Subdivide a bezier curve into points. */ public Vector3f[] subdivide(int numberOfPoints) { // Check the input. if (numberOfPoints < 2) throw new RuntimeException("Cannot subdivide a bezier curve with less than 2 points."); // Allocate a new array and compute the interval length. float interval = 1.0f / (numberOfPoints - 1); Vector3f[] points = new Vector3f[numberOfPoints]; // Compute the points. for (int i = 0; i < numberOfPoints; i++) points[i] = getPoint(i * interval); return points; } }
lattwood/datadog-agent
pkg/util/winutil/iphelper/adapters.go
<reponame>lattwood/datadog-agent<gh_stars>0 // Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2018-present Datadog, Inc. //go:build windows // +build windows package iphelper import ( "C" "fmt" "golang.org/x/sys/windows" "net" "syscall" "unsafe" ) var ( procGetAdaptersAddresses = modiphelper.NewProc("GetAdaptersAddresses") ) type IPAdapterUnicastAddress struct { Flags uint32 Address net.IP } type sockaddr struct { family int16 port uint16 // if it's ipv4, the address is the first 4 bytes // if it's ipv6, the address is bytes 4->20 addressBase uintptr } type socketAddress struct { lpSockaddr *sockaddr iSockaddrLength int32 } type ipAdapterUnicastAddress struct { length uint32 flags uint32 next *ipAdapterUnicastAddress address socketAddress } // IpAdapterAddressesLh is a go adaptation of the C structure IP_ADAPTER_ADDRESSES_LH // it is a go adaptation, rather than a matching structure, because the real structure // is difficult to approximate in Go. type IpAdapterAddressesLh struct { Index uint32 AdapterName string UnicastAddresses []IPAdapterUnicastAddress } type ipAdapterAddresses struct { length uint32 ifIndex uint32 next *ipAdapterAddresses adapterName unsafe.Pointer // pointer to character buffer firstUnicastAddress *ipAdapterUnicastAddress } // GetAdaptersAddresses returns a map of all of the adapters, indexed by // interface index func GetAdaptersAddresses() (table map[uint32]IpAdapterAddressesLh, err error) { size := uint32(15 * 1024) rawbuf := make([]byte, size) r, _, _ := procGetAdaptersAddresses.Call(uintptr(syscall.AF_INET), uintptr(0), // flags == 0 for now uintptr(0), // reserved, always zero uintptr(unsafe.Pointer(&rawbuf[0])), uintptr(unsafe.Pointer(&size))) if r != 0 { if r != uintptr(windows.ERROR_BUFFER_OVERFLOW) { err = fmt.Errorf("Error getting address list %v", r) return } rawbuf = make([]byte, size) r, _, _ := procGetAdaptersAddresses.Call(uintptr(syscall.AF_INET), uintptr(0), // flags == 0 for now uintptr(0), // reserved, always zero uintptr(unsafe.Pointer(&rawbuf[0])), uintptr(unsafe.Pointer(&size))) if r != 0 { err = fmt.Errorf("Error getting address list %v", r) return } } // need to walk the list. The list is a C style list. The `Next` pointer // is not the first element. The C structure is as follows /* typedef struct _IP_ADAPTER_ADDRESSES_LH { union { ULONGLONG Alignment; struct { ULONG Length; IF_INDEX IfIndex; }; }; struct _IP_ADAPTER_ADDRESSES_LH *Next; PCHAR AdapterName; PIP_ADAPTER_UNICAST_ADDRESS_LH FirstUnicastAddress; // more fields follow which we're not using */ var addr *ipAdapterAddresses table = make(map[uint32]IpAdapterAddressesLh) addr = (*ipAdapterAddresses)(unsafe.Pointer(&rawbuf[0])) for addr != nil { var entry IpAdapterAddressesLh entry.Index = addr.ifIndex entry.AdapterName = C.GoString((*C.char)(addr.adapterName)) unicast := addr.firstUnicastAddress for unicast != nil { if unicast.address.lpSockaddr.family == syscall.AF_INET { // ipv4 address var uni IPAdapterUnicastAddress uni.Address = (*[1 << 29]byte)(unsafe.Pointer(unicast.address.lpSockaddr))[4:8:8] entry.UnicastAddresses = append(entry.UnicastAddresses, uni) } else if unicast.address.lpSockaddr.family == syscall.AF_INET6 { var uni IPAdapterUnicastAddress uni.Address = (*[1 << 29]byte)(unsafe.Pointer(&(unicast.address.lpSockaddr.addressBase)))[:16:16] entry.UnicastAddresses = append(entry.UnicastAddresses, uni) } unicast = unicast.next } table[entry.Index] = entry addr = addr.next } return }
jwhudnall/2021-web-dev-bootcamp
section-25/FormEvents/InputEventPractice/app.js
<filename>section-25/FormEvents/InputEventPractice/app.js const h1 = document.querySelector('h1'); const field = document.querySelector('#username'); field.addEventListener('input', function(e) { if(field.value.length === 0) { h1.textContent = 'Enter Your Username'; } else { const welcomeMsg = 'Welcome, '; h1.textContent = `${welcomeMsg} ${field.value}`; } })
ibalajiarun/go-consensus
protocols/dispel/epoch.go
package dispel import ( "github.com/ibalajiarun/go-consensus/peer/peerpb" pb "github.com/ibalajiarun/go-consensus/protocols/dispel/dispelpb" ) type epoch struct { epochNum pb.Epoch rbDoneCount int consDoneCount int rbs map[peerpb.PeerID]*rbroadcast cons map[peerpb.PeerID]*dbft d *Dispel } func makeEpoch(m *pb.RBMessage, d *Dispel) *epoch { e := &epoch{ epochNum: m.EpochNum, rbs: make(map[peerpb.PeerID]*rbroadcast), cons: make(map[peerpb.PeerID]*dbft), d: d, } return e }
CalamityC/ui-agreements
src/routes/AgreementEditRoute.js
<filename>src/routes/AgreementEditRoute.js import React from 'react'; import PropTypes from 'prop-types'; import { cloneDeep } from 'lodash'; import compose from 'compose-function'; import SafeHTMLMessage from '@folio/react-intl-safe-html'; import { LoadingView } from '@folio/stripes/components'; import { CalloutContext, stripesConnect } from '@folio/stripes/core'; import { checkScope, collapseAllSections, expandAllSections, withAsyncValidation } from '@folio/stripes-erm-components'; import withFileHandlers from './components/withFileHandlers'; import { joinRelatedAgreements, splitRelatedAgreements } from './utilities/processRelatedAgreements'; import View from '../components/views/AgreementForm'; import NoPermissions from '../components/NoPermissions'; import { urls } from '../components/utilities'; const RECORDS_PER_REQUEST = 100; class AgreementEditRoute extends React.Component { static manifest = Object.freeze({ agreement: { type: 'okapi', path: 'erm/sas/:{id}', shouldRefresh: () => false, }, agreementLines: { type: 'okapi', path: 'erm/entitlements', params: { filters: 'owner=:{id}', sort: 'resource.name', stats: 'true', }, limitParam: 'perPage', perRequest: RECORDS_PER_REQUEST, records: 'results', recordsRequired: '1000', }, agreementStatusValues: { type: 'okapi', path: 'erm/refdata/SubscriptionAgreement/agreementStatus', shouldRefresh: () => false, }, reasonForClosureValues: { type: 'okapi', path: 'erm/refdata/SubscriptionAgreement/reasonForClosure', limitParam: 'perPage', perRequest: RECORDS_PER_REQUEST, shouldRefresh: () => false, }, amendmentStatusValues: { type: 'okapi', path: 'erm/refdata/LicenseAmendmentStatus/status', shouldRefresh: () => false, }, contactRoleValues: { type: 'okapi', path: 'erm/refdata/InternalContact/role', limitParam: 'perPage', perRequest: RECORDS_PER_REQUEST, shouldRefresh: () => false, }, documentCategories: { type: 'okapi', path: 'erm/refdata/DocumentAttachment/atType', limitParam: 'perPage', perRequest: RECORDS_PER_REQUEST, shouldRefresh: () => false, }, isPerpetualValues: { type: 'okapi', path: 'erm/refdata/SubscriptionAgreement/isPerpetual', shouldRefresh: () => false, }, licenseLinkStatusValues: { type: 'okapi', path: 'erm/refdata/RemoteLicenseLink/status', shouldRefresh: () => false, }, orderLines: { type: 'okapi', path: 'orders/order-lines', params: (_q, _p, _r, _l, props) => { const query = (props?.resources?.agreementLines?.records ?? []) .filter(line => line.poLines && line.poLines.length) .map(line => (line.poLines .map(poLine => `id==${poLine.poLineId}`) .join(' or ') )) .join(' or '); return query ? { query } : null; }, fetch: props => !!props.stripes.hasInterface('order-lines', '1.0'), records: 'poLines', }, orgRoleValues: { type: 'okapi', path: 'erm/refdata/SubscriptionAgreementOrg/role', shouldRefresh: () => false, }, renewalPriorityValues: { type: 'okapi', path: 'erm/refdata/SubscriptionAgreement/renewalPriority', limitParam: 'perPage', perRequest: RECORDS_PER_REQUEST, shouldRefresh: () => false, }, relationshipTypeValues: { type: 'okapi', path: 'erm/refdata/AgreementRelationship/type', shouldRefresh: () => false, }, supplementaryProperties: { type: 'okapi', path: 'erm/custprops', shouldRefresh: () => false, }, users: { type: 'okapi', path: 'users', perRequest: RECORDS_PER_REQUEST, params: (_q, _p, _r, _l, props) => { const query = (props?.resources?.agreement?.records?.[0]?.contacts ?? []) .filter(contact => contact.user) .map(contact => `id==${contact.user}`) .join(' or '); return query ? { query } : null; }, fetch: props => !!props.stripes.hasInterface('users', '15.0'), permissionsRequired: 'users.collection.get', records: 'users', }, basket: { initialValue: [] }, query: { initialValue: {} }, }); static propTypes = { checkAsyncValidation: PropTypes.func, handlers: PropTypes.object, history: PropTypes.shape({ push: PropTypes.func.isRequired, }).isRequired, location: PropTypes.shape({ search: PropTypes.string.isRequired, }).isRequired, match: PropTypes.shape({ params: PropTypes.shape({ id: PropTypes.string.isRequired, }).isRequired, }).isRequired, mutator: PropTypes.shape({ agreement: PropTypes.shape({ PUT: PropTypes.func.isRequired, }), agreements: PropTypes.shape({ PUT: PropTypes.func.isRequired, }), query: PropTypes.shape({ update: PropTypes.func.isRequired }).isRequired, }).isRequired, resources: PropTypes.shape({ agreement: PropTypes.object, agreementLines: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), agreementStatusValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), amendmentStatusValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), basket: PropTypes.arrayOf(PropTypes.object), contactRoleValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), documentCategories: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), externalAgreementLine: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), isPerpetualValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), licenseLinkStatusValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), orderLines: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), orgRoleValues: PropTypes.object, query: PropTypes.shape({ addFromBasket: PropTypes.string, }), reasonForClosureValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), relationshipTypeValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), renewalPriorityValues: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), statusValues: PropTypes.object, supplementaryProperties: PropTypes.object, typeValues: PropTypes.object, users: PropTypes.shape({ records: PropTypes.arrayOf(PropTypes.object), }), }).isRequired, stripes: PropTypes.shape({ hasInterface: PropTypes.func.isRequired, hasPerm: PropTypes.func.isRequired, okapi: PropTypes.object.isRequired, }).isRequired, }; static defaultProps = { handlers: { }, } static contextType = CalloutContext; constructor(props) { super(props); this.state = { hasPerms: props.stripes.hasPerm('ui-agreements.agreements.edit'), initialValues: {}, }; } static getDerivedStateFromProps(props, state) { let updated = false; const agreement = props?.resources?.agreement?.records?.[0] ?? {}; // Start with the existing initialValues. However, if we've just fetched a new agreement // then use that as the baseline. This would be the case if we didn't have an agreement in // resources at first, but also if we pulled stale agreement data from `resources` when this // component was inited. Eg, when viewing one agreement and then entering the Edit screen // for another agreement without viewing it first. This would occur when adding to an agreement // via the Basket. let initialValues = state.initialValues; if (agreement.id === props.match.params.id && !initialValues.id) { initialValues = cloneDeep(agreement); } const { agreementStatus = {}, contacts = [], isPerpetual = {}, items = [], linkedLicenses = [], orgs = [], reasonForClosure = {}, renewalPriority = {}, supplementaryDocs = [], } = initialValues; if (initialValues.id !== state.initialValues.id) { updated = true; // Set the values of dropdown-controlled props as values rather than objects. initialValues.agreementStatus = agreementStatus.value; initialValues.isPerpetual = isPerpetual.value; initialValues.reasonForClosure = reasonForClosure.value; initialValues.renewalPriority = renewalPriority.value; initialValues.contacts = contacts.map(c => ({ ...c, role: c.role.value })); initialValues.orgs = orgs.map(o => ({ ...o, role: o.role && o.role.value })); initialValues.supplementaryDocs = supplementaryDocs.map(o => ({ ...o, atType: o.atType?.value })); initialValues.linkedLicenses = linkedLicenses.map(l => ({ ...l, status: l.status.value, // Init the list of amendments based on the license's amendments to ensure // we display those that have been created since this agreement's license was last // edited. Ensure we provide defaults via amendmentId. // eslint-disable-next-line camelcase amendments: (l?.remoteId_object?.amendments ?? []) .map(a => { const assignedAmendment = (l.amendments || []).find(la => la.amendmentId === a.id) || {}; return { ...assignedAmendment, amendmentId: a.id, status: assignedAmendment.status ? assignedAmendment.status.value : undefined, }; }) })); // Add the default supplementaryProperties to the already-set supplementaryProperties. initialValues.customProperties = initialValues.customProperties || {}; const supplementaryProperties = (props?.resources?.supplementaryProperties?.records ?? []); supplementaryProperties .filter(t => t.primary && initialValues.customProperties[t.name] === undefined) .forEach(t => { initialValues.customProperties[t.name] = ''; }); compose( joinRelatedAgreements, )(initialValues); } const lines = (props?.resources?.agreementLines?.records ?? []); if (items.length && lines.length && (lines[0].owner.id === props.match.params.id)) { updated = true; initialValues.items = items.map(item => { if (item.resource) return item; const line = lines.find(l => l.id === item.id); if (!line) return item; return { id: line.id, coverage: line.customCoverage ? line.coverage : undefined, poLines: line.poLines, activeFrom: line.startDate, activeTo: line.endDate, note: line.note }; }); } if (updated) { return { initialValues }; } return null; } handleBasketLinesAdded = () => { this.props.mutator.query.update({ addFromBasket: null, authority: null, referenceId: null, }); } handleClose = () => { const { location, match } = this.props; this.props.history.push(`${urls.agreementView(match.params.id)}${location.search}`); } handleSubmit = (agreement) => { const { history, location, mutator, resources } = this.props; const relationshipTypeValues = resources?.relationshipTypeValues?.records ?? []; const name = agreement?.name; compose( splitRelatedAgreements, )(agreement, relationshipTypeValues); return mutator.agreement .PUT(agreement) .then(({ id }) => { this.context.sendCallout({ message: <SafeHTMLMessage id="ui-agreements.agreements.update.callout" values={{ name }} /> }); history.push(`${urls.agreementView(id)}${location.search}`); }); } getAgreementLines = () => { return [ ...(this.props.resources?.agreementLines?.records ?? []), ...this.getAgreementLinesToAdd(), ]; } getAgreementLinesToAdd = () => { const { resources } = this.props; const { query: { addFromBasket } } = resources; const externalAgreementLines = resources?.externalAgreementLine?.records ?? []; let basketLines = []; if (resources.query.addFromBasket) { const basket = resources?.basket ?? []; basketLines = addFromBasket .split(',') .map(index => ({ resource: basket[parseInt(index, 10)] })) .filter(line => line.resource); // sanity check that there _was_ an item at that index } return [ ...externalAgreementLines, ...basketLines, ]; } fetchIsPending = () => { return Object.values(this.props.resources) .filter(r => r && r.resource !== 'agreements') .some(r => r.isPending); } render() { const { handlers, resources } = this.props; if (!this.state.hasPerms) return <NoPermissions />; if (this.fetchIsPending()) return <LoadingView dismissible onClose={this.handleClose} />; return ( <View data={{ agreementLines: this.getAgreementLines(), agreementLinesToAdd: this.getAgreementLinesToAdd(), agreementStatusValues: resources?.agreementStatusValues?.records ?? [], reasonForClosureValues: resources?.reasonForClosureValues?.records ?? [], amendmentStatusValues: resources?.amendmentStatusValues?.records ?? [], basket: resources?.basket ?? [], contactRoleValues: resources?.contactRoleValues?.records ?? [], documentCategories: resources?.documentCategories?.records ?? [], externalAgreementLine: resources?.externalAgreementLine?.records ?? [], isPerpetualValues: resources?.isPerpetualValues?.records ?? [], licenseLinkStatusValues: resources?.licenseLinkStatusValues?.records ?? [], orderLines: resources?.orderLines?.records ?? [], orgRoleValues: resources?.orgRoleValues?.records ?? [], renewalPriorityValues: resources?.renewalPriorityValues?.records ?? [], supplementaryProperties: resources?.supplementaryProperties?.records ?? [], users: resources?.users?.records ?? [], }} handlers={{ ...handlers, checkScope, collapseAllSections, expandAllSections, onBasketLinesAdded: this.handleBasketLinesAdded, onAsyncValidate: this.props.checkAsyncValidation, onClose: this.handleClose, }} initialValues={this.state.initialValues} isLoading={this.fetchIsPending()} onSubmit={this.handleSubmit} /> ); } } export default compose( withFileHandlers, withAsyncValidation, stripesConnect )(AgreementEditRoute);
stuhacking/SGEngine-Cpp
src/engine/gl/glslshader.h
/*--- GLSLShader.h - GLSL Shader Header --------------------------*- C++ -*--- * * Stuart's Game Engine * * This file is distributed under the Revised BSD License. See LICENSE.TXT * for details. * * -------------------------------------------------------------------------- * * @brief Defines a GLSL shader type which is part of a GLSLProgram. */ #ifndef __SGE_GLSLSHADER_H #define __SGE_GLSLSHADER_H #include <string> namespace sge { class GLSLShader { public: friend class GLSLProgram; /** * GLSLShader is an individual component of a complete shader. */ GLSLShader (const std::string &pFilename); bool compile (); bool isCompiled () const { return mId > 0; } /** * Clean up assigned IDs. */ void destroy (); private: GLuint mId = 0; /**< GL shader Id. 0 == error/uninitialized. */ GLenum mType; /**< Shader type. */ std::string mFilename; /**< Path to shader source. */ }; } /* namespace sge */ #endif /* __SGE_GLSLSHADER_H */
RINEARN/vnano
src/org/vcssl/nano/spec/EngineInformation.java
/* * Copyright(C) 2017-2021 RINEARN (<NAME>) * This software is released under the MIT License. */ package org.vcssl.nano.spec; import java.util.HashMap; import java.util.Map; import javax.script.ScriptEngine; // Documentation: https://www.vcssl.org/en-us/dev/code/main-jimpl/api/org/vcssl/nano/spec/EngineInformation.html // ドキュメント: https://www.vcssl.org/ja-jp/dev/code/main-jimpl/api/org/vcssl/nano/spec/EngineInformation.html /** * <p> * <span> * <span class="lang-en"> * The class to define basic information (language name, version, and so on) of * this implementation of the script engine of the Vnano * </span> * <span class="lang-ja"> * この Vnano のスクリプトエンジン実装の基本情報(言語名やバージョンなど)が定義されたクラスです * </span> * . * </p> * * <p> * &raquo; <a href="../../../../../src/org/vcssl/nano/spec/EngineInformation.java">Source code</a> * </p> * * <hr> * * <p> * | <a href="../../../../../api/org/vcssl/nano/spec/EngineInformation.html">Public Only</a> * | <a href="../../../../../api-all/org/vcssl/nano/spec/EngineInformation.html">All</a> | * </p> * * @author RINEARN (<NAME>) */ public class EngineInformation { public static final String ENGINE_NAME = "RINEARN Vnano Engine"; public static final String ENGINE_VERSION = "0.9.0"; public static final String[] EXTENTIONS = { "vnano" }; public static final String[] MIME_TYPES = { }; public static final String[] NAMES = { "vnano", "Vnano", "VnanoEngine", "vnanoengine", "Vnano Engine", "vnano engine", "RINEARN Vnano Engine", "rinearn vnano engine", ENGINE_NAME, }; public static final String LANGUAGE_NAME = "Vnano"; public static final String LANGUAGE_VERSION = ENGINE_VERSION; private static final Map<String, Object> KEY_INFORMATION_MAP = new HashMap<String, Object>(); static { KEY_INFORMATION_MAP.put(ScriptEngine.ENGINE, ENGINE_NAME); KEY_INFORMATION_MAP.put(ScriptEngine.ENGINE_VERSION, ENGINE_VERSION); KEY_INFORMATION_MAP.put(ScriptEngine.LANGUAGE, LANGUAGE_NAME); KEY_INFORMATION_MAP.put(ScriptEngine.LANGUAGE_VERSION, LANGUAGE_VERSION); KEY_INFORMATION_MAP.put(ScriptEngine.NAME, NAMES[0]); } public static final Object getValue(String key) { return KEY_INFORMATION_MAP.get(key); } }
idanh/querulous
src/main/scala/com/twitter/querulous/evaluator/QueryEvaluatorProxy.scala
<reponame>idanh/querulous<gh_stars>1-10 package com.twitter.querulous.evaluator import java.sql.ResultSet import java.sql.{SQLException, SQLIntegrityConstraintViolationException} import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException import com.twitter.xrayspecs.{Time, Duration} import com.twitter.xrayspecs.TimeConversions._ abstract class QueryEvaluatorProxy(queryEvaluator: QueryEvaluator) extends QueryEvaluator { def select[A](query: String, params: Any*)(f: ResultSet => A) = { delegate(queryEvaluator.select(query, params: _*)(f)) } def selectOne[A](query: String, params: Any*)(f: ResultSet => A) = { delegate(queryEvaluator.selectOne(query, params: _*)(f)) } def execute(query: String, params: Any*) = { delegate(queryEvaluator.execute(query, params: _*)) } def count(query: String, params: Any*) = { delegate(queryEvaluator.count(query, params: _*)) } def nextId(tableName: String) = { delegate(queryEvaluator.nextId(tableName)) } def insert(query: String, params: Any*) = { delegate(queryEvaluator.insert(query, params: _*)) } def transaction[T](f: Transaction => T) = { delegate(queryEvaluator.transaction(f)) } protected def delegate[A](f: => A) = f }
digipost/signering-api-client-java
src/main/java/no/digipost/signature/client/core/exceptions/SenderNotSpecifiedException.java
package no.digipost.signature.client.core.exceptions; import java.util.function.Supplier; public class SenderNotSpecifiedException extends SignatureException { public static final Supplier<SignatureException> SENDER_NOT_SPECIFIED = SenderNotSpecifiedException::new; private SenderNotSpecifiedException() { super("Sender is not specified. Please call ClientConfiguration#sender to set it globally, " + "or DirectJob.Builder#withSender or PortalJob.Builder#withSender if you need to specify sender " + "on a per job basis (typically when acting as a broker on behalf of multiple senders)."); } }
rmartinc/keycloak
model/jpa/src/main/java/org/keycloak/events/jpa/EventEntity.java
<reponame>rmartinc/keycloak<filename>model/jpa/src/main/java/org/keycloak/events/jpa/EventEntity.java /* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.events.jpa; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ @Entity @Table(name="EVENT_ENTITY") public class EventEntity { @Id @Column(name="ID", length = 36) private String id; @Column(name="EVENT_TIME") private long time; @Column(name="TYPE") private String type; @Column(name="REALM_ID") private String realmId; @Column(name="CLIENT_ID") private String clientId; @Column(name="USER_ID") private String userId; @Column(name="SESSION_ID") private String sessionId; @Column(name="IP_ADDRESS") private String ipAddress; @Column(name="ERROR") private String error; @Column(name="DETAILS_JSON", length = 2550) private String detailsJson; public String getId() { return id; } public void setId(String id) { this.id = id; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getRealmId() { return realmId; } public void setRealmId(String realmId) { this.realmId = realmId; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getDetailsJson() { return detailsJson; } public void setDetailsJson(String detailsJson) { this.detailsJson = detailsJson; } }
mattdricker/lms
tests/unit/lms/db/__init___test.py
<filename>tests/unit/lms/db/__init___test.py import pytest import sqlalchemy as sa from lms.db import BASE from lms.db._bulk_action import BulkAction class Child(BASE): __tablename__ = "child" id = sa.Column(sa.Integer, primary_key=True) class ModelClass(BASE): __tablename__ = "model_class" id = sa.Column(sa.Integer, primary_key=True) column = sa.Column(sa.Integer, sa.ForeignKey("child.id")) relationship = sa.orm.relationship("Child") class TestBase: def test_we_can_get_columns(self): assert sorted(ModelClass.columns()) == [ "column", "id", ] def test_we_can_update_from_dict(self, model): model.update_from_dict( { "id": 4321, "column": "new_value", "relationship": "something", "missing": "Another value", } ) assert model.id == 1234 assert model.column == "new_value" def test_we_can_specify_keys_to_skip(self, model): model.update_from_dict( {"id": 4321, "column": "new_value"}, skip_keys={"column"} ) assert model.id == 4321 assert model.column == "original_value" def test_we_fail_to_update_when_skip_keys_is_not_a_set(self): with pytest.raises(TypeError): ModelClass().update_from_dict({}, skip_keys=["a"]) def test_repr(self): model = ModelClass(id=23, column=46) assert repr(model) == "ModelClass(id=23, column=46)" def test_repr_is_valid_python(self): model = ModelClass(id=23, column=46) deserialized_model = eval(repr(model)) # pylint:disable=eval-used for attr in ( "id", "column", ): assert getattr(deserialized_model, attr) == getattr(model, attr) @pytest.fixture def model(self): return ModelClass(id=1234, column="original_value") class TestCustomSession: def test_it_adds_bulk_object(self, db_session): assert isinstance(db_session.bulk, BulkAction)
CarlosRobertoMedeiros/revision-frontend-javascript
13-RB-ExpressoesRegulares/00-MetaCaracteres.js
/* Os MetaCaracteres Quick Reference [abc] Um simples caracter como a, b ou c [^abc] Qualquer caracter simples exceto a,b ou c [a-z] Qualquer caractere simples entre a-z [a-zA-Z] Qualquer caractere simples entre a-z ou A-Z ^ Inicia uma linha $ Fim da Linha \A Inicia uma String \z Fim de uma String . Qualquer caractere simples \s Qualquer caractere com espaço em branco \S Qualquer caractere diferente de espaço em branco \d Qualquer dígito \D Qualquer não dígito \w Qualquer cractere de palavra(letra, número, sublinhado) \W Qualquer caractere não verbal \b Qualquer limite de palavra (...) Captura tudo fechado (a|b) a ou b a? Zero ou um de um a* Zero ou mais de um a+ Um ou mais de um a{3} Exatamente 3 de a{3,} 3 ou mais de um a{3,6} Entre 3 e 6 de a MetaCaracteres Nome . Ponto(Um caractere qualquer) [] Lista [^] Lista Negada ? Opcional(Zero ou um) * Asterisco(Zero, um ou mais) + Mais(um ou mais) {} Chaves {n,m} Chaves(de n até m) ^ Circunflexo $ Cifrão \b Borda \ Escape | Ou () Grupo \1 Retrovisor [...] Lista de Caracteres Permitidos [^...] Lista de Caracteres Negado ^ Inicio da Linha $ Fim da linha \b Inicio ou fim da palavra Links para Estudar MDN https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Regular_Expressions Links para testar https://rubular.com/ */
ivanDannels/hasor
src/extends-parent/jetty-all/src/main/java/javax/servlet/jsp/tagext/TagData.java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2004 The Apache Software Foundation * * 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 javax.servlet.jsp.tagext; import java.util.Hashtable; /** * The (translation-time only) attribute/value information for a tag instance. * * <p> * TagData is only used as an argument to the isValid, validate, and * getVariableInfo methods of TagExtraInfo, which are invoked at * translation time. */ public class TagData implements Cloneable { /** * Distinguished value for an attribute to indicate its value * is a request-time expression (which is not yet available because * TagData instances are used at translation-time). */ public static final Object REQUEST_TIME_VALUE = new Object(); /** * Constructor for TagData. * * <p> * A typical constructor may be * <pre> * static final Object[][] att = {{"connection", "conn0"}, {"id", "query0"}}; * static final TagData td = new TagData(att); * </pre> * * All values must be Strings except for those holding the * distinguished object REQUEST_TIME_VALUE. * @param atts the static attribute and values. May be null. */ public TagData(Object[] atts[]) { if (atts == null) { attributes = new Hashtable<String, Object>(); } else { attributes = new Hashtable<String, Object>(atts.length); } if (atts != null) { for (int i = 0; i < atts.length; i++) { attributes.put((String)atts[i][0], atts[i][1]); } } } /** * Constructor for a TagData. * * If you already have the attributes in a hashtable, use this * constructor. * * @param attrs A hashtable to get the values from. */ public TagData(Hashtable<String, Object> attrs) { this.attributes = attrs; } /** * The value of the tag's id attribute. * * @return the value of the tag's id attribute, or null if no such * attribute was specified. */ public String getId() { return getAttributeString(TagAttributeInfo.ID); } /** * The value of the attribute. * If a static value is specified for an attribute that accepts a * request-time attribute expression then that static value is returned, * even if the value is provided in the body of a &lt;jsp:attribute&gt; action. * The distinguished object REQUEST_TIME_VALUE is only returned if * the value is specified as a request-time attribute expression * or via the &lt;jsp:attribute&gt; action with a body that contains * dynamic content (scriptlets, scripting expressions, EL expressions, * standard actions, or custom actions). Returns null if the attribute * is not set. * * @param attName the name of the attribute * @return the attribute's value */ public Object getAttribute(String attName) { return attributes.get(attName); } /** * Set the value of an attribute. * * @param attName the name of the attribute * @param value the value. */ public void setAttribute(String attName, Object value) { attributes.put(attName, value); } /** * Get the value for a given attribute. * * @param attName the name of the attribute * @return the attribute value string * @throws ClassCastException if attribute value is not a String */ public String getAttributeString(String attName) { Object o = attributes.get(attName); if (o == null) { return null; } else { return (String) o; } } /** * Enumerates the attributes. * *@return An enumeration of the attributes in a TagData */ public java.util.Enumeration<String> getAttributes() { return attributes.keys(); }; // private data private Hashtable<String, Object> attributes; // the tagname/value map }
A-Platform/apc-mall
mall-common/common-spring-boot-starter/src/main/java/com/a/platform/common/util/FileUtil.java
package com.a.platform.common.util; import org.apache.commons.io.FileUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Delete; import org.apache.tools.ant.taskdefs.Expand; import org.springframework.web.multipart.MultipartFile; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; /** * 文件工具类 * * @author weixing.yang * @version 1.0 * @date 2019/10/19 17:16 */ public class FileUtil { protected final static Log logger = LogFactory.getLog(FileUtil.class); private FileUtil() { } public static BufferedImage toBufferedImage(Image image) { if (image instanceof BufferedImage) { return (BufferedImage) image; } // This code ensures that all the pixels in the image are loaded image = new ImageIcon(image).getImage(); // Determine if the image has transparent pixels; for this method's // implementation, see e661 Determining If an Image Has Transparent // Pixels // boolean hasAlpha = hasAlpha(image); // Create a buffered image with a format that's compatible with the // screen BufferedImage bimage = null; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); try { // Determine the type of transparency of the new buffered image int transparency = Transparency.TRANSLUCENT; /* * if (hasAlpha) { transparency = Transparency.BITMASK; } */ // Create the buffered image GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency); } catch (HeadlessException e) { // The system does not have a screen } catch (Exception e) { e.printStackTrace(); } if (bimage == null) { // Create a buffered image using the default color model int type = BufferedImage.TYPE_INT_RGB; // int type = BufferedImage.TYPE_3BYTE_BGR;//by wang /* * if (hasAlpha) { type = BufferedImage.TYPE_INT_ARGB; } */ bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type); } // Copy image to buffered image Graphics g = bimage.createGraphics(); // Paint the image onto the buffered image g.drawImage(image, 0, 0, null); g.dispose(); return bimage; } public static void createFile(InputStream in, String filePath) { if (in == null) { throw new RuntimeException("create file error: inputstream is null"); } int potPos = filePath.lastIndexOf('/') + 1; String folderPath = filePath.substring(0, potPos); createFolder(folderPath); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(filePath); byte[] by = new byte[1024]; int c; while ((c = in.read(by)) != -1) { outputStream.write(by, 0, c); } } catch (IOException e) { e.getStackTrace(); } try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { in.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 是否是允许上传文件 * * @param logoFileName 文件名称 * @return */ public static boolean isAllowUp(String logoFileName) { logoFileName = logoFileName.toLowerCase(); String allowTYpe = "gif,jpg,jpeg,bmp,swf,png,rar,doc,docx,xls,xlsx,pdf,zip,ico,txt,mp4"; if (!"".equals(logoFileName.trim()) && logoFileName.length() > 0) { String ex = logoFileName.substring(logoFileName.lastIndexOf(".") + 1, logoFileName.length()); // return allowTYpe.toString().indexOf(ex) >= 0; //lzf edit 20110717 //解决只认小写问题 //同时加入jpeg扩展名/png扩展名 return allowTYpe.toUpperCase().indexOf(ex.toUpperCase()) >= 0; } else { return false; } } /** * 是否是允许上传的图片 * * @param ex 文件后缀 * @return */ public static boolean isAllowUpImg(String ex) { String allowTYpe = "gif,jpg,png,jpeg"; if (!"".equals(ex.trim()) && ex.length() > 0) { return allowTYpe.toUpperCase().indexOf(ex.toUpperCase()) >= 0; } else { return false; } } /** * 把内容写入文件 * * @param filePath * @param fileContent */ public static void write(String filePath, String fileContent) { try { FileOutputStream fo = new FileOutputStream(filePath); OutputStreamWriter out = new OutputStreamWriter(fo, "UTF-8"); out.write(fileContent); out.close(); } catch (IOException ex) { System.err.println("Create File Error!"); ex.printStackTrace(); } } /** * 将inputStream写入文件 * * @param file * @param path */ public static void write(MultipartFile file, String path) { try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path)); } catch (IOException e) { e.printStackTrace(); } } /** * 将inputstream写入文件 * * @param stream 文件流 * @param path 要写入的文件路径 */ public static void write(InputStream stream, String path) { try { FileUtils.copyInputStreamToFile(stream, new File(path)); } catch (IOException e) { logger.error("文件写入异常:", e); } } /** * 读取文件内容 默认是UTF-8编码 * * @param filePath * @return */ public static String read(String filePath, String code) { if (code == null || "".equals(code)) { code = "UTF-8"; } StringBuffer stringBuffer = new StringBuffer(""); File file = new File(filePath); try { InputStreamReader read = new InputStreamReader(new FileInputStream( file), code); BufferedReader reader = new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line + "\n"); } read.close(); read = null; reader.close(); read = null; } catch (Exception ex) { ex.printStackTrace(); stringBuffer = new StringBuffer(""); } return stringBuffer.toString(); } /** * 删除文件或文件夹 * * @param filePath */ public static void delete(String filePath) { try { File file = new File(filePath); if (file.exists()) { if (file.isDirectory()) { FileUtils.deleteDirectory(file); } else { file.delete(); } } } catch (Exception ex) { logger.error("删除文件异常:", ex); } } public static boolean exist(String filepath) { File file = new File(filepath); return file.exists(); } /** * 创建文件夹 * * @param filePath */ public static void createFolder(String filePath) { try { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } } catch (Exception ex) { logger.error("创建文件目录异常:", ex); } } /** * 重命名文件、文件夹 * * @param from * @param to */ public static void renameFile(String from, String to) { try { File file = new File(from); if (file.exists()) { file.renameTo(new File(to)); } } catch (Exception ex) { logger.error("Rename File/Folder Error:", ex); } } /** * 得到文件的扩展名 * * @param fileName * @return */ public static String getFileExt(String fileName) { int potPos = fileName.lastIndexOf('.') + 1; String type = fileName.substring(potPos, fileName.length()); return type; } /** * 通过File对象创建文件 * * @param file * @param filePath */ public static void createFile(File file, String filePath) { int potPos = filePath.lastIndexOf('/') + 1; String folderPath = filePath.substring(0, potPos); createFolder(folderPath); FileOutputStream outputStream = null; FileInputStream fileInputStream = null; try { outputStream = new FileOutputStream(filePath); fileInputStream = new FileInputStream(file); byte[] by = new byte[1024]; int c; while ((c = fileInputStream.read(by)) != -1) { outputStream.write(by, 0, c); } outputStream.close(); fileInputStream.close(); } catch (IOException e) { logger.error("创建件文件异常", e); } } public static String readFile(String resource) { InputStream stream = getResourceAsStream(resource); String content = readStreamToString(stream); return content; } public static InputStream getResourceAsStream(String resource) { String stripped = resource.startsWith("/") ? resource.substring(1) : resource; InputStream stream = null; ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); if (classLoader != null) { stream = classLoader.getResourceAsStream(stripped); } return stream; } public static String readStreamToString(InputStream stream) { StringBuffer fileContentsb = new StringBuffer(); String fileContent = ""; try { InputStreamReader read = new InputStreamReader(stream, "utf-8"); BufferedReader reader = new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { fileContentsb.append(line + "\n"); } read.close(); read = null; reader.close(); read = null; fileContent = fileContentsb.toString(); } catch (Exception ex) { fileContent = ""; } return fileContent; } /** * delete file folder * * @param path */ public static void removeFile(File path) { if (path.isDirectory()) { try { FileUtils.deleteDirectory(path); } catch (IOException e) { e.printStackTrace(); } } } public static void copyFile(String srcFile, String destFile) { try { if (FileUtil.exist(srcFile)) { FileUtils.copyFile(new File(srcFile), new File(destFile)); } } catch (IOException e) { logger.error("复制文件异常", e); } } public static void copyFolder(String sourceFolder, String destinationFolder) { ////System.out.println("copy " + sourceFolder + " to " + destinationFolder); try { File sourceF = new File(sourceFolder); if (sourceF.exists()) { FileUtils.copyDirectory(new File(sourceFolder), new File( destinationFolder)); } } catch (Exception e) { throw new RuntimeException("copy file error"); } } /** * 拷贝源文件夹至目标文件夹 * 只拷贝新文件 * * @param sourceFolder * @param targetFolder */ public static void copyNewFile(String sourceFolder, String targetFolder) { try { File sourceF = new File(sourceFolder); if (!targetFolder.endsWith("/")) { targetFolder = targetFolder + "/"; } if (sourceF.exists()) { File[] filelist = sourceF.listFiles(); for (File f : filelist) { File targetFile = new File(targetFolder + f.getName()); if (f.isFile()) { //如果目标文件比较新,或源文件比较新,则拷贝,否则跳过 if (!targetFile.exists() || FileUtils.isFileNewer(f, targetFile)) { FileUtils.copyFileToDirectory(f, new File(targetFolder)); ////System.out.println("copy "+ f.getName()); } else { // //System.out.println("skip "+ f.getName()); } } } } } catch (Exception e) { throw new RuntimeException("copy file error"); } } public static void unZip(String zipPath, String targetFolder, boolean cleanZip) { File folderFile = new File(targetFolder); File zipFile = new File(zipPath); Project prj = new Project(); Expand expand = new Expand(); expand.setEncoding("UTF-8"); expand.setProject(prj); expand.setSrc(zipFile); expand.setOverwrite(true); expand.setDest(folderFile); expand.execute(); if (cleanZip) { //清除zip包 Delete delete = new Delete(); delete.setProject(prj); delete.setDir(zipFile); delete.execute(); } } /** * 获取文件类型 * * @param fileType 文件后缀 * @return */ public static String contentType(String fileType) { fileType = fileType.toLowerCase(); String contentType = ""; if ("bmp".equals(fileType)) { contentType = "image/bmp"; } else if ("gif".equals(fileType)) { contentType = "image/gif"; } else if ("png".equals(fileType) || "jpeg".equals(fileType) || "jpg".equals(fileType)) { contentType = "image/jpeg"; } else if ("html".equals(fileType)) { contentType = "text/html"; } else if ("txt".equals(fileType)) { contentType = "text/plain"; } else if ("vsd".equals(fileType)) { contentType = "application/vnd.visio"; } else if ("ppt".equals(fileType) || "pptx".equals(fileType)) { contentType = "application/vnd.ms-powerpoint"; } else if ("doc".equals(fileType) || "docx".equals(fileType)) { contentType = "application/msword"; } else if ("xml".equals(fileType)) { contentType = "text/xml"; } else if ("mp4".equals(fileType)) { contentType = "video/mp4"; } else { contentType = "application/octet-stream"; } return contentType; } }
Flexberry/ember-flexberry-designer
addon/controllers/fd-generation.js
/** @module ember-flexberry-designer */ import Controller from '@ember/controller'; import FdReadonlyProjectMixin from '../mixins/fd-readonly-project'; import FdGroupDropdown from '../mixins/fd-group-dropdown'; import { inject as service } from '@ember/service'; import { A } from '@ember/array'; import { isNone, isBlank } from '@ember/utils'; import { computed } from '@ember/object'; import moment from 'moment'; /** The controller for the form with a log of generation. @class FdGenerationListLogController @extends Ember.Controller */ export default Controller.extend(FdReadonlyProjectMixin, FdGroupDropdown, { /** Service for managing the state of the sheet component. @property fdSheetService @type FdSheetService */ fdSheetService: service(), /** Value search input. @property searchValue @type String @default '' */ searchValue: '', /** Sheet component name. @property sheetComponentName @type String @default '' */ sheetComponentName: '', /** Array groups. @property groupArray @type Array */ groupArray: computed('i18n.locale', function() { return A([ 'forms.fd-generation.all-states', 'forms.fd-generation.run-caption', 'forms.fd-generation.success-caption', 'forms.fd-generation.error-caption', 'forms.fd-generation.other-caption' ]); }), /** Update model for search @method filteredModel */ filteredModel: computed('model', 'searchValue', function() { let searchStr = this.get('searchValue'); let model = this.get('model'); if (isBlank(searchStr)) { return model; } searchStr = searchStr.trim().toLocaleLowerCase(); let filterFunction = function(item) { let data = moment(item.data.get('startTime')).format('DD.MM.YYYY HH:mm:ss'); if (!isNone(data) && data.toLocaleLowerCase().indexOf(searchStr) !== -1) { return item; } }; let newModel = {}; for (let prop in model) { let newdata = model[prop].filter(filterFunction); newModel[prop] = A(newdata); } return newModel; }), init() { this._super(...arguments); this.set('groupValueLocale', 'forms.fd-generation.all-states'); }, actions: { /** This method will notify all observers that the model changed value. @method actions.updateModel */ updateModel() { this.notifyPropertyChange('model'); } } });
hicala/jaeger-analytics-java
tracedsl/src/main/java/io/jaegertracing/analytics/tracequality/MinimumClientVersion.java
package io.jaegertracing.analytics.tracequality; import io.jaegertracing.analytics.ModelRunner; import io.jaegertracing.analytics.gremlin.GraphCreator; import io.jaegertracing.analytics.model.Span; import io.prometheus.client.Counter; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; /** * Emits a passing score if the version number of a client is higher than the ones specified and a failing score * otherwise. */ public class MinimumClientVersion implements ModelRunner { static final String VERSION_TAG = "jaeger.version"; static final String MISSING_VERSION = "none"; public static class Builder implements Serializable { private String javaVersion = "1.0.0"; private String nodeVersion = "3.17.1"; private String goVersion = "2.22.0"; private String pythonVersion = "4.0.0"; private Builder() {} public MinimumClientVersion build() { return new MinimumClientVersion(this); } public Builder withJavaVersion(String javaVersion) { this.javaVersion = javaVersion; return this; } public Builder withNodeVersion(String nodeVersion) { this.nodeVersion = nodeVersion; return this; } public Builder withGoVersion(String goVersion) { this.goVersion = goVersion; return this; } public Builder withPythonVersion(String pythonVersion) { this.pythonVersion = pythonVersion; return this; } } public static Builder builder() { return new Builder(); } private MinimumClientVersion(Builder builder) { languageToMinVersion = Collections.unmodifiableMap(new HashMap<String, String>() {{ put("go", builder.goVersion); put("python", builder.pythonVersion); put("node", builder.nodeVersion); put("java", builder.javaVersion); }}); } private final Map<String, String> languageToMinVersion; private static final Counter counter = Counter.build() .name("trace_quality_minimum_client_version_total") .help("The service emitted spans with Jaeger client version") .labelNames("pass", "service", "version") .create() .register(); @Override public void runWithMetrics(Graph graph) { Iterator<Vertex> vertices = graph.vertices(); while (vertices.hasNext()) { Vertex vertex = vertices.next(); Span span = GraphCreator.toSpan(vertex); String jaegerVersion = span.tags.get(VERSION_TAG); if (jaegerVersion == null || jaegerVersion.isEmpty()) { jaegerVersion = MISSING_VERSION; } boolean result = computeScore(span); counter.labels(Boolean.toString(result), span.serviceName, jaegerVersion) .inc(); } } public boolean computeScore(Span span) { String version = span.tags.get(VERSION_TAG); if (version == null || version.isEmpty()) { return false; } String[] languageVersion = version.toLowerCase().split("-"); if (languageVersion.length != 2 || languageToMinVersion.get(languageVersion[0]) == null || !languageVersion[1].matches("[0-9]+(\\.[0-9]+)*")) { return false; } if (isGreaterThanOrEqualTo(languageToMinVersion.get(languageVersion[0]), languageVersion[1])) { return true; } else { return false; } } /** * Compares two semantic version strings * * @param left semantic version string * @param right semantic version string * @return true if right is greater than or equal to left * false for all other cases */ boolean isGreaterThanOrEqualTo(String left, String right) { String[] leftParts = left.split("\\."); String[] rightParts = right.split("\\."); int length = Math.min(leftParts.length, rightParts.length); try { for (int i = 0; i < length; i++) { int leftPart = Integer.parseInt(leftParts[i]); int rightPart = Integer.parseInt(rightParts[i]); if (leftPart < rightPart) { return true; } if (leftPart > rightPart) { return false; } } } catch (NumberFormatException e) { return false; } return true; } }
venusdrogon/feilong
feilong-lib/feilong-lib-commons-digester3/src/main/java/com/feilong/lib/digester3/binder/DigesterLoader.java
package com.feilong.lib.digester3.binder; import static com.feilong.lib.digester3.binder.BinderClassLoader.createBinderClassLoader; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Formatter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import com.feilong.lib.digester3.Digester; import com.feilong.lib.digester3.RuleSet; import com.feilong.lib.digester3.Rules; import com.feilong.lib.digester3.RulesBase; import com.feilong.lib.digester3.Substitutor; /** * This class manages the creation of Digester instances from digester rules modules. */ public final class DigesterLoader{ /** * The default head when reporting an errors list. */ private static final String HEADING = "Digester creation errors:%n%n"; /** * Creates a new {@link DigesterLoader} instance given one or more {@link RulesModule} instance. * * @param rulesModules * The modules containing the {@code Rule} binding * @return A new {@link DigesterLoader} instance */ public static DigesterLoader newLoader(RulesModule...rulesModules){ if (rulesModules == null || rulesModules.length == 0){ throw new DigesterLoadingException("At least one RulesModule has to be specified"); } List<RulesModule> asList = Arrays.asList(rulesModules); return new DigesterLoader(asList); } /** * The concrete {@link RulesBinder} implementation. */ private final DefaultRulesBinder rulesBinder = new DefaultRulesBinder(); /** * The URLs of entityValidator that have been registered, keyed by the public * identifier that corresponds. */ private final Map<String, URL> entityValidator = new HashMap<>(); /** * The SAXParserFactory to create new default {@link Digester} instances. */ private final SAXParserFactory factory = SAXParserFactory.newInstance(); private final Iterable<RulesModule> rulesModules; /** * The class loader to use for instantiating application objects. * If not specified, the context class loader, or the class loader * used to load Digester itself, is used, based on the value of the * <code>useContextClassLoader</code> variable. */ private final BinderClassLoader classLoader; /** * An optional class that substitutes values in attributes and body text. This may be null and so a null check is * always required before use. */ private Substitutor substitutor; /** * Creates a new {@link DigesterLoader} instance given a collection of {@link RulesModule} instance. * * @param rulesModules * The modules containing the {@code Rule} binding */ private DigesterLoader(Iterable<RulesModule> rulesModules){ this.rulesModules = rulesModules; this.classLoader = createBinderClassLoader(Thread.currentThread().getContextClassLoader()); } /** * Set the "namespace aware" flag for parsers we create. * * @param namespaceAware * The new "namespace aware" flag * @return This loader instance, useful to chain methods. */ public DigesterLoader setNamespaceAware(boolean namespaceAware){ factory.setNamespaceAware(namespaceAware); return this; } /** * Return the "namespace aware" flag for parsers we create. * * @return true, if the "namespace aware" flag for parsers we create, false otherwise. */ private boolean isNamespaceAware(){ return factory.isNamespaceAware(); } /** * Set the XInclude-aware flag for parsers we create. This additionally * requires namespace-awareness. * * @param xIncludeAware * The new XInclude-aware flag * @return This loader instance, useful to chain methods. * @see #setNamespaceAware(boolean) */ public DigesterLoader setXIncludeAware(boolean xIncludeAware){ factory.setXIncludeAware(xIncludeAware); return this; } /** * Set the validating parser flag. * * @param validating * The new validating parser flag. * @return This loader instance, useful to chain methods. */ public DigesterLoader setValidating(boolean validating){ factory.setValidating(validating); return this; } /** * Return the validating parser flag. * * @return true, if the validating parser flag is set, false otherwise */ public boolean isValidating(){ return this.factory.isValidating(); } private DigesterLoader register(String publicId,URL entityURL){ entityValidator.put(publicId, entityURL); return this; } /** * <p> * Convenience method that registers the string version of an entity URL * instead of a URL version. * </p> * * @param publicId * Public identifier of the entity to be resolved * @param entityURL * The URL to use for reading this entity * @return This loader instance, useful to chain methods. */ public DigesterLoader register(String publicId,String entityURL){ try{ return register(publicId, new URL(entityURL)); }catch (MalformedURLException e){ throw new IllegalArgumentException("Malformed URL '" + entityURL + "' : " + e.getMessage()); } } /** * Creates a new {@link Digester} instance that relies on the default {@link Rules} implementation. * * @return a new {@link Digester} instance */ public Digester newDigester(){ try{ SAXParser parser = this.factory.newSAXParser(); RulesBase rules = new RulesBase(); if (parser == null){ throw new DigesterLoadingException("SAXParser must be not null"); } try{ XMLReader reader = parser.getXMLReader(); if (reader == null){ throw new DigesterLoadingException("XMLReader must be not null"); } Digester digester = new Digester(reader); // the ClassLoader adapter is no needed anymore digester.setClassLoader(classLoader.getAdaptedClassLoader()); digester.setRules(rules); digester.setSubstitutor(substitutor); digester.registerAll(entityValidator); digester.setNamespaceAware(isNamespaceAware()); addRules(digester); return digester; }catch (SAXException e){ throw new DigesterLoadingException("An error occurred while creating the XML Reader", e); } }catch (ParserConfigurationException e){ throw new DigesterLoadingException("SAX Parser misconfigured", e); }catch (SAXException e){ throw new DigesterLoadingException("An error occurred while initializing the SAX Parser", e); } } /** * Add rules to an already created Digester instance, analyzing the digester annotations in the target class. * * @param digester * the Digester instance reference. */ public void addRules(final Digester digester){ RuleSet ruleSet = createRuleSet(); ruleSet.addRuleInstances(digester); } /** * Creates a new {@link RuleSet} instance based on the current configuration. * * @return A new {@link RuleSet} instance based on the current configuration. */ public RuleSet createRuleSet(){ if (classLoader != rulesBinder.getContextClassLoader()){ rulesBinder.initialize(classLoader); for (RulesModule rulesModule : rulesModules){ rulesModule.configure(rulesBinder); } } if (rulesBinder.hasError()){ Formatter fmt = new Formatter().format(HEADING); int index = 1; for (ErrorMessage errorMessage : rulesBinder.getErrors()){ fmt.format("%s) %s%n", index++, errorMessage.getMessage()); Throwable cause = errorMessage.getCause(); if (cause != null){ StringWriter writer = new StringWriter(); cause.printStackTrace(new PrintWriter(writer)); fmt.format("Caused by: %s", writer.getBuffer()); } fmt.format("%n"); } if (rulesBinder.errorsSize() == 1){ fmt.format("1 error"); }else{ fmt.format("%s errors", rulesBinder.errorsSize()); } throw new DigesterLoadingException(fmt.toString()); } return rulesBinder.getFromBinderRuleSet(); } }
YungTsun/alameda
datahub/pkg/dao/entities/prometheus/metrics/namespace.go
package metrics import ( DaoMetricTypes "github.com/containers-ai/alameda/datahub/pkg/dao/interfaces/metrics/types" FormatEnum "github.com/containers-ai/alameda/datahub/pkg/formatconversion/enumconv" FormatTypes "github.com/containers-ai/alameda/datahub/pkg/formatconversion/types" "github.com/containers-ai/alameda/datahub/pkg/kubernetes/metadata" InternalPromth "github.com/containers-ai/alameda/internal/pkg/database/prometheus" ) type NamespaceCPUUsageMillicoresEntity struct { PrometheusEntity InternalPromth.Entity NamespaceName string Samples []FormatTypes.Sample } // NamespaceMetric Build NamespaceMetric base on entity properties func (e *NamespaceCPUUsageMillicoresEntity) NamespaceMetric() DaoMetricTypes.NamespaceMetric { m := DaoMetricTypes.NamespaceMetric{ ObjectMeta: metadata.ObjectMeta{ Name: e.NamespaceName, }, Metrics: map[FormatEnum.MetricType][]FormatTypes.Sample{ FormatEnum.MetricTypeCPUUsageSecondsPercentage: e.Samples, }, } return m } type NamespaceMemoryUsageBytesEntity struct { PrometheusEntity InternalPromth.Entity NamespaceName string Samples []FormatTypes.Sample } // NamespaceMetric Build NamespaceMetric base on entity properties func (e *NamespaceMemoryUsageBytesEntity) NamespaceMetric() DaoMetricTypes.NamespaceMetric { m := DaoMetricTypes.NamespaceMetric{ ObjectMeta: metadata.ObjectMeta{ Name: e.NamespaceName, }, Metrics: map[FormatEnum.MetricType][]FormatTypes.Sample{ FormatEnum.MetricTypeMemoryUsageBytes: e.Samples, }, } return m }
ceekay1991/CallTraceForWeChat
CallTraceForWeChat/CallTraceForWeChat/WeChat_Headers/DetailSubIcon.h
<gh_stars>10-100 // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import <objc/NSObject.h> @class NSString, UIImage; @interface DetailSubIcon : NSObject { NSString *_subIconUrl; UIImage *_subIconDefault; } @property(retain) UIImage *subIconDefault; // @synthesize subIconDefault=_subIconDefault; @property(retain) NSString *subIconUrl; // @synthesize subIconUrl=_subIconUrl; - (void).cxx_destruct; @end
yipeiw/pserver
src/system/message.h
#pragma once #include "util/common.h" #include "util/threadpool.h" #include "util/shared_array.h" #include "system/proto/task.pb.h" #include "filter/proto/filter.pb.h" namespace PS { typedef std::string NodeID; struct Message; typedef std::shared_ptr<Message> MessagePtr; typedef std::shared_ptr<const Message> MessageCPtr; typedef std::vector<MessagePtr> MessagePtrList; typedef std::vector<Range<Key>> KeyRangeList; struct Message { public: const static int kInvalidTime = -1; Message() { } Message(const NodeID& dest, int time = kInvalidTime, int wait_time = kInvalidTime); explicit Message(const Task& tk) : task(tk) { } void miniCopyFrom(const Message& msg); // the header of the message, containing all metadata Task task; // key and value arrays. You'd better use setKey() and addValue() when add // key/value arrays SArray<char> key; std::vector<SArray<char> > value; // functions manipulate task, key and values. FilterConfig* addFilter(FilterConfig::Type type); // return task.has_key(); bool hasKey() const { return !key.empty(); } template <typename T> void setKey(const SArray<T>& key); void clearKey() { task.clear_has_key(); key.clear(); } template <typename T> void addValue(const SArray<T>& value); template <typename T> void addValue(const SArrayList<T>& value) { for (const auto& v : value) addValue(v); } template <typename T> void addValue(const std::initializer_list<SArray<T>>& value) { for (const auto& v : value) addValue(v); } void clearValue() { task.clear_value_type(); value.clear(); } void clearData() { clearKey(); clearValue(); } // more control signals, which are only used by local process // sender node id NodeID sender; // receiver node id NodeID recver; // the original receiver node id. for example, when a worker send a message to // the server group (kServerGroup), then the message going to a particular // server will have kServerGroup as its *original_recver* NodeID original_recver; // true if this message has been replied, to avoid double reply bool replied = false; // true if the task asscociated with this message has been finished. bool finished = true; // an inivalid message will not be sent, instead, the postoffice will fake a // reply message. see Postoffice::queue() bool valid = true; // set it to be true to stop the sending thread of Postoffice. bool terminate = false; // wait or not when submit this message bool wait = false; typedef std::function<void()> Callback; // *recv_handle* will be called if anythings goes back from the destination // node. When called, this task has not been marked as finished. If could be // called multiple time when the destination node is a node group. Callback recv_handle; // *fin_handle* will be called when this task has been finished. If the dest // node is a node group, then it means replies from all nodes in this group // have been received. Callback fin_handle; // debug std::string shortDebugString() const; std::string debugString() const; // helper template <typename V> static DataType encodeType() { if (std::is_same<V, uint32>::value) return DataType::UINT32; if (std::is_same<V, uint64>::value) return DataType::UINT64; if (std::is_same<V, int32>::value) return DataType::INT32; if (std::is_same<V, int64>::value) return DataType::INT64; if (std::is_same<typename std::remove_cv<V>::type, float>::value) return DataType::FLOAT; if (std::is_same<V, double>::value) return DataType::DOUBLE; if (std::is_same<V, uint8>::value) return DataType::UINT8; if (std::is_same<V, int8>::value) return DataType::INT8; if (std::is_same<V, char>::value) return DataType::CHAR; return DataType::OTHER; } }; template <typename T> void Message::setKey(const SArray<T>& key) { task.set_key_type(encodeType<T>()); if (hasKey()) clearKey(); task.set_has_key(true); this->key = SArray<char>(key); if (!task.has_key_range()) Range<Key>::all().to(task.mutable_key_range()); } template <typename T> void Message::addValue(const SArray<T>& value) { task.add_value_type(encodeType<T>()); this->value.push_back(SArray<char>(value)); } template <typename K> MessagePtrList sliceKeyOrderedMsg(const MessagePtr& msg, const KeyRangeList& krs) { // find the positions in msg.key size_t n = krs.size(); std::vector<size_t> pos(n+1); SArray<K> key(msg->key); Range<Key> msg_key_range(msg->task.key_range()); for (int i = 0; i < n; ++i) { if (i == 0) { K k = (K)msg_key_range.project(krs[0].begin()); pos[0] = std::lower_bound(key.begin(), key.end(), k) - key.begin(); } else { CHECK_EQ(krs[i-1].end(), krs[i].begin()); } K k = (K)msg_key_range.project(krs[i].end()); pos[i+1] = std::lower_bound(key.begin(), key.end(), k) - key.begin(); } // split the message according to *pos* MessagePtrList ret(n); for (int i = 0; i < n; ++i) { ret[i] = MessagePtr(new Message()); ret[i]->miniCopyFrom(*msg); if (krs[i].setIntersection(msg_key_range).empty()) { // the remote node does not maintain this key range. mark this message as // valid, which will not be sent ret[i]->valid = false; } else { ret[i]->valid = true; // must set true, otherwise this piece might not be sent if (key.empty()) continue; // to void be divided by 0 SizeR lr(pos[i], pos[i+1]); ret[i]->setKey(key.segment(lr)); for (auto& v : msg->value) { // ret[i]->addValue(v.segment(lr * (v.size() / key.size()))); ret[i]->value.push_back(v.segment(lr * (v.size() / key.size()))); } } } return ret; } inline std::ostream& operator<<(std::ostream& os, const Message& msg) { return (os << msg.shortDebugString()); } } // namespace PS