text
stringlengths
1
1.05M
oc project default cat <<! | oc create -f - apiVersion: v1 kind: PersistentVolumeClaim metadata: name: registry-storage-claim spec: accessModes: - ReadWriteOnce resources: requests: storage: 2Gi ! oc get pvc
#!/bin/sh #PBS -q h-regular #PBS -l select=1 #PBS -W group_list=gk77 #PBS -l walltime=18:00:00 #PBS -N LISA-HI-ELMO #PBS -j oe #PBS -M christopher@orudo.cc #PBS -m abe JOB_NAME="conll09-sa-small-dep_prior-gold_inp-mixture_model_10-lsparse-return_last-inf_full-px3-gp" SAVEDIR=.model/llisa/e2e/glove_100d/1620402409/conll09-sa-small-dep_prior-gold_inp-mixture_model_10-lsparse-return_last-inf_full-px3-gp CONF=config/llisa/e2e/glove_100d/conll09-sa-small-dep_prior-gold_inp-bilinear-px3-gp.conf #SINGULARITY_IMG=/lustre/gk77/k77015/.Singularity/imgs/LISA.simg SINGULARITY_IMG=/home/u00222/singularity/images/LISA-tfp.simg HPARAMS_STR="" source reedbush-scripts/llisa/hparam_str/conll09.sh source reedbush-scripts/llisa/hparam_str/fixed_seed.sh source reedbush-scripts/llisa/hparam_str/dep_prior_trainable.sh source reedbush-scripts/llisa/hparam_str/memory_efficient_prior_implementation.sh source reedbush-scripts/llisa/hparam_str/use_dependency_type_on_bilinear.sh source reedbush-scripts/llisa/hparam_str/aggregation_weight_one_init.sh source reedbush-scripts/llisa/hparam_str/learn_mask_per_srl_label.sh source reedbush-scripts/llisa/hparam_str/exclude_specific_path.sh source reedbush-scripts/llisa/hparam_str/apply_mean_weight.sh source reedbush-scripts/llisa/hparam_str/mixture_model_10.sh source reedbush-scripts/llisa/hparam_str/return_last.sh #source reedbush-scripts/llisa/hparam_str/share_pred_role_mlp.sh source reedbush-scripts/llisa/hparam_str/new_updown_search.sh source reedbush-scripts/llisa/hparam_str/mixture_model_inference_full.sh echo $HPARAMS_STR ADDITIONAL_PARAMETERS="--hparams "$HPARAMS_STR" --use_llisa_proj" echo $ADDITIONAL_PARAMETERS source reedbush-scripts/llisa/run_experiment_gs.sh
# test await expression import sys if sys.implementation.name == 'micropython': # uPy allows normal generators to be awaitables coroutine = lambda f: f else: import types coroutine = types.coroutine @coroutine def wait(value): print('wait value:', value) msg = yield 'message from wait(%u)' % value print('wait got back:', msg) return 10 async def f(): x = await wait(1)**2 print('x =', x) coro = f() print('return from send:', coro.send(None)) try: coro.send('message from main') except StopIteration: print('got StopIteration')
import * as _ from "lodash"; import createCacher from "./bundleapi/apicacher"; import createApi from "./bundleapi/apicreator"; import { Bucket } from "./bundleapi/bucket"; import { get as conf } from "./configuration"; export interface IRecipe { type: "MysticForge" | "Salvage" | "Vendor" | "Charge" | "DoubleClick" | "Achievement" | "Crafting"; ingredients: Array<IRecipeItem | IRecipeCurrency | IAchievement>; results: Array<IRecipeItem | IRecipeCurrency>; prerequisites: Array<IAchievementPrerequisite | ICraftingPrerequisite>; } export interface ICraftingPrerequisite { disciplines: Discipline[]; rating: number; } export type Discipline = "Artificer" | "Armorsmith" | "Chef" | "Huntsman" | "Jeweler" | "Leatherworker" | "Tailor" | "Weaponsmith" | "Scribe"; export interface IOfficialApiRecipe { output_item_id: number; output_item_count: number; min_rating: number; disciplines: Discipline[]; ingredients: Array<{ item_id: number; count: number; }>; id: number; } export interface IMysticApiRecipe { type: "MysticForge" | "Salvage" | "Vendor" | "Charge" | "DoubleClick" | "Achievement"; ingredients: Array<IRecipeItem | IRecipeCurrency | IAchievement>; results: Array<IRecipeItem | IRecipeCurrency>; prerequisites: IAchievementPrerequisite[]; } function isRecipeItem(x: IRecipeItem | IRecipeCurrency): x is IRecipeItem { return (x as IRecipeItem).id !== undefined; } export interface IRecipeItem { id: number; amount: number; } export interface IRecipeCurrency { name: string; amount: number; } export interface IAchievement { achievement_id: number; } export interface IAchievementPrerequisite { achievement_id: number; } export interface ICharacterEquipment { equipment: Array<{ id: number; }>; } export interface ICharacterInventory { bags: Array<{ id: number; size: number; inventory: Array<{ id: number; count: number; }>; } | null>; } export interface IMaterial { id: number; category: number; count: number; } export interface IBankEntry { id: number; count: number; charges?: number; } export interface IItem { id: number; chat_link: string; name: string; icon: string; description: string; } export type TokenInfoPermission = "account" | "builds" | "characters" | "guilds" | "inventories" | "progressions" | "pvp" | "tradingpost" | "unlocks" | "wallet"; export interface ITokenInfo { id: string; name: string; permissions: TokenInfoPermission[]; } export interface ICurrency { id: number; name: string; description: string; order: number; icon: string; } export interface IWalletEntry { id: number; value: number; } export interface IPrice { id: number; whitelisted: boolean; buys: { quantity: number; unit_price: number; }; sells: { quantity: number; unit_price: number; }; } export interface IApi { getAccountBank: (accessToken: string) => Promise<Array<IBankEntry | null>>; getAccountCharacterEquipment: (accessToken: string, characterName: string) => Promise<ICharacterEquipment>; getAccountCharacterInventory: (accessToken: string, characterName: string) => Promise<ICharacterInventory>; getAccountCharacters: (accessToken: string) => Promise<string[]>; getAccountMaterials: (accessToken: string) => Promise<IMaterial[]>; getAccountWallet: (accessToken: string) => Promise<IWalletEntry[]>; getCommercePrice: (id: number) => Promise<IPrice>; getCurrenciesIds: () => Promise<number[]>; getCurrency: (id: number) => Promise<ICurrency>; getItem: (id: number) => Promise<IItem>; getRecipesFromOutput: (outputId: number) => Promise<IRecipe[]>; getTokenInfo: (accessToken: string) => Promise<TokenInfoPermission>; } const getApi = (): IApi => { const officialApiBucket = new Bucket(0, 10, 100); const oapiBase = "https://api.guildwars2.com/v2"; const officialApiBundle = createApi( officialApiBucket, oapiBase, "ids", "id"); const officialApiBundleCacher = createCacher<[string, number]>( ([path, id]: [string, number]) => officialApiBundle(path, id), ([path, id]: [string, number]) => 24 * 60 * 60 * 1000); const officialApiRaw = (url: string) => officialApiBucket .getToken() .then(() => conf().fetch(url)) .then((response) => response.status < 200 || response.status >= 400 ? getResponseError(response) : response.json()); const officialApiRawCacher = createCacher<[string]>( ([url]: [string]) => officialApiRaw(url), ([url]: [string]) => 24 * 60 * 60 * 1000); const mysticApiBucket = new Bucket(0, 10, 100); const mysticApiBundle = createApi( mysticApiBucket, "https://legendary-quest.herokuapp.com/api", "resultitemids", "", { getObjectId: (obj: any, idList: number[]) => _.intersection( idList, (obj as IMysticApiRecipe) .results .filter(isRecipeItem) .map((recipeItem) => recipeItem.id))[0], }); const mysticApiBundleCacher = createCacher<[string, number]>( ([path, id]: [string, number]) => mysticApiBundle(path, id), ([path, id]: [string, number]) => 60 * 60 * 1000); const getResponseError = (response: Response) => response .text() .then((text) => Promise.reject(`API error: status = ${response.status}, text = ${text}`)); const getOApiUrl = (path: string, accessToken?: string): [string] => [oapiBase + path + (accessToken ? "?access_token=" + accessToken : "")]; const api = { getAccountBank: (accessToken: string): Promise<Array<IBankEntry | null>> => officialApiRawCacher(getOApiUrl("/account/bank", accessToken)), getAccountCharacterEquipment: (accessToken: string, characterName: string): Promise<ICharacterEquipment> => officialApiRawCacher(getOApiUrl(`/characters/${characterName}/equipment`, accessToken)), getAccountCharacterInventory: (accessToken: string, characterName: string): Promise<ICharacterInventory> => officialApiRawCacher(getOApiUrl(`/characters/${characterName}/inventory`, accessToken)), getAccountCharacters: (accessToken: string): Promise<string[]> => officialApiRawCacher(getOApiUrl("/characters", accessToken)), getAccountMaterials: (accessToken: string): Promise<IMaterial[]> => officialApiRawCacher(getOApiUrl("/account/materials", accessToken)), getAccountWallet: (accessToken: string): Promise<IWalletEntry[]> => officialApiRawCacher(getOApiUrl("/account/wallet", accessToken)), getCommercePrice: (id: number) => officialApiBundleCacher(["/commerce/prices", id]), getCurrenciesIds: (): Promise<number[]> => officialApiRawCacher(getOApiUrl("/currencies")), getCurrency: (id: number): Promise<ICurrency> => officialApiBundleCacher(["/currencies", id]), getItem: (id: number): Promise<IItem> => officialApiBundleCacher(["/items", id]), getRecipesFromOutput: (outputId: number) => officialApiRawCacher(getOApiUrl(`/recipes/search?output=${outputId}`)) .then((ids: number[]) => ids && ids.length > 0 ? Promise.all(ids.map((id) => (officialApiBundleCacher(["/recipes", id]) as Promise<IOfficialApiRecipe[]>) .then((recipes) => officialApiRecipeConverter(recipes[0])))) : (mysticApiBundleCacher(["/recipes", outputId]) as Promise<IMysticApiRecipe[]>) .then((recipes) => recipes.map(mysticApiRecipeConverter))), getTokenInfo: (accessToken: string): Promise<TokenInfoPermission> => officialApiRawCacher(getOApiUrl("/tokeninfo", accessToken)), }; const mysticApiRecipeConverter = (r: IMysticApiRecipe): IRecipe => ({ ingredients: r.ingredients, prerequisites: r.prerequisites, results: r.results, type: r.type, }); const officialApiRecipeConverter = (r: IOfficialApiRecipe): IRecipe => { return ({ ingredients: r.ingredients.map((oIngredient) => ({ amount: oIngredient.count, id: oIngredient.item_id, })), prerequisites: r.disciplines.length > 0 ? [{ disciplines: r.disciplines, rating: r.min_rating }] : [], results: [{ amount: r.output_item_count, id: r.output_item_id, }], type: "Crafting", }); }; return api; }; export default getApi;
<reponame>dhanangap/opensrp-client-anc package org.smartregister.anc.library.helper; import org.smartregister.anc.library.util.DBConstantsUtils; /** * Created by ndegwamartin on 28/01/2018. */ public class DBQueryHelper { public static final String getHomePatientRegisterCondition() { return DBConstantsUtils.KeyUtils.DATE_REMOVED + " IS NULL"; } }
<reponame>SAP-samples/safety-at-work-android<gh_stars>1-10 package demo.sap.safetyandroid.test.testcases.ui; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import demo.sap.safetyandroid.app.WelcomeActivity; import demo.sap.safetyandroid.test.core.ClientPolicyManager; import demo.sap.safetyandroid.test.core.BaseTest; import demo.sap.safetyandroid.test.core.UIElements; import demo.sap.safetyandroid.test.core.Utils; import demo.sap.safetyandroid.test.core.Credentials; import demo.sap.safetyandroid.test.core.WizardDevice; import demo.sap.safetyandroid.test.pages.DetailPage; import demo.sap.safetyandroid.test.pages.PasscodePage; import demo.sap.safetyandroid.test.pages.EntityListPage; import demo.sap.safetyandroid.test.pages.MasterPage; import demo.sap.safetyandroid.test.pages.SettingsListPage; import demo.sap.safetyandroid.test.pages.WelcomePage; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static demo.sap.safetyandroid.test.core.UIElements.EntityListScreen.entityList; @RunWith(AndroidJUnit4.class) public class LogonTests extends BaseTest { @Rule public ActivityTestRule<WelcomeActivity> activityTestRule = new ActivityTestRule<>(WelcomeActivity.class); @Test public void testLogonFlow() { // Take care of welcome screen, authentication, and passcode flow. Utils.doOnboarding(activityTestRule.getActivity()); // Actions on the entitylist Page EntityListPage entityListPage = new EntityListPage(entityList); entityListPage.clickFirstElement(); entityListPage.leavePage(); // Actions on the master Page MasterPage masterPage = new MasterPage(UIElements.MasterScreen.refreshButton); masterPage.clickFirstElement(); masterPage.leavePage(); DetailPage detailPage = new DetailPage(); detailPage.clickBack(); detailPage.leavePage(); masterPage = new MasterPage(UIElements.MasterScreen.refreshButton); masterPage.clickBack(); masterPage.leavePage(); entityListPage = new EntityListPage(entityList); entityListPage.clickSettings(); entityListPage.leavePage(); SettingsListPage settingsListPage = new SettingsListPage(); settingsListPage.clickResetApp(); settingsListPage.checkConfirmationDialog(); settingsListPage.clickYes(); } @Test public void logonFlowPutAppIntoBackground() { // Take care of welcome screen, authentication, and passcode flow. Utils.doOnboarding(activityTestRule.getActivity()); EntityListPage entityListPage = new EntityListPage(entityList); entityListPage.clickFirstElement(); entityListPage.leavePage(); MasterPage masterPage = new MasterPage(UIElements.MasterScreen.refreshButton); masterPage.clickFirstElement(); masterPage.leavePage(); // Get the lockTimeOut (in seconds) from the SecureStoreManager int lockTimeOut = ClientPolicyManager.getInstance().getPasscodeLockTimeout(); // Put the app into background and immediately start again WizardDevice.putApplicationBackground(0, activityTestRule); WizardDevice.reopenApplication(); if (lockTimeOut == 0) { PasscodePage.EnterPasscodePage enterPasscodePage = new PasscodePage().new EnterPasscodePage(); enterPasscodePage.enterPasscode(Credentials.PASSCODE); enterPasscodePage.clickSignIn(); enterPasscodePage.leavePage(); } DetailPage mDetailPage = new DetailPage(UIElements.DetailScreen.deleteButton); mDetailPage.clickBack(); mDetailPage.leavePage(); masterPage = new MasterPage(UIElements.MasterScreen.refreshButton); masterPage.clickBack(); masterPage.leavePage(); entityListPage = new EntityListPage(entityList); entityListPage.clickSettings(); entityListPage.leavePage(); SettingsListPage settingsListPage = new SettingsListPage(); settingsListPage.clickResetApp(); settingsListPage.checkConfirmationDialog(); settingsListPage.clickYes(); } @Test public void LogonFlowBack () { Utils.checkCredentials(); WelcomePage welcomePage = new WelcomePage(); welcomePage.clickGetStarted(); welcomePage.waitForCredentials(); Utils.pressBack(); Utils.doOnboarding(activityTestRule.getActivity()); } }
#!/bin/bash -eu # Publish any versions of the docker image not yet pushed to ${JENKINS_REPO} # Arguments: # -n dry run, do not build or publish images # -d debug set -o pipefail . jenkins-support : "${DOCKERHUB_ORGANISATION:=jenkins}" : "${DOCKERHUB_REPO:=jenkins}" JENKINS_REPO="${DOCKERHUB_ORGANISATION}/${DOCKERHUB_REPO}" cat <<EOF Docker repository in Use: * JENKINS_REPO: ${JENKINS_REPO} EOF sort-versions() { if [ "$(uname)" == 'Darwin' ]; then gsort --version-sort else sort --version-sort fi } # Try tagging with and without -f to support all versions of docker docker-tag() { local from="${JENKINS_REPO}:$1" local to="$2/${DOCKERHUB_REPO}:$3" local out docker pull "$from" if out=$(docker tag -f "$from" "$to" 2>&1); then echo "$out" else docker tag "$from" "$to" fi } login-token() { # could use jq .token curl -q -sSL "https://auth.docker.io/token?service=registry.docker.io&scope=repository:${JENKINS_REPO}:pull" | grep -o '"token":"[^"]*"' | cut -d':' -f 2 | xargs echo } is-published() { local tag=$1 local opts="" if [ "$debug" = true ]; then opts="-v" fi local http_code; http_code=$(curl $opts -q -fsL -o /dev/null -w "%{http_code}" -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -H "Authorization: Bearer $TOKEN" "https://index.docker.io/v2/${JENKINS_REPO}/manifests/$tag") if [ "$http_code" -eq "404" ]; then false elif [ "$http_code" -eq "200" ]; then true else echo "Received unexpected http code from Docker hub: $http_code" exit 1 fi } get-manifest() { local tag=$1 local opts="" if [ "$debug" = true ]; then opts="-v" fi curl $opts -q -fsSL -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -H "Authorization: Bearer $TOKEN" "https://index.docker.io/v2/${JENKINS_REPO}/manifests/$tag" } get-digest() { local manifest manifest=$(get-manifest "$1") #get-manifest "$1" | jq .config.digest if [ "$debug" = true ]; then >&2 echo "DEBUG: Manifest for $1: $manifest" fi echo "$manifest" | grep -A 10 -o '"config".*' | grep digest | head -1 | cut -d':' -f 2,3 | xargs echo } get-latest-versions() { curl -q -fsSL https://repo.jenkins-ci.org/releases/org/jenkins-ci/main/jenkins-war/maven-metadata.xml | grep '<version>.*</version>' | grep -E -o '[0-9]+(\.[0-9]+)+' | sort-versions | uniq | tail -n 30 } publish() { local version=$1 local variant=$2 local tag="${version}${variant}" local sha local build_opts=(--no-cache --pull) if [ "$dry_run" = true ]; then build_opts=() fi sha=$(curl -q -fsSL "https://repo.jenkins-ci.org/releases/org/jenkins-ci/main/jenkins-war/${version}/jenkins-war-${version}.war.sha256" ) docker build --file "Dockerfile$variant" \ --build-arg "JENKINS_VERSION=$version" \ --build-arg "JENKINS_SHA=$sha" \ --tag "${JENKINS_REPO}:${tag}" \ "${build_opts[@]+"${build_opts[@]}"}" . # " line to fix syntax highlightning if [ ! "$dry_run" = true ]; then docker push "${JENKINS_REPO}:${tag}" else echo "Dry run mode: no docker push" fi } tag-and-push() { local source=$1 local target=$2 local digest_source local digest_target if [ "$debug" = true ]; then >&2 echo "DEBUG: Getting digest for ${source}" fi # if tag doesn't exist yet, ie. dry run if ! digest_source=$(get-digest "${source}"); then echo "Unable to get source digest for '${source} ${digest_source}'" digest_source="" fi if [ "$debug" = true ]; then >&2 echo "DEBUG: Getting digest for ${target}" fi if ! digest_target=$(get-digest "${target}"); then echo "Unable to get target digest for '${target} ${digest_target}'" digest_target="" fi if [ "$digest_source" == "$digest_target" ] && [ -n "${digest_target}" ]; then echo "Images ${source} [$digest_source] and ${target} [$digest_target] are already the same, not updating tags" else echo "Creating tag ${target} pointing to ${source}" docker-tag "${source}" "${DOCKERHUB_ORGANISATION}" "${target}" destination="${REPO:-${JENKINS_REPO}}:${target}" if [ ! "$dry_run" = true ]; then echo "Pushing ${destination}" docker push "${destination}" else echo "Would push ${destination}" fi fi } publish-latest() { local version=$1 local variant=$2 echo "publishing latest: $version$variant" # push latest (for master) or the name of the branch (for other branches) if [ -z "${variant}" ]; then tag-and-push "${version}${variant}" "latest" else tag-and-push "${version}${variant}" "${variant#-}" fi } publish-lts() { local version=$1 local variant=$2 tag-and-push "${version}${variant}" "lts${variant}" tag-and-push "${version}${variant}" "${version}-lts${variant}" } # Process arguments dry_run=false debug=false variant="" start_after="1.0" # By default, we will publish anything missing (only the last 20 actually) while [[ $# -gt 0 ]]; do key="$1" case $key in -n) dry_run=true ;; -d) debug=true ;; -v|--variant) variant="-"$2 shift ;; --start-after) start_after=$2 shift ;; *) echo "Unknown option: $key" return 1 ;; esac shift done if [ "$dry_run" = true ]; then echo "Dry run, will not publish images" fi TOKEN=$(login-token) lts_version="" version="" for version in $(get-latest-versions); do if is-published "$version$variant"; then echo "Tag is already published: $version$variant" else echo "$version$variant not published yet" if versionLT "$start_after" "$version"; then # if start_after < version echo "Version $version higher than $start_after: publishing $version$variant" publish "$version" "$variant" else echo "Version $version lower or equal to $start_after, no publishing (variant=$variant)." fi fi # Update lts tag (if we have an LTS version depending on $start_after) if versionLT "$start_after" "$version" && [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then lts_version="${version}" fi done publish-latest "${version}" "${variant}" if [ -n "${lts_version}" ]; then publish-lts "${lts_version}" "${variant}" else echo "No LTS publishing" fi
<reponame>jeckhummer/wf-constructor import React from 'react'; import {connect} from 'react-redux'; import {EditorModal} from "../../dumb/editor/EditorModal"; import {getTaskEditorFormValidationResult, getTaskEditorState} from "../../selectors/ui"; import {closeTaskEditor, saveTaskEditorTask, openTaskEditorTab} from "../../actions/taskEditor"; import {TaskEditorContent} from "./TaskEditorContent"; import {TASK_EDITOR_TABS} from "../../reducers/ui/taskEditor"; const mapStateToProps = (state) => { const { isNameValid, isPhaseValid, isTeamValid, result } = getTaskEditorFormValidationResult(state); const errorMessage = ` ${!isNameValid ? 'Name shouldn\'t be empty. ' : ''} ${[ !isPhaseValid ? 'Phase' : null, !isTeamValid ? 'Team' : null, ].filter(x => x != null) .join(' and ')} ${!isPhaseValid || !isTeamValid ? 'should be selected.' : ''} `; const {isNewTask, task} = getTaskEditorState(state); const header = isNewTask ? 'New task' : task.name; const {activeTab} = getTaskEditorState(state); const tabs = [ { name: 'General', value: TASK_EDITOR_TABS.GENERAL, active: activeTab === TASK_EDITOR_TABS.GENERAL }, { name: 'Custom fields', value: TASK_EDITOR_TABS.CUSTOM_FIELDS, active: activeTab === TASK_EDITOR_TABS.CUSTOM_FIELDS }, { name: 'Notifications', value: TASK_EDITOR_TABS.NOTIFICATIONS, active: activeTab === TASK_EDITOR_TABS.NOTIFICATIONS, }, ]; return { isActive: true, header: header, content: <TaskEditorContent/>, saveButtonDisabled: !result, errorMessage, tabs }; }; const mapDispatchToProps = (dispatch) => { return { onSaveClick: () => { dispatch(saveTaskEditorTask()); dispatch(closeTaskEditor()); }, onCloseClick: () => dispatch(closeTaskEditor()), onTabClick: (_, {value}) => dispatch(openTaskEditorTab(value)) }; }; export const TaskEditor = connect( mapStateToProps, mapDispatchToProps )(EditorModal);
package br.com.pucrs.io; import br.com.pucrs.collections.GeneralTree; import br.com.pucrs.model.ContentBook; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Scanner; public class BookReader { private ContentBook capituloAtual; private ContentBook secaoAtual; private ContentBook subSecaoAtual; private int nroCapitulos; private int nroSecoes; private int nroSubSecoes; private int nroParagrafos; public BookReader() { capituloAtual = null; secaoAtual = null; subSecaoAtual = null; nroCapitulos = 0; nroSecoes = 0; nroSubSecoes = 0; nroParagrafos = 0; } public GeneralTree<ContentBook> readFile(Path path) throws IOException { GeneralTree<ContentBook> tree = new GeneralTree<>(); try (Scanner scanner = new Scanner(Files.newBufferedReader(path))) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); String tipo = line.substring(0, 2).trim(); ContentBook page = new ContentBook(line.substring(2), tipo); switch (tipo) { case "L": tree.add(page, null); break; case "C": addChapter(tree, page); break; case "S": addSection(tree, page); break; case "SS": addSubSection(tree, page); break; case "P": addParagraph(tree, page); break; default: //não faz nada break; } } } catch (IOException e) { throw new IOException(e.getMessage(), e); } return tree; } public void clear() { capituloAtual = null; secaoAtual = null; subSecaoAtual = null; nroCapitulos = 0; nroSecoes = 0; nroSubSecoes = 0; nroParagrafos = 0; } private void addSubSection(GeneralTree<ContentBook> tree, ContentBook page) { subSecaoAtual = page; tree.add(subSecaoAtual, secaoAtual); nroSubSecoes++; } private void addParagraph(GeneralTree<ContentBook> tree, ContentBook page) { if (subSecaoAtual != null) { tree.add(page, subSecaoAtual); } else if (secaoAtual != null) { tree.add(page, secaoAtual); } else { tree.add(page, capituloAtual); } nroParagrafos++; } private void addSection(GeneralTree<ContentBook> tree, ContentBook page) { subSecaoAtual = null; secaoAtual = page; tree.add(secaoAtual, capituloAtual); nroSecoes++; } private void addChapter(GeneralTree<ContentBook> tree, ContentBook line) { if (capituloAtual != null) { secaoAtual = null; subSecaoAtual = null; } capituloAtual = line; tree.add(line, tree.getRoot()); nroCapitulos++; } public int getNroCapitulos() { return nroCapitulos; } public int getNroSecoes() { return nroSecoes; } public int getNroSubSecoes() { return nroSubSecoes; } public int getNroParagrafos() { return nroParagrafos; } }
class MiniMQ { constructor () { this.queue = [] this.closeQueue() this.handlerFunction = (el, prm, resolve, reject) => {} } openQueue () { while (this.queue.length !== 0) { let currentEl = this.queue.shift() this.handlerFunction(currentEl.el, currentEl.prm, currentEl.resolveInstance, currentEl.rejectInstance) } this.isQueueOpen = true } closeQueue () { this.isQueueOpen = false } addElement (el) { let resolveInstance let rejectInstance let prm = new Promise((resolve, reject) => { resolveInstance = resolve rejectInstance = reject }) if (this.isQueueOpen) { this.handlerFunction(el, prm, resolveInstance, rejectInstance) } else { this.queue.push({ el: el, prm: prm, resolveInstance: resolveInstance, rejectInstance: rejectInstance }) } return prm } } module.exports = MiniMQ
// the constant contains the order of precedence. // the higher the value, higher the precedence. module.exports = grammar({ name: 'trafficscript', // inline: $ => [ // $._string_content, // //$.member_expression, // //$._call_signature, // //$.statement, // $._expressions, // $.semi_colon, // $.identifier, // ], conflicts: _$ => [ ], precedences: $ => [ [ 'string', 'comments', // comments over anything, except in strings 'member', // . member access 'call', // function call 'postfix_update_exp', // i++ i-- operator 'prefix_update_exp', // ++i --i operator 'unary_not', // unary + - ! - 'binary_times', // * / % operator 'binary_plus', // + = . operator 'binary_shift',// << >> 'binary_relation',// < > <= >= 'binary_equality', // == != 'bitwise_and', // & 'bitwise_xor', // ^ 'bitwise_or', // | 'logical_and', // && 'logical_or', // || 'ternary_operator', // ?: 'assignment_operators', // = += etc $.primary_expression, $.statement_block, 'hash' ], ['declaration', 'literal'], ['declaration', $.expression], ['member', $.expression], ], extras: $ => [ $.comments, /[\s\uFEFF\u2060\u200B\u00A0]/, // any kind of whitespace ], supertypes: $ => [ $.statement, $.declaration, $.expression, $.primary_expression, ], externals: $ => [ $._newline, $._string_start, $._string_content, $._string_end, ], word: $ => $.identifier, rules: { source_file: $ => repeat($.statement), // // Statements // statement: $ => choice( $.import_statement, $.expression_statement, $.declaration, $.statement_block, $.if_statement, $.switch_statement, $.for_statement, $.for_each_statement, $.while_statement, $.do_statement, $.break_statement, $.continue_statement, $.return_statement, $.empty_statement, ), expression_statement: $ => seq($.expression, $.semi_colon), // // Import declarations // //import: _$ => token('import'), import_statement: $ => seq( 'import', field('source', choice($.identifier, $.string)), optional(seq( 'as', field('alias', $.identifier), )), $.semi_colon, ), else_clause: $ => seq('else', $.statement), if_statement: $ => prec.right(seq( 'if', field('condition', $.parenthesized_expression), field('consequence', $.statement), optional(field('alternative', $.else_clause)) )), switch_statement: $ => seq( 'switch', field('value', seq( '(', $.expression, optional(seq(',', $.member_expression)), ')' )), field('body', $.switch_body) ), switch_body: $ => seq( '{', repeat($.switch_case), optional($.switch_default), '}' ), switch_case: $ => seq( 'case', field('value', $._expressions), ':', repeat($.statement), ), switch_default: $ => seq( 'default', ':', repeat($.statement), ), empty_statement: _$ => ';', break_statement: $ => seq('break', $.semi_colon), continue_statement: $ => seq( 'continue', $.semi_colon ), while_statement: $ => seq( 'while', field('condition', $.parenthesized_expression), field('body', $.statement), ), // the C - style for loop for_statement: $ => seq( 'for', $._for_parenthesize, field('body', $.statement_block), ), _for_parenthesize: $ => seq( '(', optional(field('initializer', $.expression)), $.semi_colon, optional(field('condition', $.expression)), $.semi_colon, optional(field('incrementor', $.expression)), ')' ), for_each_statement: $ => seq( 'foreach', $._foreach_parenthesize, field('body', $.statement_block), ), _foreach_parenthesize: $ => seq( '(', field('left', $.scalar_identifier), 'in', field('right', $.expression), ')', ), do_statement: $ => seq( 'do', field('body', $.statement), 'while', field('condition', $.parenthesized_expression), $.semi_colon ), declaration: $ => choice( $.function_declaration, $.variable_declaration, ), variable_declaration: $ => prec('declaration', seq( commaSep1($.assignment_expression), $.semi_colon )), _call_signature: $ => field('parameters', $.formal_parameters), function_declaration: $ => prec.left('declaration', seq( 'sub', field('name', $.identifier), $._call_signature, field('body', $.statement_block) )), formal_parameters: $ => seq( '(', prec.left('call', optional(seq( commaSep1($.scalar_identifier), optional(',') ))), ')' ), statement_block: $ => seq( '{', optional(repeat($.statement)), '}' ), parenthesized_expression: $ => seq( '(', prec.left($.expression), ')' ), return_statement: $ => seq( 'return', optional($.expression), $.semi_colon ), expression: $ => choice( $.primary_expression, $.assignment_expression, // right $.unary_expression, // right $.binary_expression, // left $.ternary_expression, // right $.update_expression, // prefix: right, postfix: none ), primary_expression: $ => choice( $.subscript_expression, $.parenthesized_expression, $.member_expression, $.scalar_identifier, $.global_identifier, $.number, $.string, $.true, $.false, $.hash, $.array, $.call_expression, ), // begin of operators binary_expression: $ => choice( ...[ ['&&', 'logical_and'], ['||', 'logical_or'], ['>>', 'binary_shift'], //['>>>', 'binary_shift'], ['<<', 'binary_shift'], ['&', 'bitwise_and'], ['^', 'bitwise_xor'], ['|', 'bitwise_or'], ['+', 'binary_plus'], ['.', 'binary_plus'], ['-', 'binary_plus'], ['*', 'binary_times'], ['/', 'binary_times'], ['%', 'binary_times'], ['<', 'binary_relation'], ['<=', 'binary_relation'], ['==', 'binary_equality'], ['!=', 'binary_equality'], ['>=', 'binary_relation'], ['>', 'binary_relation'], ].map(([operator, precedence]) => prec.left(precedence, seq( field('left', $.expression), field('operator', operator), field('right', $.expression) )) ) ), ternary_expression: $ => prec.right("ternary_operator", seq( field('condition', $.expression), field('operator', '?'), field('true', $.expression), field('operator', ':'), field('false', $.expression), )), // no associativity // auto increment and auto decrement update_expression: $ => choice( prec.right('prefix_update_exp', seq( field('operator', choice('++', '--')), field('variable', $.expression), )), prec('postfix_update_exp', seq( field('variable', $.expression), field('operator', choice('++', '--')), )), ), unary_expression: $ => choice(...[ ['!', 'unary_not'], ['~', 'unary_not'], ['-', 'unary_not'], //['+', 'unary_not'], ].map(([operator, precedence]) => prec.right(precedence, seq( field('operator', operator), field('argument', $.expression) )) )), assignment_expression: $ => choice( ...[ '=', '+=', '*=', '&=', '<<=', '-=', '/=', '|=', '>>=', '.=', '%=', '^=', ].map((operator) => prec.right('assignment_operators', seq( field('left', choice( $.subscript_expression, $.scalar_identifier, $.global_identifier )), field('operator', operator), field('right', choice($.expression, $.member_expression)), ), )) ), // end of operators call_expression: $ => prec.left('call', seq( field('function', $.member_expression), field('arguments', $.arguments) )), member_expression: $ => seq( field('module', optional(repeat(seq( $.identifier, token.immediate('.'), )))), field('property', alias($.identifier, $.property_identifier)) ), subscript_expression: $ => prec.left('member', seq( field('object', choice($.scalar_identifier, $.primary_expression)), '[', field('index', $._expressions), ']' )), arguments: $ => prec.left('call', seq( '(', commaSep($.expression), ')' )), _expressions: $ => choice( $.expression, $.sequence_expression ), sequence_expression: $ => seq( field('left', $.expression), ',', field('right', choice($.sequence_expression, $.expression)) ), number: _$ => { const hex_literal = seq( choice('0x', '0X'), /[\da-fA-F](_?[\da-fA-F])*/ ) const decimal_digits = /\d(_?\d)*/ const signed_integer = seq(optional(choice('-', '+')), decimal_digits) const exponent_part = seq(choice('e', 'E'), signed_integer) const binary_literal = seq(choice('0b', '0B'), /[0-1](_?[0-1])*/) const octal_literal = seq(choice('0o', '0O'), /[0-7](_?[0-7])*/) const bigint_literal = seq(choice(hex_literal, binary_literal, octal_literal, decimal_digits), 'n') const decimal_integer_literal = choice( '0', seq(optional('0'), /[1-9]/, optional(seq(optional('_'), decimal_digits))) ) const decimal_literal = choice( seq(decimal_integer_literal, '.', optional(decimal_digits), optional(exponent_part)), seq('.', decimal_digits, optional(exponent_part)), seq(decimal_integer_literal, exponent_part), seq(decimal_digits), ) return token(choice( hex_literal, decimal_literal, binary_literal, octal_literal, bigint_literal, )) }, // the strings string: $ => seq( alias($._string_start, '"'), repeat(choice($.escape_sequence, $._not_escape_sequence, $._string_content)), alias($._string_end, '"') ), escape_sequence: _$ => token(prec(1, seq( '\\', choice( /u[a-fA-F\d]{4}/, /U[a-fA-F\d]{8}/, /x[a-fA-F\d]{2}/, /\d{3}/, /\r?\n/, /['"abfrntv\\]/, ) ))), _not_escape_sequence: _$ => '\\', scalar_identifier: _$ => { const alpha = /[^\x00-\x1F\s0-9:;`"'@#.,|^&<=>+\-*/\\%?!~()\[\]{}\uFEFF\u2060\u200B\u00A0]|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\}/ const alphanumeric = /[^\x00-\x1F\s:;`"'@#.,|^&<=>+\-*/\\%?!~()\[\]{}\uFEFF\u2060\u200B\u00A0]|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\}/ return token(seq('$', alpha, repeat(alphanumeric))) }, global_identifier: _$ => /\$[1-9]/, // $1 - $9 global variables identifier: _$ => { const alpha = /[^\x00-\x1F\s0-9:;`"'@#.,|^&<=>+\-*/\\%?!~()\[\]{}\uFEFF\u2060\u200B\u00A0]|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\}/ const alphanumeric = /[^\x00-\x1F\s:;`"'@#.,|^&<=>+\-*/\\%?!~()\[\]{}\uFEFF\u2060\u200B\u00A0]|\\u[0-9a-fA-F]{4}|\\u\{[0-9a-fA-F]+\}/ return token(seq(alpha, repeat(alphanumeric))) }, semi_colon: _$ => ';', not_escape_sequence: _$ => '\\', true: _$ => 'true', false: _$ => 'false', _property_name: $ => choice( alias($.scalar_identifier, $.property_identifier), $.string, $.number, ), hash: $ => prec('hash', seq( '[', commaSep($.pair), ']' )), array: $ => seq( '[', commaSep1($.expression), ']' ), pair: $ => seq( field('key', $._property_name), '=>', field('value', $.expression) ), // some key words comments: _$ => token(prec("comments", choice( /#.*/, // single line comment ))), } }); /** * repeats the rule comma separated, like * rule, rule * example: (a, b); * using it in the above. * @param {*} rule */ function commaSep(rule) { return optional(commaSep1(rule)); } /** * repeats the rule comma separated at least once, like * rule * rule, rule * example: (a, b); * using it in the above. * @param {*} rule */ function commaSep1(rule) { return seq(rule, repeat(seq(',', rule))); }
function getIndicesOfItemWeights(arr, limit) { // use an object to store item weights // along with their 'complement' const o = {}; for (let i = 0; i < arr.length; i++) { const weight = arr[i]; // check the object to see we have the // complement of the current weight const complementIndex = o[limit - weight]; // if we do, then we're done! if (complementIndex !== undefined) { return [i, complementIndex]; } else { // otherwise, store the weight with its index o[weight] = i; } } return []; } /* Some simple console.log tests */ console.log(getIndicesOfItemWeights( [4, 6, 10, 15, 16], 21 )); // should print [3, 1] console.log(getIndicesOfItemWeights( [4, 4], 8 )); // should print [1, 0] console.log(getIndicesOfItemWeights( [12, 6, 7, 14, 19, 3, 0, 25, 40], 7 )); // should print [6, 2] console.log(getIndicesOfItemWeights( [9], 9 )); // should print []
<reponame>vimalkumarvelayudhan/galaxy from galaxy import exceptions from abc import ABCMeta from abc import abstractmethod from galaxy import model import logging log = logging.getLogger( __name__ ) class DatasetCollectionType(object): __metaclass__ = ABCMeta @abstractmethod def generate_elements( self, dataset_instances ): """ Generate DatasetCollectionElements with corresponding to the supplied dataset instances or throw exception if this is not a valid collection of the specified type. """ class BaseDatasetCollectionType( DatasetCollectionType ): def _validation_failed( self, message ): raise exceptions.ObjectAttributeInvalidException( message )
<filename>star_tracker/views/widget_view.py from PySide2.QtWidgets import* from matplotlib.backends.backend_qt5agg import FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure from numpy import rad2deg from modules.basic import deg2rad, spherical2catersian #my models includes from model.main_model import * try: from modules.canvas_2D import * from modules.canvas_3D import * except ImportError: from star_tracker.modules.canvas_2D import * from star_tracker.modules.canvas_3D import * class Widget(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self._vertical_layout = QVBoxLayout() self._graticule_plots = [] self._camera_position = [] self.set_2D_view() self.set_3D_view() self.set_view(ViewMode.VIEW2D) self.setLayout(self._vertical_layout) self._graticule_color = "yellow" def set_2D_view(self): self._canvas_2D = Canvas2D(Figure()) self._toolbar_2D = NavigationToolbar(self._canvas_2D, self) self._vertical_layout.addWidget(self._toolbar_2D) self._vertical_layout.addWidget(self._canvas_2D) self._canvas_2D.draw() def set_3D_view(self): self._canvas_3D = Canvas3D(Figure()) self._toolbar_3D = NavigationToolbar(self._canvas_3D, self) self._vertical_layout.addWidget(self._toolbar_3D) self._vertical_layout.addWidget(self._canvas_3D) self._canvas_3D.draw() def set_view(self, mode): if mode == ViewMode.VIEW2D: self._canvas_2D.setVisible(True) self._toolbar_2D.setVisible(True) self._canvas_3D.setVisible(False) self._toolbar_3D.setVisible(False) else: self._canvas_2D.setVisible(False) self._toolbar_2D.setVisible(False) self._canvas_3D.setVisible(True) self._toolbar_3D.setVisible(True) @property def model(self): return self._model @model.setter def model(self, value : MainModel): self._model = value #events signal self._model.view_plot_mode_changed.connect(self.set_view) self._model.stars_changed.connect(self.plot_stars) self._model.camera_auxiliary_view_changed.connect(self.plot_camera) self._model.graticule_view_changed.connect(self.plotGraticule) def plotGraticule(self, show): self._canvas_2D.showGraticule(show) self._canvas_2D.draw() self._canvas_3D.showGraticule(show) self._canvas_3D.draw() def plot_stars(self, stars, show): self._canvas_2D.stars = stars self._canvas_2D.show_stars(show) self._canvas_2D.draw() self._canvas_3D.stars = stars self._canvas_3D.show_stars(show) self._canvas_3D.draw() def plot_camera(self, camera_3D, camera_2D, show): #camera_3D = {'3D':camera['3D'], '3D_pos': camera['3D_pos']} #camera_2D = camera['2D'] self._canvas_2D.camera = camera_2D self._canvas_2D.show_camera(show) self._canvas_2D.draw() self._canvas_3D.camera = camera_3D self._canvas_3D.show_camera(show) self._canvas_3D.draw()
import { Component, OnInit, ElementRef, ViewChild, Input, NgZone } from "@angular/core"; import { MapboxViewApi, Viewport as MapboxViewport, MapboxMarker } from "nativescript-mapbox"; import { RestApiService } from "../shared/rest-api.service"; import { MultiSelect, AShowType } from 'nativescript-multi-select'; import { MSOption } from 'nativescript-multi-select'; @Component({ selector: "Maps", templateUrl: "./maps.component.html", styleUrls: ["./maps.component.css"] }) export class MapsComponent implements OnInit { @Input() BackgroundColor: string = "#E6A938"; private map: MapboxViewApi; constructor(private restApi: RestApiService, private zone: NgZone) { this._MSelect = new MultiSelect(); this.predefinedItems = ["moi-a", "moi-b"]; } amenities = ['pharmacies', 'banks', 'supermarkets', 'doctors', 'police', 'taxi']; amentitiesDescription = ['Φαρμακεία', 'Τράπεζες', 'Super Markets', 'Ιατροί', 'Αστυνομικό τμήμα', 'Ταξί']; private _MSelect: MultiSelect; private predefinedItems: Array<any>; public selectedItems: Array<any>; ngOnInit(): void { this.publicpredifefilterList(); } onMapReady(args): void { this.map = args.map; this.restApi.getCityPolygon().subscribe(s => { //this.map.addPolygon(s); this.map.setViewport({ bounds: { north: 37.970557, east: 23.6249957, south: 38.0036854, west: 23.6648962 }, animated: true }); }); this.addSelectedMarkers(); } addSelectedMarkers() { this.restApi.getCityAmenities(this.predefinedItems).subscribe(s => { s.forEach(item => { this.map.addMarkers(item); }); }); } public filterList(): any[] { let result = []; for (let index = 0; index < this.amentitiesDescription.length; index++) { const element = { name: this.amentitiesDescription[index], value: this.amenities[index] }; result.push(element); } return result; } publicpredifefilterList() { this.predefinedItems = []; for (let index = 0; index < this.amentitiesDescription.length; index++) { const element = { name: this.amentitiesDescription[index], value: this.amenities[index] }; this.predefinedItems.push(this.amenities[index]); } } public onSelectTapped(): void { const options: MSOption = { title: "Επιλογή", confirmButtonText: 'Επιλογή', cancelButtonText: 'Ακύρωση', items: this.filterList(), selectedItems: this.predefinedItems, bindValue: 'value', displayLabel: 'name', onConfirm: selectedItems => { this.zone.run(() => { this.selectedItems = selectedItems; this.predefinedItems = selectedItems; this.map.removeMarkers(); this.addSelectedMarkers(); }) }, onItemSelected: selectedItem => { console.log("SELECTED ITEM => ", selectedItem); }, onCancel: () => { console.log('CANCEL'); }, android: { titleSize: 25, cancelButtonTextColor: "#252323", confirmButtonTextColor: "#70798C", }, ios: { cancelButtonBgColor: "#252323", confirmButtonBgColor: "#70798C", cancelButtonTextColor: "#ffffff", confirmButtonTextColor: "#ffffff", showType: AShowType.TypeBounceIn } }; this._MSelect.show(options); } }
<filename>packages/@glimmer/ssr/src/serializing-builder.ts import { DOMBuilder } from "@glimmer/application"; import { serializeBuilder } from "@glimmer/node"; import { Environment, ElementBuilder } from "@glimmer/interfaces"; export default class SerializingBuilder extends DOMBuilder { getBuilder(env: Environment): ElementBuilder { return serializeBuilder(env, this.cursor); } }
<reponame>johnwanjohi/ngx-awesome-popup<gh_stars>0 import { Observable } from 'rxjs'; import { IToastNotificationPublicResponse } from './interfaces'; import * as i0 from "@angular/core"; export declare class ToastEvokeService { #private; success(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; info(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; warning(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; danger(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; customOne(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; customTwo(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; customThree(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; customFour(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; customFive(title: string, message: string, confirmLabel?: string, declineLabel?: string): Observable<IToastNotificationPublicResponse>; static ɵfac: i0.ɵɵFactoryDeclaration<ToastEvokeService, never>; static ɵprov: i0.ɵɵInjectableDeclaration<ToastEvokeService>; }
import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Path("/users") public class UserResource { private static Map<Integer, User> users = new ConcurrentHashMap<>(); private static int currentId = 0; @Context UriInfo uriInfo; @GET @Path("{id}") @Produces("application/json") public User getUser(@PathParam("id") int id) { User user = users.get(id); if (user == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return user; } @POST @Produces("application/json") public User createUser(User user) { user.setId(++currentId); users.put(user.getId(), user); return user; } @PUT @Path("{id}") @Produces("application/json") public User updateUser(@PathParam("id") int id, User user) { if (user == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } User existingUser = users.get(id); if (existingUser == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } existingUser.setName(user.getName()); users.put(id, existingUser); return user; } @DELETE @Path("{id}") public void deleteUser(@PathParam("id") int id) { users.remove(id); } }
# template cmd echo abc 2>&- export VAR=value || setenv VAR value echo def cd /tmp pwd echo ghi echo 'zut' > /tmp/history_cat_file cat -e /tmp/history_cat_file rm -f /tmp/history_cat_file echo "test1" \echo "======== EXP ========" !e !ech !echo d !echoo d echo !p !e !ech\ o 'echo' test2 !'ech
<filename>pkg/rewriter/func_concat.go<gh_stars>0 package rewriter func init() { register("concat", funcConcat) register("concat!", must("concat")) } func funcConcat(state *State, args Arguments) (string, error) { result := "" for i := 0; i < len(args); i++ { val, err := args.Evaluate(i, state) if err != nil { return "", err } result += val } return result, nil }
package update import "os/exec" // TODO perhaps make this a parallel thread in the future? func performOSUpdate() error { cmd := exec.Command("/usr/bin/update_engine_client", "-update") return cmd.Run() }
#!/usr/bin/env bash source ~/ENV/bin/activate cd ~/MultiModesPreferenceEstimation python tune_parameters.py --data-dir data/amazon/digital_music/ --save-path amazon/digital_music/tuning_general/mmp-part29.csv --parameters config/amazon/digital_music/mmp-part29.yml
#!/bin/bash set -euo pipefail IFS=$'\n\t' # wait until scm passes all health checks echo "wait until scm passes all health checks" if ! doguctl healthy --wait --timeout 300 scm; then echo "timeout reached by waiting of scm to get healthy" exit 1 fi TRUSTSTORE="${SMEAGOL_HOME}/truststore.jks" create_truststore.sh "${TRUSTSTORE}" > /dev/null # override setting from src/main/resources/application.yml FQDN=$(doguctl config --global fqdn) cat > /app/application.yml <<EOF stage: production server: contextPath: /smeagol homeDirectory: ${SMEAGOL_HOME} scm: url: https://${FQDN}/scm cas: url: https://${FQDN}/cas serviceUrl: https://${FQDN}/smeagol EOF java -Djava.awt.headless=true \ -Djava.net.preferIPv4Stack=true \ -Djavax.net.ssl.trustStore="${TRUSTSTORE}" \ -Djavax.net.ssl.trustStorePassword=changeit \ -jar /app/smeagol.war
/** @format */ /* issueChallenge() 1. Check if `id` == Okta UserID or Email => yes 1. getUser to see if factor already exists. 2. if Okta factor exists, USE IT => no 1. Create Okta User */
import org.apache.ignite.IgniteException; // Custom exception class for handling query memory quota exceeded scenario class QueryQuotaExceededException extends IgniteException { public QueryQuotaExceededException(String message) { super(message); } } public class CustomExceptionHandling { private static final String QUERY_2048_TO_4096 = "SELECT * FROM table_name WHERE column_name BETWEEN 2048 AND 4096"; public static void main(String[] args) { try { executeQuery(QUERY_2048_TO_4096); } catch (QueryQuotaExceededException e) { System.out.println("Custom exception handling: " + e.getMessage()); // Additional handling logic can be added here } } // Method to execute SQL query and handle memory quota exceeded scenario private static void executeQuery(String query) throws QueryQuotaExceededException { try { // Execute the SQL query against the Ignite data grid // stmt.execute(query); // Simulating memory quota exceeded scenario throw new QueryQuotaExceededException("SQL query ran out of memory: Query quota was exceeded."); } catch (IgniteException e) { // Re-throw the exception as QueryQuotaExceededException throw new QueryQuotaExceededException(e.getMessage()); } } }
<gh_stars>0 package util; import main.Game; public final class Factors { public static final int factorX(double percent){ return (int)(percent * (Game.game.getWidth() / 100.0)); } public static final int factorY(double percent){ return (int)(percent * (Game.game.getHeight() / 100.0)); } }
<gh_stars>0 // Copyright 2011 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.integration.app1.pages; import org.apache.tapestry5.Link; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.PageRenderLinkSource; import org.apache.tapestry5.services.Request; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Page for testing the query parameter component parameter on all of the framework-supplied link components * (page, action, event) */ public class LinkQueryParameters { @Property private String paramName; @Inject private Request request; @Inject private PageRenderLinkSource linkSource; public Map<String,?> getEmptyParameters() { return Collections.emptyMap(); } public Map<String, ?> getNonEmptyParameters() { Map<String, Object> map = new HashMap<String, Object>(); map.put("param1","value1"); map.put("param2", 10); return map; } public Link onAction() { return buildLink(); } public Link onParameterCheck() { return buildLink(); } //small hack for test simplicity: we'll generate a new page link, add any parameters we find in the current //request, and redirect to that instead of the default. private Link buildLink() { Link l = linkSource.createPageRenderLink(LinkQueryParameters.class); for(String param : request.getParameterNames()) { l.addParameter(param,request.getParameter(param)); } return l; } public boolean isHasParameters() { return !request.getParameterNames().isEmpty(); } public List<String> getParameters() { return request.getParameterNames(); } public String getParamVal() { return request.getParameter(paramName); } }
<gh_stars>0 import firebase from "firebase/app"; import "firebase/auth"; import "firebase/firestore"; const firebaseConfig = { apiKey: "<KEY>", authDomain: "clone-4dabc.firebaseapp.com", projectId: "clone-4dabc", storageBucket: "clone-4dabc.appspot.com", messagingSenderId: "708109777714", appId: "1:708109777714:web:ae8989a29a3f971f47b52b", }; const firebaseApp = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app(); const db = firebaseApp.firestore(); const auth = firebaseApp.auth(); const Provider = new firebase.auth.GoogleAuthProvider(); export { db, auth, Provider };
const router = require('express').Router() const {User, Order, Product, ProductOrder} = require('../db/models') const {adminOnly, currentUserOnly} = require('../utils') // get all users for admin settings router.get('/', adminOnly, async (req, res, next) => { try { const users = await User.findAll({ // explicitly select only the id and email fields - even though // users’ passwords are encrypted, it won’t help if we just // send everything to anyone who asks! attributes: ['id', 'email'] }) res.json(users) } catch (err) { next(err) } }) // get a single user router.get('/:id', adminOnly, async (req, res, next) => { try { const singleUser = await User.findByPk(req.params.id) res.json(singleUser) } catch (error) { next(error) } }) // delete a user for admin settings router.delete('/:id', adminOnly, async (req, res, next) => { try { const deletedUser = await User.destroy({ where: { id: req.params.id } }) res.status(204).send(deletedUser) } catch (error) { next(error) } }) // get a user's cart router.get('/cart/:userId', currentUserOnly, async (req, res, next) => { try { const cartItems = await Product.findAll({ include: { model: Order, where: { userId: req.params.userId, status: 'cart' } } }) res.json(cartItems) } catch (error) { next(error) } }) // add a product to a user's cart router.put('/cart/:userId', currentUserOnly, async (req, res, next) => { try { // find the product in the db const product = await Product.findByPk(req.body.id) // find the user cart order const currentOrder = await Order.findOne({ where: { userId: req.params.userId, status: 'cart' } }) // if the cart does not exist yet, create the cart if (!currentOrder) { const currentOrder = await Order.create({ userId: req.params.userId, status: 'cart' }) await ProductOrder.create({ orderId: currentOrder.id, productId: req.body.id, quantity: 1, purchasePrice: product.price }) } // if the cart does exist, add the product to the cart if (currentOrder) { await ProductOrder.create({ orderId: currentOrder.id, productId: req.body.id, quantity: 1, purchasePrice: product.price }) } // retrieve the newly added item const newItem = await ProductOrder.findOne({ where: { productId: product.id, orderId: currentOrder.id } }) res.json(newItem) } catch (error) { next(error) } }) //delete item from user's cart router.delete( '/cart/:userId/:productId', currentUserOnly, async (req, res, next) => { try { const removedProduct = await Product.findByPk(req.params.productId) const currentOrder = await Order.findOne({ where: {userId: req.params.userId, status: 'cart'} }) await currentOrder.removeProduct(removedProduct) res.sendStatus(204) } catch (error) { next(error) } } ) // route to checkout cart router.put('/checkout/:userId/', currentUserOnly, async (req, res, next) => { try { const order = await Order.findOne({ where: {userId: req.params.userId, status: 'cart'} }) order.status = 'purchased' await order.save() } catch (error) { next(error) } }) module.exports = router
package org.museautomation.ui.valuesource.list; import org.museautomation.core.values.*; import org.museautomation.ui.extend.actions.*; /** * @author <NAME> (see LICENSE.txt for license details) */ public class RemoveIndexedSubsourceAction extends UndoableAction { public RemoveIndexedSubsourceAction(ContainsIndexedSources target_source, int index) { _target_source = target_source; _index = index; } @Override protected boolean executeImplementation() { _removed_source = _target_source.removeSource(_index); return true; } @Override protected boolean undoImplementation() { _target_source.addSource(_index, _removed_source); return true; } private ContainsIndexedSources _target_source; private int _index; private ValueSourceConfiguration _removed_source; }
<reponame>sfc-gh-kmaurya/SnowAlert<filename>src/runners/handlers/pd.py """SnowAlert Pager Duty handler usage: OBJECT_CONSTRUCT( 'type', 'pd' ) in alert query handlers column """ import os from pdpyras import EventsAPISession, PDClientError from runners.helpers import log from runners.helpers import vault # default value (input severity is replaced for it if not in the list) should be the last in the list severityDictionary = ['critical', 'error', 'warning', 'info', 'unknown'] # used for testing, should probably go into a test, keeping here for now testAlert = { 'TITLE': 'test SnowAlert', 'DETECTOR': 'SnowAlert', 'SEVERITY': 'info', 'DETECTOR': 'SnowAlert', 'QUERY_ID': 'CT_DELETE_LOG_GROUP', 'DESCRIPTION': 'S: Subject Verb Predicate at 2020-03-08 03:29:50.987 Z', } def handle( alert, summary=None, source=None, dedup_key=None, severity=None, custom_details=None, pd_api_token=None, ): if 'PD_API_TOKEN' not in os.environ and pd_api_token is None: log.error(f"No PD_API_TOKEN in env, skipping handler.") return None pd_token_ct = pd_api_token or os.environ['PD_API_TOKEN'] pd_token = vault.decrypt_if_encrypted(pd_token_ct) pds = EventsAPISession(pd_token) summary = summary or alert['DESCRIPTION'] source = source or alert['DETECTOR'] severity = severity or alert['SEVERITY'] if severity not in severityDictionary: log.warn( f"Set severity to {severityDictionary[-1]}, " f"supplied {severity} is not in allowed values: {severityDictionary}" ) severity = severityDictionary[-1] custom_details = custom_details or alert try: response = pds.trigger( summary, source, dedup_key, severity, custom_details=alert ) log.info(f"triggered PagerDuty alert \"{summary}\" at severity {severity}") return response except PDClientError as e: log.error(f"Cannot trigger PagerDuty alert: {e.msg}") return None
# X11 package TERMUX_PKG_HOMEPAGE=https://xorg.freedesktop.org/ TERMUX_PKG_DESCRIPTION="X11 toolkit intrinsics library" TERMUX_PKG_LICENSE="MIT" TERMUX_PKG_MAINTAINER="@termux" TERMUX_PKG_VERSION=1.2.1 TERMUX_PKG_SRCURL=https://xorg.freedesktop.org/releases/individual/lib/libXt-${TERMUX_PKG_VERSION}.tar.bz2 TERMUX_PKG_SHA256=679cc08f1646dbd27f5e48ffe8dd49406102937109130caab02ca32c083a3d60 TERMUX_PKG_DEPENDS="libice, libsm, libuuid, libx11, libxau, libxcb, libxdmcp" TERMUX_PKG_BUILD_DEPENDS="xorg-util-macros" TERMUX_PKG_EXTRA_CONFIGURE_ARGS="--enable-malloc0returnsnull" termux_step_pre_configure() { export CFLAGS_FOR_BUILD=" " export LDFLAGS_FOR_BUILD=" " }
<filename>src/build/clean.js const path = require('path'); const rimraf = require('rimraf'); rimraf.sync(path.resolve(__dirname, '../dist')); rimraf.sync(path.resolve(__dirname, '../frameworks')); rimraf.sync(path.resolve(__dirname, '../platforms')); rimraf.sync(path.resolve(__dirname, '../plugins'));
import string def remove_punctuation(text): punctuations = string.punctuation return ''.join([char for char in text if char not in punctuations])
<reponame>MootezSaaD/LibMS-frontend import * as React from 'react'; import { RegistrationForm } from './RegistrationForm'; import { useYupValidationResolver } from 'app/services/validation/resolvers/Resolver'; import { RegisterValidationScheme } from 'app/services/validation/schemes/Register'; import { useForm } from 'react-hook-form'; import { Button, Col, Form } from 'react-bootstrap'; export function RegisterForm() { const validEmailDomains = ['smu.tn', 'msb.tn', 'medtech.tn', 'lci.tn']; const onSubmit = (data: RegistrationForm): void => console.info(JSON.stringify(data)); const resolver = useYupValidationResolver(RegisterValidationScheme); const { register, handleSubmit, formState: { errors }, } = useForm<any>({ resolver, }); return ( <Form className="mb-5" data-testid="registration-form" onSubmit={handleSubmit(onSubmit)} > <Form.Group> <Form.Label htmlFor="firstName">First name</Form.Label> <Form.Control type="text" className="w-75" id="firstName" aria-label="firstName" {...register('firstName')} aria-describedby="firstNameHelp" isInvalid={!!errors.firstName} /> <Form.Control.Feedback type="invalid"> {errors.firstName?.message} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label htmlFor="lastName">Last name</Form.Label> <Form.Control type="text" className="w-75" id="lastName" aria-label="lastName" aria-describedby="lastNameHelp" {...register('lastName')} isInvalid={!!errors.lastName} /> <Form.Control.Feedback type="invalid"> {errors.lastName?.message} </Form.Control.Feedback> </Form.Group> <Form.Row> <Form.Group as={Col}> <Form.Label htmlFor="emailName">Email name</Form.Label> <Form.Control type="text" id="emailName" className="w-100" {...register('emailName')} aria-describedby="emailNameHelp" aria-label="emailName" isInvalid={!!errors.emailName} /> <Form.Control.Feedback type="invalid"> {errors.emailName?.message} </Form.Control.Feedback> </Form.Group> <Form.Group as={Col}> <Form.Label htmlFor="emailDomain">Email domain</Form.Label> <Form.Control as="select" id="emailDomain" className="w-50" {...register('emailDomain')} aria-describedby="emailDomainHelp" aria-label="emailDomain" isInvalid={!!errors.emailDomain} > {validEmailDomains.map(emailDomain => { let emailAddress = '@' + emailDomain; return ( <option key={emailDomain} value={emailAddress}> {emailAddress} </option> ); })} </Form.Control> <Form.Control.Feedback type="invalid"> {errors.emailDomain?.message} </Form.Control.Feedback> </Form.Group> </Form.Row> <Form.Group> <Form.Label htmlFor="universityID">University ID</Form.Label> <Form.Control type="text" className="w-75" id="universityID" {...register('universityID')} aria-describedby="universityIDHelp" aria-label="universityID" isInvalid={!!errors.universityID} /> <Form.Control.Feedback type="invalid"> {errors.universityID?.message} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label htmlFor="password">Password</Form.Label> <Form.Control type="password" className="w-75" id="password" {...register('password')} isInvalid={!!errors.password} aria-label="password" /> <Form.Control.Feedback type="invalid"> {errors.password?.message} </Form.Control.Feedback> </Form.Group> <Form.Group> <Form.Label htmlFor="confirmPassword">Confirm password</Form.Label> <Form.Control type="password" className="w-75" id="confirmPassword" aria-label="confirmPassword" {...register('confirmPassword')} isInvalid={!!errors.confirmPassword} /> <Form.Control.Feedback type="invalid"> {errors.confirmPassword?.message} </Form.Control.Feedback> </Form.Group> <Button type="submit" className="w-75" data-testid="submit-button"> Submit </Button> </Form> ); }
<gh_stars>0 module Jkf # Define parser namespace module Parser # Parse error class ParseError < StandardError; end end end require "jkf/parser/base" require "jkf/parser/kifuable" require "jkf/parser/kif" require "jkf/parser/ki2" require "jkf/parser/csa"
import glob import re def process_files(pathglob): file_data = [] rssrx = re.compile(r'kb=(\d+)') sizerx = re.compile(r'size=(\d+)') for path in glob.iglob(pathglob): with open(path) as f: first_line = f.readline() kb_match = rssrx.search(first_line) size_match = sizerx.search(path) if kb_match and size_match: kb = int(kb_match.group(1)) size = int(size_match.group(1)) file_data.append({'path': path, 'kb': kb, 'size': size}) return file_data
// Function to compress an integer using bitwise operations const compress = (x) => { const mask = 0x3 let compressed = 0 let count = 0 while (x != 0) { const b1 = (x & mask) << (count * 2) compressed |= b1 x >>= 2 count++ } return compressed } // Input let x = 30; // Output let compressedVal = compress(x); console.log(compressedVal);
import requests TELEGRAM_TOKEN = "..." # Replace with actual token RELATIVE_CHAT_IDS = ["...", "..."] # Replace with actual chat IDs TEXT = { "bot_info": ('Привет, я бот, который отвечает за равномерное распределение участников по комнатам.\n\n' 'Нажми кнопку, если готов сменить комнату'), "get_link": "Получить рекомендацию", "new_room": "Ваша новая комната\n%s", "nothing_to_change": "На данный момент ничего менять не требуется" } def change_room(chat_id: str) -> str: # Simulate room change logic based on chat_id # Replace with actual logic to determine the new room or if no change is required new_room = "Room 2" # Replace with actual new room determination logic no_change_message = TEXT["nothing_to_change"] if chat_id in RELATIVE_CHAT_IDS: # Replace with actual API call to send message to the user # For example, using the requests library to make a POST request to the Telegram bot API # Example: requests.post(f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage", data={"chat_id": chat_id, "text": new_room}) return TEXT["new_room"] % new_room else: return no_change_message
#!/bin/bash [[ -f /usr/local/finisher/settings.conf ]] && . /usr/local/finisher/settings.conf MUK_DIR=${MUK_DIR:-"/opt/modify_ubuntu_kit"} [[ ! -e ${MUK_DIR}/files/includes.sh ]] && (echo Missing includes file! Aborting!; exit 1) . ${MUK_DIR}/files/includes.sh # No parameter specified? Or maybe help requested? if [[ "$1" == "--help" || "$1" == "-h" ]]; then echo -e "${RED}Purpose:${NC} Installs Mozilla Firefox and Thunderbird on your computer." echo "" exit 0 fi #============================================================================== _title "Installing Mozilla Firefox and Thunderbird..." #============================================================================== # First: Install the software: #============================================================================== apt install -y firefox thunderbird # Second: Install the Kodi addon: #============================================================================== ### First: Get the repo: git clone --depth=1 https://github.com/xptsp/script.kodi.launches.firefox ${KODI_OPT}/script.kodi.launches.firefox ### Second: Link the repo: ln -sf ${KODI_OPT}/script.kodi.launches.firefox ${KODI_ADD}/script.kodi.launches.firefox ### Third: Enable addon by default: kodi_enable script.kodi.launches.firefox # Third: Copy launcher to the desktop: #============================================================================== [[ ! -d ~/Desktop ]] && mkdir -p ~/Desktop cp /usr/share/applications/firefox.desktop ~/Desktop/ chmod +x ~/Desktop/firefox.desktop cp /usr/share/applications/thunderbird.desktop ~/Desktop/ chmod +x ~/Desktop/thunderbird.desktop
import { Column, Formatter } from './../models/index'; import { decimalFormatted } from './../services/utilities'; export const dollarFormatter: Formatter = (row: number, cell: number, value: any, columnDef: Column, dataContext: any) => { const isNumber = (value === null || value === undefined) ? false : !isNaN(+value); const params = columnDef && columnDef.params || {}; const minDecimal = params.minDecimal || 2; const maxDecimal = params.minDecimal || 4; const outputValue = (isNumber && (params.minDecimal || params.maxDecimal)) ? decimalFormatted(value, minDecimal, maxDecimal) : value; return !isNumber ? '' : `$${outputValue}`; };
/* MACHINE GENERATED FILE, DO NOT EDIT */ #include <jni.h> #include "extcl.h" typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetPlatformIDsPROC) (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetPlatformInfoPROC) (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsPROC) (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceInfoPROC) (cl_device_id device, cl_device_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_context (CL_API_CALL *clCreateContextPROC) (const cl_context_properties * properties, cl_uint num_devices, const cl_device_id * devices, cl_create_context_callback pfn_notify, void * user_data, cl_int * errcode_ret); typedef CL_API_ENTRY cl_context (CL_API_CALL *clCreateContextFromTypePROC) (const cl_context_properties * properties, cl_device_type device_type, cl_create_context_callback pfn_notify, void * user_data, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainContextPROC) (cl_context context); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseContextPROC) (cl_context context); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetContextInfoPROC) (cl_context context, cl_context_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_command_queue (CL_API_CALL *clCreateCommandQueuePROC) (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainCommandQueuePROC) (cl_command_queue command_queue); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseCommandQueuePROC) (cl_command_queue command_queue); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetCommandQueueInfoPROC) (cl_command_queue command_queue, cl_command_queue_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateBufferPROC) (cl_context context, cl_mem_flags flags, size_t size, cl_void * host_ptr, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReadBufferPROC) (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t cb, cl_void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueWriteBufferPROC) (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t cb, const cl_void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueCopyBufferPROC) (cl_command_queue command_queue, cl_mem src_buffer, cl_mem dst_buffer, size_t src_offset, size_t dst_offset, size_t cb, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_void * (CL_API_CALL *clEnqueueMapBufferPROC) (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_map, cl_map_flags map_flags, size_t offset, size_t cb, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event, cl_int * errcode_ret); typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateImage2DPROC) (cl_context context, cl_mem_flags flags, const cl_image_format * image_format, size_t image_width, size_t image_height, size_t image_row_pitch, cl_void * host_ptr, cl_int * errcode_ret); typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateImage3DPROC) (cl_context context, cl_mem_flags flags, const cl_image_format * image_format, size_t image_width, size_t image_height, size_t image_depth, size_t image_row_pitch, size_t image_slice_pitch, cl_void * host_ptr, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetSupportedImageFormatsPROC) (cl_context context, cl_mem_flags flags, cl_mem_object_type image_type, cl_uint num_entries, cl_image_format * image_formats, cl_uint * num_image_formats); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReadImagePROC) (cl_command_queue command_queue, cl_mem image, cl_bool blocking_read, const size_t * origin, const size_t * region, size_t row_pitch, size_t slice_pitch, cl_void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueWriteImagePROC) (cl_command_queue command_queue, cl_mem image, cl_bool blocking_write, const size_t * origin, const size_t * region, size_t input_row_pitch, size_t input_slice_pitch, const cl_void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueCopyImagePROC) (cl_command_queue command_queue, cl_mem src_image, cl_mem dst_image, const size_t * src_origin, const size_t * dst_origin, const size_t * region, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueCopyImageToBufferPROC) (cl_command_queue command_queue, cl_mem src_image, cl_mem dst_buffer, const size_t * src_origin, const size_t * region, size_t dst_offset, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueCopyBufferToImagePROC) (cl_command_queue command_queue, cl_mem src_buffer, cl_mem dst_image, size_t src_offset, const size_t * dst_origin, const size_t * region, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_void * (CL_API_CALL *clEnqueueMapImagePROC) (cl_command_queue command_queue, cl_mem image, cl_bool blocking_map, cl_map_flags map_flags, const size_t * origin, const size_t * region, size_t * image_row_pitch, size_t * image_slice_pitch, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetImageInfoPROC) (cl_mem image, cl_image_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainMemObjectPROC) (cl_mem memobj); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseMemObjectPROC) (cl_mem memobj); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueUnmapMemObjectPROC) (cl_command_queue command_queue, cl_mem memobj, cl_void * mapped_ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetMemObjectInfoPROC) (cl_mem memobj, cl_mem_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_sampler (CL_API_CALL *clCreateSamplerPROC) (cl_context context, cl_bool normalized_coords, cl_addressing_mode addressing_mode, cl_filter_mode filter_mode, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainSamplerPROC) (cl_sampler sampler); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseSamplerPROC) (cl_sampler sampler); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetSamplerInfoPROC) (cl_sampler sampler, cl_sampler_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_program (CL_API_CALL *clCreateProgramWithSourcePROC) (cl_context context, cl_uint count, const cl_char ** string, const size_t* lengths, cl_int * errcode_ret); typedef CL_API_ENTRY cl_program (CL_API_CALL *clCreateProgramWithBinaryPROC) (cl_context context, cl_uint num_devices, const cl_device_id* device, const size_t* lengths, const cl_uchar ** binary, cl_int * binary_status, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainProgramPROC) (cl_program program); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseProgramPROC) (cl_program program); typedef CL_API_ENTRY cl_int (CL_API_CALL *clBuildProgramPROC) (cl_program program, cl_uint num_devices, const cl_device_id * device_list, const cl_char * options, cl_build_program_callback pfn_notify, void * user_data); typedef CL_API_ENTRY cl_int (CL_API_CALL *clUnloadCompilerPROC) (); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetProgramInfoPROC) (cl_program program, cl_program_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetProgramBuildInfoPROC) (cl_program program, cl_device_id device, cl_program_build_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_kernel (CL_API_CALL *clCreateKernelPROC) (cl_program program, const cl_char * kernel_name, cl_int * errcode_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clCreateKernelsInProgramPROC) (cl_program program, cl_uint num_kernels, cl_kernel * kernels, cl_uint * num_kernels_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainKernelPROC) (cl_kernel kernel); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseKernelPROC) (cl_kernel kernel); typedef CL_API_ENTRY cl_int (CL_API_CALL *clSetKernelArgPROC) (cl_kernel kernel, cl_uint arg_index, size_t arg_size, const cl_void * arg_value); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetKernelInfoPROC) (cl_kernel kernel, cl_kernel_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetKernelWorkGroupInfoPROC) (cl_kernel kernel, cl_device_id device, cl_kernel_work_group_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueNDRangeKernelPROC) (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, const size_t * global_work_offset, const size_t * global_work_size, const size_t * local_work_size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueTaskPROC) (cl_command_queue command_queue, cl_kernel kernel, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueNativeKernelPROC) (cl_command_queue command_queue, cl_native_kernel_func user_func, cl_void * args, size_t cb_args, cl_uint num_mem_objects, const cl_mem* mem_list, const cl_void ** args_mem_loc, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clWaitForEventsPROC) (cl_uint num_events, const cl_event * event_list); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetEventInfoPROC) (cl_event event, cl_event_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clRetainEventPROC) (cl_event event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clReleaseEventPROC) (cl_event event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueMarkerPROC) (cl_command_queue command_queue, cl_event * event); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueBarrierPROC) (cl_command_queue command_queue); typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueWaitForEventsPROC) (cl_command_queue command_queue, cl_uint num_events, const cl_event * event_list); typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetEventProfilingInfoPROC) (cl_event event, cl_profiling_info param_name, size_t param_value_size, cl_void * param_value, size_t * param_value_size_ret); typedef CL_API_ENTRY cl_int (CL_API_CALL *clFlushPROC) (cl_command_queue command_queue); typedef CL_API_ENTRY cl_int (CL_API_CALL *clFinishPROC) (cl_command_queue command_queue); typedef CL_API_ENTRY void * (CL_API_CALL *clGetExtensionFunctionAddressPROC) (const cl_char * func_name); JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetPlatformIDs(JNIEnv *env, jclass clazz, jint num_entries, jlong platforms, jlong num_platforms, jlong function_pointer) { cl_platform_id *platforms_address = (cl_platform_id *)(intptr_t)platforms; cl_uint *num_platforms_address = (cl_uint *)(intptr_t)num_platforms; clGetPlatformIDsPROC clGetPlatformIDs = (clGetPlatformIDsPROC)((intptr_t)function_pointer); cl_int __result = clGetPlatformIDs(num_entries, platforms_address, num_platforms_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetPlatformInfo(JNIEnv *env, jclass clazz, jlong platform, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetPlatformInfoPROC clGetPlatformInfo = (clGetPlatformInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetPlatformInfo((cl_platform_id)(intptr_t)platform, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetDeviceIDs(JNIEnv *env, jclass clazz, jlong platform, jlong device_type, jint num_entries, jlong devices, jlong num_devices, jlong function_pointer) { cl_device_id *devices_address = (cl_device_id *)(intptr_t)devices; cl_uint *num_devices_address = (cl_uint *)(intptr_t)num_devices; clGetDeviceIDsPROC clGetDeviceIDs = (clGetDeviceIDsPROC)((intptr_t)function_pointer); cl_int __result = clGetDeviceIDs((cl_platform_id)(intptr_t)platform, device_type, num_entries, devices_address, num_devices_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetDeviceInfo(JNIEnv *env, jclass clazz, jlong device, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetDeviceInfoPROC clGetDeviceInfo = (clGetDeviceInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetDeviceInfo((cl_device_id)(intptr_t)device, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateContext(JNIEnv *env, jclass clazz, jlong properties, jint num_devices, jlong devices, jlong pfn_notify, jlong user_data, jlong errcode_ret, jlong function_pointer) { const cl_context_properties *properties_address = (const cl_context_properties *)(intptr_t)properties; const cl_device_id *devices_address = (const cl_device_id *)(intptr_t)devices; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateContextPROC clCreateContext = (clCreateContextPROC)((intptr_t)function_pointer); cl_context __result = clCreateContext(properties_address, num_devices, devices_address, (cl_create_context_callback)(intptr_t)pfn_notify, (void *)(intptr_t)user_data, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateContextFromType(JNIEnv *env, jclass clazz, jlong properties, jlong device_type, jlong pfn_notify, jlong user_data, jlong errcode_ret, jlong function_pointer) { const cl_context_properties *properties_address = (const cl_context_properties *)(intptr_t)properties; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateContextFromTypePROC clCreateContextFromType = (clCreateContextFromTypePROC)((intptr_t)function_pointer); cl_context __result = clCreateContextFromType(properties_address, device_type, (cl_create_context_callback)(intptr_t)pfn_notify, (void *)(intptr_t)user_data, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainContext(JNIEnv *env, jclass clazz, jlong context, jlong function_pointer) { clRetainContextPROC clRetainContext = (clRetainContextPROC)((intptr_t)function_pointer); cl_int __result = clRetainContext((cl_context)(intptr_t)context); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseContext(JNIEnv *env, jclass clazz, jlong context, jlong function_pointer) { clReleaseContextPROC clReleaseContext = (clReleaseContextPROC)((intptr_t)function_pointer); cl_int __result = clReleaseContext((cl_context)(intptr_t)context); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetContextInfo(JNIEnv *env, jclass clazz, jlong context, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetContextInfoPROC clGetContextInfo = (clGetContextInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetContextInfo((cl_context)(intptr_t)context, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateCommandQueue(JNIEnv *env, jclass clazz, jlong context, jlong device, jlong properties, jlong errcode_ret, jlong function_pointer) { cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateCommandQueuePROC clCreateCommandQueue = (clCreateCommandQueuePROC)((intptr_t)function_pointer); cl_command_queue __result = clCreateCommandQueue((cl_context)(intptr_t)context, (cl_device_id)(intptr_t)device, properties, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainCommandQueue(JNIEnv *env, jclass clazz, jlong command_queue, jlong function_pointer) { clRetainCommandQueuePROC clRetainCommandQueue = (clRetainCommandQueuePROC)((intptr_t)function_pointer); cl_int __result = clRetainCommandQueue((cl_command_queue)(intptr_t)command_queue); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseCommandQueue(JNIEnv *env, jclass clazz, jlong command_queue, jlong function_pointer) { clReleaseCommandQueuePROC clReleaseCommandQueue = (clReleaseCommandQueuePROC)((intptr_t)function_pointer); cl_int __result = clReleaseCommandQueue((cl_command_queue)(intptr_t)command_queue); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetCommandQueueInfo(JNIEnv *env, jclass clazz, jlong command_queue, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetCommandQueueInfoPROC clGetCommandQueueInfo = (clGetCommandQueueInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetCommandQueueInfo((cl_command_queue)(intptr_t)command_queue, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateBuffer(JNIEnv *env, jclass clazz, jlong context, jlong flags, jlong size, jlong host_ptr, jlong errcode_ret, jlong function_pointer) { cl_void *host_ptr_address = (cl_void *)(intptr_t)host_ptr; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateBufferPROC clCreateBuffer = (clCreateBufferPROC)((intptr_t)function_pointer); cl_mem __result = clCreateBuffer((cl_context)(intptr_t)context, flags, size, host_ptr_address, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueReadBuffer(JNIEnv *env, jclass clazz, jlong command_queue, jlong buffer, jint blocking_read, jlong offset, jlong cb, jlong ptr, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { cl_void *ptr_address = (cl_void *)(intptr_t)ptr; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueReadBufferPROC clEnqueueReadBuffer = (clEnqueueReadBufferPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueReadBuffer((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)buffer, blocking_read, offset, cb, ptr_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueWriteBuffer(JNIEnv *env, jclass clazz, jlong command_queue, jlong buffer, jint blocking_write, jlong offset, jlong cb, jlong ptr, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const cl_void *ptr_address = (const cl_void *)(intptr_t)ptr; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueWriteBufferPROC clEnqueueWriteBuffer = (clEnqueueWriteBufferPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueWriteBuffer((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)buffer, blocking_write, offset, cb, ptr_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueCopyBuffer(JNIEnv *env, jclass clazz, jlong command_queue, jlong src_buffer, jlong dst_buffer, jlong src_offset, jlong dst_offset, jlong cb, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueCopyBufferPROC clEnqueueCopyBuffer = (clEnqueueCopyBufferPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueCopyBuffer((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)src_buffer, (cl_mem)(intptr_t)dst_buffer, src_offset, dst_offset, cb, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jobject JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueMapBuffer(JNIEnv *env, jclass clazz, jlong command_queue, jlong buffer, jint blocking_map, jlong map_flags, jlong offset, jlong cb, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong errcode_ret, jlong result_size, jlong function_pointer) { const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clEnqueueMapBufferPROC clEnqueueMapBuffer = (clEnqueueMapBufferPROC)((intptr_t)function_pointer); cl_void * __result = clEnqueueMapBuffer((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)buffer, blocking_map, map_flags, offset, cb, num_events_in_wait_list, event_wait_list_address, event_address, errcode_ret_address); return safeNewBuffer(env, __result, result_size); } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateImage2D(JNIEnv *env, jclass clazz, jlong context, jlong flags, jlong image_format, jlong image_width, jlong image_height, jlong image_row_pitch, jlong host_ptr, jlong errcode_ret, jlong function_pointer) { const cl_image_format *image_format_address = (const cl_image_format *)(intptr_t)image_format; cl_void *host_ptr_address = (cl_void *)(intptr_t)host_ptr; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateImage2DPROC clCreateImage2D = (clCreateImage2DPROC)((intptr_t)function_pointer); cl_mem __result = clCreateImage2D((cl_context)(intptr_t)context, flags, image_format_address, image_width, image_height, image_row_pitch, host_ptr_address, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateImage3D(JNIEnv *env, jclass clazz, jlong context, jlong flags, jlong image_format, jlong image_width, jlong image_height, jlong image_depth, jlong image_row_pitch, jlong image_slice_pitch, jlong host_ptr, jlong errcode_ret, jlong function_pointer) { const cl_image_format *image_format_address = (const cl_image_format *)(intptr_t)image_format; cl_void *host_ptr_address = (cl_void *)(intptr_t)host_ptr; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateImage3DPROC clCreateImage3D = (clCreateImage3DPROC)((intptr_t)function_pointer); cl_mem __result = clCreateImage3D((cl_context)(intptr_t)context, flags, image_format_address, image_width, image_height, image_depth, image_row_pitch, image_slice_pitch, host_ptr_address, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetSupportedImageFormats(JNIEnv *env, jclass clazz, jlong context, jlong flags, jint image_type, jint num_entries, jlong image_formats, jlong num_image_formats, jlong function_pointer) { cl_image_format *image_formats_address = (cl_image_format *)(intptr_t)image_formats; cl_uint *num_image_formats_address = (cl_uint *)(intptr_t)num_image_formats; clGetSupportedImageFormatsPROC clGetSupportedImageFormats = (clGetSupportedImageFormatsPROC)((intptr_t)function_pointer); cl_int __result = clGetSupportedImageFormats((cl_context)(intptr_t)context, flags, image_type, num_entries, image_formats_address, num_image_formats_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueReadImage(JNIEnv *env, jclass clazz, jlong command_queue, jlong image, jint blocking_read, jlong origin, jlong region, jlong row_pitch, jlong slice_pitch, jlong ptr, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const size_t *origin_address = (const size_t *)(intptr_t)origin; const size_t *region_address = (const size_t *)(intptr_t)region; cl_void *ptr_address = (cl_void *)(intptr_t)ptr; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueReadImagePROC clEnqueueReadImage = (clEnqueueReadImagePROC)((intptr_t)function_pointer); cl_int __result = clEnqueueReadImage((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)image, blocking_read, origin_address, region_address, row_pitch, slice_pitch, ptr_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueWriteImage(JNIEnv *env, jclass clazz, jlong command_queue, jlong image, jint blocking_write, jlong origin, jlong region, jlong input_row_pitch, jlong input_slice_pitch, jlong ptr, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const size_t *origin_address = (const size_t *)(intptr_t)origin; const size_t *region_address = (const size_t *)(intptr_t)region; const cl_void *ptr_address = (const cl_void *)(intptr_t)ptr; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueWriteImagePROC clEnqueueWriteImage = (clEnqueueWriteImagePROC)((intptr_t)function_pointer); cl_int __result = clEnqueueWriteImage((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)image, blocking_write, origin_address, region_address, input_row_pitch, input_slice_pitch, ptr_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueCopyImage(JNIEnv *env, jclass clazz, jlong command_queue, jlong src_image, jlong dst_image, jlong src_origin, jlong dst_origin, jlong region, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const size_t *src_origin_address = (const size_t *)(intptr_t)src_origin; const size_t *dst_origin_address = (const size_t *)(intptr_t)dst_origin; const size_t *region_address = (const size_t *)(intptr_t)region; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueCopyImagePROC clEnqueueCopyImage = (clEnqueueCopyImagePROC)((intptr_t)function_pointer); cl_int __result = clEnqueueCopyImage((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)src_image, (cl_mem)(intptr_t)dst_image, src_origin_address, dst_origin_address, region_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueCopyImageToBuffer(JNIEnv *env, jclass clazz, jlong command_queue, jlong src_image, jlong dst_buffer, jlong src_origin, jlong region, jlong dst_offset, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const size_t *src_origin_address = (const size_t *)(intptr_t)src_origin; const size_t *region_address = (const size_t *)(intptr_t)region; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueCopyImageToBufferPROC clEnqueueCopyImageToBuffer = (clEnqueueCopyImageToBufferPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueCopyImageToBuffer((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)src_image, (cl_mem)(intptr_t)dst_buffer, src_origin_address, region_address, dst_offset, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueCopyBufferToImage(JNIEnv *env, jclass clazz, jlong command_queue, jlong src_buffer, jlong dst_image, jlong src_offset, jlong dst_origin, jlong region, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const size_t *dst_origin_address = (const size_t *)(intptr_t)dst_origin; const size_t *region_address = (const size_t *)(intptr_t)region; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueCopyBufferToImagePROC clEnqueueCopyBufferToImage = (clEnqueueCopyBufferToImagePROC)((intptr_t)function_pointer); cl_int __result = clEnqueueCopyBufferToImage((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)src_buffer, (cl_mem)(intptr_t)dst_image, src_offset, dst_origin_address, region_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jobject JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueMapImage(JNIEnv *env, jclass clazz, jlong command_queue, jlong image, jint blocking_map, jlong map_flags, jlong origin, jlong region, jlong image_row_pitch, jlong image_slice_pitch, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong errcode_ret, jlong function_pointer) { const size_t *origin_address = (const size_t *)(intptr_t)origin; const size_t *region_address = (const size_t *)(intptr_t)region; size_t *image_row_pitch_address = (size_t *)(intptr_t)image_row_pitch; size_t *image_slice_pitch_address = (size_t *)(intptr_t)image_slice_pitch; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clEnqueueMapImagePROC clEnqueueMapImage = (clEnqueueMapImagePROC)((intptr_t)function_pointer); cl_void * __result = clEnqueueMapImage((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)image, blocking_map, map_flags, origin_address, region_address, image_row_pitch_address, image_slice_pitch_address, num_events_in_wait_list, event_wait_list_address, event_address, errcode_ret_address); return safeNewBuffer(env, __result, extcl_CalculateImageSize(region_address, *image_row_pitch_address, image_slice_pitch_address == NULL ? 0 : *image_slice_pitch_address)); } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetImageInfo(JNIEnv *env, jclass clazz, jlong image, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetImageInfoPROC clGetImageInfo = (clGetImageInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetImageInfo((cl_mem)(intptr_t)image, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainMemObject(JNIEnv *env, jclass clazz, jlong memobj, jlong function_pointer) { clRetainMemObjectPROC clRetainMemObject = (clRetainMemObjectPROC)((intptr_t)function_pointer); cl_int __result = clRetainMemObject((cl_mem)(intptr_t)memobj); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseMemObject(JNIEnv *env, jclass clazz, jlong memobj, jlong function_pointer) { clReleaseMemObjectPROC clReleaseMemObject = (clReleaseMemObjectPROC)((intptr_t)function_pointer); cl_int __result = clReleaseMemObject((cl_mem)(intptr_t)memobj); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueUnmapMemObject(JNIEnv *env, jclass clazz, jlong command_queue, jlong memobj, jlong mapped_ptr, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { cl_void *mapped_ptr_address = (cl_void *)(intptr_t)mapped_ptr; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueUnmapMemObjectPROC clEnqueueUnmapMemObject = (clEnqueueUnmapMemObjectPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueUnmapMemObject((cl_command_queue)(intptr_t)command_queue, (cl_mem)(intptr_t)memobj, mapped_ptr_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetMemObjectInfo(JNIEnv *env, jclass clazz, jlong memobj, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetMemObjectInfoPROC clGetMemObjectInfo = (clGetMemObjectInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetMemObjectInfo((cl_mem)(intptr_t)memobj, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateSampler(JNIEnv *env, jclass clazz, jlong context, jint normalized_coords, jint addressing_mode, jint filter_mode, jlong errcode_ret, jlong function_pointer) { cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateSamplerPROC clCreateSampler = (clCreateSamplerPROC)((intptr_t)function_pointer); cl_sampler __result = clCreateSampler((cl_context)(intptr_t)context, normalized_coords, addressing_mode, filter_mode, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainSampler(JNIEnv *env, jclass clazz, jlong sampler, jlong function_pointer) { clRetainSamplerPROC clRetainSampler = (clRetainSamplerPROC)((intptr_t)function_pointer); cl_int __result = clRetainSampler((cl_sampler)(intptr_t)sampler); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseSampler(JNIEnv *env, jclass clazz, jlong sampler, jlong function_pointer) { clReleaseSamplerPROC clReleaseSampler = (clReleaseSamplerPROC)((intptr_t)function_pointer); cl_int __result = clReleaseSampler((cl_sampler)(intptr_t)sampler); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetSamplerInfo(JNIEnv *env, jclass clazz, jlong sampler, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetSamplerInfoPROC clGetSamplerInfo = (clGetSamplerInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetSamplerInfo((cl_sampler)(intptr_t)sampler, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithSource(JNIEnv *env, jclass clazz, jlong context, jint count, jlong string, jlong lengths, jlong errcode_ret, jlong function_pointer) { const cl_char *string_address = (const cl_char *)(intptr_t)string; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithSourcePROC clCreateProgramWithSource = (clCreateProgramWithSourcePROC)((intptr_t)function_pointer); cl_program __result = clCreateProgramWithSource((cl_context)(intptr_t)context, count, (const cl_char **)&string_address, (const size_t*)&lengths, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithSource2(JNIEnv *env, jclass clazz, jlong context, jint count, jlong strings, jlong lengths, jlong errcode_ret, jlong function_pointer) { const cl_char *strings_address = (const cl_char *)(intptr_t)strings; unsigned int _str_i; cl_char *_str_address; cl_char **strings_str = (cl_char **) malloc(count * sizeof(cl_char *)); const size_t *lengths_address = (const size_t *)(intptr_t)lengths; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithSourcePROC clCreateProgramWithSource = (clCreateProgramWithSourcePROC)((intptr_t)function_pointer); cl_program __result; _str_i = 0; _str_address = (cl_char *)strings_address; while ( _str_i < count ) { strings_str[_str_i] = _str_address; _str_address += lengths_address[_str_i++]; } __result = clCreateProgramWithSource((cl_context)(intptr_t)context, count, (const cl_char **)strings_str, lengths_address, errcode_ret_address); free(strings_str); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithSource3(JNIEnv *env, jclass clazz, jlong context, jint count, jobjectArray strings, jlong lengths, jlong errcode_ret, jlong function_pointer) { unsigned int _ptr_i; jobject _ptr_object; cl_char **strings_ptr = (cl_char **) malloc(count * sizeof(cl_char *)); const size_t *lengths_address = (const size_t *)(intptr_t)lengths; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithSourcePROC clCreateProgramWithSource = (clCreateProgramWithSourcePROC)((intptr_t)function_pointer); cl_program __result; _ptr_i = 0; while ( _ptr_i < count ) { _ptr_object = (*env)->GetObjectArrayElement(env, strings, _ptr_i); strings_ptr[_ptr_i++] = (cl_char *)(intptr_t)getPointerWrapperAddress(env, _ptr_object); } __result = clCreateProgramWithSource((cl_context)(intptr_t)context, count, (const cl_char **)strings_ptr, lengths_address, errcode_ret_address); free(strings_ptr); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithSource4(JNIEnv *env, jclass clazz, jlong context, jint count, jlong strings, jlong lengths, jlong errcode_ret, jlong function_pointer) { const cl_char *strings_address = (const cl_char *)(intptr_t)strings; unsigned int _str_i; cl_char *_str_address; cl_char **strings_str = (cl_char **) malloc(count * sizeof(cl_char *)); const size_t *lengths_address = (const size_t *)(intptr_t)lengths; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithSourcePROC clCreateProgramWithSource = (clCreateProgramWithSourcePROC)((intptr_t)function_pointer); cl_program __result; _str_i = 0; _str_address = (cl_char *)strings_address; while ( _str_i < count ) { strings_str[_str_i] = _str_address; _str_address += lengths_address[_str_i++]; } __result = clCreateProgramWithSource((cl_context)(intptr_t)context, count, (const cl_char **)strings_str, lengths_address, errcode_ret_address); free(strings_str); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithBinary(JNIEnv *env, jclass clazz, jlong context, jint num_devices, jlong device, jlong lengths, jlong binary, jlong binary_status, jlong errcode_ret, jlong function_pointer) { const cl_uchar *binary_address = (const cl_uchar *)(intptr_t)binary; cl_int *binary_status_address = (cl_int *)(intptr_t)binary_status; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithBinaryPROC clCreateProgramWithBinary = (clCreateProgramWithBinaryPROC)((intptr_t)function_pointer); cl_program __result = clCreateProgramWithBinary((cl_context)(intptr_t)context, num_devices, (const cl_device_id*)(cl_device_id)(intptr_t)&device, (const size_t*)&lengths, (const cl_uchar **)&binary_address, binary_status_address, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithBinary2(JNIEnv *env, jclass clazz, jlong context, jint num_devices, jlong device_list, jlong lengths, jlong binaries, jlong binary_status, jlong errcode_ret, jlong function_pointer) { const cl_device_id *device_list_address = (const cl_device_id *)(intptr_t)device_list; const size_t *lengths_address = (const size_t *)(intptr_t)lengths; const cl_uchar *binaries_address = (const cl_uchar *)(intptr_t)binaries; unsigned int _str_i; cl_uchar *_str_address; cl_uchar **binaries_str = (cl_uchar **) malloc(num_devices * sizeof(cl_uchar *)); cl_int *binary_status_address = (cl_int *)(intptr_t)binary_status; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithBinaryPROC clCreateProgramWithBinary = (clCreateProgramWithBinaryPROC)((intptr_t)function_pointer); cl_program __result; _str_i = 0; _str_address = (cl_uchar *)binaries_address; while ( _str_i < num_devices ) { binaries_str[_str_i] = _str_address; _str_address += lengths_address[_str_i++]; } __result = clCreateProgramWithBinary((cl_context)(intptr_t)context, num_devices, device_list_address, lengths_address, (const cl_uchar **)binaries_str, binary_status_address, errcode_ret_address); free(binaries_str); return (intptr_t)__result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateProgramWithBinary3(JNIEnv *env, jclass clazz, jlong context, jint num_devices, jlong device_list, jlong lengths, jobjectArray binaries, jlong binary_status, jlong errcode_ret, jlong function_pointer) { const cl_device_id *device_list_address = (const cl_device_id *)(intptr_t)device_list; const size_t *lengths_address = (const size_t *)(intptr_t)lengths; unsigned int _ptr_i; jobject _ptr_object; cl_uchar **binaries_ptr = (cl_uchar **) malloc(num_devices * sizeof(cl_uchar *)); cl_int *binary_status_address = (cl_int *)(intptr_t)binary_status; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateProgramWithBinaryPROC clCreateProgramWithBinary = (clCreateProgramWithBinaryPROC)((intptr_t)function_pointer); cl_program __result; _ptr_i = 0; while ( _ptr_i < num_devices ) { _ptr_object = (*env)->GetObjectArrayElement(env, binaries, _ptr_i); binaries_ptr[_ptr_i++] = (cl_uchar *)(intptr_t)getPointerWrapperAddress(env, _ptr_object); } __result = clCreateProgramWithBinary((cl_context)(intptr_t)context, num_devices, device_list_address, lengths_address, (const cl_uchar **)binaries_ptr, binary_status_address, errcode_ret_address); free(binaries_ptr); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainProgram(JNIEnv *env, jclass clazz, jlong program, jlong function_pointer) { clRetainProgramPROC clRetainProgram = (clRetainProgramPROC)((intptr_t)function_pointer); cl_int __result = clRetainProgram((cl_program)(intptr_t)program); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseProgram(JNIEnv *env, jclass clazz, jlong program, jlong function_pointer) { clReleaseProgramPROC clReleaseProgram = (clReleaseProgramPROC)((intptr_t)function_pointer); cl_int __result = clReleaseProgram((cl_program)(intptr_t)program); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclBuildProgram(JNIEnv *env, jclass clazz, jlong program, jint num_devices, jlong device_list, jlong options, jlong pfn_notify, jlong user_data, jlong function_pointer) { const cl_device_id *device_list_address = (const cl_device_id *)(intptr_t)device_list; const cl_char *options_address = (const cl_char *)(intptr_t)options; clBuildProgramPROC clBuildProgram = (clBuildProgramPROC)((intptr_t)function_pointer); cl_int __result = clBuildProgram((cl_program)(intptr_t)program, num_devices, device_list_address, options_address, (cl_build_program_callback)(intptr_t)pfn_notify, (void *)(intptr_t)user_data); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclUnloadCompiler(JNIEnv *env, jclass clazz, jlong function_pointer) { clUnloadCompilerPROC clUnloadCompiler = (clUnloadCompilerPROC)((intptr_t)function_pointer); cl_int __result = clUnloadCompiler(); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetProgramInfo(JNIEnv *env, jclass clazz, jlong program, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetProgramInfoPROC clGetProgramInfo = (clGetProgramInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetProgramInfo((cl_program)(intptr_t)program, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetProgramInfo2(JNIEnv *env, jclass clazz, jlong program, jint param_name, jlong param_value_size, jlong sizes, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { const size_t *sizes_address = (const size_t *)(intptr_t)sizes; cl_uchar *param_value_address = (cl_uchar *)(intptr_t)param_value; unsigned int _str_i; cl_uchar *_str_address; cl_uchar **param_value_str = (cl_uchar **) malloc(param_value_size * sizeof(cl_uchar *)); size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetProgramInfoPROC clGetProgramInfo = (clGetProgramInfoPROC)((intptr_t)function_pointer); cl_int __result; _str_i = 0; _str_address = (cl_uchar *)param_value_address; while ( _str_i < param_value_size ) { param_value_str[_str_i] = _str_address; _str_address += sizes_address[_str_i++]; } __result = clGetProgramInfo((cl_program)(intptr_t)program, param_name, param_value_size, (cl_uchar **)param_value_str, param_value_size_ret_address); free(param_value_str); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetProgramInfo3(JNIEnv *env, jclass clazz, jlong program, jint param_name, jlong param_value_size, jobjectArray param_value, jlong param_value_size_ret, jlong function_pointer) { unsigned int _ptr_i; jobject _ptr_object; cl_uchar **param_value_ptr = (cl_uchar **) malloc(param_value_size * sizeof(cl_uchar *)); size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetProgramInfoPROC clGetProgramInfo = (clGetProgramInfoPROC)((intptr_t)function_pointer); cl_int __result; _ptr_i = 0; while ( _ptr_i < param_value_size ) { _ptr_object = (*env)->GetObjectArrayElement(env, param_value, _ptr_i); param_value_ptr[_ptr_i++] = (cl_uchar *)(intptr_t)getPointerWrapperAddress(env, _ptr_object); } __result = clGetProgramInfo((cl_program)(intptr_t)program, param_name, param_value_size, (cl_uchar **)param_value_ptr, param_value_size_ret_address); free(param_value_ptr); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetProgramBuildInfo(JNIEnv *env, jclass clazz, jlong program, jlong device, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetProgramBuildInfoPROC clGetProgramBuildInfo = (clGetProgramBuildInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetProgramBuildInfo((cl_program)(intptr_t)program, (cl_device_id)(intptr_t)device, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclCreateKernel(JNIEnv *env, jclass clazz, jlong program, jlong kernel_name, jlong errcode_ret, jlong function_pointer) { const cl_char *kernel_name_address = (const cl_char *)(intptr_t)kernel_name; cl_int *errcode_ret_address = (cl_int *)(intptr_t)errcode_ret; clCreateKernelPROC clCreateKernel = (clCreateKernelPROC)((intptr_t)function_pointer); cl_kernel __result = clCreateKernel((cl_program)(intptr_t)program, kernel_name_address, errcode_ret_address); return (intptr_t)__result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclCreateKernelsInProgram(JNIEnv *env, jclass clazz, jlong program, jint num_kernels, jlong kernels, jlong num_kernels_ret, jlong function_pointer) { cl_kernel *kernels_address = (cl_kernel *)(intptr_t)kernels; cl_uint *num_kernels_ret_address = (cl_uint *)(intptr_t)num_kernels_ret; clCreateKernelsInProgramPROC clCreateKernelsInProgram = (clCreateKernelsInProgramPROC)((intptr_t)function_pointer); cl_int __result = clCreateKernelsInProgram((cl_program)(intptr_t)program, num_kernels, kernels_address, num_kernels_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainKernel(JNIEnv *env, jclass clazz, jlong kernel, jlong function_pointer) { clRetainKernelPROC clRetainKernel = (clRetainKernelPROC)((intptr_t)function_pointer); cl_int __result = clRetainKernel((cl_kernel)(intptr_t)kernel); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseKernel(JNIEnv *env, jclass clazz, jlong kernel, jlong function_pointer) { clReleaseKernelPROC clReleaseKernel = (clReleaseKernelPROC)((intptr_t)function_pointer); cl_int __result = clReleaseKernel((cl_kernel)(intptr_t)kernel); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclSetKernelArg(JNIEnv *env, jclass clazz, jlong kernel, jint arg_index, jlong arg_size, jlong arg_value, jlong function_pointer) { const cl_void *arg_value_address = (const cl_void *)(intptr_t)arg_value; clSetKernelArgPROC clSetKernelArg = (clSetKernelArgPROC)((intptr_t)function_pointer); cl_int __result = clSetKernelArg((cl_kernel)(intptr_t)kernel, arg_index, arg_size, arg_value_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetKernelInfo(JNIEnv *env, jclass clazz, jlong kernel, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetKernelInfoPROC clGetKernelInfo = (clGetKernelInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetKernelInfo((cl_kernel)(intptr_t)kernel, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetKernelWorkGroupInfo(JNIEnv *env, jclass clazz, jlong kernel, jlong device, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetKernelWorkGroupInfoPROC clGetKernelWorkGroupInfo = (clGetKernelWorkGroupInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetKernelWorkGroupInfo((cl_kernel)(intptr_t)kernel, (cl_device_id)(intptr_t)device, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueNDRangeKernel(JNIEnv *env, jclass clazz, jlong command_queue, jlong kernel, jint work_dim, jlong global_work_offset, jlong global_work_size, jlong local_work_size, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const size_t *global_work_offset_address = (const size_t *)(intptr_t)global_work_offset; const size_t *global_work_size_address = (const size_t *)(intptr_t)global_work_size; const size_t *local_work_size_address = (const size_t *)(intptr_t)local_work_size; const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueNDRangeKernelPROC clEnqueueNDRangeKernel = (clEnqueueNDRangeKernelPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueNDRangeKernel((cl_command_queue)(intptr_t)command_queue, (cl_kernel)(intptr_t)kernel, work_dim, global_work_offset_address, global_work_size_address, local_work_size_address, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueTask(JNIEnv *env, jclass clazz, jlong command_queue, jlong kernel, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueTaskPROC clEnqueueTask = (clEnqueueTaskPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueTask((cl_command_queue)(intptr_t)command_queue, (cl_kernel)(intptr_t)kernel, num_events_in_wait_list, event_wait_list_address, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueNativeKernel(JNIEnv *env, jclass clazz, jlong command_queue, jlong user_func, jlong args, jlong cb_args, jint num_mem_objects, jobjectArray mem_list, jint num_events_in_wait_list, jlong event_wait_list, jlong event, jlong function_pointer) { cl_void *args_address = (cl_void *)(intptr_t)args; unsigned int _ptr_i; jobject _ptr_object; cl_mem *mem_list_ptr = num_mem_objects == 0 ? NULL : (cl_mem *) malloc(num_mem_objects * sizeof(cl_mem )); const cl_event *event_wait_list_address = (const cl_event *)(intptr_t)event_wait_list; cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueNativeKernelPROC clEnqueueNativeKernel = (clEnqueueNativeKernelPROC)((intptr_t)function_pointer); cl_int __result; void **args_mem_loc = num_mem_objects == 0 ? NULL : (void **)malloc(num_mem_objects * sizeof(void *)); _ptr_i = 0; while ( _ptr_i < num_mem_objects ) { _ptr_object = (*env)->GetObjectArrayElement(env, mem_list, _ptr_i); mem_list_ptr[_ptr_i++] = (cl_mem)(intptr_t)getPointerWrapperAddress(env, _ptr_object); } _ptr_i = 0; while ( _ptr_i < num_mem_objects ) { args_mem_loc[_ptr_i] = (cl_void *)((char *)args_address + (4 + _ptr_i * (4 + sizeof(void *)))); _ptr_i++; } __result = clEnqueueNativeKernel((cl_command_queue)(intptr_t)command_queue, (cl_native_kernel_func)(intptr_t)user_func, args_address, cb_args, num_mem_objects, (const cl_mem*)mem_list_ptr, (const void**)args_mem_loc, num_events_in_wait_list, event_wait_list_address, event_address); free(args_mem_loc); free(mem_list_ptr); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclWaitForEvents(JNIEnv *env, jclass clazz, jint num_events, jlong event_list, jlong function_pointer) { const cl_event *event_list_address = (const cl_event *)(intptr_t)event_list; clWaitForEventsPROC clWaitForEvents = (clWaitForEventsPROC)((intptr_t)function_pointer); cl_int __result = clWaitForEvents(num_events, event_list_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetEventInfo(JNIEnv *env, jclass clazz, jlong event, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetEventInfoPROC clGetEventInfo = (clGetEventInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetEventInfo((cl_event)(intptr_t)event, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclRetainEvent(JNIEnv *env, jclass clazz, jlong event, jlong function_pointer) { clRetainEventPROC clRetainEvent = (clRetainEventPROC)((intptr_t)function_pointer); cl_int __result = clRetainEvent((cl_event)(intptr_t)event); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclReleaseEvent(JNIEnv *env, jclass clazz, jlong event, jlong function_pointer) { clReleaseEventPROC clReleaseEvent = (clReleaseEventPROC)((intptr_t)function_pointer); cl_int __result = clReleaseEvent((cl_event)(intptr_t)event); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueMarker(JNIEnv *env, jclass clazz, jlong command_queue, jlong event, jlong function_pointer) { cl_event *event_address = (cl_event *)(intptr_t)event; clEnqueueMarkerPROC clEnqueueMarker = (clEnqueueMarkerPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueMarker((cl_command_queue)(intptr_t)command_queue, event_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueBarrier(JNIEnv *env, jclass clazz, jlong command_queue, jlong function_pointer) { clEnqueueBarrierPROC clEnqueueBarrier = (clEnqueueBarrierPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueBarrier((cl_command_queue)(intptr_t)command_queue); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclEnqueueWaitForEvents(JNIEnv *env, jclass clazz, jlong command_queue, jint num_events, jlong event_list, jlong function_pointer) { const cl_event *event_list_address = (const cl_event *)(intptr_t)event_list; clEnqueueWaitForEventsPROC clEnqueueWaitForEvents = (clEnqueueWaitForEventsPROC)((intptr_t)function_pointer); cl_int __result = clEnqueueWaitForEvents((cl_command_queue)(intptr_t)command_queue, num_events, event_list_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclGetEventProfilingInfo(JNIEnv *env, jclass clazz, jlong event, jint param_name, jlong param_value_size, jlong param_value, jlong param_value_size_ret, jlong function_pointer) { cl_void *param_value_address = (cl_void *)(intptr_t)param_value; size_t *param_value_size_ret_address = (size_t *)(intptr_t)param_value_size_ret; clGetEventProfilingInfoPROC clGetEventProfilingInfo = (clGetEventProfilingInfoPROC)((intptr_t)function_pointer); cl_int __result = clGetEventProfilingInfo((cl_event)(intptr_t)event, param_name, param_value_size, param_value_address, param_value_size_ret_address); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclFlush(JNIEnv *env, jclass clazz, jlong command_queue, jlong function_pointer) { clFlushPROC clFlush = (clFlushPROC)((intptr_t)function_pointer); cl_int __result = clFlush((cl_command_queue)(intptr_t)command_queue); return __result; } JNIEXPORT jint JNICALL Java_org_lwjgl_opencl_CL10_nclFinish(JNIEnv *env, jclass clazz, jlong command_queue, jlong function_pointer) { clFinishPROC clFinish = (clFinishPROC)((intptr_t)function_pointer); cl_int __result = clFinish((cl_command_queue)(intptr_t)command_queue); return __result; } JNIEXPORT jlong JNICALL Java_org_lwjgl_opencl_CL10_nclGetExtensionFunctionAddress(JNIEnv *env, jclass clazz, jlong func_name, jlong function_pointer) { const cl_char *func_name_address = (const cl_char *)(intptr_t)func_name; clGetExtensionFunctionAddressPROC clGetExtensionFunctionAddress = (clGetExtensionFunctionAddressPROC)((intptr_t)function_pointer); void * __result = clGetExtensionFunctionAddress(func_name_address); return (intptr_t)__result; }
<filename>src/extractor/extractEffects.ts import extractorInterface from '@typings/extractorInterface' import { effectPropertyInterface } from '@typings/propertyObject' import { EffectType, UnitTypePixel, PropertyType } from '@typings/valueTypes' import { tokenTypes } from '@config/tokenTypes' import { roundRgba } from '../utilities/convertColor' import { tokenCategoryType } from '@typings/tokenCategory' import { tokenExportKeyType } from '@typings/tokenExportKey' import config from '@config/config' const effectType = { LAYER_BLUR: 'layerBlur', BACKGROUND_BLUR: 'backgroundBlur', DROP_SHADOW: 'dropShadow', INNER_SHADOW: 'innerShadow' } const blurValues = (effect) => ({ effectType: { value: effectType[effect.type] as EffectType, type: 'string' as PropertyType }, radius: { value: effect.radius, unit: 'pixel' as UnitTypePixel, type: 'number' as PropertyType } }) const shadowValues = effect => ({ effectType: { value: effectType[effect.type] as EffectType, type: 'string' as PropertyType }, radius: { value: effect.radius, unit: 'pixel' as UnitTypePixel, type: 'number' as PropertyType }, color: { value: roundRgba(effect.color), type: 'color' as PropertyType }, offset: { x: { value: effect.offset.x, unit: 'pixel' as UnitTypePixel, type: 'number' as PropertyType }, y: { value: effect.offset.y, unit: 'pixel' as UnitTypePixel, type: 'number' as PropertyType } }, spread: { value: effect.spread, unit: 'pixel' as UnitTypePixel, type: 'number' as PropertyType } }) const extractEffects: extractorInterface = (tokenNodes: EffectStyle[], prefixArray: string[]): effectPropertyInterface[] => { // get effect styles return tokenNodes // remove tokens with no grid .filter(node => node.effects.length > 0) // build .map(node => ({ name: `${prefixArray[0]}/${node.name}`, category: 'effect' as tokenCategoryType, exportKey: tokenTypes.effect.key as tokenExportKeyType, description: node.description || null, values: node.effects.map( (effect: Effect) => effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR' ? blurValues(effect) : shadowValues(effect) ), extensions: { [config.key.extensionPluginData]: { [config.key.extensionFigmaStyleId]: node.id, exportKey: tokenTypes.effect.key as tokenExportKeyType } } })) } export default extractEffects
import Token from '../src/token'; describe('Token', () => { describe('constructer', () => { test('new Token', () => { const i = new Token('INT', '10'); expect(i.Type).toBe('INT'); expect(i.Literal).toBe('10'); expect(Token.TOKEN_TYPE.COMMA).toBe(','); }); }); describe('static LookupIdent', () => { test('Token.LookupIdent("c")', () => { expect(typeof Token.LookupIdent).toBe('function'); expect(Token.LookupIdent('ident')).toBe(Token.TOKEN_TYPE.IDENT); const expectation = { 'as': Token.TOKEN_TYPE.AS, 'import': Token.TOKEN_TYPE.IMPORT, 'fn': Token.TOKEN_TYPE.FUNCTION, 'while': Token.TOKEN_TYPE.WHILE, 'for': Token.TOKEN_TYPE.FOR, 'let': Token.TOKEN_TYPE.LET, 'true': Token.TOKEN_TYPE.TRUE, 'false': Token.TOKEN_TYPE.FALSE, 'if': Token.TOKEN_TYPE.IF, 'else': Token.TOKEN_TYPE.ELSE, 'return': Token.TOKEN_TYPE.RETURN, 'and': Token.TOKEN_TYPE.LAND, 'or': Token.TOKEN_TYPE.LOR }; const keys = Object.keys(expectation); for(const key of keys){ expect(Token.LookupIdent(key)).toBe(expectation[key]); } }); }); describe('Type', () => { test('get this[_type]', () => { const i = new Token('INT', '10'); expect(i.Type).toBe('INT'); }); }); describe('Literal', () => { test('get this[_literal]', () => { const i = new Token('INT', '10'); expect(i.Literal).toBe('10'); }); }); describe('toString', () => { test('string expression', () => { const i = new Token('INT', '10'); const str = `${i}`; expect(str).toBe('Token { type: \'INT\', literal: \'10\' }'); }); }); });
package plex import ( "encoding/xml" "errors" "io/ioutil" "net/http" "strconv" ) const plexTVURL = "https://plex.tv" const clientIdentifier = "plextrack" type devicesResp struct { XMLName xml.Name `xml:"MediaContainer"` PublicAddress HTTPURL `xml:"publicAddress,attr"` Devices []Device `xml:"Device"` } type sessionsResp struct { XMLName xml.Name `xml:"MediaContainer"` Videos []Video `xml:"Video"` } // Hook to override for tests var client = http.DefaultClient func GetUser(username, password string) (User, error) { req, err := http.NewRequest("POST", plexTVURL+"/users/sign_in.xml", nil) if err != nil { return User{}, err } req.SetBasicAuth(username, password) req.Header.Add("X-Plex-Client-Identifier", clientIdentifier) resp, err := fetchContent(req, http.StatusCreated) if err != nil { return User{}, err } user := User{} err = xml.Unmarshal(resp, &user) if err != nil { return User{}, err } return user, nil } func (user User) GetDevices() ([]Device, error) { req, err := http.NewRequest("GET", plexTVURL+"/devices.xml", nil) if err != nil { return nil, err } req.Header.Add("X-Plex-Client-Identifier", clientIdentifier) req.Header.Add("X-Plex-Token", user.AuthToken) content, err := fetchContent(req, http.StatusOK) resp := &devicesResp{} err = xml.Unmarshal(content, resp) if err != nil { return nil, err } for i := range resp.Devices { resp.Devices[i].Owner = user } return resp.Devices, nil } func (user User) GetServers() ([]Server, error) { devices, err := user.GetDevices() if err != nil { return nil, err } var servers []Server for _, device := range devices { server, err := device.toServer() if err == nil { servers = append(servers, server) } } return servers, nil } func (server Server) GetActivity() ([]Video, error) { server.PublicAddress.Path = "/status/sessions" req, err := http.NewRequest("GET", server.PublicAddress.String(), nil) if err != nil { return nil, err } req.Header.Add("X-Plex-Client-Identifier", clientIdentifier) req.Header.Add("X-Plex-Token", server.Owner.AuthToken) resp, err := fetchContent(req, http.StatusOK) if err != nil { return nil, err } container := &sessionsResp{} if err := xml.Unmarshal(resp, container); err != nil { return nil, err } return container.Videos, nil } func fetchContent(req *http.Request, expectedStatusCode int) ([]byte, error) { resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != expectedStatusCode { return nil, errors.New("Received status: " + strconv.Itoa(resp.StatusCode) + " expected status: " + strconv.Itoa(expectedStatusCode)) } contents, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return contents, nil }
def string_to_int(str) int = 0 str.each_char do |char| int = int * 10 + char.to_i end int end string_to_int("12345") # returns 12345
import { Component, OnInit } from '@angular/core'; import { SubAnswer } from './answer' @Component({ selector: 'qaa-answer-form', templateUrl: './answer-form.component.html', styleUrls: ['./answer-form.component.css'] }) export class AnswerFormComponent implements OnInit { submitted = false; model = new SubAnswer({}); constructor() { } ngOnInit() { } onSubmit() { this.submitted = true; } newAnswer(data) { this.model = new SubAnswer(data); } get diagnostic() { return JSON.stringify(this.model); } }
#ifndef INCLUDED_MAP_ROOM_START_PROPERTY_H #define INCLUDED_MAP_ROOM_START_PROPERTY_H #include "core/map/level_generator/i_property.h" #include "platform/i_platform.h" #include "entrance_type.h" namespace map { class RoomStartProperty : public IProperty { public: DEFINE_ROOM_PROPERTY_BASE(RoomStartProperty) RoomStartProperty( int32_t Id ); virtual void Load( Json::Value& setters ); virtual void Save( Json::Value& setters ) const; typedef std::vector<int32_t> Targets_t; void SetTargets( Targets_t blockedTargets ); Targets_t const& GetTargets() const; virtual void Generate( RoomDesc& roomDesc, MapElementHolder& mMapElementHolder, glm::vec2 pos, bool editor = false ); private: Targets_t mTargets; }; } // namespace map #endif//INCLUDED_MAP_ROOM_START_PROPERTY_H //command: "classgenerator.exe" -g "map_element" -c "cell_entrance_property" -p "property" -n "map" -m "int32_t-x int32_t-y EntranceType::Type-type Targets_t-blockedTargets Targets_t-entranceTargets"
<filename>src/com/cnblogs/honoka/utils/ToolsUtil.java package com.cnblogs.honoka.utils; import static java.lang.System.*; /** * 常用功能 * @author honoka */ public class ToolsUtil { /** * 判断对象是否非空 * @author honoka * @param obj * @return */ public static boolean isNotEmpty(Object obj) { return (null != obj)&&(!"".equals(obj.toString())); } }
#!/bin/bash mkdir -p australia-oceania CONTOURS=skip ./build.sh australia-oceania australia CONTOURS=1sec ./build.sh australia-oceania fiji CONTOURS=1sec ./build.sh australia-oceania new-caledonia CONTOURS=3sec ./build.sh australia-oceania new-zealand ./gc.sh
public class Quicksort { public static void sort(int[] array, int left, int right) { if (left < right) { // set pivot int pivot = array[right]; // index indicates how many values in array are small than pivot int index = left; for (int i = left; i < right; i++) { if (array[i] <= pivot) { swap(array, index, i); index++; } } swap(array, index, right); // sort left and right subarray sort(array, left, index - 1); sort(array, index + 1, right); } } public static void swap(int[] array, int i, int j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } }
<reponame>nairihar/zeronode<gh_stars>100-1000 export default { CLIENT_MUST_HEARTBEAT_INTERVAL: 6000, CLIENT_PING_INTERVAL: 2000 }
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class UserService { constructor(private http: Http) { } getUsers(){ return this.http.get("http://jsonplaceholder.typicode.com/users").map(res=>res.json()); } getMovie(movieName:any){ return this.http.get("http://www.omdbapi.com/?t="+movieName).map(res=>res.json()); } }
<reponame>koolamusic/remix-project<filename>libs/remix-ui/workspace/src/index.ts export * from './lib/remix-ui-workspace'
#!/bin/bash # # Script to fetch generated API references docs from the Android build server and stage them. source gbash.sh || exit readonly defaultDb="" DEFINE_string buildId --required "" "The build ID from the Android build server" DEFINE_string dateStr "<insert date here>" "Date string used for CL message. Enclose date in double quotes (ex: \"April 29, 2021\")" DEFINE_string db "$defaultDb" "The database used for staging. Omitting this value will stage changes to the staging DB." DEFINE_bool useToT false "Stage docs from tip-of-tree docs build rather than public docs build" gbash::init_google "$@" # Allowlist for including specific directories being generated by Dackka. # # There are separate lists for Java and Kotlin refdocs as some libraries (such # as Compose) only publish refdocs for a single language. # # Each directory's spelling must match the library's directory in # frameworks/support. # # This list should match, or be a subset of, the list of libraries defined in # https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:buildSrc/src/main/kotlin/androidx/build/docs/AndroidXDocsPlugin.kt;l=568 readonly javaLibraryDirs=( # "benchmark" # "collection" "navigation" "paging" "window" ) readonly kotlinLibraryDirs=( # "benchmark" "compose" # "collection" "navigation" # "paging" "window" ) # Change directory to this script's location and store the directory cd "$(dirname $0)" scriptDirectory=$(pwd) # Working directories for the refdocs outDir="$scriptDirectory/out" readonly newDir="reference-docs" readonly dackkaNewDir="reference-docs-dackka" # Remove and recreate the existing out directory to avoid conflicts from previous runs rm -rf $outDir mkdir -p $outDir/$newDir mkdir -p $outDir/$dackkaNewDir cd $outDir printf "=================================================================== \n" printf "== Download the doc zip files from the build server \n" printf "=================================================================== \n" if (( FLAGS_useToT )); then printf "Downloading docs-tip-of-tree zip files \n" androidxJavaDocsZip="doclava-tip-of-tree-docs-${FLAGS_buildId}.zip" androidxKotlinDocsZip="dokka-tip-of-tree-docs-${FLAGS_buildId}.zip" androidxDackkaDocsZip="dackka-tip-of-tree-docs-${FLAGS_buildId}.zip" else printf "Downloading docs-public zip files \n" androidxJavaDocsZip="doclava-public-docs-${FLAGS_buildId}.zip" androidxKotlinDocsZip="dokka-public-docs-${FLAGS_buildId}.zip" androidxDackkaDocsZip="dackka-public-docs-${FLAGS_buildId}.zip" fi /google/data/ro/projects/android/fetch_artifact --bid $FLAGS_buildId --target androidx $androidxJavaDocsZip /google/data/ro/projects/android/fetch_artifact --bid $FLAGS_buildId --target androidx $androidxKotlinDocsZip /google/data/ro/projects/android/fetch_artifact --bid $FLAGS_buildId --target androidx $androidxDackkaDocsZip printf "\n" printf "=================================================================== \n" printf "== Unzip the doc zip files \n" printf "=================================================================== \n" unzip $androidxJavaDocsZip -d $newDir unzip $androidxKotlinDocsZip -d $newDir unzip $androidxDackkaDocsZip -d $dackkaNewDir printf "\n" printf "=================================================================== \n" printf "== Format the doc zip files \n" printf "=================================================================== \n" cd $newDir # Remove directories we never publish rm en -rf rm reference/android -rf rm reference/java -rf rm reference/org -rf rm reference/hierarchy.html rm reference/kotlin/org -rf rm reference/kotlin/android -rf # Move package list into the correct location mv reference/kotlin/package-list reference/kotlin/androidx/package-list # Remove javascript files that have no use rm -f reference/androidx/lists.js rm -f reference/androidx/navtree_data.js # Remove extraneous _book.yaml that improperly overwrites the correct one rm -f reference/androidx/_book.yaml printf "\n" printf "=================================================================== \n" printf "== Generate the language switcher \n" printf "=================================================================== \n" # The switcher script still requires python2 to run correctly cd reference python2 ./../../../switcher.py --work androidx printf "\n" printf "=================================================================== \n" printf "== Copy over Dackka generated refdocs \n" printf "=================================================================== \n" # Dackka adds the language switcher during generation, so the Dackka directories # should be copied over after the switcher.py runs - otherwise the contents in # the Dackka directories will contain a duplicate language switcher. cd $outDir for dir in "${javaLibraryDirs[@]}" do printf "Copying Java refdocs for $dir\n" cp -r $dackkaNewDir/reference/androidx/$dir $newDir/reference/androidx/ done for dir in "${kotlinLibraryDirs[@]}" do printf "Copying Kotlin refdocs for $dir\n" cp -r $dackkaNewDir/reference/kotlin/androidx/$dir $newDir/reference/kotlin/androidx/ done printf "\n" printf "=================================================================== \n" printf "== Create (if needed) and sync g4 workspace \n" printf "=================================================================== \n" client="$(p4 g4d -f androidx-ref-docs-stage)" cd "$client" # Revert all local changes to prevent merge conflicts when syncing. # This is OK since we always want to start with a fresh CitC client g4 revert ... g4 sync # Temporarily skipping due to o/128063951. b/186655027 tracks adding this back. # TODO: check this logic when uncommenting # # Provision database if the target DB is not the default staging DB. # if [ "${FLAGS_db}" != "$defaultDb" ]; then # printf "\n" # printf "=================================================================== \n" # printf "== Provision staging database ${FLAGS_db} \n" # printf "=================================================================== \n" # # /google/data/ro/projects/devsite/devsite2 provision --db="${FLAGS_db}" # fi printf "\n" printf "=================================================================== \n" printf "== Prep directories and copy refdocs to CitC client \n" printf "=================================================================== \n" cd third_party/devsite/android/en/reference cd kotlin/androidx ls | grep -v "package\|class\|book\|toc\|constraint\|test\|index" | xargs -I {} rm -rf {} cd ../../androidx ls | grep -v "package\|class\|book\|toc\|constraint\|test\|index" | xargs -I {} rm -rf {} cd .. cp -r $outDir/$newDir/reference/* . printf "\n" printf "=================================================================== \n" printf "== Create a changelist of pending refdoc changes \n" printf "=================================================================== \n" stagingLinkJava="go/dac-stage/reference/androidx/packages" stagingLinkKotlin="go/dac-stage/reference/kotlin/androidx/packages" # Add the db param to links if the target database is not the default staging DB. if [ "$FLAGS_db" != "$defaultdb" ]; then stagingLinkJava+="?db=$FLAGS_db" stagingLinkKotlin+="?db=$FLAGS_db" fi # Construct CL description clDesc="Androidx $FLAGS_dateStr Ref Docs DO NOT SUBMIT GO LIVE TIME: $FLAGS_dateStr @ 10:00 AM PST Staged: * Java: $stagingLinkJava * Kotlin: $stagingLinkKotlin All docs build id: $FLAGS_buildId The following scripts were used to create these docs: https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:development/referenceDocs/ " # Grab the CL number generated from running `g4 change`. clNum=$(g4 change --desc "$clDesc" | tail -1 | awk '{print $2}') printf "View pending changes at http://cl/${clNum} \n" printf "\n" printf "=================================================================== \n" printf "== Stage changes \n" printf "=================================================================== \n" # Construct the devsite command and parameters devsiteCmd="/google/data/ro/projects/devsite/devsite2 stage" devsiteCmd+=" --parallelize_build" devsiteCmd+=" --use_large_thread_pools" devsiteCmd+=" --upload_safety_check_mode=ignore" # Add the --db flag if the target database is not the default staging DB. if [ "$FLAGS_db" != "$defaultDb" ]; then devsiteCmd+=" --db=$FLAGS_db" fi # Directories to stage devsiteCmd+=" androidx" devsiteCmd+=" kotlin/androidx" printf "Running devsite command:\n" printf "$devsiteCmd\n" $devsiteCmd # Print devsite command and CL link again in case they scrolled off the screen or # scrollback buffer printf "\n" printf "Ran devsite command:\n" printf "$devsiteCmd\n" printf "\n" printf "View pending changes at http://cl/${clNum} \n"
MAX_NODE=3 HOSTNAME_PREFIX="node-" YARN_RM="${HOSTNAME_PREFIX}0" YARN_RM_IP=10.1.1.2 YARN_RM_HOSTNAME="${HOSTNAME_PREFIX}0" HDFS_NN="${HOSTNAME_PREFIX}0" HDFS_NN_IP=10.1.1.2 CLIENT_NODE="${HOSTNAME_PREFIX}0" SLAVES_FILE="$PSBIN/ucare_se_conf/hadoop-etc/hadoop-2.7.1/slaves" #SLAVES_FILE=/proj/ucare/git/hadoop-ucare/psbin/mini-slaves
<reponame>chlds/util<filename>lib/car/obj/src/cv_spcr.c<gh_stars>0 /* **** Notes Replace CR with SP. */ # define CAR # include <stdio.h> # include "./../../../incl/config.h" signed(__cdecl cv_spcr(signed char(*argp))) { auto signed char *b; auto signed i,r; if(!argp) return(0x00); return(cv_ds_f(argp,SP,CR)); }
<filename>src/background/actions/tab-stop-requirement-actions.ts // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. import { Action } from 'common/flux/action'; import { AddTabStopInstancePayload, RemoveTabStopInstancePayload, ResetTabStopRequirementStatusPayload, ToggleTabStopRequirementExpandPayload, UpdateTabStopInstancePayload, UpdateTabStopRequirementStatusPayload, } from './action-payloads'; export class TabStopRequirementActions { public readonly getCurrentState = new Action(); public readonly updateTabStopsRequirementStatus = new Action<UpdateTabStopRequirementStatusPayload>(); public readonly addTabStopInstance = new Action<AddTabStopInstancePayload>(); public readonly updateTabStopInstance = new Action<UpdateTabStopInstancePayload>(); public readonly removeTabStopInstance = new Action<RemoveTabStopInstancePayload>(); public readonly resetTabStopRequirementStatus = new Action<ResetTabStopRequirementStatusPayload>(); public readonly toggleTabStopRequirementExpand = new Action<ToggleTabStopRequirementExpandPayload>(); }
/* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package tests.unit.com.microsoft.azure.sdk.iot.service.auth; import com.microsoft.azure.sdk.iot.service.auth.SymmetricKey; import mockit.Deencapsulation; import mockit.integration.junit4.JMockit; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(JMockit.class) public class SymmetricKeyTest { // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_001: [The function shall throw IllegalArgumentException if the length of the key less than 16 or greater than 64] // Assert @Test (expected = IllegalArgumentException.class) public void setPrimaryKey_length_less_than_16() { // Arrange String key = "012345678901234"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setPrimaryKey(key); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_001: [The function shall throw IllegalArgumentException if the length of the key less than 16 or greater than 64] // Assert @Test (expected = IllegalArgumentException.class) public void setPrimaryKey_length_greater_than_64() { // Arrange String key = "01234567890123456789012345678901234567890123456789012345678901234"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setPrimaryKey(key); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_002: [The function shall set the private primaryKey member to the given value if the length validation passed] @Test public void setPrimaryKey_length_good_case_min() { // Arrange String key = "0123456789012345"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setPrimaryKey(key); // Assert assertEquals(key, Deencapsulation.getField(symmetricKey, "primaryKey")); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_002: [The function shall set the private primaryKey member to the given value if the length validation passed] @Test public void setPrimaryKey_length_good_case_max() { // Arrange String key = "0123456789012345678901234567890123456789012345678901234567890123"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setPrimaryKey(key); // Assert assertEquals(key, Deencapsulation.getField(symmetricKey, "primaryKey")); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_003: [The function shall throw IllegalArgumentException if the length of the key less than 16 or greater than 64] // Assert @Test (expected = IllegalArgumentException.class) public void setSecondaryKey_length_less_than_16() { // Arrange String key = "012345678901234"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setSecondaryKey(key); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_003: [The function shall throw IllegalArgumentException if the length of the key less than 16 or greater than 64] // Assert @Test (expected = IllegalArgumentException.class) public void setSecondaryKey_length_greater_than_64() { // Arrange String key = "01234567890123456789012345678901234567890123456789012345678901234"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setSecondaryKey(key); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_003: [The function shall throw IllegalArgumentException if the length of the key less than 16 or greater than 64] @Test public void setSecondaryKey_length_good_case_min() { // Arrange String key = "0123456789012345"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setSecondaryKey(key); // Assert assertEquals(key, Deencapsulation.getField(symmetricKey, "secondaryKey")); } // Tests_SRS_SERVICE_SDK_JAVA_SYMMETRICKEY_12_003: [The function shall throw IllegalArgumentException if the length of the key less than 16 or greater than 64] @Test public void setSecondaryKey_length_good_case_max() { // Arrange String key = "0123456789012345678901234567890123456789012345678901234567890123"; SymmetricKey symmetricKey = new SymmetricKey(); // Act symmetricKey.setSecondaryKey(key); // Assert assertEquals(key, Deencapsulation.getField(symmetricKey, "secondaryKey")); } }
public class MaxValueFinder { public static int findMaxValue(int[] arr) { int v = Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { if (arr[i] > v) { v = arr[i]; } } return v; } }
package malte0811.controlengineering.gui.tape; import it.unimi.dsi.fastutil.bytes.ByteConsumer; import malte0811.controlengineering.blockentity.tape.KeypunchBlockEntity; import malte0811.controlengineering.blockentity.tape.KeypunchState; import malte0811.controlengineering.gui.CEContainerMenu; import malte0811.controlengineering.gui.misc.LambdaDataSlot; import malte0811.controlengineering.network.SimplePacket; import malte0811.controlengineering.network.keypunch.FullSync; import malte0811.controlengineering.network.keypunch.KeypunchPacket; import malte0811.controlengineering.network.keypunch.KeypunchSubPacket; import malte0811.controlengineering.network.keypunch.TypeChar; import net.minecraft.world.inventory.DataSlot; import net.minecraft.world.inventory.MenuType; import java.util.HashSet; import java.util.Set; public class KeypunchMenu extends CEContainerMenu<KeypunchSubPacket> { private final KeypunchState state; private final ByteConsumer printNonLoopback; private final DataSlot isLoopback; private final Set<KeypunchMenu> openMenus; public KeypunchMenu(MenuType<?> type, int id, KeypunchBlockEntity keypunch) { super(type, id, isValidFor(keypunch), keypunch::setChanged); this.state = keypunch.getState(); this.printNonLoopback = keypunch::queueForRemotePrint; this.isLoopback = addDataSlot(LambdaDataSlot.serverSide(() -> keypunch.isLoopback() ? 1 : 0)); this.openMenus = keypunch.getOpenContainers(); } public KeypunchMenu(MenuType<?> type, int id) { super(type, id); this.state = new KeypunchState(() -> {}); this.printNonLoopback = $ -> {}; this.isLoopback = addDataSlot(DataSlot.standalone()); this.openMenus = new HashSet<>(); } @Override protected SimplePacket makePacket(KeypunchSubPacket data) { return new KeypunchPacket(data); } @Override protected KeypunchSubPacket getInitialSync() { return new FullSync(state.getAvailable(), state.getData().toByteArray()); } public KeypunchState getState() { return state; } public boolean isLoopback() { return isLoopback.get() != 0; } public void onTypedOnServer(byte data) { sendToListeningPlayers(new TypeChar(data)); } public void resyncFullTape() { sendToListeningPlayers(getInitialSync()); } @Override protected void onFirstOpened() { super.onFirstOpened(); openMenus.add(this); } @Override protected void onLastClosed() { super.onLastClosed(); openMenus.remove(this); } public ByteConsumer getPrintNonLoopback() { return printNonLoopback; } }
<filename>LeetCodeSolutions/345 - Reverse Vowels of a String(easy) - Java.java class Solution { public String reverseVowels(String s) { int i = -1; int j = s.length(); char[] chs = s.toCharArray(); while (i < j) { while ( ++ i < j && !isVowel(chs[i])); while (i < --j && !isVowel(chs[j])); // swap if (i < j) { char tmp = chs[i]; chs[i] = chs[j]; chs[j] = tmp; } } return String.valueOf(chs); } public boolean isVowel(char ch) { return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'; } }
puts( "hello".reverse ) class String remove_method( :reverse ) end puts( "hello".reverse )
<reponame>yahuli/ureport /** * Created by Jacky.Gao on 2017-01-25. */ import Tool from './Tool.js'; import SaveDialog from '../dialog/SaveDialog.js'; import {alert} from '../MsgBox.js'; import {resetDirty,tableToXml} from '../Utils.js'; import {getToken} from '../Utils.js' export default class SaveTool extends Tool{ execute(){ } buildButton(){ const group=$(`<div class="btn-group"></div>`); const mainBtn=$(`<button type="button" class="btn btn-default dropdown-toggle" style="border:none;border-radius:0;background: #f8f8f8;padding: 6px 8px;" data-toggle="dropdown" title="${window.i18n.tools.save.save}"> <i class="ureport ureport-save" style="color: #0e90d2;"></i> <span class="caret"></span> </button>`); const ul=$(`<ul class="dropdown-menu" role="menu"></ul>`); const save=$(`<li id="__save_btn" class="disabled"> <a href="###"> <i class="ureport ureport-save" style="color: #0e90d2;"></i> ${window.i18n.tools.save.save} </a> </li>`); ul.append(save); const saveDialog=new SaveDialog(); const _this=this; save.click(function(){ const content=tableToXml(_this.context); if(window._reportFile){ $.ajax({ url:window._server+"/designer/saveReportFile", headers: { Authorization: getToken() }, data:{content,file:window._reportFile}, type:'POST', success:function(){ alert(`${window.i18n.tools.save.successSave}`); resetDirty(); }, error:function(response){ if(response && response.responseText){ alert("服务端错误:"+response.responseText+""); }else{ alert(`${window.i18n.tools.save.failSave}`); } } }); }else{ saveDialog.show(content,_this.context); } }); const saveAs=$(`<li> <a href="###"> <i class="glyphicon glyphicon-floppy-disk" style="color: #0e90d2;font-size: 16px"></i> ${window.i18n.tools.save.saveAs} </a> </li>`); ul.append(saveAs); saveAs.click(function(){ const content=tableToXml(_this.context); saveDialog.show(content,_this.context); }); group.append(mainBtn); group.append(ul); return group; } getTitle(){ return `${window.i18n.tools.save.save}`; } getIcon(){ return `<i class="ureport ureport-save" style="color: #0e90d2"></i>`; } }
package encoding import ( "io" ) type ConstDecoder int32 func (d ConstDecoder) Init(_ io.Reader) error { return nil } func (d ConstDecoder) InitSize(_ io.Reader) error { return nil } func (d ConstDecoder) Next() (int32, error) { return int32(d), nil }
var dir_5bee762cfd03f62aa80233ed05f1bfdf = [ [ "AddDebug.hpp", "_add_debug_8hpp.xhtml", "_add_debug_8hpp" ], [ "All.hpp", "_all_8hpp.xhtml", null ], [ "ConvertConstants.hpp", "_convert_constants_8hpp.xhtml", "_convert_constants_8hpp" ], [ "ConvertFp32NetworkToFp16.hpp", "_convert_fp32_network_to_fp16_8hpp.xhtml", "_convert_fp32_network_to_fp16_8hpp" ], [ "FoldPadIntoConvolution2d.hpp", "_fold_pad_into_convolution2d_8hpp.xhtml", "_fold_pad_into_convolution2d_8hpp" ], [ "MovePermuteUp.hpp", "_move_permute_up_8hpp.xhtml", "_move_permute_up_8hpp" ], [ "MoveTransposeUp.hpp", "_move_transpose_up_8hpp.xhtml", "_move_transpose_up_8hpp" ], [ "Optimization.hpp", "_optimization_8hpp.xhtml", [ [ "Optimization", "classarmnn_1_1_optimization.xhtml", "classarmnn_1_1_optimization" ], [ "OptimizeForTypeImpl", "classarmnn_1_1_optimize_for_type_impl.xhtml", "classarmnn_1_1_optimize_for_type_impl" ], [ "OptimizeForTypeImpl< Layer, Wrapped >", "classarmnn_1_1_optimize_for_type_impl_3_01_layer_00_01_wrapped_01_4.xhtml", "classarmnn_1_1_optimize_for_type_impl_3_01_layer_00_01_wrapped_01_4" ], [ "OptimizeForType", "classarmnn_1_1_optimize_for_type.xhtml", null ], [ "OptimizeForConnectionImpl", "classarmnn_1_1_optimize_for_connection_impl.xhtml", "classarmnn_1_1_optimize_for_connection_impl" ], [ "OptimizeForConnection", "classarmnn_1_1_optimize_for_connection.xhtml", null ] ] ], [ "OptimizeConsecutiveReshapes.hpp", "_optimize_consecutive_reshapes_8hpp.xhtml", "_optimize_consecutive_reshapes_8hpp" ], [ "OptimizeInverseConversions.hpp", "_optimize_inverse_conversions_8hpp.xhtml", "_optimize_inverse_conversions_8hpp" ], [ "OptimizeInversePermutes.hpp", "_optimize_inverse_permutes_8hpp.xhtml", "_optimize_inverse_permutes_8hpp" ], [ "PermuteAndBatchToSpaceAsDepthToSpace.hpp", "_permute_and_batch_to_space_as_depth_to_space_8hpp.xhtml", "_permute_and_batch_to_space_as_depth_to_space_8hpp" ], [ "PermuteAsReshape.hpp", "_permute_as_reshape_8hpp.xhtml", "_permute_as_reshape_8hpp" ], [ "SquashEqualSiblings.hpp", "_squash_equal_siblings_8hpp.xhtml", "_squash_equal_siblings_8hpp" ], [ "TransposeAsReshape.hpp", "_transpose_as_reshape_8hpp.xhtml", "_transpose_as_reshape_8hpp" ] ];
package resolvers import ( "github.com/bradpurchase/grocerytime-backend/internal/pkg/auth" "github.com/bradpurchase/grocerytime-backend/internal/pkg/stores" "github.com/graphql-go/graphql" ) // JoinStoreWithShareCodeResolver resolves the joinStoreWithShareCode mutation func JoinStoreWithShareCodeResolver(p graphql.ResolveParams) (interface{}, error) { header := p.Info.RootValue.(map[string]interface{})["Authorization"] user, err := auth.FetchAuthenticatedUser(header.(string)) if err != nil { return nil, err } appScheme := p.Info.RootValue.(map[string]interface{})["App-Scheme"] code := p.Args["code"].(string) storeUser, err := stores.AddUserToStoreWithCode(user, code, appScheme.(string)) if err != nil { return nil, err } return storeUser, nil }
package net.ninjacat.omg.conditions; import net.ninjacat.omg.errors.ConditionException; import org.junit.Test; import static junit.framework.TestCase.fail; public class ConditionsTest { @Test(expected = ConditionException.class) public void shouldNotAllowMoreThanOneChildForNot() { Conditions.matcher().not(n -> n .property("a").lt(10) .property("b").eq(1) ).build(); } @Test public void shouldIgnoreTypesAndOperations() { try { Conditions.matcher().property("stringProp").gt("some string").build(); } catch (final Exception ex) { fail("Should not have failed"); } } }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _objectAssign = require('object-assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _posthtml = require('posthtml'); var _posthtml2 = _interopRequireDefault(_posthtml); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Array of all enabled modules var defaultOptions = { removeComments: 'safe', removeEmptyAttributes: true, removeRedundantAttributes: false, collapseWhitespace: 'conservative', collapseBooleanAttributes: true, mergeStyles: true, mergeScripts: true, minifyCss: { safe: true }, minifyJs: {}, minifyJson: {}, minifySvg: {}, custom: [] }; function htmlnano() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return function minifier(tree) { options = (0, _objectAssign2.default)({}, defaultOptions, options); var promise = Promise.resolve(tree); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { var _loop = function _loop() { var moduleName = _step.value; if (!options[moduleName]) { // The module is disabled return 'continue'; } if (defaultOptions[moduleName] === undefined) { throw new Error('Module "' + moduleName + '" is not defined'); } var module = require('./modules/' + moduleName); promise = promise.then(function (tree) { return module.default(tree, options, options[moduleName]); }); }; for (var _iterator = Object.keys(options)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _ret = _loop(); if (_ret === 'continue') continue; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return promise; }; } htmlnano.process = function (html, options) { return (0, _posthtml2.default)([htmlnano(options)]).process(html); }; htmlnano.defaultOptions = defaultOptions; exports.default = htmlnano;
import React from 'react'; export default class ArrowDown extends React.Component { render() { const { width, height, color } = this.props; return ( <svg width={width} height={height} viewBox="0 0 140 140" version="1.1" > <g id="Icons" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd"> <g transform="translate(-4057.000000, -56.000000)" fill={color} fillRule="nonzero" id="right-copy"> <g transform="translate(4127.000000, 126.000000) rotate(90.000000) translate(-4127.000000, -126.000000) translate(4099.000000, 56.000000)"> <path d="M12.3421053,1.12253289 L53.6513158,64.5139803 C56.7598684,67.5534539 56.7598684,72.4350329 53.6513158,75.4514803 L12.3421053,138.865954 C10.7993421,140.362664 8.28947368,140.362664 6.74671053,138.865954 L1.17434211,133.385691 C-0.391447368,131.88898 -0.391447368,129.448191 1.17434211,127.928454 L39.6743421,72.7574013 C41.2401316,71.2376645 41.2401316,68.7738487 39.6743421,67.2541118 L1.17434211,12.0370066 C-0.391447368,10.5633224 -0.391447368,8.09950658 1.17434211,6.57976974 L6.76973684,1.12253289 C8.28947368,-0.374177632 10.7993421,-0.374177632 12.3421053,1.12253289 Z" id="Shape"></path> </g> </g> </g> </svg> ) } }
<filename>matchbox/storage/storagepb/storage.pb.go // Code generated by protoc-gen-go. // source: storage.proto // DO NOT EDIT! /* Package storagepb is a generated protocol buffer package. It is generated from these files: storage.proto It has these top-level messages: Group Profile NetBoot */ package storagepb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Group selects one or more machines and matches them to a Profile. type Group struct { // machine readable Id Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` // human readable name Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` // Profile id Profile string `protobuf:"bytes,3,opt,name=profile" json:"profile,omitempty"` // Selectors to match machines Selector map[string]string `protobuf:"bytes,4,rep,name=selector" json:"selector,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // JSON encoded metadata Metadata []byte `protobuf:"bytes,5,opt,name=metadata,proto3" json:"metadata,omitempty"` } func (m *Group) Reset() { *m = Group{} } func (m *Group) String() string { return proto.CompactTextString(m) } func (*Group) ProtoMessage() {} func (*Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Group) GetId() string { if m != nil { return m.Id } return "" } func (m *Group) GetName() string { if m != nil { return m.Name } return "" } func (m *Group) GetProfile() string { if m != nil { return m.Profile } return "" } func (m *Group) GetSelector() map[string]string { if m != nil { return m.Selector } return nil } func (m *Group) GetMetadata() []byte { if m != nil { return m.Metadata } return nil } // Profile defines the boot and provisioning behavior of a group of machines. type Profile struct { // profile id Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` // human readable name Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` // ignition id IgnitionId string `protobuf:"bytes,3,opt,name=ignition_id,json=ignitionId" json:"ignition_id,omitempty"` // cloud config id CloudId string `protobuf:"bytes,4,opt,name=cloud_id,json=cloudId" json:"cloud_id,omitempty"` // support network boot / PXE Boot *NetBoot `protobuf:"bytes,5,opt,name=boot" json:"boot,omitempty"` // generic config id GenericId string `protobuf:"bytes,6,opt,name=generic_id,json=genericId" json:"generic_id,omitempty"` } func (m *Profile) Reset() { *m = Profile{} } func (m *Profile) String() string { return proto.CompactTextString(m) } func (*Profile) ProtoMessage() {} func (*Profile) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *Profile) GetId() string { if m != nil { return m.Id } return "" } func (m *Profile) GetName() string { if m != nil { return m.Name } return "" } func (m *Profile) GetIgnitionId() string { if m != nil { return m.IgnitionId } return "" } func (m *Profile) GetCloudId() string { if m != nil { return m.CloudId } return "" } func (m *Profile) GetBoot() *NetBoot { if m != nil { return m.Boot } return nil } func (m *Profile) GetGenericId() string { if m != nil { return m.GenericId } return "" } // NetBoot describes network or PXE boot settings for a machine. type NetBoot struct { // the URL of the kernel image Kernel string `protobuf:"bytes,1,opt,name=kernel" json:"kernel,omitempty"` // the init RAM filesystem URLs Initrd []string `protobuf:"bytes,2,rep,name=initrd" json:"initrd,omitempty"` // kernel args Args []string `protobuf:"bytes,4,rep,name=args" json:"args,omitempty"` } func (m *NetBoot) Reset() { *m = NetBoot{} } func (m *NetBoot) String() string { return proto.CompactTextString(m) } func (*NetBoot) ProtoMessage() {} func (*NetBoot) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *NetBoot) GetKernel() string { if m != nil { return m.Kernel } return "" } func (m *NetBoot) GetInitrd() []string { if m != nil { return m.Initrd } return nil } func (m *NetBoot) GetArgs() []string { if m != nil { return m.Args } return nil } func init() { proto.RegisterType((*Group)(nil), "storagepb.Group") proto.RegisterType((*Profile)(nil), "storagepb.Profile") proto.RegisterType((*NetBoot)(nil), "storagepb.NetBoot") } func init() { proto.RegisterFile("storage.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 334 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x8c, 0x91, 0x4f, 0x4b, 0xf3, 0x40, 0x10, 0xc6, 0xc9, 0x9f, 0x36, 0xc9, 0xf4, 0xed, 0x4b, 0x19, 0x44, 0xd6, 0x82, 0x1a, 0x7a, 0x90, 0x9e, 0x72, 0xa8, 0x17, 0xa9, 0x37, 0x41, 0xa4, 0x1e, 0x44, 0xe2, 0x55, 0x90, 0x6d, 0x76, 0x0c, 0x4b, 0xd3, 0xdd, 0xb0, 0xdd, 0x0a, 0xfd, 0x56, 0x7e, 0x1e, 0x3f, 0x8d, 0x64, 0xbb, 0x2d, 0x7a, 0xf3, 0x36, 0xbf, 0x67, 0x27, 0x33, 0xcf, 0x33, 0x81, 0xe1, 0xc6, 0x6a, 0xc3, 0x6b, 0x2a, 0x5a, 0xa3, 0xad, 0xc6, 0xcc, 0x63, 0xbb, 0x9c, 0x7c, 0x05, 0xd0, 0x7b, 0x30, 0x7a, 0xdb, 0xe2, 0x7f, 0x08, 0xa5, 0x60, 0x41, 0x1e, 0x4c, 0xb3, 0x32, 0x94, 0x02, 0x11, 0x62, 0xc5, 0xd7, 0xc4, 0x42, 0xa7, 0xb8, 0x1a, 0x19, 0x24, 0xad, 0xd1, 0xef, 0xb2, 0x21, 0x16, 0x39, 0xf9, 0x80, 0x38, 0x87, 0x74, 0x43, 0x0d, 0x55, 0x56, 0x1b, 0x16, 0xe7, 0xd1, 0x74, 0x30, 0xbb, 0x28, 0x8e, 0x5b, 0x0a, 0xb7, 0xa1, 0x78, 0xf1, 0x0d, 0xf7, 0xca, 0x9a, 0x5d, 0x79, 0xec, 0xc7, 0x31, 0xa4, 0x6b, 0xb2, 0x5c, 0x70, 0xcb, 0x59, 0x2f, 0x0f, 0xa6, 0xff, 0xca, 0x23, 0x8f, 0x6f, 0x61, 0xf8, 0xeb, 0x33, 0x1c, 0x41, 0xb4, 0xa2, 0x9d, 0xf7, 0xd9, 0x95, 0x78, 0x02, 0xbd, 0x0f, 0xde, 0x6c, 0x0f, 0x4e, 0xf7, 0x30, 0x0f, 0x6f, 0x82, 0xc9, 0x67, 0x00, 0xc9, 0xb3, 0x37, 0xf8, 0x97, 0x78, 0x97, 0x30, 0x90, 0xb5, 0x92, 0x56, 0x6a, 0xf5, 0x26, 0x85, 0x8f, 0x08, 0x07, 0x69, 0x21, 0xf0, 0x0c, 0xd2, 0xaa, 0xd1, 0x5b, 0xd1, 0xbd, 0xc6, 0xfb, 0x03, 0x38, 0x5e, 0x08, 0xbc, 0x82, 0x78, 0xa9, 0xb5, 0x75, 0x01, 0x06, 0x33, 0xfc, 0x11, 0xfe, 0x89, 0xec, 0x9d, 0xd6, 0xb6, 0x74, 0xef, 0x78, 0x0e, 0x50, 0x93, 0x22, 0x23, 0xab, 0x6e, 0x48, 0xdf, 0x0d, 0xc9, 0xbc, 0xb2, 0x10, 0x93, 0x57, 0x48, 0x7c, 0x3f, 0x9e, 0x42, 0x7f, 0x45, 0x46, 0x51, 0xe3, 0x5d, 0x7b, 0xea, 0x74, 0xa9, 0xa4, 0x35, 0x82, 0x85, 0x79, 0xd4, 0xe9, 0x7b, 0xea, 0x12, 0x71, 0x53, 0x6f, 0xdc, 0xf9, 0xb3, 0xd2, 0xd5, 0x8f, 0x71, 0x1a, 0x8d, 0xe2, 0x32, 0xa9, 0xd6, 0xa2, 0x91, 0x8a, 0x96, 0x7d, 0xf7, 0xff, 0xaf, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x10, 0x74, 0x65, 0xd8, 0x10, 0x02, 0x00, 0x00, }
export const updateDemandCertificationCreate = (client: HTTPClient) => async ( parameters: CertificationRequestBody<INftUpdateDemand>, ): Promise<void> => { try { // Make an HTTP request to update the demand certification using the provided client and parameters const response = await client.post('/update-demand-certification', parameters); // Check if the request was successful if (response.status === 200) { console.log('Demand certification updated successfully'); } else { throw new Error('Failed to update demand certification'); } } catch (error) { console.error('Error updating demand certification:', error); throw error; } };
.MODEL SMALL .STACK 100h .DATA arr dw 2,4,6,8,10 ; array len dw 5 ; length of array max dw ? ; initial maximum .CODE ; find largest value in array MAIN PROC MOV AX, @DATA MOV DS, AX MOV CX, len MOV SI, 0 MOV max, 0 next: MOV AX, arr[SI] CMP AX, max JLE skip MOV max, AX skip: INC SI LOOP next MOV AH, 4ch INT 21h MAIN ENDP END MAIN
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'lib-post', template: '{{random}}', }) export class PostComponent { random = Math.random(); } @NgModule({ declarations: [PostComponent], exports: [PostComponent], }) export class PostModule { }
const connection = require('../database/connection'); const bcrypt = require('bcryptjs'); const generateToken = require('../utils/generateToken'); const verifyMail = require('../utils/verifyMail'); module.exports = { async create(req, res) { const { email, password } = req.body; const user = await connection('ong').where('email', email).select('password', 'name', 'id', 'verified').first(); try { if ((!user) || (!await bcrypt.compare(password, user.password))) { return res.status(401).send('Verify user and password') } if (user.verified === 0) { verifyMail(user.id, email); return res.status(403).send('User is not verified, check your email') } return res.json({name: user.name, token: generateToken({id: user.id})}) } catch (err) { return res.status(400).send('connection failed') } } }
#!/usr/bin/env bash ## Complete the following steps to get Docker running locally # Step 1: # Build image and add a descriptive tag # Assuming the image name is nd9991_p4 docker build --tag=nd9991_p4_project . # Step 2: # List docker images docker image ls # Step 3: # Run flask app docker run --name myContainer -it -p 8000:80 nd9991_p4_project
<reponame>kymngan1003/thesis<filename>app/src/main/java/com/burhanrashid52/photoeditor/hangltt3_initial.java package com.burhanrashid52.photoeditor; import com.burhanrashid52.photoeditor.base.BaseActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class hangltt3_initial extends BaseActivity { private Button btnGallery; private Button btnCamera; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); makeFullScreen(); setContentView(R.layout.hangltt3_initial); btnGallery = (Button) findViewById(R.id.btnGallery); btnCamera = (Button) findViewById(R.id.btnCamera); btnGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openActivity(); } }); btnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openActivity1(); } }); } public void openActivity(){ Intent intent = new Intent(this, GalleryActivity.class); startActivity(intent); } public void openActivity1(){ Intent intent = new Intent(this, CameraActivity.class); startActivity(intent); } }
#include <cstdlib> #include <cstdint> void* custom_aligned_alloc(size_t size, size_t align) { void* ptr = nullptr; #ifdef _WIN32 ptr = _aligned_malloc(size, align); #else if (posix_memalign(&ptr, align, size) != 0) { ptr = nullptr; } #endif return ptr; } void custom_aligned_free(void* ptr) { #ifdef _WIN32 _aligned_free(ptr); #else free(ptr); #endif }
public class Circle { private float _radius; public Circle(float radius) { _radius = radius; } public float calculateDistance(Circle other) { return _radius + other._radius; } public static void main(String[] args) { Circle circle1 = new Circle(5.0f); Circle circle2 = new Circle(3.0f); float distance = circle1.calculateDistance(circle2); System.out.println("Distance between circle1 and circle2: " + distance); } }
#!/bin/bash sudo cp --force .devcontainer/welcome-message.txt /usr/local/etc/vscode-dev-containers/first-run-notice.txt script/setup
<reponame>asterisk/dana-the-stream-gatekeeper<gh_stars>0 import React, { Component } from 'react'; import IconButton from '@material-ui/core/IconButton'; import Chip from '@material-ui/core/Chip'; import { withStyles } from '@material-ui/styles'; import { MicOutlined as MicIcon, MicOffOutlined as MicOffIcon, VideocamOffOutlined as VideoCamOffIcon, VideocamOutlined as VideoCamIcon, PictureInPicture as PictureInPictureIcon, Cancel as CancelIcon, Fullscreen as FullscreenIcon } from '@material-ui/icons'; const styles = theme => ({ root: { position: 'relative', height: '100%', width: '100%' }, selected: { borderWidth: '3px', borderStyle: 'solid', borderColor: theme.palette.secondary.main }, buttons: { position: 'absolute', bottom: 0, width: '100%', textAlign: 'center', zIndex: 100 }, name: { position: 'absolute', top: 0, width: '100%', textAlign: 'left', zIndex: 100 }, video: { objectFit: 'cover', maxWidth: '100%', borderRadius: '5px' }, videoPreview: { width: '100%' }, myVideoGrid: { width: '150px', height: '150px' }, videoInGrid: { height: '100%', width: '100%' } }); class Video extends Component { constructor(props) { super(props) this.state = { controlsVisible: false, audioMuted: false, videoMuted: false, pipEnabled: false }; this._videoRef = React.createRef(); } _addStreamToVideo() { if (this._videoRef.current && this._videoRef.current.srcObject !== this.props.stream) { this._videoRef.current.srcObject = this.props.stream; console.log('VIDEO srcObject not set', this.props.stream, this._videoRef); this._videoRef.current.onloadedmetadata = () => { console.log('VIDEO META DATA LOADED', this._videoRef); let tracks = this.props.stream.getVideoTracks(); for (let i = 0; i < tracks.length; ++i) { console.log('enabling track', tracks[i], this._videoRef); tracks[i].enabled = true; } console.log('playing video', this._videoRef); }; this._videoRef.current.addEventListener('leavepictureinpicture', (event) => { this.setState({pipEnabled: false}); }); } } componentDidMount() { this._addStreamToVideo(); } componentDidUpdate() { this._addStreamToVideo(); } componentWillUnmount() { if (this.state.pipEnabled) { this.togglePiP() } } mouseOver() { this.setState({controlsVisible: true}) } mouseOut() { this.setState({controlsVisible: false}) } toggleVideoMute() { this.props.stream.getVideoTracks().forEach((track) => { track.enabled = this.state.videoMuted; }); this.setState({videoMuted: !this.state.videoMuted}); } toggleAudioMute() { this.props.stream.getAudioTracks().forEach((track) => { track.enabled = this.state.audioMuted; }); this.setState({audioMuted: !this.state.audioMuted}); } async togglePiP() { console.log('attempting to pip'); if (this.state.pipEnabled) { try { await document.exitPictureInPicture(); } catch(err) { console.log('error exiting picture in picture'); } }else { try { if (this._videoRef.current !== document.pictureInPictureElement) { await this._videoRef.current.requestPictureInPicture(); this.setState({pipEnabled: true}) } } catch(error) { // TODO: Show error message to user. console.log('error!', error) } finally { } } } async enableFullscreen() { try { await this._videoRef.current.requestFullscreen(); } catch(error) { // TODO: Show error message to user. console.log('error!', error) } finally { } } render() { //should be able to hover over each one and mute it let { muted, enableControls, onSelect, stream, selected, classes, inGrid, previewVideo, myStreamGrid, channelData } = this.props; let { controlsVisible, audioMuted, videoMuted, pipEnabled } = this.state; let selectedClassNames = [classes.root, (selected ? classes.selected : '')].join(' '); let videoClassNames = [ classes.video, (inGrid ? classes.videoInGrid : ''), (previewVideo ? classes.videoPreview : ''), (myStreamGrid ? classes.myVideoGrid : '') ].join(' '); let hasStreamGotAudioTrack = false; if (stream && stream.getAudioTracks().length) { hasStreamGotAudioTrack = true; } return ( <div onClick={() => { if (onSelect) { onSelect(stream); } }} onMouseLeave={this.mouseOut.bind(this)} onMouseEnter={this.mouseOver.bind(this)} className={selectedClassNames} > {channelData && channelData.caller && channelData.caller.name && ( <span className={classes.name}> <Chip label={channelData.caller.name} color="secondary" /> </span> )} {enableControls && controlsVisible ? <span className={classes.buttons}> {hasStreamGotAudioTrack ? <IconButton edge="end" color="inherit" aria-label="Mic Off" onClick={this.toggleAudioMute.bind(this)}> {!audioMuted ? <MicIcon /> : <MicOffIcon /> } </IconButton> : null } <IconButton edge="end" color="inherit" aria-label="Video Off" onClick={this.toggleVideoMute.bind(this)}> {!videoMuted ? <VideoCamIcon /> : <VideoCamOffIcon /> } </IconButton> <IconButton edge="end" color="inherit" aria-label="PiP" onClick={this.togglePiP.bind(this)}> {!pipEnabled ? <PictureInPictureIcon /> : <CancelIcon />} </IconButton> <IconButton edge="end" color="inherit" aria-label="FullScreen" onClick={this.enableFullscreen.bind(this)}> <FullscreenIcon /> </IconButton> </span> : null } <video className={videoClassNames} ref={this._videoRef} autoPlay muted={muted}/> {/* <video className={videoClassNames} controls ref={this._videoRef}> <source src="https://storage.googleapis.com/webfundamentals-assets/videos/chrome.webm" type="video/webm" /> <source src="https://storage.googleapis.com/webfundamentals-assets/videos/chrome.mp4" type="video/mp4" /> <p>This browser does not support the video element.</p> </video> */} </div> ); }; } export default withStyles(styles)(Video);
def isPerfectSquare(n): root = n ** 0.5 return root == int(root) result = isPerfectSquare(36) print(result)
#!/bin/bash export PYTHONPATH="$(pwd)" fixed_arc="${1}" output_appendix="${2}" filters="${3-96}" echo $fixed_arc python src/cifar10/main.py \ --data_format="NCHW" \ --search_for="macro" \ --reset_output_dir \ --data_path="data/cifar10" \ --output_dir="outputs_${output_appendix}" \ --batch_size=100 \ --num_epochs=310 \ --log_every=50 \ --eval_every_epochs=1 \ --child_fixed_arc="${fixed_arc}" \ --child_use_aux_heads \ --child_num_layers=6 \ --child_out_filters=${filters} \ --child_l2_reg=2e-4 \ --child_num_branches=6 \ --child_num_cell_layers=5 \ --child_keep_prob=0.50 \ --child_lr_cosine \ --child_lr_max=0.05 \ --child_lr_min=0.001 \ --child_lr_T_0=10 \ --child_lr_T_mul=2 \ --nocontroller_training \ --controller_search_whole_channels \ --controller_entropy_weight=0.0001 \ --controller_train_every=1 \ --controller_sync_replicas \ --controller_num_aggregate=20 \ --controller_train_steps=50 \ --controller_lr=0.001 \ --controller_tanh_constant=1.5 \ --controller_op_tanh_reduce=2.5 \ --controller_skip_target=0.4 \ --controller_skip_weight=0.8 \ "$@"
<gh_stars>0 import validate from '../validator'; import Requests from '../requests'; import CONFIG from '../../env'; import BaseController from './base.controller'; const client = new Requests(); class UserInfoController extends BaseController { async addUserInfo(userId, data, schema) { const response = await client.url(`${(CONFIG.BASE_URL)}/user_info/${userId}`).headers(this.params.token).method('POST').body(data) .send('Add user information'); validate(schema, response.data); return response; } async getUserInfo(userId, schema) { const response = await client.url(`${(CONFIG.BASE_URL)}/user_info/${userId}`).headers(this.params.token).method('GET') .send('Get user information'); validate(schema, response.data); return response; } async deleteUserInfo(userId, schema) { const response = await client.url(`${(CONFIG.BASE_URL)}/user_info/${userId}`).headers(this.params.token).method('DELETE') .send('Delete user information'); validate(schema, response.data); return response; } async editUserInfo(userId, data, schema) { const response = await client.url(`${(CONFIG.BASE_URL)}/user_info/${userId}`).headers(this.params.token).method('PUT').body(data) .send('Edit user information'); validate(schema, response.data); return response; } } export default UserInfoController;
<reponame>ES-UFABC/UFABCplanner export interface IDeleteAcademyYear { academicYearId: string; }
#!/usr/bin/env bash set -euo pipefail source "$(dirname "${0}")/teamcity-support.sh" tc_start_block "Prepare environment" # Grab a testing license good for one hour. COCKROACH_DEV_LICENSE=$(curl -f "https://register.cockroachdb.com/api/prodtest") run mkdir -p artifacts maybe_ccache tc_end_block "Prepare environment" tc_start_block "Compile CockroachDB" run build/builder.sh make build tc_end_block "Compile CockroachDB" tc_start_block "Compile roachprod/workload/roachtest" run build/builder.sh make bin/roachprod bin/workload bin/roachtest tc_end_block "Compile roachprod/workload/roachtest" tc_start_block "Run local roachtests" # TODO(peter,dan): curate a suite of the tests that works locally. run build/builder.sh env \ COCKROACH_DEV_LICENSE="$COCKROACH_DEV_LICENSE" \ stdbuf -oL -eL \ ./bin/roachtest run acceptance kv/splits cdc/bank \ --local \ --parallelism=1 \ --cockroach "cockroach" \ --roachprod "bin/roachprod" \ --workload "bin/workload" \ --artifacts artifacts \ --teamcity 2>&1 \ | tee artifacts/roachtest.log tc_end_block "Run local roachtests"
<filename>Documentation/classarmnn_utils_1_1_model_accuracy_checker.js var classarmnn_utils_1_1_model_accuracy_checker = [ [ "ModelAccuracyChecker", "classarmnn_utils_1_1_model_accuracy_checker.xhtml#a143dac91f5ef85d672e7bccb0358e3f7", null ], [ "AddImageResult", "classarmnn_utils_1_1_model_accuracy_checker.xhtml#a38d140dac29d228fdd1681e465507c29", null ], [ "GetAccuracy", "classarmnn_utils_1_1_model_accuracy_checker.xhtml#ad6ddd3b77dd12eb33875d58a391b2412", null ] ];
package com.cgovern.governor.models; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.validation.Valid; import org.springframework.validation.annotation.Validated; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; /** * BadRequest */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-12-22T04:22:26.530Z") public class BadRequest { @JsonProperty("id") private String id = null; @JsonProperty("code") private Integer code = null; @JsonProperty("message") private String message = null; @JsonProperty("fields") @Valid private List<String> fields = null; public BadRequest id(String id) { this.id = id; return this; } /** * Get id * * @return id **/ @ApiModelProperty(value = "") public String getId() { return id; } public void setId(String id) { this.id = id; } public BadRequest code(Integer code) { this.code = code; return this; } /** * Get code * * @return code **/ @ApiModelProperty(value = "") public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public BadRequest message(String message) { this.message = message; return this; } /** * Get message * * @return message **/ @ApiModelProperty(value = "") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public BadRequest fields(List<String> fields) { this.fields = fields; return this; } public BadRequest addFieldsItem(String fieldsItem) { if (this.fields == null) { this.fields = new ArrayList<String>(); } this.fields.add(fieldsItem); return this; } /** * Get fields * * @return fields **/ @ApiModelProperty(value = "") public List<String> getFields() { return fields; } public void setFields(List<String> fields) { this.fields = fields; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BadRequest badRequest = (BadRequest) o; return Objects.equals(this.id, badRequest.id) && Objects.equals(this.code, badRequest.code) && Objects.equals(this.message, badRequest.message) && Objects.equals(this.fields, badRequest.fields); } @Override public int hashCode() { return Objects.hash(id, code, message, fields); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BadRequest {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).append("\n"); sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
def divisible_by_3?(n) n % 3 == 0 end # Usage 15.divisible_by_3? # => false 3.divisible_by_3? # => true
#!/bin/bash if [ "$(id -u)" != "0" ]; then echo "This script has to be run as root." 1>&2 exit 1 fi service dnsmasq stop service hostapd stop service network-manager stop [[ -e /etc/network/interfaces.d/wlan0.conf_ ]] && mv /etc/network/interfaces.d/wlan0.conf{_,} service networking restart service network-manager start service hostapd start service dnsmasq start
SELECT name, address, email FROM user WHERE city = 'Los Angeles';
<reponame>azjezz/waffle <?hh namespace Waffle\Tests\Container; use type Waffle\Container\Exception\NotFoundException; use function Facebook\FBExpect\expect; use type Waffle\Container\ReflectionContainer; use type Waffle\Container\Container; use type Waffle\Tests\Container\Asset\{Foo, FooCallable, Bar}; use type Facebook\HackTest\HackTest; class ReflectionContainerTest extends HackTest { /** * Asserts that ReflectionContainer claims it has an item if a class exists for the alias. */ public function testHasReturnsTrueIfClassExists() { $container = new ReflectionContainer(); expect($container->has(ReflectionContainer::class))->toBeTrue(); } /** * Asserts that ReflectionContainer denies it has an item if a class does not exist for the alias. */ public function testHasReturnsFalseIfClassDoesNotExist() { $container = new ReflectionContainer(); expect($container->has('blah'))->toBeFalse(); } /** * Asserts that ReflectionContainer instantiates a class that does not have a constructor. */ public function testContainerInstantiatesClassWithoutConstructor() { $classWithoutConstructor = \stdClass::class; $container = new ReflectionContainer(); expect($container->get($classWithoutConstructor))->toBeInstanceOf($classWithoutConstructor); } /** * Asserts that ReflectionContainer instantiates and cacheds a class that does not have a constructor. */ public function testContainerInstantiatesAndCachesClassWithoutConstructor() { $classWithoutConstructor = \stdClass::class; $container = (new ReflectionContainer())->cacheResolutions(); $classWithoutConstructorOne = $container->get($classWithoutConstructor); $classWithoutConstructorTwo = $container->get($classWithoutConstructor); expect($classWithoutConstructorOne)->toBeInstanceOf($classWithoutConstructor); expect($classWithoutConstructorTwo)->toBeInstanceOf($classWithoutConstructor); expect($classWithoutConstructorTwo)->toBeSame($classWithoutConstructorOne); } /** * Asserts that ReflectionContainer instantiates a class that has a constructor. */ public function testGetInstantiatesClassWithConstructor() { $classWithConstructor = Foo::class; $dependencyClass = Bar::class; $container = new ReflectionContainer(); $container->setContainer($container); $item = $container->get($classWithConstructor); expect($item)->toBeInstanceOf($classWithConstructor); /* HH_IGNORE_ERROR[4064] */ expect($item->bar)->toBeInstanceOf($dependencyClass); } /** * Asserts that ReflectionContainer instantiates and caches a class that has a constructor. */ public function testGetInstantiatesAndCachedClassWithConstructor() { $classWithConstructor = Foo::class; $dependencyClass = Bar::class; $container = (new ReflectionContainer())->cacheResolutions(); $container->setContainer($container); $itemOne = $container->get($classWithConstructor); $itemTwo = $container->get($classWithConstructor); expect($itemOne)->toBeInstanceOf($classWithConstructor); /* HH_IGNORE_ERROR[4064] */ expect($itemOne->bar)->toBeInstanceOf($dependencyClass); expect($itemTwo)->toBeInstanceOf($classWithConstructor); /* HH_IGNORE_ERROR[4064] */ expect($itemTwo->bar)->toBeInstanceOf($dependencyClass); expect($itemTwo)->toBeSame($itemOne); /* HH_IGNORE_ERROR[4064] */ expect($itemTwo->bar)->toBeSame($itemOne->bar); } /** * Asserts that ReflectionContainer instantiates a class that has a constructor with a type-hinted argument, and * fetches that dependency from the container injected into the ReflectionContainer. */ public function testGetInstantiatesClassWithConstructorAndUsesContainer() { $classWithConstructor = Foo::class; $dependencyClass = Bar::class; $dependency = new Bar(); $container = new ReflectionContainer(); $innerContainer = new Container(); $innerContainer->add($dependencyClass, () ==> $dependency); $container->setContainer($innerContainer); $item = $container->get($classWithConstructor); expect($item)->toBeInstanceOf($classWithConstructor); /* HH_IGNORE_ERROR[4064] */ expect($item->bar)->toBeSame($dependency); } /** * Asserts that ReflectionContainer instantiates a class that has a constructor with a type-hinted argument, and * uses the values provided in the argument array. */ public function testGetInstantiatesClassWithConstructorAndUsesArguments() { $classWithConstructor = Foo::class; $dependencyClass = Bar::class; $dependency = new Bar(); $container = new ReflectionContainer(); $innerContainer = new Container(); $innerContainer->add($dependencyClass, () ==> $dependency); $container->setContainer($innerContainer); $item = $container->get($classWithConstructor); expect($item)->toBeInstanceOf($classWithConstructor); /* HH_IGNORE_ERROR[4064] */ expect($item->bar)->toBeSame($dependency); } /** * Asserts that an exception is thrown when attempting to get a class that does not exist. */ public function testThrowsWhenGettingNonExistentClass() { expect(() ==> { $container = new ReflectionContainer(); $container->get('Whoooooopyyyy'); })->toThrow(NotFoundException::class); } /** * Asserts that call reflects on a closure and injects arguments. */ public function testCallReflectsOnClosureArguments() { $container = new ReflectionContainer(); $foo = $container->call(function (Foo $foo) { return $foo; }); expect($foo)->toBeInstanceOf(Foo::class); /* HH_IGNORE_ERROR[4064] */ expect($foo->bar)->toBeInstanceOf(Bar::class); } /** * Asserts that call reflects on an instance method and injects arguments. */ public function testCallReflectsOnInstanceMethodArguments() { $container = new ReflectionContainer(); $foo = new Foo(null); $container->call([$foo, 'setBar']); expect($foo)->toBeInstanceOf(Foo::class); expect($foo->bar)->toBeInstanceOf(Bar::class); } /** * Asserts that call reflects on a static method and injects arguments. */ public function testCallReflectsOnStaticMethodArguments() { $container = new ReflectionContainer(); $container->setContainer($container); $container->call('Waffle\Tests\Container\Asset\Foo::staticSetBar'); expect(Asset\Foo::$staticBar)->toBeInstanceOf(Bar::class); expect(Asset\Foo::$staticHello)->toBePHPEqual('hello world'); } /** * Asserts that exception is thrown when an argument cannot be resolved. */ public function testThrowsWhenArgumentCannotBeResolved() { expect(() ==> { $container = new ReflectionContainer(); $container->call([new Bar(), 'setSomething']); })->toThrow(NotFoundException::class); } /** * Tests the support for __invokable/callable classes for the ReflectionContainer::call method. */ public function testInvokableClass() { $container = new ReflectionContainer(); $foo = $container->call(new FooCallable(), dict[ 'bar' => new Bar() ]); expect($foo)->toBeInstanceOf(Foo::class); /* HH_IGNORE_ERROR[4064] */ expect($foo->bar)->toBeInstanceOf(Bar::class); } }
<reponame>sssu3996/tool<gh_stars>0 // 将方法封装到对象身上 var kits = {}; // 给数值小于0的数字,在前面加上一个 0 kits.dispatchZero = function(num) { if (num < 10) { num = "0" + num; } return num; }; // 获取时间 kits.formatDate = function() { var date = new Date(); // 把年月日时分秒获取 var year = date.getFullYear(); var month = date.getMonth() + 1; month = this.dispatchZero(month); var day = date.getDate(); day = this.dispatchZero(day); var hour = date.getHours(); hour = this.dispatchZero(hour); var minutes = date.getMinutes(); minutes = this.dispatchZero(minutes); var seconds = date.getSeconds(); seconds = this.dispatchZero(seconds); return ( year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds ); }; // 获取随机整数 kits.randomInt = function(n, m) { return Math.floor(Math.random() * (m - n + 1) + n); }; // 常见的给id的方式1 // 当前时间戳 + 大的随机数 kits.getId = function() { // 返回一个不容易重复的id let date = new Date(); // 从1970年1月1日到现在为止的毫秒总数 let time = date.getTime(); // 然后再得到一个足够大的随机数,把毫秒和随机数相连,作为新的id let r = this.randomInt(10000, 99999); // 把两个数字连起来 let id = time + "" + r; return id; }; // 获取一个随机的十六进制的颜色 kits.randomHexColor = function() { let arr = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" ]; let str = "#"; let num = 0; for (let i = 0; i < 6; i++) { // num = parseInt(Math.random() * 16); num = this.randomInt(0, 15); str += arr[num]; } return str; }; // 获取一个随机的rgb格式的颜色 kits.randomRGBColor = function() { let r = this.randomInt(0, 255); let g = this.randomInt(0, 255); let b = this.randomInt(0, 255); return "rgb(" + r + "," + g + "," + b + ")"; }; // 将一个数组(arr)以指定的键(key)存储到localStorage里面 kits.saveLocalDataArray = function(key, arr) { let json = JSON.stringify(arr); localStorage.setItem(key, json); }; // 从locatStorage根据指定的键(key)获取一个数组 kits.getLocalDataArray = function(key, arr) { let date = localStorage.getItem(key, arr); let Arr = JSON.parse(date); if (!Arr) { Arr = []; } return Arr; }; // appendDataIntoArray(key,data) 向localStorage里面指定键(key)的数组数据追加一个数据对象(data) kits.appendDataIntoArray = function(key, data) { arr = this.getLocalDataArray(key, arr); arr = arr || []; arr.unshift(data); this.saveLocalDataArray(key, arr); }; // deleteLocalDataById(key,id) 根据对应的id从localStorage中指定键(key)的数组中删除一条数据 kits.deleteLocalDataById = function(key, id) { arr = this.getLocalDataArray(key, arr); arr = arr || []; arr.forEach((e, i) => { // console.log(e.id); // console.log(id.id); if (e.id == id.id) { arr.splice(0, 1); } }); this.saveLocalDataArray(key, arr); }; // modifyLocalDataById(key,id,data) 根据id修改localStorage里面的指定键(key)的数组数据 kits.modifyLocalDataById = function(key, id, data) { arr = this.getLocalDataArray(key, arr); arr = arr || []; arr.forEach((e, i) => { if (e.id == id.id) { e.id = data.id; e.content = data.content; } }); this.saveLocalDataArray(key, arr); };
[Route("api/[controller]")] public class PostsController : Controller { private readonly IPostsRepository _postsRepository; public PostsController(IPostsRepository postsRepository) { _postsRepository = postsRepository; } [HttpGet] public async Task<ActionResult<IEnumerable<Post>>> GetAll() { return Ok(await _postsRepository.GetAll()); } [HttpGet("{id}")] public async Task<ActionResult<Post>> GetById([FromRoute] int id) { var post = await _postsRepository.GetById(id); if (post == null) return NotFound(); return Ok(post); } [HttpPost] public async Task<ActionResult<Post>> Create(Post post) { var newPost = await _postsRepository.Create(post); return CreatedAtAction(nameof(GetById), new {id = newPost.Id}, newPost); } }
package component import ( "github.com/fighthorse/redisAdmin/component/conf" "github.com/fighthorse/redisAdmin/component/httpclient" "github.com/fighthorse/redisAdmin/component/log" "github.com/fighthorse/redisAdmin/component/thirdpart/trace_redis" "github.com/fighthorse/redisAdmin/component/trace" ) func InitComponent() { // redis cfg trace_redis.InitCfg(conf.GConfig.Redis) // http cfg httpclient.Init(conf.GConfig.HttpServer) httpclient.InitCircuitBreaker(conf.GConfig.HttpBreaker) httpclient.InitChildService(conf.GConfig.ChildServer) //trace trace.Init() // log log.Init() }
import * as firebase from '@firebase/testing'; expect.extend({ async toAllow(pr) { let pass = false; try { await firebase.assertSucceeds(pr); pass = true; } catch (err) { // no-op } return { pass, message: () => 'Expected Firebase operation to be allowed, but it was denied', }; }, }); expect.extend({ async toDeny(pr) { let pass = false; try { await firebase.assertFails(pr); pass = true; } catch (err) { // no-op } return { pass, message: () => 'Expected Firebase operation to be denied, but it was allowed', }; }, }); //# sourceMappingURL=helpers.js.map
package com.solvd.carfactory.models.employee; import com.solvd.carfactory.models.assemblyline.AssemblyLine; public class AssemblyEmployee extends Employee{ private long id; private AssemblyLine assemblyLine; public AssemblyEmployee() { } public AssemblyEmployee(long id) { this.id = id; } public long getId() { return id; } public void setId(long id) { this.id = id; } public AssemblyLine getAssemblyLine() { return assemblyLine; } public void setAssemblyLine(AssemblyLine assemblyLine) { this.assemblyLine = assemblyLine; } }
<filename>hartree-common/src/main/java/org/cmayes/hartree/model/NormalModeReport.java package org.cmayes.hartree.model; import java.util.Map; /** * Defines a report made on the normal modes for a given calculation. * * @author cmayes */ public interface NormalModeReport { /** * Returns a map of normal modes that have the highest percentage of a * degree of freedom for a dihedral pair, keyed by that pair. The value for * the dihedral can be looked up from the summary map. * * @return A map of normal modes that have the highest percentage of a * degree of freedom for a dihedral pair, keyed by that pair. */ Map<DihedralPair, NormalMode> findHighestDihedrals(); /** * Returns summaries of the normal mode's degree of freedom keyed by the * normal mode. * * @return A map of normal modes to summaries. */ Map<NormalMode, NormalModeSummary> getSummaries(); }
import string import random chars = string.ascii_letters random_string = ''.join([random.choice(chars) for x in range(8)]) print(random_string)
/** * Created by hustcc on 18/5/20. * Contract: <EMAIL> */ import { LocaleFunc } from './interface'; /** * register a locale * @param locale * @param func */ export declare const register: (locale: string, func: LocaleFunc) => void; /** * get a locale, default is en_US * @param locale * @returns {*} */ export declare const getLocale: (locale: string) => LocaleFunc;