text
stringlengths
1
1.05M
export declare const RESET: unique symbol;
function findLongestStringLength(arr) { let longestLength = 0; for (const str of arr) { const length = str.length; if (length > longestLength) { longestLength = length; } } return longestLength; } const length = findLongestStringLength(["Hello", "World", "This", "is", "a", "test"]); console.log(length);
#!/bin/bash set -e DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" cd ${DIR}/../mc-build/ rm -rf robot-software mkdir robot-software mkdir robot-software/build #cp common/test-common robot-software/build cp $1 robot-software/build find . -name \*.so* -exec cp {} ./robot-software/build \; cp ../scripts/run_mc* ./robot-software/build cp ../scripts/setup_network_mc.py ./robot-software/build cp ../scripts/run_mc_debug.sh ./robot-software/build cp ../scripts/config_network_lcm.sh ./robot-software cp -r ../robot robot-software cp -r ../config robot-software DATE=$(date +"%Y%m%d%H%M") #scp -r robot-software user@10.0.0.34:~/robot-software-$DATE/ if [ -z "$2" ] then echo "No mini-cheetah number specified, using old mini-cheetah address" scp -r robot-software user@10.0.0.34:~/ else scp -r robot-software user@10.0.0.4$2:~/ fi
#!/usr/bin/env bash readonly EXTRA_PACKAGES="${EXTRA_PACKAGES:-}" readonly DOCKER_ENABLED="${DOCKER_ENABLED:-}" readonly CONSUL_CONFIG_DIR="${CONSUL_CONFIG_DIR:-/etc/consul.d}" readonly CONSUL_ENABLED="${CONSUL_ENABLED:-}" readonly CONSUL_EXTRA_ARGS="${CONSUL_EXTRA_ARGS:-}" readonly VAULT_CONFIG_DIR="${VAULT_CONFIG_DIR:-/etc/vault.d}" readonly VAULT_ENABLED="${VAULT_ENABLED:-}" readonly VAULT_EXTRA_ARGS="${VAULT_EXTRA_ARGS:-}" readonly NOMAD_CONFIG_DIR="${NOMAD_CONFIG_DIR:-/etc/nomad.d}" readonly NOMAD_ENABLED="${NOMAD_ENABLED:-}" readonly NOMAD_EXTRA_ARGS="${NOMAD_EXTRA_ARGS:-}" if [[ -n "${EXTRA_PACKAGES}" ]]; then # shellcheck disable=SC2086 apk add ${EXTRA_PACKAGES} fi docker_pid="" mkdir -p "${CONSUL_CONFIG_DIR}" mkdir -p /data/consul consul_pid="" mkdir -p "${VAULT_CONFIG_DIR}" mkdir -p /data/vault vault_pid="" mkdir -p "${NOMAD_CONFIG_DIR}" mkdir -p /data/nomad nomad_pid="" function cleanup() { if [[ -n "$nomad_pid" ]]; then pkill $nomad_pid fi if [[ -n "$vault_pid" ]]; then pkill $vault_pid fi if [[ -n "$consul_pid" ]]; then pkill $consul_pid fi if [[ -n "$docker_pid" ]]; then pkill $docker_pid fi } trap cleanup EXIT if [[ -e /usr/local/bin/dockerd-entrypoint.sh ]] && [[ -n "${DOCKER_ENABLED}" ]]; then /usr/local/bin/dockerd-entrypoint.sh & docker_pid="$!" fi if [[ -n "${CONSUL_ENABLED}" ]]; then /consul/bin/consul agent ${CONSUL_EXTRA_ARGS} -config-dir "${CONSUL_CONFIG_DIR}" & consul_pid="$!" fi if [[ -n "${VAULT_ENABLED}" ]]; then /vault/bin/vault server ${VAULT_EXTRA_ARGS} -config "${VAULT_CONFIG_DIR}" & vault_pid="$!" fi if [[ -n "${NOMAD_ENABLED}" ]]; then /nomad/bin/nomad agent ${NOMAD_EXTRA_ARGS} -config "${NOMAD_CONFIG_DIR}" & nomad_pid="$!" fi wait -n $nomad_pid $vault_pid $consul_pid $docker_pid exit $?
public class PrimeFactors { public static void main(String[] args) { int n = 18; System.out.print("Prime factors of "+ n + " are: "); while(n % 2 == 0) { System.out.print(2 + " "); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while(n % i == 0) { System.out.print(i + " "); n /= i; } } if (n > 2) System.out.print(n); } }
#!/bin/bash K8S_NAMESPACE="${K8S_NAMESPACE:-istio-system}" CERT_MANAGER_VERSION="${CERT_MANAGER_VERSION:-1.4.0}" ISTIO_AGENT_IMAGE="${CERT_MANAGER_ISTIO_AGENT_IMAGE:-localhost:5000/cert-manager-istio-csr:v0.1.3}" KUBECTL_BIN="${KUBECTL_BIN:-./bin/kubectl}" HELM_BIN="${HELM_BIN:-./bin/helm}" KIND_BIN="${KIND_BIN:-./bin/kind}" ./hack/demo/kind-with-registry.sh $1 echo ">> docker build -t ${ISTIO_AGENT_IMAGE} ." docker build -t ${ISTIO_AGENT_IMAGE} . echo ">> docker push ${ISTIO_AGENT_IMAGE}" docker push $ISTIO_AGENT_IMAGE apply_cert-manager_bootstrap_manifests() { $KUBECTL_BIN apply -n $K8S_NAMESPACE -f ./hack/demo/cert-manager-bootstrap-resources.yaml return $? } echo ">> loading demo container images into kind" IMAGES=("quay.io/joshvanl_jetstack/httpbin:latest" "quay.io/joshvanl_jetstack/curl") IMAGES+=("gcr.io/istio-release/pilot:$2" "gcr.io/istio-release/proxyv2:$2") for image in ${IMAGES[@]}; do docker pull $image $KIND_BIN load docker-image $image --name istio-demo done echo ">> installing cert-manager" $KUBECTL_BIN apply -f https://github.com/jetstack/cert-manager/releases/download/v$CERT_MANAGER_VERSION/cert-manager.yaml $KUBECTL_BIN rollout status deploy -n cert-manager cert-manager $KUBECTL_BIN rollout status deploy -n cert-manager cert-manager-cainjector $KUBECTL_BIN rollout status deploy -n cert-manager cert-manager-webhook echo ">> creating cert-manager istio resources" $KUBECTL_BIN create namespace $K8S_NAMESPACE max=15 for x in $(seq 1 $max); do apply_cert-manager_bootstrap_manifests res=$? if [ $res -eq 0 ]; then break fi echo ">> [${x}] cert-manager not ready" && sleep 5 if [ x -eq 15 ]; then echo ">> Failed to deploy cert-manager and bootstrap manifests in time" exit 1 fi done echo ">> installing cert-manager-istio-csr" $HELM_BIN install cert-manager-istio-csr ./deploy/charts/istio-csr -n cert-manager --values ./hack/demo/istio-csr-values.yaml echo ">> installing istio" ./bin/istioctl-$2 install -y -f ./hack/istio-config-$2.yaml echo ">> enforcing mTLS everywhere" $KUBECTL_BIN apply -n istio-system -f - <<EOF apiVersion: "security.istio.io/v1beta1" kind: "PeerAuthentication" metadata: name: "default" spec: mtls: mode: STRICT EOF
#!/bin/bash gdb=0 valgrind=0 prefix=() extend() { if which "$1" &>/dev/null; then prefix+=("$@") else # bailing out would be counted as a failure by test harnesses, # ignore missing programs so that tests can be gracefully skipped printf "warning: command '$1' not found\n" >&2 fi } usage() { printf "runtest.sh - run an pacman test\n" printf "usage: runtest.sh [options] <testfile> [test-options]\n" printf "\n" printf "Options:\n" printf " -g gdb\n" printf " -h display help\n" printf " -v valgrind\n" } while getopts cdghlrsv name; do case $name in g) gdb=1;; h) usage; exit;; v) valgrind=1;; esac done [ $gdb -eq 1 ] && extend gdb [ $valgrind -eq 1 ] && extend valgrind --quiet --leak-check=full \ --gen-suppressions=no --error-exitcode=123 shift $(($OPTIND - 1)) # remove our options from the stack prog="$(realpath "$1")"; shift "${prefix[@]}" "$prog" "$@"
<gh_stars>0 import { h, Component } from 'preact'; import { Input } from '@authenticator/form'; import { NullAppError } from '@authenticator/errors'; interface Props { class?: string; id: string; label?: string; error: NullAppError; value: string; placeholder?: string; onChange: { (evt: Event, error: NullAppError): void }; onInput: { (code: string): void }; } /** * Higher level component to expose a validated TOTP * code submitted through an `Input` component. */ export default class InputCode extends Component<Props, {}> { handleCode = (e: Event): void => { const { value } = (e.currentTarget as HTMLFormElement); const { onInput } = this.props; onInput(value.trim()); } validateCode = (input: string | number): NullAppError => { const minCodeLen = 6; if (String(input).length < minCodeLen) { return { message: `Code should be at least ${minCodeLen} characters long`, code: 'invalid_code', } } return null; } render(): JSX.Element { return ( <Input class={this.props.class} label={this.props.label} value={this.props.value} error={this.props.error} placeholder={this.props.placeholder || 'Enter 6 digit verification code'} type='number' id={this.props.id} onChange={this.props.onChange} onInput={this.handleCode} validator={this.validateCode} /> ); } };
def round_value(value): return round(value, 2) def foo(x): return round_value(x) def bar(y): return round_value(y)
#!/usr/bin/env bash #####download one image and visualize its segmentation results #create directories for input&output data img_dir='raw_data' mkdir $img_dir res_dir='results' mkdir $res_dir rect_dir='col_rect' mkdir $res_dir/$rect_dir visualization='visualization' mkdir $res_dir/$visualization #download one orginal images from AWS S3 index='pr1954_p246' AWS_S3_Path="s3://harvardaha-raw-data/personnel-records/1954/scans/firm/$index.png" aws2 s3 cp $AWS_S3_Path $img_dir #download correspondent segmentation results from AWS S3 index='pr1954_p0246' #zero-padded AWS_S3_Path="s3://harvardaha-results/personnel-records/1954/seg/firm/$rect_dir/${index}_0.json" aws2 s3 cp $AWS_S3_Path $res_dir/$rect_dir #####visualize the results python ../Visualization/RenderBBox.py --imgdir=$img_dir --jsondir=$res_dir/$rect_dir --outputdir=$res_dir/$visualization
const mongoose = require('mongoose'); const { NOTE_CREATION, NOTE_UPDATE } = require('../helpers/constants'); const { formatQuery, formatQueryMiddlewareList } = require('./preHooks/validate'); const CustomerNoteHistorySchema = mongoose.Schema({ company: { type: mongoose.Schema.Types.ObjectId, ref: 'Company', required: true, immutable: true }, customerNote: { type: mongoose.Schema.Types.ObjectId, ref: 'CustomerNote', required: true, immutable: true }, title: { type: String, required() { return this.action === NOTE_CREATION; }, immutable: true }, description: { type: String, required() { return this.action === NOTE_CREATION; }, immutable: true }, createdBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, immutable: true }, action: { type: String, required: true, immutable: true, enum: [NOTE_CREATION, NOTE_UPDATE] }, }, { timestamps: true }); formatQueryMiddlewareList().map(middleware => CustomerNoteHistorySchema.pre(middleware, formatQuery)); module.exports = mongoose.model('CustomerNoteHistory', CustomerNoteHistorySchema);
/* * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.server.common.nosql.mongo.dao; import org.kaaproject.kaa.common.dto.HasVersion; import org.kaaproject.kaa.server.common.dao.exception.KaaOptimisticLockingFailureException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.OptimisticLockingFailureException; public abstract class AbstractVersionableMongoDao<T extends HasVersion, K> extends AbstractMongoDao<T, K> { private static final Logger LOG = LoggerFactory.getLogger(AbstractVersionableMongoDao.class); public T save(T dto) { try { mongoTemplate.save(dto); return dto; } catch (OptimisticLockingFailureException exception) { LOG.error("[{}] Can't update entity with version {}. Entity already changed!", getDocumentClass(), dto.getVersion()); throw new KaaOptimisticLockingFailureException( "Can't update entity with version " + dto.getVersion() + ". Entity already changed!"); } catch (DuplicateKeyException exception) { LOG.error("[{}] Can't insert entity. Entity already exists!", getDocumentClass()); throw new KaaOptimisticLockingFailureException("Can't insert entity. Entity already exists!"); } } }
export default()=>{}; //# sourceMappingURL=edgeTarget.prod.js.map
<reponame>ziecik/rental-cars-rest-api<gh_stars>0 package com.example.rentalcarsrestapi.model.audit; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) //@JsonIgnoreProperties(value = {"creatorUser", "lastModifierUser"}) public abstract class UserDateAudit extends DateAudit{ @CreatedBy private String creatorUser; @LastModifiedBy private String lastModifierUser; public String getCreatorUser() { return creatorUser; } public void setCreatorUser(String creatorUser) { this.creatorUser = creatorUser; } public String getLastModifierUser() { return lastModifierUser; } public void setLastModifierUser(String lastModifierUser) { this.lastModifierUser = lastModifierUser; } }
func isFunction(object: Any?, functionName: String, completion: @escaping (Bool) -> Void) { // Implement the logic to check if the function exists within the object // For example, if the object is a class instance, you can use reflection to check for the existence of the function // Placeholder logic to demonstrate the completion let functionExists = false // Replace with actual logic to check function existence // Simulate asynchronous behavior using DispatchQueue DispatchQueue.global().async { completion(functionExists) } } // Example usage: let testObject: Any? = SomeClass() // Replace with the actual object to be inspected let functionName = "someFunction" // Replace with the actual function name to be checked isFunction(object: testObject, functionName: functionName) { (isFunction) in if isFunction { print("The function '\(functionName)' exists within the object.") } else { print("The function '\(functionName)' does not exist within the object.") } }
import logging import tornado.web REQUEST_ID_HEADER = 'X-Request-Id' AUTH_USER_HEADER = 'X-Auth-User' class LoggingApplication(tornado.web.Application): def __init__(self, handlers=None, default_host="", transforms=None, **settings): super(LoggingApplication, self).__init__(handlers, default_host, transforms, **settings) self.logger = logging.getLogger('custom_logger') self.logger.setLevel(logging.INFO) async def __call__(self, request): request_id = request.headers.get(REQUEST_ID_HEADER) auth_user = request.headers.get(AUTH_USER_HEADER) self.log_request_info(request_id, auth_user) return await super().__call__(request) def log_request_info(self, request_id, auth_user): log_message = f"Request ID: {request_id}" if auth_user: log_message += f", Authenticated User: {auth_user}" self.logger.info(log_message)
#!/bin/bash # Copyright 2021 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 set -euo pipefail TANZU_BOM_DIR=${HOME}/.config/tanzu/tkg/bom INSTALL_INSTRUCTIONS='See https://github.com/mikefarah/yq#install for installation instructions' TKG_IMAGE_REPO=${TKG_IMAGE_REPO:-''} TKG_BOM_IMAGE_TAG=${TKG_BOM_IMAGE_TAG:-''} echodual() { echo "$@" 1>&2 echo "#" "$@" } if [ -z "$TKG_IMAGE_REPO" ]; then echo "TKG_IMAGE_REPO variable is required but is not defined" >&2 exit 2 fi if ! [ -x "$(command -v imgpkg)" ]; then echo 'Error: imgpkg is not installed.' >&2 exit 3 fi if ! [ -x "$(command -v yq)" ]; then echo 'Error: yq is not installed.' >&2 echo "${INSTALL_INSTRUCTIONS}" >&2 exit 3 fi function imgpkg_copy() { flags=$1 src=$2 dst=$3 echo "" echo "imgpkg copy $flags $src --to-tar $dst.tar" } echo "set -euo pipefail" echodual "Note that yq must be version above or equal to version 4.9.2 and below version 5." actualImageRepository="$TKG_IMAGE_REPO" # Iterate through TKG BoM file to create the complete Image name # and then pull, retag and push image to custom registry. list=$(imgpkg tag list -i "${actualImageRepository}"/tkg-bom) for imageTag in ${list}; do tanzucliversion=$(tanzu version | head -n 1 | cut -c10-15) if [[ ${imageTag} == ${tanzucliversion}* ]] || [[ ${imageTag} == ${TKG_BOM_IMAGE_TAG} ]]; then TKG_BOM_FILE="tkg-bom-${imageTag//_/+}.yaml" imgpkg pull --image "${actualImageRepository}/tkg-bom:${imageTag}" --output "tmp" > /dev/null 2>&1 echodual "Processing TKG BOM file ${TKG_BOM_FILE}" actualTKGImage=${actualImageRepository}/tkg-bom:${imageTag} customTKGImage=tkg-bom-${imageTag} imgpkg_copy "-i" $actualTKGImage $customTKGImage # Get components in the tkg-bom. # Remove the leading '[' and trailing ']' in the output of yq. components=(`yq e '.components | keys | .. style="flow"' "tmp/$TKG_BOM_FILE" | sed 's/^.//;s/.$//'`) for comp in "${components[@]}" do # remove: leading and trailing whitespace, and trailing comma comp=`echo $comp | sed -e 's/^[[:space:]]*//' | sed 's/,*$//g'` get_comp_images="yq e '.components[\"${comp}\"][] | select(has(\"images\"))|.images[] | .imagePath + \":\" + .tag' "\"tmp/\"$TKG_BOM_FILE"" flags="-i" if [ $comp = "tkg-standard-packages" ] || [ $comp = "standalone-plugins-package" ] || [ $comp = "tanzu-framework-management-packages" ]; then flags="-b" fi eval $get_comp_images | while read -r image; do actualImage=${actualImageRepository}/${image} image2=$(echo "$image" | tr ':' '-' | tr '/' '-') customImage=${image2} imgpkg_copy $flags $actualImage $customImage done done rm -rf tmp echodual "Finished processing TKG BOM file ${TKG_BOM_FILE}" echo "" fi done # Iterate through TKR BoM file to create the complete Image name # and then pull, retag and push image to custom registry. list=$(imgpkg tag list -i ${actualImageRepository}/tkr-bom) for imageTag in ${list}; do if [[ ${imageTag} == v* ]]; then TKR_BOM_FILE="tkr-bom-${imageTag//_/+}.yaml" echodual "Processing TKR BOM file ${TKR_BOM_FILE}" actualTKRImage=${actualImageRepository}/tkr-bom:${imageTag} customTKRImage=tkr-bom-${imageTag} imgpkg_copy "-i" $actualTKRImage $customTKRImage imgpkg pull --image ${actualImageRepository}/tkr-bom:${imageTag} --output "tmp" > /dev/null 2>&1 # Get components in the tkr-bom. # Remove the leading '[' and trailing ']' in the output of yq. components=(`yq e '.components | keys | .. style="flow"' "tmp/$TKR_BOM_FILE" | sed 's/^.//;s/.$//'`) for comp in "${components[@]}" do # remove: leading and trailing whitespace, and trailing comma comp=`echo $comp | sed -e 's/^[[:space:]]*//' | sed 's/,*$//g'` get_comp_images="yq e '.components[\"${comp}\"][] | select(has(\"images\"))|.images[] | .imagePath + \":\" + .tag' "\"tmp/\"$TKR_BOM_FILE"" flags="-i" if [ $comp = "tkg-core-packages" ]; then flags="-b" fi eval $get_comp_images | while read -r image; do actualImage=${actualImageRepository}/${image} image2=$(echo "$image" | tr ':' '-' | tr '/' '-') customImage=${image2} imgpkg_copy $flags $actualImage $customImage done done rm -rf tmp echodual "Finished processing TKR BOM file ${TKR_BOM_FILE}" echo "" fi done list=$(imgpkg tag list -i ${actualImageRepository}/tkr-compatibility) for imageTag in ${list}; do if [[ ${imageTag} == v* ]]; then echodual "Processing TKR compatibility image" actualImage=${actualImageRepository}/tkr-compatibility:${imageTag} customImage=tkr-compatibility-${imageTag} imgpkg_copy "-i" $actualImage $customImage echo "" echodual "Finished processing TKR compatibility image" fi done list=$(imgpkg tag list -i ${actualImageRepository}/tkg-compatibility) for imageTag in ${list}; do if [[ ${imageTag} == v* ]]; then echodual "Processing TKG compatibility image" actualImage=${actualImageRepository}/tkg-compatibility:${imageTag} customImage=tkg-compatibility-${imageTag} imgpkg_copy "-i" $actualImage $customImage echo "" echodual "Finished processing TKG compatibility image" fi done
fpath=(/usr/local/share/zsh/site-functions $fpath) autoload -U compinit compinit -u setopt auto_menu setopt complete_in_word setopt always_to_end zstyle ':completion:*:*:*:*:*' menu select # menu select zstyle ':completion:*' matcher-list 'm:{a-zA-Z-_}={A-Za-z_-}' 'r:|=*' 'l:|=* r:|=*' # case insensitive search zstyle ':completion:*' list-colors '' # colored completions # Use caching so that commands like apt and dpkg complete are useable zstyle ':completion::complete:*' use-cache 1 zstyle ':completion::complete:*' cache-path ~/.zsh/cache
package io.dronefleet.mavlink.common; import io.dronefleet.mavlink.annotations.MavlinkFieldInfo; import io.dronefleet.mavlink.annotations.MavlinkMessageBuilder; import io.dronefleet.mavlink.annotations.MavlinkMessageInfo; import io.dronefleet.mavlink.util.EnumValue; import java.lang.Enum; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Collection; import java.util.Objects; /** * Status text message. These messages are printed in yellow in the COMM console of * QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status * and error messages. If implemented wisely, these messages are buffered on the MCU and sent only * at a limited rate (e.g. 10 Hz). */ @MavlinkMessageInfo( id = 253, crc = 83, description = "Status text message. These messages are printed in yellow in the COMM console of QGroundControl. WARNING: They consume quite some bandwidth, so use only for important status and error messages. If implemented wisely, these messages are buffered on the MCU and sent only at a limited rate (e.g. 10 Hz)." ) public final class Statustext { private final EnumValue<MavSeverity> severity; private final String text; private Statustext(EnumValue<MavSeverity> severity, String text) { this.severity = severity; this.text = text; } /** * Returns a builder instance for this message. */ @MavlinkMessageBuilder public static Builder builder() { return new Builder(); } /** * Severity of status. Relies on the definitions within RFC-5424. */ @MavlinkFieldInfo( position = 1, unitSize = 1, enumType = MavSeverity.class, description = "Severity of status. Relies on the definitions within RFC-5424." ) public final EnumValue<MavSeverity> severity() { return this.severity; } /** * Status text message, without null termination character */ @MavlinkFieldInfo( position = 2, unitSize = 1, arraySize = 50, description = "Status text message, without null termination character" ) public final String text() { return this.text; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !getClass().equals(o.getClass())) return false; Statustext other = (Statustext)o; if (!Objects.deepEquals(severity, other.severity)) return false; if (!Objects.deepEquals(text, other.text)) return false; return true; } @Override public int hashCode() { int result = 0; result = 31 * result + Objects.hashCode(severity); result = 31 * result + Objects.hashCode(text); return result; } @Override public String toString() { return "Statustext{severity=" + severity + ", text=" + text + "}"; } public static final class Builder { private EnumValue<MavSeverity> severity; private String text; /** * Severity of status. Relies on the definitions within RFC-5424. */ @MavlinkFieldInfo( position = 1, unitSize = 1, enumType = MavSeverity.class, description = "Severity of status. Relies on the definitions within RFC-5424." ) public final Builder severity(EnumValue<MavSeverity> severity) { this.severity = severity; return this; } /** * Severity of status. Relies on the definitions within RFC-5424. */ public final Builder severity(MavSeverity entry) { return severity(EnumValue.of(entry)); } /** * Severity of status. Relies on the definitions within RFC-5424. */ public final Builder severity(Enum... flags) { return severity(EnumValue.create(flags)); } /** * Severity of status. Relies on the definitions within RFC-5424. */ public final Builder severity(Collection<Enum> flags) { return severity(EnumValue.create(flags)); } /** * Status text message, without null termination character */ @MavlinkFieldInfo( position = 2, unitSize = 1, arraySize = 50, description = "Status text message, without null termination character" ) public final Builder text(String text) { this.text = text; return this; } public final Statustext build() { return new Statustext(severity, text); } } }
#ifndef _WKT_KEYBOARD_EVENT_SYSTEM_H #define _WKT_KEYBOARD_EVENT_SYSTEM_H #include "ecs/System.h" #include "components/KeyboardReceiver.h" #include "components/KeyboardEventReceiver.h" #include "input/KeyboardProxy.h" #include <vector> namespace wkt { namespace systems { class KeyboardSystemBase { public: void init(); void shutdown(); public: std::vector<wkt::events::KeyboardEventType>& getEvents() { return this->events; } private: std::vector<wkt::events::KeyboardEventType> events; }; class KeyboardReceiverSystem : public wkt::ecs::SequentialSystem<wkt::components::KeyboardReceiver> { public: KeyboardReceiverSystem(); public: void init() override { this->ksb.init(); } void operator()(std::shared_ptr<wkt::components::KeyboardReceiver>); void shutdown() override { this->ksb.shutdown(); } private: std::vector<wkt::events::KeyboardEventType>& getEvents() { return this->ksb.getEvents(); } private: KeyboardSystemBase ksb; }; class KeyboardEventReceiverSystem : public wkt::ecs::SequentialSystem<wkt::components::KeyboardEventReceiver> { public: KeyboardEventReceiverSystem(); public: void init() override { this->ksb.init(); } void operator()(std::shared_ptr<wkt::components::KeyboardEventReceiver>); void shutdown() override { this->ksb.shutdown(); } private: std::vector<wkt::events::KeyboardEventType>& getEvents() { return this->ksb.getEvents(); } private: KeyboardSystemBase ksb; }; }} #endif
export interface Form { name: string; email: string; message: string; } export interface State { loading: boolean; success: boolean; error: boolean; } export enum ActionTypes { SEND_MESSAGE_START = 'SEND_MESSAGE_START', SEND_MESSAGE_SUCCESS = 'SEND_MESSAGE_SUCCESS', SEND_MESSAGE_ERROR = 'SEND_MESSAGE_ERROR', RESET_SUCCESS = 'RESET_SUCCESS', RESET_ERROR = 'RESET_ERROR', }
#!/bin/bash -eu echo -e '\033[33mCreating a nice looking StackStorm welcome message after SSH login ...\033[0m' echo 'StackStorm \n \l' > /etc/issue cat << 'EOF' > /etc/update-motd.d/00-header #!/bin/sh if [ -f /opt/stackstorm/st2/lib/python3.6/site-packages/st2common/__init__.py ]; then # Get st2 version based on hardcoded string in st2common ST2_VERSION=$(/opt/stackstorm/st2/bin/python -c 'exec(open("/opt/stackstorm/st2/lib/python3.6/site-packages/st2common/__init__.py").read()); print(__version__)') printf "Welcome to \033[1;38;5;208mStackStorm\033[0m \033[1m%s\033[0m (Ubuntu 16.04 LTS %s %s)\n" "v${ST2_VERSION}" "$(uname -o)" "$(uname -m)" else printf "Welcome to \033[1;38;5;208mStackStorm\033[0m (Ubuntu 16.04 LTS %s %s)\n" "$(uname -o)" "$(uname -m)" fi EOF cat << 'EOF' > /etc/update-motd.d/10-help-text #!/bin/sh printf "\n" printf " * Documentation: https://docs.stackstorm.com/\n" printf " * Community: https://stackstorm.com/community-signup\n" printf " * Forum: https://forum.stackstorm.com/\n" EOF chmod +x /etc/update-motd.d/*
#!/bin/bash # configs/stm3220g-eval/nxwm/setenv.sh # # Copyright (C) 2012 Gregory Nutt. All rights reserved. # Author: Gregory Nutt <gnutt@nuttx.org> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # 3. Neither the name NuttX nor the names of its contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # if [ "$_" = "$0" ] ; then echo "You must source this script, not run it!" 1>&2 exit 1 fi WD=`pwd` if [ ! -x "setenv.sh" ]; then echo "This script must be executed from the top-level NuttX build directory" exit 1 fi if [ -z "${PATH_ORIG}" ]; then export PATH_ORIG="${PATH}" fi # This is the Cygwin path to the location where I installed the RIDE # toolchain under windows. You will also have to edit this if you install # the RIDE toolchain in any other location #export TOOLCHAIN_BIN="/cygdrive/c/Program Files (x86)/Raisonance/Ride/arm-gcc/bin" # This is the Cygwin path to the location where I installed the CodeSourcery # toolchain under windows. You will also have to edit this if you install # the CodeSourcery toolchain in any other location export TOOLCHAIN_BIN="/cygdrive/c/Program Files (x86)/CodeSourcery/Sourcery G++ Lite/bin" # These are the Cygwin paths to the locations where I installed the Atollic # toolchain under windows. You will also have to edit this if you install # the Atollic toolchain in any other location. /usr/bin is added before # the Atollic bin path because there is are binaries named gcc.exe and g++.exe # at those locations as well. #export TOOLCHAIN_BIN="/usr/bin:/cygdrive/c/Program Files (x86)/Atollic/TrueSTUDIO for ARM Pro 2.3.0/ARMTools/bin" #export TOOLCHAIN_BIN="/usr/bin:/cygdrive/c/Program Files (x86)/Atollic/TrueSTUDIO for STMicroelectronics STM32 Lite 2.3.0/ARMTools/bin" # This is the Cygwin path to the location where I build the buildroot # toolchain. #export TOOLCHAIN_BIN="${WD}/../buildroot/build_arm_nofpu/staging_dir/bin" # Add the path to the toolchain to the PATH variable export PATH="${TOOLCHAIN_BIN}:/sbin:/usr/sbin:${PATH_ORIG}" echo "PATH : ${PATH}"
HCDIR=`dirname $(readlink -f "$0")` dnf update --assumeyes pkgs="autoconf \ bison \ flex \ gcc \ gcc-c++ \ libstdc++ \ libstdc++-static \ glibc-static \ git \ libtool \ make \ pkg-config \ protobuf-devel \ protobuf-compiler \ git \ wget \ java-1.8.0-openjdk \ java-1.8.0-openjdk-devel \ python3 \ libnl3-devel" dnf install --enablerepo=PowerTools --assumeyes $pkgs || dnf install --enablerepo=powertools --assumeyes $pkgs dnf module --assumeyes install nodejs:14 curl https://sh.rustup.rs -sSf | sh -s -- --profile default -y && source ~/.cargo/env source /etc/profile npm install -g npm git clone -b v0.4.0 --depth=1 --single-branch https://github.com/ThinkSpiritLab/ojcmp.git ~/ojcmp \ && cd ~/ojcmp && cargo build --release && cp target/release/ojcmp /usr/bin && cd ~ git clone --depth=1 --single-branch https://github.com/google/nsjail.git ~/nsjail \ && cd ~/nsjail && make && cp ~/nsjail/nsjail /usr/bin/nsjail && cd ~ git clone --depth=1 --single-branch https://github.com/ThinkSpiritLab/Heng-Core.git ~/Heng-Core \ && cd ~/Heng-Core && make && cp ~/Heng-Core/hc /usr/bin/hc && cd ~ cp -r ~/.rustup/toolchains/`ls ~/.rustup/toolchains/ | grep "stable"` /usr/local/rustup && ln -s /usr/local/rustup/bin/rustc /usr/bin/rustc cp $HCDIR/Tools/testlib.h /testlib.h cd $HCDIR && npm install && npm run build && cd ~ dnf clean all rm -rf /var/cache/yum rm -rf /var/cache/dnf rm -rf ~/ojcmp rm -rf ~/nsjail rm -rf ~/Heng-Core rm -rf ~/.cargo rm -rf ~/.rustup/ rm -rf /usr/local/rustup/share/doc npm cache clean --force
import { ResolveTree } from "graphql-parse-resolve-info"; import { Attribute, Model, Relation } from "../types"; interface ModelArg { baseModel: Model; models: { [key: string]: Model }; tree: ResolveTree; } /** * Convert a graphql selectionSet to * */ export const graphFieldsToModel = ({ tree, baseModel, models }: ModelArg): Model => { const attributes: { [key: string]: Attribute } = {}; const relations: { [key: string]: Relation } = {}; const { fieldsByTypeName } = tree; const [[, projection]] = Object.entries(fieldsByTypeName); for (const [fieldName, fieldTree] of Object.entries(projection)) { if (baseModel.attributes[fieldName]) { attributes[fieldName] = baseModel.attributes[fieldName]; } else { const theRelation = { ...baseModel.relations[fieldName] }; relations[fieldName] = Object.assign(theRelation, { model: graphFieldsToModel({ baseModel: models[theRelation.type], models, tree: fieldTree }) }); } } return { ...baseModel, attributes, relations }; };
#!/bin/bash set -euo pipefail # You can execute this script with: # bash <(curl -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -s 'https://raw.githubusercontent.com/alombarte/raspberry-osmc-automated/master/install.sh') /home/osmc/.raspberry-osmc-automated if [ $# != 1 ] then echo "Installation of raspberry-osmc-automated" echo "--USAGE: $0 install_path" exit 0 fi if [ "root" = "$(whoami)" ]; then echo "Do not run this script as root. The sudo command will be used when needed." exit 0 fi INSTALLATION_FOLDER=$1 SETTINGS_FILE="$INSTALLATION_FOLDER/bash/settings.cfg" SAMPLE_RSS_FEED="http://showrss.info/rss.php?user_id=51436&hd=2&proper=1" echo "Starting installation in path $INSTALLATION_FOLDER" echo "Press ENTER to proceed or CTRL+C to abort" echo "--------------------------------------------------" read -r _ curl -L -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -O 'https://raw.githubusercontent.com/alombarte/raspberry-osmc-automated/master/install.sh' # DOWNLOAD TARBALL bash <(curl -s https://raw.githubusercontent.com/alombarte/raspberry-osmc-automated/master/bash/download_tarball.sh) "$INSTALLATION_FOLDER" # Add installation path to settings echo "INSTALLATION_FOLDER=$INSTALLATION_FOLDER" >> "$SETTINGS_FILE" # Ask user for default paths echo "--------------------------------------------------" echo "Take a few seconds to customize your installation." echo "" echo "Paste your RSS feed URL below or press ENTER to use sample" echo "E.g: : $SAMPLE_RSS_FEED" read -r CONFIG_RSS_FEED if [ "$CONFIG_RSS_FEED" == "" ] ; then CONFIG_RSS_FEED=$SAMPLE_RSS_FEED echo "No RSS provided, using sample feed $CONFIG_RSS_FEED" fi # Add RSS feed to settings echo "CONFIG_RSS_FEED=\"$CONFIG_RSS_FEED\"" >> "$SETTINGS_FILE" # Confirm IP IP_GUESS=$(ifconfig | awk '/inet /{print $2}' | grep -v 127.0.0.1 | tail -n 1) echo "" echo "IP address (or ENTER to accept) [$IP_GUESS]: " read -r IP if [ "$IP" == "" ] ; then IP=$IP_GUESS fi IP_RANGE=$(echo "$IP" | sed -r 's/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)[0-9]{1,3}/\1*/') echo "OSMC_HOST=\"$IP\"" >> "$SETTINGS_FILE" echo "TRANSMISSION_WHITELIST_RANGE=\"$IP_RANGE\"" >> "$SETTINGS_FILE" echo "" echo "Are you storing content on a external storage? If so, what is the mountpoint? (e.g: /media/KINGSTON)" echo "Press ENTER to skip, or write the path now:" read -r EXTERNAL_STORAGE if [ "$EXTERNAL_STORAGE" == "" ] || [ ! -d "$EXTERNAL_STORAGE" ] ; then echo "Omitting external storage. Preparing folder structure..." mkdir -p "$EXTERNAL_STORAGE"/{Downloads/Incomplete,Movies,Music,Pictures,"TV Shows"} else bash "$INSTALLATION_FOLDER/bash/folder_structure.sh" "$EXTERNAL_STORAGE" echo "EXTERNAL_STORAGE=\"$EXTERNAL_STORAGE\"" >> "$SETTINGS_FILE" fi echo "" echo "In what language do you want the subtitles? " echo "(Two letter code: en,es,fr,de,it...) : " read -r SUBTITLES_LANGUAGE if [ "$SUBTITLES_LANGUAGE" == "" ] ; then echo "Default to English subtitles" SUBTITLES_LANGUAGE="en" fi echo "--------------------------------------------------" # INSTALLATION BEGIN echo "All set. INSTALLING..." echo "Updating APT repositories" sudo apt-get update # Add write permission to osmc group. We will add other users in this group chmod -R 775 /home/osmc bash "$INSTALLATION_FOLDER/bash/install_transmission.sh" "$IP_RANGE" bash "$INSTALLATION_FOLDER/bash/install_flexget.sh" "$INSTALLATION_FOLDER" "$SUBTITLES_LANGUAGE" "$CONFIG_RSS_FEED" bash "$INSTALLATION_FOLDER/bash/install_crontab.sh" "$SUBTITLES_LANGUAGE" bash "$INSTALLATION_FOLDER/bash/user_profile.sh" bash "$INSTALLATION_FOLDER/bash/install_additional_packages.sh" bash "$INSTALLATION_FOLDER/bash/install_motd.sh" echo "--------------------------------------------------" echo " Installation complete!" echo "--------------------------------------------------" echo "The following services are also available from your network *:" echo "" echo "Transmission web client (montitor ongoing downloads)" echo "- http://$IP:9091 (credentials: transmission / transmission)" echo "" echo "Kodi Web (remote control)" echo "- http://$IP" echo "" echo "--------------------------------------------------" echo "" echo "You might want to set your Timezone now" echo "Run: sudo dpkg-reconfigure tzdata" echo "" echo "You might also want to move this file away" echo "Run: mv install.sh /home/osmc/.raspberry-osmc-automated/"
<filename>src/components/primatives/modal.tsx<gh_stars>0 import React, { useEffect, useRef, useLayoutEffect } from "react" import styled from "@emotion/styled" const ModalOverlay = styled.div` align-items: center; justify-content: center; background-color: rgba(0, 0, 0, 0.65); display: flex; padding: 1em; position: fixed; top: 0; left: 0; height: 100%; width: 100%; ` const ModalPaper = styled.div` background-color: white; border-radius: 3px; padding: 1rem 2rem; text-align: center; overflow: visible; max-height: 100vh; overflow-y: auto; ` // Hooks function useOnClickOutside( ref: React.RefObject<HTMLDivElement>, handler: (a: any) => void ) { useEffect(() => { const listener = (event: Event) => { // Do nothing if clicking ref's element or descendent elements if (!ref.current || ref.current.contains(event.target as Node)) { return } handler(event) } document.addEventListener("mousedown", listener) document.addEventListener("touchstart", listener) return () => { document.removeEventListener("mousedown", listener) document.removeEventListener("touchstart", listener) } }, []) // Empty array ensures that effect is only run on mount and unmount } function useLockBodyScroll() { useLayoutEffect(() => { // Prevent scrolling on mount document.body.style.overflow = "hidden" // Re-enable scrolling when component unmounts return () => (document.body.style.overflow = "visible") }, []) // Empty array ensures effect is only run on mount and unmount } export default function Modal({ onClose, children, }: { onClose: () => void children: React.ReactNode }) { const ref = useRef(null) useOnClickOutside(ref, () => onClose()) useLockBodyScroll() return ( <ModalOverlay> <ModalPaper ref={ref}>{children}</ModalPaper> </ModalOverlay> ) }
<reponame>init00/portfolio_site<filename>src/pages/index.js<gh_stars>0 import React, { Component } from "react" import Navbar from '../components/UI/navigation/navbar/navbar' import Banner from '../components/UI/banner/banner' import Cards from '../components/UI/cards/cards' import contentUrlMap from '../constants/contentUrlMap' class App extends Component { constructor() { super() this.state = { projectCoverUrlMap: contentUrlMap, showBanner: true, imageLoading: true } } componentDidMount() { this.prev = window.scrollY window.addEventListener('scroll', this.detectScrollDirection.bind(this), true) } detectScrollDirection(event) { event.preventDefault() const window = event.currentTarget; if(!this.state.showBanner) { window.removeEventListener('scroll', this.detectScrollDirection.bind(this), true) return; } if (this.prev - window.scrollY > 0) { this.setState({showBanner: true}) } if (this.prev - window.scrollY < 0) { this.setState({showBanner: false}) } this.prev = window.scrollY } bannerClickHandler = (event) => { event.preventDefault() this.setState({showBanner: false}) } imageLoadHandler = (event) => { this.setState({imageLoading: false}) } render() { let banner = <Banner showBanner={this.state.showBanner} bannerHandler={this.bannerClickHandler} /> let projDisplay = <Cards contentUrl={this.state.projectCoverUrlMap} showBanner={this.state.showBanner} /> return ( <div className="app-enclosure" onScroll={this.bannerClickHandler}> <Navbar activePage="Work" /> {banner} {projDisplay} </div> )} } export default App
<reponame>wongoo/alipay-sdk-java-all<filename>src/main/java/com/alipay/api/domain/GFAOpenAPICommandReceipt.java<gh_stars>0 package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 业财受理指令回执信息 * * @author auto create * @since 1.0, 2020-08-27 20:00:30 */ public class GFAOpenAPICommandReceipt extends AlipayObject { private static final long serialVersionUID = 3565937843246549316L; /** * 回执扩展信息 */ @ApiField("ext_info") private String extInfo; /** * 回执状态 */ @ApiField("receipt_status") private String receiptStatus; public String getExtInfo() { return this.extInfo; } public void setExtInfo(String extInfo) { this.extInfo = extInfo; } public String getReceiptStatus() { return this.receiptStatus; } public void setReceiptStatus(String receiptStatus) { this.receiptStatus = receiptStatus; } }
#!/usr/bin/env bash # Script to start / stop halOS. # # Parameter # 1. start|stop # 2. port # # What it does # 1. Pull halOS (if necessary) # 2. Start / stop halOS docker container # 3. Create a network for talking to WildFly instances NETWORK=halos-net if [[ $# -lt 1 ]] then echo "Please use $0 start|stop <port>" exit 1 fi command=$1 if [[ $command == "start" ]] then if [[ -z $2 ]] then echo "Please use $0 start <port>" exit 1 fi port=$2 docker network inspect $NETWORK >/dev/null 2>&1 || docker network create $NETWORK docker run --name halos -p $port:8080 --detach --rm --network $NETWORK quay.io/halconsole/halos:latest elif [[ $command == "stop" ]] then docker stop halos fi
<!DOCTYPE html> <html> <head> <title>User Profile</title> </head> <body> <h1>User Profile</h1> <p>Name: John Doe</p> <p>Age: 28</p> <p>Country: USA</p> </body> </html>
def sum_prime_numbers(limit): sum = 0 for num in range(2, limit + 1): if all(num % i != 0 for i in range(2, num)): sum += num return sum print(sum_prime_numbers(100))
<reponame>rjwittrock/WIT<filename>wit/src/MrPt.h //============================================================================== // WIT // // Based On: //============================================================================== // Constrained Materials Management and Production Planning Tool // // (C) Copyright IBM Corp. 1993, 2020 All Rights Reserved //============================================================================== #ifndef MrPtH #define MrPtH //------------------------------------------------------------------------------ // Header file: "MrPt.h" // // Contains the declaration of class MrPt. //------------------------------------------------------------------------------ #include <DetSelPt.h> #include <SelCand.h> //------------------------------------------------------------------------------ // Class MrPt. // // "Multi-Route Point" // Represents a location (in the BOM structure) and period at which multi-route // selection is to be performed. // // Class Hierarchy: // // SelPt // DetSelPt // MrPt // // Implemented in MultiRoute.C. //------------------------------------------------------------------------------ class WitMrPt: public WitDetSelPt { public: //------------------------------------------------------------------------ // Constructor functions. //------------------------------------------------------------------------ WitMrPt (WitMrSite *, WitPeriod); //------------------------------------------------------------------------ // Destructor function. //------------------------------------------------------------------------ virtual ~WitMrPt (); //------------------------------------------------------------------------ // Other public member functions. //------------------------------------------------------------------------ void select (WitRtCand * theRtCand); // // Selects theRtCand for this MrPt. void recoverInitState (); // // Restores the Multi-Route configuration at this MrPt to its initial // state. accessFunc (WitMrSite *, myMrSite) accessFunc (WitPeriod, myPer) accessFunc (WitRtCand *, selRtCand) private: //------------------------------------------------------------------------ // Private member functions. //------------------------------------------------------------------------ virtual WitSelMgr * mySelMgr (); virtual void prtID (); virtual bool splittable (); virtual void getSortData (WitPart * &, WitPeriod &); virtual WitSelCand * newSelCand (); virtual bool sglSrcMode (); // // Overrides from class SelPt. virtual bool hasResAlt (); virtual void alterSelection (); virtual void storeRecoveryPt (); virtual void tempAlterSel (); virtual void cancelTempAlt (); virtual void printAlteration (); // // Overrides from class DetSelPt. void refreshHasResAlt (); // // Computes hasResAlt_. WitRtCand * findNextRtCand (); // // Finds and returns the first selectable RtCand for this MrPt // that is not its current selection, or NULL, if there is none. void printRecovery (); // // Prints the restoration of the Multi-Route configuration at this MrPt // to its initial state. FILE * msgFile (); inline WitSelector * mySelector (); noCopyCtorAssign (WitMrPt); //------------------------------------------------------------------------ // Private member data. //------------------------------------------------------------------------ WitMrSite * const myMrSite_; // // The MrSite that owns this MrPt. const WitPeriod myPer_; // // The period in which selection is to be done. WitRtCand * selRtCand_; // // The RtCand currently selected for routing from this MrPt, if any; // otherwise, NULL. bool hasResAlt_; // // true, iff this MrPt currently has a selection and an // shortage-resolving alternative to the current selection exists. }; #endif
<reponame>Crowntium/crowntium<gh_stars>1-10 // Aleth: Ethereum C++ client, tools and libraries. // Copyright 2015-2019 Aleth Authors. // Licensed under the GNU General Public License, Version 3. /** * Determines the PoW algorithm. */ #pragma once #include <libethcore/BlockHeader.h> #include <libdevcore/Guards.h> namespace dev { namespace eth { /// Proof of work definition for Ethash. struct EthashProofOfWork { struct Solution { Nonce nonce; h256 mixHash; }; struct Result { h256 value; h256 mixHash; }; struct WorkPackage { WorkPackage() {} WorkPackage(BlockHeader const& _bh); WorkPackage(WorkPackage const& _other); WorkPackage& operator=(WorkPackage const& _other); void reset() { Guard l(m_headerHashLock); m_headerHash = h256(); } operator bool() const { Guard l(m_headerHashLock); return m_headerHash != h256(); } h256 headerHash() const { Guard l(m_headerHashLock); return m_headerHash; } h256 boundary; h256 seedHash; private: h256 m_headerHash; ///< When h256() means "pause until notified a new work package is available". mutable Mutex m_headerHashLock; }; static const WorkPackage NullWorkPackage; /// Default value of the local work size. Also known as workgroup size. static const unsigned defaultLocalWorkSize; /// Default value of the global work size as a multiplier of the local work size static const unsigned defaultGlobalWorkSizeMultiplier; /// Default value of the milliseconds per global work size (per batch) static const unsigned defaultMSPerBatch; }; } }
karma start ../config/karma.conf.js *
# See the README.md module Horcrux VERSION = "0.1.2" # Implements the optional methods of a Horcrux adapter. module Methods def self.included(klass) klass.send :attr_reader, :client, :serializer end # Public: Sets up an adapter with the client. # # client - This is the object that the adapter uses to store and # retrieve data. # serializer - An object that responds to #pack and #unpack for # serializing and deserializing values. Default: a # StringSerializer. def initialize(client, serializer = nil) @client = client @serializer = serializer || StringSerializer end # Public: Gets all the values for the given keys. # # @adapter.get_all('a', 'b') # # => ['1', '2'] # # keys - One or more String keys. # # Returns an Array of unpacked values in the order of their associated # keys. def get_all(*keys) keys.map { |k| get(k) } end # Public: Sets the given values. # # @adapter.set_all 'a' => '1', 'b' => '2' # # => ['a', 'b'] # # values - A Hash of String keys and Object values. # # Returns an Array of the successfully written String keys. def set_all(values) good_keys = [] values.each do |key, value| good_keys << key if set(key, value) end good_keys end # Public: Deletes the given keys. # # @adapter.delete_all 'a', 'b' # # => [true, false] # # keys - One or more String keys. # # Returns an Array of Booleans specifying whether the deletes were # successful. def delete_all(*keys) keys.map { |k| delete(k) } end # Public: Determines if the key is set. # # key - A String key. # # Returns true if the key is set, or false. def key?(key) !get(key).nil? end # Public: Either gets the value of the key, or sets it if it doesn't exist. # # # if 'some-cache' is not set, call #slow_method # @adapter.fetch('some-cache') { slow_method } # # key - A String key. # # Yields if the key does not exist. The key is set to the return value of # the block. # Returns the Object value. def fetch(key) get(key) || begin value = yield set(key, value) value end end # Public: Transforms the given application key to the internal key that # the storage system uses. # # key - The String key. # # Returns the String internal key for the adapter. def key_for(key) key.to_s end end # Passes values through Horcrux untouched. module NullSerializer def self.dump(value) value end def self.load(str) str end end # Ensures that Horcrux values are turned to strings. module StringSerializer def self.dump(value) value.to_s end def self.load(str) str end end class Memory include Methods # Sample Horcrux adapter that stores unmodified values in a ruby Hash. # # client - Optional Hash. def initialize(client = {}, serializer = NullSerializer) @client = client @serializer = serializer end # Public: Uses Hash#key? to check the existence of a key. # # key - String key. # # Returns true if the key exists, or false. def key?(key) client.key? key_for(key) end # Public: Gets the value for the given key. # # key - The String key. # # Returns the Object value. def get(key) serializer.load client[key_for(key)] end # Public: Sets the value for the given key. # # key - The String key. # value - The Object value. # # Returns true if the operation succeeded, or false. def set(key, value) client[key_for(key)] = serializer.dump(value) true end # Public: Deletes the value for the given key. # # key - The String key. # # Returns true if a value was deleted, or false. def delete(key) !client.delete(key_for(key)).nil? end end end
package services.askde; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Duration; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import javax.inject.Inject; import javax.inject.Singleton; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.commons.lang3.StringUtils; import io.ebean.Ebean; import bindings.askde.listings.Listing; import bindings.askde.listings.Listings; import bindings.askde.listings.OpenHouses; import bindings.askde.listings.OpenHouse; import exceptions.askde.ListingsLoadException; import models.askde.Neighborhood; import models.askde.ZillowFeedHistory; import models.askde.ZipCode; import com.typesafe.config.Config; import play.Environment; import play.Logger; import play.inject.ApplicationLifecycle; import play.libs.ws.WSClient; import play.libs.ws.WSResponse; import raven.services.AWS; import raven.services.BaseService; @Singleton public class ListingsService extends BaseService { @Inject WSClient ws; @Inject public ListingsService (Environment env, Config conf, ApplicationLifecycle al) { super(env,conf,al); } public List<models.askde.OpenHouse> getOpenHouses() { List<models.askde.OpenHouse> openHouses = models.askde.OpenHouse.find.all(); return openHouses; } public models.askde.OpenHouse getRandomizedOpenHouseByNeighborhood(String neighborhood) { Logger.info("## Search request for random open house by neighborhood " + neighborhood); Date currentDateTime = new Date(); List<models.askde.OpenHouse> results = models.askde.OpenHouse.find.query().where().eq("neighborhood", neighborhood.toLowerCase()).and().gt("startDateTime", currentDateTime).order("startDateTime asc").findList(); Logger.info("Matches with same neighborhood " + neighborhood + " found: " + results.size()); if(results.size()>1) { Date nextOpenHouse = results.get(0).getStartDateTime(); List<models.askde.OpenHouse> openHousesAtSameTime = new ArrayList<models.askde.OpenHouse>(); for (models.askde.OpenHouse oh : results) { if(oh.getStartDateTime().equals(nextOpenHouse)) openHousesAtSameTime.add(oh); } Logger.info("Multiple open houses at the earliest time: " + openHousesAtSameTime.size() + " for neighborhood " + neighborhood); if(openHousesAtSameTime.size()>1) { int randomItem = ThreadLocalRandom.current().nextInt(0, openHousesAtSameTime.size()); return openHousesAtSameTime.get(randomItem); } } if(results.size()==1) { Logger.info("Only one open house in neighborhood " + neighborhood); return results.get(0); } if(results.size()>0) { Logger.info("Going to randomize from " + results.size() + " open houses in neighborhood " + neighborhood); return results.get(ThreadLocalRandom.current().nextInt(0, results.size())); } Logger.info("No open houses found for neighborhood " + neighborhood); return null; } public models.askde.OpenHouse getRandomizedOpenHouseByZipCode (Integer zipCode) { // Business rule // The current EST date/time is retrieved // The next available (earliest) open house's date/time after the current EST date/time is identified // If there are more than one open houses at the same earliest date/time, one is selected randomly // If there are no additional open houses at the same date/time, one is selected randomly from all open houses in that zip code Logger.info("## Search request for random open house by zip code " + zipCode); Date currentDateTime = new Date(); List<models.askde.OpenHouse> results = models.askde.OpenHouse.find.query().where().eq("zipCode", zipCode).and().gt("startDateTime", currentDateTime).order("startDateTime asc").findList(); Logger.info("Matches with same zip code " + zipCode + " found: " + results.size()); if(results.size()>1) { Date nextOpenHouse = results.get(0).getStartDateTime(); List<models.askde.OpenHouse> openHousesAtSameTime = new ArrayList<models.askde.OpenHouse>(); for (models.askde.OpenHouse oh : results) { if(oh.getStartDateTime().equals(nextOpenHouse)) openHousesAtSameTime.add(oh); } Logger.info("Multiple open houses at the earliest time: " + openHousesAtSameTime.size() + " for zip code " + zipCode); if(openHousesAtSameTime.size()>1) { int randomItem = ThreadLocalRandom.current().nextInt(0, openHousesAtSameTime.size()); return openHousesAtSameTime.get(randomItem); } } if(results.size()==1) { Logger.info("Only one open house in zip code " + zipCode); return results.get(0); } if(results.size()>0) { Logger.info("Going to randomize from " + results.size() + " open houses in zip code " + zipCode); return results.get(ThreadLocalRandom.current().nextInt(0, results.size())); } Logger.info("No open houses found for zip code " + zipCode); return null; } /* public models.askde.OpenHouse getRandomizedOpenHouseByNeighborhood(String neighborhood) { Date currentDateTime = new Date(); List<models.askde.OpenHouse> results = models.askde.OpenHouse.find.query().where().eq("neighborhood", neighborhood).and().gt("startDateTime", currentDateTime).order("startDateTime asc").findList(); if(results.size()>0) retu }*/ public void loadCanonicalNeighborhoods() { Logger.info("Loading neighborhoods from data/CanonicalNeighborhoods.csv"); BufferedReader br = null; String line = ""; try { br = new BufferedReader(new FileReader("data/CanonicalNeighborhoods.csv")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<Neighborhood> ns = new ArrayList<Neighborhood>(600); Neighborhood n = null; try { while ((line = br.readLine()) != null) { String[] arrayLine = line.split(","); n = new Neighborhood(); n.setName(expandNeighborhood(arrayLine[1]).toLowerCase().trim()); ns.add(n); } Ebean.saveAll(ns); } catch (IOException e) { e.printStackTrace(); } Logger.info("Canonical neighborhoods loaded: " + Neighborhood.find.query().findCount()); } public void loadZipCodes() { Logger.info("Loading zip codes from data/ZipCodeWhiteList.csv"); BufferedReader br = null; String line = ""; try { br = new BufferedReader(new FileReader("data/ZipCodeWhiteList.csv")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Integer zip = null; ZipCode zipCode = null; List<ZipCode> zs = new ArrayList<ZipCode>(400); try { while ((line = br.readLine()) != null) { String[] arrayLine = line.split(","); zip = Integer.valueOf(arrayLine[0]); zipCode = new ZipCode(); zipCode.setZipCode(zip); zs.add(zipCode); } Ebean.saveAll(zs); } catch (IOException e) { e.printStackTrace(); } Logger.info("Zip codes loaded: " + zs.size()); } private boolean checkListingIsClean(Listing l) { if(l.getLocation().getZip()!=null && !l.getLocation().getZip().isEmpty() && StringUtils.isNumeric(l.getLocation().getZip()) && l.getLocation().getStreetAddress()!=null && !l.getLocation().getStreetAddress().isEmpty() && l.getListingDetails().getMlsId()!=null && !l.getListingDetails().getMlsId().isEmpty()) return true; return false; } private boolean checkOpenHouseIsClean(OpenHouse o) { if(o.getDate()!=null && !o.getDate().isEmpty() && o.getStartTime()!=null && !o.getStartTime().isEmpty() && o.getEndTime()!=null && !o.getEndTime().isEmpty() && checkOpenHouseIsAtOddHours(o)) return true; return false; } private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private boolean checkOpenHouseIsInPastAlready(Date now, OpenHouse o) { try { Date startDateTime = formatter.parse(o.getDate() + " " + o.getStartTime()); if(startDateTime.before(now)) return true; // open house is in the past } catch (ParseException e) { return true; } return false; } private boolean checkIsRental(Listing l) { if(l.getListingDetails().getStatus().equalsIgnoreCase("for rent")) return true; return false; } private boolean checkOpenHouseIsAtOddHours(OpenHouse o) { try { Date morningBoundary = new SimpleDateFormat("HH:mm:ss").parse(conf.getString("askde.openHouseMorningBoundary")); Calendar calendarMorningBoundary = Calendar.getInstance(); calendarMorningBoundary.setTime(morningBoundary); Date nightBoundary = new SimpleDateFormat("HH:mm:ss").parse(conf.getString("askde.openHouseNightBoundary")); Calendar calendaryNightBoundary = Calendar.getInstance(); calendaryNightBoundary.setTime(nightBoundary); calendaryNightBoundary.add(Calendar.DATE, 1); Date current = new SimpleDateFormat("HH:mm").parse(o.getStartTime()); Calendar currentCalendar = Calendar.getInstance(); currentCalendar.setTime(current); Date x = currentCalendar.getTime(); if(x.after(calendarMorningBoundary.getTime()) && x.before(calendaryNightBoundary.getTime())) return true; else { Logger.info("Open house is at odd hour, discarded - From " + o.getStartTime() + " till " + o.getEndTime()); return false; } } catch (Exception e) { Logger.error("checkOpenHouseIsAtOddHours error",e); } return false; } private String expandNeighborhood(String neighborhood) { neighborhood = neighborhood.replace("n. ", "north "); neighborhood = neighborhood.replace("s. ", "south "); neighborhood = neighborhood.replace("e. ", "east "); neighborhood = neighborhood.replace("w. ", "west "); neighborhood = neighborhood.replace("st. ", "saint "); neighborhood = neighborhood.replace("mt. ", "mount "); neighborhood = neighborhood.replace("west village - meatpacking district", "west village"); neighborhood = neighborhood.replace("little italy - chinatown", "little italy"); neighborhood = neighborhood.replace("east hampton village fringe", "east hampton village"); neighborhood = neighborhood.replace("bedford - stuyvesant", "bed stuy"); neighborhood = neighborhood.replace("prospect-lefferts gardens", "prospect lefferts gardens"); neighborhood = neighborhood.replace("prospect-lefferts garden", "prospect lefferts gardens"); neighborhood = neighborhood.replace("hastings-on-hudson", "hastings on hudson"); neighborhood = neighborhood.replace("soho - nolita", "soho"); neighborhood = neighborhood.replace("garden city s.", "garden city"); neighborhood = neighborhood.replace("east elmhurst", "elmhurst"); neighborhood = neighborhood.replace("huntington sta", "huntington station"); neighborhood = neighborhood.replace("pt.jefferson sta", "port jefferson station"); neighborhood = neighborhood.replace("pt.jefferson vil", "port jefferson village"); neighborhood = neighborhood.replace("quiogue","quogue"); neighborhood = neighborhood.replace("quogue north","quogue"); neighborhood = neighborhood.replace("quogue south","quogue"); neighborhood = neighborhood.replace("rochaway beach", "rockaway beach"); neighborhood = neighborhood.replace("rochaway park", "rockaway park"); neighborhood = neighborhood.replace("sagaponack north", "sagaponack"); neighborhood = neighborhood.replace("sagaponack south", "sagaponack"); neighborhood = neighborhood.replace("shelter island h", "shelter island heights"); neighborhood = neighborhood.replace("richmond hill south", "richmond hill"); neighborhood = neighborhood.replace("richmond hill north", "richmond hill"); neighborhood = neighborhood.replace("queens village south", "queens village"); neighborhood = neighborhood.replace("queens village north", "queens village"); neighborhood = neighborhood.replace("amagansett north", "amagansett"); neighborhood = neighborhood.replace("amagansett south", "amagansett"); neighborhood = neighborhood.replace("amagansett dunes", "amagansett"); neighborhood = neighborhood.replace("bellerose terr ", "bellerose terrace"); neighborhood = neighborhood.replace("cold spring hrbr", "cold spring harbor"); neighborhood = neighborhood.replace("e atlantic beach", "east atlantic beach"); neighborhood = neighborhood.replace("east hampton northwest", "east hampton"); neighborhood = neighborhood.replace("east hampton south", "east hampton"); neighborhood = neighborhood.replace("east hampton nw", "east hampton"); neighborhood = neighborhood.replace("eh north", "east hampton"); neighborhood = neighborhood.replace("flatiron district", "flatiron"); neighborhood = neighborhood.replace("fresh meadow", "fresh meadows"); neighborhood = neighborhood.replace("great neck est", "great neck"); neighborhood = neighborhood.replace("great neck east", "great neck"); neighborhood = neighborhood.replace("bed stuy", "bedford stuyvesant"); neighborhood = neighborhood.replace("gramercy - union square", "gramercy"); neighborhood = neighborhood.replace("jamaica north", "jamaica"); neighborhood = neighborhood.replace("jamaica south", "jamaica"); neighborhood = neighborhood.replace("westhampton beach north", "west hampton beach"); neighborhood = neighborhood.replace("westhampton beach south", "west hampton beach"); neighborhood = neighborhood.replace("westhampton dunes", "west hampton"); neighborhood = neighborhood.replace("westhampton north", "west hampton"); neighborhood = neighborhood.replace("westhampton south", "west hampton"); return neighborhood; } private String transformPropertyType(String propertyType) { switch(propertyType.toLowerCase()) { case "unit": return ""; case "coop": return "co-op"; } return propertyType; } public void loadOpenHouses() throws ListingsLoadException { ZillowFeedHistory zfh = new ZillowFeedHistory(); zfh.setFeedLoadStart(new Date()); Ebean.save(zfh); List<ZipCode> zips = ZipCode.find.all(); Set<Integer> zipCodeWhiteList = new HashSet<Integer>(); for(ZipCode z : zips) zipCodeWhiteList.add(z.getZipCode()); JAXBContext ctx; Unmarshaller u; boolean isLoadFromURLSuccessful = false; Logger.info("Retrieving Zillow feed URL from config file"); String url = conf.getString("askde.listingsFeedURL"); if(url==null || url.isEmpty()) { zfh.setFailed(true); zfh.setFailureCause("Feed URL not in config file or is blank"); Ebean.update(zfh); throw new ListingsLoadException("Feed URL not in config file or is blank"); } Logger.info("Retrieving listings feed from Zillow at URL " + url); CompletionStage<WSResponse> resp = ws.url(url) .setRequestTimeout(Duration.ofMillis(60000)) .get(); CompletionStage<InputStream> feed = resp.thenApply(WSResponse::getBodyAsStream); try { ctx = JAXBContext.newInstance(Listings.class); } catch (JAXBException e) { zfh.setFailed(true); zfh.setFailureCause(e.getMessage()); Ebean.update(zfh); e.printStackTrace(); Logger.error("JAXBContext creation failed",e); throw new ListingsLoadException("JAXBContext creation failed. Message: " + e.getMessage()); } try { u = ctx.createUnmarshaller(); } catch (JAXBException e) { e.printStackTrace(); zfh.setFailed(true); zfh.setFailureCause(e.getMessage()); Ebean.update(zfh); Logger.error("JAXBContext unmarshaller creation failed",e); throw new ListingsLoadException("JAXBContext unmarshaller creation failed. Message: " + e.getMessage()); } Listings allListings = null; Set<String> neighborhoods = new HashSet<String>(20); try { allListings = (Listings) u.unmarshal(feed.toCompletableFuture().get()); isLoadFromURLSuccessful = true; } catch (JAXBException | InterruptedException | ExecutionException e) { e.printStackTrace(); zfh.setFailed(true); zfh.setFailureCause(e.getMessage()); Ebean.update(zfh); Logger.error("DE Zillow feed load from Zillow failed",e); Logger.info("Attempting to load from local file"); File f = new File("conf/DEZillowFeed.xml"); try { allListings = (Listings) u.unmarshal(f); Logger.info("Feed loaded from local file conf/DEZillowFeed.xml"); } catch (JAXBException e1) { e.printStackTrace(); zfh.setFailed(true); zfh.setFailureCause(e.getMessage()); Ebean.update(zfh); Logger.error("DE Zillow feed load from local file failed",e1); Logger.info("Attempting to load from S3"); try { allListings = (Listings) u.unmarshal(AWS.S3.get("askde", "DEZillowFeed.xml")); } catch (JAXBException e2) { e2.printStackTrace(); zfh.setFailed(true); zfh.setFailureCause(e.getMessage()); Ebean.update(zfh); Logger.error("Failed to load from S3",e1); Logger.info("Ask DE will operate in maintenance mode. Restart when connectivity / feeds are available"); throw new ListingsLoadException("All alternatives to loading feed have failed. Message: " + e.getMessage()); } } } Logger.info("Feed loaded into memory"); Marshaller m = null; File f = null; if(isLoadFromURLSuccessful) { Logger.info("Since feed is loaded from URL, we will persist it to local and S3"); Logger.info("Storing file to local for backup under data/ as filename DEZillowFeed.xml"); try { m = ctx.createMarshaller(); f = new File("data/DEZillowFeed.xml"); m.marshal(allListings, f); } catch (JAXBException e) { zfh.setFailed(true); zfh.setFailureCause("Failed to marshal feed to local file"); Ebean.update(zfh); Logger.error("Failed to marshal feed to local file",e); e.printStackTrace(); } Logger.info("Storing file to S3 for backup under data/ as filename DEZillowFeed.xml"); //Logger.info("Storing back to up S3"); //AWS.S3.upload("askde", "DEZillowFeed.xml", f, true); } Logger.info("Processing and flattening listings..."); int listingsCount = 1; int rentalsCount = 0; models.askde.OpenHouse oh = null; List<models.askde.OpenHouse> listOfOpenHouses = new ArrayList<models.askde.OpenHouse>(); Listings discardedListings = new Listings(); Listings listingsWithOpenHouses = new Listings(); String neighborhood = null; boolean isRental = false; for(Listing l : allListings.getListing()) { isRental = false; if(listingsCount++%1000==0) Logger.info("... " + listingsCount + " listings processed"); if(checkListingIsClean(l)) { // Check if it is clean before doing any work Integer zip = Integer.valueOf(l.getLocation().getZip().trim()); OpenHouses openHouses = l.getOpenHouses(); if(zipCodeWhiteList.contains(zip)) { neighborhood = expandNeighborhood(l.getNeighborhood().getName().toLowerCase()); neighborhoods.add(neighborhood); if(openHouses.getOpenHouse().size()>0) { // Match up with zip whitelist and make sure there are open houses in this listing if(checkIsRental(l)) { // toggle rental flag isRental = true; rentalsCount++; } Date now = new Date(); listingsWithOpenHouses.getListing().add(l); // need this to output a file String phoneNumber; for(OpenHouse o : openHouses.getOpenHouse()) { // need to check if oh is in the past if(!checkOpenHouseIsInPastAlready(now,o) && checkOpenHouseIsClean(o)) { // check open house has relevant pieces of data before processing oh = new models.askde.OpenHouse(); oh.setStartDateTime(o.getDate(),o.getStartTime()); oh.setAddress(l.getLocation().getStreetAddress()); oh.setUnitNumber(l.getLocation().getUnitNumber()); oh.setDate(o.getDate()); oh.setStatus(l.getListingDetails().getStatus()); oh.setStartTime(o.getStartTime()); oh.setEndDateTime(o.getDate(),o.getEndTime()); oh.setEndTime(o.getEndTime()); oh.setUnitNumber(l.getLocation().getUnitNumber()); oh.setListingID(l.getListingDetails().getMlsId()); oh.setZipCode(Integer.valueOf(l.getLocation().getZip())); oh.setNeighborhood(neighborhood); oh.setCity(l.getLocation().getCity()); oh.setState(l.getLocation().getState()); oh.setDescription(l.getBasicDetails().getDescription()); oh.setPrice(l.getListingDetails().getPrice()); oh.setStatus(l.getListingDetails().getStatus()); oh.setRental(isRental); oh.setBeds(l.getBasicDetails().getBedrooms()); oh.setBaths(l.getBasicDetails().getBathrooms()); oh.setPropertyType(transformPropertyType(l.getBasicDetails().getPropertyType())); oh.setAgentName(l.getAgent().getFirstName() + " " +l.getAgent().getLastName()); phoneNumber = l.getAgent().getMobileLineNumber(); if(phoneNumber==null || phoneNumber.isEmpty()) { phoneNumber = l.getAgent().getOfficeLineNumber(); if(phoneNumber==null || phoneNumber.isEmpty()) phoneNumber = "(212) 891-7000"; } oh.setAgentPhoneNumber(phoneNumber); oh.setAgentEmail(l.getAgent().getEmailAddress()); oh.setCurrent(true); listOfOpenHouses.add(oh); } else { Logger.info("Open house in past or missing or malformed date/time data, listing ID: " + l.getListingDetails().getMlsId()); } } } else discardedListings.getListing().add(l); } else discardedListings.getListing().add(l); } else discardedListings.getListing().add(l); } Logger.info("....done."); Logger.info("Preparing open houses for database"); // Separate process to make the db changes within the shortest window possible Logger.info("Preparation complete"); if(models.askde.OpenHouse.find.query().findCount()>0) { Logger.info("Purging old data and inserting new"); Date now = new Date(); List<models.askde.OpenHouse> delete = models.askde.OpenHouse.find.query().where().lt("createdAt", now).findList(); Logger.info("Will purge " + delete.size() + " rows and insert " + listOfOpenHouses.size() + " rows"); try { Logger.info("Starting transaction.."); Ebean.beginTransaction(); Ebean.saveAll(listOfOpenHouses); Ebean.deleteAll(delete); Ebean.commitTransaction(); Logger.info("Transaction committed"); } finally { Ebean.endTransaction(); } } else { Logger.info("Database empty, creating intial load"); Logger.info("Persisting.."); Ebean.saveAll(listOfOpenHouses); Logger.info("..open houses saved to DB"); } Logger.info("Number of US listings: " + allListings.getListing().size()); Logger.info("Number of NYC, Nassau, Suffolk & Westchester listings with open houses: " + listOfOpenHouses.size()); Logger.info("..Of which, # of rentals are: " + rentalsCount); Logger.info("Number of listings discarded: " + discardedListings.getListing().size()); Logger.info("Rows stored in Open House DB: " + models.askde.OpenHouse.find.query().findCount()); Logger.info("Storing discarded listings to data/DiscardedListings.xml"); try { m = ctx.createMarshaller(); f = new File("data/DiscardedListings.xml"); m.marshal(discardedListings, f); Logger.info("Discarded listings stored successfully to data/DiscardedListings.xml"); } catch (JAXBException e) { Logger.error("Failed to marshal feed to local file for discarded listings",e); } try { m = ctx.createMarshaller(); f = new File("data/ListingsWithOpenHouses.xml"); m.marshal(listingsWithOpenHouses, f); Logger.info("ListingsWithOpenHouses matching zip code whitelist stored successfully to data/ListingsWithOpenHouses.xml"); } catch (JAXBException e) { Logger.error("Failed to marshal feed to local file for ListingsWithOpenHouses ",e); } Logger.info("Persisting list of neighborhoods, needed for training Alexa"); f = new File ("data/Neighborhoods.csv"); PrintWriter pw; try { pw = new PrintWriter(f); for(String n : neighborhoods) pw.println(n); pw.flush(); pw.close(); } catch (FileNotFoundException e) { Logger.error("Failed to write neighborhoods",e); } zfh.setFailed(false); zfh.setFeedLoadComplete(new Date()); zfh.setTotalListings(allListings.getListing().size()); zfh.setRelevantListings(listOfOpenHouses.size()); zfh.setDiscardedListings(discardedListings.getListing().size()); zfh.setRelevantRentals(rentalsCount); zfh.setRelevantSales(listOfOpenHouses.size() - rentalsCount); zfh.setNeighborhoods(neighborhoods.size()); Ebean.update(zfh); Logger.info("Load completed"); // Signal to gc neighborhoods = null; listingsWithOpenHouses = null; listOfOpenHouses = null; allListings = null; discardedListings = null; } }
<reponame>TheDadi/polyfill-library 'use strict'; const sinon = require('sinon'); module.exports = { getPolyfillMeta: sinon.stub().resolves(), listPolyfills: sinon.stub().resolves(), getConfigAliases: sinon.stub().resolves(), streamPolyfillSource: sinon.stub(), };
/* * 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.jena.sparql.pfunction; import org.apache.jena.atlas.io.IndentedWriter ; import org.apache.jena.graph.Node ; import org.apache.jena.query.QueryBuildException ; import org.apache.jena.sparql.engine.ExecutionContext ; import org.apache.jena.sparql.engine.QueryIterator ; import org.apache.jena.sparql.engine.binding.Binding ; import org.apache.jena.sparql.engine.iterator.QueryIterRepeatApply ; import org.apache.jena.sparql.serializer.SerializationContext ; import org.apache.jena.sparql.util.FmtUtils ; import org.apache.jena.sparql.util.IterLib ; /** Basic property function handler that calls the implementation * subclass one binding at a time */ public abstract class PropertyFunctionBase implements PropertyFunction { PropFuncArgType subjArgType ; PropFuncArgType objFuncArgType ; protected PropertyFunctionBase() { this(PropFuncArgType.PF_ARG_EITHER, PropFuncArgType.PF_ARG_EITHER) ; } protected PropertyFunctionBase(PropFuncArgType subjArgType, PropFuncArgType objFuncArgType) { this.subjArgType = subjArgType ; this.objFuncArgType = objFuncArgType ; } @Override public void build(PropFuncArg argSubject, Node predicate, PropFuncArg argObject, ExecutionContext execCxt) { if ( subjArgType.equals(PropFuncArgType.PF_ARG_SINGLE) ) if ( argSubject.isList() ) throw new QueryBuildException("List arguments (subject) to "+predicate.getURI()) ; if ( subjArgType.equals(PropFuncArgType.PF_ARG_LIST) && ! argSubject.isList() ) throw new QueryBuildException("Single argument, list expected (subject) to "+predicate.getURI()) ; if ( objFuncArgType.equals(PropFuncArgType.PF_ARG_SINGLE) && argObject.isList() ) { if ( ! argObject.isNode() ) // But allow rdf:nil. throw new QueryBuildException("List arguments (object) to "+predicate.getURI()) ; } if ( objFuncArgType.equals(PropFuncArgType.PF_ARG_LIST) ) if ( ! argObject.isList() ) throw new QueryBuildException("Single argument, list expected (object) to "+predicate.getURI()) ; } @Override public QueryIterator exec(QueryIterator input, PropFuncArg argSubject, Node predicate, PropFuncArg argObject, ExecutionContext execCxt) { // This is the property function equivalent of Substitute. // To allow property functions to see the whole input stream, // the exec() operation allows the PF implementation to get at the // input iterator. Normally, we just want that applied one binding at a time. return new RepeatApplyIteratorPF(input, argSubject, predicate, argObject, execCxt) ; } public abstract QueryIterator exec(Binding binding, PropFuncArg argSubject, Node predicate, PropFuncArg argObject, ExecutionContext execCxt) ; class RepeatApplyIteratorPF extends QueryIterRepeatApply { private final PropFuncArg argSubject ; private final Node predicate ; private final PropFuncArg argObject ; public RepeatApplyIteratorPF(QueryIterator input, PropFuncArg argSubject, Node predicate, PropFuncArg argObject, ExecutionContext execCxt) { super(input, execCxt) ; this.argSubject = argSubject ; this.predicate = predicate ; this.argObject = argObject ; } @Override protected QueryIterator nextStage(Binding binding) { QueryIterator iter = exec(binding, argSubject, predicate, argObject, getExecContext()) ; if ( iter == null ) iter = IterLib.noResults(getExecContext()) ; return iter ; } @Override protected void details(IndentedWriter out, SerializationContext sCxt) { out.print("PropertyFunction ["+FmtUtils.stringForNode(predicate, sCxt)+"]") ; out.print("[") ; argSubject.output(out, sCxt) ; out.print("][") ; argObject.output(out, sCxt) ; out.print("]") ; out.println() ; } } }
<reponame>AlvaWang/spring-may<gh_stars>0 package net.bambooslips.demo.jpa.service; import net.bambooslips.demo.exception.CompetitionEntireNotFoundException; import net.bambooslips.demo.exception.UnitEssentialNotFoundException; import net.bambooslips.demo.jpa.model.CompetitionEntire; import net.bambooslips.demo.jpa.model.UnitEssential; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by Administrator on 2017/4/21. */ @Service public interface UnitEssentialService { Long create(UnitEssential unitEssential); @Transactional(rollbackFor = UnitEssentialNotFoundException.class) /** * 更新基本信息 */ UnitEssential update(UnitEssential update); UnitEssential delete(Long id); Long findByEntireId(Long entireId); UnitEssential findListByEntireId(Long entireId); // Page<UnitEssential> findByComName(String comName); }
llvm_dir="/home/kazooie/local/llvm/master/bin" #opt="${llvm_dir}/opt" opt=opt debug="" #file="pocl_2mm_kernel1.ll" file="pocl_noif_2mm_kernel1.ll" dot_file="._pocl_kernel_mm2_kernel1.dot" echo "POCL IR" ${opt} -dot-cfg ${file} > /dev/null 2>&1 dot -Tpdf ${dot_file} -o ${file}.pdf printf "\n\n\n\n" echo "VPlan IR with native path" ${opt} ${file} -o vplan_${file} -S ${debug} --loop-vectorize --pass-remarks=loop-vectorize --pass-remarks-missed=loop-vectorize --pass-remarks-analysis=loop-vectorize --enable-vplan-native-path ${opt} -dot-cfg vplan_${file} > /dev/null 2>&1 dot -Tpdf ${dot_file} -o vplan_${file}.pdf printf "\n\n\n\n" echo "VPlan IR with predication" ${opt} ${file} -o vplan_predicate_${file} -S ${debug} --loop-vectorize --pass-remarks=loop-vectorize --pass-remarks-missed=loop-vectorize --pass-remarks-analysis=loop-vectorize --enable-vplan-native-path --enable-vplan-predication ${opt} -dot-cfg vplan_predicate_${file} > /dev/null 2>&1 dot -Tpdf ${dot_file} -o vplan_predicate_${file}.pdf printf "\nResults:\n" if grep -q vectorized vplan_${file}; then echo "VPlan native path vectorized!" else echo "VPlan native path not vectorized!" fi if grep -q vectorized vplan_predicate_${file}; then echo "VPlan with predication vectorized!" else echo "VPlan with predication not vectorized!" fi
#!/bin/bash # Take a PR from Github, merge it into master/stable and push that into presubmit-master/stable # so that presubmit will merge it into master/stable if all the tests pass. PR_NUMBER=$1 ORIGINAL_BRANCH=$(git rev-parse --abbrev-ref HEAD) # Stash local changes first. if [ "$(git status -s --untracked-files=no)" ]; then git stash STASHED=true fi if [ $PR_NUMBER ]; then PR_BRANCH_CREATED=true PR_BRANCH="pr-$PR_NUMBER" git fetch upstream pull/$PR_NUMBER/head:$PR_BRANCH git checkout $PR_BRANCH else echo "No PR number provided, merging the current branch." PR_BRANCH=$ORIGINAL_BRANCH fi # Make sure we have all the latest bits. git fetch upstream master git fetch upstream canary # Determine whether merging to master/canary. COMMON_PARENT=$(git merge-base $PR_BRANCH upstream/canary) if git merge-base --is-ancestor $COMMON_PARENT upstream/master; then MERGE_INTO="master" else MERGE_INTO="canary" fi # Do not merge feat changes into master. if [ "$MERGE_INTO" = "master" ]; then DIFF_FEAT=$(git log $PR_BRANCH ^$MERGE_INTO --grep "^feat" --oneline) if [ "$DIFF_FEAT" ]; then echo "Can not merge features into master. Merging into canary instead." MERGE_INTO="canary" fi fi echo "Merging into $MERGE_INTO..." git log $PR_BRANCH ^upstream/$MERGE_INTO --no-merges --oneline MERGING_BRANCH="presubmit-$MERGE_INTO-$PR_BRANCH" git checkout -b $MERGING_BRANCH upstream/$MERGE_INTO git merge $PR_BRANCH git push upstream $MERGING_BRANCH # Revert the original state of the workspace. git checkout $ORIGINAL_BRANCH if [ "$STASHED" ]; then git stash pop fi git branch -D $MERGING_BRANCH if [ "$PR_BRANCH_CREATED" ]; then git branch -D $PR_BRANCH fi
HPARAMS_STR+="label_smoothing=0.,"
npm run-script build:prod
<filename>src/utils/api.js<gh_stars>1-10 export default function api() { if (process.env.NODE_ENV !== "production") { return 'http://localhost:3001'; } return 'http://localhost:3001'; }
<gh_stars>0 // 报警类型 export const getAlarmType = state => { return state.alarmType } // 菜单展开状态 export const getCollapsed = state => { return state.collapsed } // 获取 deviceTypes export const getDeviceTypes = state => { return state.deviceTypes } // 获取 deviceRunningStatus export const getDeviceRunningStatus = state => { return state.deviceRunningStatus } // 获取 AcquisitionParameterStatus export const getAcquisitionParameterStatus = state => { return state.acquisitionParameterStatus } // 获取 routes export const getRoutes = state => { // state.routes = JSON.parse(localStorage.getItem('routes')) || [] return state.routes } // 获取 routesConfig export const getRoutesConfig = state => { return state.routesConfig } // 获取 deviceTypeList export const getDeviceTypeList = state => { return state.deviceTypeList } // 获取 processStatusList export const getProcessStatusList = state => { return state.processStatusList } // 获取 perspectiveList export const getPerspectiveList = state => { return state.perspectiveList } // 获取 alarmColorList export const getAlarmColorList = state => { return state.alarmColorList } // 获取 alarmColorDict export const getAlarmColorDict = state => { return state.alarmColorDict } // 获取 alarmTypeList export const getAlarmTypeList = state => { return state.alarmTypeList } // 获取 menuModule export const getMenuModule = state => { return state.menuModule } // 获取 现场管理unitTypeId export const getSiteUnitTypeId = state => { return state.siteUnitTypeId }
<gh_stars>100-1000 package leetcode // 路径总和 func hasPathSum(root *TreeNode, targetSum int) bool { if root == nil { return false } if root.Left == nil && root.Right == nil { return targetSum == root.Val } return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val) } // 广度优先搜索 func hasPathSum2(root *TreeNode, targetSum int) bool { if root == nil { return false } queue := []*TreeNode{root} queueVal := []int{root.Val} for len(queue) > 0 { node, val := queue[0], queueVal[0] queue, queueVal = queue[1:], queueVal[1:] if node.Left == nil && node.Right == nil { if val == targetSum { return true } } if node.Left != nil { queue = append(queue, node.Left) queueVal = append(queueVal, node.Left.Val+val) } if node.Right != nil { queue = append(queue, node.Right) queueVal = append(queueVal, node.Right.Val+val) } } return false }
#!/bin/sh # Author KMS - Martin Dubois, ing. # Product KmsBase # File KmsLib/Clean.sh # Usage ./Clean.sh # CODE REVIEW 2019-07-19 KMS - Martin Dubois, ing. echo Executing KmsLib/Clean.sh ... # ===== Execution =========================================================== rm -f ../Libraries/KmsLib.a rm -f *.o # ===== End ================================================================= echo OK
#!/bin/bash rm -rf sensehat-demo.log ./sensehat-launcher.py &> sensehat-demo.log
<gh_stars>1-10 /** * NUI Message Example * SendNUIMessage({ * module = "weapon-state", * data = { * type = "", * name = "" * } * }) */ window.addEventListener("message", function (event) { if (event.data.module == "weapon-state") { const data = event.data.data switch (data.type) { case "updateWeaponState": $('#weapon-state-img').attr("src", `imgs/${data.name}.png`); break; case "setWeaponStateImgRight": $('.weapon-state').css("right", `${data.name}`); break; case "setWeaponStateImgBottom": $('.weapon-state').css("bottom", `${data.name}`); break; case "hideWeaponStateImg": $('.weapon-state').css("display", "none"); break; case "showWeaponStateImg": $('.weapon-state').css("display", "initial"); break; default: break; } } });
Pod::Spec.new do |s| s.name = "HPKeychain" s.version = "0.0.1" s.summary = "A lightweight but customisable networking stack written in Swift" s.homepage = "https://panhans.dev/opensource/hpkeychain" s.license = "MIT" s.author = { "<NAME>" => "<EMAIL>" } s.social_media_url = "https://twitter.com/henrik_dmg" s.ios.deployment_target = "12.0" s.osx.deployment_target = "10.11" s.watchos.deployment_target = "5.0" s.tvos.deployment_target = "12.0" s.source = { :git => "https://github.com/henrik-dmg/HPKeychain.git", :tag => s.version } s.source_files = "Sources/HPKeychain/**/*.swift" s.framework = "Foundation" s.swift_version = "5.1" end
SELECT hashtag, COUNT(*) AS count FROM myTable WHERE created_date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY hashtag ORDER BY COUNT(*) DESC LIMIT 10;
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mammb.code.jpostal.server; import com.mammb.code.jpostal.Postal; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Objects; import java.util.logging.Logger; /** * PostalServer. * * @author naotsugu */ public class PostalServer { private static final Logger log = Logger.getLogger(PostalServer.class.getName()); private final HttpServer server; private PostalServer(Postal postal, int port) { try { String contextRoot = "/postal"; this.server = HttpServer.create(new InetSocketAddress(port), 0); this.server.createContext(contextRoot, new PostalHandler(contextRoot, postal)); } catch (IOException e) { throw new RuntimeException(e); } } /** * Create the server instance. * @param postal the Postal * @return PostalServer */ public static PostalServer of(Postal postal) { return new PostalServer(postal, 8080); } /** * Create the server instance. * @param postal the Postal * @param port the port to listen on * @return PostalServer */ public static PostalServer of(Postal postal, int port) { return new PostalServer(postal, port); } /** * Starts this server. */ public void start() { server.start(); } /** * Stops this server. */ public void stop() { if (Objects.nonNull(server)) { server.stop(0); } } }
const deepEqual = require("fast-deep-equal"); const path = require("path"); const { EventEmitter } = require("events"); const errorStackRegExp = /^(?:[^\s]*\s*\bat\s+)(?:(.*)\s+\()?((?:\/|[a-zA-Z]:\\)[^:)]+:(\d+)(?::(\d+))?)/; module.exports = class Test extends EventEmitter { constructor(name, cb) { super(); this.name = name || "(anonymous)"; this.assertCount = 0; this.cb = cb; this.progeny = []; this.ok = true; } run() { if (!this.cb) { return this._end(); } this.timeoutAfter(); this.emit("prerun"); this.cb(this); this.emit("run"); } timeoutAfter() { const timeout = setTimeout(() => { this.fail(`test timed out after ${500}ms`); this.end(); }, 500); this.once("end", () => clearTimeout(timeout)); } end() { if (this.calledEnd) { this.fail(".end() called twice"); } this.calledEnd = true; this._end(); } _end() { if (this.progeny.length) { const test = this.progeny.shift(); test.on("end", () => this._end()); test.run(); return; } if (!this.ended) { this.emit("end"); } this.ended = true; } exit() { if (!this.ended) { this.fail("test exited without ending", { exiting: true, }); } } assert(ok, opts = {}) { const result = { id: this.assertCount++, ok: Boolean(ok), name: opts.message || "(unnamed assert)", }; if (opts.hasOwnProperty("actual")) { result.actual = opts.actual; } if (opts.hasOwnProperty("expected")) { result.expected = opts.expected; } this.ok = Boolean(this.ok && ok); if (!ok) { result.error = opts.error || new Error(result.name); const error = new Error("exception"); const errorStack = (error.stack || "").split("\n"); const dir = `${__dirname}${path.sep}`; for (let i = 0; i < errorStack.length; i += 1) { const [, callDescription = "<anonymous>", filePath, line, column] = errorStackRegExp.exec(errorStack[i]) || []; if (!filePath) { continue; } if (filePath.slice(0, dir.length) === dir) { continue; } // Function call description may not (just) be a function name. // Try to extract function name by looking at first "word" only. result.functionName = callDescription.split(/\s+/)[0]; result.file = filePath; result.line = Number(line); if (column) { result.column = Number(column); } result.at = `${callDescription} (${filePath})`; break; } } this.emit("result", result); setImmediate(() => this._end()); } fail(message) { this.assert(false, { message, }); } deepEqual(actual, expected, message = "should be equal") { // @todo: A feature for comparing an error against a string. Maybe useful, maybe not. if (actual instanceof Error && typeof expected === "string") { actual = actual.message; } this.assert(deepEqual(actual, expected), { message, actual, expected, }); } };
export * from './keyword-grid-modal.component'; export * from './add-keyword.modal.component'; export * from './publications.modal.component'; export * from './edit-profile-modal.component'; export * from './contact.modal.component';
<gh_stars>1-10 var ExtractText = require('extract-text-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: __dirname + '/build', publicPath: '/build/', filename: 'index.js', }, devtool: 'source-map', module: { loaders: [ {test: /\.js$/, exclude: /node_modules/, loader: 'babel'}, {test: /\.json$/, loader: 'json'}, { test: /\.s?css/, loader: ExtractText.extract([ 'css?sourceMap', 'autoprefixer', 'sass?sourceMap&sourceMapContents=true', ]) } ] }, plugins: [ new ExtractText('index.css'), ], };
<gh_stars>1000+ from .controller import DagsterDaemonController from .daemon import DagsterDaemon, SchedulerDaemon, get_default_daemon_logger from .run_coordinator.queued_run_coordinator_daemon import QueuedRunCoordinatorDaemon
#!/bin/bash ### # Script to run after pulling in changes to this repo; create directories and # symlinks in local filesystem that we expect to manage. ### _repo=$(pwd) source bash/post_pull_functions.sh create_symlinks () { echo -n "Creating directories and symlinks for $(basename $_repo) " echo "on behalf of $(whoami) on $(hostname)..." safe_mkdir $HOME/.vimswp/ safe_mkdir $HOME/bin/ safe_mkdir $HOME/bin/py3status/ safe_mkdir $HOME/remotefs/ # dot files link_to_git_repo $HOME/.ackrc $_repo/dotfiles/ackrc link_to_git_repo $HOME/.bashrc $_repo/dotfiles/bashrc link_to_git_repo $HOME/.bash_profile $_repo/dotfiles/bash_profile link_to_git_repo $HOME/.inputrc $_repo/dotfiles/inputrc link_to_git_repo $HOME/.profile $_repo/dotfiles/profile link_to_git_repo $HOME/.pylintrc $_repo/dotfiles/pylintrc link_to_git_repo $HOME/.screenrc $_repo/dotfiles/screenrc link_to_git_repo $HOME/.vimrc $_repo/dotfiles/vimrc link_to_git_repo $HOME/.Xresources $_repo/dotfiles/Xresources link_to_git_repo $HOME/.zshrc $_repo/dotfiles/zshrc # i3 link_to_git_repo $HOME/bin/i3-suspend $_repo/scripts/i3-suspend.sh # programs/scripts link_to_git_repo $HOME/bin/latex2png $_repo/latex/latex2png.sh link_to_git_repo $HOME/bin/convert_to_mp3 $_repo/scripts/convert_to_mp3.sh link_to_git_repo $HOME/bin/password_check $_repo/scripts/password_check.sh link_to_git_repo $HOME/bin/remotefs $_repo/scripts/remotefs.py link_to_git_repo $HOME/bin/random_words $_repo/scripts/random_words.py link_to_git_repo $HOME/bin/eapy $_repo/scripts/eapy/ } if [ ! $SUCCESS_COUNTER ] ; then SUCCESS_COUNTER=0 FAILURE_COUNTER=0 IGNORED_COUNTER=0 local_counters_only="yep" fi create_symlinks if [ $local_counters_only ] ; then echo " OK: $SUCCESS_COUNTER files" echo "FAIL: $FAILURE_COUNTER files" echo "IGNR: $IGNORED_COUNTER files" fi
seen = set() for item in array: if "apple" in item: if item not in seen: print(item) seen.add(item)
<filename>src/index.js // @flow export const Avatar = require('./avatar').default; export const AvatarToggle = require('./avatar-toggle').default; export const DiaItem = require('./dia-item').default; export const Countdown = require('./countdown').default; export const HeaderBar = require('./header-bar').default; export const ListItem = require('./list-item').default; export const LoginForm = require('./login/login-form').default; export const MonthLinePicker = require('./month-line-picker').default; export const Separator = require('./separator').default; export const Circle = require('./circle').default; export const ListViewFull = require('./list-view-full').default; export const ButtonSecond = require('./button-second').default; export const Form = require('./form').default; export const FormInput = require('./form-input').default; export const ConnectionMsg = require('./connection-msg').default; export const Timeline = require('./timeline').default; export const LineCircle = require('./line-circle').default; export const DatePicker = require('./date-picker').default; export const Constants = { HEADER_HEIGHT: require('./header-bar').HEADER_HEIGHT }; export default { Avatar, AvatarToggle, DiaItem, DatePicker, Countdown, HeaderBar, ListItem, LoginForm, MonthLinePicker, Separator, Circle, Constants, ListViewFull, ButtonSecond, Form, FormInput, ConnectionMsg, LineCircle, Timeline };
<filename>cpp/thread.cpp<gh_stars>1-10 #include "thread.h" #include "list.h" #include "pcb.h" #include "SCHEDULE.H" #include "lock.h" #include "timer.h" #include <iostream.h> #include "idle.h" #include "siglist.h" ID Thread::getId () { return myPCB->getId(); } ID Thread::getParentId() { return myPCB->parent->getId(); } ID Thread::getRunningId () { return PCB::running->getId(); } Thread * Thread::getThreadById(ID id) { PCB * pcb = PCB::PCBList->findById(id); return pcb->getThread(); } Thread::Thread(StackSize stackSize, Time timeSlice) { myPCB = new PCB(this, stackSize, timeSlice); } Thread::Thread(int i) { myPCB = new PCB(this); } void Thread::start() { if (myPCB->getState() == NEW) { myPCB->initStack(); myPCB->setState(READY); if (myPCB->getId() != PCB::idleId) Scheduler::put(myPCB); } } Thread::~Thread () { waitToComplete(); delete myPCB; myPCB = 0; } void Thread::waitToComplete() { if (myPCB->getState() != FINISHED && PCB::running != Idle::getIdlePCB() && PCB::running != this->myPCB) { Enable::disableContextSwitch(); PCB::running->setState(BLOCKED); myPCB->getWaitingList()->add(PCB::running); Enable::enableContextSwitch(); dispatch(); } } void dispatch() { Timer::contextSwitchRequested = 1; asm int 8h; } //**************************************************** //**************************************************** // Signal associated //**************************************************** //**************************************************** void Thread::signal(SignalId signal) { Enable::disableContextSwitch(); if (signal == 2 && myPCB->getState() == FINISHED && getHandler(signal) != 0) { getHandler(signal)(); Enable::enableContextSwitch(); return; } if (signal < SIGNALNUM && myPCB != PCB::running) { if (myPCB->getState() == PAUSED && myPCB->masked[signal] == UNMASKED && myPCB->maskedGlobally[signal] == UNMASKED) { myPCB->setState(READY); Scheduler::put(myPCB); } if (myPCB->masked[signal] != MASKED && myPCB->masked[signal] != MASKED) { myPCB->receivedSignals->add(signal); } } Enable::enableContextSwitch(); } void Thread::pause() { PCB::running->setState(PAUSED); dispatch(); } void Thread::registerHandler(SignalId signal, SignalHandler handler) { if (signal < SIGNALNUM) { myPCB->myHandlers[signal] = handler; } } SignalHandler Thread::getHandler(SignalId signal) { if (signal < SIGNALNUM) { return myPCB->myHandlers[signal]; } return 0; } // ************************************************ // Signal masking void Thread::maskSignal(SignalId signal) { if (signal < SIGNALNUM) { myPCB->masked[signal] = MASKED; } } void Thread::unmaskSignal(SignalId signal) { if (signal < SIGNALNUM) { myPCB->masked[signal] = UNMASKED; } } void Thread::maskSignalGlobally(SignalId signal) { if (signal < SIGNALNUM) { PCB::maskedGlobally[signal] = MASKED; } } void Thread::unmaskSignalGlobally(SignalId signal) { if (signal < SIGNALNUM) { PCB::maskedGlobally[signal] = UNMASKED; } } //************************************************** //Signal blocking void Thread::blockSignal(SignalId signal) { if (signal < SIGNALNUM) { myPCB->blocked[signal] = BLOCKD; } } void Thread::unblockSignal(SignalId signal) { if (signal < SIGNALNUM) { myPCB->blocked[signal] = UNBLOCKED; } } void Thread::blockSignalGlobally(SignalId signal) { if (signal < SIGNALNUM) { PCB::blockedGlobally[signal] = BLOCKD; } } void Thread::unblockSignalGlobally(SignalId signal) { if (signal < SIGNALNUM) { PCB::blockedGlobally[signal] = UNBLOCKED; } } //***************************************************
module Fog module Compute class OracleCloud class Real def create_ip_network (params) if !params[:name].nil? && !params[:name].start_with?("/Compute-") then # They haven't provided a well formed name, add their name in params[:name] = "/Compute-#{@identity_domain}/#{@username}/#{params[:name]}" end params = params.reject {|key, value| value.nil?} request( :method => 'POST', :expects => 201, :path => "/network/v1/ipnetwork/", :body => Fog::JSON.encode(params), :headers => { 'Content-Type' => 'application/oracle-compute-v3+json' } ) end end class Mock def create_ip_network (params) response = Excon::Response.new name = params[:name] name.sub! "/Compute-#{@identity_domain}/#{@username}/", '' self.data[:ip_networks][name] = { 'name' => "/Compute-#{@identity_domain}/#{@username}/#{name}", 'uri' => "#{@api_endpoint}network/v1/ipnetwork/Compute-#{@identity_domain}/#{@username}/#{name}", 'description' => nil, 'tags' => nil, 'ipAddressPrefix' => params[:ipAddressPrefix], 'ipNetworkExchange' => params[:ipNetworkExchange], 'publicNaptEnabledFlag' => false } response.status = 201 response.body = self.data[:ip_networks][name] response end end end end end
#!/bin/sh #SOCKET_ERROR is defined as -1 on windows platform here is no need sed -i 's/^#define SOCKET_ERROR 4/\/\/#define SOCKET_ERROR 4/' skynet-src/socket_server.h #mingw 5.3 some header files are changed sed -i 's/^#include \"sys\/socket.h\"/#include <sys\/socket.h> \r#include <time.h>/' platform/platform.h #mingw 5.3 _WIN32_WINNT default defined as _WIN32_WINNT_WIN2K(0x0500) for Windows 2000 sed -i 's/^#ifndef _WIN32_WINNT/#ifdef _WIN32_WINNT\r#undef _WIN32_WINNT/' platform/sys/socket.h #for strsep strsep inet_ntop clock_gettime warning on complie time sed -i 's/^CFLAGS := -g -O2 -Wall -I$(PLATFORM_INC) -I$(LUA_INC) $(MYCFLAGS)/CFLAGS := -g -O2 -includeplatform.h -Wall -I$(PLATFORM_INC) -I$(LUA_INC) $(MYCFLAGS)/' Makefile #using nanosleep replace usleep whick was marked deprecated in mingw5.3 sed -i 's/\tusleep/ nusleep/g' skynet-src/skynet_start.c lualib-src/lua-socket.c lualib-src/lua-debugchannel.c lualib-src/lua-clientsocket.c
<filename>src/main/java/com/alibaba/dubbo/spring/boot/listener/ConsumerSubscribeListener.java package com.alibaba.dubbo.spring.boot.listener; import java.util.Set; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.utils.ConcurrentHashSet; import com.alibaba.dubbo.rpc.Invoker; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.listener.InvokerListenerAdapter; import com.alibaba.dubbo.spring.boot.bean.ClassIdBean; import com.alibaba.dubbo.spring.boot.bean.DubboSpringBootStarterConstants; /** * Dubbo client invoker listener * * @author xionghui * @version 1.0.0 * @since 1.0.0 */ @Activate public class ConsumerSubscribeListener extends InvokerListenerAdapter { /** * subscribe interfaces */ public static final Set<ClassIdBean> SUBSCRIBEDINTERFACES_SET = new ConcurrentHashSet<ClassIdBean>(); @Override public void referred(Invoker<?> invoker) throws RpcException { Class<?> interfaceClass = invoker.getInterface(); URL url = invoker.getUrl(); String group = url.getParameter(DubboSpringBootStarterConstants.GROUP); String version = url.getParameter(DubboSpringBootStarterConstants.VERSION); ClassIdBean classIdBean = new ClassIdBean(interfaceClass, group, version); SUBSCRIBEDINTERFACES_SET.add(classIdBean); } @Override public void destroyed(Invoker<?> invoker) { Class<?> interfaceClass = invoker.getInterface(); URL url = invoker.getUrl(); String group = url.getParameter(DubboSpringBootStarterConstants.GROUP); String version = url.getParameter(DubboSpringBootStarterConstants.VERSION); ClassIdBean classIdBean = new ClassIdBean(interfaceClass, group, version); SUBSCRIBEDINTERFACES_SET.remove(classIdBean); } }
<reponame>pjunior/titanium<filename>apps/apivalidator/Resources/tests/testinclude.js // just a simple js to make sure the script is evaluated window.TESTVAL = 100;
import {createStyles, Theme, WithStyles, withStyles} from '@material-ui/core'; import React, {ReactNode} from 'react'; import {assertElement, cssClasses} from '@age-online/lib-core'; import {elementTouched, TouchEventHandler} from './touch-event-handler'; import {IButtonsDown, noButtonsDown} from './buttons-down'; import {TidyComponent} from '@age-online/lib-react'; const CSS_CLASS_PRESSED = 'pressed'; const CSS_RADIUS_DIRECTIONS = '20%'; const styles = (theme: Theme) => createStyles({ container: { // No browser gesture handling for this element, // we handle touch events all by ourselves. // See also: // https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action // https://developers.google.com/web/updates/2017/01/scrolling-intervention touchAction: 'none', // no selectable text userSelect: 'none', }, cross: { height: theme.spacing(3 * 5), width: theme.spacing(3 * 5), color: theme.palette.primary.main, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gridTemplateRows: '1fr 1fr 1fr', gridTemplateAreas: '"up-left up up-right" "left unused right" "down-left down down-right"', [`& .${CSS_CLASS_PRESSED}`]: { color: theme.palette.primary.contrastText, backgroundColor: theme.palette.primary.main, }, }, upLeft: { gridArea: 'up-left', borderTop: '1px dotted', borderLeft: '1px dotted', borderTopLeftRadius: '100%', }, up: { gridArea: 'up', border: '3px solid', borderBottom: '1px dotted', borderTopLeftRadius: CSS_RADIUS_DIRECTIONS, borderTopRightRadius: CSS_RADIUS_DIRECTIONS, }, upRight: { gridArea: 'up-right', borderTop: '1px dotted', borderRight: '1px dotted', borderTopRightRadius: '100%', }, left: { gridArea: 'left', border: '3px solid', borderRight: '1px dotted', borderTopLeftRadius: CSS_RADIUS_DIRECTIONS, borderBottomLeftRadius: CSS_RADIUS_DIRECTIONS, }, right: { gridArea: 'right', border: '3px solid', borderLeft: '1px dotted', borderTopRightRadius: CSS_RADIUS_DIRECTIONS, borderBottomRightRadius: CSS_RADIUS_DIRECTIONS, }, downLeft: { gridArea: 'down-left', borderBottom: '1px dotted', borderLeft: '1px dotted', borderBottomLeftRadius: '100%', }, down: { gridArea: 'down', border: '3px solid', borderTop: '1px dotted', borderBottomLeftRadius: CSS_RADIUS_DIRECTIONS, borderBottomRightRadius: CSS_RADIUS_DIRECTIONS, }, downRight: { gridArea: 'down-right', borderBottom: '1px dotted', borderRight: '1px dotted', borderBottomRightRadius: '100%', }, }); export interface ICrossControlsProps { readonly className?: string; readonly crossDown?: (button: keyof IButtonsDown) => void; readonly crossUp?: (button: keyof IButtonsDown) => void; readonly pressingRight?: boolean; readonly pressingDown?: boolean; readonly pressingLeft?: boolean; readonly pressingUp?: boolean; } type TCrossControlsProps = ICrossControlsProps & WithStyles; class ComposedCrossControls extends TidyComponent<TCrossControlsProps> { private elemContainer?: HTMLElement | null; private elemUpLeft?: HTMLElement | null; private elemUp?: HTMLElement | null; private elemUpRight?: HTMLElement | null; private elemLeft?: HTMLElement | null; private elemRight?: HTMLElement | null; private elemDownLeft?: HTMLElement | null; private elemDown?: HTMLElement | null; private elemDownRight?: HTMLElement | null; private readonly buttonsDown = noButtonsDown(); componentDidMount() { const eventHandler = new TouchEventHandler( assertElement(this.elemContainer), points => { const { elemUpLeft, elemUp, elemUpRight, elemLeft, elemRight, elemDownLeft, elemDown, elemDownRight, buttonsDown, props: {crossDown, crossUp}, } = this; const ul = elementTouched(assertElement(elemUpLeft), points); const ur = elementTouched(assertElement(elemUpRight), points); const dl = elementTouched(assertElement(elemDownLeft), points); const dr = elementTouched(assertElement(elemDownRight), points); const r = ur || dr || elementTouched(assertElement(elemRight), points); const d = dl || dr || elementTouched(assertElement(elemDown), points); const l = ul || dl || elementTouched(assertElement(elemLeft), points); const u = ul || ur || elementTouched(assertElement(elemUp), points); checkButton('gbRight', r); checkButton('gbDown', d); checkButton('gbLeft', l); checkButton('gbUp', u); function checkButton(button: keyof IButtonsDown, buttonState: boolean): void { if (buttonState !== buttonsDown[button]) { buttonsDown[button] = buttonState; (buttonState ? crossDown : crossUp)?.(button); } } }, ); this.callOnUnmount(() => eventHandler.removeListeners()); } render(): ReactNode { const {props: {classes, className, pressingRight, pressingDown, pressingLeft, pressingUp}} = this; return ( <div className={cssClasses(classes.container, className)} ref={elem => void (this.elemContainer = elem)}> <div className={classes.cross}> <div className={cssClasses(classes.upLeft, pressedCss(pressingLeft && pressingUp))} ref={elem => void (this.elemUpLeft = elem)}>&#8203;</div> <div className={cssClasses(classes.up, pressedCss(pressingUp))} ref={elem => void (this.elemUp = elem)}>&#8203;</div> <div className={cssClasses(classes.upRight, pressedCss(pressingRight && pressingUp))} ref={elem => void (this.elemUpRight = elem)}>&#8203;</div> <div className={cssClasses(classes.left, pressedCss(pressingLeft))} ref={elem => void (this.elemLeft = elem)}>&#8203;</div> <div className={cssClasses(classes.right, pressedCss(pressingRight))} ref={elem => void (this.elemRight = elem)}>&#8203;</div> <div className={cssClasses(classes.downLeft, pressedCss(pressingLeft && pressingDown))} ref={elem => void (this.elemDownLeft = elem)}>&#8203;</div> <div className={cssClasses(classes.down, pressedCss(pressingDown))} ref={elem => void (this.elemDown = elem)}>&#8203;</div> <div className={cssClasses(classes.downRight, pressedCss(pressingRight && pressingDown))} ref={elem => void (this.elemDownRight = elem)}>&#8203;</div> </div> </div> ); function pressedCss(flag: unknown): string { return flag ? CSS_CLASS_PRESSED : ''; } } } export const CrossControls = withStyles(styles)( ComposedCrossControls, );
#!/usr/bin/env bash envr=github.com user=eddo888 pass=$(passwords.py -e $envr -a git -u $user) ppwd=$(basename $(dirname $(pwd))) ownr=$(basename $(pwd)) echo $ppwd/$ownr >&2 if [ "$ppwd" != "github.com" ] then ownr=$user fi gitrepos.py -u $user -p $pass -o $ownr $*
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata # Given data X_vector = [...] # Latitude coordinates Y_vector = [...] # Longitude coordinates Z_vector = [...] # Data values num = ... # Number of points for the contour plot kwargs = {...} # Optional parameters # Create grid for contour plot xi = np.linspace(min(X_vector), max(X_vector), num) yi = np.linspace(min(Y_vector), max(Y_vector), num) zi = griddata(X_vector, Y_vector, Z_vector, xi, yi) # Do contour plot with optional features if 'contour' in kwargs: plt.contour(xi, yi, zi, linewidths=0.5, colors='k') if 'map_name' in kwargs: # Add code to display the map based on the provided 'map_name' using appropriate library or API # Example: Using Basemap for map visualization # from mpl_toolkits.basemap import Basemap # m = Basemap(projection='ortho', lat_0=45, lon_0=-100) # m.drawcoastlines() # plt.show() # Display the contour plot plt.show()
<reponame>OSWeDev/oswedev import { Component, Prop } from 'vue-property-decorator'; import ModuleDAO from '../../../../../../../../../shared/modules/DAO/ModuleDAO'; import ModuleVar from '../../../../../../../../../shared/modules/Var/ModuleVar'; import VarDataBaseVO from '../../../../../../../../../shared/modules/Var/vos/VarDataBaseVO'; import VueComponentBase from '../../../../../../VueComponentBase'; import './VarDescExplainDepParamComponent.scss'; @Component({ template: require('./VarDescExplainDepParamComponent.pug'), components: { Vardescparamfieldscomponent: () => import(/* webpackChunkName: "VarDescParamFieldsComponent" */ '../../../param_fields/VarDescParamFieldsComponent') } }) export default class VarDescExplainDepParamComponent extends VueComponentBase { @Prop() private param: VarDataBaseVO; private async update_var_data() { if (this.param.value_type == VarDataBaseVO.VALUE_TYPE_IMPORT) { this.snotify.error(this.label('var.desc_mode.update_var_data.not_allowed_on_imports')); return; } await ModuleVar.getInstance().invalidate_cache_exact([this.param]); this.snotify.info(this.label('var.desc_mode.update_var_data')); } }
#!/usr/bin/env bats DOCKER_COMPOSE_FILE="${BATS_TEST_DIRNAME}/php-5.2_ini_igbinary_on.yml" container() { echo "$(docker-compose -f ${DOCKER_COMPOSE_FILE} ps php | grep php | awk '{ print $1 }')" } setup() { docker-compose -f "${DOCKER_COMPOSE_FILE}" up -d sleep 20 } teardown() { docker-compose -f "${DOCKER_COMPOSE_FILE}" kill docker-compose -f "${DOCKER_COMPOSE_FILE}" rm --force } @test "php-5.2: ini: igbinary: on" { run docker exec "$(container)" /bin/su - root -mc "php -m | grep 'igbinary'" [ "${status}" -eq 0 ] }
<reponame>ujjwalguptaofficial/infinity export declare const removeFirstSlace: (value: string) => string;
#!/bin/sh set -e ROOTDIR=dist BUNDLE=${ROOTDIR}/CLH-Qt.app CODESIGN=codesign TEMPDIR=sign.temp TEMPLIST=${TEMPDIR}/signatures.txt OUT=signature.tar.gz if [ ! -n "$1" ]; then echo "usage: $0 <codesign args>" echo "example: $0 -s MyIdentity" exit 1 fi rm -rf ${TEMPDIR} ${TEMPLIST} mkdir -p ${TEMPDIR} ${CODESIGN} -f --file-list ${TEMPLIST} "$@" "${BUNDLE}" for i in `grep -v CodeResources ${TEMPLIST}`; do TARGETFILE="${BUNDLE}/`echo ${i} | sed "s|.*${BUNDLE}/||"`" SIZE=`pagestuff $i -p | tail -2 | grep size | sed 's/[^0-9]*//g'` OFFSET=`pagestuff $i -p | tail -2 | grep offset | sed 's/[^0-9]*//g'` SIGNFILE="${TEMPDIR}/${TARGETFILE}.sign" DIRNAME="`dirname ${SIGNFILE}`" mkdir -p "${DIRNAME}" echo "Adding detached signature for: ${TARGETFILE}. Size: ${SIZE}. Offset: ${OFFSET}" dd if=$i of=${SIGNFILE} bs=1 skip=${OFFSET} count=${SIZE} 2>/dev/null done for i in `grep CodeResources ${TEMPLIST}`; do TARGETFILE="${BUNDLE}/`echo ${i} | sed "s|.*${BUNDLE}/||"`" RESOURCE="${TEMPDIR}/${TARGETFILE}" DIRNAME="`dirname "${RESOURCE}"`" mkdir -p "${DIRNAME}" echo "Adding resource for: "${TARGETFILE}"" cp "${i}" "${RESOURCE}" done rm ${TEMPLIST} tar -C ${TEMPDIR} -czf ${OUT} . rm -rf ${TEMPDIR} echo "Created ${OUT}"
#! /usr/bin/env bash A=($(< "${1:-3.txt}")); l=${#A[0]}; k=0; j=3; total=1; x="" for i in "${A[@]}"; do x+=${i:k:1}; ((k=(k+j)%l)); done; x=${x//\.} echo "3A: ${#x}" idx2=$(seq 0 2 $((${#A[@]}-1))) for j in 1 3 5 7; do x=""; k=0; for i in "${A[@]}"; do x+=${i:k:1}; ((k=(k+j)%l)); done; x=${x//\.}; total+="*${#x}"; done x=""; k=0; for i in $idx2; do x+=${A[i]:k:1}; ((k=(k+2)%l)); done ; x=${x//\.}; total+="*${#x}" echo "3B: ${total:2} = $((total))"
add_lunch_combo cm_d2att-eng
import {range} from "../src/Sequence"; describe("range", () => { it("should create range of numbers with step = 1", () => { const numbers = range(0, 5).toArray(); expect(numbers).toEqual([0, 1, 2, 3, 4, 5]); }); it("should create range of numbers with step = .5", () => { const numbers = range(0, 4, .5).toArray(); expect(numbers).toEqual([0, .5, 1, 1.5, 2, 2.5, 3, 3.5, 4.0]); }); it("should include one element", () => { const numbers = range(0, 0).toArray(); expect(numbers).toEqual([0]); }); it("should include two element", () => { const numbers = range(0, 1).toArray(); expect(numbers).toEqual([0, 1]); }); it("should throw on invalid boundaries", () => { expect(() => range(1, 0)).toThrow(); }); });
package io.rapidpro.surveyor.ui; import android.app.ProgressDialog; import android.content.Context; /** * A blocking progress dialog */ public class BlockingProgress extends ProgressDialog { public BlockingProgress(Context context, int title, int message, int total) { super(context); setTitle(title); setMessage(getContext().getString(message)); setIndeterminate(false); setMax(total); setCancelable(false); setCanceledOnTouchOutside(false); setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); setProgress(0); } @Override public void incrementProgressBy(int diff) { super.incrementProgressBy(diff); // check if we are ready to dismiss if (getProgress() == getMax()) { dismiss(); } } }
<gh_stars>0 import React from "react"; import Drawer from "@material-ui/core/Drawer"; import List from "@material-ui/core/List"; import ListItem from "@material-ui/core/ListItem"; import { scroller } from "react-scroll"; const MyDrawer = props => { const scrollToComponent = component => { scroller.scrollTo(component, { duration: 1000, delay: 100, smooth: true, offset: -150 }); props.onClose(false); }; return ( <Drawer anchor="top" open={props.open} onClose={() => props.onClose(false)}> <List component="nav" className="list"> <ListItem className="list_item" button onClick={() => scrollToComponent("Featured")} > Countdown </ListItem> <ListItem className="list_item" button onClick={() => scrollToComponent("Info")} > Venue Info </ListItem> <ListItem className="list_item" button onClick={() => scrollToComponent("Highlights")} > Deals </ListItem> <ListItem className="list_item" button onClick={() => scrollToComponent("PriceCard")} > Pricing </ListItem> <ListItem classname="list_item" button onClick={() => scrollToComponent("Map")} > Directions </ListItem> </List> </Drawer> ); }; export default MyDrawer;
GIT=https://gitlab.redox-os.org/redox-os/orbutils.git BINDIR=/ui/bin DEPENDS="orbital"
<filename>src/mol-gl/shader/chunks/apply-marker-color.glsl.ts<gh_stars>0 export const apply_marker_color = ` float marker = floor(vMarker * 255.0 + 0.5); // rounding required to work on some cards on win if (marker > 0.1) { if (intMod(marker, 2.0) > 0.1) { gl_FragColor.rgb = mix(uHighlightColor, gl_FragColor.rgb, 0.3); gl_FragColor.a = max(0.02, gl_FragColor.a); // for direct-volume rendering } else { gl_FragColor.rgb = mix(uSelectColor, gl_FragColor.rgb, 0.3); } } `;
text = "I saw 9 dogs, 7 cats, 5 goats, 10 sheep and 6 cows." numbers = re.findall(r'\d+', text) total = sum([int(x) for x in numbers]) print(total) # 37
from .api import BuienradarApi, AsyncBuienradarApi class WeatherClient: def fetch_weather_sync(self, location: str) -> dict: try: api = BuienradarApi() return api.fetch_weather(location) except Exception as e: print(f"Error fetching weather data synchronously: {e}") return {} async def fetch_weather_async(self, location: str) -> dict: try: api = AsyncBuienradarApi() return await api.fetch_weather(location) except Exception as e: print(f"Error fetching weather data asynchronously: {e}") return {}
package vip import ( "net" "github.com/pkg/errors" ) // LookupHost resolves dnsName and return an IP or an error func lookupHost(dnsName string) (string, error) { addrs, err := net.LookupHost(dnsName) if err != nil { return "", err } if len(addrs) == 0 { return "", errors.Errorf("empty address for %s", dnsName) } return addrs[0], nil } // IsIP returns if address is an IP or not func IsIP(address string) bool { ip := net.ParseIP(address) return ip != nil }
<reponame>el-dorado/bilibili-trend export * from './helper' export * from './factory' export * from './extends/PGraphics'
package cache import ( "fmt" "strconv" "sync" "testing" "time" ) const ( lru_loops = 10 ) func forkLRUCacheForTest(size int) Cache { return New(size).LRU().EvictedFunc(func(key, value interface{}) { fmt.Printf("key:%v value:%v evicted.\n", key, value) }).Expiration(1 * time.Second).Build() } func TestLRUGetMany(t *testing.T) { wg := sync.WaitGroup{} c := forkLRUCacheForTest(lru_loops) for i := 0; i < lru_loops; i++ { wg.Add(1) c.Set(strconv.Itoa(i), i) } go func() { time.Sleep(200 * time.Millisecond) for i := 0; i < lru_loops; i++ { defer wg.Add(-1) obj, err := c.Get(strconv.Itoa(i)) if err != nil { t.Errorf("fail to get value:%v", i) } else if i != obj.(int) { t.Errorf("index: %v not correct", i) t.FailNow() } time.Sleep(50 * time.Millisecond) } }() wg.Wait() } func TestLRUGetExpire(t *testing.T) { c := forkLRUCacheForTest(10) c.SetWithExpire("k1", "v1", time.Second) time.Sleep(500 * time.Millisecond) if v, err := c.Get("k1"); err != nil { t.Error("fail to get k1.", err) t.FailNow() } else if "v1" != v.(string) { t.Error("value mismatch.", err) t.FailNow() } time.Sleep(500 * time.Millisecond) if _, err := c.Get("k1"); err == nil { t.Error("k1 should be expired but not.") t.FailNow() } } func TestLRUNormal(t *testing.T) { c := forkLRUCacheForTest(3) c.Set("k1", "v1") c.Set("k2", "v2") c.Set("k3", "v3") c.Get("k1") c.Get("k1") c.Get("k1") c.Get("k2") c.Get("k2") c.Get("k3") c.Set("k4", "v4") if _, err := c.Get("k1"); err == nil { t.Error("k1 should be evicted") t.FailNow() } t.Log(fmt.Sprintf("hit:%v miss:%v lookup:%v rate:%v", c.HitCount(), c.MissCount(), c.LookupCount(), c.HitRate())) }
import mongoose from "mongoose"; import { onError } from "../utils/response"; const validateObjectId = (req, res, next) => { if (!mongoose.Types.ObjectId.isValid(req.params.id)) { return onError(res, 404, "Not Found"); } next(); }; export default validateObjectId;
<filename>src/main/java/cn/wwl/radio/executor/functions/FakeCaseOpenFunction.java package cn.wwl.radio.executor.functions; import cn.wwl.radio.executor.ConsoleFunction; import cn.wwl.radio.network.SocketTransfer; import cn.wwl.radio.utils.FakeCaseManager; import java.util.List; public class FakeCaseOpenFunction implements ConsoleFunction { @Override public boolean isRequireTicking() { return false; } @Override public boolean isRequireParameter() { return false; } @Override public void onExecuteFunction(List<String> parameter) { FakeCaseManager.CSGOCaseDrop fakeCase = FakeCaseManager.openFakeCase(FakeCaseManager.CSGOCases.OPERATION_RIPTIDE_CASE); CustomRadioFunction.sendCustomRadio(SocketTransfer.getInstance().getPlayerName() + " #white#从武器箱中获得了: " + fakeCase.getColorSkinName(),true); } }
const fs=require('fs') fs.writeFileSync('Append.txt','I am learning Node.js') fs.appendFileSync('Append.txt',' \nThis is my first program in Node.js')
<reponame>thegoldenmule/boX<gh_stars>1-10 /** * Author: thegoldenmule * Date: 8/9/13 */ (function (global) { "use strict"; var AnimationCurveEditor = function () { var scope = this; scope.canvas = null; scope.context = null; // set up a default scope._animationCurve = new AnimationCurve(); scope._animationCurve.addKey(new AnimationCurveKey(0, 0)); scope._animationCurve.addKey(new AnimationCurveKey(1, 1)); return scope; }; AnimationCurveEditor.prototype = { constructor: AnimationCurveEditor, initialize: function(canvas) { this.canvas = canvas; this.context = this.canvas.getContext("2d"); //this.redraw(); }, edit: function(curve) { this._animationCurve = curve; this.redraw(); }, redraw: function() { if (!this._animationCurve || this._animationCurve.getKeys().length < 2 || !this.context || !this.canvas) { return; } // fill this.context.fillStyle = "#CCCCCC"; this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); this.context.fill(); // draw grid this.context.beginPath(); var gridRes = 4; for (var x = 0, xlen = this.canvas.width / gridRes; x < xlen; x++) { this.context.moveTo(x * xlen, 0); this.context.lineTo(x * xlen, this.canvas.height); for (var y = 0, ylen = this.canvas.height / gridRes; y < ylen; y++) { this.context.moveTo(0, y * ylen); this.context.lineTo(this.canvas.width, y * ylen); } } this.context.lineWidth = 1; this.context.strokeStyle = "#999999"; this.context.stroke(); this.context.closePath(); // use resolution this.context.beginPath(); this.context.moveTo(0, this.canvas.height - this._animationCurve.evaluate(0) * this.canvas.height); var keys = this._animationCurve.getKeys(); for (var i = 0, len = keys.length; i < len - 1; i++) { drawSegment(this.canvas, this.context, this._animationCurve, keys[i], keys[i + 1]); } this.context.lineWidth = 1; this.context.lineCap = "round"; this.context.lineJoin = "round"; this.context.strokeStyle = "#DD0000"; this.context.stroke(); this.context.closePath(); } }; function drawSegment(canvas, context, curve, a, b) { var totalDeltaTime = b.time - a.time; var pieces = 16; for (var i = 0; i < 1; i += 1 / pieces) { var startT = a.time + i * totalDeltaTime; var endT = a.time + (i + 1 / pieces) * totalDeltaTime; var start = curve.evaluate(startT); var end = curve.evaluate(endT); var distance = Math.sqrt( (b.time - a.time) * (b.time - a.time) + (end - start) * (end - start)); var dx = endT - startT; for (var j = 0; j < distance; j++) { var x = startT + j * dx; var y = curve.evaluate(x); context.lineTo( x * canvas.width, canvas.height - y * canvas.height ); } } context.lineTo( b.time * canvas.width, canvas.height - b.value * canvas.height ); } global.AnimationCurveEditor = AnimationCurveEditor; })(this);
#!/bin/bash # Check if a branch name is provided as an argument if [ -z "$1" ]; then echo "You must specify the branch to keep" exit 1 # Return an error code fi # Check if the specified branch exists if ! git rev-parse --verify "$1" >/dev/null 2>&1; then echo "Branch '$1' does not exist" exit 1 # Return an error code fi # Delete all branches except the specified one git branch | grep -v '*' | grep -vw "$1" | xargs git branch -D echo "All branches except '$1' have been deleted"
class Converter: def __init__(self, base_currency): self.base_currency = base_currency self.rates = self.get_rates() def get_rates(self): # code to get the exchange rates from a web API def convert(self, target_currency, amount): return amount / self.rates[target_currency] * self.rates[self.base_currency] if __name__ == '__main__': converter = Converter("USD") converted_amount = converter.convert("EUR", 100) print(converted_amount)
#!/bin/sh #source "$(realpath $(dirname $0))/emsdk_inc.sh" source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/emsdk_inc.sh" [ -f $(dirname $0)/colors.sh ] && source $(dirname $0)/colors.sh PLATFORM="emscripten" SRC_DIR="external/equilibria-cpp/external/boost-sdk" INSTALL_DIR="build/boost" SRC_PATH="$(pwd)/$SRC_DIR" INSTALL_PATH="$(pwd)/$INSTALL_DIR" JAM_CONFIG_PATH="$(pwd)/configs/$PLATFORM.jam" [ ! -d ${SRC_PATH} -o $# -ge 1 ] \ && { case "$1" in "github"|"clone") shift [ -d ${SRC_PATH} -a "$1" != "force" ] \ && { echo "${RED}Target directory exists.${WHITE} Will not proceed without ${YELLOW}'force'${RESTORE}" exit 1 } [ ! -d ${SRC_PATH} -o "$1" = "force" ] \ && { get_boost_github ${SRC_PATH} || exit 1 } ;; "archive"|"source") shift [ -d ${SRC_PATH} -a "$1" != "force" ] \ && { echo "${RED}Target directory exists.${WHITE} Will not proceed without ${YELLOW}'force'${RESTORE}" exit 1 } [ ! -d ${SRC_PATH} -o "$1" = "force" ] \ && { get_boost_source ${SRC_PATH} || exit 1 } ;; "") [ -d ${SRC_PATH} ] \ || { echo "* Missing $(basename ${SRC_PATH}) Downloading..." get_boost_source ${SRC_PATH} || exit 1 } ;; *) echo "Unknown parameter: $1" exit 1 ;; esac } if [ ! -d "$SRC_PATH" ]; then echo "SOURCE NOT FOUND!" exit 1 fi if [ -z "$EMSCRIPTEN" ]; then echo "EMSCRIPTEN MUST BE DEFINED!" exit -1 fi cd $EMSCRIPTEN python ./embuilder.py build zlib \ || { echo "EMSDK build zlib failed.." exit 1 } # --- cd "$SRC_PATH" rm -rf bjam rm -rf b2 rm -rf project-config.jam rm -rf bootstrap.log rm -rf bin.v2 export NO_BZIP2=1 #bc it's supplied by emscripten but b2 will fail to find it # --with-libraries=atomic,signals,timer,system,filesystem,thread,date_time,chrono,regex,serialization,program_options,locale \ ./bootstrap.sh \ --with-libraries=system,thread,chrono,serialization,regex \ 2>&1 if [ $? != 0 ]; then echo "ERROR: boostrap FAILED!" exit 1 fi cat "$JAM_CONFIG_PATH" >> project-config.jam # --- # Clean rm -rf "$INSTALL_PATH" mkdir "$INSTALL_PATH" HOST_NCORES=$(nproc 2>/dev/null|| shell nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1) # threading=single \ ./b2 -q -a -j$HOST_NCORES \ toolset=clang-emscripten \ threading=single \ link=static \ optimization=space \ variant=release \ stage \ --stagedir="$INSTALL_PATH" \ 2>&1 unset NO_BZIP2 if [ $? != 0 ]; then echo "ERROR: b2 FAILED!" exit 1 fi # --- cd "$INSTALL_PATH" ln -s "$SRC_PATH" include
<gh_stars>10-100 # Starting omnifocus # Rehearsal -------------------------------------------------------------- # through /usr/bin/osascript 0.020000 0.050000 3.560000 ( 4.665417) # through appscript 0.060000 0.090000 0.150000 ( 0.135597) # ----------------------------------------------------- total: 3.710000sec # user system total real # through /usr/bin/osascript 0.010000 0.040000 3.490000 ( 4.604980) # through appscript 0.060000 0.080000 0.140000 ( 0.131573) # Loading projects # Rehearsal -------------------------------------------------------------- # through /usr/bin/osascript 0.020000 0.050000 4.540000 ( 5.911968) # through appscript 0.110000 0.110000 0.220000 ( 0.390105) # ----------------------------------------------------- total: 4.760000sec # user system total real # through /usr/bin/osascript 0.020000 0.050000 4.540000 ( 5.879542) # through appscript 0.080000 0.100000 0.180000 ( 0.331314) require 'benchmark' require 'appscript' include Appscript require 'open3' def osascript(script, language = "AppleScript") stdin, stdout = Open3.popen2("osascript -l #{language}") stdin.puts script stdin.close stdout.read end def start_omnifocus osascript <<-EOF tell application "System Events" if not (exists process "OmniFocus") then tell application "OmniFocus" to activate end if end tell EOF end def projects script = <<-EOF var app = Application('OmniFocus'); var doc = app.defaultDocument; projects = doc.flattenedProjects.whose({completed: false})() names = projects.map(function(project) { return project.name(); }) names EOF projects_string = osascript(script, "JavaScript").force_encoding("UTF-8") projects_string.split(",").map(&:strip) end def appscript_projects whose = its app("OmniFocus").default_document.flattened_projects[whose.completed.eq(false)].name.get end Times = 50 puts "\nStarting omnifocus\n\n\n" Benchmark.bmbm do |bm| bm.report('through /usr/bin/osascript') do Times.times do start_omnifocus end end bm.report('through appscript') do Times.times do unless app("OmniFocus").is_running? app("OmniFocus").activate end end end end puts "\nLoading projects\n\n\n" Benchmark.bmbm do |bm| bm.report('through /usr/bin/osascript') do Times.times do projects end end bm.report('through appscript') do Times.times do appscript_projects end end end
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2020 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:<EMAIL> */ #pragma once #include "Common-cpp/inc/defines.h" #ifdef _EG_UNIX_PLATFORM int getTimeUnix(void); # ifdef _EG_ANDROID_PLATFORM size_t EG_wcslen(const EG_CHAR* wcs); int EG_wcscmp (const EG_CHAR* src, const EG_CHAR* dst); EG_CHAR* EG_wcscpy(EG_CHAR * dst, const EG_CHAR * src); EG_CHAR* EG_wcscat (EG_CHAR * dst, const EG_CHAR * src); EG_CHAR* EG_wcsstr(const EG_CHAR* wcs1, const EG_CHAR* wcs2); size_t EG_wcsnlen(const EG_CHAR *s, size_t maxlen); EG_CHAR* EG_wcschr(const EG_CHAR * string, EG_CHAR ch); int EG_wcsncmp(const EG_CHAR * first, const EG_CHAR * last, size_t count); wchar_t * EG_wcsrchr (const EG_CHAR * string, EG_CHAR ch); # endif # if defined _EG_MARMALADE_PLATFORM && (!defined I3D_ARCH_X86 || !(defined _EG_MS_COMPILER || defined __clang__)) && !defined I3D_ARCH_64_BIT && !defined S3E_IPHONE_STATIC_LINK || defined _EG_ANDROID_PLATFORM || defined _EG_EMSCRIPTEN_PLATFORM int EG_vswprintf(EG_CHAR* wcs, size_t maxlen, const EG_CHAR* format, va_list args); int EG_swprintf(EG_CHAR* wcs, size_t maxlen, const EG_CHAR* format, ...); # endif #endif
<gh_stars>0 package com.qht.rest; import com.github.wxiaoqi.security.common.rest.BaseController; import com.qht.RequestObject; import com.qht.ResultObject; import com.qht.biz.ChapterBiz; import com.qht.common.util.BeanUtil; import com.qht.dto.CourseChapterDto; import com.qht.dto.CourseIntroParameter; import com.qht.entity.Chapter; import com.qht.model.CourseIntroParam; import com.qht.services.ChapterService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; @Controller public class ChapterController extends APIBaseController<ChapterBiz,Chapter> implements ChapterService { @Autowired private ChapterBiz chapterBiz; @Override @PostMapping("/student/courseChapter") @ResponseBody public ResultObject<List<CourseChapterDto>> courseChapter(@RequestBody RequestObject<CourseIntroParameter> requestObject) { ResultObject<List<CourseChapterDto>> resultObject=new ResultObject<>(); if(requestObject.getData()==null){ resultObject.setData(new ArrayList<>()); return resultObject.setMsg("参数为空"); }; CourseIntroParam param=new CourseIntroParam(); BeanUtil.copyFields(param,requestObject.getData()); List<CourseChapterDto> list=chapterBiz.selectCourseChapter(param); if(list.size()>0){ resultObject.setCode("0"); resultObject.setMsg("成功"); resultObject.setData(list); return resultObject; } resultObject.setData(new ArrayList<>()); resultObject.setMsg("查询无数据"); return resultObject; } /** * 课程体系 */ @Override @PostMapping("/student/app/courseChapter") @ResponseBody public ResultObject<List<CourseChapterDto>> selectCourseChapterByCuId(@RequestBody RequestObject<CourseIntroParameter> requestObject) { return this.courseChapter(requestObject); } }
# generated by Git for Windows test -f ~/.profile && . ~/.profile test -f ~/.bashrc && . ~/.bashrc
#!/bin/sh . ${BUILDPACK_TEST_RUNNER_HOME}/lib/test_utils.sh WRAPPER_DIR=${BUILDPACK_HOME}/opt/wrapper installWrapper() { cp -r "$WRAPPER_DIR"/* ${BUILD_DIR} } testCompileWithoutWrapper() { cat > ${BUILD_DIR}/build.gradle <<EOF task stage << { println "${expected_stage_output}" } EOF compile assertCapturedSuccess assertCaptured "Installing Gradle Wrapper" } testCompileWithWrapper() { installWrapper expected_stage_output="STAGING:${RANDOM}" cat > ${BUILD_DIR}/build.gradle <<EOF task stage << { println "${expected_stage_output}" } EOF compile assertCapturedSuccess assertCaptured "Installing JDK 1.8" assertCaptured "${expected_stage_output}" assertCaptured "BUILD SUCCESSFUL" assertTrue "Java should be present in runtime." "[ -d ${BUILD_DIR}/.jdk ]" assertTrue "Java version file should be present." "[ -f ${BUILD_DIR}/.jdk/version ]" assertTrue "Gradle profile.d file should be present in build dir." "[ -f ${BUILD_DIR}/.profile.d/jvmcommon.sh ]" assertTrue "GRADLE_USER_HOME should be CACHE_DIR/.gradle." "[ -d ${CACHE_DIR}/.gradle ]" } testCompileWithCustomTask() { installWrapper expected_stage_output="STAGING:${RANDOM}" cat > ${BUILD_DIR}/build.gradle <<EOF task foo << { println "${expected_stage_output}" } EOF echo -n "foo" > ${ENV_DIR}/GRADLE_TASK compile assertCapturedSuccess assertCaptured "executing ./gradlew foo" } testCompile_Fail() { installWrapper expected_stage_output="STAGING:${RANDOM}" cat > ${BUILD_DIR}/build.gradle <<EOF task stage << { throw new GradleException("${expected_stage_output}") } EOF compile assertCapturedError "${expected_stage_output}" assertCapturedError "BUILD FAILED" }
import { Line, Subcommand } from "https://deno.land/x/line@v0.1.1/mod.ts"; class Hello extends Subcommand { public signature = "hello [string]"; public description = "Say hello [string]."; public handle(): void { const name = this.getArgumentValue("string"); if (!name) return console.error("Name not specified."); console.log(`Hello ${name}`); } } const cli = new Line({ command: "test", name: "Test CLI", description: "A test CLI.", version: "v1.0.0", subcommands: [ Hello, ], }); cli.run();
from scapy.all import DUID_LL class ServerManager: def __init__(self, pg0_remote_mac): self.pg0 = NetworkInterface(pg0_remote_mac) self.server_duid = DUID_LL(lladdr=self.pg0.remote_mac) # Initialize server_duid attribute with DUID_LL format def admin_up(self): # Implement the method to bring the network interface up self.pg0.admin_up() def config_ip6(self): # Implement the method to configure the IPv6 address for the network interface # Assume the IPv6 configuration logic is implemented here pass class NetworkInterface: def __init__(self, remote_mac): self.remote_mac = remote_mac def admin_up(self): # Implement the method to bring the network interface up pass
<filename>build/watch.js<gh_stars>0 import BuildProcessBuildStage from "./buildProcessBuildStage" new BuildProcessBuildStage(false)
import html # define string string = '&quot; is a quote.' # convert HTML entities to characters converted_string = html.unescape(string) # print converted string print('Converted string:', converted_string)