content
stringlengths
10
4.9M
<reponame>fossabot/markuplint import { createRule, Result } from '@markuplint/ml-core'; import { MLDOMElement, MLDOMElementCloseTag } from '@markuplint/ml-core/lib/ml-dom/tokens'; export type Value = 'lower' | 'upper'; export default createRule<Value, null>({ name: 'case-sensitive-tag-name', defaultLevel: 'warning', defaultValue: 'lower', defaultOptions: null, async verify(document, messages) { const reports: Result[] = []; await document.walk(async node => { if (node instanceof MLDOMElement || node instanceof MLDOMElementCloseTag) { if (node.isForeignElement) { return; } const ms = node.rule.severity === 'error' ? 'must' : 'should'; const deny = node.rule.value === 'lower' ? /[A-Z]/ : /[a-z]/; const message = messages( `{0} of {1} ${ms} be {2}`, 'Tag name', 'HTML element', `${node.rule.value}case`, ); if (deny.test(node.nodeName)) { reports.push({ severity: node.rule.severity, message, line: node.startLine, col: node instanceof MLDOMElement ? node.startCol + 1 // remove "<" char. : node.startCol + 2, // remove "</" char. raw: node.nodeName, }); } } }); return reports; }, // async fix(document) { // await document.walk(async node => { // if (node instanceof Element || node instanceof ElementCloseTag) { // if (node.isForeignElement) { // return; // } // const deny = node.rule.value === 'lower' ? /[A-Z]/ : /[a-z]/; // if (deny.test(node.nodeName)) { // if (node.rule.value === 'lower') { // node.nodeName = node.nodeName.toLowerCase(); // } else { // node.nodeName = node.nodeName.toUpperCase(); // } // } // } // }); // }, });
def log_profile_plots( targets: Mapping[str, np.ndarray], predictions: Mapping[str, np.ndarray], nsamples: int = 4, ): for name in set(targets) & set(predictions): t = targets[name] p = predictions[name] _plot_profiles(t[:nsamples], p[:nsamples], name)
#include<bits/stdc++.h> using namespace std; #define FOR(i, a, b) for(int (i) = (a); (i) <= (b); (i)++) #define ROF(i, a, b) for(int (i) = (a); (i) >= (b); (i)--) #define SIZE 12 struct Move { int from; int to; }; int Cases(string S) { int c = 0; FOR(i, 0, SIZE - 3) { if (S.substr(i,3) == "-oo" || S.substr(i, 3) == "oo-") { c++; } } return c; } void GetMoves(string S, Move Ms[]) { int j = 0; FOR(i, 0, SIZE - 3) { if (S.substr(i,3) == "-oo") { Ms[j].from = i + 2; Ms[j].to = i; j++; } else if (S.substr(i, 3) == "oo-") { Ms[j].from = i; Ms[j].to = i + 2; j++; } } } string TakeMove(string S, Move M) { string nS; if (M.from < M.to) { nS = S.substr(0, M.from) + "--o" + S.substr(M.to + 1); } else { nS = S.substr(0, M.to) + "o--" + S.substr(M.from + 1); } return nS; } int PeddleCount (string S) { int c = 0; FOR(i, 0, SIZE - 1) { if (S.substr(i,1) == "o") { c++; } } return c; } int MakeMove (string S, Move M, int Memo[][SIZE], bool R[]) { string nS = TakeMove(S, M); if (Cases(nS) == 0){ R[PeddleCount(nS) - 1] = 1; return 1; } else { Move Ms[Cases(nS)]; GetMoves(nS,Ms); int ans = -1; Move OptM; int pre_ans = -1; FOR(i, 0, Cases(nS) - 1){ pre_ans = ans; ans = max(ans, MakeMove(nS, Ms[i], Memo, R)); if (ans >= pre_ans) { OptM.from = Ms[i].from; OptM.to = Ms[i].to; } } Memo[OptM.from][OptM.to] = ans; return 1 + ans; } } int main() { int N; cin >> N; FOR(k, 0, N - 1) { int Memo[SIZE][SIZE]; FOR(i, 0, SIZE - 1){ FOR(j, 0, SIZE - 1){ Memo[i][j] = -1; } } string S; cin >> S; int c = Cases(S); if (c == 0) { cout << PeddleCount(S) << endl; continue; } else { Move Ms[c]; GetMoves(S, Ms); bool R[SIZE] = {0}; FOR(i, 0, c - 1) { FOR(a, 0, SIZE - 1){ FOR(b, 0, SIZE - 1){ Memo[a][b] = -1; } } MakeMove(S,Ms[i],Memo,R); } FOR(i,0, SIZE - 1) { if (R[i] == 1){ cout << i + 1 << endl; break; } } } } return 0; }
from copy import deepcopy n=int(input()) A=list(map(int, input().split())) B=[0]+deepcopy(A)+[0] total=0 b=0 for a in A: total+=abs(a-b) b=a total+=abs(b) for i in range(1,n+1): z,x,c=B[i-1], B[i], B[i+1] print(total-abs(x-z)-abs(c-x)+abs(c-z))
/// Intern a value. If this value has not previously been /// interned, then `new` will allocate a spot for the value on the /// heap. Otherwise, it will return a pointer to the object /// previously allocated. /// /// Note that `ArcIntern::new` is a bit slow, since it needs to check /// a `DashMap` which is protected by internal sharded locks. pub fn new(mut val: T) -> ArcIntern<T> { loop { let c = Self::get_container(); let m = c.downcast_ref::<Container<T>>().unwrap(); if let Some(b) = m.get_mut(&val) { let b = b.key(); // First increment the count. We are holding the write mutex here. // Has to be the write mutex to avoid a race let oldval = b.0.count.fetch_add(1, Ordering::SeqCst); if oldval != 0 { // we can only use this value if the value is not about to be freed return ArcIntern { pointer: std::ptr::NonNull::from(b.0.borrow()), }; } else { // we have encountered a race condition here. // we will just wait for the object to finish // being freed. b.0.count.fetch_sub(1, Ordering::SeqCst); } } else { let b = Box::new(RefCount { count: AtomicUsize::new(1), data: val, }); match m.entry(BoxRefCount(b)) { Entry::Vacant(e) => { // We can insert, all is good let p = ArcIntern { pointer: std::ptr::NonNull::from(e.key().0.borrow()), }; e.insert(()); return p; } Entry::Occupied(e) => { // Race, map already has data, go round again let box_ref_count = e.into_key(); val = box_ref_count.into_inner(); } } } // yield so that the object can finish being freed, // and then we will be able to intern a new copy. std::thread::yield_now(); } }
/** * Deletes an existing subscription. All pending messages in the subscription * are immediately dropped. Calls to `Pull` after deletion will return * `NOT_FOUND`. After a subscription is deleted, a new one may be created with * the same name, but the new one has no association with the old * subscription, or its topic unless the same topic is specified. * * Sample code: * <pre><code> * try (SubscriberApi subscriberApi = SubscriberApi.create()) { * String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); * subscriberApi.deleteSubscription(formattedSubscription); * } * </code></pre> * * @param subscription The subscription to delete. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteSubscription(String subscription) { SUBSCRIPTION_PATH_TEMPLATE.validate(subscription, "deleteSubscription"); DeleteSubscriptionRequest request = DeleteSubscriptionRequest.newBuilder().setSubscription(subscription).build(); deleteSubscription(request); }
import * as AWS from "aws-sdk"; import { BucketName } from "aws-sdk/clients/s3"; import * as crypto from "crypto"; import { readdir, mkdir, readFile } from "fs-extra"; import * as glob from "glob"; import * as hashFiles from "hash-files"; import * as path from "path"; import { defaultCachePath } from "./config"; import Logger from "./logger"; import { Dir, FilePath, Bins, Deps, MonoConfig } from "./typings"; export const getCompressedName = (pathWithoutExtension: string) => `${pathWithoutExtension}.tar.xz`; export const getIdFromCompressedName = (name: string) => { const tar = path.parse(name).name; return path.parse(tar).name; }; export const makeCacheDir = async (logger: Logger, cacheDir: Dir) => { if (cacheDir) { return cacheDir; } logger.warn(`No cache destination, using ${defaultCachePath}`); try { await mkdir(defaultCachePath); } catch (e) { if (e.code !== "EEXIST") { throw new Error(e); } } return defaultCachePath; }; export const getYarnLockId = (cwd: Dir) => new Promise<string>((res, rej) => { hashFiles( { files: [path.join(cwd, "yarn.lock")], noGlob: true }, (err: Error, hash: string) => { if (err) { return rej(err); } return res(hash); } ); }); export const arrToMap = <T>(arr: T[], getKey: (t: T) => string) => arr.reduce((m, item, indx) => ({ ...m, [getKey(item)]: arr[indx] }), {}); export const getBins = async (cwd: Dir) => { try { const bins = await readdir(path.join(cwd, "/node_modules/.bin")); return arrToMap(bins, x => x); } catch (e) { return {}; } }; export const getMonoConfig = (cwd: Dir, configPath: FilePath) => { if (configPath) { return require(path.join(cwd, configPath)); } // eslint-disable-next-line global-require, import/no-dynamic-require return require(path.join(cwd, "lerna.json")); }; export const getMonoFiles = (cwd: Dir, monoPkgPath: FilePath) => new Promise<string[]>((res, rej) => { glob( `${monoPkgPath}/*package.json`, { cwd }, (err, files) => { if (err) { return rej(err.message); } return res(files); } ); }); const applyToMonoPkg = async ( cwd: Dir, monoPkgPath: FilePath, pred: (pjPath: string) => void ) => { const files = await getMonoFiles(cwd, monoPkgPath); for (let i = 0; i < files.length; i++) { await pred(files[i]); } }; export const applyToMonoPkgs = async ( cwd: Dir, monoConfig: MonoConfig, pred: (pjPath: string) => void ) => { for (let i = 0; i < monoConfig.packages.length; i++) { await applyToMonoPkg(cwd, monoConfig.packages[i], pred); } }; export const makeBinDepKey = (bins: Bins, deps: Deps) => { if (!deps) { return null; } const binDeps = deps ? Object.keys(deps) .filter(dep => { if (dep === "flow-bin") { return "flow"; } return bins[dep]; }) .map(dep => `${dep}@${deps[dep]}`) : []; if (binDeps.length === 0) { return null; } return crypto.createHmac("sha256", binDeps.join("")).digest("hex"); }; export const getS3 = (S3: typeof AWS.S3, Bucket: BucketName) => new S3({ apiVersion: "2006-03-01", params: { Bucket } }); export const uploadToS3 = async ( s3: AWS.S3, Bucket: BucketName, Key: string, data: Buffer ) => new Promise((res, rej) => { s3.upload( { Bucket, Key, Body: Buffer.from(data) }, (err, result) => { if (err) { return rej(err); } return res(result); } ); }); export const getUploadedTars = (s3: AWS.S3) => new Promise<AWS.S3.Object[]>((res, rej) => s3.listObjects((err, data) => { if (err) { return rej(err); } return res(data.Contents); }) ); export const sendToS3 = async ( S3: typeof AWS.S3, logger: Logger, bucketName: BucketName, cacheDir: Dir ) => { const s3 = getS3(S3, bucketName); const uploadedTars = await getUploadedTars(s3); const keys = arrToMap(uploadedTars, ({ Key }: { Key: string }) => getCompressedName(Key) ); const cachedTars = await readdir(cacheDir); const newTars = cachedTars.filter((cachedTar: string) => !keys[cachedTar]); if (newTars.length === 0) { return; } logger.log(`Uploading ${newTars.length} new tars`); logger.info(newTars.toString()); for (let i = 0; i < newTars.length; i++) { const data = await readFile(path.join(cacheDir, newTars[i])); const result = await uploadToS3( s3, bucketName, getIdFromCompressedName(newTars[i]), data ); logger.info(JSON.stringify(result)); } logger.log("Uploaded new caches"); }; export const getFile = ( s3: AWS.S3, Bucket: AWS.S3.BucketName, Key: AWS.S3.ObjectKey ): Promise<AWS.S3.Types.GetObjectOutput> => new Promise((res, rej) => s3.getObject({ Key, Bucket }, (err, data) => { if (err) { return rej(err); } return res(data); }) ); // const syncCache = async ( // S3: typeof AWS.S3, // logger: Logger, // remote: BucketName, // cacheDir: Dir // ) => { // const s3 = getS3(S3, remote); // const uploadedTars = await getUploadedTars(s3); // const cachedTars = await readdir(cacheDir); // const keys = arrToMap(cachedTars, (x: string) => getIdFromCompressedName(x)); // const newRemote = uploadedTars.filter( // ({ Key }: { Key: string }) => !keys[Key] // ); // // logger.log("Syncing remote..."); // logger.info(`Syncing: ${JSON.stringify(newRemote)}`); // // for (let i = 0; i < newRemote.length; i++) { // const key = newRemote[i].Key; // const file = await getFile(s3, remote, key); // // await writeFile(path.join(cacheDir, getCompressedName(key)), file.Body); // // logger.info(`${getCompressedName(key)} written to ${cacheDir}`); // } // // logger.log("Remote synced"); // };
World Foundation for Renal Care: helping acute and chronic renal failure patients and their families worldwide: an interview with Geraldine Biddle. In this interview, Geraldine Biddle, president and co-founder of the World Foundation for Renal Care (WFRC), describes the organization's beginnings and the progress it has made toward its mission and vision. Ms. Biddle also details the historic involvement of ANNA informing WFRC and participating in its activities. Founded in 1997, the WFRC has its world headquarters in London and currently has three ANNA past presidents on its Board of Directors.
/** * <pre> * Request is the data structure for storing requests in the storage. * </pre> * * Protobuf type {@code oracle.v1.Request} */ public static final class Request extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:oracle.v1.Request) RequestOrBuilder { private static final long serialVersionUID = 0L; // Use Request.newBuilder() to construct. private Request(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Request() { calldata_ = com.google.protobuf.ByteString.EMPTY; requestedValidators_ = com.google.protobuf.LazyStringArrayList.EMPTY; clientId_ = ""; rawRequests_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new Request(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Request( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { oracleScriptId_ = input.readInt64(); break; } case 18: { calldata_ = input.readBytes(); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000001) != 0)) { requestedValidators_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000001; } requestedValidators_.add(s); break; } case 32: { minCount_ = input.readUInt64(); break; } case 40: { requestHeight_ = input.readInt64(); break; } case 48: { requestTime_ = input.readUInt64(); break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); clientId_ = s; break; } case 66: { if (!((mutable_bitField0_ & 0x00000002) != 0)) { rawRequests_ = new java.util.ArrayList<oracle.v1.Oracle.RawRequest>(); mutable_bitField0_ |= 0x00000002; } rawRequests_.add( input.readMessage(oracle.v1.Oracle.RawRequest.parser(), extensionRegistry)); break; } case 74: { oracle.v1.Oracle.IBCChannel.Builder subBuilder = null; if (ibcChannel_ != null) { subBuilder = ibcChannel_.toBuilder(); } ibcChannel_ = input.readMessage(oracle.v1.Oracle.IBCChannel.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(ibcChannel_); ibcChannel_ = subBuilder.buildPartial(); } break; } case 80: { executeGas_ = input.readUInt64(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { requestedValidators_ = requestedValidators_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000002) != 0)) { rawRequests_ = java.util.Collections.unmodifiableList(rawRequests_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return oracle.v1.Oracle.internal_static_oracle_v1_Request_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return oracle.v1.Oracle.internal_static_oracle_v1_Request_fieldAccessorTable .ensureFieldAccessorsInitialized( oracle.v1.Oracle.Request.class, oracle.v1.Oracle.Request.Builder.class); } public static final int ORACLE_SCRIPT_ID_FIELD_NUMBER = 1; private long oracleScriptId_; /** * <pre> * OracleScriptID is ID of an oracle script * </pre> * * <code>int64 oracle_script_id = 1 [(.gogoproto.customname) = "OracleScriptID", (.gogoproto.casttype) = "OracleScriptID"];</code> * @return The oracleScriptId. */ @java.lang.Override public long getOracleScriptId() { return oracleScriptId_; } public static final int CALLDATA_FIELD_NUMBER = 2; private com.google.protobuf.ByteString calldata_; /** * <pre> * Calldata is the data used as argument params for the oracle script * </pre> * * <code>bytes calldata = 2;</code> * @return The calldata. */ @java.lang.Override public com.google.protobuf.ByteString getCalldata() { return calldata_; } public static final int REQUESTED_VALIDATORS_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList requestedValidators_; /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @return A list containing the requestedValidators. */ public com.google.protobuf.ProtocolStringList getRequestedValidatorsList() { return requestedValidators_; } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @return The count of requestedValidators. */ public int getRequestedValidatorsCount() { return requestedValidators_.size(); } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param index The index of the element to return. * @return The requestedValidators at the given index. */ public java.lang.String getRequestedValidators(int index) { return requestedValidators_.get(index); } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param index The index of the value to return. * @return The bytes of the requestedValidators at the given index. */ public com.google.protobuf.ByteString getRequestedValidatorsBytes(int index) { return requestedValidators_.getByteString(index); } public static final int MIN_COUNT_FIELD_NUMBER = 4; private long minCount_; /** * <pre> * MinCount is minimum number of validators required for fulfilling the * request * </pre> * * <code>uint64 min_count = 4;</code> * @return The minCount. */ @java.lang.Override public long getMinCount() { return minCount_; } public static final int REQUEST_HEIGHT_FIELD_NUMBER = 5; private long requestHeight_; /** * <pre> * RequestHeight is block height that the request has been created * </pre> * * <code>int64 request_height = 5;</code> * @return The requestHeight. */ @java.lang.Override public long getRequestHeight() { return requestHeight_; } public static final int REQUEST_TIME_FIELD_NUMBER = 6; private long requestTime_; /** * <pre> * RequestTime is timestamp of the chain's block which contains the request * </pre> * * <code>uint64 request_time = 6;</code> * @return The requestTime. */ @java.lang.Override public long getRequestTime() { return requestTime_; } public static final int CLIENT_ID_FIELD_NUMBER = 7; private volatile java.lang.Object clientId_; /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @return The clientId. */ @java.lang.Override public java.lang.String getClientId() { java.lang.Object ref = clientId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); clientId_ = s; return s; } } /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @return The bytes for clientId. */ @java.lang.Override public com.google.protobuf.ByteString getClientIdBytes() { java.lang.Object ref = clientId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); clientId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RAW_REQUESTS_FIELD_NUMBER = 8; private java.util.List<oracle.v1.Oracle.RawRequest> rawRequests_; /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ @java.lang.Override public java.util.List<oracle.v1.Oracle.RawRequest> getRawRequestsList() { return rawRequests_; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ @java.lang.Override public java.util.List<? extends oracle.v1.Oracle.RawRequestOrBuilder> getRawRequestsOrBuilderList() { return rawRequests_; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ @java.lang.Override public int getRawRequestsCount() { return rawRequests_.size(); } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ @java.lang.Override public oracle.v1.Oracle.RawRequest getRawRequests(int index) { return rawRequests_.get(index); } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ @java.lang.Override public oracle.v1.Oracle.RawRequestOrBuilder getRawRequestsOrBuilder( int index) { return rawRequests_.get(index); } public static final int IBC_CHANNEL_FIELD_NUMBER = 9; private oracle.v1.Oracle.IBCChannel ibcChannel_; /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> * @return Whether the ibcChannel field is set. */ @java.lang.Override public boolean hasIbcChannel() { return ibcChannel_ != null; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> * @return The ibcChannel. */ @java.lang.Override public oracle.v1.Oracle.IBCChannel getIbcChannel() { return ibcChannel_ == null ? oracle.v1.Oracle.IBCChannel.getDefaultInstance() : ibcChannel_; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ @java.lang.Override public oracle.v1.Oracle.IBCChannelOrBuilder getIbcChannelOrBuilder() { return getIbcChannel(); } public static final int EXECUTE_GAS_FIELD_NUMBER = 10; private long executeGas_; /** * <pre> * ExecuteGas is amount of gas to reserve for executing * </pre> * * <code>uint64 execute_gas = 10;</code> * @return The executeGas. */ @java.lang.Override public long getExecuteGas() { return executeGas_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (oracleScriptId_ != 0L) { output.writeInt64(1, oracleScriptId_); } if (!calldata_.isEmpty()) { output.writeBytes(2, calldata_); } for (int i = 0; i < requestedValidators_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, requestedValidators_.getRaw(i)); } if (minCount_ != 0L) { output.writeUInt64(4, minCount_); } if (requestHeight_ != 0L) { output.writeInt64(5, requestHeight_); } if (requestTime_ != 0L) { output.writeUInt64(6, requestTime_); } if (!getClientIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, clientId_); } for (int i = 0; i < rawRequests_.size(); i++) { output.writeMessage(8, rawRequests_.get(i)); } if (ibcChannel_ != null) { output.writeMessage(9, getIbcChannel()); } if (executeGas_ != 0L) { output.writeUInt64(10, executeGas_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (oracleScriptId_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(1, oracleScriptId_); } if (!calldata_.isEmpty()) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, calldata_); } { int dataSize = 0; for (int i = 0; i < requestedValidators_.size(); i++) { dataSize += computeStringSizeNoTag(requestedValidators_.getRaw(i)); } size += dataSize; size += 1 * getRequestedValidatorsList().size(); } if (minCount_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(4, minCount_); } if (requestHeight_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, requestHeight_); } if (requestTime_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(6, requestTime_); } if (!getClientIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, clientId_); } for (int i = 0; i < rawRequests_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(8, rawRequests_.get(i)); } if (ibcChannel_ != null) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(9, getIbcChannel()); } if (executeGas_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(10, executeGas_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof oracle.v1.Oracle.Request)) { return super.equals(obj); } oracle.v1.Oracle.Request other = (oracle.v1.Oracle.Request) obj; if (getOracleScriptId() != other.getOracleScriptId()) return false; if (!getCalldata() .equals(other.getCalldata())) return false; if (!getRequestedValidatorsList() .equals(other.getRequestedValidatorsList())) return false; if (getMinCount() != other.getMinCount()) return false; if (getRequestHeight() != other.getRequestHeight()) return false; if (getRequestTime() != other.getRequestTime()) return false; if (!getClientId() .equals(other.getClientId())) return false; if (!getRawRequestsList() .equals(other.getRawRequestsList())) return false; if (hasIbcChannel() != other.hasIbcChannel()) return false; if (hasIbcChannel()) { if (!getIbcChannel() .equals(other.getIbcChannel())) return false; } if (getExecuteGas() != other.getExecuteGas()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ORACLE_SCRIPT_ID_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getOracleScriptId()); hash = (37 * hash) + CALLDATA_FIELD_NUMBER; hash = (53 * hash) + getCalldata().hashCode(); if (getRequestedValidatorsCount() > 0) { hash = (37 * hash) + REQUESTED_VALIDATORS_FIELD_NUMBER; hash = (53 * hash) + getRequestedValidatorsList().hashCode(); } hash = (37 * hash) + MIN_COUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getMinCount()); hash = (37 * hash) + REQUEST_HEIGHT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRequestHeight()); hash = (37 * hash) + REQUEST_TIME_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRequestTime()); hash = (37 * hash) + CLIENT_ID_FIELD_NUMBER; hash = (53 * hash) + getClientId().hashCode(); if (getRawRequestsCount() > 0) { hash = (37 * hash) + RAW_REQUESTS_FIELD_NUMBER; hash = (53 * hash) + getRawRequestsList().hashCode(); } if (hasIbcChannel()) { hash = (37 * hash) + IBC_CHANNEL_FIELD_NUMBER; hash = (53 * hash) + getIbcChannel().hashCode(); } hash = (37 * hash) + EXECUTE_GAS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getExecuteGas()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static oracle.v1.Oracle.Request parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static oracle.v1.Oracle.Request parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static oracle.v1.Oracle.Request parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static oracle.v1.Oracle.Request parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static oracle.v1.Oracle.Request parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static oracle.v1.Oracle.Request parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static oracle.v1.Oracle.Request parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static oracle.v1.Oracle.Request parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static oracle.v1.Oracle.Request parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static oracle.v1.Oracle.Request parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static oracle.v1.Oracle.Request parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static oracle.v1.Oracle.Request parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(oracle.v1.Oracle.Request prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * Request is the data structure for storing requests in the storage. * </pre> * * Protobuf type {@code oracle.v1.Request} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:oracle.v1.Request) oracle.v1.Oracle.RequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return oracle.v1.Oracle.internal_static_oracle_v1_Request_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return oracle.v1.Oracle.internal_static_oracle_v1_Request_fieldAccessorTable .ensureFieldAccessorsInitialized( oracle.v1.Oracle.Request.class, oracle.v1.Oracle.Request.Builder.class); } // Construct using oracle.v1.Oracle.Request.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getRawRequestsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); oracleScriptId_ = 0L; calldata_ = com.google.protobuf.ByteString.EMPTY; requestedValidators_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); minCount_ = 0L; requestHeight_ = 0L; requestTime_ = 0L; clientId_ = ""; if (rawRequestsBuilder_ == null) { rawRequests_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { rawRequestsBuilder_.clear(); } if (ibcChannelBuilder_ == null) { ibcChannel_ = null; } else { ibcChannel_ = null; ibcChannelBuilder_ = null; } executeGas_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return oracle.v1.Oracle.internal_static_oracle_v1_Request_descriptor; } @java.lang.Override public oracle.v1.Oracle.Request getDefaultInstanceForType() { return oracle.v1.Oracle.Request.getDefaultInstance(); } @java.lang.Override public oracle.v1.Oracle.Request build() { oracle.v1.Oracle.Request result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public oracle.v1.Oracle.Request buildPartial() { oracle.v1.Oracle.Request result = new oracle.v1.Oracle.Request(this); int from_bitField0_ = bitField0_; result.oracleScriptId_ = oracleScriptId_; result.calldata_ = calldata_; if (((bitField0_ & 0x00000001) != 0)) { requestedValidators_ = requestedValidators_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000001); } result.requestedValidators_ = requestedValidators_; result.minCount_ = minCount_; result.requestHeight_ = requestHeight_; result.requestTime_ = requestTime_; result.clientId_ = clientId_; if (rawRequestsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { rawRequests_ = java.util.Collections.unmodifiableList(rawRequests_); bitField0_ = (bitField0_ & ~0x00000002); } result.rawRequests_ = rawRequests_; } else { result.rawRequests_ = rawRequestsBuilder_.build(); } if (ibcChannelBuilder_ == null) { result.ibcChannel_ = ibcChannel_; } else { result.ibcChannel_ = ibcChannelBuilder_.build(); } result.executeGas_ = executeGas_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof oracle.v1.Oracle.Request) { return mergeFrom((oracle.v1.Oracle.Request)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(oracle.v1.Oracle.Request other) { if (other == oracle.v1.Oracle.Request.getDefaultInstance()) return this; if (other.getOracleScriptId() != 0L) { setOracleScriptId(other.getOracleScriptId()); } if (other.getCalldata() != com.google.protobuf.ByteString.EMPTY) { setCalldata(other.getCalldata()); } if (!other.requestedValidators_.isEmpty()) { if (requestedValidators_.isEmpty()) { requestedValidators_ = other.requestedValidators_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureRequestedValidatorsIsMutable(); requestedValidators_.addAll(other.requestedValidators_); } onChanged(); } if (other.getMinCount() != 0L) { setMinCount(other.getMinCount()); } if (other.getRequestHeight() != 0L) { setRequestHeight(other.getRequestHeight()); } if (other.getRequestTime() != 0L) { setRequestTime(other.getRequestTime()); } if (!other.getClientId().isEmpty()) { clientId_ = other.clientId_; onChanged(); } if (rawRequestsBuilder_ == null) { if (!other.rawRequests_.isEmpty()) { if (rawRequests_.isEmpty()) { rawRequests_ = other.rawRequests_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureRawRequestsIsMutable(); rawRequests_.addAll(other.rawRequests_); } onChanged(); } } else { if (!other.rawRequests_.isEmpty()) { if (rawRequestsBuilder_.isEmpty()) { rawRequestsBuilder_.dispose(); rawRequestsBuilder_ = null; rawRequests_ = other.rawRequests_; bitField0_ = (bitField0_ & ~0x00000002); rawRequestsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getRawRequestsFieldBuilder() : null; } else { rawRequestsBuilder_.addAllMessages(other.rawRequests_); } } } if (other.hasIbcChannel()) { mergeIbcChannel(other.getIbcChannel()); } if (other.getExecuteGas() != 0L) { setExecuteGas(other.getExecuteGas()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { oracle.v1.Oracle.Request parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (oracle.v1.Oracle.Request) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long oracleScriptId_ ; /** * <pre> * OracleScriptID is ID of an oracle script * </pre> * * <code>int64 oracle_script_id = 1 [(.gogoproto.customname) = "OracleScriptID", (.gogoproto.casttype) = "OracleScriptID"];</code> * @return The oracleScriptId. */ @java.lang.Override public long getOracleScriptId() { return oracleScriptId_; } /** * <pre> * OracleScriptID is ID of an oracle script * </pre> * * <code>int64 oracle_script_id = 1 [(.gogoproto.customname) = "OracleScriptID", (.gogoproto.casttype) = "OracleScriptID"];</code> * @param value The oracleScriptId to set. * @return This builder for chaining. */ public Builder setOracleScriptId(long value) { oracleScriptId_ = value; onChanged(); return this; } /** * <pre> * OracleScriptID is ID of an oracle script * </pre> * * <code>int64 oracle_script_id = 1 [(.gogoproto.customname) = "OracleScriptID", (.gogoproto.casttype) = "OracleScriptID"];</code> * @return This builder for chaining. */ public Builder clearOracleScriptId() { oracleScriptId_ = 0L; onChanged(); return this; } private com.google.protobuf.ByteString calldata_ = com.google.protobuf.ByteString.EMPTY; /** * <pre> * Calldata is the data used as argument params for the oracle script * </pre> * * <code>bytes calldata = 2;</code> * @return The calldata. */ @java.lang.Override public com.google.protobuf.ByteString getCalldata() { return calldata_; } /** * <pre> * Calldata is the data used as argument params for the oracle script * </pre> * * <code>bytes calldata = 2;</code> * @param value The calldata to set. * @return This builder for chaining. */ public Builder setCalldata(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } calldata_ = value; onChanged(); return this; } /** * <pre> * Calldata is the data used as argument params for the oracle script * </pre> * * <code>bytes calldata = 2;</code> * @return This builder for chaining. */ public Builder clearCalldata() { calldata_ = getDefaultInstance().getCalldata(); onChanged(); return this; } private com.google.protobuf.LazyStringList requestedValidators_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureRequestedValidatorsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { requestedValidators_ = new com.google.protobuf.LazyStringArrayList(requestedValidators_); bitField0_ |= 0x00000001; } } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @return A list containing the requestedValidators. */ public com.google.protobuf.ProtocolStringList getRequestedValidatorsList() { return requestedValidators_.getUnmodifiableView(); } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @return The count of requestedValidators. */ public int getRequestedValidatorsCount() { return requestedValidators_.size(); } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param index The index of the element to return. * @return The requestedValidators at the given index. */ public java.lang.String getRequestedValidators(int index) { return requestedValidators_.get(index); } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param index The index of the value to return. * @return The bytes of the requestedValidators at the given index. */ public com.google.protobuf.ByteString getRequestedValidatorsBytes(int index) { return requestedValidators_.getByteString(index); } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param index The index to set the value at. * @param value The requestedValidators to set. * @return This builder for chaining. */ public Builder setRequestedValidators( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureRequestedValidatorsIsMutable(); requestedValidators_.set(index, value); onChanged(); return this; } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param value The requestedValidators to add. * @return This builder for chaining. */ public Builder addRequestedValidators( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureRequestedValidatorsIsMutable(); requestedValidators_.add(value); onChanged(); return this; } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param values The requestedValidators to add. * @return This builder for chaining. */ public Builder addAllRequestedValidators( java.lang.Iterable<java.lang.String> values) { ensureRequestedValidatorsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, requestedValidators_); onChanged(); return this; } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @return This builder for chaining. */ public Builder clearRequestedValidators() { requestedValidators_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * RequestedValidators is a list of validator addresses that are assigned for * fulfilling the request * </pre> * * <code>repeated string requested_validators = 3;</code> * @param value The bytes of the requestedValidators to add. * @return This builder for chaining. */ public Builder addRequestedValidatorsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureRequestedValidatorsIsMutable(); requestedValidators_.add(value); onChanged(); return this; } private long minCount_ ; /** * <pre> * MinCount is minimum number of validators required for fulfilling the * request * </pre> * * <code>uint64 min_count = 4;</code> * @return The minCount. */ @java.lang.Override public long getMinCount() { return minCount_; } /** * <pre> * MinCount is minimum number of validators required for fulfilling the * request * </pre> * * <code>uint64 min_count = 4;</code> * @param value The minCount to set. * @return This builder for chaining. */ public Builder setMinCount(long value) { minCount_ = value; onChanged(); return this; } /** * <pre> * MinCount is minimum number of validators required for fulfilling the * request * </pre> * * <code>uint64 min_count = 4;</code> * @return This builder for chaining. */ public Builder clearMinCount() { minCount_ = 0L; onChanged(); return this; } private long requestHeight_ ; /** * <pre> * RequestHeight is block height that the request has been created * </pre> * * <code>int64 request_height = 5;</code> * @return The requestHeight. */ @java.lang.Override public long getRequestHeight() { return requestHeight_; } /** * <pre> * RequestHeight is block height that the request has been created * </pre> * * <code>int64 request_height = 5;</code> * @param value The requestHeight to set. * @return This builder for chaining. */ public Builder setRequestHeight(long value) { requestHeight_ = value; onChanged(); return this; } /** * <pre> * RequestHeight is block height that the request has been created * </pre> * * <code>int64 request_height = 5;</code> * @return This builder for chaining. */ public Builder clearRequestHeight() { requestHeight_ = 0L; onChanged(); return this; } private long requestTime_ ; /** * <pre> * RequestTime is timestamp of the chain's block which contains the request * </pre> * * <code>uint64 request_time = 6;</code> * @return The requestTime. */ @java.lang.Override public long getRequestTime() { return requestTime_; } /** * <pre> * RequestTime is timestamp of the chain's block which contains the request * </pre> * * <code>uint64 request_time = 6;</code> * @param value The requestTime to set. * @return This builder for chaining. */ public Builder setRequestTime(long value) { requestTime_ = value; onChanged(); return this; } /** * <pre> * RequestTime is timestamp of the chain's block which contains the request * </pre> * * <code>uint64 request_time = 6;</code> * @return This builder for chaining. */ public Builder clearRequestTime() { requestTime_ = 0L; onChanged(); return this; } private java.lang.Object clientId_ = ""; /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @return The clientId. */ public java.lang.String getClientId() { java.lang.Object ref = clientId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); clientId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @return The bytes for clientId. */ public com.google.protobuf.ByteString getClientIdBytes() { java.lang.Object ref = clientId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); clientId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @param value The clientId to set. * @return This builder for chaining. */ public Builder setClientId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } clientId_ = value; onChanged(); return this; } /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @return This builder for chaining. */ public Builder clearClientId() { clientId_ = getDefaultInstance().getClientId(); onChanged(); return this; } /** * <pre> * ClientID is arbitrary id provided by requester. * It is used by client-side for referencing the request * </pre> * * <code>string client_id = 7 [(.gogoproto.customname) = "ClientID"];</code> * @param value The bytes for clientId to set. * @return This builder for chaining. */ public Builder setClientIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); clientId_ = value; onChanged(); return this; } private java.util.List<oracle.v1.Oracle.RawRequest> rawRequests_ = java.util.Collections.emptyList(); private void ensureRawRequestsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { rawRequests_ = new java.util.ArrayList<oracle.v1.Oracle.RawRequest>(rawRequests_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< oracle.v1.Oracle.RawRequest, oracle.v1.Oracle.RawRequest.Builder, oracle.v1.Oracle.RawRequestOrBuilder> rawRequestsBuilder_; /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public java.util.List<oracle.v1.Oracle.RawRequest> getRawRequestsList() { if (rawRequestsBuilder_ == null) { return java.util.Collections.unmodifiableList(rawRequests_); } else { return rawRequestsBuilder_.getMessageList(); } } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public int getRawRequestsCount() { if (rawRequestsBuilder_ == null) { return rawRequests_.size(); } else { return rawRequestsBuilder_.getCount(); } } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public oracle.v1.Oracle.RawRequest getRawRequests(int index) { if (rawRequestsBuilder_ == null) { return rawRequests_.get(index); } else { return rawRequestsBuilder_.getMessage(index); } } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder setRawRequests( int index, oracle.v1.Oracle.RawRequest value) { if (rawRequestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRawRequestsIsMutable(); rawRequests_.set(index, value); onChanged(); } else { rawRequestsBuilder_.setMessage(index, value); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder setRawRequests( int index, oracle.v1.Oracle.RawRequest.Builder builderForValue) { if (rawRequestsBuilder_ == null) { ensureRawRequestsIsMutable(); rawRequests_.set(index, builderForValue.build()); onChanged(); } else { rawRequestsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder addRawRequests(oracle.v1.Oracle.RawRequest value) { if (rawRequestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRawRequestsIsMutable(); rawRequests_.add(value); onChanged(); } else { rawRequestsBuilder_.addMessage(value); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder addRawRequests( int index, oracle.v1.Oracle.RawRequest value) { if (rawRequestsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureRawRequestsIsMutable(); rawRequests_.add(index, value); onChanged(); } else { rawRequestsBuilder_.addMessage(index, value); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder addRawRequests( oracle.v1.Oracle.RawRequest.Builder builderForValue) { if (rawRequestsBuilder_ == null) { ensureRawRequestsIsMutable(); rawRequests_.add(builderForValue.build()); onChanged(); } else { rawRequestsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder addRawRequests( int index, oracle.v1.Oracle.RawRequest.Builder builderForValue) { if (rawRequestsBuilder_ == null) { ensureRawRequestsIsMutable(); rawRequests_.add(index, builderForValue.build()); onChanged(); } else { rawRequestsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder addAllRawRequests( java.lang.Iterable<? extends oracle.v1.Oracle.RawRequest> values) { if (rawRequestsBuilder_ == null) { ensureRawRequestsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, rawRequests_); onChanged(); } else { rawRequestsBuilder_.addAllMessages(values); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder clearRawRequests() { if (rawRequestsBuilder_ == null) { rawRequests_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { rawRequestsBuilder_.clear(); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public Builder removeRawRequests(int index) { if (rawRequestsBuilder_ == null) { ensureRawRequestsIsMutable(); rawRequests_.remove(index); onChanged(); } else { rawRequestsBuilder_.remove(index); } return this; } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public oracle.v1.Oracle.RawRequest.Builder getRawRequestsBuilder( int index) { return getRawRequestsFieldBuilder().getBuilder(index); } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public oracle.v1.Oracle.RawRequestOrBuilder getRawRequestsOrBuilder( int index) { if (rawRequestsBuilder_ == null) { return rawRequests_.get(index); } else { return rawRequestsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public java.util.List<? extends oracle.v1.Oracle.RawRequestOrBuilder> getRawRequestsOrBuilderList() { if (rawRequestsBuilder_ != null) { return rawRequestsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(rawRequests_); } } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public oracle.v1.Oracle.RawRequest.Builder addRawRequestsBuilder() { return getRawRequestsFieldBuilder().addBuilder( oracle.v1.Oracle.RawRequest.getDefaultInstance()); } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public oracle.v1.Oracle.RawRequest.Builder addRawRequestsBuilder( int index) { return getRawRequestsFieldBuilder().addBuilder( index, oracle.v1.Oracle.RawRequest.getDefaultInstance()); } /** * <pre> * RawRequests is a list of raw requests specified by execution of oracle * script * </pre> * * <code>repeated .oracle.v1.RawRequest raw_requests = 8 [(.gogoproto.nullable) = false];</code> */ public java.util.List<oracle.v1.Oracle.RawRequest.Builder> getRawRequestsBuilderList() { return getRawRequestsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< oracle.v1.Oracle.RawRequest, oracle.v1.Oracle.RawRequest.Builder, oracle.v1.Oracle.RawRequestOrBuilder> getRawRequestsFieldBuilder() { if (rawRequestsBuilder_ == null) { rawRequestsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< oracle.v1.Oracle.RawRequest, oracle.v1.Oracle.RawRequest.Builder, oracle.v1.Oracle.RawRequestOrBuilder>( rawRequests_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); rawRequests_ = null; } return rawRequestsBuilder_; } private oracle.v1.Oracle.IBCChannel ibcChannel_; private com.google.protobuf.SingleFieldBuilderV3< oracle.v1.Oracle.IBCChannel, oracle.v1.Oracle.IBCChannel.Builder, oracle.v1.Oracle.IBCChannelOrBuilder> ibcChannelBuilder_; /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> * @return Whether the ibcChannel field is set. */ public boolean hasIbcChannel() { return ibcChannelBuilder_ != null || ibcChannel_ != null; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> * @return The ibcChannel. */ public oracle.v1.Oracle.IBCChannel getIbcChannel() { if (ibcChannelBuilder_ == null) { return ibcChannel_ == null ? oracle.v1.Oracle.IBCChannel.getDefaultInstance() : ibcChannel_; } else { return ibcChannelBuilder_.getMessage(); } } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ public Builder setIbcChannel(oracle.v1.Oracle.IBCChannel value) { if (ibcChannelBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ibcChannel_ = value; onChanged(); } else { ibcChannelBuilder_.setMessage(value); } return this; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ public Builder setIbcChannel( oracle.v1.Oracle.IBCChannel.Builder builderForValue) { if (ibcChannelBuilder_ == null) { ibcChannel_ = builderForValue.build(); onChanged(); } else { ibcChannelBuilder_.setMessage(builderForValue.build()); } return this; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ public Builder mergeIbcChannel(oracle.v1.Oracle.IBCChannel value) { if (ibcChannelBuilder_ == null) { if (ibcChannel_ != null) { ibcChannel_ = oracle.v1.Oracle.IBCChannel.newBuilder(ibcChannel_).mergeFrom(value).buildPartial(); } else { ibcChannel_ = value; } onChanged(); } else { ibcChannelBuilder_.mergeFrom(value); } return this; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ public Builder clearIbcChannel() { if (ibcChannelBuilder_ == null) { ibcChannel_ = null; onChanged(); } else { ibcChannel_ = null; ibcChannelBuilder_ = null; } return this; } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ public oracle.v1.Oracle.IBCChannel.Builder getIbcChannelBuilder() { onChanged(); return getIbcChannelFieldBuilder().getBuilder(); } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ public oracle.v1.Oracle.IBCChannelOrBuilder getIbcChannelOrBuilder() { if (ibcChannelBuilder_ != null) { return ibcChannelBuilder_.getMessageOrBuilder(); } else { return ibcChannel_ == null ? oracle.v1.Oracle.IBCChannel.getDefaultInstance() : ibcChannel_; } } /** * <pre> * IBCChannel is an IBC channel info of the other chain, which contains a * channel and a port to allow bandchain connect to that chain. This field * allows other chain be able to request data from bandchain via IBC. * </pre> * * <code>.oracle.v1.IBCChannel ibc_channel = 9 [(.gogoproto.customname) = "IBCChannel"];</code> */ private com.google.protobuf.SingleFieldBuilderV3< oracle.v1.Oracle.IBCChannel, oracle.v1.Oracle.IBCChannel.Builder, oracle.v1.Oracle.IBCChannelOrBuilder> getIbcChannelFieldBuilder() { if (ibcChannelBuilder_ == null) { ibcChannelBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< oracle.v1.Oracle.IBCChannel, oracle.v1.Oracle.IBCChannel.Builder, oracle.v1.Oracle.IBCChannelOrBuilder>( getIbcChannel(), getParentForChildren(), isClean()); ibcChannel_ = null; } return ibcChannelBuilder_; } private long executeGas_ ; /** * <pre> * ExecuteGas is amount of gas to reserve for executing * </pre> * * <code>uint64 execute_gas = 10;</code> * @return The executeGas. */ @java.lang.Override public long getExecuteGas() { return executeGas_; } /** * <pre> * ExecuteGas is amount of gas to reserve for executing * </pre> * * <code>uint64 execute_gas = 10;</code> * @param value The executeGas to set. * @return This builder for chaining. */ public Builder setExecuteGas(long value) { executeGas_ = value; onChanged(); return this; } /** * <pre> * ExecuteGas is amount of gas to reserve for executing * </pre> * * <code>uint64 execute_gas = 10;</code> * @return This builder for chaining. */ public Builder clearExecuteGas() { executeGas_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:oracle.v1.Request) } // @@protoc_insertion_point(class_scope:oracle.v1.Request) private static final oracle.v1.Oracle.Request DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new oracle.v1.Oracle.Request(); } public static oracle.v1.Oracle.Request getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Request> PARSER = new com.google.protobuf.AbstractParser<Request>() { @java.lang.Override public Request parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Request(input, extensionRegistry); } }; public static com.google.protobuf.Parser<Request> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Request> getParserForType() { return PARSER; } @java.lang.Override public oracle.v1.Oracle.Request getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import pytest import numpy as np from numpy.testing import assert_equal from numpy.testing.utils import assert_allclose try: import scipy # pylint: disable=W0611 except ImportError: HAS_SCIPY = False else: HAS_SCIPY = True from ..jackknife import jackknife_resampling, jackknife_stats def test_jackknife_resampling(): data = np.array([1, 2, 3, 4]) answer = np.array([[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]]) assert_equal(answer, jackknife_resampling(data)) # test jackknife stats, except confidence interval @pytest.mark.skipif('not HAS_SCIPY') def test_jackknife_stats(): # Test from the third example of Ref.[3] data = np.array((115, 170, 142, 138, 280, 470, 480, 141, 390)) # true estimate, bias, and std_err answer = (258.4444, 0.0, 50.25936) assert_allclose(answer, jackknife_stats(data, np.mean)[0:3], atol=1e-4) # test jackknife stats, including confidence intervals @pytest.mark.skipif('not HAS_SCIPY') def test_jackknife_stats_conf_interval(): # Test from the first example of Ref.[3] data = np.array([48, 42, 36, 33, 20, 16, 29, 39, 42, 38, 42, 36, 20, 15, 42, 33, 22, 20, 41, 43, 45, 34, 14, 22, 6, 7, 0, 15, 33, 34, 28, 29, 34, 41, 4, 13, 32, 38, 24, 25, 47, 27, 41, 41, 24, 28, 26, 14, 30, 28, 41, 40]) data = np.reshape(data, (-1, 2)) data = data[:, 1] # true estimate, bias, and std_err answer = (113.7862, -4.376391, 22.26572) # calculate the mle of the variance (biased estimator!) def mle_var(x): return np.sum((x - np.mean(x))*(x - np.mean(x)))/len(x) assert_allclose(answer, jackknife_stats(data, mle_var, 0.95)[0:3], atol=1e-4) # test confidence interval answer = np.array((70.14615, 157.42616)) assert_allclose(answer, jackknife_stats(data, mle_var, 0.95)[3], atol=1e-4)
def accent_1(self) -> RgbColor: return self._colors.get(ColorScheme._COLOR_ACCENT_1, None) or self.foreground
<reponame>Rasoul-Jahanshahi/Hardware_Performance_Counters_Can_Detect_Malware_Myth_or_Fact import learn_all_boyou, learn_1k_cv, \ logging, sys, random, os, time, json, itertools import numpy as np from sklearn.model_selection import StratifiedKFold class learn_1k_cv_optimization(learn_1k_cv.learn_1k_cv): def setup_classifiers(self): """ setup_classifiers only generate the classifier class objects. nothing more. Note that KNeighborsClassifier is inherited from learn_all_boyou instead of sklearn (learn_all_boyou inherits the implements from sklearn). """ # self.names = [\ # "Nearest Neighbors", \ # "Decision Tree", \ # "Random Forest", \ # "AdaBoost", \ # "Naive Bayes",\ # "Neural Net" \ # #### "Logistic Regression",\ # #### "Linear SVM", "Rbf SVM", "Poly SVM", "Sigmoid SVM"\ # ####, "Gaussian Process" # ] max_iterations = 1000 # self.classifiers = [ \ # learn_all_boyou.KNeighborsClassifier(\ # n_neighbors=7, weights='uniform', algorithm='auto', n_jobs=-1),\ # learn_all_boyou.DecisionTreeClassifier(\ # max_depth=17, min_samples_split=12, min_samples_leaf=12,\ # presort=True, max_features=None,\ # random_state=int(round(time.time()))),\ # learn_all_boyou.RandomForestClassifier(max_depth=100, min_samples_split=12,\ # min_samples_leaf=12, \ # n_estimators=100, max_features=None,\ # random_state=int(round(time.time()))), \ # learn_all_boyou.AdaBoostClassifier(algorithm='SAMME.R', n_estimators=200, \ # random_state=int(round(time.time()))),\ # learn_all_boyou.GaussianNB(priors=[0.5, 0.5]),\ # learn_all_boyou.MLPClassifier(hidden_layer_sizes=(100,100,100,100), \ # alpha=100, solver='lbfgs',\ # max_iter=max_iterations,\ # activation='tanh', tol=1e-5,\ # warm_start='True') \ # #### LogisticRegression(penalty='l2', tol=1e-4, C=1e2,\ # #### fit_intercept=True, solver='lbfgs', \ # #### class_weight='balanced', max_iter=max_iterations), \ # #### SVC(kernel="linear", C=1e2, tol=1e-4, max_iter=max_iterations,\ # #### probability= True),\ # #### SVC(kernel="rbf", C=1e2, tol=1e-4, max_iter=max_iterations,\ # #### probability=True, shrinking=True), # #### SVC(kernel="poly", C=1e2, degree=4, tol=1e-4,\ # #### max_iter=max_iterations, probability=True),\ # #### SVC(kernel="sigmoid", C=1e2, gamma=1e-1, tol=1e-3, \ # #### max_iter=max_iterations, probability=True, \ # #### shrinking=True)#,\ # #### GaussianProcessClassifier(1.0 * RBF(1.0), n_jobs=-1, \ # #### copy_X_train=False, \ # #### max_iter_predict=100, warm_start=False )\ # ] self.classifiers = list(\ itertools.chain(\ [learn_all_boyou.KNeighborsClassifier(\ n_neighbors=parameter_i, \ weights='uniform', \ algorithm='auto', \ n_jobs=-1) \ for parameter_i in list(xrange(38, 68, 3))],\ [learn_all_boyou.DecisionTreeClassifier(\ max_depth=parameter_i, \ min_samples_split=12, \ min_samples_leaf=12,\ presort=True, max_features=None,\ random_state=int(round(time.time()))) \ for parameter_i in list(xrange(35, 45, 1))],\ [learn_all_boyou.RandomForestClassifier(\ max_depth=parameter_i, \ min_samples_split=12,\ min_samples_leaf=12, \ n_estimators=100, max_features=None,\ random_state=int(round(time.time()))) \ for parameter_i in list(xrange(30, 40, 1))],\ [learn_all_boyou.AdaBoostClassifier(\ algorithm='SAMME.R', \ n_estimators=parameter_i, \ random_state=int(round(time.time()))) for parameter_i in list(xrange(300, 1300, 100))],\ [learn_all_boyou.GaussianNB(\ priors=[0.5, 0.5])],\ [learn_all_boyou.MLPClassifier(\ hidden_layer_sizes=(parameter_i,parameter_i,parameter_i), \ alpha = 5, \ solver='lbfgs',\ max_iter=max_iterations,\ activation='tanh', tol=1e-5,\ warm_start='True') \ for parameter_i in list(xrange(3, 53, 5))]\ )\ ) self.names = list (\ itertools.chain(\ ["Nearest Neighbors: " + \ json.dumps(self.classifiers[parameter_i].get_params()) \ for parameter_i in list(xrange(0, 10))],\ ["Decision Tree: " + \ json.dumps(self.classifiers[parameter_i].get_params()) \ for parameter_i in list(xrange(10, 20))],\ ["Random Forest: " + \ json.dumps(self.classifiers[parameter_i].get_params()) \ for parameter_i in list(xrange(20, 30))],\ ["AdaBoost: " + \ json.dumps(self.classifiers[parameter_i].get_params()) \ for parameter_i in list(xrange(30, 40))],\ ["Naive Bayes: " + \ json.dumps(self.classifiers[40].get_params())], \ ["Neural Net: " + \ json.dumps(self.classifiers[parameter_i].get_params()) \ for parameter_i in list(xrange(41, 51))]\ )\ ) def classic_cross_validation(self): """ This function does 10 fold split for self.data and its label :class:`learn_all_boyou`. Data and label will be shuffled. The data and label is splited with granularity of single feature vector. :param dict self.report: simulation report dictionary :param array self.X_train: Training array :param array self.X_test: Testing array :param array self.y_train: Training label :param array self.y_test: Testing label :param list prediction: prediction results :param list predict_proba: prediction confidence """ self.logger.info('Start to cross validate ...') self.load_data() self.setup_classifiers() self.report = {} # random shuffling zipped_list = zip(self.data, self.label) random.shuffle(zipped_list) self.data, self.label = zip(*zipped_list) self.data = np.array(list(self.data)) self.label = np.array(list(self.label)) # 10 fold split cv = StratifiedKFold(n_splits = 10) experiment_path = self.result_path zipped_clfs = zip(self.names, self.classifiers) #for names, clf in zip(self.names, self.classifiers): names, clf = zipped_clfs[int(sys.argv[1].split('/')[-1])] self.logger.info(names + " in process ....") count = 0 for train_idx, test_idx in cv.split(self.data, self.label): self.X_train, self.X_test = self.data[train_idx], self.data[test_idx] self.y_train, self.y_test = self.label[train_idx], self.label[test_idx] clf.fit(self.X_train, self.y_train) self.result_path = experiment_path + str(count) + '/' count += 1 if not os.path.isdir(self.result_path): self.logger.info(self.result_path + " new folder created ....") os.mkdir(self.result_path) else: self.logger.info(self.result_path + " old directory exists ....") if os.path.isfile(self.result_path + 'classification_report.txt'): self.logger.info(self.result_path + " old report exists ....") with open(self.result_path + 'classification_report.txt', 'r') as outfile: self.report = json.load(outfile) outfile.close() self.prediction = clf.predict(self.X_test) self.text_class_report(names) self.predict_proba = clf.predict_proba(self.X_test) self.roc_curve_report(names) self.logger.info(names + " testing completed!") if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger_handler = logging.StreamHandler() logger_handler.setFormatter(\ logging.Formatter('%(asctime)s [%(levelname)s]\ %(filename)s [%(lineno)d]: %(funcName)s(): %(message)s')) logger.addHandler(logger_handler) learn1 = learn_1k_cv_optimization(logger, \ data_path_prefix='../amd_data/') #data_path_prefix='/home/bobzhou/2017_summer/data_analysis/amd_data_analysis/') learn1.result_path = sys.argv[1] + '/' logger.info("files will be saved in the following path: " + learn1.result_path) #learn1.run() learn1.classic_cross_validation() #learn1.test_rasoul()
// GEPTypeBridgeIterator // // #ifndef SVF_GEPTYPEBRIDGEITERATOR_H #define SVF_GEPTYPEBRIDGEITERATOR_H #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Operator.h" #include "llvm/IR/User.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/IR/GetElementPtrTypeIterator.h" namespace llvm { template<typename ItTy = User::const_op_iterator> class generic_bridge_gep_type_iterator : public std::iterator<std::forward_iterator_tag, Type *, ptrdiff_t> { typedef std::iterator<std::forward_iterator_tag,Type *, ptrdiff_t> super; ItTy OpIt; PointerIntPair<Type *,1> CurTy; unsigned AddrSpace; generic_bridge_gep_type_iterator() {} public: static generic_bridge_gep_type_iterator begin(Type *Ty, ItTy It) { generic_bridge_gep_type_iterator I; I.CurTy.setPointer(Ty); I.OpIt = It; return I; } static generic_bridge_gep_type_iterator begin(Type *Ty, unsigned AddrSpace, ItTy It) { generic_bridge_gep_type_iterator I; I.CurTy.setPointer(Ty); I.CurTy.setInt(true); I.AddrSpace = AddrSpace; I.OpIt = It; return I; } static generic_bridge_gep_type_iterator end(ItTy It) { generic_bridge_gep_type_iterator I; I.OpIt = It; return I; } bool operator==(const generic_bridge_gep_type_iterator& x) const { return OpIt == x.OpIt; } bool operator!=(const generic_bridge_gep_type_iterator& x) const { return !operator==(x); } Type *operator*() const { if ( CurTy.getInt() ) return CurTy.getPointer()->getPointerTo(AddrSpace); return CurTy.getPointer(); } Type *getIndexedType() const { assert(false && "needs to be refactored"); if ( CurTy.getInt() ) return CurTy.getPointer(); #if LLVM_VERSION_MAJOR >= 11 Type * CT = CurTy.getPointer(); if (auto ST = dyn_cast<StructType>(CT)) return ST->getTypeAtIndex(getOperand()); else if (auto Array = dyn_cast<ArrayType>(CT)) return Array->getElementType(); else if (auto Vector = dyn_cast<VectorType>(CT)) return Vector->getElementType(); else return CT; #else CompositeType *CT = llvm::cast<CompositeType>( CurTy.getPointer() ); return CT->getTypeAtIndex(getOperand()); #endif } // non-standard operators, these may not need be bridged but seems it's // predunt to do so... Type *operator->() const { return operator*(); } Value *getOperand() const { return const_cast<Value*>(&**OpIt); } generic_bridge_gep_type_iterator& operator++() { if ( CurTy.getInt() ) { CurTy.setInt(false); } #if LLVM_VERSION_MAJOR >= 11 else if ( Type * CT = CurTy.getPointer() ) { if (auto ST = dyn_cast<StructType>(CT)) CurTy.setPointer(ST->getTypeAtIndex(getOperand())); else if (auto Array = dyn_cast<ArrayType>(CT)) CurTy.setPointer(Array->getElementType()); else if (auto Vector = dyn_cast<VectorType>(CT)) CurTy.setPointer(Vector->getElementType()); else CurTy.setPointer(nullptr); } #else else if ( CompositeType * CT = dyn_cast<CompositeType>(CurTy.getPointer()) ) { CurTy.setPointer(CT->getTypeAtIndex(getOperand())); } #endif else { CurTy.setPointer(nullptr); } ++OpIt; return *this; } generic_bridge_gep_type_iterator operator++(int) { generic_bridge_gep_type_iterator tmp = *this; ++*this; return tmp; } }; typedef generic_bridge_gep_type_iterator<> bridge_gep_iterator; inline bridge_gep_iterator bridge_gep_begin(const User* GEP) { auto *GEPOp = llvm::cast<GEPOperator>(GEP); return bridge_gep_iterator::begin(GEPOp->getSourceElementType(), llvm::cast<PointerType>(GEPOp->getPointerOperandType()->getScalarType())->getAddressSpace(), GEP->op_begin() + 1); } inline bridge_gep_iterator bridge_gep_end(const User* GEP) { return bridge_gep_iterator::end(GEP->op_end()); } inline bridge_gep_iterator bridge_gep_begin(const User &GEP) { auto &GEPOp = llvm::cast<GEPOperator>(GEP); return bridge_gep_iterator::begin( GEPOp.getSourceElementType(), llvm::cast<PointerType>(GEPOp.getPointerOperandType()->getScalarType())->getAddressSpace(), GEP.op_begin() + 1); } inline bridge_gep_iterator bridge_gep_end(const User &GEP) { return bridge_gep_iterator::end(GEP.op_end()); } template<typename T> inline generic_bridge_gep_type_iterator<const T*> bridge_gep_end( Type * /*Op0*/, ArrayRef<T> A ) { return generic_bridge_gep_type_iterator<const T*>::end(A.end()); } } // End namespace llvm #endif
Development of reflex-adaptive organizational structure of high robustness One of the modern problems of business is the robustness of daily operations of company. Real productive industries permanently face the dramatic changes in the characteristics of the external environment which causes the explosive growth of risk situations that can lead to considerable damages and losses. That is why in modern management a significant place is occupied by methods called “risk management” designed to predict the emergence of negative situations and develop on this basis the protective measures. The purpose of the article is to equip developers of organizational structures, managers and participants of the construction process with not a complex but with the effective methodology of developing of organizational structures with high resistance qualities to the impact of external and internal environment based on the analysis of the reflex-adaptive qualities of the organizational structure of the investment and construction project. Overall, such method allows to express quantitatively the characteristics of the project structure’s elements for scoping the resistance qualities of the organizational structure of the investment and construction project. This article offers another method for improving robustness of the operating of the business structures based on modern concepts of informatics and the management of information flows. In work, the factors of robustness, sustainability and persistence of organizational structures of the investment and construction project are revealed and systematized. The life cycle of the investment and construction project is considered as a sequence of changes in the organizational structure which consists of a set of functional production-oriented units linked by technological, logistical and other processes synchronized in time. The article also offers the use of a mathematical model of the sustainability of the organizational structure under single impact of an external disturbance which allows us to determine the most loaded element of the system. The article provides a clear concept of the resistance qualities: robustness, sustainability and persistence of organizational structures based on the specific features of interaction of external and internal factors of the organizational structure as a system with elements of the organizational structure. Thus, for providing the maximum robustness of the structure is necessary to ensure the permanence of the internal environment of the system, that is, in any change in pragmatic information about the state of the internal environment an appropriate action is taken to counter negative impacts. For providing the robustness of the organizational structure, the reaction time of the system should not be less than the time of the disturbing effect change. Persistence is determined by the numerical value of factors affecting on the elements of the system. Overall, this article could be interesting to a wide range of specialists engaged in system design and allows us to consider solutions of system resistance from the modern positions of informatics. Abstract. One of the modern problems of business is the robustness of daily operations of company. Real productive industries permanently face the dramatic changes in the characteristics of the external environment which causes the explosive growth of risk situations that can lead to considerable damages and losses. That is why in modern management a significant place is occupied by methods called "risk management" designed to predict the emergence of negative situations and develop on this basis the protective measures. The purpose of the article is to equip developers of organizational structures, managers and participants of the construction process with not a complex but with the effective methodology of developing of organizational structures with high resistance qualities to the impact of external and internal environment based on the analysis of the reflex-adaptive qualities of the organizational structure of the investment and construction project. Overall, such method allows to express quantitatively the characteristics of the project structure's elements for scoping the resistance qualities of the organizational structure of the investment and construction project. This article offers another method for improving robustness of the operating of the business structures based on modern concepts of informatics and the management of information flows. In work, the factors of robustness, sustainability and persistence of organizational structures of the investment and construction project are revealed and systematized. The life cycle of the investment and construction project is considered as a sequence of changes in the organizational structure which consists of a set of functional production-oriented units linked by technological, logistical and other processes synchronized in time. The article also offers the use of a mathematical model of the sustainability of the organizational structure under single impact of an external disturbance which allows us to determine the most loaded element of the system. The article provides a clear concept of the resistance qualities: robustness, sustainability and persistence of organizational structures based on the specific features of interaction of external and internal factors of the organizational structure as a system with elements of the organizational structure. Thus, for providing the maximum robustness of the structure is necessary to ensure the permanence of the internal environment of the system, that is, in any change in pragmatic information about the state of the internal environment an appropriate action is taken to counter negative impacts. For providing the robustness of the organizational structure, the reaction time of the system should not be less than the time of the disturbing effect change. Persistence is determined by the numerical value of factors affecting on the elements of the system. Overall, this article could be interesting to a wide range of specialists engaged in system design and allows us to consider solutions of system resistance from the modern positions of informatics. Introduction The urgent tasks of developing and implementing highly effective organizational production structures are determined by ever increasing demands for obtaining additional competitive advantages in the commodity and production markets of various economic systems. The solution of this problem accompanies the progress of industrial production at all stages of the productive forces. Along with the improvement of technology, the introduction of modern production machines and the enhancement of personnel internal relations which are determined by the organizational structure of company are developing. The need to provide the designed organizational structures with resisting properties to the negative impacts of the external environment is caused by increasing risks and dramatic changes in the conditions in which the productive activities of enterprises and companies are realized. The intention to protect your business under the economic and social turbulence forces the production managers to solve this problem by thoroughly studying the properties of modern organizational structures in order to reveal the patterns of interaction of the organizational structure with the environment that determine the guaranteed operation of organizational structures throughout the range of changes in the properties of the external environment. In works the one of the possible highly effective organizational structures of the investment and construction project possessing high qualities of robustness, sustainability and persistence is shown. This article continues to consider the ways of studying the properties of the reflex-adaptive structure with the purpose of improving the robustness of its operability, sustainability and persistence under the influence of negative environmental factors . Despite some kind of similarity in terms of robustness, sustainability and persistence it is in the interest of analytical work to determine precisely what exactly is meant by these terms. First, by them we will not designate any abstract concepts, but specific properties of the system characterized not only by qualitative but also by numerical values. So under the robustness we will understand the probability of the system to ensure its functioning with a given quality in a static field of influence when the characteristics of the internal environment are changing. This definition (probability of failure-free operation) is written as follows in technology t -operation time of the product. As indicated the determination of the robustness of a technical product is not very difficult: it is necessary to determine the value of f(x), which is achieved by calculation or empirically. Such approach to determining the robustness of the socio-economic system, which is an industrial organization, is absolutely unacceptable. As shown in works the stability of the internal environment of the system is the determining factor of its reliable functioning under the condition of a stationary external environment that does not exceed the calculated values of its parameters. The condition for reliable operation of the system is the ratio: Where: I -pragmatic information about the state of the internal environment of the system. Rresource designed to reflect the changes in the internal environment. Let's analyze this ratio in details. In this ratio "I" is the pragmatic information, the concept of which was introduced by the Russian scientist A. Kharkevich. The value of pragmatic information determines as the difference in the probability of achieving the goal by the system before receiving information and after receiving it: Where: 1 P -the probability of achieving the goal by the system after receiving information; 0 P -the probability of achieving the goal by the system before receiving information. The question may arise, what kind of resource "R" should be used to parry negative environmental impacts on the organizational system. Generally, organization's management system recommends using that kind of resource which caused the negative impact. But the main universal resource is funds. To fulfill this condition a mechanism for analyzing the current information should be created and on the basis of its conclusions appropriate solutions should be made. Organizational structure of the reflex-adaptive type easily copes with this task. Sustainability will determine as the property of the system to maintain its efficiency in conditions of constancy of the internal environment under external influence the rate of change of which is commensurate with the speed of the system's response to this impact. Persistence determines the probability of the system to ensure its operability in conditions of exceeding the calculated values of the environmental impact while the internal environment is constant. Such a gradation of resistive properties of the organizational structure based on the assessment of the state of the properties of the external and internal environment of the system is most objective and universal and allows the detailed characterization of the structure properties. In the system of interaction of objects "organizational structure of the project" and "external environment" the main features of interacting systems are highlighted. First, we consider the life cycle of an investment and construction project as a set of its functional, production-oriented blocks connected by technological, logistical and other processes synchronized in time. Using the adopted project life cycle into stages and guided by the order of the works caused by the project matrix we see that each stage of the project life cycle has its own organizational structure inherent only in this project for this stage. We draw attention to the fact that depending on the task of the study a greater detail of the functional blocks of the project is possible. Also, a more detailed decomposition of the organizational structure over time is possible which allow us to speak of scaling the organizational structure as a convenient method of research. Considering the life cycle of the investment and construction project as a sequence of changes in the organizational structure we come to the conclusion that this is the main feature of the reflex-adaptive organizational structure. This gives us an understanding that under the same external influences the reaction of the organizational structure of the project will be different and the degree of its efficiency will correlate with the current changes in the structure. Mathematical model of persistence of organizational structure assumes exact knowledge and an estimation of robustness of elements of system at influence of external indignation. The definition of the digital expression of the robustness of the element of the system which is an integral part of the investment and construction project is a very difficult task: this element is not a machine, mechanism or a combination of them. Elements of the project are its participants: individuals, work communities of various complexity and composition, companies and organizations associated with the external and internal environment with incalculable connections. Nevertheless, it is highly desirable to express quantitatively the qualitative characteristics of the elements of the project structure for carrying out an analytical study of the persistence of the organizational structure as a whole. Many researches are subordinated to this task today not only in the construction complex, but primarily in the financial and banking business -wherever a partner wants to assess the robustness of his partner . Today there are various methods for assessing the financial, payment, organizational and technological robustness of companies which adequately reflect the real quality of the activities of companies. These methods are based on expert assessments of various aspects of a Material and moral incentives promoters of production 6. Existence of creative competitions by profession We will use this technology slightly modifying it in terms of accounting for the largest number of factors (Table 1.) affecting the robustness of company. Then the company robustness assessment will be: Where: N -company robustness in numerical expression; k  -factor determines the robustness of k-element of operation of company; T k -weighting factor of importance of k-element is the function of operation of company; t k -expert coefficient of robustness of k-element of company. Despite some subjectivity of the presented method of assessing the robustness of companies as an element of the organizational structure of the investment and construction project, its accuracy is All variety of environmental factors can be classified on the basis of their inherent certain universal characteristics. Abstracting from the explicit and individual characteristics of the types of external influences on the organizational structure as a system it is possible to distinguish such generally valid properties of external influences as: force of influence, duration of impact, rate of impact change. The threat of external influences to the organizational structure and its elements and also effects these interactions will produce are determined and ranked digitally on the basis of expert assessments and statistical observations. This methodology and practice are well known and widely used by risk management specialists. However, in our case this method should be significantly supplemented. The peculiarities are that if risk management techniques consider the impact object as an isolated system then when considering the organizational structure of the investment and construction project, it is necessary to take into account the complex nature of the system consisting of the block elements, which are simultaneously affected by external disturbances ( Table 2). These features complicate the process of investigating the organizational structure, but, at the same time, increase the accuracy of research and the behavior of the system under specific operating conditions. This digraph illustrates the preparatory phase of the life cycle of investment and construction project which is in the fact that the "O" block having formed the concept of investment and construction project entrusts its detailed elaboration to the "I" block, which in turn sends its requirements to the respective blocks in order to develop the design specification. Investigation of the persistence of the organizational structure will be carried out by the method of simulation modeling, acting alternately on each element of the system, determining the propagation of the disturbance along the system and highlighting in each step of the impact a decrease in the robustness of each element. The simulation modeling of the stability of the organizational structure of the digraph G = (V,X), which describes the interrelation between the elements "O", "F", "L", "T", "I", "P", reduces to calculating the numerical values of the weights of the vertices of the graph , which characterize the robustness of the elements in , i.e. When passing through the impulse action, which is given by the ratio: These formulas specify the changes in the weights of the vertices of the graph G = (V, X), thereby determining the dynamics of the propagation of the external impact across the system. Thus, the presented method of recording and forming the properties of the resistivity of the organizational structure to the negative influences of environmental factors makes it possible to predict the response of the system to perturbing environmental influences at the design stage of the reflex-adaptive organizational structure. This makes it possible to take preventive measures to increase the resilience of the organizational structure to external influences, as well as to calculate the necessary resource for parrying possible risk situations.
from distutils.version import LooseVersion from pathlib import Path from tempfile import TemporaryDirectory from common_helper_yara.common import get_yara_version from common_helper_yara.yara_compile import compile_rules from common_helper_yara.yara_scan import scan DIR_OF_CURRENT_FILE = Path(__file__).parent COMPILED_FLAG = get_yara_version() >= LooseVersion('3.9') def test_compile_and_scan(): with TemporaryDirectory(prefix="common_helper_yara_test_") as tmp_dir: input_dir = DIR_OF_CURRENT_FILE / 'data/rules' signature_file = Path(tmp_dir) / 'test.yc' data_files = DIR_OF_CURRENT_FILE / 'data/data_files' compile_rules(input_dir, signature_file, external_variables={'test_flag': 'true'}) assert signature_file.exists(), "file not created" result = scan(signature_file, data_files, recursive=True, compiled=COMPILED_FLAG) assert 'lighttpd' in result.keys(), "at least one match missing" assert 'lighttpd_simple' in result.keys(), "at least one match missing"
Feature trailer for John Carter. From Academy Award–winning filmmaker Andrew Stanton comes John Carter—a sweeping action-adventure set on the mysterious and exotic planet of Barsoom (Mars). John Carter is based on a classic novel by Edgar Rice Burroughs, whose highly imaginative adventures served as inspiration for many filmmakers, both past and present. The film tells the story of war-weary, former military captain John Carter (Taylor Kitsch), who is inexplicably transported to Mars where he becomes reluctantly embroiled in a conflict of epic proportions amongst the inhabitants of the planet, including Tars Tarkas (Willem Dafoe) and the captivating Princess Dejah Thoris (Lynn Collins). In a world on the brink of collapse, Carter rediscovers his humanity when he realizes that the survival of Barsoom and its people rests in his hands.
<filename>commands/misc/miscellaneous.py from discord.ext import commands import statics import time import requests QUOTE_API = 'https://zenquotes.io/api/random' class Miscellaneous(commands.Cog, name='misc'): """ A set of miscellaneous commands for various purposes. """ def __init__(self, bot: commands.Bot): self.bot = bot @commands.command( brief="Check the bot's ping to your server.", help="Measures the duration between when a message is sent and it is received by discord." ) async def ping(self, ctx: commands.Context): before = time.monotonic() message = await ctx.send(embed=statics.get_embed('Pong!')) delta: int = round((time.monotonic() - before) * 1000) await message.edit(embed=statics.get_embed(f'Pong! `{delta} ms`')) @commands.command( brief='I need, motivation.', help='Get a motivating quote to inspire your ass off.' ) @commands.cooldown(1, 5, commands.BucketType.user) async def quote(self, ctx: commands.Context): response = requests.get(QUOTE_API).json() await ctx.send(embed=statics.get_embed(response[0]['q'], 'Here is a random quote for you')) def setup(bot: commands.Bot): bot.add_cog(Miscellaneous(bot))
/** * Compares all differences with the referenceSequence in order to reduce the stored sequence. * Also adds sequence for deletion differences. * * @param alignment The Alignment * @param referenceSequence Reference sequence * @param referenceSequenceStart Reference sequence start * @throws ShortReferenceSequenceException */ public static void completeDifferencesFromReference(Alignment alignment, String referenceSequence, long referenceSequenceStart) throws ShortReferenceSequenceException { int offset = (int) (alignment.getUnclippedStart() - referenceSequenceStart); String subRef; String subRead; if ((alignment.getFlags() & Alignment.SEGMENT_UNMAPPED) != 0) { return; } List<Alignment.AlignmentDifference> newDifferences = new LinkedList<>(); for(Alignment.AlignmentDifference alignmentDifference : alignment.getDifferences()){ Alignment.AlignmentDifference currentDifference = null; switch (alignmentDifference.getOp()){ case Alignment.AlignmentDifference.DELETION: try{ if(!alignmentDifference.isAllSequenceStored()){ subRef = referenceSequence.substring( alignmentDifference.getPos() + offset, alignmentDifference.getPos() + offset + alignmentDifference.getLength() ); alignmentDifference.setSeq( subRef ); } } catch (StringIndexOutOfBoundsException e){ throw new ShortReferenceSequenceException("ReferenceSequence Out of Bounds in Alignment.completeDifferences()"); } currentDifference = alignmentDifference; break; case Alignment.AlignmentDifference.MATCH_MISMATCH: case Alignment.AlignmentDifference.MISMATCH: try{ subRef = referenceSequence.substring( alignmentDifference.getPos() + offset, alignmentDifference.getPos() + offset + alignmentDifference.getLength() ); } catch (StringIndexOutOfBoundsException e){ throw new ShortReferenceSequenceException("ReferenceSequence Out of Bounds in Alignment.completeDifferences()"); } subRead = alignmentDifference.getSeq(); newDifferences.addAll(getMismatchDiff(subRef, subRead, alignmentDifference.getPos())); break; case Alignment.AlignmentDifference.HARD_CLIPPING: /* subRef = referenceSequence.substring( alignmentDifference.getPos() + offset, alignmentDifference.getPos() + offset + alignmentDifference.getLength() ); alignmentDifference.setSeq(subRef);*/ currentDifference = alignmentDifference; break; case Alignment.AlignmentDifference.SOFT_CLIPPING: currentDifference = alignmentDifference; try{ if(alignmentDifference.isAllSequenceStored()){ subRef = referenceSequence.substring( alignmentDifference.getPos() + offset, alignmentDifference.getPos() + offset + alignmentDifference.getLength() ); if(subRef.equals(alignmentDifference.getSeq())){ currentDifference.setSeq(null); } } } catch (StringIndexOutOfBoundsException e){ This Soft clipping difference will not be compacted. It's not a bug, just a feature. TODO: Check for 2.0 version } break; offset -= alignmentDifference.getLength(); case Alignment.AlignmentDifference.INSERTION: case Alignment.AlignmentDifference.PADDING: case Alignment.AlignmentDifference.SKIPPED_REGION: currentDifference = alignmentDifference; break; } if(currentDifference != null){ newDifferences.add(currentDifference); } } alignment.setDifferences(newDifferences); }
He’s been this way for over an hour, and as word’s gotten out the audience has swelled to over 30,000. As Overwatch’s creative director, Jeff Kaplan has spoken in the past about how dedicated the team is to supporting the game and engaging with the community, even if that means working holidays. The Twitch stream opened a couple hours ago on an empty chair. A few minutes later Kaplan walked in and sat down. He’s been there ever since, sometimes crossing his legs, sometimes uncrossing them, and always looking, watching, waiting. And lest anyone think the stream is somehow a small segment of footage on loop, there have been a few weird moments sprinkled throughout, including one where Jeff gets booped by an off camera boom mic. In the other, less action filled parts, you can feel time passing as the rate of Jeff blinking changes. Three different blinking speeds, we’ll call them long stare, short stare, and turbo eye lash flicking, have taken shape in the stream like the ghosts of Christmas past, present, and future. The Yule Log started as an annual holiday program in the late 60s at WPIX, a TV station in New York, so that the employees wouldn’t have to worry about working. Plus the people of New York City, many of whom didn’t have fire places, could have the warmth of a crackling fire beamed into their apartments. In recent years it’s become a meme of sorts, just like everything else. In 2015 Nick Offerman of Parks and Rec sipped whiskey for forty five minutes as part of one. The absurdity of it was supposed to help sell Lagavulin. Advertisement The Overwatch fans who have flooded the Twitch chat have been similarly intrigued and confused by the spectacle. It’s boring to the point of being impossible to look away. It’s actually the opposite of what this time of year’s supposed to be about. You should be having human interactions with other people. Catching up with family and friends. Not sitting with your phone or laptop transfixed by a motionless Jeff Kaplan. After all, what’s he doing there? What’s this all about? And most importantly how long will it go on? Like passersby at the zoo, the thousands who have tuned into the stream have set their expectations low. They’re not expecting some big, new Overwatch announcement, or an update on the game’s 2018 plans. The answers they’re seeking are more basic. “Do something,” is a common refrain you can see floating by in the chat log (which sometimes he does). As well as people begging him to eat some of the cookies nestled alongside a jar of milk on the table next to him. Advertisement But so far he’s just continued to sit and stare, perhaps pondering the future of the game or that email he forgot to respond to from a few days ago or maybe just the fact the how many Christmas Eves ago he never imagined where he’d be on December 24, 2017. [Update—2:35 p.m.]: After three hours Jeff breaks his silence. He says the milk is probably poisonous and the cookies are a lie. Also there’s nothing in the coffee mug, something he demonstrated by picking it up and turning it upside down. Someone off camera meanwhile told him he had to do this for another seven hours. This has led chants of “#freejeff” to break out in the Twitch chat as well as on Twitter, with skeptics still shouting “looped!” The designer said that working on Overwatch and making it better is his happy place, not sitting in front of a fireplace making eyes at the camera and puffing his mouth out. Still, he persists. Advertisement [Update—6:20 p.m.]: The stream is still live but now people have been watching long enough to detect particular moments when the feed appears to loop. While there are original skits peppered throughout the stream, like one where Jeff gets on his phone and starts playing Hearthstone, the performance always returns to a certain key set of movements, including the now iconic Jeff-spread. Advertisement While it’s possible the Overwatch director is just one of the most brilliant actors of our generation, it’s more likely that the stream is a compilation of prerecorded bits edited together into an extended video. Still, that hasn’t stopped thousands who have now spent hours watching, or at least had the stream on in the background (as any Yule Log program is intended to exist), and have convinced themselves Jeff really is just sitting in a studio all day on Christmas Eve. It is, after all, a time for believing in the impossible. Advertisement You can continue watching along in the stream below:
s = set([1,2,3]) A=int(input()) B=int(input()) C=[A,B] D=set(C) E=s-D F=list(E) ans=F[0] print(ans)
def clear(self): self._session.clear() self._used.clear()
/* * Copyright 2008-2009 Katholieke Universiteit Leuven * * Use of this software is governed by the GNU LGPLv2.1 license * * Written by Sven Verdoolaege, K.U.Leuven, Departement * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium */ #ifndef ISL_LIST_H #define ISL_LIST_H #include <isl/ctx.h> #include <isl/printer.h> #if defined(__cplusplus) extern "C" { #endif #define ISL_DECLARE_LIST(EL) \ struct isl_##EL; \ struct isl_##EL##_list; \ typedef struct isl_##EL##_list isl_##EL##_list; \ isl_ctx *isl_##EL##_list_get_ctx(__isl_keep isl_##EL##_list *list); \ __isl_give isl_##EL##_list *isl_##EL##_list_from_##EL( \ __isl_take struct isl_##EL *el); \ __isl_give isl_##EL##_list *isl_##EL##_list_alloc(isl_ctx *ctx, int n); \ __isl_give isl_##EL##_list *isl_##EL##_list_copy( \ __isl_keep isl_##EL##_list *list); \ void *isl_##EL##_list_free(__isl_take isl_##EL##_list *list); \ __isl_give isl_##EL##_list *isl_##EL##_list_add( \ __isl_take isl_##EL##_list *list, \ __isl_take struct isl_##EL *el); \ __isl_give isl_##EL##_list *isl_##EL##_list_concat( \ __isl_take isl_##EL##_list *list1, \ __isl_take isl_##EL##_list *list2); \ int isl_##EL##_list_n_##EL(__isl_keep isl_##EL##_list *list); \ __isl_give struct isl_##EL *isl_##EL##_list_get_##EL( \ __isl_keep isl_##EL##_list *list, int index); \ int isl_##EL##_list_foreach(__isl_keep isl_##EL##_list *list, \ int (*fn)(__isl_take struct isl_##EL *el, void *user), \ void *user); \ __isl_give isl_printer *isl_printer_print_##EL##_list( \ __isl_take isl_printer *p, __isl_keep isl_##EL##_list *list); \ void isl_##EL##_list_dump(__isl_keep isl_##EL##_list *list); ISL_DECLARE_LIST(basic_set) ISL_DECLARE_LIST(set) ISL_DECLARE_LIST(aff) ISL_DECLARE_LIST(pw_aff) ISL_DECLARE_LIST(band) #if defined(__cplusplus) } #endif #endif
/** * Stores the specified field handler. This field will be added to the * internally maintained form object. The component that is associated with * the field handler will also be accessible by the * {@link #getComponent(String)} and * {@link #getComponentHandler(String)} methods. * * @param name the name of the field * @param fld the field handler */ public void storeFieldHandler(String name, FieldHandler fld) { getComponentStore().addFieldHandler(name, fld); storeComponentHandler(name, fld.getComponentHandler()); }
package export import ( "encoding/json" "errors" "fmt" "net/url" "strings" "github.com/treeverse/lakefs/block" "github.com/treeverse/lakefs/logging" "github.com/treeverse/lakefs/parade" ) const actorName parade.ActorID = "EXPORT" type Handler struct { adapter block.Adapter } func NewHandler(adapter block.Adapter) *Handler { return &Handler{ adapter: adapter, } } type TaskBody struct { DestinationNamespace string DestinationID string SourceNamespace string SourceID string } func PathToPointer(path string) (block.ObjectPointer, error) { u, err := url.Parse(path) // TODO(guys): add verify path on create task if err != nil { return block.ObjectPointer{}, err } return block.ObjectPointer{ StorageNamespace: fmt.Sprintf("%s://%s", u.Scheme, u.Host), Identifier: u.Path, }, err } func (h *Handler) copy(body *string) error { var copyData CopyData err := json.Unmarshal([]byte(*body), &copyData) if err != nil { return err } from, err := PathToPointer(copyData.From) if err != nil { return err } to, err := PathToPointer(copyData.To) if err != nil { return err } return h.adapter.Copy(from, to) // TODO(guys): add wait for copy in handler } func (h *Handler) remove(body *string) error { var deleteData DeleteData err := json.Unmarshal([]byte(*body), &deleteData) if err != nil { return err } path, err := PathToPointer(deleteData.File) if err != nil { return err } return h.adapter.Remove(path) } func (h *Handler) touch(body *string) error { var successData SuccessData err := json.Unmarshal([]byte(*body), &successData) if err != nil { return err } path, err := PathToPointer(successData.File) if err != nil { return err } return h.adapter.Put(path, 0, strings.NewReader(""), block.PutOpts{}) } var errUnknownAction = errors.New("unknown action") func (h *Handler) Handle(action string, body *string) parade.ActorResult { var err error switch action { case CopyAction: err = h.copy(body) case DeleteAction: err = h.remove(body) case TouchAction: err = h.touch(body) case DoneAction: // TODO(guys): handle done action default: err = errUnknownAction } if err != nil { logging.Default().WithFields(logging.Fields{ "actor": actorName, "action": action, }).WithError(err).Error("touch failed") return parade.ActorResult{ Status: err.Error(), StatusCode: parade.TaskInvalid, } } return parade.ActorResult{ Status: "Completed", StatusCode: parade.TaskCompleted, } } func (h *Handler) Actions() []string { return []string{CopyAction, DeleteAction, TouchAction, DoneAction} } func (h *Handler) ActorID() parade.ActorID { return actorName }
package io.renren.modules.erp.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import io.renren.common.utils.PageUtils; import io.renren.common.utils.Query; import io.renren.common.utils.R; import io.renren.modules.erp.entity.BusiReportWrgEntity; import io.renren.modules.erp.service.BusiReportWrgService; import io.renren.modules.sys.controller.AbstractController; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.Map; /** * 未认购 * * @author 李大龙 * @email <EMAIL> * @date 2021-01-06 17:24:58 */ @RestController @RequestMapping("erp/busireportwrg") public class BusiReportWrgController extends AbstractController { @Autowired private BusiReportWrgService busiReportWrgService; /** * 列表 */ @RequestMapping("/listByMy") public R listByMy(@RequestParam Map<String, Object> params){ String name = getUser().getName(); IPage<BusiReportWrgEntity> page = busiReportWrgService.page( new Query<BusiReportWrgEntity>().getPage(params), new QueryWrapper<BusiReportWrgEntity>() .lambda() .gt(BusiReportWrgEntity::getYqdate,0) .like(BusiReportWrgEntity::getUsername,name) .orderByDesc(BusiReportWrgEntity::getQsdate) ); PageUtils pageUtils = new PageUtils(page); return R.ok().put("page", pageUtils); } /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("erp:busireportwrg:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = busiReportWrgService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("erp:busireportwrg:info") public R info(@PathVariable("id") Integer id){ BusiReportWrgEntity busiReportWrg = busiReportWrgService.getById(id); return R.ok().put("busiReportWrg", busiReportWrg); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("erp:busireportwrg:save") public R save(@RequestBody BusiReportWrgEntity busiReportWrg){ busiReportWrgService.save(busiReportWrg); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("erp:busireportwrg:update") public R update(@RequestBody BusiReportWrgEntity busiReportWrg){ busiReportWrgService.updateById(busiReportWrg); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("erp:busireportwrg:delete") public R delete(@RequestBody Integer[] ids){ busiReportWrgService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
def format_status(status,wind): if status == "DB" or status == "LO" or status == "WV": return "Disturbance, Low, or Tropical Wave" elif status == "SD": return "Subtropical Depression" elif status == "TD": return "Tropical Depression" elif status == "SS": return "Subtropical Storm" elif status == "TS": return "Tropical Storm" elif status == "EX": return "Extratropical Cyclone" elif status == "HU" and wind < 96: return "Hurricane" elif status == "HU" and wind >= 96: return "Major Hurricane" else: return "Unknown"
<filename>pt.iul.iscte.dcti.pa.jaxel/src/pt/iul/iscte/dcti/pa/jaxel/observer/EventDetails.java package pt.iul.iscte.dcti.pa.jaxel.observer; public class EventDetails{ public final EEventType eventType; public final Object[] extraData; public EventDetails(EEventType eventType, Object[] extraData) { this.eventType = eventType; this.extraData = extraData; } }
/** * Given the alpha affine key and a single ciphertext char and its associated plaintext char, * compute the appropriate beta affine key. * * @param alpha * the given alpha * * @param c * the given ciphertext char * * @param p * the given plaintext char * * @return The resulting beta affine key. * * @throws IllegalArgumentException * If <code>(!Affine.isValidAlpha(alpha)) * || (!CryptoTools.isUpperEnglish(c)) || (!CryptoTools.isUpperEnglish(p))</code> */ public static int keyBeta(int alpha, int c, int p) throws IllegalArgumentException { alpha = Affine.validateAlpha(alpha); c = CryptoTools.upperEnglish(c) - 'A'; p = CryptoTools.upperEnglish(p) - 'A'; /** * <code>Let m = CryptoTools.ENGLISH_ALPHABET_SIZE.</code> * <code>Step 1: c = alpha * p + beta (mod m)</code> * <code>Step 2: c - alpha * p (mod m) = beta</code> */ return ((int) MathUtil.modFixedInput(c - alpha * p, CryptoTools.ENGLISH_ALPHABET_SIZE)); }
class CallbackStreamWrapper: """A class to just wrap a read stream, but perform a callback every few bytes. Should be used only for streams open in read mode. """ def __init__( self, stream: StreamSeekBytesType, callback: Optional[Callable], total_length: int = 0, description: str = "Streamed object", ) -> None: """ Initialises the reader to a given stream. :param stream: an open stream :param callback: a callback to call to update the status (or None if not needed) :param total_length: the expected length """ self._stream = stream self._callback = callback self._total_length = total_length self._description = description # Update at most 400 times, avoiding to increase CPU usage; if the list is small: every object. self._update_every: int = max(int(total_length / 400), 1) if total_length else 1 # Counter of how many objects have been since since the last update. # A new callback will be performed when this value is > update_every. self._since_last_update: int = 0 if self._callback: # If we have a callback, compute the total count of objects in this pack self._callback( action="init", value={"total": total_length, "description": description} ) @property def mode(self) -> str: return self._stream.mode def seekable(self) -> bool: """Return whether object supports random access.""" return self._stream.seekable() def seek(self, target: int, whence: int = 0) -> int: """Change stream position.""" if target > self.tell(): if self._callback: self._since_last_update = self._since_last_update + target - self.tell() if self._since_last_update >= self._update_every: self._callback(action="update", value=self._since_last_update) self._since_last_update = 0 else: self.close_callback() if self._callback: # If we have a callback, compute the total count of objects in this pack self._callback( action="init", value={ "total": self._total_length, "description": f"{self._description} [rewind]", }, ) # Counter of how many objects have been since since the last update. # A new callback will be performed when this value is > update_every. self._since_last_update = target self._callback(action="update", value=self._since_last_update) return self._stream.seek(target, whence) def tell(self) -> int: """Return current stream position.""" return self._stream.tell() def read(self, size: int = -1) -> bytes: """ Read and return up to n bytes. If the argument is omitted, None, or negative, reads and returns all data until EOF (that corresponds to the length specified in the __init__ method). Returns an empty bytes object on EOF. """ data = self._stream.read(size) if self._callback: self._since_last_update += len(data) if self._since_last_update >= self._update_every: self._callback(action="update", value=self._since_last_update) self._since_last_update = 0 return data def __enter__(self) -> "CallbackStreamWrapper": """Use as context manager.""" return self def __exit__(self, exc_type, value, traceback) -> None: """Close context manager.""" def close_callback(self) -> None: """ Call the wrap up closing calls for the callback. .. note:: it DOES NOT close the stream. """ if self._callback: # Final call to complete the bar if self._since_last_update: self._callback(action="update", value=self._since_last_update) # Perform any wrap-up, if needed self._callback(action="close", value=None)
package com.joshy23.autopicker.listener; import com.joshy23.autopicker.AutoPicker; import com.sk89q.worldguard.LocalPlayer; import com.sk89q.worldguard.protection.ApplicableRegionSet; import com.sk89q.worldguard.protection.flags.DefaultFlag; import com.sk89q.worldguard.protection.managers.RegionManager; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; public class PlayerEvents implements Listener { private AutoPicker plugin = AutoPicker.getPlugin(); @EventHandler public void onBlockBreak(BlockBreakEvent e){ Player p = e.getPlayer(); Block b = e.getBlock(); if(p.getInventory().firstEmpty() > 0){ if(plugin.getWorldGuard() != null || plugin.getWorldEdit() != null){ LocalPlayer localPlayer = plugin.getWorldGuard().wrapPlayer(p); RegionManager manager = plugin.getWorldGuard().getRegionManager(p.getWorld()); ApplicableRegionSet set = manager.getApplicableRegions(localPlayer.getPosition()); if(set.testState(localPlayer, DefaultFlag.BLOCK_BREAK)){ e.setCancelled(true); p.getInventory().addItem(b.getDrops().toArray(new ItemStack[]{})); p.setLevel(p.getLevel()+e.getExpToDrop()); b.setType(Material.AIR); p.playSound(p.getLocation(), Sound.LEVEL_UP,1,1); }else{ e.setCancelled(false); } }else{ e.setCancelled(true); p.getInventory().addItem(b.getDrops().toArray(new ItemStack[]{})); p.setLevel(p.getLevel()+e.getExpToDrop()); b.setType(Material.AIR); p.playSound(p.getLocation(), Sound.LEVEL_UP,1,1); } }else{ p.sendTitle(AutoPicker.getColor("&c&lInventory full"),""); p.playSound(p.getLocation(),Sound.VILLAGER_NO,1,1); } } /* @EventHandler public void onWorldChange(PlayerChangedWorldEvent e){ } */ }
import { container } from 'tsyringe'; import '@modules/users/providers'; import './providers'; import IPetsRepository from '@modules/pets/repositories/IPetsRepository'; import PetsRepository from '@modules/pets/infra/typeorm/repositories/PetsRepository'; import IUsersRepository from '@modules/users/repositories/IUsersRepository'; import UsersRepository from '@modules/users/infra/typeorm/repositories/UsersRepository'; import IUserTokensRepository from '@modules/users/repositories/IUserTokensRepository'; import UserTokensRepository from '@modules/users/infra/typeorm/repositories/UserTokensRepository'; container.registerSingleton<IUsersRepository>( 'UsersRepository', UsersRepository, ); container.registerSingleton<IUserTokensRepository>( 'UserTokensRepository', UserTokensRepository, ); container.registerSingleton<IPetsRepository>('PetsRepository', PetsRepository);
from typing import Any, List, Union import numpy as np def add_gaussian_noise( default_value: Union[float, List[float]], percentage_std: Union[float, Any] = 0.01, random_generator: np.random.Generator = None, ) -> Union[float, Any]: """ Add gaussian noise to default value. Parameters ---------- default_value: Union[float, List[float]] Mean of normal distribution. Can be a scalar or a list of floats. If it is a list(-like) with length n, the output will also be of length n. percentage_std: float, optional = 0.01 Relative standard deviation, multiplied with default value (mean) is standard deviation of normal distribution. If the default value is 0, percentage_std is assumed to be the absolute standard deviation. random_generator: np.random.Generator, optional = None Optional random generator to ensure deterministic behavior. Returns ------- Union[float, List[float]] Default value with gaussian noise. If input was list (or array) with length n, output is also list (or array) with length n. """ if type(default_value) in [int, float] and default_value != 0: std = percentage_std * np.abs(default_value) else: std = percentage_std mean = np.zeros_like(default_value) if not random_generator: random_generator = np.random.default_rng() value = default_value + random_generator.normal(loc=mean, scale=std) return value
/* * Copyright (C) 2008, Robert Oostenveld * F.C. Donders Centre for Cognitive Neuroimaging, Radboud University Nijmegen, * Kapittelweg 29, 6525 EN Nijmegen, The Netherlands * * $Id$ */ #include "mex.h" #include "matrix.h" #include "buffer.h" #define NUMBER_OF_FIELDS 6 #define MAX_NUM_BLOBS 32 #define SIZE_NIFTI_1 348 /* return field number on success, or -1 if already existing or invalid */ int addIfNew(mxArray *S, const char *name) { int field; if (mxGetFieldNumber(S, name) >= 0) { printf("Chunk '%s' already defined. Skipping.\n", name); return -1; } field = mxAddField(S, name); if (field<0) { printf("Can not add '%s' to output struct. Skipping.\n", name); } return field; } mxArray *channelNames2Cell(const char *str, int len, int numChannels) { int i,pe,ps = 0; mxArray *A = mxCreateCellMatrix(numChannels, 1); for (i=0;i<numChannels;i++) { mxArray *name; for (pe=ps; pe<len; pe++) { if (str[pe]==0) break; } if (pe>=len) { printf("Invalid name for channel %i. Skipping the rest.\n", i+1); break; } name = mxCreateString(str + ps); mxSetCell(A, i, name); /* next channel name begins after the 0 of the previous one */ ps = pe+1; } return A; } void addChunksToMatrix(mxArray *S, const char *buf, int bufsize, int numChannels) { int bufpos = 0; int numBlobs = 0; mxArray *blobs[MAX_NUM_BLOBS]; mxArray *keyval = NULL; mxArray *A; int field; while (bufpos + sizeof(ft_chunkdef_t) <= bufsize) { ft_chunk_t *chunk = (ft_chunk_t *) (buf + bufpos); /* "chunk" now points to the right location, make sure it has a valid size definition */ if (bufpos + sizeof(ft_chunkdef_t) + chunk->def.size > bufsize) { printf("Invalid chunk size (%i) in Fieldtrip header detected. Stopping to parse.\n", chunk->def.size); break; } switch (chunk->def.type) { case FT_CHUNK_CHANNEL_NAMES: field = addIfNew(S, "channel_names"); if (field < 0) break; A = channelNames2Cell(chunk->data, chunk->def.size, numChannels); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_NIFTI1: if (chunk->def.size != SIZE_NIFTI_1) { mexWarnMsgTxt("Invalid NIFTI-1 chunk detected. Skipping."); break; } field = addIfNew(S, "nifti_1"); if (field < 0) break; /* pass on as 348 bytes (uint8), should be decoded on MATLAB level (?) */ A = mxCreateNumericMatrix(1, SIZE_NIFTI_1, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, SIZE_NIFTI_1); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_SIEMENS_AP: field = addIfNew(S, "siemensap"); if (field < 0) break; /* pass on as uint8, should be decoded on MATLAB level (?) */ A = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, chunk->def.size); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_CTF_RES4: field = addIfNew(S, "ctf_res4"); if (field < 0) break; /* pass on as uint8, should be decoded on MATLAB level */ A = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, chunk->def.size); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_NEUROMAG_HEADER: field = addIfNew(S, "neuromag_header"); if (field < 0) break; /* pass on as uint8, should be decoded on MATLAB level */ A = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, chunk->def.size); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_NEUROMAG_ISOTRAK: field = addIfNew(S, "neuromag_isotrak"); if (field < 0) break; /* pass on as uint8, should be decoded on MATLAB level */ A = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, chunk->def.size); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_NEUROMAG_HPIRESULT: field = addIfNew(S, "neuromag_hpiresult"); if (field < 0) break; /* pass on as uint8, should be decoded on MATLAB level */ A = mxCreateNumericMatrix(1, chunk->def.size, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, chunk->def.size); mxSetFieldByNumber(S, 0, field, A); break; case FT_CHUNK_RESOLUTIONS: field = addIfNew(S, "resolutions"); if (field >=0) { int nc = chunk->def.size / sizeof(double); /* If the chunk is buggy and there are less resolution values present, we only fill in those we have. If there are more, we only fill in numChannels. So the returned 'resolutions' field will always match the number of channels in the buffer. */ if (nc>numChannels) nc = numChannels; A = mxCreateDoubleMatrix(numChannels, 1, mxREAL); memcpy(mxGetPr(A), chunk->data, nc*sizeof(double)); } break; case FT_CHUNK_UNSPECIFIED: default: if (numBlobs < MAX_NUM_BLOBS) { /* pass on the binary(?) blob as an uint8 matrix */ A = mxCreateNumericMatrix(chunk->def.size, (chunk->def.size>0)?1:0, mxUINT8_CLASS, mxREAL); memcpy(mxGetData(A), chunk->data, chunk->def.size); blobs[numBlobs++] = A; } else { mexWarnMsgTxt("Encountered too many unspecified chunks in header. Skipping this one."); } } /* jump to next chunk */ bufpos += chunk->def.size + sizeof(ft_chunkdef_t); } if (numBlobs > 0) { int i; field = addIfNew(S, "unspecified_blob"); if (field < 0) return; A = mxCreateCellMatrix(numBlobs,1); for (i=0;i<numBlobs;i++) { mxSetCell(A, i, blobs[i]); } mxSetFieldByNumber(S, 0, field, A); } } int buffer_gethdr(int server, mxArray *plhs[], const mxArray *prhs[]) { int verbose = 0; int result = 0; message_t *request = NULL; message_t *response = NULL; /* this is for the MATLAB specific output */ const char *field_names[NUMBER_OF_FIELDS] = {"nchans", "nsamples", "nevents", "fsample", "data_type", "bufsize"}; /* allocate the elements that will be used in the communication */ request = malloc(sizeof(message_t)); request->def = malloc(sizeof(messagedef_t)); request->buf = NULL; request->def->version = VERSION; request->def->command = GET_HDR; request->def->bufsize = 0; if (verbose) print_request(request->def); result = clientrequest(server, request, &response); if (result == 0) { if (verbose) print_response(response->def); if (response->def->command==GET_OK) { headerdef_t *headerdef = (headerdef_t *) response->buf; if (verbose) print_headerdef(headerdef); plhs[0] = mxCreateStructMatrix(1, 1, NUMBER_OF_FIELDS, field_names); mxSetFieldByNumber(plhs[0], 0, 0, mxCreateDoubleScalar((double)(headerdef->nchans))); mxSetFieldByNumber(plhs[0], 0, 1, mxCreateDoubleScalar((double)(headerdef->nsamples))); mxSetFieldByNumber(plhs[0], 0, 2, mxCreateDoubleScalar((double)(headerdef->nevents))); mxSetFieldByNumber(plhs[0], 0, 3, mxCreateDoubleScalar((double)(headerdef->fsample))); mxSetFieldByNumber(plhs[0], 0, 4, mxCreateDoubleScalar((double)(headerdef->data_type))); mxSetFieldByNumber(plhs[0], 0, 5, mxCreateDoubleScalar((double)(headerdef->bufsize))); addChunksToMatrix(plhs[0], (const char *) response->buf + sizeof(headerdef_t), headerdef->bufsize, headerdef->nchans); } else { result = response->def->command; } } if (response) { FREE(response->def); FREE(response->buf); FREE(response); } if (request) { FREE(request->def); FREE(request->buf); FREE(request); } return result; }
// extractResourceGroupByNicID extracts the resource group name by nicID. func extractResourceGroupByNicID(nicID string) (string, error) { matches := nicResourceGroupRE.FindStringSubmatch(nicID) if len(matches) != 2 { return "", fmt.Errorf("error of extracting resourceGroup from nicID %q", nicID) } return matches[1], nil }
Inspiration on wheels: Derek Unwin (74) is competing in his second criterium on February 2. Picture: Emma Reeves www.communitypix.com.au d413239 Northern Beaches Cycling Club is preparing to host its second criterium ” the Yanchep National Park Challenge, on February 2 ” and president Chris Howard said drivers should be conscious of safety as they pass cyclists. ‘One of the issues that we have on the road is how dehumanised cyclists are,’ Dr Howard said. ‘Some drivers go out of the way to harass us. ‘They can’t see our faces, we have got our backs to them.’ Dr Howard said among the cyclists who had experienced abusive behaviour from drivers were the club’s oldest member, Derek ‘the Fox’ Unwin (74), and young talent Jacob Wood (16). Dr Howard said Mr Unwin was an inspiration Unwin was an inspiration in the club, having overcome health problems to become a ‘superfit retiree’. ‘He often rides out early and solo so that group riders can try to catch him before he reaches the coffee shop,’ he said. However, the Jindalee grandfather has had near misses while riding on Marmion Avenue, and heard drivers shouting, swearing and honking their horns at cyclists. ‘Derek has resorted to filming his rides in the event of the abusive rants of a small minority of drivers,’ Dr Howard said. ‘He has seen it on his regular rides on northern suburbs and would appreciate a wave rather than abuse from other road users.’ Mr Unwin said he was riding towards Yanchep on one occasion when a driver turned left in front of him. ‘He looked right through me ” he missed me by about six inches,’ he said. ‘Some of the cyclists have had bottles thrown at them. Like a flag, they attack us because we are there, not for any reason. ‘It is the exception rather than the rule but the problem is the exception can be pretty dangerous. ‘Good drivers still move over and give us plenty of room.’ Mr Unwin said he started cycling in 2006 then discovered he was at risk of a stroke because he had a 95 per cent blockage in an artery. As he recovered, he joined the fledgling cycling club and found they were always willing to ride at his pace, with all members meeting up at a caf� afterwards. ‘The club have really looked after me ” I am slow,’ the septuagenarian said. ‘If anyone is the same age as me, they shouldn’t worry about joining because they won’t be left behind.’
<filename>src/main/java/crain/model/dto/ItemDto.java package crain.model.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Positive; import javax.validation.constraints.PositiveOrZero; @Data @NoArgsConstructor @AllArgsConstructor public class ItemDto { @Positive(message="World Id must be greater than 0.") private int sourcePlayerWorldId; @Positive(message="World Id must be greater than 0.") private int targetPlayerWorldId; @PositiveOrZero(message="Item Ids cannot be less than 0.") private int itemId; }
/** * Resolve the OS-specific test file to execute. */ protected File resolveTestScript(final String directoryName, final String baseName) { final File result = TestUtil.resolveScriptForOS(testDir + "/" + directoryName + "/" + baseName); if (!result.exists()) { throw new IllegalArgumentException("Unable to find the following file: " + result.getAbsolutePath()); } return result; }
import { CharacterEntity } from '../entities/CharacterEntity'; import { FilmEntity } from '../entities/FilmEntity'; import { Gateways } from '../gateways/Gateways'; import { PlanetEntity } from '../entities/PlanetEntity'; export class PlanetModel { private _gateways: Gateways; private _planet: PlanetEntity; private _films: FilmEntity[]; private _residents: CharacterEntity[]; public constructor(gateways: Gateways) { this._gateways = gateways; } public async loadPlanetData(id: number): Promise<null> { const planetsGateway = this._gateways.planetsGateway; const planet = await planetsGateway.retrievePlanet(`https://swapi.co/api/planets/${id}/`); this._planet = planet; await Promise.all([ this.loadFilms(), this.loadResidents() ]); return null; } public getPlanet(): PlanetEntity { return this._planet; } public getFilms(): FilmEntity[] { return this._films; } public getResidents() { return this._residents; } private async loadFilms(): Promise<null> { const filmsGateway = this._gateways.filmsGateway; const planet = this._planet; const filmUrls = planet.getFilmUrls(); const filmPromises = []; filmUrls.map((url: string) => { const promise = filmsGateway.retrieveFilm(url); filmPromises.push(promise); }); this._films = await Promise.all(filmPromises); return null; }; private async loadResidents(): Promise<null> { const charactersGateway = this._gateways.charactersGateway; const planet = this._planet; const characterUrls = planet.getResidentCharacterUrls(); const characterPromises = []; characterUrls.map((url: string) => { const promise = charactersGateway.retrieveCharacter(url); characterPromises.push(promise); }); this._residents = await Promise.all(characterPromises); return null; } }
/** * Created by Administrator on 2018/1/29. */ public class UrlFactory { public static final String host = UrlConfig.BASE_URL; //获取充币地址 public static String getChongbi() { return host + "/uc/asset/wallet/reset-address"; } //申请成为商家 public static String getSellerApply() { return host + "/uc/approve/certified/business/apply"; } // 提币验证码 public static String getCode() { return host + "/uc/mobile/withdraw/code"; } // 提币接口 public static String getTIBi() { return host + "/uc/withdraw/apply/code"; } //获取保证金币种列表 public static String getDepositList() { return host + "/uc/approve/business-auth-deposit/list"; } //帮助中心 public static String getHelp() { return host + "/uc/ancillary/more/help"; } public static String getHelpXinShou() { return host + "/uc/ancillary/more/help/page"; } //交易明细接口 public static String getCha() { return host + "/uc/asset/transaction/all"; } //提币明细 public static String getChaTiBi() { return host + "/uc/withdraw/record"; } // public static String getShangjia() { return host + "/uc/approve/certified/business/status"; } // 获取汇率 public static String getRateUrl() { return host + "/market/exchange-rate/usd-cny"; } public static String getPhoneCodeUrl() { return host + "/uc/mobile/code"; } //注册 public static String getSignUpByPhone() { return host + "/uc/register/for_phone"; } public static String getSignUpByEmail() { return host + "/uc/register/email"; } public static String getLoginUrl() { return host + "/uc/login"; } public static String getKDataUrl() { return host + "/market/history"; } public static String getAllCurrency() { return host + "/market/symbol-thumb"; } /** * 首页获取所有的币种 */ public static String getAllCurrencys() { return host + "/market/overview"; } /** * 得到信息,来设置输入小数点位数的限制 */ public static String getSymbolInfo() { return host + "/market/symbol-info"; } public static String getFindUrl() { return host + "/exchange/favor/find"; } public static String getDeleteUrl() { return host + "/exchange/favor/delete"; } public static String getAddUrl() { return host + "/exchange/favor/add"; } public static String getExChangeUrl() { return host + "/exchange/order/add"; } public static String getWalletUrl() { return host + "/uc/asset/wallet/"; } public static String getAllUrl() { return host + "/otc/coin/all"; } public static String getAdvertiseUrl() { return host + "/otc/advertise/page"; } public static String getCountryUrl() { return host + "/uc/support/country"; } public static String getReleaseAdUrl() { return host + "/otc/advertise/create"; } public static String getUploadPicUrl() { return host + "/uc/upload/oss/base64"; } public static String getNameUrl() { return host + "/uc/approve/real/name"; } public static String getAccountPwdUrl() { return host + "/uc/approve/transaction/password"; } public static String getAllAdsUrl() { return host + "/otc/advertise/all"; } public static String getReleaseUrl() { return host + "/otc/advertise/on/shelves"; } public static String getDeleteAdsUrl() { return host + "/otc/advertise/delete"; } public static String getOffShelfUrl() { return host + "/otc/advertise/off/shelves"; } public static String getAdDetailUrl() { return host + "/otc/advertise/detail"; } public static String getUpdateAdUrl() { return host + "/otc/advertise/update"; } public static String getC2CInfoUrl() { return host + "/otc/order/pre"; } public static String getC2CBuyUrl() { return host + "/otc/order/buy"; } public static String getC2CSellUrl() { return host + "/otc/order/sell"; } public static String getMyOrderUrl() { return host + "/otc/order/self"; } public static String getExtractinfoUrl() { return host + "/uc/withdraw/support/coin/info"; } public static String getExtractUrl() { return host + "/uc/withdraw/apply"; } public static String getAllTransactionUrl2() { return host + "/uc/asset/transaction/all"; } public static String getSafeSettingUrl() { return host + "/uc/approve/security/setting"; } public static String getAvatarUrl() { return host + "/uc/approve/change/avatar"; } public static String getBindPhoneUrl() { return host + "/uc/approve/bind/phone"; } public static String getSendCodeUrl() { return host + "/uc/mobile/bind/code"; } public static String getBindEmailUrl() { return host + "/uc/approve/bind/email"; } public static String getSendEmailCodeUrl() { return host + "/uc/bind/email/code"; } public static String getEditLoginPwdUrl() { return host + "/uc/mobile/update/password/code"; } public static String getEditPwdUrl() { return host + "/uc/approve/update/password"; } public static String getPlateUrl() { return host + "/market/exchange-plate"; } /** * 查询当前委托 */ public static String getEntrustUrl() { return host + "/exchange/order/personal/current"; } /** * 获取历史委托记录 */ public static String getHistoryEntrus() { return host + "/exchange/order/personal/history"; } public static String getCancleEntrustUrl() { return host + "/exchange/order/cancel/"; } public static String getPhoneForgotPwdCodeUrl() { return host + "/uc/mobile/reset/code"; } public static String getEmailForgotPwdCodeUrl() { return host + "/uc/reset/email/code"; } public static String getForgotPwdUrl() { return host + "/uc/reset/login/password"; } public static String getCaptchaUrl() { return host + "/uc/start/captcha"; } public static String getSendChangePhoneCodeUrl() { return host + "/uc/mobile/change/code"; } public static String getChangePhoneUrl() { return host + "/uc/approve/change/phone"; } public static String getMessageUrl() { return host + "/uc/announcement/page"; } public static String getMessageDetailUrl() { return host + "/uc/announcement/"; } public static String getMessageHelpUrl() { return host + "/uc/ancillary/more/help/detail"; } public static String getRemarkUrl() { return host + "/uc/feedback"; } public static String getAppInfoUrl() { return host + "/uc/ancillary/website/info"; } public static String getBannersUrl() { return host + "/uc/ancillary/system/advertise"; } public static String getOrderDetailUrl() { return host + "/otc/order/detail"; } public static String getCancleUrl() { return host + "/otc/order/cancel"; } public static String getpayDoneUrl() { return host + "/otc/order/pay"; } public static String getReleaseOrderUrl() { return host + "/otc/order/release"; } public static String getAppealUrl() { return host + "/otc/order/appeal"; } public static String getEditAccountPwdUrl() { return host + "/uc/approve/update/transaction/password"; } public static String getResetAccountPwdUrl() { return host + "/uc/approve/reset/transaction/password"; } public static String getResetAccountPwdCodeUrl() { return host + "/uc/mobile/transaction/code"; } public static String getHistoryMessageUrl() { return host + "/chat/getHistoryMessage"; } public static String getEntrustHistory() { return host + "/exchange/order/history"; } public static String getCreditInfo() { return host + "/uc/approve/real/detail"; } public static String getNewVision() { return host + "/uc/ancillary/system/app/version/0"; } public static String getSymbolUrl() { return host + "/market/symbol"; } public static String getAccountSettingUrl() { return host + "/uc/approve/account/setting"; } public static String getBindBankUrl() { return host + "/uc/approve/bind/bank"; } public static String getUpdateBankUrl() { return host + "/uc/approve/update/bank"; } public static String getBindAliUrl() { return host + "/uc/approve/bind/ali"; } public static String getUpdateAliUrl() { return host + "/uc/approve/update/ali"; } public static String getBindWechatUrl() { return host + "/uc/approve/bind/wechat"; } public static String getUpdateWechatUrl() { return host + "/uc/approve/update/wechat"; } public static String getCheckMatchUrl() { return host + "/uc/asset/wallet/match-check"; } public static String getStartMatchUrl() { return host + "/uc/asset/wallet/match"; } public static String getPromotionUrl() { return host + "/uc/promotion/record"; } public static String getPromotionRewardUrl() { return host + "/uc/promotion/reward/record"; } public static String getDepth() { return host + "/market/exchange-plate-full"; } // 获取深度图数据 public static String getVolume() { return host + "/market/latest-trade"; } // 获取成交数据 // C2C交易接口(承兑商版) public static String getCtcOrderList() { return host + "/uc/ctc/page-query"; } public static String getCtcOrderDetail() { return host + "/uc/ctc/detail"; } public static String getCtcOrderCancel() { return host + "/uc/ctc/cancel-ctc-order"; } public static String getCtcOrderPay() { return host + "/uc/ctc/pay-ctc-order"; } public static String getCtcPrice() { return host + "/market/ctc-usdt"; } public static String getCtcNewOrder() { return host + "/uc/ctc/new-ctc-order"; } public static String getCtcSendNewOrderPhoneCode() { return host + "/uc/mobile/ctc/code"; } public static String getMyPromotion(){ return host + "/uc/promotion/mypromotion"; } }
import React, { Dispatch } from "react"; import { StoreState } from "../store/types"; import { IMainLogin } from "./types/MainLogin"; import { UserActionType } from "../actions/types/user"; import { setUserIsLoggedIn } from "../actions/user"; import { withRouter } from "next/router"; import { connect } from "react-redux"; import { IMainEntryProps, IMainEntryStates } from "./types/MainEntry"; import Link from "next/link"; import styles from "./MainEntry.module.css"; class MainEntry extends React.Component<IMainEntryProps, IMainEntryStates> { constructor(props) { super(props); this.handleInputOnKeyPressed = this.handleInputOnKeyPressed.bind(this); } private handleInputOnKeyPressed(event) { if (event.key === "Enter") { this.props.router.push("/signup"); } } render() { return ( <div> <section className={`section hero is-info ${styles["full-height"]}`}> <div className="hero-body"> <div className="container has-text-centered"> <div className="column is-6 is-offset-3"> <h1 className="title"> Your URL Shortener </h1> <h2 className="subtitle"> The best url shortener as ever. </h2> <div className="box"> <div className="field is-grouped"> <p className="control is-expanded"> <input className="input" type="text" placeholder="Shorten your link" onKeyPress={this.handleInputOnKeyPressed} /> </p> <p className="control"> <Link href="/signup"> <a className="button is-info"> Sign Up </a> </Link> </p> </div> </div> </div> </div> </div> </section> </div> ); } } const mapStateToProps = (state: StoreState, ownProps: IMainLogin.IInnerProps): IMainLogin.IStateFromProps => { return { userLoggedIn: state.userMisc.userLoggedIn, }; }; const mapDispatchToProps = (dispatch: Dispatch<UserActionType>, ownProps: IMainLogin.IInnerProps): IMainLogin.IPropsFromDispatch => { return { setUserIsLoggedIn: (userLoggedIn: boolean) => dispatch(setUserIsLoggedIn(userLoggedIn)), }; }; export default withRouter(connect( mapStateToProps, mapDispatchToProps, )(MainEntry));
// printTree recursively prints the tree's contents in a tree-like structure. func (cmd *TreeCommand) printTree(t *api.Tree, w io.Writer) { rootDirName := func() string { if cmd.fullPaths { return cmd.path.Value() + "/" } return t.RootDir.Name + "/" }() name := colorizeByStatus(t.RootDir.Status, rootDirName) fmt.Fprintf(w, "%s\n", name) if cmd.fullPaths { cmd.printDirContentsRecursively(t.RootDir, "", w, cmd.path.Value()) } else { cmd.printDirContentsRecursively(t.RootDir, "", w, "") } if !cmd.noReport { fmt.Fprintf(w, "\n%s, %s\n", pluralize("directory", "directories", t.DirCount()), pluralize("secret", "secrets", t.SecretCount()), ) } }
<filename>chat/client/main.go package main import ( "github.com/carsonsx/net4g" "github.com/carsonsx/net4g-demo/chat/global" "time" "github.com/carsonsx/log4g" ) var dispatcher = net4g.NewDispatcher("chat-client") func init() { dispatcher.AddHandler(setUserInfoReply, new(global.SetUserInfoReply)) dispatcher.AddHandler(func(agent net4g.NetAgent) { log4g.Debug("message: %v", agent.Msg()) }, new(global.SendMessage)) } //func addrFn() (addr string, err error) { // cli, err := api.NewClient(&api.Config{ // //Address: "consul-dev:8500", // Address: "192.168.56.201:8500", // }) // if err != nil { // return "", err // } // se, _, err := cli.Health().Service("chatserver", "", true, nil) // if err != nil { // return "", err // } // l := len(se) // if l == 0 { // text := "not found any chat router service" // log4g.Error(text) // return "", errors.New(text) // } // log4g.Debug("found %d services", l) // r := rand.New(rand.NewSource(time.Now().UnixNano())) // selectIndex := r.Intn(l) // log4g.Debug("service select index: %d", selectIndex) // one := se[selectIndex].Service // return fmt.Sprintf("%s:%d", one.Address, one.Port), nil //} func setUserInfoReply(agent net4g.NetAgent) { if agent.Msg().(*global.SetUserInfoReply).Success { go func() { var m global.SendMessage m.Text = "hello world!" var stop bool for !stop { time.Sleep(1 * time.Second) if err := dispatcher.BroadcastOne(&m, func(err error) { stop = true }); err != nil { break } } }() } } func main() { //log4g.SetLevel(log4g.LEVEL_TRACE) dispatcher.OnConnectionCreated(func(agent net4g.NetAgent) { var u global.SetUserInfo u.Username = "carson4" dispatcher.BroadcastAll(&u) }) net4g.NewTcpClient(net4g.NewNetAddrFn(":8000")). SetSerializer(global.Serializer). AddDispatchers(dispatcher). Connect(). Wait() }
<gh_stars>1-10 package cn.tsoft.framework.testing.jmeter.plugin.util; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.List; import cn.tsoft.framework.testing.jmeter.plugin.dubbo.sample.MethodArgument; public class ClassUtils { private static final String TYPE_NAME_PREFIX = "class "; public static String getClassName(Type type) { if (type == null) { return ""; } String className = type.toString(); if (className.startsWith(TYPE_NAME_PREFIX)) { className = className.substring(TYPE_NAME_PREFIX.length()); } return className; } @SuppressWarnings("rawtypes") public static String[] getMethodParamType(String interfaceName, String methodName) { try { // 创建类 Class<?> class1 = Class.forName(interfaceName); // 获取所有的公共的方法 Method[] methods = class1.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] paramClassList = method.getParameterTypes(); String[] paramTypeList = new String[paramClassList.length]; int i = 0; for (Class className : paramClassList) { paramTypeList[i] = className.getName(); i++; } return paramTypeList; } } } catch (Exception e) { e.printStackTrace(); } return null; } public static void parseParameter(Type type,List<String> paramterTypeList, List<Object> parameterValuesList, MethodArgument arg) throws ClassNotFoundException { String className = getClassName(type); if (className.equals("int")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Integer.parseInt(arg.getParamValue())); } else if (className.equals("double")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Double.parseDouble(arg.getParamValue())); } else if (className.equals("short")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Short.parseShort(arg.getParamValue())); } else if (className.equals("float")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Float.parseFloat(arg.getParamValue())); } else if (className.equals("long")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Long.parseLong(arg.getParamValue())); } else if (className.equals("byte")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Byte.parseByte(arg.getParamValue())); } else if (className.equals("boolean")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(Boolean.parseBoolean(arg.getParamValue())); } else if (className.equals("char")) { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(arg.getParamValue().charAt(0)); } else if (className.equals("java.lang.String") || className.equals("String") || className.equals("string")) { paramterTypeList.add("java.lang.String"); parameterValuesList.add(String.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Integer") || className.equals("Integer") || className.equals("integer")) { paramterTypeList.add("java.lang.Integer"); parameterValuesList.add(Integer.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Double") || className.equals("Double")) { paramterTypeList.add("java.lang.Double"); parameterValuesList.add(Double.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Short") || className.equals("Short")) { paramterTypeList.add("java.lang.Short"); parameterValuesList.add(Short.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Long") || className.equals("Long")) { paramterTypeList.add("java.lang.Long"); parameterValuesList.add(Long.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Float") || className.equals("Float")) { paramterTypeList.add("java.lang.Float"); parameterValuesList.add(Float.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Byte") || className.equals("Byte")) { paramterTypeList.add("java.lang.Byte"); parameterValuesList.add(Byte.valueOf(arg.getParamValue())); } else if (className.equals("java.lang.Boolean") || className.equals("Boolean")) { paramterTypeList.add("java.lang.Boolean"); parameterValuesList.add(Boolean.valueOf(arg.getParamValue())); } else { paramterTypeList.add(arg.getParamType()); parameterValuesList.add(JsonUtils.formJson(arg.getParamValue(), type)); } } }
// ListProfiles returns all valid and invalid (if any) minikube profiles // invalidPs are the profiles that have a directory or config file but not usable // invalidPs would be suggested to be deleted func ListProfiles(miniHome ...string) (validPs []*Profile, inValidPs []*Profile, err error) { pDirs, err := profileDirs(miniHome...) if err != nil { return nil, nil, err } cs, err := oci.ListOwnedContainers(oci.Docker) if err == nil { pDirs = append(pDirs, cs...) } pDirs = removeDupes(pDirs) for _, n := range pDirs { p, err := LoadProfile(n, miniHome...) if err != nil { inValidPs = append(inValidPs, p) continue } if !p.IsValid() { inValidPs = append(inValidPs, p) continue } validPs = append(validPs, p) } return validPs, inValidPs, nil }
<filename>src/game/team.rs use std::str::FromStr; use std::fmt; use crate::util::{SCError, SCResult}; /// A playing party in the game. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Team { One, Two, } impl Team { /// The team's index. pub fn index(self) -> i32 { match self { Team::One => 0, Team::Two => 1, } } /// The opponent of the given team. pub fn opponent(self) -> Team { match self { Team::One => Team::Two, Team::Two => Team::One, } } /// The x-direction of the team on the board. pub fn direction(self) -> i32 { match self { Team::One => 1, Team::Two => -1, } } } impl fmt::Display for Team { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Team::One => write!(f, "ONE"), Team::Two => write!(f, "TWO"), } } } impl FromStr for Team { type Err = SCError; fn from_str(s: &str) -> SCResult<Self> { match s { "ONE" => Ok(Team::One), "TWO" => Ok(Team::Two), _ => Err(SCError::UnknownVariant(format!("Unknown team {}", s))), } } }
<gh_stars>0 package ai.api.sample.adapter; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import ai.api.sample.R; import ai.api.sample.model.Message; /** * Created by anuj on 14/07/18. */ public class ChatRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<Message> messageList; public ChatRecyclerAdapter(ArrayList<Message> messageList) { this.messageList=messageList; } public void addMessage(Message message){ if (messageList == null) { messageList = new ArrayList<>(); }else{ messageList.add(message); notifyItemInserted(messageList.size()-1); } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if (viewType == 1) { view = LayoutInflater.from(parent.getContext()).inflate(R.layout.right_message, parent, false); return new ChatRecyclerAdapter.RightViewHolder(view); } else { view = LayoutInflater.from(parent.getContext()).inflate(R.layout.left_message, parent, false); return new ChatRecyclerAdapter.LeftViewHolder(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { Message message = messageList.get(position); if (getItemViewType(position) == 1) { ((RightViewHolder) holder).rightMessage.setText(message.getMessage()); } else { ((LeftViewHolder) holder).leftMessage.setText(message.getMessage()); } } @Override public int getItemViewType(int position) { return messageList.get(position).getViewType(); } @Override public int getItemCount() { return messageList.size(); } public class RightViewHolder extends RecyclerView.ViewHolder { AppCompatTextView rightMessage; public RightViewHolder(View itemView) { super(itemView); rightMessage = (AppCompatTextView) itemView.findViewById(R.id.message); } } public class LeftViewHolder extends RecyclerView.ViewHolder { AppCompatTextView leftMessage; public LeftViewHolder(View itemView) { super(itemView); leftMessage = (AppCompatTextView) itemView.findViewById(R.id.message); } } }
def makeShuffleArrows(self): arrows = [] runLog.extra("Building list of shuffle arrows.") for a in self.r.core.getAssemblies(): currentCoords = a.spatialLocator.getGlobalCoordinates() oldCoords = self.oldLocations.get(a.getName(), None) if oldCoords is None: oldCoords = numpy.array((-50, -50, 0)) elif any(currentCoords != oldCoords): arrows.append((oldCoords, currentCoords)) return arrows
def find_pareto_front(metrics): metrics = np.array(metrics) pareto_front_point_indices = np.arange(metrics.shape[0]) next_point_idx = 0 while next_point_idx < len(metrics): nondominated_points = np.any(metrics > metrics[next_point_idx], axis=1) nondominated_points[next_point_idx] = True pareto_front_point_indices = pareto_front_point_indices[nondominated_points] metrics = metrics[nondominated_points] next_point_idx = np.sum(nondominated_points[:next_point_idx+1]) return pareto_front_point_indices
United States Supreme Court case Nixon v. Herndon, 273 U.S. 536 (1927), was a United States Supreme Court decision which struck down a 1923 Texas law forbidding blacks from voting in the Texas Democratic Party primary.[1] Due to the limited amount of Republican Party activity in Texas at the time following the suppression of black voting through poll taxes, the Democratic Party primary was essentially the only competitive process and chance to choose candidates for the Senate, House of Representatives and state offices. This case was one of four supported by the National Association for the Advancement of Colored People (NAACP) that challenged the Texas Democratic Party's all-white primary, which was finally prohibited in the Supreme Court ruling Smith v. Allwright in 1944. Facts [ edit ] In 1902 the Texas legislature passed a requirement for a poll tax, which resulted in the suppressed voting by black and Mexican Americans. As voter participation by these groups declined, the Democratic Party became more dominant.[2] Dr. Lawrence A. Nixon, a black physician in El Paso, Texas and member of the Democratic Party, sought to vote in the Democratic Party primary of 1924 in El Paso.[3] The defendants were magistrates in charge of elections who prevented him from doing so on the basis of the 1923 Statute of Texas which provided that "in no event shall a negro be eligible to participate in a Democratic party primary election held in the State of Texas." Nixon sought an injunction against the statute in the federal district court. The district court dismissed the suit, and Nixon appealed to the United States Supreme Court. Issue [ edit ] Nixon argued that the statute violated the Fourteenth and Fifteenth Amendments to the Constitution. The defendants argued that the Court lacked jurisdiction over the issue, as it was a political question. Ruling [ edit ] The Court, speaking through Justice Oliver Wendell Holmes, unanimous rejected the argument that the political question doctrine barred the Court from deciding the case. The argument, said the Court, was "little more than a play upon words." While the injury which the plaintiff alleged "involved political action," his suit "allege[d] and s[ought] to recover for private damage." The Court then turned to the merits of the suit. It said that it was unnecessary to discuss whether the statute violated the Fifteenth Amendment, "because it seems to us hard to imagine a more direct and obvious infringement of the Fourteenth." The Court continued: The [Fourteenth Amendment] ... was passed, as we know, with a special intent to protect the blacks from discrimination against them. ... The statute of Texas ... assumes to forbid negroes to take part in a primary election the importance of which we have indicated, discriminating against them by the distinction of color alone. States may do a good deal of classifying that it is difficult to believe rational, but there are limits, and it is too clear for extended argument that color cannot be made the basis of a statutory classification affecting the right set up in this case. The Court reversed the district court's dismissal of the suit. Aftermath [ edit ] Texas promptly enacted a new provision to continue restrictions on black voter participation, granting authority to political parties to determine who should vote in their primaries. Within four months the Executive Committee of the Democratic Party passed a resolution that "all white Democrats ... and none other" be allowed to participate in the approaching primary of 1927.[2][4] Five years later, in 1932, Dr. Nixon reappeared before the Supreme Court in another suit, Nixon v. Condon, against the all-white primary. The Court again ruled against the State, which passed another variation in a continuing endeavor to maintain the white primary system. It was not until Smith v. Allwright (1944) that the Supreme Court "finally and decisively prohibited the white primary."[2] References [ edit ]
// StatsIssued returns a slice of the certificates which were issued during // the specified time window, along with the total count of those certificates. // The total count may be higher than the number of certificates in the slice if // the total count is higher than the specified number of certificates per // page. The HVCA API enforces a maximum number of certificates per page. If // the total count is higher than the number of certificates in the slice, the // remaining certificates may be retrieved by incrementing the page number in // subsequent calls of this method. func (c *Client) StatsIssued( ctx context.Context, page, perPage int, from, to time.Time, ) ([]CertMeta, int64, error) { return c.statsCommon(ctx, endpointStatsIssued, page, perPage, from, to) }
<filename>src/hssh/local_topological/event.h /* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of <NAME>, <EMAIL>. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file event.h * \author <NAME> * * Declaration of the LocalAreaEvent interface. */ #ifndef HSSH_LOCAL_TOPOLOGICAL_EVENT_H #define HSSH_LOCAL_TOPOLOGICAL_EVENT_H #include <hssh/local_metric/pose.h> #include <hssh/utils/id.h> #include <system/message_traits.h> #include <cereal/access.hpp> #include <string> #include <vector> #include <cstdint> namespace vulcan { namespace hssh { class LocalAreaEvent; class LocalAreaEventVisitor; // Types used for containing various events and event sequences using LocalAreaEventPtr = std::shared_ptr<LocalAreaEvent>; using LocalAreaEventVec = std::vector<LocalAreaEventPtr>; /** * LocalAreaEvent is the base class for every event that happens in the system. The following is true of every * event: * * 1) Occurs at an area (area) * 2) Has a monotonically increasing id (sequenceId) * 3) Supports the LocalAreaEventVisitor (accept) * * The LocalAreaEvent hierarchy is mostly just a discriminated union. The events themselves are merely informative, but * don't perform operations, hence just some observer methods. */ class LocalAreaEvent { public: using IdIter = std::vector<Id>::const_iterator; virtual ~LocalAreaEvent(void) { } /** * timestamp retrieves the time at which the event occurred. */ int64_t timestamp(void) const { return timestamp_; } /** * sequenceId retrieves the id for the event. */ int32_t sequenceId(void) const { return id_; } /** * pose retrieves the approximate pose of the robot when the event occurred. */ LocalPose pose(void) const { return pose_; } /** * beginAreaIds is the start iterator for all area ids involved with this area. */ virtual IdIter beginAreaIds(void) const = 0; /** * endAreaIds is the end iterator for all area ids involved with this area. */ virtual IdIter endAreaIds(void) const = 0; /** * description produces a text description of the event that occurred. */ virtual std::string description(void) const = 0; /** * clone produces a copy of the LocalAreaEvent. */ virtual LocalAreaEventPtr clone(void) const = 0; /** * accept accepts a LocalAreaEventVisitor and calls the appropriate visitXXXX method. */ virtual void accept(LocalAreaEventVisitor& visitor) const = 0; protected: /** * Constructor for LocalAreaEvent. * * Optionally sets the id for the event. A new id should be created whenever an actually new event is being created. * The default constructor for an event, used solely for serialization purposes, should not be setting the id, as it * will be loaded from a file. * * \param timestamp Time at which the event occurred * \param pose Pose when the event occurred (approximately) * \param needNewId Flag indicating if a new event id should be generated */ LocalAreaEvent(int64_t timestamp, const LocalPose& pose, bool needNewId) : timestamp_(timestamp) , pose_(pose) , id_(needNewId ? nextEventId() : -1) { } /** * Default constructor for LocalAreaEvent. */ LocalAreaEvent(void) = default; private: int64_t timestamp_ = -1; LocalPose pose_; int32_t id_ = -1; int32_t nextEventId(void) { static int32_t eventId = 0; return eventId++; } // Serialization support friend class cereal::access; template <class Archive> void serialize(Archive& ar) { ar (timestamp_, pose_, id_); } }; } } DEFINE_SYSTEM_MESSAGE(hssh::LocalAreaEventVec, ("HSSH_LOCAL_TOPO_EVENTS")) #endif // HSSH_LOCAL_TOPOLOGICAL_EVENT_H
<reponame>Psyruss77/TestSuite4<filename>linker_lib/src/util.rs /* This file is part of TON OS. TON OS is free software: you can redistribute it and/or modify it under the terms of the Apache License 2.0 (http://www.apache.org/licenses/) Copyright 2019-2021 (c) TON LABS */ use num::{BigInt}; use crate::num::ToPrimitive; use std::io::Cursor; use std::time::SystemTime; use std::str::FromStr; use ton_types::{ UInt256, SliceData, AccountId, cells_serialization::{deserialize_cells_tree} }; use ton_block::{ CommonMsgInfo, MsgAddressIntOrNone, CurrencyCollection, Deserializable, ExternalInboundMessageHeader, Grams, InternalMessageHeader, Message, MsgAddressExt, MsgAddressInt, StateInit, UnixTime32, }; pub fn bigint_to_u64(n: &BigInt) -> u64 { n.to_biguint().unwrap().to_u64().unwrap() } pub fn get_msg_value(msg: &Message) -> Option<u64> { let grams = &msg.get_value()?.grams; let grams = bigint_to_u64(&grams.value()); Some(grams) } fn get_src_addr_mut<'a>(msg: &'a mut Message) -> Option<&'a mut MsgAddressIntOrNone> { match msg.header_mut() { CommonMsgInfo::IntMsgInfo(hdr) => Some(&mut hdr.src), CommonMsgInfo::ExtOutMsgInfo(hdr) => Some(&mut hdr.src), CommonMsgInfo::ExtInMsgInfo(_) => None } } pub fn substitute_address(mut msg: Message, address: &MsgAddressInt) -> Message { let src = get_src_addr_mut(&mut msg).unwrap(); if *src == MsgAddressIntOrNone::None { *src = MsgAddressIntOrNone::Some(address.clone()); } msg } pub fn convert_address(address: UInt256, wc: i8) -> MsgAddressInt { MsgAddressInt::with_standart(None, wc, AccountId::from(address)).unwrap() } pub fn load_from_file(contract_file: &str) -> StateInit { let mut csor = Cursor::new(std::fs::read(contract_file).unwrap()); let cell = deserialize_cells_tree(&mut csor).unwrap().remove(0); StateInit::construct_from(&mut cell.into()).unwrap() } pub fn create_external_inbound_msg(src_addr: MsgAddressExt, dst_addr: MsgAddressInt, body: Option<SliceData>) -> Message { let mut hdr = ExternalInboundMessageHeader::default(); hdr.dst = dst_addr; hdr.src = src_addr; hdr.import_fee = Grams(0x1234u32.into()); // TODO: what's that? let mut msg = Message::with_ext_in_header(hdr); *msg.body_mut() = body; msg } pub fn create_internal_msg( src_addr: MsgAddressInt, dst_addr: MsgAddressInt, value: CurrencyCollection, lt: u64, at: u32, body: Option<SliceData>, bounced: bool, ) -> Message { let mut hdr = InternalMessageHeader::with_addresses( src_addr, dst_addr, value, ); hdr.bounce = !bounced; hdr.bounced = bounced; hdr.ihr_disabled = true; hdr.ihr_fee = Grams::from(0u64); hdr.created_lt = lt; hdr.created_at = UnixTime32(at); let mut msg = Message::with_int_header(hdr); *msg.body_mut() = body; msg } pub fn get_now() -> u64 { SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u64 } pub fn decode_address(address: &String) -> MsgAddressInt { MsgAddressInt::from_str(&address).unwrap() }
Almost $4 billion is needed to meet the humanitarian demands of countries facing food shortages because of an El Nino-induced drought, the United Nations said. About 60 million people, including 40 million in eastern and southern Africa, face a lack of food because of El Nino, which has scorched crops, the UN’s Food and Agricultural Organization said in a statement on its website Wednesday. With scientists forecasting an increasing likelihood of the opposite rain- and flood-inducing La Nina taking place, the number of those affected by the combined impacts of the events may reach 100 million, it said. The El Nino-induced drought damaged crops from palm oil, rice and sugar in Asia to grains in southern Africa and robusta coffee in South America. Storms spurred by the phenomenon have wiped out harvests in Fiji and some of its neighboring island states, the FAO said. The agency, together with the UN’s World Food Programme and International Fund for Agricultural Development, is “redoubling efforts to mitigate the negative impacts and capitalize on the opportunities of a likely La Nina phenomenon in the coming months,” it said. “Acting now will ensure that farmers have sufficient levels of agricultural inputs for upcoming planting seasons.” Opportunity window There is a three-month window before the start of southern Africa’s corn-planting season in which interventions such as distributing agricultural inputs “are urgently needed to avoid the dependence of millions of rural families on humanitarian assistance programs well into 2018,” the FAO said. The organization is on standby to provide emergency seeds and tools in Vietnam, where drought and saltwater intrusion are threatening farmers’ livelihoods, where IFAD is also supporting growers. More than 7.6 million people have received food assistance from the WFP in Ethiopia and a further 260,000 have been helped in Papua New Guinea.
// Open is a wrapper around os.Open that will also check FS to access // embedded data. The intended use is to use the an embedding library to create an // Asset function that matches this signature. func Open(file string) (io.ReadCloser, error) { fixedPath := fixWindowsPath(file) f, readErr := FS.Open(fixedPath) if readErr != nil && OSFallback { osFile, err := os.Open(file) if err != nil { return nil, err } return osFile, nil } return f, readErr }
/*********************************************************************/ /** ** ** GetNextStompMsgToSend ** ** Forms the next stomp frame to send and changes state to start sending it ** ** \param sc - pointer to STOMP connection ** ** \return USP_ERR_OK if successfully formed next STOMP frame to send, USP_ERR_INTERNAL_ERROR if unable to get agent or controller queue name ** **************************************************************************/ int GetNextStompMsgToSend(stomp_connection_t *sc) { int err = USP_ERR_OK; stomp_send_item_t *queued_msg; if (sc->perform_resubscribe & SCHEDULE_UNSUBSCRIBE) { sc->perform_resubscribe &= (~SCHEDULE_UNSUBSCRIBE); err = StartSendingFrame_UNSUBSCRIBE(sc); } else if (sc->perform_resubscribe & SCHEDULE_SUBSCRIBE) { sc->perform_resubscribe &= (~SCHEDULE_SUBSCRIBE); err = StartSendingFrame_SUBSCRIBE(sc); } else { RemoveExpiredStompMessages(sc); queued_msg = (stomp_send_item_t *) sc->usp_record_send_queue.head; if (queued_msg != NULL) { err = StartSendingFrame_SEND(sc, queued_msg->controller_queue, queued_msg->agent_queue, queued_msg->usp_msg_type, queued_msg->pbuf, queued_msg->pbuf_len, queued_msg->content_type, queued_msg->err_id_header); } } return err; }
<filename>src/utils/darkmode.ts<gh_stars>10-100 import { backgroundSemiAccent, darkBackgroundSemiAccent } from '@/styles/colors' /** * 시스템이 다크 모드를 사용하는지 확인하여 boolean으로 반환합니다. */ export const useDarkMode = (): boolean => { return window.matchMedia('screen and (prefers-color-scheme: dark)').matches } /** * 현재 설정에 맞춰 다크모드 사용 여부를 반환합니다. * @param active * @param system */ export const checkSystemDark = (active: boolean, system: boolean): boolean => { return system ? useDarkMode() : active } export const updateMetaTheme = (value: string) => { const metaTheme = document.querySelector('meta[name="theme-color"]') if (metaTheme) { metaTheme.setAttribute('content', value) } } /** * 인자 값에 따라서 <html>의 클래스를 지정합니다. * @param value */ export const toggleDarkMode = (value: boolean) => { document.documentElement.classList[value ? 'add' : 'remove']('llct-dark') updateMetaTheme(value ? darkBackgroundSemiAccent : backgroundSemiAccent) } export const onModeUpdate = (cb: () => void) => { const media = window.matchMedia('screen and (prefers-color-scheme: dark)') media.addEventListener('change', () => { cb() }) }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { EmpresasViewComponent } from './empresas-view/empresas-view.component'; import { EmpresasSectionComponent } from './empresas-section/empresas-section.component'; import { SharedModule } from '../shared/shared.module'; import { EmpresasCardComponent } from './empresas-card/empresas-card.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ EmpresasViewComponent, EmpresasSectionComponent, EmpresasCardComponent, ], imports: [CommonModule, HttpClientModule, SharedModule], }) export class EmpresasModule {}
/** * Parses an object name, softening any exceptions that result. Useful * for when you know the object name is going to be valid, or you don't * care about catching the resulting exception. * * @param name the name to parse * @return the parsed version of the name * @throws IllegalArgumentException if the name can't be parsed */ public static ObjectName parseName(String name) { try { return new ObjectName(name); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("bad name " + name, e); } }
/* * Forward Declarations */ /* * Text draw code + helper functions */ #include "fontUtils/characterStruct.h" // Provides a simple struct for caching character glyph data #include "fontUtils/atlasClass.h" // Provides a class for building a Text Atlas + OpenGL texture mapping, etc. #include "fontUtils/primCharTrig.cpp" // Provides a primitive for drawing characters #include "fontUtils/primStringTRIG.cpp" // Provides a high-order primitive for drawing strings //std::vector<textAtlas> fontAtlases; // Used to store all generated fonts //textAtlas* quack; extern std::map<std::string, textAtlas> textFonts; extern std::string selectedAtlas; // C/C++ function for drawing text void drawText( std::string inputString, // string of text draw GLfloat horiAlignment, // 0.0=left, 0.5=center, 1.0=right GLfloat vertAlignment, // 0.0=bottom, 0.5=center, 1.0=top GLfloat gx, // X position GLfloat gy, // Y position GLfloat sx, // X scale GLfloat sy, // Y scale GLfloat w2h, // width to height ration textAtlas* atlas, // texture atlas to draw characters from GLfloat* textColor, // color of text GLfloat* faceColor, // color of backdrop drawCall* textLine, // pointer to input drawCall to write text drawCall* textBackdrop // pointer to input drawCall to write text backdrop ); // C/C++ overload for drawing text, no background void drawText( std::string inputString, // string of text draw GLfloat horiAlignment, // 0.0=left, 0.5=center, 1.0=right GLfloat vertAlignment, // 0.0=bottom, 0.5=center, 1.0=top GLfloat gx, // X position GLfloat gy, // Y position GLfloat sx, // X scale GLfloat sy, // Y scale GLfloat w2h, // width to height ration textAtlas* atlas, // texture atlas to draw characters from GLfloat* textColor, // color of text GLfloat* faceColor, // color of backdrop drawCall* textLine // pointer to input drawCall to write text ); #include "fontUtils/drawText.cpp" // Draws an input string with a given font #include "fontUtils/buildAtlas.cpp" // Builds a text Atlas with data ferried from Python, stores in global vector
package cd4017be.rs_ctr2.part; import static cd4017be.api.grid.IGridHost.posOfport; import static cd4017be.math.Linalg.*; import java.util.List; import cd4017be.rs_ctr2.Content; import cd4017be.rs_ctr2.Main; import cd4017be.api.grid.*; import cd4017be.lib.render.MicroBlockFace; import cd4017be.lib.render.model.JitBakedModel; import cd4017be.lib.util.ItemFluidUtil; import net.minecraft.client.renderer.model.BakedQuad; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.*; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; /**@author CD4017BE */ public class Cable extends GridPart implements IWire { public Cable() { super(2); } public Cable(int pos, Direction d1, Direction d2, int type) { this(); this.bounds = 1L << pos; this.ports[0] = port(pos, d1, type); this.ports[1] = port(pos, d2, type); } @Override public Item item() { return ITEMS[ports[0] >> 12 & 7]; } @Override public ItemStack asItemStack() { return new ItemStack(item(), Long.bitCount(bounds)); } @Override public byte getLayer() { return L_INNER; } @Override public ActionResultType onInteract(PlayerEntity player, Hand hand, BlockRayTraceResult hit, int pos) { if (hand != null) return ActionResultType.PASS; if (!player.level.isClientSide && player.getMainHandItem().getItem() instanceof IGridItem) { remove(pos); if (!player.isCreative()) ItemFluidUtil.dropStack(new ItemStack(item()), player); } return ActionResultType.CONSUME; } public void merge(GridPart other) { if (!(other instanceof Cable && (bounds & other.bounds) == 0)) return; short[] tp = this.ports, op = other.ports; if (tp[0] == op[1]) tp[0] = op[0]; else if (tp[1] == op[0]) tp[1] = op[1]; else if (tp[0] == op[0]) tp[0] = op[1]; else if (tp[1] == op[1]) tp[1] = op[0]; else return; bounds |= other.bounds; other.host.removePart(other); } public void addTo(IGridHost host) { Port p; if ( (p = host.findPort(this, ports[0])) != null ? !p.isMaster() : (p = host.findPort(this, ports[1])) != null && p.isMaster() ) { short p0 = ports[0]; ports[0] = ports[1]; ports[1] = p0; } host.addPart(this); } public void remove(int pos) { //remove old part: IGridHost host = this.host; host.removePart(this); long b = bounds & ~(1L << pos); if (b == 0) { host.removeIfEmpty(); return; } //split up: long f0 = path(b, ports[0]); long f1 = path(b, ports[1]); if (f0 != 0) { Cable part = new Cable(); if (f1 == f0) {//still in one piece f1 = 0; part.ports[1] = ports[1]; } else part.ports[1] = portNear(f0, pos, ports[1] >> 12); part.ports[0] = ports[0]; part.bounds = f0; b &= ~f0; host.addPart(part); } if (f1 != 0) { Cable part = new Cable(); part.ports[0] = portNear(f1, pos, ports[0] >> 12); part.ports[1] = ports[1]; part.bounds = f1; b &= ~f1; host.addPart(part); } //drop remainder: if (b != 0) ItemFluidUtil.dropStack(new ItemStack(item(), Long.bitCount(b)), host.world(), host.pos()); host.removeIfEmpty(); } private static short portNear(long b, int pos, int type) { Direction d; if (( 3 & pos) != 0 && (b >>> pos - 1 & 1) != 0) d = Direction.WEST; else if (( 3 & ~pos) != 0 && (b >>> pos + 1 & 1) != 0) d = Direction.EAST; else if ((12 & pos) != 0 && (b >>> pos - 4 & 1) != 0) d = Direction.DOWN; else if ((12 & ~pos) != 0 && (b >>> pos + 4 & 1) != 0) d = Direction.UP; else if ((48 & pos) != 0 && (b >>> pos - 16 & 1) != 0) d = Direction.NORTH; else if ((48 & ~pos) != 0 && (b >>> pos + 16 & 1) != 0) d = Direction.SOUTH; else {pos = Long.numberOfTrailingZeros(b); d = Direction.NORTH;} return port(pos, d, type); } private static long path(long b, short port) { int p = posOfport(port); if ((p < 0 || (b >> p & 1) == 0) && (p = posOfport(port - 0x111)) < 0) return 0L; return floodFill(b, 1L << p); } @Override public void storeState(CompoundNBT nbt, int mode) { super.storeState(nbt, mode); nbt.putLong("bounds", bounds); nbt.putInt("ports", ports[0] & 0xffff | ports[1] << 16); } @Override public void loadState(CompoundNBT nbt, int mode) { super.loadState(nbt, mode); bounds = nbt.getLong("bounds"); int port = nbt.getInt("ports"); ports[0] = (short)port; ports[1] = (short)(port >>> 16); } @Override public Object getHandler(int port) { Port p = host.findPort(this, ports[port ^ 1]); return p == null ? null : p.getHandler(); } @Override public void setHandler(int port, Object handler) { Port p = host.findPort(this, ports[port ^ 1]); if (p != null) p.setHandler(handler); } @Override public boolean isMaster(int channel) { return channel != 0; } @Override @OnlyIn(Dist.CLIENT) public void fillModel(JitBakedModel model, long opaque) { MicroBlockFace[] faces = MicroBlockFace.facesOf(MODELS[ports[0] >> 12 & 7]); List<BakedQuad> quads = model.inner(); long b = bounds, visible = ~opaque; drawPort(quads, faces, ports[0], b, visible); drawPort(quads, faces, ports[1], b, visible); drawStrips(quads, faces, b & b >>> 1 & 0x7777_7777_7777_7777L, visible, 0); drawStrips(quads, faces, b & b >>> 4 & 0x0fff_0fff_0fff_0fffL, visible, 1); drawStrips(quads, faces, b & b >>> 16 & 0x0000_ffff_ffff_ffffL, visible, 2); } @OnlyIn(Dist.CLIENT) private static void drawStrips( List<BakedQuad> quads, MicroBlockFace[] faces, long line, long visible, int ax ) { int s = 1 << ax + ax, d = ax == 0 ? 2 : ax - 1; while(line != 0) { int p = Long.numberOfTrailingZeros(line), n = 1; long m = 1L << p; for (long l = m << s; (line & l) != 0; l <<= s, n++) m |= l; line &= ~m; if (((m | m << s) & visible) == 0) continue; float[] vec = sca(3, dadd(3, vec(p), .25F), .25F); float[] size = {.125F, .125F, .125F}; size[ax] += n * .25F; for (int i = 0; i < 6; i++) if (i >> 1 != d && faces[i] != null) quads.add(faces[i].makeRect(vec, size)); } } @OnlyIn(Dist.CLIENT) private static void drawPort( List<BakedQuad> quads, MicroBlockFace[] faces, int port, long b, long visible ) { int p0 = IGridHost.posOfport(port); int p1 = IGridHost.posOfport(port - 0x111); boolean visible0 = p0 < 0 || (visible >>> p0 & 1) != 0; boolean visible1 = p1 < 0 || (visible >>> p1 & 1) != 0; if ((b >>> p0 & 1) == 0) p0 = -1; if ((b >>> p1 & 1) == 0) p1 = -1; if (p0 < 0 ^ p1 >= 0 || !(visible0 | visible1)) return; if (p0 >= 0) { boolean v = visible0; visible0 = visible1; visible1 = v; } else p0 = p1; int ax = Integer.numberOfTrailingZeros(0x111 & ~port) >> 2; if (ax >= 3) return; float[] vec = dadd(3, vec(p0), .25F); float[] size = {.5F, .5F, .5F}; if (p1 < 0) vec[ax] -= .2505F; size[ax] = .751F; sca(3, vec, .25F); sca(3, size, .25F); int d = p1 >>> 31 | (ax == 0 ? 4 : ax - 1 << 1); for (int i = 0; i < 6; i++) if (i != d && faces[i] != null && (i == (d ^ 1) ? visible0 : visible1)) quads.add(faces[i].makeRect(vec, size)); } private static final Item[] ITEMS = { Content.data_cable, Content.power_cable, Content.item_cable, Content.fluid_cable, Content.block_cable, Items.AIR, Items.AIR, Items.AIR }; public static final ResourceLocation[] MODELS = { Main.rl("part/data_cable"), Main.rl("part/power_cable"), Main.rl("part/item_cable"), Main.rl("part/fluid_cable"), Main.rl("part/block_cable"), null, null, null }; @Override public boolean merge(IGridHost other) { Port p0 = other.findPort(this, ports[0]); Port p1 = other.findPort(this, ports[1]); Cable c0 = p0 != null && p0.host instanceof Cable ? (Cable)p0.host : null; Cable c1 = p1 != null && p1.host instanceof Cable ? (Cable)p1.host : null; int i = 1; if (c0 == null) { if (c1 == null) return true; p0 = p1; c0 = c1; c1 = null; i = 0; } c0.bounds |= this.bounds; if (c1 != null) { c0.bounds |= c1.bounds; c0.ports[p0.channel] = c1.ports[p1.channel ^ 1]; other.removePart(c1); } else c0.ports[p0.channel] = ports[i]; return false; } @Override public boolean canRotate() { return true; } @Override public void rotate(int steps) { rotate(ports, steps); super.rotate(steps); } @Override public boolean canMove(Direction d, int n) { long m = mask(d.ordinal(), n), b0 = bounds & m, b1 = bounds & ~m; return b0 == 0 || b1 == 0 || Long.bitCount(outline(b0) & b1) == 1; } @Override public GridPart move(Direction d, int n) { GridPart part = super.move(d, n); if (part == null || part == this) { move(ports, d, n, part == this); return part; } move(part.ports, d, n, true); move(ports, d, n, false); int xor = 0; long b = part.bounds; switch(d) { case DOWN: b >>>= 12; xor = 0x080; break; case UP: b <<= 12; xor = 0x080; break; case NORTH: b >>>= 48; xor = 0x800; break; case SOUTH: b <<= 48; xor = 0x800; break; case WEST: b >>>= 3; xor = 0x008; break; case EAST: b <<= 3; xor = 0x008; break; } short p0 = port( Long.numberOfTrailingZeros(b & bounds & FACES[d.ordinal()]), d, ports[0] >> 12 ), p1 = (short)(p0 ^ xor); if (overflow(ports[0])) { ports[0] = p0; part.ports[1] = p1; } else { ports[1] = p0; part.ports[0] = p1; } return part; } private static boolean overflow(short p) { return ((p & 0x888) * 7 >> 3 & p) != 0; } @Override protected Cable copy(long bounds) { Cable c = new Cable(); c.bounds = bounds; c.ports[0] = ports[0]; c.ports[1] = ports[1]; return c; } }
package com.weichu.mdesigner.api.service.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.weichu.mdesigner.api.service.IMerchantDictItemService; import com.weichu.mdesigner.api.service.IMerchantGoodsExtraService; import com.weichu.mdesigner.common.entity.MerchantDictionary; import com.weichu.mdesigner.common.entity.MerchantDictionaryExample; import com.weichu.mdesigner.common.entity.MerchantDictionaryItem; import com.weichu.mdesigner.common.entity.MerchantDictionaryItemExample; import com.weichu.mdesigner.common.mapper.MerchantDictionaryItemMapper; import com.weichu.mdesigner.common.mapper.MerchantDictionaryMapper; /** * 商家字典 可自行维护的字典(计量单位、商品附属属性等) * * @author Administrator * */ @Service @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class) public class MerchantDictItemServiceImpl implements IMerchantDictItemService { @Autowired private MerchantDictionaryMapper dictMapper; @Autowired private MerchantDictionaryItemMapper dictItemMapper; @Autowired private IMerchantGoodsExtraService extraService; @Override public int saveExtra(MerchantDictionary extra, int mid) throws Exception { MerchantDictionaryExample example = new MerchantDictionaryExample(); example.createCriteria().andDictCodeEqualTo(extra.getDictCode()).andMerchantIdEqualTo(mid); MerchantDictionaryExample.Criteria criteria = example.createCriteria(); criteria.andDictCodeEqualTo(extra.getDictCode()).andMerchantIdEqualTo(0); example.or(criteria); if(dictMapper.selectByExample(example).size() > 0) { throw new Exception("属性代码重复,请换个代码"); } extra.setMerchantId(mid); extra.setEnabled("1"); extra.setCategory(2); extra.setCreateTime(new Date()); dictMapper.insertSelective(extra); return extra.getId(); } @Override public int updateExtra(MerchantDictionary extra, int mid) throws Exception { if(extra.getMerchantId() == null || mid != extra.getMerchantId()) { throw new Exception("非法操作"); } // MerchantDictionaryExample example = new MerchantDictionaryExample(); // example.createCriteria().andIdNotEqualTo(extra.getId()).andDictCodeEqualTo(extra.getDictCode()).andMerchantIdEqualTo(mid); // MerchantDictionaryExample.Criteria criteria = example.createCriteria(); // criteria.andDictCodeEqualTo(extra.getDictCode()).andMerchantIdEqualTo(0); // example.or(criteria); // // if(dictMapper.selectByExample(example).size() > 0) { // throw new Exception("属性代码重复,请换个代码"); // } //字典代码不允许修改 extra.setDictCode(null); extra.setMerchantId(mid); extra.setModifyTime(new Date()); return dictMapper.updateByPrimaryKeySelective(extra); } @Override public int deleteExtra(int id, int mid) { MerchantDictionaryExample example = new MerchantDictionaryExample(); example.createCriteria().andMerchantIdEqualTo(mid).andIdEqualTo(id); MerchantDictionaryItemExample itemExample = new MerchantDictionaryItemExample(); itemExample.createCriteria().andDictIdEqualTo(id).andMerchantIdEqualTo(mid); dictItemMapper.deleteByExample(itemExample); //删除已关联到商品的附属属性 extraService.deleteByExtraId(id, mid); return dictMapper.deleteByExample(example); } @Override public MerchantDictionary selectExtraById(Integer id, int mid) { MerchantDictionaryExample example = new MerchantDictionaryExample(); example.createCriteria().andIdEqualTo(id).andMerchantIdEqualTo(mid); List<MerchantDictionary> dicts = dictMapper.selectByExample(example); if (!dicts.isEmpty()) { return dicts.get(0); } return null; } @Override public int saveDictItem(MerchantDictionaryItem dictItem, int mid) throws Exception { MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); example.createCriteria().andMerchantIdEqualTo(mid).andDictCodeEqualTo(dictItem.getDictCode()) .andItemValueEqualTo(dictItem.getItemValue()); MerchantDictionaryItemExample.Criteria criteria = example.createCriteria(); criteria.andMerchantIdEqualTo(0).andDictCodeEqualTo(dictItem.getDictCode()) .andItemValueEqualTo(dictItem.getItemValue()); example.or(criteria); if(dictItemMapper.selectByExample(example).size() > 0) { throw new Exception("附属属性项的值重复."); } dictItem.setMerchantId(mid); dictItem.setEnabled("1"); dictItem.setCreateTime(new Date()); dictItemMapper.insertSelective(dictItem); return dictItem.getId(); } @Override public int deleteDictItem(int dictItemId, int mid) { MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); example.createCriteria().andIdEqualTo(dictItemId).andMerchantIdEqualTo(mid); return dictItemMapper.deleteByExample(example); } @Override public int updateDictItem(MerchantDictionaryItem dictItem, int mid) throws Exception { if (dictItem.getMerchantId() == null || mid != dictItem.getMerchantId()) { throw new Exception("非法操作"); } // MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); // example.createCriteria().andIdNotEqualTo(dictItem.getId()).andMerchantIdEqualTo(mid).andDictCodeEqualTo(dictItem.getDictCode()) // .andItemValueEqualTo(dictItem.getItemValue()); // MerchantDictionaryItemExample.Criteria criteria = example.createCriteria(); // criteria.andMerchantIdEqualTo(0).andDictCodeEqualTo(dictItem.getDictCode()) // .andItemValueEqualTo(dictItem.getItemValue()); // example.or(criteria); // if(dictItemMapper.selectByExample(example).size() > 0) { // throw new Exception("附属属性项的值重复."); // } dictItem.setItemValue(null);//属性(数据)项的值不允许修改 dictItem.setModifyTime(new Date()); return dictItemMapper.updateByPrimaryKeySelective(dictItem); } @Override public MerchantDictionaryItem selectDictItemById(int dictItemId, int mid) { MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); example.createCriteria().andIdEqualTo(dictItemId).andMerchantIdEqualTo(mid); List<MerchantDictionaryItem> dictItems = dictItemMapper.selectByExample(example); if (!dictItems.isEmpty()) { return dictItems.get(0); } return null; } @Override public List<MerchantDictionary> selectDict(MerchantDictionary dict, int mid) { MerchantDictionaryExample example = new MerchantDictionaryExample(); example.setOrderByClause("sort_no asc, id asc"); //商品附属属性(可以增删改) MerchantDictionaryExample.Criteria criteria = example.createCriteria(); criteria.andMerchantIdEqualTo(mid).andEnabledEqualTo("1"); if (!StringUtils.isEmpty(dict.getDictName())) { criteria.andDictNameLike("%" + dict.getDictName() + "%"); } if (!StringUtils.isEmpty(dict.getDictCode())) { criteria.andDictCodeLike("%" + dict.getDictCode() + "%"); } if (!StringUtils.isEmpty(dict.getCategory())) { criteria.andCategoryEqualTo(dict.getCategory()); } //公用的字典(不能增删改) MerchantDictionaryExample.Criteria criteria2 = example.createCriteria(); criteria2.andMerchantIdEqualTo(0); criteria2.andEnabledEqualTo("1"); if (!StringUtils.isEmpty(dict.getDictName())) { criteria2.andDictNameLike("%" + dict.getDictName() + "%"); } if (!StringUtils.isEmpty(dict.getDictCode())) { criteria2.andDictCodeLike("%" + dict.getDictCode() + "%"); } if (!StringUtils.isEmpty(dict.getCategory())) { criteria2.andCategoryEqualTo(dict.getCategory()); } example.or(criteria2); return dictMapper.selectByExample(example); } @Override public List<MerchantDictionaryItem> selectDictItem(MerchantDictionaryItem dictItem) { MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); example.setOrderByClause("sort_no asc"); MerchantDictionaryItemExample.Criteria criteria = example.createCriteria(); criteria.andMerchantIdEqualTo(dictItem.getMerchantId()); if (!StringUtils.isEmpty(dictItem.getDictCode())) { criteria.andDictCodeEqualTo(dictItem.getDictCode()); } if(!StringUtils.isEmpty(dictItem.getItemValue())) { criteria.andItemValueEqualTo(dictItem.getItemValue()); } MerchantDictionaryItemExample.Criteria criteria2 = example.createCriteria(); criteria2.andMerchantIdEqualTo(0);//为0表示所有商家共用的字典项 if (!StringUtils.isEmpty(dictItem.getDictCode())) { criteria2.andDictCodeEqualTo(dictItem.getDictCode()); } if(!StringUtils.isEmpty(dictItem.getItemValue())) { criteria2.andItemValueEqualTo(dictItem.getItemValue()); } example.or(criteria2); return dictItemMapper.selectByExample(example); } @Override public List<MerchantDictionaryItem> selectDictItem(String dictCode, int mid) throws Exception { if (StringUtils.isEmpty(dictCode)) { throw new Exception("dictCode must not be empty!"); } MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); example.setOrderByClause("sort_no asc"); MerchantDictionaryItemExample.Criteria criteria = example.createCriteria(); criteria.andDictCodeEqualTo(dictCode); criteria.andMerchantIdEqualTo(mid); // criteria.andEnabledEqualTo("1"); MerchantDictionaryItemExample.Criteria criteria2 = example.createCriteria(); criteria2.andDictCodeEqualTo(dictCode); criteria2.andMerchantIdEqualTo(0);//为0表示所有商家共用的字典项 criteria2.andEnabledEqualTo("1"); example.or(criteria2); return dictItemMapper.selectByExample(example); } public List<MerchantDictionaryItem> selectEnabeldDictItem(String dictCode, int mid) { MerchantDictionaryItemExample example = new MerchantDictionaryItemExample(); example.setOrderByClause("sort_no asc"); MerchantDictionaryItemExample.Criteria criteria = example.createCriteria(); criteria.andDictCodeEqualTo(dictCode); criteria.andMerchantIdEqualTo(mid); criteria.andEnabledEqualTo("1"); MerchantDictionaryItemExample.Criteria criteria2 = example.createCriteria(); criteria2.andDictCodeEqualTo(dictCode); criteria2.andMerchantIdEqualTo(0);//为0表示所有商家共用的字典项 criteria2.andEnabledEqualTo("1"); example.or(criteria2); return dictItemMapper.selectByExample(example); } }
// acceptEnvPair reports whether the environment variable key=value pair // should be accepted from the client. It uses the same default as OpenSSH // AcceptEnv. func acceptEnvPair(kv string) bool { k, _, ok := strings.Cut(kv, "=") if !ok { return false } return k == "TERM" || k == "LANG" || strings.HasPrefix(k, "LC_") }
import java.util.LinkedList; import java.util.Scanner; public class AandBAndCompilationErrors { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int init = sc.nextInt(); int ab = 0; int bc = 0; int a =0; int b =0; int c = 0; // initial for (int i =0; i < init; i++) { a+=sc.nextInt(); } //System.out.println(list); for (int i = 0; i < init-1; i++) { b+=sc.nextInt(); } for (int i = 0; i < init-2; i++) { c+=sc.nextInt(); } //System.out.println(list); System.out.println(a-b); System.out.println(b-c); } }
The removal of an Angus tourist information point just before celebrations around the Declaration of Arbroath anniversary has been criticised. VisitScotland said 39 of its 65 centres would shut over the next two years, leaving 26 “high impact regional hubs”. The VisitScotland iCentre at the town’s harbour will cease trading from the end of March as the town gears up for the 700th anniversary of the signing of the Declaration of Arbroath, to be marked with a “world class celebration” in 2020. SNP Angus South MSP Graeme Dey said: “I recognise the way that many visitors access information has changed remarkably over the past decade and that this will continue to evolve. “Nevertheless this is disappointing news given, I understand, that the fall in usage of the Arbroath facility is markedly lower than the average decline nationally and we are fast approaching the 700th anniversary of the signing of the Declaration of Arbroath with all the potential for increased visitor numbers to the town that represents. “I have already raised with VisitScotland its plans for future information provision relating to this part of Angus and will be pursuing that in greater detail. “Elements of the local tourism sector itself, along with Angus Council, are doing their bit to bring visitors to the county in greater numbers and provide the best possible experience, but we also need the national tourism body deploying appropriate resource and effort to that purpose.” VisitScotland said information will continue to be provided in all the locations thanks to “partnership arrangements” with visitor attractions and organisations. The iCentre in Stonehaven will stop trading after this month. Jim Stephen, chairman of Stonehaven Town Partnership, which runs the Land Train in the seaside town and the caravan park, said: “We are gutted that the visitor centre is closing. “I can understand that the footfall is down in areas and VisitScotland is trying to make a decision, but what is its next move? A place like Stonehaven has thousands of visitors to places like Dunnottar Castle, the fireballs, the open air pool and Feein Market. “There should be a visitor centre so that people can see what great things there are to do in the town.” Jim Clarkson, Regional Partnerships Director at VisitScotland said: “The way visitors access information has changed significantly over the past decade. “It’s time to switch our focus and investment into new and diverse initiatives to ensure we are reaching as many visitors to Angus and Dundee as possible with the information they want, in the way they want it, when they want it. “With three in four adults now owning a smartphone, a key focus is ensuring our digital communications provide succinct inspirational and informational advice to visitors at every stage of their journey.”
def find_events(self): credentials = get_credentials() service = build('calendar', 'v3', credentials=credentials) now = datetime.datetime.utcnow().isoformat() + 'Z' events_result = service.events().list( calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime', ).execute() return events_result.get('items', [])
/************************************************************************* This function should never be called. It is here to prevent spurious compiler warnings about unused variables (in fact: used). *************************************************************************/ void ae_never_call_it() { ae_touch_ptr((void*)_ae_bool_must_be_8_bits_wide); ae_touch_ptr((void*)_ae_int32_t_must_be_32_bits_wide); ae_touch_ptr((void*)_ae_int64_t_must_be_64_bits_wide); ae_touch_ptr((void*)_ae_int_t_must_be_pointer_sized); }
<reponame>wenfeifei/miniblink49 //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by crash_generation_app.rc // #define IDC_SMALL 2 #define IDC_BIG 3
/** BEGIN_DOC ## Example ``` $ find PROJ/ -name "accepted_hits.bam" |\ java -jar dist/howmanybamdict.jar DICT 208e057b92b5c45262c59b40209b5fde 22 2725537669 chr1=195471971;chr10=130694993;chr11=122082543;chr12=120129022;chr13=120421639;chr14=124902244;chr15=104043685;chr16=98207768;chr17=94987271;chr18=90702639;chr19=61431566;chr2=182113224;chr3=160039680;chr4=156508116;chr5=151834684;chr6=149736546;chr7=145441459;chr8=129401213;chr9=124595110;chrM=16299;chrX=171031299;chrY=91744698 PROJ/S1/accepted_hits.bams.bam BAM PROJ/S1/accepted_hits.bam 208e057b92b5c45262c59b40209b5fde DICT 86b39aef44f740da797b89baf3f505d8 66 2730871774 chr1=195471971;chr10=130694993;chr11=122082543;chr12=120129022;chr13=120421639;chr14=124902244;chr15=104043685;chr16=98207768;chr17=94987271;chr18=90702639;chr19=61431566;chr1_GL456210_random=169725;chr1_GL456211_random=241735;chr1_GL456212_random=153618;chr1_GL456213_random=39340;chr1_GL456221_random=206961;chr2=182113224;chr3=160039680;chr4=156508116;chr4_GL456216_random=66673;chr4_GL456350_random=227966;chr4_JH584292_random=14945;chr4_JH584293_random=207968;chr4_JH584294_random=191905;chr4_JH584295_random=1976;chr5=151834684;chr5_GL456354_random=195993;chr5_JH584296_random=199368;chr5_JH584297_random=205776;chr5_JH584298_random=184189;chr5_JH584299_random=953012;chr6=149736546;chr7=145441459;chr7_GL456219_random=175968;chr8=129401213;chr9=124595110;chrM=16299;chrUn_GL456239=40056;chrUn_GL456359=22974;chrUn_GL456360=31704;chrUn_GL456366=47073;chrUn_GL456367=42057;chrUn_GL456368=20208;chrUn_GL456370=26764;chrUn_GL456372=28664;chrUn_GL456378=31602;chrUn_GL456379=72385;chrUn_GL456381=25871;chrUn_GL456382=23158;chrUn_GL456383=38659;chrUn_GL456385=35240;chrUn_GL456387=24685;chrUn_GL456389=28772;chrUn_GL456390=24668;chrUn_GL456392=23629;chrUn_GL456393=55711;chrUn_GL456394=24323;chrUn_GL456396=21240;chrUn_JH584304=114452;chrX=171031299;chrX_GL456233_random=336933;chrY=91744698;chrY_JH584300_random=182347;chrY_JH584301_random=259875;chrY_JH584302_random=155838;chrY_JH584303_random=158099 PROJ/S2/accepted_hits.bam ROJ/S2/accepted_hits.bam BAM PROJ/S2/accepted_hits.bam 86b39aef44f740da797b89baf3f505d8 BAM PROJ/S3/accepted_hits.bam 86b39aef44f740da797b89baf3f505d8 ``` END_DOC */ @Program(name="howmanybamdict", description="finds if there's are some differences in the sequence dictionaries.", keywords={"sam","bam","dict"}, modificationDate="20190912" ) public class HowManyBamDict extends Launcher { private static final Logger LOG = Logger.build(HowManyBamDict.class).make(); @Parameter(names={"-o","--output"},description=OPT_OUPUT_FILE_OR_STDOUT) private Path outputFile = null; private class Dict { SAMSequenceDictionary ssd; String hash; File representative; Dict(SAMSequenceDictionary ssd,File representative) { this.ssd=ssd; this.representative=representative; this.hash =ssd.md5(); } @Override public boolean equals(Object obj) { if(this==obj) return true; if(obj==null) return false; return this.ssd.equals(Dict.class.cast(obj).ssd); } @Override public int hashCode() { return ssd.hashCode(); } void print() { System.out.print("DICT"); System.out.print("\t"); System.out.print(this.hash); System.out.print("\t"); System.out.print(ssd.size()); System.out.print("\t"); System.out.print(ssd.getReferenceLength()); System.out.print("\t"); boolean first=true; for(SAMSequenceRecord ssr:ssd.getSequences()) { if(!first) System.out.print(";"); first=false; System.out.print(ssr.getSequenceName()); System.out.print('='); System.out.print(ssr.getSequenceLength()); } System.out.print("\t"); System.out.print(this.representative); System.out.println(); } } private Dict empty=null; private Set<Dict> allditcs=new LinkedHashSet<Dict>(); private void handle(PrintWriter out,File f) throws IOException { SamReader sfr=null; try { LOG.info(f.getPath()); sfr= super.openSamReader(f.getPath()); SAMFileHeader header=sfr.getFileHeader(); if(header==null || header.getSequenceDictionary()==null) { if(this.empty==null) { this.empty=new Dict(new SAMSequenceDictionary(),f); allditcs.add(this.empty); this.empty.print(); } out.print("BAM\t"); out.print(f.getPath()); out.print("\t"); out.print(this.empty.hash); out.println(); } else { Dict d=new Dict(header.getSequenceDictionary(), f); if(this.allditcs.add(d)) { d.print(); } out.print("BAM\t"); out.print(f.getPath()); out.print("\t"); out.print(d.hash); out.println(); } } catch (Exception e) { LOG.error(e.getMessage(),e); throw new IOException(e); } finally { CloserUtil.close(sfr); } } @Override public int doWork(List<String> args) { PrintWriter out=null; try { out = super.openPathOrStdoutAsPrintWriter(this.outputFile); if(args.isEmpty()) { LOG.info("Reading from stdin"); String line; BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); while((line=in.readLine())!=null) { if(line.isEmpty() || line.endsWith(File.separator) || line.startsWith("#")) continue; handle(out,new File(line)); } in.close(); } else { for(String filename:args) { handle(out,new File(filename)); } } out.flush(); return RETURN_OK; } catch(IOException err) { LOG.error(err); return -1; } finally { CloserUtil.close(out); } } public static void main(String[] args) { new HowManyBamDict().instanceMainWithExit(args); } }
<reponame>mdiener21/mapillary-js import {map} from "rxjs/operators"; import {Observable} from "rxjs"; import { ICoreNode, IFillNode, IGPano, ILatLon, } from "../API"; import {IEdge} from "../Edge"; import { IEdgeStatus, IMesh, ILoadStatus, NodeCache, } from "../Graph"; import {ImageSize} from "../Viewer"; /** * @class Node * * @classdesc Represents a node in the navigation graph. * * Explanation of position and bearing properties: * * When images are uploaded they will have GPS information in the EXIF, this is what * is called `originalLatLon` {@link Node.originalLatLon}. * * When Structure from Motions has been run for a node a `computedLatLon` that * differs from the `originalLatLon` will be created. It is different because * GPS positions are not very exact and SfM aligns the camera positions according * to the 3D reconstruction {@link Node.computedLatLon}. * * At last there exist a `latLon` property which evaluates to * the `computedLatLon` from SfM if it exists but falls back * to the `originalLatLon` from the EXIF GPS otherwise {@link Node.latlon}. * * Everything that is done in in the Viewer is based on the SfM positions, * i.e. `computedLatLon`. That is why the smooth transitions go in the right * direction (nd not in strange directions because of bad GPS). * * E.g. when placing a marker in the Viewer it is relative to the SfM * position i.e. the `computedLatLon`. * * The same concept as above also applies to the compass angle (or bearing) properties * `originalCa`, `computedCa` and `ca`. */ export class Node { private _cache: NodeCache; private _core: ICoreNode; private _fill: IFillNode; /** * Create a new node instance. * * @description Nodes are always created internally by the library. * Nodes can not be added to the library through any API method. * * @param {ICoreNode} coreNode - Raw core node data. */ constructor(core: ICoreNode) { this._cache = null; this._core = core; this._fill = null; } /** * Get assets cached. * * @description The assets that need to be cached for this property * to report true are the following: fill properties, image and mesh. * The library ensures that the current node will always have the * assets cached. * * @returns {boolean} Value indicating whether all assets have been * cached. */ public get assetsCached(): boolean { return this._core != null && this._fill != null && this._cache != null && this._cache.image != null && this._cache.mesh != null; } /** * Get alt. * * @description If SfM has not been run the computed altitude is * set to a default value of two meters. * * @returns {number} Altitude, in meters. */ public get alt(): number { return this._fill.calt; } /** * Get ca. * * @description If the SfM computed compass angle exists it will * be returned, otherwise the original EXIF compass angle. * * @returns {number} Compass angle, measured in degrees * clockwise with respect to north. */ public get ca(): number { return this._fill.cca != null ? this._fill.cca : this._fill.ca; } /** * Get capturedAt. * * @returns {number} Timestamp when the image was captured. */ public get capturedAt(): number { return this._fill.captured_at; } /** * Get camera uuid. * * @description Will be undefined if the camera uuid was not * recorded in the image exif information. * * @returns {string} Universally unique id for camera used * when capturing image. */ public get cameraUuid(): string { return this._fill.captured_with_camera_uuid; } public get ck1(): number { return this._fill.ck1; } public get ck2(): number { return this._fill.ck2; } /** * Get computedCA. * * @description Will not be set if SfM has not been run. * * @returns {number} SfM computed compass angle, measured * in degrees clockwise with respect to north. */ public get computedCA(): number { return this._fill.cca; } /** * Get computedLatLon. * * @description Will not be set if SfM has not been run. * * @returns {ILatLon} SfM computed latitude longitude in WGS84 datum, * measured in degrees. */ public get computedLatLon(): ILatLon { return this._core.cl; } /** * Get focal. * * @description Will not be set if SfM has not been run. * * @returns {number} SfM computed focal length. */ public get focal(): number { return this._fill.cfocal; } /** * Get full. * * @description The library ensures that the current node will * always be full. * * @returns {boolean} Value indicating whether the node has all * properties filled. */ public get full(): boolean { return this._fill != null; } /** * Get fullPano. * * @returns {boolean} Value indicating whether the node is a complete * 360 panorama. */ public get fullPano(): boolean { return this._fill.gpano != null && this._fill.gpano.CroppedAreaLeftPixels === 0 && this._fill.gpano.CroppedAreaTopPixels === 0 && this._fill.gpano.CroppedAreaImageWidthPixels === this._fill.gpano.FullPanoWidthPixels && this._fill.gpano.CroppedAreaImageHeightPixels === this._fill.gpano.FullPanoHeightPixels; } /** * Get gpano. * * @description Will not be set for non panoramic images. * * @returns {IGPano} Panorama information for panorama images. */ public get gpano(): IGPano { return this._fill.gpano; } /** * Get height. * * @returns {number} Height of original image, not adjusted * for orientation. */ public get height(): number { return this._fill.height; } /** * Get image. * * @description The image will always be set on the current node. * * @returns {HTMLImageElement} Cached image element of the node. */ public get image(): HTMLImageElement { return this._cache.image; } /** * Get image$. * * @returns {Observable<HTMLImageElement>} Observable emitting * the cached image when it is updated. */ public get image$(): Observable<HTMLImageElement> { return this._cache.image$; } /** * Get key. * * @returns {string} Unique key of the node. */ public get key(): string { return this._core.key; } /** * Get latLon. * * @description If the SfM computed latitude longitude exist * it will be returned, otherwise the original EXIF latitude * longitude. * * @returns {ILatLon} Latitude longitude in WGS84 datum, * measured in degrees. */ public get latLon(): ILatLon { return this._core.cl != null ? this._core.cl : this._core.l; } /** * Get loadStatus. * * @returns {ILoadStatus} Value indicating the load status * of the mesh and image. */ public get loadStatus(): ILoadStatus { return this._cache.loadStatus; } /** * Get merged. * * @returns {boolean} Value indicating whether SfM has been * run on the node and the node has been merged into a * connected component. */ public get merged(): boolean { return this._fill != null && this._fill.merge_version != null && this._fill.merge_version > 0; } /** * Get mergeCC. * * @description Will not be set if SfM has not yet been run on * node. * * @returns {number} SfM connected component key to which * image belongs. */ public get mergeCC(): number { return this._fill.merge_cc; } /** * Get mergeVersion. * * @returns {number} Version for which SfM was run and image was merged. */ public get mergeVersion(): number { return this._fill.merge_version; } /** * Get mesh. * * @description The mesh will always be set on the current node. * * @returns {IMesh} SfM triangulated mesh of reconstructed * atomic 3D points. */ public get mesh(): IMesh { return this._cache.mesh; } /** * Get organizationKey. * * @returns {string} Unique key of the organization to which * the node belongs. If the node does not belong to an * organization the organization key will be undefined. */ public get organizationKey(): string { return this._fill.organization_key; } /** * Get orientation. * * @returns {number} EXIF orientation of original image. */ public get orientation(): number { return this._fill.orientation; } /** * Get originalCA. * * @returns {number} Original EXIF compass angle, measured in * degrees. */ public get originalCA(): number { return this._fill.ca; } /** * Get originalLatLon. * * @returns {ILatLon} Original EXIF latitude longitude in * WGS84 datum, measured in degrees. */ public get originalLatLon(): ILatLon { return this._core.l; } /** * Get pano. * * @returns {boolean} Value indicating whether the node is a panorama. * It could be a cropped or full panorama. */ public get pano(): boolean { return this._fill.gpano != null && this._fill.gpano.FullPanoWidthPixels != null; } /** * Get private. * * @returns {boolean} Value specifying if image is accessible to * organization members only or to everyone. */ public get private(): boolean { return this._fill.private; } /** * Get projectKey. * * @returns {string} Unique key of the project to which * the node belongs. If the node does not belong to a * project the project key will be undefined. * * @deprecated This property will be deprecated in favor * of the organization key and private properties. */ public get projectKey(): string { return this._fill.project != null ? this._fill.project.key : null; } /** * Get rotation. * * @description Will not be set if SfM has not been run. * * @returns {Array<number>} Rotation vector in angle axis representation. */ public get rotation(): number[] { return this._fill.c_rotation; } /** * Get scale. * * @description Will not be set if SfM has not been run. * * @returns {number} Scale of atomic reconstruction. */ public get scale(): number { return this._fill.atomic_scale; } /** * Get sequenceKey. * * @returns {string} Unique key of the sequence to which * the node belongs. */ public get sequenceKey(): string { return this._core.sequence_key; } /** * Get sequenceEdges. * * @returns {IEdgeStatus} Value describing the status of the * sequence edges. */ public get sequenceEdges(): IEdgeStatus { return this._cache.sequenceEdges; } /** * @ignore * * Get sequenceEdges$. * * @description Internal observable, should not be used as an API. * * @returns {Observable<IEdgeStatus>} Observable emitting * values describing the status of the sequence edges. */ public get sequenceEdges$(): Observable<IEdgeStatus> { return this._cache.sequenceEdges$; } /** * Get spatialEdges. * * @returns {IEdgeStatus} Value describing the status of the * spatial edges. */ public get spatialEdges(): IEdgeStatus { return this._cache.spatialEdges; } /** * @ignore * * Get spatialEdges$. * * @description Internal observable, should not be used as an API. * * @returns {Observable<IEdgeStatus>} Observable emitting * values describing the status of the spatial edges. */ public get spatialEdges$(): Observable<IEdgeStatus> { return this._cache.spatialEdges$; } /** * Get userKey. * * @returns {string} Unique key of the user who uploaded * the image. */ public get userKey(): string { return this._fill.user.key; } /** * Get username. * * @returns {string} Username of the user who uploaded * the image. */ public get username(): string { return this._fill.user.username; } /** * Get width. * * @returns {number} Width of original image, not * adjusted for orientation. */ public get width(): number { return this._fill.width; } /** * Cache the image and mesh assets. * * @description The assets are always cached internally by the * library prior to setting a node as the current node. * * @returns {Observable<Node>} Observable emitting this node whenever the * load status has changed and when the mesh or image has been fully loaded. */ public cacheAssets$(): Observable<Node> { return this._cache.cacheAssets$(this.key, this.pano, this.merged).pipe( map( (cache: NodeCache): Node => { return this; })); } public cacheImage$(imageSize: ImageSize): Observable<Node> { return this._cache.cacheImage$(this.key, imageSize).pipe( map( (cache: NodeCache): Node => { return this; })); } /** * Cache the sequence edges. * * @description The sequence edges are cached asynchronously * internally by the library. * * @param {Array<IEdge>} edges - Sequence edges to cache. */ public cacheSequenceEdges(edges: IEdge[]): void { this._cache.cacheSequenceEdges(edges); } /** * Cache the spatial edges. * * @description The spatial edges are cached asynchronously * internally by the library. * * @param {Array<IEdge>} edges - Spatial edges to cache. */ public cacheSpatialEdges(edges: IEdge[]): void { this._cache.cacheSpatialEdges(edges); } /** * Dispose the node. * * @description Disposes all cached assets. */ public dispose(): void { if (this._cache != null) { this._cache.dispose(); this._cache = null; } this._core = null; this._fill = null; } /** * Initialize the node cache. * * @description The node cache is initialized internally by * the library. * * @param {NodeCache} cache - The node cache to set as cache. */ public initializeCache(cache: NodeCache): void { if (this._cache != null) { throw new Error(`Node cache already initialized (${this.key}).`); } this._cache = cache; } /** * Fill the node with all properties. * * @description The node is filled internally by * the library. * * @param {IFillNode} fill - The fill node struct. */ public makeFull(fill: IFillNode): void { if (fill == null) { throw new Error("Fill can not be null."); } this._fill = fill; } /** * Reset the sequence edges. */ public resetSequenceEdges(): void { this._cache.resetSequenceEdges(); } /** * Reset the spatial edges. */ public resetSpatialEdges(): void { this._cache.resetSpatialEdges(); } /** * Clears the image and mesh assets, aborts * any outstanding requests and resets edges. */ public uncache(): void { if (this._cache == null) { return; } this._cache.dispose(); this._cache = null; } } export default Node;
/** * Move to trash if trash exist in OS, else remove from file system * * @param fileToRemove: file to be removed * @return true if file is removed successfully * @throws IOException */ public static boolean removeFile(File fileToRemove) throws IOException { FileUtils fileUtils = FileUtils.getInstance(); if (fileUtils.hasTrash()) { fileUtils.moveToTrash( new File[]{fileToRemove} ); return true; } else { return deleteFolderOrFile(fileToRemove); } }
import { GetStaticProps } from 'next' import Head from 'next/head' import { stripe } from '../services/stripe' import { SubscribeButton } from '../components/SubscribeButton' import styles from '../styles/home.module.scss' interface HomeProps { product: { priceId: string; amount: number; } } export default function Home({ product }: HomeProps) { return ( <> <Head> <title>Home | ig.news</title> </Head> <main className={styles.contentContainer}> <section className={styles.hero}> <span>👏 Hey, welcome</span> <h1>News about <br /> the <span>React</span> world</h1> <p> Get access to all the publications <br /> <span>for {product.amount} month</span> </p> <SubscribeButton priceId={product.priceId} /> </section> <img src="/images/avatar.svg" alt="Girl coding" /> </main> </> ) } export const getStaticProps: GetStaticProps = async () => { const price = await stripe.prices.retrieve('price_1KPUbxEa9DWIVKt7gEVdINnK') const product = { priceId: price.id, amount: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', }).format(price.unit_amount / 100), // prices are usually saved in cents in the databases, so the need to divide by 100 } return { props: { product }, revalidate: 60 * 60 * 24, // 24 hours } } // 3 main ways to make an api call in React/Next.js // Client-side/Single-page Application (SPA) -> page that needs information that is loaded with some user action and not necessarily when the page is loaded/information that sometimes has no need to already be there when the page is loaded or that do not need indexing/SEO // Server-side (SSR) -> page that need dynamic user session data/real-time information from the user who is accessing, from the context of the request, and who need indexing/SEO // Static Site Generation (SSG) -> page that will be the same for all users and that need indexing/SEO
/** * Runs this gatherer and traverses the file system (optionally in a recursive * fashion) . Once the files are gathered, all waiting threads on the locks * monitor are notified. */ @Override public synchronized void run() { String path = this.config.get( Constants.OPT_COLLECTION_LOCATION ); boolean recursive = Boolean.valueOf( this.config.get( Constants.OPT_RECURSIVE ) ); this.ready = false; this.traverseFiles( new File( path ), recursive, true ); System.out.println( this.count + " files were submitted for processing" ); LOG.info( "{} files were submitted for processing successfully", this.count ); }
<filename>src/components/Game/render/elementsList.ts import { renderBlock } from './block'; import { Block } from '../types'; function renderElementsList(): void { const { blocks } = this.level; if (!blocks) { return; } const ctx: CanvasRenderingContext2D = this.elementsCanvas.getContext('2d'); let index = 1; ctx.clearRect(0, 0, this.cellSize * 3, this.cellSize * 11); for (let i = 1; i <= 8; i += 1) { const elements: Block[] = blocks.filter((block: Block) => { return block.type === i; }); if (elements && elements.length > 0) { renderBlock.call( this, ctx, elements[0].type, this.cellSize / 3, this.cellSize * (index - 1) + this.cellSize * (index - 1) / 3 + this.cellSize / 3, ); ctx.font = '5vmin Courier'; ctx.textAlign = 'left'; ctx.textBaseline = 'bottom'; ctx.fillStyle = 'rgb(0, 0, 0)'; ctx.fillText( `X${elements.length}`, this.cellSize / 2 + this.cellSize, this.cellSize * (index - 1) + this.cellSize * (index - 1) / 3 + this.cellSize / 3 + this.cellSize, ); index += 1; } } } export { renderElementsList };
def create_campaign(request): if request.method == 'POST': context = {'error_msg': 'ERROR, form not filled in properly'} form = CreationCampaignForm(request.POST) if form.is_valid(): campaign_name = form.cleaned_data['campaign_name'] target_group_name = form.cleaned_data['target_group_name'] email_template_name = form.cleaned_data['email_template_name'] landing_page_name = form.cleaned_data['landing_page_name'] smtp_profile_name = form.cleaned_data['smtp_profile_name'] phishing_url = form.cleaned_data['phishing_url'] launch_date = form.cleaned_data['launch_date'] if launch_date !='': args = [campaign_name, target_group_name, email_template_name, landing_page_name, smtp_profile_name, phishing_url, launch_date] else: args = [campaign_name, target_group_name, email_template_name, landing_page_name, smtp_profile_name, phishing_url] campaign, msg = create_campaign_(args) if msg == 'OK': context = {'campaign': campaign} else: context = {'error_msg': msg} else: form = CreationCampaignForm() context = {'form': form} return render(request, 'SETA_gophish/create_campaign.html', context)
def _other_sessions(user_id, token=None): if not user_id: if not token: return False sockets = Socket.get(token=token) else: sockets = Socket.get(user=user_id) return bool(sockets)
/** * * * @return list; a list of the constants mentioned in ASSERTION, in no particular order. Recurses into narts and sub-assertions, and includes the mt of the assertion (if it's a constant). * @unknown pace */ @LispMethod(comment = "@return list; a list of the constants mentioned in ASSERTION, in no particular order.\r\nRecurses into narts and sub-assertions, and includes the mt of the assertion (if it\'s a constant).\r\n@unknown pace") public static SubLObject assertion_constants(final SubLObject assertion) { assert NIL != assertion_handles.assertion_p(assertion) : "! assertion_handles.assertion_p(assertion) " + ("assertion_handles.assertion_p(assertion) " + "CommonSymbols.NIL != assertion_handles.assertion_p(assertion) ") + assertion; return cycl_utilities.formula_constants(list(assertion_cnf_or_gaf_hl_formula(assertion), assertion_mt(assertion)), T); }
Preferred place of death and end-of-life care for adult cancer patients in Iran: A cross-sectional study Background More than 50,000 deaths in terms of cancer occur annually in Iranian hospitals. Determining the preferred place of end-of-life care and death for cancer patients in Iran is a quality marker for good end-of-life care and good death. The purpose of this study was to determine the preferred place of end-of-life care and death in cancer patients. Method In 2021, the current descriptive cross-sectional investigation was carried out. Using the convenience sample approach, patients were chosen from three Tehran referral hospitals (the capital of Iran). A researcher-made questionnaire with three parts for demographic data, clinical features, and two questions on the choice of the desired location for end-of-life care and the death of cancer patients served as the data collecting instrument. Data were analyzed using SPSS software version 18. The relationship between the two variables preferred place for end-of-life care and death and other variables was investigated using chi-square, Fisher exact test, and multiple logistic regression. Result The mean age of patients participating in the study was 50.21 ± 13.91. Three hundred ninety (69.6%) of the patients chose home, and 170 (30.4%) patients chose the hospital as the preferred place of end-of-life care. Choosing the home as a preferred place for end-of-life care had a significant relationship with type of care (OR = .613 , P = .042), level of education (OR = 2.61 , P = 0.007), type of cancer (OR = 1.70 , P = .049), and income level (Mediate: (OR: 3.27 (1.49, 7.14), P = .003) and Low: (OR: 3.38 (1.52–7.52), P = .003). Also, 415 (75.2%) patients chose home and 137 (24.8%) patients chose hospital as their preferred place of death. Choosing the home as a preferred place of death had a significant relationship with marriage (OR = 1.62 , P = .039) and time to diagnostic disease less than 6 months (OR = 1.62 , P = .002). Conclusion The findings of the current research indicate that the majority of cancer patients selected their homes as the preferred location for end-of-life care and final disposition. Researchers advise paying more attention to patients’ wishes near the end of life in light of the findings of the current study. This will be achieved by strengthening the home care system using creating appropriate infrastructure, insurance coverage, designing executive instructions, and integration of palliative care in home care services. Introduction Cancer is the second leading cause of death in the world and the third leading cause of death in Iran (1)(2)(3). According to the World Health Organization, cancer caused the deaths of 10 million people in 2020 (1 in 6 deaths) with a mean age of 72 years worldwide (4). According to GLOBALCAN statistics, more than 110,000 new cases of cancer were detected in Iran in 2018, and by 2030, this figure is projected to rise to 156,000 (5).. Iran has documented 55,785 cancer-related fatalities so far this year (1). In general, only 39% of countries report access to primary healthcare and 40% of countries report access to palliative care in community care and home care (6). Weakness in access to palliative care and end-of-life care is more serious in cancer patients. However, only 14% of cancer patients get the end-of-life care they need (out of the 34% that need it) (7). Despite these figures, the state of end-of-life care in Iran is only partially quantified. Recently, in terms of the increasing incidence of cancer and the decline in the quality of end-of-life care of these patients, this type of service has received more attention from health policymakers (8). Dying and caring for patients' preferred place in the last days of life are considered a quality marker to have good end-of-life care worldwide (9). Many of these patients in the final stages of life attach great importance to the preferred place for end-of-life care (PPOEOLC) and preferred place of death (PPOD), and this place will have a significant impact on their quality of life and death and care (10,11). The terms "preferred place of death" (PPOD) and "preferred place for end-of-life care" (PPOEOLC) relate to people's preferences for where they would want to pass away or receive care in their last days, respectively (8). Awareness of patients' preferences about PPOEOLC and PPOD is essential for end-of-life palliative care planning (11). Besides, meeting these personal preferences is one of the ultimate criteria for success in palliative care (12). Therefore, understanding the PPOEOLC and PPOD is the first step to ensuring adequate resources for patients. The significance of this topic is shown by the many preferred surveys conducted to calculate the PPOEOLC and PPOD in the United Kingdom (9), the United States (13), European nations (14), and other countries (15). Regardless of cultural or national distinctions, the majority of cancer patients have selected their home as their PPOEOLC and PPOD (11,12,16). A systematic review study by Fereidouni et al. (3) in 2021 and a study by Brogaard et al. in 2013 (12) also showed that more than half of cancer patients preferred home as the PPOD and end-of-life care. However, the most common actual place of care and death for cancer patients in different countries is the hospital (15,17,18). In Iran, 60% of deaths occur in hospitals (18). The reported rate of achieving a PPOD in patients varies from 49% to 88% in western countries to 66% in south Africa (16). The effect of societal and cultural factors, sociodemographic factors, clinical characteristics, and patients' access to different palliative and psychiatric care is responsible for the variation in these data (19,20). According to the conceptual framework created by Gomez and Higginson, the environment, the individual, and the illness all have an impact on where a person passes away. Sociodemographic details and the patient's choices for the location of death are examples of personal considerations. Environmental factors can be attributed to healthcare inputs (home care, hospital bed availability, and hospital admissions), social support (living arrangements, patient's social support network, and caregiver coping), and macro-social factors (historical trends, health care policy, and cultural factors) (21). Other factors influencing the choice of PPOEOLC and PPOD include insufficient government support for palliative care as a dimension of universal health coverage, difficulty accessing drugs and inadequate training in drug use, lack of proper education, and limited financial resources in this context (22, 23). Studies have mainly examined the demographic and patients 'clinical characteristics affecting PPOEOLC and PPOD using multiple logistic models (24)(25)(26). Iranians are mostly Shiite Muslims (5). Death is seen as a rebirth in Iranian-Islamic culture, and each person's death time is determined by divine destiny (27,28). There is a distinction between a good death and a poor death in this society (28). Islam places a high value on death, as shown by the fact that the word "death" appears 84 times in the Muslim holy book, the Quran (27). Discussions about PPOC and PPOD are sensitive issues that are difficult to address without patient preparation, because they cause anxiety in the patient (11). For this reason, very few studies were conducted in Islamic countries on the PPOEOLC and PPOD. Finding a suitable and preferential place for end-oflife care and death to implement effective policies and planning based on the preferences of cancer patients is essential to providing more favorable palliative interventions. It also helps properly distribute resources to care units, such as hospitals, homes, or intermediate centers (hospices, long-term care centers) (3). Despite all these advantages and how crucial it is to treat the PPOEOLC and PPOD issues, Iran's health system has so far paid little attention to them. As a result, the goal of the current research was to identify PPOEOLC and PPOD in Iranian cancer patients. Study design This cross-sectional descriptive study was conducted from October to November 2021. The study population was hospitalized cancer patients and referred to the outpatient department of three referral hospitals in Tehran (the capital of Iran). Study population After learning the research's goals and completing a written informed permission form, patients who satisfied the inclusion criteria joined the trial via convenient ways. Inclusion requirements include having received a medically confirmed diagnosis of cancer, being above the age of 18, being able to read and write Persian, being in adequate physical condition to complete the questionnaire, and not having cognitive issues such as Alzheimer's or dementia. The required sample size was obtained based on the study of Alsirafy et al. (29) which was P = 0.28, and 345 people were obtained using the formula n = Z 2 P (1-P)/d 2 with 95% confidence level and (d) = 0.05; the sample size was calculated to be 370 people with design effect equal to 1.5. Data collection tool The data collection tool included a researcher-made questionnaire consisting of three sections: The first part includes the patient's demographic information including age, gender, level of education, marital status, number of children, employment status, monthly income, and race; the second part includes patients' clinical characteristics including type of care (inpatient/outpatient), type of cancer (gastrointestinal, breast, blood, other), insurance coverage (Social Security Insurance funded by the Social Security Organization, Armed Forces Insurance funded by the Ministry of Defense and Armed Forces Logistics, etc.) and time to diagnostic disease (less than 6 months, more than 6 months); and the third part includes two questions related to the The questionnaire's face validity was assessed using two quantitative and qualitative techniques. By concentrating on respondents' cognitive process while completing the scale, a cognitive interview is undertaken to determine the cause of inaccuracy in the scale (30). Ten cancer patients with diverse economic, social, and education levels were interviewed. They were requested to rate the legibility, clarity, and structure of the items, ease of comprehension, item difficulty, confusing words, item classification, ease of responding, language forms, and wording. Subsequently, the modifications were applied in the primary questionnaire. The impact score of each question was calculated to quantify face validity. For each item, the Likert scale was divided into five parts: I completely agree (score 5), I agree (score 4), I have no opinion (score 3), I disagree (score 2), and I completely disagree (score 1). Then a questionnaire was given to 10 specialists (three oncologists, five nursing professors, one palliative specialist, and one psychologist) to determine the validity. Then the impact score for each item of the questionnaire is calculated by the method (importance × frequency = impact score). If the impact score is greater than 1.5, the item is suitable (31). The impact score for both questions was more than 1.5. "At the end of life, some individuals choose to be cared for at home, while others prefer to be cared for in a hospital," was one of two questions connected to the PPOEOLC and the PPOD. Where would you rather get treatment as you near death? and "At the end of their lives, some individuals choose to pass away at home while others choose to pass away in a hospital. Where would you rather pass away?" Data analysis After data collection, the collected data were analyzed by SPSS software version 18. Descriptive analyses including frequency and percentage were used for qualitative data, and mean and standard deviation were used for normal quantitative data. The two primary variables, the PPOEOLC and the PPOD, together with demographic factors and clinical features of the subjects were examined using chi-square and Fisher exact tests. The threshold for statistical significance was set at P 0.05. Finally, significant variables were included in the model through multiple logistic regression with the Wald backward method. The effect of individual explanatory variables on the outcome variable was measured using the adjusted odds ratio (AOR) with a 95% confidence interval (CI). Ethical consideration Permission for this study was approved by the ethics committee of Baqiyatallah University of Medical Sciences with the code of ethics (IR.BMSU.REC.1399.42). Participants were assured of anonymity and confidentiality of the information obtained. Result Demographic and clinical characteristics of the patients (Figure 1). Univariant test showed that choosing home in outpatients (72.6%) was higher than in inpatients (59.7%), which shows a significant difference (P = 0.005). Moreover, the percentage of choosing home in women (73.4%) was higher than in men (62.2%) (P = 0.007). People with academic education (77.6%) were more likely to receive care at home than other people with elementary education (59.6%) and high school (74.4%) (P = 0.000). Additionally, Persians (76%) picked their homes more often than other races (P = 0.013). The logistic model showed that inpatient patients had a lower likelihood of selecting home than outpatient patients (OR:.613 (.383,.982), P =.042). Patients with academic education had a higher likelihood of choosing home than patients with elementary education, although this difference was not statistically significant (OR: 2.61 (1.29, 5.24), P =.007). Patients with high school education had similar chances of choosing home as patients with elementary education. Chances of choosing home in two groups of patients with mediate income (OR: 3.27 (1.49, 7.14), P = .003) and low (OR: 3.38 (1.52, 7.52), P = .003) were significantly higher than in patients with high income. In other words, by decreasing income, the chance of choosing the home increased, and patients with breast cancer had a better chance of choosing a home than with gastrointestinal cancer (OR: 1.70 (1.01, 2.89), P = .049) ( Table 2). Preferred place of death Four hundred fifteen (75.2%) patients chose home as their PPOD, while 137 (24.8%) people chose the hospital (Figure 1). Choosing a home as a PPOD in married patients (77.6%) compared to single patients (66.7%) was higher (P = 0.014). Also, patients with Armed Forces Insurance with 82.1% were the most patients who chose home as the PPOD (P = 0.011). Moreover, patients with a disease period of less than 6 months (84.9%) compared to patients with a period of more than 6 months (72%) had chosen home as the PPOD (P = 0.002). However, the logistic model showed that married people have a higher chance of choosing the home than single people (OR: 1.62 (1.02, 2.57), P = .039). Besides, people with a disease period longer than 6 months had a significantly lower chance of choosing the home than people with a disease period of less than 6 months (OR:.468 (.286,.765), P = .002). (Table 3). Discussion In Iran, there are no official statistics on the PPOEOLC and the PPOD in cancer patients. Therefore, the purpose of this study was to determine the PPOEOLC and PPOD in cancer patients. Given that there is a view in Iranian culture that discussing death and dying with patients is inappropriate because of stress and poor patient morale, the paucity of study in this field is likely a result of cultural and religious constraints. Thus, preference about the place of death and place of end-of-life care is not a stable concept and can change over time through discussion between healthcare professionals and patients according to social, supportive, and individual conditions (32,33). By reviewing the literature, various studies have discussed the PPOEOLC and PPOD together (11,12,15,34). However, in the present study, both concepts (PPOEOLC and PPOD) were surveyed using two separate questions. In the present study, most cancer patients chose home as their PPOEOLC and PPOD. Another systematic review shows that the home is the PPOD for most cancer patients worldwide (3). The reason why individuals in various nations choose to pass away at home is probably impacted by a number of things. For instance, patients who preferred to pass away at home were more likely to do so if they were less educated, lived with their spouse or family, or were from rural regions (34, 36). Some patients may have a history of adversity in their lives, which influences their decision (39). Dying and caring at home may have religious significance, because the home environment can facilitate cultural and religious ceremonies at the end of life as an integral part of peaceful death (16). The cultural family-centered principle of Iranian-Islamic society and patients' desire for family members to be present in bed when receiving end-of-life care is a feature of Iranian society that is effective to achieve the present result. According to other research, the capacity to address the patient's fundamental requirements, patient privacy, a more soothing environment for the patient and caregiver, and simple access to home care support systems are the most prevalent reasons patients opt to get their care at home (16,40,41). The hospital was the second priority as the PPOEOLC and PPOD of cancer patients. Consistent with the present study, the study by Choi et al. in South Korea (34), Skorstengaard et al. in Denmark (11), and three other studies show that the hospital is the second priority as the PPOD and PPOEOLC (34, 36,42,43). The most common reasons of patients in choosing the hospital as the second PPOD and PPOEOLC in other studies include patients not wishing to be a burden on their family (40), having a reliable relationship between caregivers and patients (44), having a safer care environment, adequate facilities, and equipment to facilitate quality care, especially time to overcome pain and discomfort (45), poor functional status of the patient and the family's inability to provide effective and quality care, and lack of the participation of the palliative care team at home (16). In accordance with Iranian society's culture, hospitals are seen as a secure and suitable setting for managing illness symptoms and suffering, particularly when doing so is challenging. The answer to the question about the PPOEOLC and PPOD was limited to two options of home and hospital. Other studies used places such as nursing home and hospice but in terms of the lack of development of hospice centers in Iran, as in many Middle-eastern countries (35), However, in countries where there are hospices, patients still choose home as their PPOD (9,13,46). The findings of the current research are consistent with those of the studies by Jeurkar et al. (13) and Gu et al. (14), which found that married patients were more likely than single patients to choose home as their PPOD (36). This is most likely because the patient and spouse have a stronger emotional bond, which makes the home environment more calming for the patient. The results of the present study showed that outpatients had a significantly higher chance of choosing the home as a PPOEOLC than inpatients. Moreover, patients with a time to diagnostic disease the less than 6 months had a significantly higher chance of choosing the home as a PPOD than the patients' time to diagnostic disease of more than 6 months. The result of this study is contrary to the study of Gu et al. (36). The reason for this difference is most likely the individual's incompatibility with the hospital environment at the beginning of the illness. Inpatients and people who have been ill for a long time are more likely to adapt to the hospital environment due to the longer hospital stay. The patients with academic level of education are more likely to choose home as the PPOEOLC than patients with elementary and high school levels of education. This result is inconsistent with the study of Choi et al. (34) and the study of Chen et al. (47). The difference may be explained by the fact that patients with greater levels of education are more aware of and knowledgeable about conditions for self-care at home, which enhances the possibility that they will choose the home. In our study, middle-and lower-income people chose home as their PPOEOLC more than high-income people; the reason for this choice is probably due to the financial inability of these people to pay for care and equipment in the hospital. According to World Health Organization's World Cancer Statistics in 2020, the most common type of cancer in 2022 is breast cancer (2.26 million cases) (4). In our study, the type of disease was also a significant factor in choosing the home as a PPOEOLC, so that people with breast cancer chose home more than people with other cancers. The result of our study was in line with the study of Chen and the study of Blanchard et al. In the Blanchard study, breast cancer patients also chose the home as the PPOD (47,48). Conclusion The results of the present study show that the majority of Iranian cancer patients chose home as the PPOEOLC and the PPOD. According to the findings of this study, experts advocate paying more attention to the preferences of terminally ill patients, strengthening the system of home healthcare. This will be accomplished through enhancing the home care system via the development of suitable infrastructure, insurance coverage, the drafting of executive directives, and the incorporation of palliative care into home care services. In addition, emphasizing death at home requires a fair distribution of health resources. For this purpose, more resources need to be allocated to home health care. The strength of the study The strength of the present study lies in the fact that we used patients' statements about their preferences rather than a proxy statement made by others, such as a family caregiver or other caregivers. Another strength of this study is that the question is asked from cancer patients about the PPOEOLC and PPOD, not from the general population without diagnosis; in fact, when people are well and live without diagnosis of life-limiting diseases or do not face death, they may use an abstract and unrealistic answer, while in our study this answer was concrete. Limitations Despite the inclusion of a wide range of potential predictors, observational studies may never be able to reduce the effect of confounding variables to zero. As patients approach their last days of life, cross-sectional evaluations may also alter the dynamic decision-making process of priorities, predictors of death, and home care. Another limitation of this study is that the "no preference" option was not considered as an answer that is suggested to be considered in future studies. Implications for practice and future research To achieve the patient's preferences at the end of life, it is important to have a preferred place to discuss death and document the decision. Therefore, it is important to ensure that all patients have the opportunity to speak about this issue in a supportive, practical, and compassionate manner. To increase their competency and confidence in end-of-life conversations, medical and nursing professionals' training may be strengthened. Death in hospitals is anticipated to predominate in the future, despite minor variations in the location of death throughout time. Therefore, it is necessary to take measures in this regard to improve the experiences of patients and their families at this time. Further research is needed on the impact of deprivation and other socioeconomic factors on preferences, the reasons for lack of discussing the place of death, and the lack of expression of preference or change of preference. Data availability statement The raw data supporting the conclusions of this article will be made available by the authors, without undue reservation. Author contributions Study design: AF, MR, and SB; data collection: FH, MJ, MK, and ME; data analysis: MS and SB; study supervision: SB; manuscript writing: AF, MR, MS, FH, MK, MJ, ME, and SB; critical revisions for important intellectual content: AF, SB, and MR. All authors contributed to the article and approved the submitted version.
<reponame>guilhermepo2/visions2D<gh_stars>0 #include "VertexArray.h" #include <glad/glad.h> namespace visions2D { VertexArray::VertexArray( const float* _verts, unsigned int _vertPropertiesCount, unsigned int _numVerts, const float* _texCoords, const unsigned int* _indices, unsigned int _numIndices) : m_NumberOfIndices(_numIndices), m_NumberOfVertices(_numVerts) { glGenVertexArrays(1, &m_VertexArrayID); glBindVertexArray(m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); glBufferData(GL_ARRAY_BUFFER, _numVerts * (_vertPropertiesCount * sizeof(float)), _verts, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glGenBuffers(1, &m_TexCoordsBufferID); glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordsBufferID); glBufferData(GL_ARRAY_BUFFER, _numVerts * (_vertPropertiesCount * sizeof(float)), _texCoords, GL_STATIC_DRAW); // texture coords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glGenBuffers(1, &m_IndexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _numIndices * sizeof(unsigned int), _indices, GL_STATIC_DRAW); } void VertexArray::SubTexCoords(const float* _texCoords) { glBindBuffer(GL_ARRAY_BUFFER, m_TexCoordsBufferID); glBufferSubData(GL_ARRAY_BUFFER, 0, 4 * (2 * sizeof(float)), _texCoords); } VertexArray::~VertexArray() { glDeleteBuffers(1, &m_VertexBufferID); glDeleteBuffers(1, &m_IndexBufferID); glDeleteBuffers(1, &m_VertexArrayID); } void VertexArray::SetActive() { glBindVertexArray(m_VertexArrayID); } }
// This function sets the A record of a domain to the IP of a running instance func dynamicDNS(AccessKeyID string, SecretKeyID string, InstanceID string, Region string, Domain string, HostedZoneID string) error { publicIpResponse, ipErr := getPublicIPOfInstance(AccessKeyID, SecretKeyID, InstanceID, Region) if ipErr != nil { fmt.Println(ipErr) return ipErr } IP := publicIpResponse.Reservations[0].Instances[0].PublicIpAddress creds := credentials.NewStaticCredentials(AccessKeyID, SecretKeyID, "") svc := route53.New(&aws.Config{Credentials: creds}) params := &route53.ChangeResourceRecordSetsInput{ ChangeBatch: &route53.ChangeBatch{ Changes: []*route53.Change{ { Action: aws.String("UPSERT"), ResourceRecordSet: &route53.ResourceRecordSet{ Name: aws.String(Domain), Type: aws.String(route53.RRTypeA), ResourceRecords: []*route53.ResourceRecord{ { Value: IP, }, }, TTL: aws.Int64(300), }, }, }, Comment: aws.String("Updating Domain for EC2 Instance via Stopwatch"), }, HostedZoneId: aws.String(HostedZoneID), } _, err := svc.ChangeResourceRecordSets(params) if err != nil { fmt.Println(err.Error()) return err } return nil }
// Receive messages from rabbit mq and send to http func Receive() { var conf = readconf.GetGeneral() var r2hConf = readconf.GetR2H() conn, err := amqp.Dial(conf.RabbitMQServer) failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() _, err = ch.QueueDeclare( r2hConf.ListenQueue, true, false, false, false, nil, ) failOnError(err, "Failed to declare a queue") for _, exchange := range r2hConf.BindExchanges { err = ch.ExchangeDeclare(exchange.ExchangeName, "fanout", true, false, false, false, nil) failOnError(err, fmt.Sprintf("Failed to bind Exchange '%s' to Queue '%s'", r2hConf.ListenQueue, exchange.ExchangeName)) log.Printf("Declared or found exchange %s", exchange.ExchangeName) err = ch.QueueBind( r2hConf.ListenQueue, "", exchange.ExchangeName, false, nil, ) failOnError(err, fmt.Sprintf("Failed to bind Exchange '%s' to Queue '%s'", r2hConf.ListenQueue, exchange.ExchangeName)) log.Printf("Bind Exchange '%s' to listener queue '%s'", exchange.ExchangeName, r2hConf.ListenQueue) } msgs, err := ch.Consume( r2hConf.ListenQueue, "", false, false, false, false, nil, ) failOnError(err, "Failed to register a consumer") listener := make(chan bool) go func() { for d := range msgs { log.Printf("Received a message %s from exchange %s with routing %s", d.MessageId, d.Exchange, d.RoutingKey) for _, exchange := range r2hConf.BindExchanges { if exchange.ExchangeName == d.Exchange { log.Printf("Found config for exchange %s for message %s, will send to %s", d.Exchange, d.MessageId, exchange.HTTPURL) client := &http.Client{} req, err := http.NewRequest("POST", exchange.HTTPURL, nil) if err != nil { log.Printf("Couldn't create request, will requeue message for later") continue } for _, header := range exchange.HTTPHeaders { req.Header.Add(header.Key, header.Value) } resp, err := client.Do(req) if resp.StatusCode == 200 { d.Ack(false) log.Printf("Received HTTP 200, Sent ACK for message %s", d.MessageId) } else { log.Printf("Received HTTP %i, ACK was not sent for message %s", resp.StatusCode, d.MessageId) } } } } }() log.Printf(" [*] Waiting for messages. To exit press CTRL+C") <-listener }
/** * Remove a placeholder from in memory storage. */ public static void removePlaceholder(Uri uri) { sSessionsToSizes.remove(uri); sSessionsToPlaceholderBitmap.remove(uri); sSessionsToPlaceholderVersions.remove(uri); }
/** * * @author Nicholas C. Zakas */ public class CSSURLEmbedderTest { private static String folderDataURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACIAAAAbCAMAAAAu7K2VAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAAwUExURWxsbNbW1v/rhf/ge//3kf/Ub9/f3/b29oeHh/7LZv/0juazTktLS8WSLf//mf/////BPrAAAAB4SURBVHja3NLdCoAgDIbhqbXZz2f3f7eZWUpMO67nQEReBqK0vaLPJohYegnSYqSdYAtRGvUYVpJhPpx7z2piLSqsJQ73oY1ztGREuEwBpCUTwpAt7cRmncRlnWTMoCdcXxmrdiMxngpvtDcSNkX9AvTnv9uyCzAAgzAw+dNAwOQAAAAASUVORK5CYII="; private CSSURLEmbedder embedder; public CSSURLEmbedderTest() { } @Before public void setUp() { } @After public void tearDown() { embedder = null; } @Test public void testAbsoluteLocalFile() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(" + folderDataURI + ");", result); } @Test public void testAbsoluteLocalFileWithMhtml() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png);"; String mhtmlUrl = "http://www.example.com/dir/"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.MHTML_OPTION, true); embedder.setMHTMLRoot(mhtmlUrl); embedder.setFilename("styles_ie.css"); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("/*\nContent-Type: multipart/related; boundary=\"" + CSSURLEmbedder.MHTML_SEPARATOR + "\"\n\n--" + CSSURLEmbedder.MHTML_SEPARATOR + "\nContent-Location:folder.png\n" + "Content-Transfer-Encoding:base64\n\n" + folderDataURI.substring(folderDataURI.indexOf(",")+1) + "\n\n--" + CSSURLEmbedder.MHTML_SEPARATOR + "--\n" + "*/\nbackground: url(mhtml:" + mhtmlUrl + "styles_ie.css!folder.png);", result); } @Test public void testAbsoluteLocalFileMultipleOneLine() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png); background: url(folder.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(" + folderDataURI + "); background: url(" + folderDataURI + ");", result); } @Test public void testAbsoluteLocalFileWithDoubleQuotes() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(\"folder.png\");"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(" + folderDataURI + ");", result); } @Test public void testAbsoluteLocalFileWithSingleQuotes() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url('folder.png');"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(" + folderDataURI + ");", result); } @Test (expected=IOException.class) public void testAbsoluteLocalFileWithMissingFile() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(fooga.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code),true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals(code, result); } @Test public void testAbsoluteLocalFileWithMissingFilesEnabled() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(fooga.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.SKIP_MISSING_OPTION, true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals(code, result); } @Test public void testAbsoluteLocalFileUnderMaxLength() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 1000); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(" + folderDataURI + ");", result); } @Test public void testAbsoluteLocalFileOverMaxLength() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 200); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals(code, result); } @Test public void testAbsoluteLocalFileUnderMaxImageSize() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 0, 300); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(" + folderDataURI + ");", result); } @Test public void testAbsoluteLocalFileOverMaxImageSize() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png);"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 0, 200); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals(code, result); } @Test public void testReadFromAndWriteToSameFile() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("samefiletest.css").getPath().replace("%20", " "); File file = new File(filename); Reader in = new InputStreamReader(new FileInputStream(file)); embedder = new CSSURLEmbedder(in, true); in.close(); Writer writer = new OutputStreamWriter(new FileOutputStream(file)); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); writer.close(); in = new InputStreamReader(new FileInputStream(file)); char[] chars = new char[(int)file.length()]; in.read(chars, 0, (int)file.length()); in.close(); String result = new String(chars); assertEquals("background: url(" + folderDataURI + ");", result); } @Test public void testRegularUrlWithMhtml() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.txt);"; String mhtmlUrl = "http://www.example.com/dir/"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.MHTML_OPTION, true); embedder.setMHTMLRoot(mhtmlUrl); embedder.setFilename("styles_ie.css"); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); assertEquals("background: url(folder.txt);", result); } @Test public void testRemoteUrlWithQueryString() throws IOException { final String expectedUrl = "http://some-http-server.com/image/with/query/parameters/image.png?a=b&c=d"; String code = "background : url(/image/with/query/parameters/image.png?a=b&c=d)"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), CSSURLEmbedder.DATAURI_OPTION, true, 0, 200) { /* * Override method to prevent a network call during unit tests */ @Override String getImageURIString(String url, String originalUrl) throws IOException { if(url.equals("")) { throw new IllegalArgumentException("Expected URL " + expectedUrl + ", but found " + url); } return "data:image/gif;base64,AAAABBBBCCCCDDDD"; } }; embedder.embedImages(writer, "http://some-http-server.com/"); String result = writer.toString(); assertEquals("background : url(data:image/gif;base64,AAAABBBBCCCCDDDD)", result); } @Test public void testImageDetection() { String tests[] = { "file://path/to/image.png", "http://some.server.com/image.png", "http://some.server.com/image.png?param=legalvalue&anotherparam=anothervalue", "http://some.server.com/image.png?param=illegal.value.with.period" }; boolean expectedImage[] = { true, true, true, false }; for(int i=0; i<tests.length; i++) { if(expectedImage[i]) { assertTrue("Expected " + tests[i] + " to resolve to an image", CSSURLEmbedder.isImage(tests[i])); } else { assertFalse("Did NOT expect " + tests[i] + " to resolve as an image", CSSURLEmbedder.isImage(tests[i])); } } } @Test public void testRegularUrlWithSkipComment() throws IOException { String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " "); String code = "background: url(folder.png); /* CssEmbed: SKIP */"; StringWriter writer = new StringWriter(); embedder = new CSSURLEmbedder(new StringReader(code), true); embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1)); String result = writer.toString(); //assert that nothing changed assertEquals(code, result); } }
def validate_measurements(circuit, N): spatial_modes = 0 for cmd in circuit: if isinstance(cmd.op, ops.Measurement): modes = [r.ind for r in cmd.reg] spatial_modes += len(modes) if not spatial_modes: raise ValueError("Must be at least one measurement.") if spatial_modes is not len(N): raise ValueError("Number of measurement operators must match number of spatial modes.") return spatial_modes
Energy-socio-economic-environmental modelling for the EU energy and post-COVID-19 transitions Relevant energy questions have arisen because of the COVID-19 pandemic. The pandemic shock leads to emissions’ reductions consistent with the rates of decrease required to achieve the Paris Agreement goals. Those unforeseen drastic reductions in emissions are temporary as long as they do not involve structural changes. However, the COVID-19 consequences and the subsequent policy response will affect the economy for decades. Focusing on the EU, this discussion article argues how recovery plans are an opportunity to deepen the way towards a low-carbon economy, improving at the same time employment, health, and equity and the role of modelling tools. Long-term alignment with the low-carbon path and the development of a resilient transition towards renewable sources should guide instruments and policies, conditioning aid to energy-intensive sectors such as transport, tourism, and the automotive industry. However, the potential dangers of short-termism and carbon leakage persist. The current energy-socio-economic-environmental modelling tools are precious to widen the scope and deal with these complex problems. The scientific community has to assess disparate, non-equilibrium, and non-ordinary scenarios, such as sectors and countries lockdowns, drastic changes in consumption patterns, significant investments in renewable energies, and disruptive technologies and incorporate uncertainty analysis. All these instruments will evaluate the cost-effectiveness of decarbonization options and potential consequences on employment, income distribution, and vulnerability. H I G H L I G H T S • Multidisciplinary modelling is required to conduct a resilient energy transition. • Policies' aim should not be limited to short-term maintenance of jobs and growth. • Decarbonization and sustainability must be the drivers for policy action. • Energy transition needs to assess potential impacts on social aspects. • Energy modelling is called for including new features and extreme scenarios. G R A P H I C A L A B S T R A C T a b s t r a c t a r t i c l e i n f o Introduction The COVID-19 pandemic has caused profound and unforeseen effects in all spheres of human life around the planet. Measures to prevent the spread of the pandemic, primarily the confinement of citizens and the lockdown of non-essential economic activities, have led to a dramatic decline in GDP (gross domestic product) and employment. The European Union (EU) experienced a 6.1% contraction of the GDP in 2020, with an unemployment rate of 7.0% (7.3% in April 2021) and a public deficit of 6.9% (EC, 2021a(EC, , 2021b(EC, , 2021c. Simultaneously, global CO 2 emissions estimates decreased by 17% in early April 2020, which is associated with an annual decrease of 4.2-7.5% (Le . In the European Union, CO 2 emissions from fossil fuel combustion decreased by 10% in 2020 compared to the previous year (EC, 2021d). To cope with the economic impacts of the pandemic, the European Commission (EC) and the Governments of the Member States (MS) have announced and developed many recovery plans. From the longrun perspective, the EC and the MS work on designing stimulus packages to boost the economic recovery, the so-called Green Recovery Plans (GRPs). In the face of the COVID-19 crisis, the EC indicated that it will continue promoting its flagship project, the European Green Deal (EGD), 1 the most comprehensive proposal for economic transformation, delivered in July 2021 (EC, 2021e). The Next Generation EU (NGEU) fund is at the core of the recovery policy in the EU. This temporary recovery instrument consists of more than €800 billion to help repair the immediate economic and social damage brought about by the coronavirus pandemic. The aim of this plan is to foster a greener, more digital, more resilient Europe and a better fit for the current and forthcoming challenges. In parallel, and in order to benefit from the NGEU, the MS have submitted to the EC their National recovery and resilience plans (EC, 2021f), outlining how they will invest the funds, and how they will contribute to a sustainable, equitable, green and digital transition. The reforms and investments included in the plans should be implemented by 2026. The NGEU fund will operate from 2021 to 2023 and will be tied to the regular long-term budget of the EU, running from 2021 to 2027. The EU's long-term budget, coupled with NGEU, will be the most extensive stimulus package ever financed in Europe with a total budget of €2 trillion. Political economy may tell us more about how this will play out in the end (depending on, e.g., the interest of well-positioned lobbies and/or large firms, the need to take advantage of planned projects, the built or needed infrastructure, etc.). According to Cowen (2021), energy policy is often judged by three criteria (cost, reliability, and effect on carbon emissions), while suggesting an alternative approach based on which green energy policies can get the support of most specialinterest groups and the fewest forces in opposition. Academic, online and political debates are then greatly modulating and adapting the above principles. Still, according to Pianta et al. (2021), surveys about the next 5 years to policy-makers and stakeholders from 55 different countries and sectors suggest that expectations that the COVID-19 pandemic will accelerate decarbonization efforts are widely shared, similarly to what citizens seem to reveal (EU, 2020). A critical question is how to shape the GRPs to rapidly deliver jobs and improve citizens' quality of life without compromising the fight against climate change and contributing to sustainable and resilient societies (Shan et al., 2021). This article, complementary to the discussions on carbon pricing and COVID-19 (Mintz-Woo et al., 2020), how the disease impacts the ongoing energy transitions (Sovacool et al., 2020), and the role of international governance in the recovery (Obergassel et al., 2020), discusses the challenges and potential of the GRPs, highlighting the value of energy systems modelling for informing policy-makers in managing an efficient, secure, and fair energy transition. It is organized into five main sections, each raising a challenge of the post-COVID-19 plans for recovery and energy transition in the EU. 2. How have the energy system, the associated environmental pressures, and the European policy agenda changed with the COVID-19 crisis? In the period of tightest restrictions against COVID-19, most of Europe experienced a notable load drop. Interestingly, while coal, oil and nuclear power generation considerably decreased in most countries, the production of renewables increased, proving that intermittent renewables are a reliable resource in critical times (Werth et al., 2021). Likewise, energy trade between countries increased. As a result, CO 2 emissions fell by 17 million tonnes in April 2020, a drop that had not been registered since 2006 (Le . estimated that greenhouse gas (GHG) emissions reductions from changes in EU consumption accounted for 6% in the EU, and around 1% globally. However, unless the future economic recovery is tilted towards green stimulus and reductions in fossil fuel investments (Forster et al., 2020), the decline in 2020 is unlikely to persist in the long term, as it does not reflect structural changes in economic systems, nor do they seem to have much effect on global climate change in the medium term (IEA, 2021;Linares, 2020). Nevertheless, studies on the impact of the COVID-19 on health, economy and the environment serve to analyze possible scenarios of considerable load reduction and higher renewable production. 2 In this context, the permanence of changes depends on how production and consumption patterns evolve (e.g., teleworking and tourism), the scope of the energy transition, and, ultimately, to what extent climate change is taken into account when planning economic responses after COVID-19. This framework is genuinely at stake, particularly in the post-pandemic EU with the GRPs. How is the European energy transition linked with the GRPs? The European energy transition appears intimately connected with the GRPs by the common goal of decarbonization. The energy transition as an engine of recovery can lead to large investments in clean energy technologies. According to the priorities of the GRPs, mobilization of funds will mainly focus on the renovation of buildings, renewables and hydrogen, and clean mobility; a share of 30% will be spent on fighting climate change (EC, 2021g). As pointed out by Escribano et al. (2020), the set of EU policies can provide the regulatory certainty that the private sector needs to embrace the low-carbon transition as a recovery opportunity (Campiglio, 2014). Additionally, the EU has built a framework for aligning financial and climate goals through the Sustainable Finance Action Plan (European Commission, 2018), and the recently published EU taxonomy for sustainable activities (OJEU (Official Journal of the European Union), 2020). These initiatives should aim to neutralize any attempt to reverse the trend towards energy and climate policies and regulations, aligning recovery plans and energy transition. The IEA proposes greater cooperation, coordination based on the national energy and climate plans (NECPs) and working on the integration of the energy market, cross-border trade, and developing stronger signals from the price of carbon (IEA, 2020a). 3 Cooperation mechanisms included in the European Renewable Energy Directive (OJEU (Official Journal of the European Union), 2018) enable EU countries to work together to meet their targets more cost-efficiently. The EGD is an opportunity to deepen measures affecting the EU pooling investments in key innovative technologies. In general, GRPs should accelerate and prioritize some of the action plans contemplated in the NECPs. Governments' role will be very relevant in innovative public procurement processes setting the benchmark for companies (Lindström et al., 2020;EC, 2014). 4. Are there specific opportunities for the energy transition (e.g., more investment for more employment-generating electricity production technologies) with these plans? There are several clear synergies between energy transition and job creation (IRENA, 2019) and improved health. For instance, pollution associated with fossil fuel combustion takes premature lives annually while increasing the respiratory risk associated with diseases such as COVID-19 (Vandyck et al., 2018). Environmental and social ratings have been resilient during COVID-19 featuring higher returns, and renewable energy technologies may yield environmental and health benefits (Guerriero et al., 2020). The IEA estimates that investing 0.7% of global GDP could create or save 9 million jobs a year in improving the efficiency of buildings, grids, and renewables, but also in improving the energy efficiency of manufacturing, food, and agriculture, textiles, infrastructure for lowcarbon transport (which should also be of low-carbon concrete and steel, e.g. for railway), and more efficient vehicles (with the reasonable substitution of the vehicle park based on its useful life) with enhanced electricity grids (IEA, 2020b). In the business field, there have been "winners" in the COVID-19 crisis (e.g., technology, distribution, food and pharmaceutical companies). Their expansion offers the chance to include them in the fight against climate change actively. For instance, electronic commerce is here to stay. Therefore, distribution companies must develop the modal shift towards electric vehicles (Shahmohammadi et al., 2020). In the same vein, technology-based electricity-intensive companies should be encouraged to keep low carbon footprints, penalizing possible carbon leakage in carbon-intensive countries (Ortiz et al., 2020;Jiborn et al., 2018) and including carbon border adjustment mechanisms (as intended by EGD for selected sectors by 2021). GRPs need to target not only the most relevant sectors in terms of emissions and economic growth (e.g., airlines committed to reducing their emissions in the medium term, or industries focused on fossil fuels that do not have much time to live in their current configuration) but also, significantly, critical activities in which the conditionality of aids can be very effective towards decarbonization (e.g., the power sector or the automotive sector). The allocation of GRPs stimuli is crucial, because it could increase global five-year emissions by −4.7% to 16.4% depending on the structures and strength of incentives (Shan et al., 2021), and a "green GRP" could outperform an equivalent stimulus package while reducing global energy CO 2 emissions by 10% (Pollitt et al., 2020). Further opportunities arise from the investment in renewable electricity, hydrogen and energy storage technologies, which are set to play a fundamental role. Promoting home-grown technology production becomes relevant for job creation. In strategic sectors for Europe, such as electricity and digital technologies, efforts may be made towards developments in the field of management, control, security, and digitization. In production technologies such as photovoltaics, aspects such as adaptation to urban environments, integration in buildings, and advances in high-efficiency cells remain as opportunities. Hydrogen research, especially electrolyzers, can be a differential technological factor. Concentrated solar technology for electricity production is an example of such technological leadership that could be promoted, being entirely consistent with the spirit of the objectives of the EGD, supporting high-value-added and sustainable economic activity in southern European countries like Spain, heavily hit by the crisis (Banacloche et al., 2020). The renovation of buildings offers an excellent opportunity to contribute to the economic recovery of the construction sector. The solutions to improve the thermal insulation of façades in existing buildings would not only redirect sectoral activity and avoid job losses but also fight against energy poverty. Likewise, the tourism sector has great potential to decarbonize and become more resilient if the necessary investments are made. It seems reasonable to implement plans at a regional and local level aimed at improving energy efficiency, circular economy, and public awareness. 5. Are there specific dangers to the energy transition, e.g. economic recovery measures that could indirectly generate more pressure on the energy and environmental system? According to IEA (2020c), the energy investment has been reduced by 20% in 2020 due to supply chain disruptions, lockdown measures, restrictions on people and goods' movement, and emerging financing pressures. Moreover, some key lobbyists and stakeholders have expressed short-term priorities for sustaining employment and economic growth of any kind. If so, there is a risk of targeting aid to specific emission-intensive industries, incentivizing vehicles' purchase, or protecting traditional tourism, which would perpetuate unsustainable production and consumption patterns. In the context of low oil prices, aggravated by the reduction in demand due to the pandemic, such interventions would dangerously delay fossil fuels' substitution. Furthermore, the potential rebound effects resulting from technology innovations and energy efficiency improvements cannot be ignored (Greening et al., 2000;Sorrell et al., 2009;Sorrell and Dimitropoulos, 2008;Antal and van den Bergh, 2014). Several instruments and interventions should be considered to mitigate the magnitude of the rebound effects: policies that promote changes in consumer behaviour and sustainable lifestyles, environmental taxation, non-fiscal measures to increase the effective price of energy services, or the development of new business models (Maxwell et al., 2011). The pandemic also has the potential to change consumer preferences, alter social institutions, and rearrange the structure and organization of production. Greening et al. (2000) refer to these potential effects as transformational rebound effects. No theory exists to predict the sign of these effects, which in the longer term could lead to higher or lower energy consumption, as well as to changes in the mix of energies used in production and consumption throughout the economy. In this regard, it is worth recalling the take-back in GHG emissions observed after the economic-financial crisis of 2008-2009, or in leisure travel after the 9/11 terrorist attacks. 6. What type of energy modelling can be particularly useful to address current challenges and to anticipate advantageous situations and trade-offs from these plans? The COVID-19 pandemic has caught the world in the transition to a sustainable low-carbon energy system and economy, and it raises new challenges to the existing ones. Environmental-energy-economic models must adapt and report on the specific dimensions of those challenges. Modelling energy transition in a post-COVID era must go beyond typical technical variables to meet environmental and social goals, flexibility and uncertain parameters and indirect effects of increasing renewables use (Tovar-Facio et al., 2021). Modellers are increasingly claimed to include aspects such as uncertainty derived from agents' interactions or evolution in their behaviour, ability to integrate shocks in both demand and supply, and non-enforcement of Say's Law or equilibrium or quick adjustment in markets and sectors (Shan et al., 2021;Pollitt et al., 2020). The integration of social indicators with a perspective of global supply chains to identify winner and losers from policy actions or inaction can be crucial to improve models' relevance to the real world. To this end, insights from political economy -regarding individuals not just as rational optimizers, mass movements, public opinions, confidence and quality of institutions, trade linkages of sectors and trade policy, among others-can be helpful, although hard to model due to data availability (Peng et al., 2021). In Appendix A, we display some examples of current efforts in multidisciplinary energy modelling to address the challenges of a sustainable energy transition, some of them already applied to the implementation of Energy and Climate Plans in the Spanish context. Input-Output Tables (IOT) and the extended Multiregional Input-Output (MRIO) models provide a systemic, multisectoral, multiregional view, in which it is possible to include different indicators for policy advice (Wood et al., 2020;Vanham et al., 2019;Tukker and Dietzenbacher, 2013;Wiedmann and Barrett, 2013): environmental impacts (emissions), resource needs (water, land), socio-economic impacts (employment, qualifications), and social risks along the value chains. They can help to define and quantify synergies and trade-offs between different measures and investments. They are also useful to assess the resilience of the economy (and in a sense, of the energy sector) to situations such as pandemic experiences since it allows modelling the closures of sectors/countries or the resource/employment needs of specific sectors by identifying bottlenecks and hotspots including all phases of the global production chain. On the demand side, they allow elaborating scenarios of change in consumption patterns. Besides, MRIO-disaster models deal explicitly with disequilibrium shortfalls in supply and demand in different markets and sectors (Shan et al., 2021). Energy systems modelling based on simulation/optimization, such as TIMES (The Integrated MARKAL-EFOM System, IEA-ETSAP, 2020), is the one chosen by, e.g., the Spanish Government to establish the narratives of the energy system for long-term energy planning (Loulou et al., 2005). In the same fashion as Computable General Equilibrium (CGE) models have been criticized for assuming optimal ("rational") behaviour, introducing optimizing behaviours in the energy sector but not anywhere else in the modelling would be inconsistent as well. Additionally, depending on the scale of application and the dimension of analysis, we should implement other modelling types. Linking MRIO models and energy systems optimization models with methodologies such as Life Cycle Sustainability Assessment (LCSA) allows understanding the implications of alternative investment options in broader sustainability aspects (Navas-Anguita et al., 2020). LCSA typically consists of an environmental life cycle assessment (LCA), a life cycle costing, and a social life cycle assessment (S-LCA) within a consistent, holistic framework (UNEP/SETAC Life Cycle Initiative, 2011). In this regard, we note that decarbonization and sustainability are expected to continue to be the drivers for policy action, especially regarding energy systems. Environmental-Energy-Economic integrated assessment models (E 3 IAMs) are useful tools to provide ex-ante information on the potential impacts of recovery plans, but, to that end, they must be able to report on the specific dimensions of the challenge. Accordingly, models should inform on employment, income (distributional), and environmental impacts of different green policies portfolios. Full multi-agent econometric input-output models should be included in the economic part of the IAMs, as done in the WILIAM model, an IAM with detailed representations of the economic, sociodemographic, resources (energy, materials, land, water) and environmental spheres. 4 The E3ME macro-econometric model (Cambridge Econometrics, 2019), based on post-Keynesian theory, shows an IOT base to model sectors and countries relationships and integrates the energy system, including bottom-up sub-models of several key energy sectors. It can be used to build scenarios to reflect the critical aspects of the pandemic and allow consideration of both demand-and supply-driven impacts derived from it (Pollitt et al., 2020). Besides, the model does not assume (as, in general, CGE models do) that the economy adjusts quickly after the pandemic impact to full employment of resources and allows fundamental uncertainty affecting spending and saving behaviour. Many models will have to adapt to the new challenges (Pfenninger et al., 2014;Solé et al., 2020) and to the new features involved with the COVID-19 crisis and the coming times with the recovery plans (Table 1). For example, they could use microdata to analyze, for specific groups of households (e.g., along with a set of socio-demographic characteristics of interest), the environmental and economic implications of different recovery policies, including distributive impacts. Another critical feature is linking the economic production and consumption functions to bottom-up energy and resources modules, looking for higher resolution models in this aspect (Prina et al., 2020). Additional aspects to implement include the criticality of the materials expected to be essential in the energy transition, the role of citizens (such as human behaviour, types of demand and users), the use of water, visual and sound impact, market regulatory advances (e.g., with schemes which avoid speculation on energy storage), energy servitization (to check whether it brings social benefits and improves the efficiency of the system), and adaptation mechanisms. Planning capacity at the regional and city levels will be crucial to the success of national measures. These modelling developments will pose a challenge for economists (input-output regionalization, recirculation, and dynamics), systems engineers (complex simulation models with high load of artificial intelligence tools and big data to configure demands, project resources, etc.), chemical engineers, and environmental scientists (regionalization and dynamic inventories in LCA), as well as decision engineers (strategies, multi-criteria decision-making, PESTEL analysis, group work, governance models and policy design). Finally, it is important to point out that "scenarios are the primary tool for examining how current decisions shape the future, but the future is affected as much by out-of-ordinary extremes as by generally expected trends. Energy modellers can study extremes both by incorporating them directly within models and by using complementary off-model analyses" (McCollum et al., 2020). Thus, uncertainty is an intrinsic attribute of macro-systems such as those evaluated by means of energy systems models (cities, regions, countries…). In this sense, uncertainty will have an effect on decisions and strategic planning. There are several types of uncertainties that affect decisionmaking processes. Some uncertainties can be quantitatively addressed and some others not, which relates to the rationale of '(un)known (un)knowns' in Courtney et al. (1997): there are known knowns (things we know we know), known unknowns (things we know that we do not 4 Developed in the LOCOMOTION (https://www.locomotion-h2020.eu) project. The economic module of the model departs from a structure inspired in the FIDELIO model ). As we conclude below, these questions highlight the importance of a modelling approach that takes into account existing uncertainty and that non-equilibrium outcomes are the common situations with changing and heterogeneous patterns. Conclusions, final warnings, and recommendations Once the health crisis is over, it will be necessary to invest more in public health and communication technologies with environmental and social sustainability criteria, not just monetary. Besides, although it is required to reactivate the economy and recover the lost or at-risk jobs, it is essential to redefine the productive schemes at all levels. This includes the commitment to a circular economy, reducing the pressure on resources through innovative eco-design solutions, dematerialization, and creating second-life solutions away from precariousness and the underground economy. Besides, the mobility model must be changed, and a sustainable work-life balance scheme should be promoted via teleworking, whenever possible, not only to avoid the exponential expansion of contagions but also to reduce pollution. Fourth, the EU's leadership has to extend beyond its borders, undertaking actions to prevent carbon leakage, and engage in global actions and alliances disseminating experiences and learnings. Finally, some policies are likely to generate much better economic and distributive outcomes than others. Energy-socio-economic-environmental modelling, which allows evaluating alternative and nonordinary scenarios, is crucial to provide information to policy-makers to make informed decisions. We emphasize the need for consistency with integrated modelling approaches that consider uncertainty, nonoptimizing behaviours, heterogeneous agents, non-equilibrium outcomes across sectors, rigidities, institutional frictions, etc. Specifically, we highlight the need to develop advanced modelling frameworks that integrate dynamic econometric multiregional models and intersectoral models of the EU economy, and multi-household microsimulation models (representative of the population of the EU), as well as developing national energy systems models oriented to production technologies (electricity/fuels). Further research is needed to explore the possibility of hybridizing integrated models and methodologies from other fields, like behavioural economics, political science, and social engineering. In this sense, there are analytical aspects that will require more outstanding modelling efforts, such as the social dimension (via S-LCA, agent-based models, diffusion models, physical models, neural networks, etc.), the adaptation of uncertainty analysis to the most relevant parameters, and aspects related to sustainability and energy and resource security. In summary, in order to tackle the significant challenges posed by the energy transition, applied research requires a multidisciplinary approach with the participation of energy modellers, data scientists, specialists in advanced governance and tax innovation, social researchers, philosophers, etc. Many of the techniques and lessons we learn today will guide future crises. Funding information All the authors belong and thank the support to the MENTES network on Energy Modelling for a Sustainable Energy Transition, by the Spanish Ministry of Science, Innovation and Universities (project/grant RED2018-102794-T). Evaluating different implications of getting them with input-output, social accounting matrix and computable general models. Potentialities to obtain them from bottom-up renewable energy investments via investment matrices which link to macroeconomics and hybrid models. Several impact levels (meaningful disaggregation level) Multiregional, national, regional, city, etc. Sectoral disaggregation to allow uneven shocks and behaviour. Non-equilibrium states Allowing disequilibrium shortfalls in supply and demand of different markets in the short or medium term. Additional uncertainty analysis Uncertainty of fossil fuel resource availability, technology penetration, etc., but also consideration of out-of-ordinary extremes. Biophysical limits The limits on the availability of non-renewable and renewable energy resources and critical materials may determine some restrictions to growth. Science and Innovation (MCI), the National Research Agency (AEI) and the European Fund for Regional Development (FEDER). Y.L. and S.B. gratefully acknowledge the support of project MUSTEC, funded by the European Union's Horizon 2020 research and innovation programme under grant agreement no. 764626. Declaration of competing interest The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper. Integration of life-cycle sustainability indicators. To assist energy decision-and policy-makers in developing roadmaps focused on prospective technology production mixes of alternative fuels for road transport, with time horizon 2050. Capable of capturing flexible forms in production and consumption, with all sectors in the economy, and detail in specific industries/products such as electricity. The cited features make it highly useful for evaluating footprints (notably GHG emissions), questions on drivers of change and scenario analysis on the energy transition, decarbonization, etc. in Spain and in the world. Currently questions on electricity self-production and self-consumption using disaggregated SUTs are specifically addressed. ENERKAD Energy assessment tool for urban scenarios that performs energy and environmental simulations. Through energy simulation, ENERKAD calculates the annual and hourly energy demand and consumption at building, district or city level, allowing the analysis and comparison of current and future scenarios based on the application of different strategies. It has an easy-to-use interface based on QGIS, facilitating the visualization of the results obtained, helping to make decisions to reduce energy consumption and CO 2 emissions and promoting sustainability. It is based on the so-called Building Stock Models (BSM) and allows calculating on an hourly basis the energy demand, energy consumption and environmental emissions associated with such consumption for each building in a city, using data from the cadastre and basic cartography. This data is combined with information such as building envelope characteristics, consumption patterns and climate information for the area, among others, to characterize the model as a whole. ENERKAD LEAP-OSeMOSYS Modelling tool based on an accounting framework (energy balances) and parametric simulation of energy flows. Its foundation is based on the idea of scenario analysis. LEAP allows the analysis of energy consumption, production and resource extraction in all sectors of the economy, as well as emissions. Its versatility allows analyses to be carried out on any scale (from local and regional to national and supranational). Depending on the behavioural rules chosen, behaviour based on sectoral or technological activity can be introduced, as well as deterministic relationship rules on how entities consume/produce energy. Coupling with OSeMOSYS or NEMO allows for optimization (cost minimization subject to constraints). LEAP-OSeMOSYS SIAM_EX Sustainability Impact Assessment Model for Extremadura (SIAM_EX) is an extended (social, economic and environmental) multiregional input-output model with detail at regional level from the EUREGIO Database. The model allows a complete assessment of socio-economic impacts by productive sectors, ranging from the generation of added value (wages and benefits), to the identification of wage income generated by income quintiles or by population density, as well as to indicators of employment generated by gender, age, occupation or education attained. and environmental impacts as well as the social risks involved within the supply chain of projects. TIMES-Spain Energy optimization model of the TIMES family representing the Spanish energy system. TIMES (The Integrated MARKAL-EFOM System) (IEA-ETSAP, 2020) is a generator of optimization models to estimate long-term and multi-period energy dynamics developed by the IEA in the frame of the ETSAP Technology Collaboration Programme. TIMES optimization models aim to provide energy services at the lowest cost by simultaneously making investment and operating decisions in equipment, primary energy supply and energy trading. The investment decisions made by the models are based on the analysis of the characteristics of alternative generation technologies, on the economic analysis of energy supply, and on environmental criteria.
/* * Copyright (c) 2014-2018 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. in no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising from, * out of or in connection with the software or the use or other dealings in the * software. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.grpc.client; import com.kumuluz.ee.configuration.utils.ConfigurationUtil; import java.util.ArrayList; import java.util.List; import java.util.Optional; /*** * GrpcChannels class. Holds different channels configurations. * * @author <NAME> * @since 1.0 */ public class GrpcChannels { public static class Builder { public GrpcChannels build() { ConfigurationUtil confUtil = ConfigurationUtil.getInstance(); Optional<Integer> numClients = confUtil.getListSize("kumuluzee.grpc.clients"); instance = new GrpcChannels(); if (numClients.isPresent()) { List<GrpcChannelConfig> clients = new ArrayList<>(); for (int i = 0; i < numClients.get(); i++) { GrpcChannelConfig.Builder gcc = new GrpcChannelConfig.Builder(); Optional<String> name = confUtil.get("kumuluzee.grpc.clients[" + i + "].name"); Optional<String> address = confUtil.get("kumuluzee.grpc.clients[" + i + "].address"); Optional<Integer> port = confUtil.getInteger("kumuluzee.grpc.clients[" + i + "].port"); Optional<String> cert = confUtil.get("kumuluzee.grpc.clients[" + i + "].certFile"); Optional<String> key = confUtil.get("kumuluzee.grpc.clients[" + i + "].keyFile"); Optional<String> trust = confUtil.get("kumuluzee.grpc.clients[" + i + "].trustFile"); name.ifPresent(gcc::name); address.ifPresent(gcc::address); port.ifPresent(gcc::port); cert.ifPresent(gcc::certFile); key.ifPresent(gcc::keyFile); trust.ifPresent(gcc::trustManager); clients.add(gcc.build()); } instance.grpcChannelConfigs = clients; } return instance; } } private List<GrpcChannelConfig> grpcChannelConfigs; private static GrpcChannels instance; public static GrpcChannels getInstance() { return instance; } public List<GrpcChannelConfig> getGrpcChannelConfigs() { return grpcChannelConfigs; } public GrpcChannelConfig getGrpcClientConfig(String name) { for (GrpcChannelConfig config : grpcChannelConfigs) { if (config.getName().equals(name)) return config; } return null; } }
<filename>database/redis/config.go<gh_stars>10-100 package redis import "time" // Config - Redis database connection config type Config struct { MasterName string Addrs []string Username string Password string MetricsTTL time.Duration DialTimeout time.Duration ReadTimeout time.Duration WriteTimeout time.Duration }
<reponame>masud-technope/ACER-Replication-Package-ASE2017 /******************************************************************************* * Copyright (c) 2007 BEA Systems, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package targets.negative.pa; /** * This code is syntactic but contains semantic errors due to missing types. * All the M* types (M for "Missing") are expected to be unresolved. * The desired behavior is specified in the javadoc for package * javax.lang.model.element: in general, missing types should be replaced * by empty types with the same name. */ class Negative3 { M1 foo(M2.M3.M4 param) { } } interface I2 extends MI1 { M5 boo(M6.M7.M8 param); }
<filename>parser/lex_test.go package parser import "testing" type lexTest struct { name string input string tokens []token } func mkToken(typ tokenType, text string) token { return token{ typ: typ, val: text, } } var ( tEOF = mkToken(tokenEOF, "") tLBrace = mkToken(tokenLBrace, "{") tRBrace = mkToken(tokenRBrace, "}") tLAngle = mkToken(tokenLAngle, "<") tRAngle = mkToken(tokenRAngle, ">") tComma = mkToken(tokenComma, ",") tSemicolon = mkToken(tokenSemicolon, ";") tInclude = mkToken(tokenInclude, "include") tModule = mkToken(tokenModule, "module") tClass = mkToken(tokenClass, "class") tByte = mkToken(tokenByte, "byte") tBoolean = mkToken(tokenBoolean, "boolean") tInt = mkToken(tokenInt, "int") tLong = mkToken(tokenLong, "long") tFloat = mkToken(tokenFloat, "float") tDouble = mkToken(tokenDouble, "double") tUString = mkToken(tokenUString, "ustring") tBuffer = mkToken(tokenBuffer, "buffer") tVector = mkToken(tokenVector, "vector") tMap = mkToken(tokenMap, "map") ) var sampleDDL = ` module links { class Link { ustring URL; boolean isRelative; ustring anchorText; }; } ` var lexTests = []lexTest{ {"empty", "", []token{tEOF}}, {"spaces", " \t\n", []token{tEOF}}, {"punctuation", "{}<>,;", []token{ tLBrace, tRBrace, tLAngle, tRAngle, tComma, tSemicolon, tEOF, }}, {"line comment", "// this is a line comment\n\n", []token{ mkToken(tokenLineComment, "// this is a line comment"), tEOF, }}, {"block comment", "/** line 1\n * line 2\n *line 3\n */", []token{ mkToken(tokenBlockComment, "/** line 1\n * line 2\n *line 3\n */"), tEOF, }}, {"bad comment", "/whoops", []token{ mkToken(tokenError, "bad character U+0077 'w'"), }}, {"unterminated block comment", "/* i am error", []token{ mkToken(tokenError, "unterminated block comment"), }}, {"quoted string", `"suck it trebek"`, []token{ mkToken(tokenString, "suck it trebek"), tEOF, }}, {"unquoted string", `"abc`, []token{ mkToken(tokenError, "unterminated quoted string"), }}, {"keywords", "include module class", []token{ tInclude, tModule, tClass, tEOF, }}, {"ptypes", "byte boolean int long float double ustring buffer", []token{ tByte, tBoolean, tInt, tLong, tFloat, tDouble, tUString, tBuffer, tEOF, }}, {"ctypes", "vector<ustring> map<int, float>", []token{ tVector, tLAngle, tUString, tRAngle, tMap, tLAngle, tInt, tComma, tFloat, tRAngle, tEOF, }}, {"identifier", "myThing myThing2 com.github.fake.news", []token{ mkToken(tokenIdentifier, "myThing"), mkToken(tokenIdentifier, "myThing2"), mkToken(tokenIdentifier, "com.github.fake.news"), tEOF, }}, {"bad character", "!", []token{ mkToken(tokenError, "unknown character U+0021 '!'"), }}, {"complete ddl", sampleDDL, []token{ tModule, mkToken(tokenIdentifier, "links"), tLBrace, tClass, mkToken(tokenIdentifier, "Link"), tLBrace, tUString, mkToken(tokenIdentifier, "URL"), tSemicolon, tBoolean, mkToken(tokenIdentifier, "isRelative"), tSemicolon, tUString, mkToken(tokenIdentifier, "anchorText"), tSemicolon, tRBrace, tSemicolon, tRBrace, tEOF, }}, } func collect(input string) []token { tokens := []token{} l := lex(input) for { token := l.nextToken() tokens = append(tokens, token) if token.typ == tokenEOF || token.typ == tokenError { break } } return tokens } func TestLex(t *testing.T) { for _, tc := range lexTests { t.Run(tc.name, func(t *testing.T) { tokens := collect(tc.input) if !equal(tokens, tc.tokens) { t.Errorf("got\n\t%+v\nexpected:\n\t%+v", tokens, tc.tokens) } }) } } func equal(t1, t2 []token) bool { if len(t1) != len(t2) { return false } for i := range t1 { if t1[i].typ != t2[i].typ { return false } if t1[i].val != t2[i].val { return false } } return true }
Vincent Kompany: Manchester City fans unfairly 'punished' Manchester City captain Vincent Kompany was unhappy his side’s fans were unable to watch their 2-2 Champions League draw with CSKA Moscow after some home supporters appeared to gain access to the ground. UEFA had ordered CSKA to play their home match with City behind closed doors as a result of racist behaviour from their travelling support in the September trip to Roma. Some tickets were issued for the game, mainly to media and representatives of the two clubs, but some home fans appeared to have gained access to the Khimki Arena. On the pitch, goals from Sergio Aguero and James Milner gave City a commanding lead, but the hosts fought back to earn a 2-2 draw through Bibras Natkho's late penalty, inflicting a major blow to the visitors' hopes of qualification. Glenn Hoddle said that complacency has cost Manchester City again in Europe after they threw away a two goal lead against CSKA Moscow. Glenn Hoddle said that complacency has cost Manchester City again in Europe after they threw away a two goal lead against CSKA Moscow. Speaking afterwards, Kompany said: “It was supposed to be a game without fans, but there were still 500 fans there, cheering them on. “That is not a problem but I don’t understand where our fans are then. Why can we not bring our fans? “I feel like the only team being punished here today was Man City. I think sometimes we need to speak up. It’s nonsense. “They are the team that gone done for racism, not Man City. Why can’t our fans come? “It didn’t affect us but fair is fair and maybe now is the time to say it, to speak up. “I am not shying away from anything that happened, with the performance we put in today, I understand everything. “We will make the analysis of how we should improve but those little things, they shouldn’t happen.” At the moment it looks like they're going to go out, but not just go out, but go out with a whimper and that's not what anybody wants to see. Jamie Redknapp on City After the match, CSKA media director Sergey Aksenov insisted the club had nothing to do with the fans who entered. He said: "Those people you are talking about are 360 people from the UEFA Champions Club - partners, sponsors. If they are CKSA fans they are good for us. Everyone is invited by UEFA, not CSKA.'' It was suggested to City boss Manuel Pellegrini that the presence of supporters may have influenced the referee's decision to award CSKA their late penalty. Pellegrini said: "Well I agree but maybe it is not my duty to talk about things that do not correspond to my duty. "I think UEFA has its rules. This stadium was closed doors to everyone. "I don't know who has permission to give entrance to all those peoples, but really it is not my duty. I don't want to talk about the referee or other things. I don't want to be punished again.'' Manuel Pellegrini refused to accept his side are outside bets for qualification to the knockout round of the Champions League, after another draw left them Manuel Pellegrini refused to accept his side are outside bets for qualification to the knockout round of the Champions League, after another draw left them Asked if his team are now outsiders to get out of Group E, Pellegrini told Sky Sports 5: "Why? We have nine points more to play for. After we have played for the remaining nine points, we will see.'' Asked further if he is confident City will qualify, he said: "Of course, in the end.'' City have now taken just two points from their opening three fixtures and seemingly have to beat CSKA at the Etihad Stadium on November 5 if they are to stand any chance of progressing. Pellegrini admitted his side had been made to pay for not killing the game off. "Football is 95 minutes, it's not just the first half," Pellegrini added. "We played very well, we scored two goals and we had clear chances to score two or three more goals. "But we didn't and we have to play 90 minutes with a team that is a good team. If you give them space, they are a dangerous team. "We didn't have the pace and we didn't move the ball as we did in the first half - we didn't really have one chance to score, and finally they scored that penalty that the referee whistled for CSKA.''
/* * * Copyright 2019-2020 felord.cn * * 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 * Website: * https://felord.cn * 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 cn.felord.payment.wechat.v3.model.discountcard; import lombok.Data; /** * 先享卡扣费状态变化通知解密. * * * @author felord.cn * @since 1.0.2.RELEASE */ @Data public class DiscountCardUserPaidConsumeData { /** * The Appid. */ private String appid; /** * The Card id. */ private String cardId; /** * The Card template id. */ private String cardTemplateId; /** * The Mchid. */ private String mchid; /** * The Openid. */ private String openid; /** * The Out card code. */ private String outCardCode; /** * The Pay information. */ private PayInformation payInformation; /** * The State. */ private String state; /** * The Total amount. */ private Long totalAmount; /** * The Unfinished reason. */ private String unfinishedReason; /** * The type Pay information. */ @Data public static class PayInformation { /** * The Pay amount. */ private Long payAmount; /** * The Pay state. */ private String payState; /** * The Pay time. */ private String payTime; /** * The Transaction id. */ private String transactionId; } }
<gh_stars>1-10 # coding: utf-8 from tag import * from icon import *
<reponame>misode/datapack-language-server /* istanbul ignore file */ export { URL as Uri } from 'url' import { promises as fsp } from 'fs' import { Uri } from '.' export interface FileService { /** * @param uri A URI. * @returns If the URI is accessible in the real file system. */ accessible(uri: string): Promise<boolean> /** * @param uri A file URI. * @returns The UTF-8 decoded content of the file at `uri`. * @throws If the URI doesn't exist in the file system. */ readFile(uri: string): Promise<string> /** * @param uri A directory URI. * @returns The content of this directory. * @throws If the URI doesn't exist in the file system. */ readdir(uri: string): Promise<string[]> stat(uri: string): Promise<FileStats> } export namespace FileService { let instance: FileService | undefined /** * @returns A `FileService` implementation that provides access to the real file system * based on build-in node.js modules. */ export function create(): FileService { return instance ?? (instance = new FileServiceImpl()) } } /** * @internal This is only exported to be overridden in tests. */ export class FileServiceImpl implements FileService { async accessible(uri: string): Promise<boolean> { return fsp.stat(new Uri(uri)).then(() => true, () => false) } async readFile(uri: string): Promise<string> { return fsp.readFile(new Uri(uri), 'utf-8') } async readdir(uri: string): Promise<string[]> { return fsp.readdir(new Uri(uri)) } async stat(uri: string): Promise<FileStats> { return fsp.stat(new Uri(uri)) } } export interface FileStats { isFile(): boolean isDirectory(): boolean isSymbolicLink(): boolean size: number atimeMs: number mtimeMs: number ctimeMs: number birthtimeMs: number atime: Date mtime: Date ctime: Date birthtime: Date }
<gh_stars>0 package com.javaee.phone; public class Phone { private String brand; private double price; public Phone() {} public Phone(String brand, double price) { this.brand = brand; this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public void makeCall() { System.out.println(brand + " make a phone call"); } public void sendMessage() { System.out.println(brand + " send a message"); } public void displayCaller() { System.out.println(brand + " display caller's phone number"); } }
package org.sagebionetworks.web.client.widget.header; import org.sagebionetworks.schema.adapter.JSONObjectAdapter; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.web.client.DateTimeUtilsImpl; import org.sagebionetworks.web.client.SynapseJSNIUtils; import org.sagebionetworks.web.client.cookie.CookieKeys; import org.sagebionetworks.web.client.cookie.CookieProvider; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class Header implements HeaderView.Presenter, IsWidget { public static final String WWW_SYNAPSE_ORG = "www.synapse.org"; private HeaderView view; private SynapseJSNIUtils synapseJSNIUtils; CookieProvider cookies; public static boolean isShowingPortalAlert = false; public static JSONObjectAdapter portalAlertJson = null; @Inject public Header(HeaderView view, SynapseJSNIUtils synapseJSNIUtils, EventBus eventBus, CookieProvider cookies, JSONObjectAdapter jsonObjectAdapter) { this.view = view; this.cookies = cookies; this.synapseJSNIUtils = synapseJSNIUtils; view.clear(); view.setPresenter(this); initStagingAlert(); view.getEventBinder().bindEventHandlers(this, eventBus); if (cookies.getCookie(CookieKeys.COOKIES_ACCEPTED) == null) { view.setCookieNotificationVisible(true); } else { view.setCookieNotificationVisible(false); } // portal alert state sticks around for entire app session String portalAlertString = cookies.getCookie(CookieKeys.PORTAL_CONFIG); isShowingPortalAlert = portalAlertString != null; if (isShowingPortalAlert) { cookies.removeCookie(CookieKeys.PORTAL_CONFIG); try { portalAlertJson = jsonObjectAdapter.createNew(portalAlertString); } catch (JSONObjectAdapterException e) { synapseJSNIUtils.consoleError(e); } } else { portalAlertJson = null; } view.setPortalAlertVisible(isShowingPortalAlert, portalAlertJson); } public void initStagingAlert() { String hostName = synapseJSNIUtils.getCurrentHostName().toLowerCase(); boolean visible = !hostName.contains(WWW_SYNAPSE_ORG); view.setStagingAlertVisible(visible); } public void configure() { refresh(); } public Widget asWidget() { view.setPresenter(this); return view.asWidget(); } public void refresh() { view.setPortalAlertVisible(isShowingPortalAlert, portalAlertJson); view.refresh(); } @Override public void onCookieNotificationDismissed() { view.setCookieNotificationVisible(false); cookies.setCookie(CookieKeys.COOKIES_ACCEPTED, Boolean.TRUE.toString(), DateTimeUtilsImpl.getYearFromNow()); } }
<reponame>gsofter/timetracker-app<filename>portable-devices/desktop/src/common/config/base-apollo-client.ts /* eslint-disable no-underscore-dangle */ /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { ApolloClient, ApolloClientOptions } from 'apollo-client'; import { InMemoryCache } from 'apollo-cache-inmemory'; import { HttpLink, createHttpLink } from 'apollo-link-http'; import { BatchHttpLink } from 'apollo-link-batch-http'; import { onError } from 'apollo-link-error'; import { ApolloLink } from 'apollo-link'; import { WebSocketLink } from 'apollo-link-ws'; import { getOperationAST } from 'graphql'; import apolloLogger from 'apollo-link-logger'; import { invariant } from 'ts-invariant'; import fetch from 'node-fetch'; const schema = ` `; interface IApolloClientParams { fragmentMatcher: any; initialState?: any; scope: 'browser' | 'server' | 'native'; linkConnectionParams?: any; additionalLinks: any[]; getDataIdFromObject: (x?: any) => string; clientState: any; isDebug: boolean; isDev: boolean; isSSR: boolean; httpGraphqlURL: string; httpLocalGraphqlURL: string; } const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { graphQLErrors.map(({ message, locations, path }) => // tslint:disable-next-line invariant.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`), ); } if (networkError) { // tslint:disable-next-line invariant.warn(`[Network error]: ${networkError}`); } }); let _apolloClient: ApolloClient<any>; let _memoryCache: InMemoryCache; export const createApolloClient = ({ linkConnectionParams, scope, isDev, isDebug, isSSR, getDataIdFromObject, clientState, additionalLinks, httpGraphqlURL, httpLocalGraphqlURL, initialState, }: IApolloClientParams) => { const isBrowser = scope === 'browser'; const isServer = scope === 'server'; let link; const cache = new InMemoryCache({ dataIdFromObject: getDataIdFromObject, fragmentMatcher: clientState.fragmentMatcher as any, }); if (_apolloClient && _memoryCache) { // return quickly if client is already created. return { apolloClient: _apolloClient, cache: _memoryCache, }; } _memoryCache = cache; if (isBrowser) { const connectionParams = () => { const param = {}; for (const connectionParam of linkConnectionParams) { Object.assign(param, connectionParam()); } return param; }; const wsLink = new WebSocketLink({ uri: httpGraphqlURL.replace(/^http/, 'ws'), options: { reconnect: true, timeout: 20000, reconnectionAttempts: 10, lazy: true, connectionParams, }, }); link = ApolloLink.split( ({ query, operationName }) => { if (operationName.endsWith('_WS')) { return true; } const operationAST = getOperationAST(query as any, operationName); return !!operationAST && operationAST.operation === 'subscription'; }, wsLink, new HttpLink({ uri: httpGraphqlURL, }), ); } else { // link = new BatchHttpLink({ uri: httpLocalGraphqlURL }); link = createHttpLink({ uri: httpLocalGraphqlURL, fetch: fetch as any }); } const links = [errorLink, ...additionalLinks, /** ...modules.errorLink, */ link]; // Add apollo logger during development only if ((isDev || isDebug) && isBrowser) { links.unshift(apolloLogger); } const params: ApolloClientOptions<any> = { queryDeduplication: true, typeDefs: schema.concat(<string>clientState.typeDefs), resolvers: clientState.resolvers as any, link: ApolloLink.from(links), cache, }; if (isSSR) { if (isBrowser) { if (initialState) { cache.restore(initialState); } params.ssrForceFetchDelay = 100; } else if (isServer) { params.ssrMode = true; } } _apolloClient = new ApolloClient<any>(params); cache.writeData({ data: { ...clientState.defaults, }, }); if ((isDev || isDebug) && isBrowser) { window.__APOLLO_CLIENT__ = _apolloClient; } return { apolloClient: _apolloClient, cache }; };
/** * Given an AppEngineWebXml, ensure that Flex-specific settings are only present if actually Flex, * and that Java11-specific settings are only present if actually Java11. * * @throws AppEngineConfigException If an option is applied to the wrong runtime. */ void validateRuntime() { if (!appEngineWebXml.isFlexible()) { if (appEngineWebXml.getNetwork() != null) { if (appEngineWebXml.getNetwork().getSessionAffinity()) { throw new AppEngineConfigException( "'session-affinity' is an <env>flex</env> specific " + "field."); } if (appEngineWebXml.getNetwork().getSubnetworkName() != null && !appEngineWebXml.getNetwork().getSubnetworkName().isEmpty()) { throw new AppEngineConfigException( "'subnetwork-name' is an <env>flex</env> specific " + "field."); } if (appEngineWebXml.getLivenessCheck() != null) { throw new AppEngineConfigException( "'liveness-check' is an <env>flex</env> specific " + "field."); } if (appEngineWebXml.getReadinessCheck() != null) { throw new AppEngineConfigException( "'readiness-check' is an <env>flex</env> specific " + "field."); } } } if (!appEngineWebXml.isJava11OrAbove()) { if (appEngineWebXml.getRuntimeChannel() != null) { throw new AppEngineConfigException( "'runtime-channel' is not valid with this runtime."); } if (appEngineWebXml.getEntrypoint() != null) { throw new AppEngineConfigException( "'entrypoint' is not valid with this runtime."); } } }
def process_cluster_attributes(self, cluster, cluster_attrs): custom_attrs = cluster_attrs.get(self.plugin.name, {}) if custom_attrs: attr_plugin_version = custom_attrs['metadata']['plugin_version'] if attr_plugin_version != self.plugin.version: return enable = custom_attrs['metadata']['enabled'] if enable and cluster not in self.plugin.clusters: self.plugin.clusters.append(cluster) elif not enable and cluster in self.plugin.clusters: self.plugin.clusters.remove(cluster)
<filename>Chapter03/breaking_python.py for number in range(0,200): if number == 0: continue elif number % 3 != 0: continue elif type(number) != int: continue else: pass print(number)
/** * Open closing the application store the high score data. */ @Override protected void onStop() { super.onStop(); SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, 0); SharedPreferences.Editor preferencesEditor = preferences.edit(); preferencesEditor.putString("highScore", highScore.getText().toString()); preferencesEditor.commit(); }
// Dump - Will return message prepared to be dumped out. It's like prettify message for output func (m *Message) Dump() (resp string) { var keys []string for k := range m.Headers { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { resp += fmt.Sprintf("%s: %s\r\n", k, m.Headers[k]) } resp += fmt.Sprintf("BODY: %v\r\n", string(m.Body)) return }