text
stringlengths
27
775k
package by.dzmitry_lakisau.month_year_picker_dialog.sample import android.app.Dialog import android.os.Bundle import androidx.fragment.app.DialogFragment import by.dzmitry_lakisau.month_year_picker_dialog.MonthYearPickerDialog class MonthPickerDialogFragment : DialogFragment() { private lateinit var dialog: MonthYearPickerDialog override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return dialog } companion object { fun newInstance(dialog: MonthYearPickerDialog): MonthPickerDialogFragment { return MonthPickerDialogFragment().apply { this.dialog = dialog } } } }
package casbin import ( "fmt" "gin-web-admin/utils/setting" "github.com/casbin/casbin/v2" //"github.com/casbin/casbin/v2/util" gormadapter "github.com/casbin/gorm-adapter/v2" _ "github.com/go-sql-driver/mysql" //"strings" ) var ( CasbinEnforcer *casbin.Enforcer ) func SetupCasbin() *casbin.Enforcer { a, _ := gormadapter.NewAdapter(setting.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s", setting.DatabaseSetting.User, setting.DatabaseSetting.Password, setting.DatabaseSetting.Host, setting.DatabaseSetting.Name, ), true, ) e, _ := casbin.NewEnforcer("conf/rbac_model.conf", a) // Or you can use an existing DB "abc" like this: // The adapter will use the table named "casbin_rule". // If it doesn't exist, the adapter will create it automatically. // a := gormadapter.NewAdapter("mysql", "mysql_username:mysql_password@tcp(127.0.0.1:3306)/abc", true) // Load the policy from DB. _ = e.LoadPolicy() // Check the permission. /* check, _ := e.Enforce("alice", "data1", "read") if check { log.Println("通过权限") } else { log.Println("权限没有通过") }*/ CasbinEnforcer = e return e // Modify the policy. //e.AddPolicy("alice2", "data1", "read") // e.RemovePolicy(...) // Save the policy back to DB. //e.SavePolicy() }
import React, { Component } from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; import { Wrapper as ListWrapper, ListHeader } from "../../UI/List"; import { Wrapper as CardWrapper } from "../../UI/Card"; const Wrapper = styled.div` display: flex; justify-content: center; padding: 0.5em; `; const ListItem = CardWrapper.extend` padding: 1em; &:last-child { margin-bottom: 0; } select { width: 100%; padding: 0.5em; } `; class SettingsView extends Component { static propTypes = { store: PropTypes.object }; state = { themeName: this.props.store.themeName }; handleThemeChange = ({ target }) => { this.setState({ themeName: target.value }); this.props.store.changeTheme(target.value); }; render() { const { themeName } = this.state; const { themeNames } = this.props.store; return ( <Wrapper> <ListWrapper> <ListHeader>Theme</ListHeader> <ListItem> <select value={themeName} onChange={this.handleThemeChange} aria-label="theme"> {themeNames.map(name => ( <option key={name} value={name}> {name} </option> ))} </select> </ListItem> </ListWrapper> </Wrapper> ); } } export default SettingsView;
import styled, { css } from 'styled-components'; export const CarLookOptionWrapper = styled.section` color: black; width: 100; margin-bottom: 30px; display: block; .car-color { width: 100%; height: 100%; } .title-wrapper { width: 100%; display: flex; justify-content: center; h2 { margin-top: 5px; font-size: 2rem; font-weight: 500; } } .color-pick-wrapper { display: flex; justify-content: center; align-items: center; flex-direction: column; .selected-option-detail { font-size: 1.4rem; letter-spacing: 0.3px; display: flex; justify-content: center; flex-direction: column; align-items: center; .selected-option-name { line-height: 24px; font-weight: 700; margin-right: 10px; } .selected-option-price { color: #666; font-weight: 300; } .selected-option-description { color: #666; font-weight: 300; margin: 0 0 10px; } } } `; export const StyledImage = styled.img` width: 35px; height: 35px; margin-left: 5px; margin-bottom: 10px; ${({ active }) => active && css` border: 2px solid rgb(0, 127, 255); border-radius: 100px; padding: 2px; `}; `;
<?php namespace Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * @Entity() * @Table(name="users") */ class User { /** * @Column(name="id", type="integer") * @Id * @GeneratedValue(strategy="AUTO") */ private $id; /** * @Column(type="string", length=255, name="username") */ private $userName; /** * @Column(type="string", length=255, name="password") */ private $passWord; /** * @OneToMany(targetEntity="ToDo", mappedBy="author", cascade={"all"}) */ public $todos; /** * @return mixed */ public function getId() { return $this->id; } /** * @return mixed */ public function getUserName() { return $this->userName; } /** * @param mixed $userName */ public function setUserName($userName) { $this->userName = $userName; } /** * @return mixed */ public function getTodos() { return $this->todos; } public function addTodos(ToDo $t) { return $this->todos[] = $t; } /** * @return mixed */ public function getPassWord() { return $this->passWord; } /** * @param mixed $passWord */ public function setPassWord($passWord) { $this->passWord = $passWord; } public function __construct() { $this->todos = new ArrayCollection(); } }
[![Build Status](https://badger-zpct3epzcq-ue.a.run.app/build/status?project=cloud-build-fhir&id=4b13d289-3b1e-4a45-aa86-8166d5a5f481)](https://storage.googleapis.com/cloud-build-gh-logs/README.html) [![codecov](https://codecov.io/gh/GoogleCloudPlatform/openmrs-fhir-analytics/branch/master/graph/badge.svg)](https://codecov.io/gh/GoogleCloudPlatform/openmrs-fhir-analytics) **NOTE**: This is a work in progress and the current version is only for demonstration purposes. Once these tools reach Alpha status, this note should be removed. This is a collaboration between Google and the OpenMRS community. # What is this? This repository includes pipelines to transform data from an [OpenMRS](https://openmrs.org) instance using the [FHIR format](https://www.hl7.org/fhir/overview.html) into a data warehouse based on [Apache Parquet files](https://parquet.apache.org), or another FHIR server (e.g., a HAPI FHIR server or Google Cloud FHIR store). There is also a query library in Python to make working with FHIR based data warehouses simpler. These tools are intended to be generic and eventually work with any FHIR-based data source and data warehouse. Here is the list of main directories with a brief description of their content: - [pipelines/](pipelines/) Batch and streaming pipelines to transform data from a FHIR based source to an analytics friendly data warehouse or another FHIR store. - [dwh/](dwh/) Query library for working with distributed FHIR-based data warehouses. - [bunsen/](bunsen/) A fork of a subset of the [Bunsen](https://github.com/cerner/bunsen) project. - [docker/](docker/) Docker configurations for various servers/pipelines. - [doc/](doc/) Documentations - [utils/](utils/) Various artifacts for setting up an initial database, running pipelines, etc. - [e2e-tests/](e2e-tests/) Scripts for testing pipelines end-to-end.
import { StoreService } from './store.service'; class TestStoreService extends StoreService { constructor(public store: any) { super(); } } describe('StoreService', () => { let service; const store: any = { dispatch: () => undefined }; function init() { service = new TestStoreService(store); } describe('dispatchAction(action: Action)', () => { beforeEach(() => { init(); }); it('has a function named dispatchAction', () => { expect(typeof service.dispatchAction).toEqual('function'); }); it('calls store.dispatch() with the given action', () => { spyOn(store, 'dispatch').and.returnValue(null); const action: any = 'test-action'; service.dispatchAction(action); expect(store.dispatch).toHaveBeenCalledWith(action); }); }); describe('getProperty(prop: string)', () => { beforeEach(() => { init(); }); it('has a function named getProperty', () => { expect(typeof service.getProperty).toEqual('function'); }); it('returns a function', () => { const f = service.getProperty('test'); const expected: any = 'function'; const result: any = typeof f; expect(result).toEqual(expected); }); it('returns the value of obj[prop]', () => { const obj = {test: 'test-value'}; const f = service.getProperty('test'); const expected: any = 'test-value'; const result: any = f(obj); expect(result).toEqual(expected); }); }); });
<a href="https://travis-ci.org/Xotic750/is-plain-object-x" title="Travis status"> <img src="https://travis-ci.org/Xotic750/is-plain-object-x.svg?branch=master" alt="Travis status" height="18"> </a> <a href="https://david-dm.org/Xotic750/is-plain-object-x" title="Dependency status"> <img src="https://david-dm.org/Xotic750/is-plain-object-x/status.svg" alt="Dependency status" height="18"/> </a> <a href="https://david-dm.org/Xotic750/is-plain-object-x?type=dev" title="devDependency status"> <img src="https://david-dm.org/Xotic750/is-plain-object-x/dev-status.svg" alt="devDependency status" height="18"/> </a> <a href="https://badge.fury.io/js/is-plain-object-x" title="npm version"> <img src="https://badge.fury.io/js/is-plain-object-x.svg" alt="npm version" height="18"> </a> <a href="https://www.jsdelivr.com/package/npm/is-plain-object-x" title="jsDelivr hits"> <img src="https://data.jsdelivr.com/v1/package/npm/is-plain-object-x/badge?style=rounded" alt="jsDelivr hits" height="18"> </a> <a href="https://bettercodehub.com/results/Xotic750/is-plain-object-x" title="bettercodehub score"> <img src="https://bettercodehub.com/edge/badge/Xotic750/is-plain-object-x?branch=master" alt="bettercodehub score" height="18"> </a> <a href="https://coveralls.io/github/Xotic750/is-plain-object-x?branch=master" title="Coverage Status"> <img src="https://coveralls.io/repos/github/Xotic750/is-plain-object-x/badge.svg?branch=master" alt="Coverage Status" height="18"> </a> <a name="module_is-plain-object-x"></a> ## is-plain-object-x Tests if a value is a plain object. <a name="exp_module_is-plain-object-x--module.exports"></a> ### `module.exports` ⇒ <code>boolean</code> ⏏ This method tests if `value` is a plain object, that is, an object created by the `Object` constructor or one with a `[[Prototype]]` of `null`. **Kind**: Exported member **Returns**: <code>boolean</code> - True if a plain object, otherwise false. | Param | Type | Description | | ----- | --------------- | ------------------ | | value | <code>\*</code> | The value to test. | **Example** ```js import isPlainObject from 'is-plain-object-x'; function Foo() { this.a = 1; } isPlainObject(new Foo()); // => false isPlainObject([1, 2, 3]); // => false isPlainObject({x: 0, y: 0}); // => true isPlainObject(Object.create(null)); // => true ```
import { IChannelServer, IServerChannel, IPCMessageRequest, IPCMessageResponse, } from '@/service/common/ipc'; import { transformErrorForSerialization } from '@/common/error'; export class BackgroundIPCServer implements IChannelServer { public registerChannel(channelName: string, server: IServerChannel) { chrome.runtime.onConnect.addListener(port => { if (port.name !== channelName) { return; } port.onMessage.addListener( async (message: IPCMessageRequest, currentPort: chrome.runtime.Port) => { const { uuid, command, arg } = message; let response: IPCMessageResponse; try { const result = await server.call(currentPort.sender, command, arg); response = { uuid, result: { data: result }, }; } catch (error) { response = { uuid, error: { data: transformErrorForSerialization(error) }, }; } port.postMessage(response); } ); }); } }
/* Package animation provides type definitions for use with the Chrome Animation protocol https://chromedevtools.github.io/devtools-protocol/tot/Animation/ */ package animation import ( "github.com/mkenney/go-chrome/tot/cdtp/dom" ) /* Animation instance. https://chromedevtools.github.io/devtools-protocol/tot/Animation/#type-Animation */ type Animation struct { // Animation's id. ID string `json:"id"` // Animation's name. Name string `json:"name"` // Animation's internal paused state. PausedState bool `json:"pausedState"` // Animation's play state. PlayState string `json:"playState"` // Animation's playback rate. PlaybackRate float64 `json:"playbackRate"` // Animation's start time. StartTime int64 `json:"startTime"` // Animation's current time. CurrentTime int64 `json:"currentTime"` // Animation type of Animation. Allowed values: // - AnimationType.CSSTransition // - AnimationType.CSSAnimation // - AnimationType.WebAnimation Type TypeEnum `json:"type"` // Optional. Animation's source animation node. Source *Effect `json:"source,omitempty"` // Optional. A unique ID for Animation representing the sources that // triggered this CSS animation/transition. CSSID string `json:"cssId,omitempty"` } /* Effect instance https://chromedevtools.github.io/devtools-protocol/tot/Animation/#type-AnimationEffect */ type Effect struct { // Effect's delay. Delay int64 `json:"delay"` // Effect's end delay. EndDelay int64 `json:"endDelay"` // Effect's iteration start. IterationStart int64 `json:"iterationStart"` // Effect's iterations. Iterations int64 `json:"iterations"` // Effect's iteration duration. Duration int64 `json:"duration"` // Effect's playback direction. Direction string `json:"direction"` // Effect's fill mode. Fill string `json:"fill"` // Optional. Effect's target node. BackendNodeID dom.BackendNodeID `json:"backendNodeId,omitempty"` // Optional. Effect's keyframes. KeyframesRule *KeyframesRule `json:"keyframesRule,omitempty"` // Effect's timing function. Easing string `json:"easing"` } /* KeyframesRule is the keyframes rule https://chromedevtools.github.io/devtools-protocol/tot/Animation/#type-KeyframesRule */ type KeyframesRule struct { // Optional. CSS keyframed animation's name. Name string `json:"name,omitempty"` // List of animation keyframes. Keyframes []*KeyframeStyle `json:"keyframes"` } /* KeyframeStyle is the keyframe Style https://chromedevtools.github.io/devtools-protocol/tot/Animation/#type-KeyframeStyle */ type KeyframeStyle struct { // Keyframe's time offset. Offset string `json:"offset"` // Effect's timing function. Easing string `json:"easing"` }
--- layout: post lang: en permalink: /en/ruffnote_inc title: Ruffnote inc. description: ' Developing a time Sharing Service for Remote workers TimeCrowd ' description_full: '<p>Developing a time Sharing Service for Remote workers <a href="https://timecrowd.net/">TimeCrowd</a></p>' categories: full_remote link: http://co.ruffnote.com/ ---
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\CurrencySymbol\Model\System; use Magento\TestFramework\Helper\Bootstrap; /** * Test for Magento\CurrencySymbol\Model\System\Currencysymbol * * @magentoAppArea adminhtml */ class CurrencysymbolTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\CurrencySymbol\Model\System\Currencysymbol */ protected $currencySymbolModel; protected function setUp() { $this->currencySymbolModel = Bootstrap::getObjectManager()->create( 'Magento\CurrencySymbol\Model\System\Currencysymbol' ); } protected function tearDown() { $this->currencySymbolModel = null; Bootstrap::getObjectManager()->get('Magento\Framework\App\Config\ReinitableConfigInterface')->reinit(); Bootstrap::getObjectManager()->create('Magento\Store\Model\StoreManagerInterface')->reinitStores(); } public function testGetCurrencySymbolsData() { $currencySymbolsData = $this->currencySymbolModel->getCurrencySymbolsData(); $this->assertArrayHasKey('USD', $currencySymbolsData, 'Default currency option for USD is missing.'); $this->assertArrayHasKey('EUR', $currencySymbolsData, 'Default currency option for EUR is missing.'); } /** * @magentoDbIsolation enabled */ public function testSetEmptyCurrencySymbolsData() { $currencySymbolsDataBefore = $this->currencySymbolModel->getCurrencySymbolsData(); $this->currencySymbolModel->setCurrencySymbolsData([]); $currencySymbolsDataAfter = $this->currencySymbolModel->getCurrencySymbolsData(); //Make sure symbol data is unchanged $this->assertEquals($currencySymbolsDataBefore, $currencySymbolsDataAfter); } /** * @magentoDbIsolation enabled */ public function testSetCurrencySymbolsData() { $currencySymbolsData = $this->currencySymbolModel->getCurrencySymbolsData(); $this->assertArrayHasKey('EUR', $currencySymbolsData); //Change currency symbol $currencySymbolsData = [ 'EUR' => '@', ]; $this->currencySymbolModel->setCurrencySymbolsData($currencySymbolsData); //Verify if the new symbol is set $this->assertEquals( '@', $this->currencySymbolModel->getCurrencySymbolsData()['EUR']['displaySymbol'], 'Symbol not set correctly.' ); $this->assertEquals('@', $this->currencySymbolModel->getCurrencySymbol('EUR'), 'Symbol not set correctly.'); } public function testGetCurrencySymbolNonExistent() { $this->assertFalse($this->currencySymbolModel->getCurrencySymbol('AUD')); } }
/** * Atena Game Engine * texture-manager.cc * * Copyright 2014-present [Ricard Sole <@rcsole, ricardsolecasas@gmail.com>] */ #include "./atena/textures/texture-manager.h" TextureManager *TextureManager::s_pInstance = 0; void TextureManager::DrawFrame(std::string texture_key, std::string frame_key, int x, int y, SDL_Renderer *pRenderer) { std::vector<int> coords = m_textureMap[texture_key]->getFrame(frame_key); if (!coords.empty()) { SDL_Rect srcRect; SDL_Rect dstRect; srcRect.x = coords[0]; srcRect.y = coords[1]; srcRect.w = dstRect.w = coords[2]; srcRect.h = dstRect.h = coords[3]; dstRect.x = x; dstRect.y = y; SDL_RenderCopyEx(pRenderer, m_textureMap[texture_key]->getTexture(), &srcRect, &dstRect, 0, 0, SDL_FLIP_NONE); } } void TextureManager::DrawFrame(std::string texture_key, int x, int y, int width, int height, int row, int frame, SDL_Renderer *pRenderer) { SDL_Rect srcRect; SDL_Rect dstRect; srcRect.x = width * frame; srcRect.y = height * (row - 1); srcRect.w = dstRect.w = width; srcRect.h = dstRect.h = height; dstRect.x = x; dstRect.y = y; SDL_RenderCopyEx(pRenderer, m_textureMap[texture_key]->getTexture(), &srcRect, &dstRect, 0, 0, SDL_FLIP_NONE); } void TextureManager::Draw(std::string texture_key, int x, int y, int width, int height, SDL_Renderer *pRenderer) { SDL_Rect srcRect; SDL_Rect dstRect; srcRect.x = 0; srcRect.y = 0; srcRect.w = dstRect.w = width; srcRect.h = dstRect.h = height; dstRect.x = x; dstRect.y = y; SDL_RenderCopyEx(pRenderer, m_textureMap[texture_key]->getTexture(), &srcRect, &dstRect, 0, 0, SDL_FLIP_NONE); } bool TextureManager::Load(std::string key, std::string pathIMG, SDL_Renderer *ren) { SDL_Texture *tmpTex = NULL; tmpTex = LoadImage(pathIMG.c_str(), ren); Texture *t = new Texture(tmpTex); m_textureMap[key] = t; return true; } bool TextureManager::Load(std::string key, std::string pathJSON, std::string pathIMG, SDL_Renderer *ren) { json_t *tmpJSON = NULL; SDL_Texture *tmpTex = NULL; tmpTex = LoadImage(pathIMG.c_str(), ren); tmpJSON = LoadJson(pathJSON.c_str()); Texture *t = new Texture(tmpTex, tmpJSON); m_textureMap[key] = t; return true; } SDL_Texture *TextureManager::LoadImage(char const *path, SDL_Renderer *ren) { SDL_Texture *tmpTexture = NULL; SDL_Surface *tmpSurface = NULL; tmpSurface = IMG_Load(path); if (tmpSurface == NULL) { printf("Error loading image %s: %s\n", path, IMG_GetError()); } else { printf("Image %s loaded\n", path); tmpTexture = SDL_CreateTextureFromSurface(ren, tmpSurface); if (tmpTexture == NULL) { printf("Error creating texture from %s: %s\n", path, IMG_GetError()); } printf("Texture %s loaded\n", path); SDL_FreeSurface(tmpSurface); } return tmpTexture; } json_t *TextureManager::LoadJson(char const *path) { json_t *root = NULL; if (FILE *p_inputFile = fopen(path, "r")) { printf("File exists\n"); json_t *jsonFile = NULL; json_error_t *error = NULL; jsonFile = json_loadf(p_inputFile, 0, error); root = json_object_get(jsonFile, "frames"); fclose(p_inputFile); } else { printf("Error loading json %s\n", path); return root; } return root; }
#!/bin/sh # Copyright 2020 Google LLC # Author: lru@google.com (Leo Rudberg) set -u HELP=" Cloud Build Notifiers setup script. This script runs almost all of the setup required for configuring and deploying a notifier on GCP. It is based on the guide here: https://cloud.google.com/cloud-build/docs/configure-notifications Setting up any 'secret_name' must be done outside this script. This script is assumed to be run in the root of your cloud-build-notifiers clone/fork. Currently, this script only deploys the 'latest' version of the notifier to Cloud Run. To check that your notifier configuration YAML can work with that version, run the notifier locally with the '--setup_check' flag that is mentioned in the repo root README.md. The currently supported notifier types (which correspond to the directories in the repo) are: * bigquery (under development) * http * slack * smtp Usage [in the cloud-build-notifiers repo root]: ./setup.sh <notifier-type> <local-config-path> [secret-name] Concrete example: ./setup.sh \ smtp \ ~/notifier-configs/my-smtp-config.yaml \ my-smtp-password For help/usage: ./setup.sh --help " main() { # Simple argument checks. if [ "$*" = "--help" ]; then echo "${HELP}" exit 0 elif [ $# -lt 2 ] || [ $# -gt 3 ]; then fail "${HELP}" fi NOTIFIER_TYPE="$1" SOURCE_CONFIG_PATH="$2" SECRET_NAME="${3:-}" # Optional secret_name name. # Check that the user is using a supported notifier type in the correct # directory. case "${NOTIFIER_TYPE}" in http | smtp | slack | bigquery) ;; *) fail "${HELP}" ;; esac if [ ! -d "${NOTIFIER_TYPE}" ]; then fail "expected to run from the root of the cloud-build-notifiers repo" fi if [ ! -r "${SOURCE_CONFIG_PATH}" ]; then fail "expected file at local source config path ${SOURCE_CONFIG_PATH} to be readable" fi # Project ID, assumed to NOT be org-scoped (only alphanumeric and dashes). PROJECT_ID=$(gcloud config get-value project) || fail "could not get default project" if [ "${PROJECT_ID}" = "(unset)" ]; then fail "default project not set; run \"gcloud config set project <project_id>\"" \ "or set the CLOUDSDK_CORE_PROJECT environment variable" fi if [ -z "${PROJECT_ID##*:*}" ]; then fail "org-scoped project IDs are not allowed by this script" fi PROJECT_NUMBER=$(gcloud projects describe "${PROJECT_ID}" \ --format="value(projectNumber)") || fail "could not get project number" REQUIRED_SERVICES=('Cloud Build API' 'Cloud Run Admin API' 'Cloud Pub/Sub API') SOURCE_CONFIG_BASENAME=$(basename "${SOURCE_CONFIG_PATH}") DESTINATION_BUCKET_NAME="${PROJECT_ID}-notifiers-config" DESTINATION_BUCKET_URI="gs://${DESTINATION_BUCKET_NAME}" DESTINATION_CONFIG_PATH="${DESTINATION_BUCKET_URI}/${SOURCE_CONFIG_BASENAME}" IMAGE_PATH="us-east1-docker.pkg.dev/gcb-release/cloud-build-notifiers/${NOTIFIER_TYPE}:latest" SERVICE_NAME="${NOTIFIER_TYPE}-notifier" SUBSCRIPTION_NAME="${NOTIFIER_TYPE}-subscription" INVOKER_SA="cloud-run-pubsub-invoker@${PROJECT_ID}.iam.gserviceaccount.com" PUBSUB_SA="service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com" # Turn on command echoing after all of the variables have been set so we # don't log spam unnecessarily. set -x check_apis_enabled if [ -n "${SECRET_NAME}" ]; then add_secret_name_accessor_permission fi upload_config deploy_notifier SERVICE_URL=$(gcloud run services describe "${SERVICE_NAME}" \ --format="value(status.url)") add_sa_token_creator_permission create_invoker_sa add_invoker_permission create_pubsub_topic check_pubsub_topic create_pubsub_subscription check_pubsub_subscription echo "** NOTIFIER SETUP COMPLETE **" 1>&2 } fail() { echo "$*" 1>&2 exit 1 } check_apis_enabled() { if [ -n "${SECRET_NAME}" ]; then REQUIRED_SERVICES+=('Secret Manager API') fi SERVICES=$(gcloud services list --enabled --format='value(config.title)') for API in "${REQUIRED_SERVICES[@]}"; do [ -z ${SERVICES[@]/*${API}*/} ] || fail "please enable the ${API}" done } add_secret_name_accessor_permission() { gcloud secrets add-iam-policy-binding "${SECRET_NAME}" \ --member="serviceAccount:${PROJECT_NUMBER}-compute@developer.gserviceaccount.com" \ --role="roles/secretmanager.secretAccessor" || fail "failed to set up secret access" } upload_config() { # We allow this `mb` command to error since we rely on the `cp` command hard- # erroring if there's an actual problem (since `mb` fails if the bucket # already exists). gsutil mb "${DESTINATION_BUCKET_URI}" gsutil cp "${SOURCE_CONFIG_PATH}" "${DESTINATION_CONFIG_PATH}" || fail "failed to copy config to GCS" } deploy_notifier() { gcloud run deploy "${SERVICE_NAME}" \ --image="${IMAGE_PATH}" \ --no-allow-unauthenticated \ --update-env-vars="CONFIG_PATH=${DESTINATION_CONFIG_PATH},PROJECT_ID=${PROJECT_ID}" || fail "failed to deploy notifier service -- check service logs for configuration error" } add_sa_token_creator_permission() { gcloud projects add-iam-policy-binding "${PROJECT_ID}" \ --member="serviceAccount:${PUBSUB_SA}" \ --role="roles/iam.serviceAccountTokenCreator" } create_invoker_sa() { gcloud iam service-accounts create cloud-run-pubsub-invoker \ --display-name "Cloud Run Pub/Sub Invoker" } add_invoker_permission() { gcloud run services add-iam-policy-binding "${SERVICE_NAME}" \ --member="serviceAccount:${INVOKER_SA}" \ --role=roles/run.invoker } create_pubsub_topic() { gcloud pubsub topics create cloud-builds } check_pubsub_topic() { gcloud pubsub topics describe cloud-builds || fail "expected the notifier Pub/Sub topic cloud-builds to exist" } create_pubsub_subscription() { gcloud pubsub subscriptions create "${SUBSCRIPTION_NAME}" \ --topic=cloud-builds \ --push-endpoint="${SERVICE_URL}" \ --push-auth-service-account="${INVOKER_SA}" } check_pubsub_subscription() { gcloud pubsub subscriptions describe "${SUBSCRIPTION_NAME}" || fail "expected the notifier Pub/Sub subscription to exist" } main "$@"
import datetime class Utc(datetime.tzinfo): __slots__ = () zero = datetime.timedelta(0) def utcoffset(self, _): return self.zero def dst(self, _): return self.zero def tzname(self, _): return 'UTC' try: utc = datetime.timezone.utc except AttributeError: utc = Utc()
; INCLUDE for DEBUGGING ; deb_buff - si pointer to text ; - di pointer to buffer deb_buff: push si call deb_wtxt mov si,di call deb_wbuff mov si, OFFSET crlf call deb_wtxt pop si retn ; deb_cnt_buff - si pointer to count ; - di pointer to buffer deb_cnt_buff: push ax push bx push cx push dx push si push di push bp mov ax,[si] mov al,ah call dbw_whex mov ax,[si] call dbw_whex call dbw_wspace mov si,di call deb_wbuff mov si, OFFSET crlf call deb_wtxt jmp deb_wexit ; deb_wchr - al character deb_wchr: push ax push bx push cx push dx push si push di push bp call dbw_wbyte jmp deb_wexit ; deb_wtxt - si pointer to text deb_wtxt: push ax push bx push cx push dx push si push di push bp deb_wtxtloop: lodsb ; next char test al,al jz deb_wexit call dbw_wbyte jmp deb_wtxtloop ; deb_whex - al value deb_whex: push ax push bx push cx push dx push si push di push bp call dbw_whex jmp deb_wexit ; deb_wbuff - si pointer to buffer deb_wbuff: push ax push bx push cx push dx push si push di push bp mov ax,si mov al,ah call dbw_whex mov ax,si call dbw_whex call dbw_wspace mov cx,16 jmp deb_wshxloop ; deb_wbhex - si pointer to buffer deb_wbhex: push ax push bx push cx push dx push si push di push bp mov cx,16 deb_wshxloop: push cx lodsb call dbw_whex pop cx loop deb_wshxloop deb_wexit: pop bp pop di pop si pop dx pop cx pop bx pop ax retn dbw_wspace: mov al,020h jmp dbw_wbyte dbw_whex: call dbw_btohex push ax mov al,dl call dbw_wbyte pop ax dbw_wbyte: mov ah,al mov dx,lpt_n ; any printer port 1? test dx,dx jz dbw_outnone inc dx ; read port status dbw_outwait: in al,dx test al,al ; bit 7 high jns dbw_outwait ; ... no mov al,ah dec dx out dx,al ; send data byte add dx,2 mov al,lpt_stblow ; and strobe out dx,al out dx,al mov al,lpt_stbhigh out dx,al dbw_outnone: retn dbw_btohex: ; call byte in al, ret first char in dl, second in al mov dh,al mov cl,4 shr al,cl ; first hex char call dbw_ntohex mov dl,al mov al,dh and al,0fh ; second hex char dbw_ntohex: cmp al,0ah ; letter? jb dbw_xadd0 add al,7 dbw_xadd0: add al,030h ; ascii CHAR retn
function requireDefault$__(obj){ return obj && obj.__esModule ? obj : { default: obj }; }; const Ψ__initor__ = Symbol.for('#__initor__'), Ψ__inited__ = Symbol.for('#__inited__'); Object.defineProperty(exports, "__esModule", {value: true}); /*body*/ var _$Authφ = requireDefault$__(require('../../Auth'/*$path$*/)); var _$DriverManagerφ = requireDefault$__(require('../../DriverManager'/*$path$*/)); var _$isEmptyφ = requireDefault$__(require('../../../Support/Helpers/isEmpty'/*$path$*/)); class Authenticate { /** @param {Repository} config */ constructor(config){ this.config = config; } /** @param {FormRequest} request @param {FastifyReply} reply @param {any[]|null} params */ async handle(request,reply,params){ const [protocol] = (!(_$isEmptyφ.default(params[0]))) ? params : [this.defaultProtocol]; this.configure(protocol); const handler = _$DriverManagerφ.default.get(protocol,request,reply,params,this.config); const personalAccessToken = await handler.verify(); return request.auth = function() { return new _$Authφ.default( personalAccessToken.tokenable, personalAccessToken.token.abilities, handler ); }; } get defaultProtocol(){ return this.config.get('auth.defaults.protocol','api'); } /** @param {String} protocol */ configure(protocol){ const fetchedProtocol = this.config.get(("auth.protocols." + protocol + ".provider")); if (_$isEmptyφ.default(fetchedProtocol)) { throw new Error(("" + protocol + " is not a valid authentication protocol")); }; const provider = this.config.get(("auth.providers." + fetchedProtocol)); return _$Authφ.default.setProvider(provider); } }; exports.default = Authenticate;
package com.mfglabs.stream import akka.stream.stage._ import akka.stream.{Attributes, FlowShape, Inlet, Outlet} /** * Inspired by https://doc.akka.io/docs/akka/2.5/stream/stream-cookbook.html#working-with-io */ class StatefulProcessor[A, B, C]( zero : => B, f : (B, A) => (Option[B], IndexedSeq[C]), lastPushIfUpstreamEnds: B => IndexedSeq[C] ) extends GraphStage[FlowShape[A, C]] { val in = Inlet[A]("StatefulProcessor.in") val out = Outlet[C]("StatefulProcessor.out") override val shape = FlowShape.of(in, out) override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) { private var state: B = _ private var buffer = Vector.empty[C] private var finishing = false setHandler(out, new OutHandler { override def onPull(): Unit = { if( state == null ) state = zero // to keep the laziness of zero emitChunkOrPull() } }) setHandler(in, new InHandler { override def onPush(): Unit = { if( state == null ) state = zero // to keep the laziness of zero val (newState, cs) = f(state, grab(in)) newState match { case Some(s) => state = s case None => finishing = true } buffer ++= cs emitChunkOrPull() } /** * We check out availaibility since a Pull might have been lost when closing. */ override def onUpstreamFinish(): Unit = { if( isAvailable(out) ) emitChunkOrPull() } }) def bufferFold(whenEmpty: => Unit)(f: C => Unit): Unit = { buffer match { case Seq() => whenEmpty case elem +: nextBuffer => buffer = nextBuffer f(elem) } } /** * We check first : * - if the customProcessor is ending * - if upstream ended */ private def emitChunkOrPull() = { if( finishing ){ bufferFold { completeStage() }{ elem => push(out, elem) } } else if( isClosed(in) ){ bufferFold { buffer = lastPushIfUpstreamEnds(state).toVector bufferFold { completeStage() } { elem => finishing = true push(out, elem) } }{ elem => push(out, elem) } } else bufferFold { pull(in) } { elem => push(out, elem) } } } }
class GameService require 'elo' def run_game(winner, loser) player_winner = Elo::Player.new(rating: winner.score.rating, games_played: winner.score.games_played) player_loser = Elo::Player.new(rating: loser.score.rating, games_played: loser.score.games_played) player_winner.wins_from(player_loser) winner.update_rating(player_winner) loser.update_rating(player_loser) end end
package temple.ast abstract class Annotation(val render: String) object Annotation { sealed abstract class AccessAnnotation(render: String) extends Annotation(render) sealed abstract class ValueAnnotation(render: String) extends Annotation(render) case object Unique extends ValueAnnotation("@unique") case object Server extends AccessAnnotation("@server") case object ServerSet extends AccessAnnotation("@serverSet") case object Client extends AccessAnnotation("@client") }
import tape from 'tape'; const test = tape; import { checksum, PackHeader, to_string, from_string, to_number, from_number, PackBodyStruct, PackBody, tail_placeholder, } from '../lib/core/htmix'; import { HTMIX_SUB_USER_REGISTER, HTMIX_MAIN_USER_MANAGER, } from '../lib/protocol'; // ////////////////////////////////////////////////////////////////////// // // PackHead // test('should checksum return 0', t => { // t.plan(1); // const htmix = new PackHeader(); // htmix.main_code = HTMIX_MAIN_USER_MANAGER; // htmix.sub_code = HTMIX_SUB_USER_REGISTER; // htmix.calc_checksum(); // // [16,16,0,0,0,1,0,1] cs=221 // const uint_8 = htmix.to_uint8(); // t.equal(checksum(uint_8) & 0xff, 0); // }); // test('protocol package header i/o array', t => { // const arr = [16, 16, 0, 0, 221, 1, 0, 1]; // const htmix = PackHeader.from(arr); // t.equal(htmix.main_code, 1); // t.equal(htmix.sub_code, 1); // t.equal(htmix.checksum, 221); // let buffer = new ArrayBuffer(8); // let view = new Uint8Array(buffer); // view.set(arr); // const uint_8 = htmix.to_uint8(); // t.equal(uint_8[0], view[0]); // t.equal(uint_8[1], view[1]); // t.equal(uint_8[2], view[2]); // t.equal(uint_8[3], view[3]); // t.equal(uint_8[4], view[4]); // t.equal(uint_8[5], view[5]); // t.equal(uint_8[6], view[6]); // t.equal(uint_8[7], view[7]); // t.end(); // }); // test('protocol package header i/o base64', t => { // const base64 = 'MTYsMTYsMCwwLDIyMSwxLDAsMQ=='; // const htmix = PackHeader.from(base64); // t.equal(htmix.to_base64(), base64); // t.equal(htmix.main_code, 1); // t.equal(htmix.sub_code, 1); // t.equal(htmix.checksum, 221); // t.end(); // }); // //////////////////////////////////////////////////////////// // // function // test('array buffer <-> string', t => { // const str = '2018年12月12日'; // const buf = from_string(str); // console.log(`buffer byte length: ${buf.byteLength}, buffer length ${buf.length}`); // let view = new ArrayBuffer(buf.byteLength); // const view_p = new Uint8Array(view); // view_p.set(buf); // t.equal(to_string(view, 0, view.byteLength), str); // t.end(); // }); test('array buffer <-> number', t => { const num = 32767; const buf = from_number(num); let view = new ArrayBuffer(buf.length); const view_p = new Int8Array(view); view_p.set(buf); t.equal(to_number(view, 0, view.byteLength), num); t.end(); }); // ///////////////////////////////////////////////////////////////// // // PackBody // interface ILoginTest { // name: string; //20 // age: number; // 4 // pwd: string; //20 // } // class LoginTest implements PackBodyStruct { // constructor(public login?: ILoginTest) { // } // init(view: ArrayBuffer): void { // if (this.login) { // const name_vw = from_string(this.login.name!); // const age_vw = from_number(this.login.age!); // const pwd_vw = from_string(this.login.pwd!); // let name_pt = new Int8Array(view, 0, 20); // name_pt.set(name_vw); // let age_pt = new Int8Array(view, 20, 4); // age_pt.set(age_vw); // let pwd_pt = new Int8Array(view, 24, 20); // pwd_pt.set(pwd_vw); // } // } // from(view: ArrayBuffer): void { // if (!this.login) { // this.login = { // name: to_string(view, 0, 20), // age: to_number(view, 20, 4), // pwd: to_string(view, 24, 20), // }; // } // } // length() { // return 20 + 4 + 20; // } // } // test('protocol package body from array buffer', t => { // const login = new PackBody(new LoginTest({ // name: '不超过十个字', // age: 24, // pwd: 'password' // })); // const result = [228, 184, 141, 232, 182, 133, 232, 191, 135, 229, // 141, 129, 228, 184, 170, 229, 173, 151, 0, 0, 0, // 0, 0, 24, 112, 97, 115, 115, 119, 111, 114, 100, // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // const uint_8 = login.to_uint8(); // const body = new PackBody(new LoginTest()); // body.from(uint_8); // const login_name = body.payload.login!.name; // const login_age = body.payload.login!.age; // const login_pwd = body.payload.login!.pwd; // t.same(login_name, '不超过十个字'); // t.same(login_age, 24); // t.same(login_pwd, 'password'); // t.end(); // }); // test('protocol package body from base64', t => { // const login = new PackBody(new LoginTest({ // name: '不超过十个字', // age: 24, // pwd: 'password' // })); // const b64 = login.to_base64(); // const body = new PackBody(new LoginTest()); // body.from(b64); // const login_name = body.payload.login!.name; // const login_age = body.payload.login!.age; // const login_pwd = body.payload.login!.pwd; // t.same(login_name, '不超过十个字'); // t.same(login_age, 24); // t.same(login_pwd, 'password'); // t.end(); // }); // /////////////////////////////////////////////////////////////////////////// // // 测试添加尾随数据的包 // interface IPackWithTail { // title: string; // time: number; // data: string; // } // class PackWithTail implements PackBodyStruct { // constructor(private pwt?: IPackWithTail) { // } // init(view: ArrayBuffer, tail?: number | undefined): void { // if (this.pwt) { // const title_view = from_string(this.pwt.title); // const title_pointer = new Uint8Array(view, 0, 20); // title_pointer.set(title_view); // const time_view = from_number(this.pwt.time); // const time_pointer = new Uint8Array(view, 20, 4); // time_pointer.set(time_view); // const data_view = from_string(this.pwt.data); // const data_pointer = new Uint8Array(view, 28, tail); // data_pointer.set(data_view); // const placeholder_view = from_number(data_view.byteLength); // const placeholder_pointer = new Uint8Array(view, 24, 4); // placeholder_pointer.set(placeholder_view); // } // } // from(view: ArrayBuffer): void { // if (!this.pwt) { // this.pwt = { // title: to_string(view, 0, 20), // time: to_number(view, 20, 4), // data: to_string(view, 28, to_number(view, 24, 4)), // }; // } // } // length(): number { // return 20 + 4; // } // } // test('测试添加尾随数据的包', t => { // t.plan(3); // const content = '通知:根据XX领导指示,现定于2018年8月20日进行考试,试题共X道,其中...'; // const bytes_length = from_string(content).byteLength; // const pwt = new PackWithTail({ // title: '考试通知', // time: 60,//分钟 // data: content, // }); // const body = new PackBody(pwt, bytes_length); // const buffer = body.to_uint8(); // let dpwt = new PackWithTail(); // const dbody = new PackBody(dpwt); // dbody.from(buffer); // const actual: any = dbody.payload['pwt']; // const expect: any = pwt['pwt']; // console.log(actual.data); // t.same(actual.title, expect.title); // t.equal(actual.time, expect.time); // t.same(actual.data, expect.data); // });
import { IPayloadMessage } from '..'; export interface IPayload<T> { data: T; message: IPayloadMessage; }
{-# language CPP #-} -- | = Name -- -- VK_KHR_present_wait - device extension -- -- == VK_KHR_present_wait -- -- [__Name String__] -- @VK_KHR_present_wait@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 249 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_swapchain@ -- -- - Requires @VK_KHR_present_id@ -- -- [__Contact__] -- -- - Keith Packard -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_KHR_present_wait] @keithp%0A<<Here describe the issue or question you have about the VK_KHR_present_wait extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2019-05-15 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Keith Packard, Valve -- -- - Ian Elliott, Google -- -- - Tobias Hector, AMD -- -- - Daniel Stone, Collabora -- -- == Description -- -- This device extension allows an application that uses the -- @VK_KHR_swapchain@ extension to wait for present operations to complete. -- An application can use this to monitor and control the pacing of the -- application by managing the number of outstanding images yet to be -- presented. -- -- == New Commands -- -- - 'waitForPresentKHR' -- -- == New Structures -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2', -- 'Vulkan.Core10.Device.DeviceCreateInfo': -- -- - 'PhysicalDevicePresentWaitFeaturesKHR' -- -- == New Enum Constants -- -- - 'KHR_PRESENT_WAIT_EXTENSION_NAME' -- -- - 'KHR_PRESENT_WAIT_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR' -- -- == Issues -- -- 1) When does the wait finish? -- -- __RESOLVED__. The wait will finish when the present is visible to the -- user. There is no requirement for any precise timing relationship -- between the presentation of the image to the user, but implementations -- /should/ signal the wait as close as possible to the presentation of the -- first pixel in the new image to the user. -- -- 2) Should this use fences or other existing synchronization mechanism. -- -- __RESOLVED__. Because display and rendering are often implemented in -- separate drivers, this extension will provide a separate synchronization -- API. -- -- 3) Should this extension share present identification with other -- extensions? -- -- __RESOLVED__. Yes. A new extension, VK_KHR_present_id, should be created -- to provide a shared structure for presentation identifiers. -- -- 4) What happens when presentations complete out of order wrt calls to -- vkQueuePresent? This could happen if the semaphores for the -- presentations were ready out of order. -- -- __OPTION A__: Require that when a PresentId is set that the driver -- ensure that images are always presented in the order of calls to -- vkQueuePresent. -- -- __OPTION B__: Finish both waits when the earliest present completes. -- This will complete the later present wait earlier than the actual -- presentation. This should be the easiest to implement as the driver need -- only track the largest present ID completed. This is also the -- \'natural\' consequence of interpreting the existing vkWaitForPresentKHR -- specificationn. -- -- __OPTION C__: Finish both waits when both have completed. This will -- complete the earlier presentation later than the actual presentation -- time. This is allowed by the current specification as there is no -- precise timing requirement for when the presentId value is updated. This -- requires slightly more complexity in the driver as it will need to track -- all outstanding presentId values. -- -- == Version History -- -- - Revision 1, 2019-02-19 (Keith Packard) -- -- - Initial version -- -- == See Also -- -- 'PhysicalDevicePresentWaitFeaturesKHR', 'waitForPresentKHR' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_present_wait Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_KHR_present_wait ( waitForPresentKHR , waitForPresentKHRSafe , PhysicalDevicePresentWaitFeaturesKHR(..) , KHR_PRESENT_WAIT_SPEC_VERSION , pattern KHR_PRESENT_WAIT_SPEC_VERSION , KHR_PRESENT_WAIT_EXTENSION_NAME , pattern KHR_PRESENT_WAIT_EXTENSION_NAME , SwapchainKHR(..) ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import GHC.Base (when) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word64) import Data.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.NamedType ((:::)) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkWaitForPresentKHR)) import Vulkan.Core10.Handles (Device_T) import Vulkan.Core10.Enums.Result (Result) import Vulkan.Core10.Enums.Result (Result(..)) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Extensions.Handles (SwapchainKHR) import Vulkan.Extensions.Handles (SwapchainKHR(..)) import Vulkan.Exception (VulkanException(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR)) import Vulkan.Core10.Enums.Result (Result(SUCCESS)) import Vulkan.Extensions.Handles (SwapchainKHR(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkWaitForPresentKHRUnsafe :: FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Word64 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Word64 -> IO Result foreign import ccall "dynamic" mkVkWaitForPresentKHRSafe :: FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Word64 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Word64 -> IO Result -- | waitForPresentKHR with selectable safeness waitForPresentKHRSafeOrUnsafe :: forall io . (MonadIO io) => (FunPtr (Ptr Device_T -> SwapchainKHR -> Word64 -> Word64 -> IO Result) -> Ptr Device_T -> SwapchainKHR -> Word64 -> Word64 -> IO Result) -> -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain on which an image was queued -- for presentation. SwapchainKHR -> -- | @presentId@ is the presentation presentId to wait for. ("presentId" ::: Word64) -> -- | @timeout@ is the timeout period in units of nanoseconds. @timeout@ is -- adjusted to the closest value allowed by the implementation-dependent -- timeout accuracy, which /may/ be substantially longer than one -- nanosecond, and /may/ be longer than the requested period. ("timeout" ::: Word64) -> io (Result) waitForPresentKHRSafeOrUnsafe mkVkWaitForPresentKHR device swapchain presentId timeout = liftIO $ do let vkWaitForPresentKHRPtr = pVkWaitForPresentKHR (case device of Device{deviceCmds} -> deviceCmds) unless (vkWaitForPresentKHRPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkWaitForPresentKHR is null" Nothing Nothing let vkWaitForPresentKHR' = mkVkWaitForPresentKHR vkWaitForPresentKHRPtr r <- traceAroundEvent "vkWaitForPresentKHR" (vkWaitForPresentKHR' (deviceHandle (device)) (swapchain) (presentId) (timeout)) when (r < SUCCESS) (throwIO (VulkanException r)) pure $ (r) -- | vkWaitForPresentKHR - Wait for presentation -- -- = Description -- -- 'waitForPresentKHR' waits for the presentId associated with @swapchain@ -- to be increased in value so that it is at least equal to @presentId@. -- -- For 'Vulkan.Extensions.VK_KHR_surface.PRESENT_MODE_MAILBOX_KHR' (or -- other present mode where images may be replaced in the presentation -- queue) any wait of this type associated with such an image /must/ be -- signaled no later than a wait associated with the replacing image would -- be signaled. -- -- When the presentation has completed, the presentId associated with the -- related @pSwapchains@ entry will be increased in value so that it is at -- least equal to the value provided in the -- 'Vulkan.Extensions.VK_KHR_present_id.PresentIdKHR' structure. -- -- There is no requirement for any precise timing relationship between the -- presentation of the image to the user and the update of the presentId -- value, but implementations /should/ make this as close as possible to -- the presentation of the first pixel in the new image to the user. -- -- The call to 'waitForPresentKHR' will block until either the presentId -- associated with @swapchain@ is greater than or equal to @presentId@, or -- @timeout@ nanoseconds passes. When the swapchain becomes OUT_OF_DATE, -- the call will either return 'Vulkan.Core10.Enums.Result.SUCCESS' (if the -- image was delivered to the presentation engine and may have been -- presented to the user) or will return early with status -- 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DATE_KHR' (if the image was not -- presented to the user). -- -- As an exception to the normal rules for objects which are externally -- synchronized, the @swapchain@ passed to 'waitForPresentKHR' /may/ be -- simultaneously used by other threads in calls to functions other than -- 'Vulkan.Extensions.VK_KHR_swapchain.destroySwapchainKHR'. Access to the -- swapchain data associated with this extension /must/ be atomic within -- the implementation. -- -- == Valid Usage -- -- - #VUID-vkWaitForPresentKHR-swapchain-04997# @swapchain@ /must/ not be -- in the retired state -- -- - #VUID-vkWaitForPresentKHR-presentWait-06234# The -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#features-presentWait presentWait> -- feature /must/ be enabled -- -- == Valid Usage (Implicit) -- -- - #VUID-vkWaitForPresentKHR-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkWaitForPresentKHR-swapchain-parameter# @swapchain@ /must/ be -- a valid 'Vulkan.Extensions.Handles.SwapchainKHR' handle -- -- - #VUID-vkWaitForPresentKHR-commonparent# Both of @device@, and -- @swapchain@ /must/ have been created, allocated, or retrieved from -- the same 'Vulkan.Core10.Handles.Instance' -- -- == Host Synchronization -- -- - Host access to @swapchain@ /must/ be externally synchronized -- -- == Return Codes -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-successcodes Success>] -- -- - 'Vulkan.Core10.Enums.Result.SUCCESS' -- -- - 'Vulkan.Core10.Enums.Result.TIMEOUT' -- -- [<https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#fundamentals-errorcodes Failure>] -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_HOST_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_OUT_OF_DEVICE_MEMORY' -- -- - 'Vulkan.Core10.Enums.Result.ERROR_DEVICE_LOST' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_present_wait VK_KHR_present_wait>, -- 'Vulkan.Core10.Handles.Device', 'Vulkan.Extensions.Handles.SwapchainKHR' waitForPresentKHR :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain on which an image was queued -- for presentation. SwapchainKHR -> -- | @presentId@ is the presentation presentId to wait for. ("presentId" ::: Word64) -> -- | @timeout@ is the timeout period in units of nanoseconds. @timeout@ is -- adjusted to the closest value allowed by the implementation-dependent -- timeout accuracy, which /may/ be substantially longer than one -- nanosecond, and /may/ be longer than the requested period. ("timeout" ::: Word64) -> io (Result) waitForPresentKHR = waitForPresentKHRSafeOrUnsafe mkVkWaitForPresentKHRUnsafe -- | A variant of 'waitForPresentKHR' which makes a *safe* FFI call waitForPresentKHRSafe :: forall io . (MonadIO io) => -- | @device@ is the device associated with @swapchain@. Device -> -- | @swapchain@ is the non-retired swapchain on which an image was queued -- for presentation. SwapchainKHR -> -- | @presentId@ is the presentation presentId to wait for. ("presentId" ::: Word64) -> -- | @timeout@ is the timeout period in units of nanoseconds. @timeout@ is -- adjusted to the closest value allowed by the implementation-dependent -- timeout accuracy, which /may/ be substantially longer than one -- nanosecond, and /may/ be longer than the requested period. ("timeout" ::: Word64) -> io (Result) waitForPresentKHRSafe = waitForPresentKHRSafeOrUnsafe mkVkWaitForPresentKHRSafe -- | VkPhysicalDevicePresentWaitFeaturesKHR - Structure indicating support -- for present wait -- -- = Members -- -- This structure describes the following feature: -- -- = Description -- -- If the 'PhysicalDevicePresentWaitFeaturesKHR' structure is included in -- the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. 'PhysicalDevicePresentWaitFeaturesKHR' /can/ also be used in -- the @pNext@ chain of 'Vulkan.Core10.Device.DeviceCreateInfo' to -- selectively enable these features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_KHR_present_wait VK_KHR_present_wait>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDevicePresentWaitFeaturesKHR = PhysicalDevicePresentWaitFeaturesKHR { -- | #features-presentWait# @presentWait@ indicates that the implementation -- supports 'waitForPresentKHR'. presentWait :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDevicePresentWaitFeaturesKHR) #endif deriving instance Show PhysicalDevicePresentWaitFeaturesKHR instance ToCStruct PhysicalDevicePresentWaitFeaturesKHR where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDevicePresentWaitFeaturesKHR{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (presentWait)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENT_WAIT_FEATURES_KHR) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDevicePresentWaitFeaturesKHR where peekCStruct p = do presentWait <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) pure $ PhysicalDevicePresentWaitFeaturesKHR (bool32ToBool presentWait) instance Storable PhysicalDevicePresentWaitFeaturesKHR where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDevicePresentWaitFeaturesKHR where zero = PhysicalDevicePresentWaitFeaturesKHR zero type KHR_PRESENT_WAIT_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_KHR_PRESENT_WAIT_SPEC_VERSION" pattern KHR_PRESENT_WAIT_SPEC_VERSION :: forall a . Integral a => a pattern KHR_PRESENT_WAIT_SPEC_VERSION = 1 type KHR_PRESENT_WAIT_EXTENSION_NAME = "VK_KHR_present_wait" -- No documentation found for TopLevel "VK_KHR_PRESENT_WAIT_EXTENSION_NAME" pattern KHR_PRESENT_WAIT_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern KHR_PRESENT_WAIT_EXTENSION_NAME = "VK_KHR_present_wait"
package com.example.calculo.percentual.gordura.components class ValidadorDadosCalculoForm(private var form: DadosCalculoForm) { fun validar(): Boolean{ return validarCamposBasicos() && if (form.isSexoMasculino()) this.validarCamposMasculino() else this.validarCamposFeminino() } private fun validarCamposBasicos(): Boolean { if (isEmpty(form.idade)) { form.exibirMensagemErroIdade() return false } if (isEmpty(form.peso)) { form.exibirMensagemErroPeso() return false } if (isEmpty(form.supra)) { form.exibirMensagemErroSupra() return false } return true } private fun validarCamposMasculino(): Boolean { if (isEmpty(form.triceps)) { form.exibirMensagemErroTriceps() return false } if (isEmpty(form.abdominal)) { form.exibirMensagemErroAbdominal() return false } return true } private fun validarCamposFeminino(): Boolean { if (isEmpty(form.subescapular)) { form.exibirMensagemErroSubescapular() return false } if (isEmpty(form.coxa)) { form.exibirMensagemErroCoxa() return false } return true } private fun isEmpty(valor: String) = valor == "" }
use crate::config::{ConnectionUri, TransformerTypeConfig}; use crate::{Config, DumpCommand, RestoreCommand, SubCommand, TransformerCommand}; use chrono::{NaiveDateTime, Utc}; use reqwest::blocking::Client as HttpClient; use reqwest::header::CONTENT_TYPE; use serde::Serialize; use std::collections::{HashMap, HashSet}; use std::io::{Error, ErrorKind}; use std::time::Duration; extern crate serde_json; pub const TELEMETRY_TOKEN: &str = "phc_3I35toj7Gbkiz5YZdxt2h5KOWBEfRx17qLCZ2OWj5Bt"; const API_ENDPOINT: &str = "https://app.posthog.com/capture/"; const TIMEOUT: &Duration = &Duration::from_millis(3000); pub struct ClientOptions { api_endpoint: String, api_key: String, } impl From<&str> for ClientOptions { fn from(api_key: &str) -> Self { ClientOptions { api_endpoint: API_ENDPOINT.to_string(), api_key: api_key.to_string(), } } } pub struct TelemetryClient { options: ClientOptions, client: HttpClient, } impl TelemetryClient { pub fn new<C: Into<ClientOptions>>(options: C) -> Self { let client = HttpClient::builder() .timeout(Some(TIMEOUT.clone())) .build() .unwrap(); // Unwrap here is as safe as `HttpClient::new` TelemetryClient { options: options.into(), client, } } pub fn capture(&self, event: Event) -> Result<(), Error> { let inner_event = InnerEvent::new(event, self.options.api_key.clone()); let _res = self .client .post(self.options.api_endpoint.clone()) .header(CONTENT_TYPE, "application/json") .body(serde_json::to_string(&inner_event).expect("unwrap here is safe")) .send() .map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?; Ok(()) } pub fn capture_batch(&self, events: Vec<Event>) -> Result<(), Error> { for event in events { self.capture(event)?; } Ok(()) } pub fn capture_command( &self, config: &Config, sub_command: &SubCommand, args: &Vec<String>, execution_time_in_millis: Option<u128>, ) -> Result<(), Error> { let mut props = HashMap::new(); let _ = props.insert("args".to_string(), args.join(" ").to_string()); props.insert( "encryption_used".to_string(), config.encryption_key.is_some().to_string(), ); match &config.source { Some(x) => { props.insert( "database".to_string(), match x.connection_uri()? { ConnectionUri::Postgres(_, _, _, _, _) => "postgresql", ConnectionUri::Mysql(_, _, _, _, _) => "mysql", ConnectionUri::MongoDB(_, _) => "mongodb", } .to_string(), ); props.insert( "compression_used".to_string(), x.compression.unwrap_or(true).to_string(), ); props.insert("skip_tables_used".to_string(), x.skip.is_some().to_string()); props.insert( "subset_used".to_string(), x.database_subset.is_some().to_string(), ); let mut transformers = HashSet::new(); if let Some(transformers_config) = &x.transformers { for transformer in transformers_config { for column in &transformer.columns { transformers.insert(match column.transformer { TransformerTypeConfig::Random => "random", TransformerTypeConfig::RandomDate => "random-date", TransformerTypeConfig::FirstName => "first-name", TransformerTypeConfig::Email => "email", TransformerTypeConfig::KeepFirstChar => "keep-first-char", TransformerTypeConfig::PhoneNumber => "phone-number", TransformerTypeConfig::CreditCard => "credit-card", TransformerTypeConfig::Redacted(_) => "redacted", TransformerTypeConfig::Transient => "transient", TransformerTypeConfig::CustomWasm(_) => "custom-wasm", }); } } for (idx, transformer_name) in transformers.iter().enumerate() { props.insert(format!("transformer_{}", idx), transformer_name.to_string()); } } } None => {} }; let event = match sub_command { SubCommand::Dump(cmd) => match cmd { DumpCommand::List => "dump-list", DumpCommand::Create(_) => "dump-create", DumpCommand::Delete(_) => "dump-delete", DumpCommand::Restore(restore_cmd) => match restore_cmd { RestoreCommand::Local(_) => "dump-restore-local", RestoreCommand::Remote(_) => "dump-restore-remote", }, }, SubCommand::Transformer(cmd) => match cmd { TransformerCommand::List => "transformer-list", }, }; self.capture(Event { event: event.to_string(), properties: Properties { distinct_id: machine_uid::get().unwrap_or("unknown".to_string()), props, }, timestamp: Some(Utc::now().naive_utc()), }) } } // This exists so that the client doesn't have to specify the API key over and over #[derive(Serialize)] struct InnerEvent { api_key: String, event: String, properties: Properties, timestamp: Option<NaiveDateTime>, } impl InnerEvent { fn new(event: Event, api_key: String) -> Self { Self { api_key, event: event.event, properties: event.properties, timestamp: event.timestamp, } } } pub struct Event { pub event: String, pub properties: Properties, pub timestamp: Option<NaiveDateTime>, } #[derive(Serialize)] pub struct Properties { pub distinct_id: String, pub props: HashMap<String, String>, }
# 049.Don't judge a person by their apperance. ## 翻译 > **不要以貌取人。** ## 文稿 ![](img/049.jpg)
import * as DBService from '/src/service/db-service.js'; import { INDEFINITE } from '/src/lib/deadline.js'; export default function DbControl() { } DbControl.prototype.init = function () { chrome.runtime.onInstalled.addListener(this.onInstalled.bind(this)); }; DbControl.prototype.onInstalled = async function (event) { if (event.reason === 'install') { // This is one of the earliest, if not the earliest, calls to open the database once the // extension is installed or updated, so we want to allow for the extra time it takes to // complete the upgrade, so we do not impose a timeout in this case. const conn = await DBService.open(INDEFINITE); conn.close(); } };
using AutoMapper; namespace Menu.AutoMapper { public static class Configuration { public static void AutoMapperConfig() { Mapper.Initialize(x => { x.AddProfile<EntityToModelConfiguration>(); x.AddProfile<ModelToEntityConfiguration>(); }); } } }
import React from 'react'; import '../Sidebar/Sidebar.css'; import { SpecialSupervision } from './Identify'; /* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */ export default { title: 'Identify/Special Supervision', component: SpecialSupervision, }; export const Normal = () => ( <SpecialSupervision> {{ address: '1405 Washington Blvd', address_start_date: 1535750000000, address_type: '1st PHYSICAL', agent_name: 'Steve Gourley', alerts: 'mean dog', cautions: 'lies a lot and has a concealed carry license', date_of_birth: 648949400000, earned_compliance_credit: 1535750000000, employer_address: 'WEST HIGHWAY 40, ROOSEVELT UT 84066', employer_phone: '435-722-5650', gang_id: null, gang_name: 'West Side Players', gang_type_id: null, offense_code: 'J', offense_description: null, primary_offense: null, race: 'native american/alaskan', ccc: 0, comp: 0, dep: 0, dora: 0, drugct: 0, ecr: 0, em: 0, fosi: 0, fug: 0, gps: 0, igint: 0, incar: 1, mio: 1, pvp: 0, resid: 0, so: 0, soa: 1, sob: 1, soc: 1, state: 'UT', supervision_start_date: 1471327200000, unit: '#8', crime_degree: 'MA', offender_phone: '801-888-0101', }} </SpecialSupervision> ); export const Single = () => ( <SpecialSupervision> {{ address: '1405 Washington Blvd', address_start_date: 1535750000000, address_type: '1st PHYSICAL', agent_name: 'Steve Gourley', alerts: 'mean dog', cautions: 'lies a lot and has a concealed carry license', date_of_birth: 648949400000, earned_compliance_credit: 1535750000000, employer_address: 'WEST HIGHWAY 40, ROOSEVELT UT 84066', employer_phone: '435-722-5650', gang_id: null, gang_name: 'West Side Players', gang_type_id: null, offense_code: 'J', offense_description: null, primary_offense: null, race: 'native american/alaskan', ccc: 0, comp: 0, dep: 0, dora: 0, drugct: 0, ecr: 0, em: 0, fosi: 0, fug: 0, gps: 0, igint: 0, incar: 0, mio: 0, pvp: 0, resid: 0, so: 0, soa: 0, sob: 0, soc: 1, state: 'UT', supervision_start_date: 1471327200000, unit: '#8', crime_degree: 'MA', offender_phone: '801-888-0101', }} </SpecialSupervision> ); export const Empty = () => ( <SpecialSupervision> {{ address: '1405 Washington Blvd', address_start_date: 1535750000000, address_type: '1st PHYSICAL', agent_name: 'Steve Gourley', alerts: 'mean dog', cautions: 'lies a lot and has a concealed carry license', date_of_birth: 648949400000, earned_compliance_credit: 1535750000000, employer_address: 'WEST HIGHWAY 40, ROOSEVELT UT 84066', employer_phone: '435-722-5650', gang_id: null, gang_name: 'West Side Players', gang_type_id: null, offense_code: 'J', offense_description: null, primary_offense: null, race: 'native american/alaskan', ccc: 0, comp: 0, dep: 0, dora: 0, drugct: 0, ecr: 0, em: 0, fosi: 0, fug: 0, gps: 0, igint: 0, incar: 0, mio: 0, pvp: 0, resid: 0, so: 0, soa: 0, sob: 0, soc: 0, state: 'UT', supervision_start_date: 1471327200000, unit: '#8', crime_degree: 'MA', offender_phone: '801-888-0101', }} </SpecialSupervision> );
### This is file doc/my_markdown_file.md <!--phmdoctest-label my-fenced-code-block--> ``` The label directive can be placed on any fenced code block. ```
using System; using System.Collections.Generic; using System.Text; namespace AnZwDev.ALTools.Server.Contracts.SymbolsInformation { public class GetTableBasedSymbolDetailsRequest : GetSymbolInformationDetailsRequest { public bool getExistingFields { get; set; } public bool getAvailableFields { get; set; } } }
--- title: "프로그래머스 - 정수 제곱근 판별" categories: - programmers last_modified_at: 2020-08-19T17:20:00+09:00 --- ### [<u>문제 링크</u>](https://programmers.co.kr/learn/courses/30/lessons/12934){: target="_blank"} <br/> ### 풀이 - `math` 모듈의 `sqrt`함수로 정수의 제곱근을 구할 수 있다. - `pow`함수로는 제곱수를 구할 수 있다. - `is_integer()`로는 해당 숫자가 정수인지 판별할 수 있다. <br/> ### 소스코드 ```python from math import sqrt def solution(n): return pow(int(sqrt(n)) + 1, 2) if sqrt(n).is_integer() else -1 ```
export { default as useDetectClickOutside } from './useDetectClickOutside'; export { default as useValidator } from './useValidator'; export * from './useFormValue';
namespace UglyToad.PdfPig.Tokenization.Scanner { using Tokens; /// <summary> /// Scan input for PostScript/PDF tokens. /// </summary> public interface ITokenScanner { /// <summary> /// Read the next token in the input. /// </summary> /// <returns></returns> bool MoveNext(); /// <summary> /// The currently read token. /// </summary> IToken CurrentToken { get; } /// <summary> /// Try reading a token of the specific type. /// </summary> bool TryReadToken<T>(out T token) where T : class, IToken; } }
#include "Node.h" #include <iostream> using namespace std; Node::Node() { word = ""; next = this; prev = this; } Node::Node(std::string input) { word = input; next = this; prev = this; } Node::Node(std::string input, Node* other) { this->setWord(input); //other is previous node this->setPrev(other); this->setNext(other); other->setNext(this); other->setPrev(this); } string& Node::getWord() { return word; } Node* Node::getNext() const { return this->next; } Node* Node::getPrev() const { return this->prev; } void Node::setWord(std::string input) { this->word = input; } void Node::setNext(Node * input) { this->next = input; } void Node::setPrev(Node * input) { this->prev = input; }
""" Created by akiselev on 2019-05-16 """ def merge_the_tools(string, k): # your code goes here if len(string)<2: print(string) return n=len(string) for i in range(0,n,k): res=[] substring=string[i:i+k] for j in substring: if j not in res: res.append(j) print(''.join(res)) return if __name__ == '__main__': #string, k = input(), int(input()) string = "AABCAAADA" k = 3 merge_the_tools(string, k)
#!/bin/bash # # Copyright © Portable EHR inc, 2021 # https://portableehr.com/ # # Need help -> runFeed.sh -h function showHelp { echo "#" echo "# Usage : runFeed.sh [-b ${BIN_FOLDER}] [-p ${SERVER_PORT}] [-m ${MOCKS_BASE_PATH}]" echo "# [-f ${FEED_HUB_BASE_PATH}] [--sslFile ${SSL_KEY_STORE_FILE}] [--sslType ${SSL_KEY_STORE_TYPE}]" echo "# [--sslPass ${SSL_KEY_STORE_PASSWORD}] [--sslAlias ${SSL_KEY_ALIAS}] [-h|--help]" echo "# Options :" echo "# -b BIN_FOLDER The folder where the portableehr-java-feed.jar is" echo "# Default value : ./bin" echo "# -p SERVER_PORT The port the Feed will use" echo "# Default value : 4004" echo "# -m MOCKS_BASE_PATH The path to the mocks folder" echo "# Default value : ./" echo "# -f FEED_HUB_BASE_PATH The base path to FeedHub" echo "# Default value : https://feed.portableehr.io:3004" echo "# --sslFile SSL_KEY_STORE_FILE The keystore containing the ssl key" echo "# Default value : classpath:PortableEHRJavaFeed.p12" echo "# --sslType SSL_KEY_STORE_TYPE The type of keystore" echo "# Default value : PKCS12" echo "# --sslPass SSL_KEY_STORE_PASSWORD The password of the keystore" echo "# Default value : changeit" echo "# --sslAlias SSL_KEY_ALIAS The key alias in the keystore" echo "# Default value : PEHRFeed" echo "# -h|--help Show this help" echo "#" } BIN_FOLDER='./bin' SERVER_PORT=4004 MOCKS_BASE_PATH='./' FEED_HUB_BASE_PATH='https://feed.portableehr.io:3004' SSL_KEY_STORE_FILE='classpath:PortableEHRJavaFeed.p12' SSL_KEY_STORE_TYPE='PKCS12' SSL_KEY_STORE_PASSWORD='changeit' SSL_KEY_ALIAS='PEHRFeed' POSITIONAL=() while [[ $# -gt 0 ]]; do key="$1" case $key in -b) BIN_FOLDER="$2" shift # past argument shift # past value ;; -p) SERVER_PORT="$2" shift # past argument shift # past value ;; -m) MOCKS_BASE_PATH="$2" shift # past argument shift # past value ;; -f) FEED_HUB_BASE_PATH="$2" shift # past argument shift # past value ;; --sslFile) SSL_KEY_STORE_FILE="$2" shift # past argument shift # past value ;; --sslType) SSL_KEY_STORE_TYPE="$2" shift # past argument shift # past value ;; --sslPass) SSL_KEY_STORE_PASSWORD="$2" shift # past argument shift # past value ;; --sslAlias) SSL_KEY_ALIAS="$2" shift # past argument shift # past value ;; -h|--help) showHelp exit 0 ;; *) # unknown option POSITIONAL+=("$1") # save it in an array for later shift # past argument ;; esac done if (( ${#POSITIONAL[@]} )); then echo "Unknown options : $POSITIONAL" echo "Try 'runFeed.sh -h'" exit 1; fi pid=`cat feed.pid` echo "Killing old Java Feed (PID=$pid)" kill $pid java -jar "$BIN_FOLDER"/portableehr-java-feed.jar \ --server.port="$SERVER_PORT" \ --mocks.basePath="$MOCKS_BASE_PATH" \ --feedhub.basePath="$FEED_HUB_BASE_PATH" \ --server.ssl.key-store="$SSL_KEY_STORE_FILE" \ --server.ssl.key-store-type="$SSL_KEY_STORE_TYPE" \ --server.ssl.key-store-password="$SSL_KEY_STORE_PASSWORD" \ --server.ssl.key-alias="$SSL_KEY_ALIAS" \ > portableehr-java-feed.log & echo $! > feed.pid echo "Tailing portableehr-java-feed.log..." tail -F portableehr-java-feed.log
# frozen_string_literal: true module FinApps module REST class AlertOccurrences < FinAppsCore::REST::Resources include FinApps::Utils::QueryBuilder END_POINT = 'portfolio/alerts/occurrences' def list(params = nil) return super END_POINT if params.nil? fail FinAppsCore::InvalidArgumentsError, 'Invalid argument: params' unless params.is_a? Hash super build_query_path(END_POINT, params) end private def build_filter(params) filter = {} filter[:portfolio_id] = params[:portfolio_id] if params[:portfolio_id] filter end end end end
import 'package:flutter/material.dart'; class TimeStampTimeAgo extends StatelessWidget { final timeStampData; final Color textColor; final double textFontSize; final FontWeight textFontWeight; final String fontFamily; final String yearAgo; final String monthAgo; final String dayAgo; final String hourAgo; final String minuteAgo; final String minuteLater; final String hourLater; final String dayLater; final String monthLater; final String yearLater; TimeStampTimeAgo( {Key key, @required this.timeStampData, this.textColor: Colors.black, this.textFontSize: 14, this.textFontWeight: FontWeight.w400, this.fontFamily: "roboto", this.yearAgo: 'years ago', this.monthAgo: 'months ago', this.dayAgo: 'days ago', this.hourAgo: 'hours ago', this.minuteAgo: 'minutes ago', this.minuteLater: 'minutes later', this.hourLater: 'hours later', this.dayLater: 'days later', this.monthLater: 'months later', this.yearLater: 'years later'}) : assert(timeStampData != null), super(key: key); @override Widget build(BuildContext context) { //TimeStamp to DateTime DateTime convertDateTime = DateTime.fromMillisecondsSinceEpoch( timeStampData.millisecondsSinceEpoch); //Minute int minute = DateTime.now().difference(convertDateTime).inMinutes; int convertPositiveMinute = DateTime.now().difference(convertDateTime).inMinutes * -1; //Hour int hour = DateTime.now().difference(convertDateTime).inHours; int convertPositiveHour = DateTime.now().difference(convertDateTime).inHours * -1; //Day int day = DateTime.now().difference(convertDateTime).inDays; int convertPositiveDay = (day * -1) + 1; //Convert Duration Duration duration = DateTime.now().difference(convertDateTime); //Month int month = (duration.inDays / 30).floor(); int convertPositiveMonth = (duration.inDays / 30 * -1).floor(); //Year int differenceInYear = (duration.inDays / 365).floor(); int convertPositiveDifferenceInYear = (duration.inDays / 365 * -1).floor(); if (hour >= 8760) { return Text( '$differenceInYear' + ' $yearAgo', style: buildTextStyle(), ); } else if (hour >= 720 && hour < 8760) { return Text( '$month' + ' $monthAgo', style: buildTextStyle(), ); } else if (hour >= 24 && hour < 720) { return Text( '$day' + ' $dayAgo', style: buildTextStyle(), ); } else if (hour >= 1 && hour < 24) { return Text( '$hour' + ' $hourAgo', style: buildTextStyle(), ); } else if (minute >= 0 && minute <= 60) { return Text( '$minute' + ' $minuteAgo', style: buildTextStyle(), ); } else if (minute <= 0 && minute >= -60) { return Text( '$convertPositiveMinute' + ' $minuteLater', style: buildTextStyle(), ); } else if (hour <= 0 && hour >= -24) { return Text( '$convertPositiveHour' + ' $hourLater', style: buildTextStyle(), ); } else if (hour < -24 && hour >= -720) { return Text( '$convertPositiveDay' + ' $dayLater', style: buildTextStyle(), ); } else if (hour <= -720 && hour >= -8760) { return Text( '$convertPositiveMonth ' + ' $monthLater', style: buildTextStyle(), ); } else if (hour < -8760) { return Text( '$convertPositiveDifferenceInYear' + ' $yearLater', style: buildTextStyle(), ); } else { return Text( ' ', style: buildTextStyle(), ); } } TextStyle buildTextStyle() => TextStyle( fontSize: textFontSize, color: textColor, fontWeight: textFontWeight, fontFamily: fontFamily, ); }
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/iAd.framework/iAd */ @interface ADPrivacyRemoteViewController : _UIRemoteViewController { <ADPrivacyRemoteViewControllerDelegate> * _delegate; } @property (nonatomic) <ADPrivacyRemoteViewControllerDelegate> *delegate; + (id)exportedInterface; + (id)serviceViewControllerInterface; - (void)_handleError:(id)arg1; - (void)_remote_adSheetDidTerminate; - (void)_remote_dismissPrivacyViewController; - (void)_remote_privacyViewControllerDidAppear; - (void)_remote_privacyViewControllerDidLinkOut; - (void)_remote_privacyViewControllerDidRenderTransparency; - (void)_remote_viewControllerDidLoad; - (void)dealloc; - (id)delegate; - (void)setDelegate:(id)arg1; - (void)viewServiceDidTerminateWithError:(id)arg1; @end
% Arbitrary expressions are not valid types var a : 1 var a : 1 ** 2 var a : (1 * 6 - 1 + 4 = 1) var a : false %%% args: --only_parser -dump ast -b %%% expected exit status: 255 %%% expected stdout: %%% ast: { %%% var [id:0] : { ref_expr nat(1) } %%% var [id:1] : { ref_expr nat(1) ** nat(2) } %%% var [id:2] : { ref_expr (nat(1) * nat(6) - nat(1) + nat(4) = nat(1)) } %%% var [id:3] : { ref_expr bool(false) } %%% } %%% expected stderr: %%% error line:2 column:9-10 Expression is not a valid type reference %%% error line:3 column:9-15 Expression is not a valid type reference %%% error line:4 column:9-28 Expression is not a valid type reference %%% error line:5 column:9-14 Expression is not a valid type reference
import {System} from "./node_modules/ecsy/build/ecsy.module.js" import {CanvasTexture, Mesh, MeshBasicMaterial, PlaneGeometry} from "./node_modules/three/build/three.module.js" import {ThreeCore} from './threesystem.js' export class VRStats { constructor() { this.canvas = null this.width = -1 this.height = -1 this.ctex = null this.lastTime = -1 } } export class VRStatsSystem extends System { execute(delta,time) { this.queries.stats.added.forEach(ent => { const stats = ent.getMutableComponent(VRStats) stats.canvas = document.createElement('canvas') stats.width = 256 stats.height = 256 stats.canvas.width = stats.width stats.canvas.height = stats.height stats.lastDraw = 0 stats.ctex = new CanvasTexture(stats.canvas) stats.obj = new Mesh( new PlaneGeometry(1,1.0), new MeshBasicMaterial({map:stats.ctex}) ) stats.obj.position.z = -3 stats.obj.position.y = 1.0 stats.obj.position.x = 0 stats.obj.material.depthTest = false stats.obj.material.depthWrite = false stats.obj.renderOrder = 1000 stats.customProps = {} const core = this.queries.three.results[0].getMutableComponent(ThreeCore) core.scene.add(stats.obj) }) this.queries.stats.results.forEach(ent =>{ const stats = ent.getMutableComponent(VRStats) if(time - stats.lastTime > 1.0) { const core = this.queries.three.results[0].getMutableComponent(ThreeCore) const fps = ((core.renderer.info.render.frame - stats.lastFrame))/(time-stats.lastTime) const c = stats.canvas.getContext('2d') c.save() c.fillStyle = 'white' c.fillRect(0, 0, stats.canvas.width, stats.canvas.height) c.fillStyle = 'black' c.font = '32pt sans-serif' const lh = 32+10 c.fillText(`calls: ${core.renderer.info.render.calls}`, 3, lh*1) c.fillText(`tris : ${core.renderer.info.render.triangles}`, 3, lh*2) c.fillText(`fps : ${fps.toFixed(2)}`,3,lh*3) Object.keys(stats.customProps).forEach((key,i) => { const val = stats.customProps[key] c.fillText(`${key} : ${val}`,3,lh*3+i*20) }) c.restore() stats.obj.material.map.needsUpdate = true stats.lastTime = time stats.lastFrame = core.renderer.info.render.frame } }) } } VRStatsSystem.queries = { stats: { components:[VRStats], listen: { added:true, removed:true, } }, three: { components: [ThreeCore] }, } /* */
package main var input = []int{ 104042, 112116, 57758, 139018, 105580, 148312, 139340, 62939, 50925, 63881, 138725, 54735, 54957, 103075, 55457, 98808, 87206, 58868, 120829, 124551, 63631, 103358, 149501, 147414, 59731, 88284, 59034, 116206, 52299, 119619, 63648, 85456, 110391, 90254, 99360, 59529, 82628, 82693, 64331, 123779, 123064, 93600, 104226, 74068, 74354, 149707, 51503, 130433, 80778, 72279, 148782, 113454, 138409, 148891, 79257, 126927, 141696, 107136, 66200, 120929, 149350, 76952, 134002, 62354, 144559, 125186, 85169, 61662, 90252, 147774, 101960, 55254, 96885, 88249, 133866, 121809, 103675, 94407, 59078, 81498, 82547, 132599, 81181, 141685, 73476, 107700, 133314, 77982, 149270, 119176, 148255, 81023, 143938, 54348, 121790, 126521, 101123, 139921, 51152, 97943, }
import { NextFunction, Request, RequestHandler, Response } from 'express'; import { OriginMasterDescriptive } from '../../Util/Roblox.Web.Util/OriginMaster'; export const OnlyCORs = (host: string) => ((request: Request, response: Response, resumeFunction: NextFunction) => { const omd = new OriginMasterDescriptive(response, host); response.header( 'Access-Control-Allow-Headers', 'Origin, Referer, X-Requested-With, Content-Type, X-CSRF-TOKEN, Pragma, Cache-Control, expires', ); response.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); omd.ExecuteOriginCheck(request.headers['origin'], request.protocol); return resumeFunction(); }) as RequestHandler;
%ifndef EXE_LENGTH %include "../UltimaPatcher.asm" %include "include/uw1.asm" %include "include/uw1-eop.asm" %include "include/additionalCharacterCodes.asm" %include "include/bindKeyOrMouse.asm" defineAddress 134, 0x018E, bindsBegin defineAddress 134, 0x06D8, bindsEnd %endif [bits 16] ; TODO: read key bindings from a configuration file startPatch EXE_LENGTH, \ customize key and mouse bindings startBlockAt addr_bindsBegin ; TODO: find out the difference between interface modes 1 and 16 ; (is 17 useful, or can it be replaced with 1?) ; movement keys here were redundant; handled in movementKeys.asm ; call eop to set-up game-specific (UW1 or UW2) bindings push varArgsEopArg(moreBindings, 0) callFromOverlay varArgsEopDispatcher add sp, 2 mov di, offsetInCodeSegment(keyBindings) forKeyBinding: cmp di, offsetInCodeSegment(keyBindings_end) jae keyBindings_end push cs pop es bindDKeyAt es:di add di, dKey_SIZE jmp forKeyBinding keyBindings: ; Ctrl+Alt+<letter> => select a rune %assign rune 'a' %rep 26 dKey 17, C|A|rune, byteArgEopDispatcher, byteArgEopArg(runeKey, rune) %assign rune rune + 1 %endrep ; Ctrl+Alt+Backspace => clear runes dKey 17, C|A| 8, byteArgEopDispatcher, byteArgEopArg(runeKey, 8) ; Ctrl+Alt+Space => cast runes dKey 17, C|A|' ', tryToCast, 1 ; call eop-attack, which remembers the chosen attack type and then ; delegates to the original attack proc dKey 1, ' ', byteArgEopDispatcher, byteArgEopArg(attack, 0) ; auto-attack dKey 1, '.', byteArgEopDispatcher, byteArgEopArg(attack, 3) ; thrust dKey 1, ';', byteArgEopDispatcher, byteArgEopArg(attack, 6) ; slash dKey 1, 'p', byteArgEopDispatcher, byteArgEopArg(attack, 9) ; bash dKey 1, 'r', byteArgEopDispatcher, byteArgEopArg(flipToPanel, 1) dKey 1, 'f', byteArgEopDispatcher, byteArgEopArg(flipToPanel, 2) dKey 1, '`', byteArgEopDispatcher, byteArgEopArg(toggleMouseLook, 0) dKey 1, A|'`', byteArgEopDispatcher, byteArgEopArg(orientMouseLook, 0) dKey 1, 'q', byteArgEopDispatcher, byteArgEopArg(interactAtCursor, 1) ; look dKey 1, 'e', byteArgEopDispatcher, byteArgEopArg(interactAtCursor, 0) ; use dKey 1, 'z', transitionToInterfaceMode, InterfaceMode_MAP dKey 1, 'c', closeInventoryContainer, 0 dKey 1, 'v', scrollInventoryDown, 0 dKey 1, 'b', scrollInventoryUp, 0 ; simulate click on compass dKey 1, 'g', clickCompass, 0 ; simulate clicks on health and mana flasks dKey 1, 'h', byteArgEopDispatcher, byteArgEopArg(clickFlasks, 0) dKey 1, C|0xA6, easyMove, 0 ; Ctrl+Up => Easy-walk dKey 1, C|0xAB, easyMove, -2 ; Ctrl+Down => Easy-back dKey 1, C|0xA8, easyMove, -1 ; Ctrl+Left => Easy-left dKey 1, C|0xA9, easyMove, 1 ; Ctrl+Right => Easy-right dKey 17, '1' , adjustPitch, 1 ; 1 => look up dKey 17, 0xA6 , adjustPitch, 1 ; Up => look up dKey 17, '2' , adjustPitch, 0 ; 2 => look ahead dKey 17, 0x90 , adjustPitch, 0 ; KP5 => look ahead dKey 17, '3' , adjustPitch, -1 ; 3 => look down dKey 17, 0xAB , adjustPitch, -1 ; Down => look down dKey 17, H|LShift, move, 7 ; jump dKey 17, H|C|LShift, move, 6 ; standing long jump dKey 1, 0x86, flipCharPanel, 0 ; F7 dKey 1, 0x87, tryToCast, 1 ; F8 dKey 1, 0x88, track, 2 ; F9 dKey 1, 0x89, sleep, 0 ; F10 dKey 1, C|'d', handleControlKey, C|'d' ; detail level dKey 1, C|'f', handleControlKey, C|'f' ; toggle sounds dKey 1, C|'m', handleControlKey, C|'m' ; toggle music dKey 1, C|'q', handleControlKey, C|'q' ; quit dKey 1, C|'r', handleControlKey, C|'r' ; restore dKey 1, C|'s', handleControlKey, C|'s' ; save ; in conversation dKey 4, '1', selectConversationOption, 1 dKey 4, '2', selectConversationOption, 2 dKey 4, '3', selectConversationOption, 3 dKey 4, '4', selectConversationOption, 4 dKey 4, '5', selectConversationOption, 5 ; on map screen dKey 2, 's', byteArgEopDispatcher, byteArgEopArg(mapControl, MapControl_LEVEL_UP) dKey 2, 'w', byteArgEopDispatcher, byteArgEopArg(mapControl, MapControl_LEVEL_DOWN) dKey 2, 'c', byteArgEopDispatcher, byteArgEopArg(mapControl, MapControl_AVATAR_LEVEL) dKey 7, H|0xA3, moveCursor, H|0xA3 ; Shift+Tab dKey 7, 9, moveCursor, 9 ; Tab dKey 7, 0x8C, moveCursor, 0x8C ; (numeric keypad) dKey 7, 0x8D, moveCursor, 0x8D ; (numeric keypad) dKey 7, 0x8E, moveCursor, 0x8E ; (numeric keypad) dKey 7, 0x8F, moveCursor, 0x8F ; (numeric keypad) dKey 7, 0x91, moveCursor, 0x91 ; (numeric keypad) dKey 7, 0x92, moveCursor, 0x92 ; (numeric keypad) dKey 7, 0x93, moveCursor, 0x93 ; (numeric keypad) dKey 7, 0x94, moveCursor, 0x94 ; (numeric keypad) dKey 7, 0x95, moveCursor, 0x95 ; (numeric keypad) dKey 7, 0x96, moveCursor, 0x96 ; (numeric keypad) dKey 27, A|0x86, byteArgEopDispatcher, byteArgEopArg(printVersion, 0) ; Alt+F7 dKey 27, A|0x87, printDebug, 0 ; Alt+F8 keyBindings_end: ; bytes reclaimed from the oblivion of inefficiency times 418 nop endBlockWithFillAt nop, off_bindsEnd endPatch
package me.quenchjian.gvotool.ui.discovery import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import dagger.hilt.android.scopes.ActivityScoped import me.quenchjian.gvotool.data.Settings import me.quenchjian.gvotool.data.entity.Character import me.quenchjian.gvotool.data.entity.Discovery import me.quenchjian.gvotool.data.entity.DiscoveryDetail import me.quenchjian.gvotool.ui.character.LoadCharacters import me.quenchjian.gvotool.ui.dashboard.DashboardViewModel import me.quenchjian.gvotool.ui.mvvm.State import javax.inject.Inject @ActivityScoped class DiscoveryViewModel @Inject constructor( settings: Settings, loadCharacters: LoadCharacters, private val loadDiscovery: LoadDiscovery, private val toggleDiscoveryState: ToggleDiscoveryState, ) : DashboardViewModel(settings, loadCharacters) { val loadState: LiveData<State<List<DiscoveryDetail>>> = MutableLiveData() val updateState: LiveData<State<Unit>> = MutableLiveData() private val loadObserver = Observer(loadState as MutableLiveData) private val updateObserver = Observer(updateState as MutableLiveData) override fun setup() { loadDiscovery.addObserver(loadObserver) toggleDiscoveryState.addObserver(updateObserver) } fun load(character: Character, type: Discovery.Type) { loadDiscovery.invoke(character, type) } fun update(data: List<DiscoveryDetail>) { toggleDiscoveryState(data) } override fun dispose() { super.dispose() loadDiscovery.dispose() } }
import { App, ArticleList, Daily, ArticleView } from './containers' const config = [{ path: '/', component: App, indexRoute: { component: ArticleList }, childRoutes: [{ path: 'articlelist', component: ArticleList }, { path: 'daily', component: Daily }, { path: 'article/:id', component: ArticleView }] }] export default config
<a href="http://job4j.ru"> <img src="https://job4j.ru/img/logomini.png"></a> <http://job4j.ru/> ### С нуля до трудоустройства, Java SE + EE. "The cource did work with git branches" "Combining Committed Changes" "Creating a new branch through IDEA"
# Change Log ## Unreleased - Changed missing ctags file notification to be less annoying. ## 2020.4.2 - Really fixed broken "reindex" command. ## 2020.4.1 - Fixed broken "reindex" command. ## 2020.4.0 - Added multi root workspaces support.
import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget from ui_linear_regression import Ui_LinearRegression from ui_linear_regression_base import Ui_LinearRegressionBase from ui_main import Ui_MainWindow class MainWin(QMainWindow, Ui_MainWindow): def __init__(self): super(MainWin, self).__init__() self.setupUi(self) self.setWindowTitle('ML😔') # self.tab_welcome. # newPage = QWidget(self.tabWidget) # self.tabWidget.addTab(newPage, 'newPage') self.treeWidget.clicked.connect(self.on_tree_clicked) self.tabWidget.tabCloseRequested.connect(self.on_close_tab) def on_tree_clicked(self, qmodelindex): item = self.treeWidget.currentItem() if item.childCount() > 0: return for i in range(self.tabWidget.count()): item_text = item.text(0) if self.tabWidget.tabText(i) == item_text: return title = item.text(0) if title == 'LinearRegression': self.tabWidget.addTab(Ui_LinearRegression(), item.text(0)) self.tabWidget.setCurrentIndex(self.tabWidget.count() - 1) print(f"key={item.text(0)} ,value={item.text(1)}, index:{qmodelindex}") def on_close_tab(self, tab_index): self.tabWidget.removeTab(tab_index) if __name__ == "__main__": app = QApplication(sys.argv) win = MainWin() win.show() sys.exit(app.exec_())
@file:Suppress("unused") package mogul.microdom import mogul.demo.platformRunEventLoop import mogul.microdom.primitives.Text import mogul.platform.* class WindowNotRegisteredException : Exception() class MicroDom(val engine: Engine, val events: EventPubSub) { private val scenesByWindow = mutableMapOf<Window, Scene>().withDefault { Scene(Text("No Scene on this Window")) } fun sceneForWindow(window: Window) = scenesByWindow[window] ?: throw WindowNotRegisteredException() fun registerWindow(window: Window, scene: Scene) { scenesByWindow[window] = scene scene.onInvalidated = { engine.runOnUiThread { // Async operation, the window could have been destroyed in the meantime... if (scenesByWindow.contains(window)) { render(window) } }} render(window) } fun unregisterWindow(window: Window) { sceneForWindow(window).onInvalidated = null scenesByWindow.remove(window) } fun render(window: Window) { // TODO: maybe this should be async, just send an event to the Window to schedule a re-render window.draw { cairo -> scenesByWindow[window]?.draw(cairo) ?: throw WindowNotRegisteredException() } } fun processEvent(event: Event) { if (event !is EventWithWindow) return if (event is WindowDestroyedEvent) { return unregisterWindow(event.window) } scenesByWindow[event.window]?.processEvent(event) ?: throw WindowNotRegisteredException() } fun shutdown() { engine.quit() } fun runEventLoop() { platformRunEventLoop(events, this) } }
--- layout: project_single title: "Industrial Farmhouse Bathroom Reveal" slug: "industrial-farmhouse-bathroom-reveal" parent: "farmhouse-master-bathroom-decor" --- This Industrial Farmhouse Bathroom is the perfect blend of styles and creates such a cozy atmosphere!
/* Title: References Description: References I used to make the knowledge base */ This page contain links to the resources used in order to gather the questions presented in this knowledge base. ## JavaScript - https://medium.com/dev-bits/a-perfect-guide-for-cracking-a-javascript-interview-a-developers-perspective-23a5c0fa4d0d - [RisingStack blog post 2017](https://blog.risingstack.com/node-js-interview-questions-and-answers-2017/) - [RisingStack blog post 2015](https://blog.risingstack.com/node-js-interview-questions/) ### React - https://blog.risingstack.com/8-react-interview-questions-for-2018/
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { GoogleLoginProvider, SocialAuthService, SocialUser } from 'angularx-social-login'; import { Observable } from 'rxjs'; import { AuthRequest } from 'src/app/shared/models/auth/auth-request'; import { AuthResult } from 'src/app/shared/models/auth/auth-result'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class AuthService { baseUrl = environment.baseUrl; static readonly UserKey = 'user'; static readonly AccessTokenKey = 'accessToken'; constructor(private http: HttpClient, private router: Router, private socialAuthService: SocialAuthService) { } getUser(): SocialUser { const user = localStorage.getItem(AuthService.UserKey); return user ? JSON.parse(user) : null; } setUser(user: SocialUser) { localStorage.setItem(AuthService.UserKey, JSON.stringify(user)); } getAccessToken() { return localStorage.getItem(AuthService.AccessTokenKey); } setAccessToken(accessToken: string) { localStorage.setItem(AuthService.AccessTokenKey, accessToken); } loginWithGoogle(returnUrl: string): void { this.socialAuthService.signIn(GoogleLoginProvider.PROVIDER_ID).then((user: SocialUser) => { const authRequest = { idToken: user.idToken, provider: user.provider } as AuthRequest; this.authenticate(authRequest).subscribe((authResult: AuthResult) => { this.setUser(user); this.setAccessToken(authResult.token); this.redirectToUrl(returnUrl); }); }); } redirectToUrl(returnUrl: string) { returnUrl ? this.router.navigate([returnUrl]) : this.router.navigate(['/admin']); } signOut() { this.socialAuthService.signOut(); localStorage.clear(); this.router.navigate(['./login']); } authenticate(authRequest: AuthRequest): Observable<AuthResult> { return this.http.post<AuthResult>(`${this.baseUrl}/api/auth/token`, authRequest); } }
# CHANGELOG for nupic cookbook This file is used to list changes made in each version of the nupic cookbook. ## 0.1.0: * Initial release of nupic cookbook * Installs base set of rpms and gems required by nupic.
# frozen_string_literal: true # == Schema Information # # Table name: research_outputs # # id :bigint(8) not null, primary key # abbreviation :string(255) # access :integer default("open"), not null # byte_size :bigint(8) # description :text(65535) # display_order :integer # is_default :boolean # output_type :integer default("dataset"), not null # output_type_description :string(255) # personal_data :boolean # release_date :datetime # sensitive_data :boolean # title :string(255) not null # created_at :datetime not null # updated_at :datetime not null # license_id :bigint(8) # plan_id :integer # # Indexes # # index_research_outputs_on_license_id (license_id) # index_research_outputs_on_output_type (output_type) # index_research_outputs_on_plan_id (plan_id) # FactoryBot.define do factory :research_output do license abbreviation { Faker::Lorem.unique.word } access { ResearchOutput.accesses.keys.sample } byte_size { Faker::Number.number } description { Faker::Lorem.paragraph } is_default { [nil, true, false].sample } display_order { Faker::Number.between(from: 1, to: 20) } output_type { ResearchOutput.output_types.keys.sample } output_type_description { Faker::Lorem.sentence } personal_data { [nil, true, false].sample } release_date { Time.now + 1.month } sensitive_data { [nil, true, false].sample } title { Faker::Music::PearlJam.song } transient do repositories_count { 1 } metadata_standards_count { 1 } end after(:create) do |research_output, evaluator| research_output.repositories = create_list(:repository, evaluator.repositories_count) research_output.metadata_standards = create_list(:metadata_standard, evaluator.metadata_standards_count) end end end
(cl:in-package #:cl-ds.sets.skip-list) (defclass mutable-skip-list-set (cl-ds.sets:mutable-set cl-ds.common.skip-list:fundamental-skip-list) ()) (defclass mutable-skip-list-set-range (cl-ds.common.skip-list:fundamental-skip-list-range) ()) (defmethod cl-ds.common.skip-list:make-range ((container mutable-skip-list-set) current-node last-node) (make 'mutable-skip-list-set-range :current-node current-node :last-node last-node)) (defmethod cl-ds:whole-range ((object mutable-skip-list-set)) (make-instance 'mutable-skip-list-set-range :current-node (~> object cl-ds.common.skip-list:read-pointers (aref 0)))) (defmethod cl-ds:consume-front ((range mutable-skip-list-set-range)) (let ((result (call-next-method))) (if (null result) (values nil nil) (values (cl-ds.common.skip-list:skip-list-node-content result) t)))) (defmethod cl-ds:peek-front ((range mutable-skip-list-set-range)) (let ((result (call-next-method))) (if (null result) (values nil nil) (values (cl-ds.common.skip-list:skip-list-node-content result) t)))) (defmethod cl-ds:traverse ((range mutable-skip-list-set-range) function) (ensure-functionf function) (call-next-method range (lambda (node) (declare (type cl-ds.common.skip-list:skip-list-node node) (optimize (speed 3))) (~>> node cl-ds.common.skip-list:skip-list-node-content (funcall function)))) range) (defmethod cl-ds:across ((range mutable-skip-list-set-range) function) (ensure-functionf function) (call-next-method range (lambda (node) (declare (type cl-ds.common.skip-list:skip-list-node node) (optimize (speed 3))) (~>> node cl-ds.common.skip-list:skip-list-node-content (funcall function)))) range) (defmethod cl-ds.meta:position-modification ((function cl-ds.meta:put!-function) container (structure mutable-skip-list-set) location &rest all) (declare (ignore all container)) (cl-ds.common.skip-list:insert-or structure location (lambda (node) (if (null node) (let ((result (cl-ds.common.skip-list:make-skip-list-node-of-random-level (cl-ds.common.skip-list:access-maximum-level structure)))) (setf (cl-ds.common.skip-list:skip-list-node-content result) location) (values result cl-ds.common:empty-changed-eager-modification-operation-status)) (values nil cl-ds.common:empty-eager-modification-operation-status))))) (defmethod cl-ds:at ((container mutable-skip-list-set) location &rest more-locations) (cl-ds:assert-one-dimension more-locations) (let* ((pointers (cl-ds.common.skip-list:skip-list-locate-node container location)) (result (aref pointers 0))) (when (null result) (return-from cl-ds:at (values nil nil))) (let ((content (cl-ds.common.skip-list:skip-list-node-content result))) (if (~> container cl-ds.common.skip-list:access-test-function (funcall content location)) (values t t) (values nil nil))))) (defun make-mutable-skip-list-set (ordering test &key (maximum-level 32)) (check-type maximum-level positive-fixnum) (make-instance 'mutable-skip-list-set :ordering-function ordering :maximum-level maximum-level :test-function test :pointers (make-array maximum-level :initial-element nil))) (defmethod cl-ds:make-from-traversable (traversable (class (eql 'mutable-skip-list-set)) &rest arguments) (lret ((result (apply #'make-mutable-skip-list-set arguments))) (cl-ds:traverse traversable (lambda (x) (cl-ds:put! result x))))) (defmethod cl-ds:lower-bound ((container mutable-skip-list-set) location) (if-let ((result-node (aref (cl-ds.common.skip-list:skip-list-locate-node container location) 0))) (values (cl-ds.common.skip-list:skip-list-node-content result-node) t) (values nil nil)))
using Test test_case = "../data/pglib_opf_case5_pjm.m" test_case_cost = 17551.891 result_keys_required = ["case", "variables", "constraints", "feasible", "cost", "time_total", "time_data", "time_build", "time_solve"] function check_result_keys(result::Dict) for k in result_keys_required if !haskey(result, k) @warn "result dict missing key \"$(k)\"" return false end end return true end @testset "Rosetta OPF" begin @testset "GalacticOptim" begin include("../galacticoptim.jl") result = solve_opf(test_case) @test check_result_keys(result) @test result["feasible"] @test isapprox(result["cost"], test_case_cost) end @testset "JuMP" begin include("../jump.jl") result = solve_opf(test_case) @test check_result_keys(result) @test result["feasible"] @test isapprox(result["cost"], test_case_cost) end @testset "NLPModels" begin include("../nlpmodels.jl") result = solve_opf(test_case) @test check_result_keys(result) @test result["feasible"] @test isapprox(result["cost"], test_case_cost) end #= # currently blocked by https://github.com/JuliaNonconvex/Nonconvex.jl/issues/130 @testset "NonConvex" begin include("../nonconvex.jl") result = solve_opf(test_case) @test check_result_keys(result) @test result["feasible"] @test isapprox(result["cost"], test_case_cost) end =# # does not converge to a feasible solution @testset "Optim" begin include("../optim.jl") result = solve_opf(test_case) @test check_result_keys(result) @test !result["feasible"] #@test isapprox(result["cost"], test_case_cost) end end
import picodisplay as screen import time from system.fileh.jsonh import * from system.sysdata import * sysconfig = load(sysconfig_path) def clear(): screen.set_pen(255, 0, 0) screen.clear() def text(string: str, x: int, y: int, size: int = 2): screen.set_pen(255, 255, 255) screen.text(string, x, y, (screen.get_width() - x), size) def separator(): screen.set_pen(255, 85, 85) screen.circle(15, int(screen.get_height() / 2), 1) screen.rectangle(15, int((screen.get_height() / 2) - 2), int(screen.get_width() - 30), 4) screen.circle(int(screen.get_width() - 15), int(screen.get_height() / 2), 1) def refresh(): screen.update() time.sleep_ms(sysconfig["display"]["refresh_delay"])
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using DevExpress.XtraReports.UI; using DevExpress.XtraCharts; namespace Pyramid.Reports.PreBuiltReports { public partial class RptBOQTrend : Pyramid.Reports.PreBuiltReports.MasterReports.RptLogoMaster { public RptBOQTrend() { InitializeComponent(); } /// <summary> /// This method fires before the chart is shown and it formats the series dates /// </summary> /// <param name="sender">The chartCriticalElementRating XRChart</param> /// <param name="e"></param> private void chartCriticalElementRating_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e) { //Go through each series in the chart foreach(Series series in chartCriticalElementRating.Series) { //Get the series name string seriesName = series.Name; //Split the series name on the dashes string[] seriesNameList = series.Name.Split('-'); //If the name list has enough records, set the series name if (seriesNameList.Length >= 3) series.Name = seriesNameList[2] + " " + seriesNameList[0]; } } } }
import {displayContactForm} from './contacts/contactForm/contactForm'; import {appendPaletteList} from './palette/palette'; import {pageChange} from './switchPage'; import {onSignOut} from './actions/registartion/registrationActions'; import {appendSignUpForm} from './registration/signUp/signUpForm'; import {appendSignInForm} from './registration/signIn/signInForm'; import './stylesGlobal/style.css'; import './stylesGlobal/header.css'; import './stylesGlobal/main.css'; import './stylesGlobal/footer.css'; import './stylesGlobal/contactList.css'; import './stylesGlobal/logo.css'; import './stylesGlobal/palette.css'; import './stylesGlobal/paletteClasses.css'; //Needs serious renaming /*synopsis: 1- the user should sign up or log in and then be directed to the contact list where he can add , edit and delete contacts. 2-when the user presses the add button in the contact list, a pop up card with a form will appear to register the contact information and a save button will save it. 3-once saved the new contact's full name will appear in the list with an edit and delete buttons beside it. 4-if the user presses the edit button the pop up card will reappear with the contact's information already in place ready to be adjusted 5-if the delete button is pressed the user will be warned if he is sure about the delete 6-the color palette should be able to change the page's style at any point of the programm*/ const logInNav = document.querySelector("#logIn"); const signUpNav = document.querySelector("#signIn"); const signOutNav = document.querySelector("#signOut"); const addContactButton = document.querySelector(".addButton"); const paletteIcon = document.querySelector("#paletteIcon"); appendSignInForm(); logInNav.addEventListener('click',()=>{ appendSignInForm(); pageChange('signIn') }); signUpNav.addEventListener('click',()=>{ appendSignUpForm(); pageChange('signUp') }); signOutNav.addEventListener('click',onSignOut); paletteIcon.addEventListener('click',appendPaletteList); addContactButton.addEventListener("click",displayContactForm);
#!/bin/bash set -Eeuo pipefail declare -x target; target="$(uname -m)"; readonly target declare -r -x download_gettext=${download_gettext:?"true or falce"} declare -r -x clean=${clean:?"if true, will clean libnvim and nvimserver"} readonly build_libnvim=${build_libnvim:?"true or false"} readonly build_dir=${build_dir:-"./.build"} package() { local -r build_folder_path=$1 pushd "${build_folder_path}" >/dev/null tar cjf "NvimServer-${target}.tar.bz2" NvimServer echo "Packaged NvimServer for ${target} to $(realpath "NvimServer-${target}.tar.bz2")" popd >/dev/null } main() { echo "### Building NvimServer" # This script is located in /NvimServer/bin and we have to go to / pushd "$(dirname "${BASH_SOURCE[0]}")/../.." >/dev/null if [[ "${build_libnvim}" == true ]]; then ./NvimServer/bin/build_libnvim.sh fi if [[ "${clean}" == true ]]; then rm -rf "${build_dir}" fi swift build -c release --product NvimServer package "${build_dir}/release" popd >/dev/null echo "### Built NvimServer" } main
#![feature(test)] extern crate peel; use peel::example::prelude::*; extern crate test; use test::Bencher; #[bench] fn tree_generation(bencher: &mut Bencher) { bencher.iter(|| { peel_example(); }); } #[bench] fn tree_parsing(bencher: &mut Bencher) { let mut peel = peel_example(); let input = b"1234"; bencher.iter(|| { peel.traverse(input, vec![]); }); bencher.bytes = input.len() as u64; }
#include <torch/csrc/jit/codegen/cuda/arith.h> #include <torch/csrc/jit/codegen/cuda/executor.h> #include <torch/csrc/jit/codegen/cuda/fusion.h> #include <torch/csrc/jit/codegen/cuda/ir_all_nodes.h> #include <torch/csrc/jit/codegen/cuda/ir_utils.h> #include <torch/csrc/jit/codegen/cuda/lower2device.h> #include <torch/csrc/jit/codegen/cuda/ops/all_ops.h> #include <torch/csrc/jit/codegen/cuda/scheduler/all_schedulers.h> #include <benchmark/benchmark.h> #include <cuda_runtime.h> #include "utils.h" using namespace torch::jit::fuser::cuda; //------------------------------------------------------------------------------ static void setupSoftmaxBWD( Fusion* fusion, DataType dtype, const int reduction_axis) { TORCH_INTERNAL_ASSERT(dtype == DataType::Float || dtype == DataType::Half); FusionGuard fg(fusion); // setup fusion auto grad_output = makeContigTensor(2, dtype); auto output = makeContigTensor(2, dtype); auto input = makeContigTensor(2, dtype); fusion->addInput(grad_output); fusion->addInput(output); fusion->addInput(input); if (dtype == DataType::Half) { grad_output = castOp(DataType::Float, grad_output); output = castOp(DataType::Float, output); input = castOp(DataType::Float, input); } auto grad_input = softmax_backward(grad_output, output, reduction_axis); if (dtype == DataType::Half) { grad_input = castOp(DataType::Half, grad_input); } fusion->addOutput(grad_input); } static void NvFuserScheduler_Softmax_BWD( benchmark::State& benchmark_state, FusionExecutorCache* fusion_executor_cache, DataType dtype, const int reduction_axis) { TORCH_INTERNAL_ASSERT(dtype == DataType::Float || dtype == DataType::Half); at::manual_seed(0); auto options = at::TensorOptions().dtype(data_type_to_aten(dtype)).device(at::kCUDA, 0); auto reduction_size = benchmark_state.range(0); auto iter_size = benchmark_state.range(1); at::Tensor input = (reduction_axis ? at::randn({iter_size, reduction_size}, options) : at::randn({reduction_size, iter_size}, options)); at::Tensor grad_output = (reduction_axis ? at::randn({iter_size, reduction_size}, options) : at::randn({reduction_size, iter_size}, options)); at::Tensor output = (reduction_axis ? at::randn({iter_size, reduction_size}, options) : at::randn({reduction_size, iter_size}, options)); std::vector<c10::IValue> aten_inputs({grad_output, output, input}); runBenchmarkIterations(benchmark_state, fusion_executor_cache, aten_inputs); benchmark_state.SetBytesProcessed( int64_t(benchmark_state.iterations()) * (3 * input.numel() * int64_t(dataTypeSize(dtype)))); } //------------------------------------------------------------------------------ static void Baseline_Softmax_BWD( benchmark::State& benchmark_state, DataType dtype, const int reduction_axis) { at::manual_seed(0); auto options = at::TensorOptions().dtype(data_type_to_aten(dtype)).device(at::kCUDA, 0); auto reduction_size = benchmark_state.range(0); auto iter_size = benchmark_state.range(1); at::Tensor input = (reduction_axis ? at::randn({iter_size, reduction_size}, options) : at::randn({reduction_size, iter_size}, options)); at::Tensor grad_output = (reduction_axis ? at::randn({iter_size, reduction_size}, options) : at::randn({reduction_size, iter_size}, options)); at::Tensor output = (reduction_axis ? at::randn({iter_size, reduction_size}, options) : at::randn({reduction_size, iter_size}, options)); for (auto _ : benchmark_state) { clearL2Cache(); CudaKernelTimer timer; auto grad_input = at::_softmax_backward_data( grad_output, output, reduction_axis, data_type_to_aten(dtype)); benchmark_state.SetIterationTime(timer.elapsed() / 1000.0); } // Sync everything up before we're finished, don't want to run ahead on the // cpu while benchmarking. cudaDeviceSynchronize(); benchmark_state.SetBytesProcessed( int64_t(benchmark_state.iterations()) * (3 * input.numel() * int64_t(dataTypeSize(dtype)))); } static void Baseline_Softmax_BWD_Outer_fp32(benchmark::State& benchmark_state) { Baseline_Softmax_BWD(benchmark_state, DataType::Float, 0); } static void Baseline_Softmax_BWD_Inner_fp32(benchmark::State& benchmark_state) { Baseline_Softmax_BWD(benchmark_state, DataType::Float, 1); } static void Baseline_Softmax_BWD_Outer_fp16(benchmark::State& benchmark_state) { Baseline_Softmax_BWD(benchmark_state, DataType::Half, 0); } static void Baseline_Softmax_BWD_Inner_fp16(benchmark::State& benchmark_state) { Baseline_Softmax_BWD(benchmark_state, DataType::Half, 1); } //------------------------------------------------------------------------------ NVFUSER_BENCHMARK_DEFINE( NvFuserScheduler_Softmax_BWD_Outer_fp32, setupSoftmaxBWD, NvFuserScheduler_Softmax_BWD, DataType::Float, 0); NVFUSER_BENCHMARK_DEFINE( NvFuserScheduler_Softmax_BWD_Inner_fp32, setupSoftmaxBWD, NvFuserScheduler_Softmax_BWD, DataType::Float, 1); NVFUSER_BENCHMARK_DEFINE( NvFuserScheduler_Softmax_BWD_Outer_fp16, setupSoftmaxBWD, NvFuserScheduler_Softmax_BWD, DataType::Half, 0); NVFUSER_BENCHMARK_DEFINE( NvFuserScheduler_Softmax_BWD_Inner_fp16, setupSoftmaxBWD, NvFuserScheduler_Softmax_BWD, DataType::Half, 1); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); NVFUSER_BENCHMARK_RUN(NvFuserScheduler_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); //------------------------------------------------------------------------------ BENCHMARK(Baseline_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp32) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Outer_fp16) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp32) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{1, 1024 * 1024}, {160, 320}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{32768, 32 * 1024 * 1024}, {2, 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{2, 16}, {32768, 32 * 1024 * 1024}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime(); BENCHMARK(Baseline_Softmax_BWD_Inner_fp16) // ->RangeMultiplier(2) ->Ranges({{128, 1024 * 16}, {128, 1024 * 16}}) ->Unit(benchmark::kMicrosecond) ->UseManualTime();
import 'package:number_trivia_app_tdd/features/get_number_trivia/data/models/number_trivia_model.dart'; import 'package:number_trivia_app_tdd/features/get_number_trivia/domain/entities/number_trivia_entitiy.dart'; extension NumberTriviaMapper on NumberTriviaModel { NumberTriviaEntity toEntity() { return NumberTriviaEntity(text: text, number: number); } }
(ns hara.time.data.long-test (:use midje.sweet) (:require [hara.protocol [string :as string] [time :as time]] [hara.time.data] [hara.time.data [coerce :as coerce] [common :as common] [map :as map]] [hara.io.environment :as env]) (:import [java.util Date Calendar TimeZone] [java.sql Timestamp])) (fact "time/-now for java.util datastructures" (time/-now {:type Date}) => #(instance? Date %) (time/-now {:type Long}) => #(instance? Long %) (time/-now {:type Calendar}) => #(instance? Calendar %) (time/-now {:type Timestamp}) => #(instance? Timestamp %) (keys (time/-now {:type clojure.lang.PersistentArrayMap})) => (just [:day :hour :timezone :long :second :month :type :year :millisecond :minute] :in-any-order)) (fact "time/-from-long for java.util datastructures" (time/-from-long 0 {:type Date}) => #inst "1970-01-01T00:00:00.000-00:00" (time/-from-long 0 {:type Date :timezone "Asia/Kolkata"}) => #inst "1970-01-01T00:00:00.000-00:00" (time/-from-long 0 {:type Long}) => 0 (.getTime ^Calendar (time/-from-long 0 {:type Calendar :timezone "GMT"})) => #inst "1970-01-01T00:00:00.000-00:00" (-> ^Calendar (time/-from-long 0 {:type Calendar :timezone "Asia/Kolkata"}) (.getTimeZone) (string/-to-string)) => "Asia/Kolkata" (time/-from-long 0 {:type Timestamp}) #inst "1970-01-01T00:00:00.000000000-00:00" (time/-from-long 0 {:type clojure.lang.PersistentArrayMap :timezone "GMT"}) => {:type clojure.lang.PersistentArrayMap, :timezone "GMT", :long 0, :year 1970, :month 1, :day 1, :hour 0, :minute 0, :second 0, :millisecond 0} (time/-from-long 0 {:type clojure.lang.PersistentArrayMap :timezone "Asia/Kolkata"}) => {:type clojure.lang.PersistentArrayMap, :timezone "Asia/Kolkata", :long 0, :year 1970, :month 1, :day 1, :hour 5, :minute 30, :second 0, :millisecond 0}) (fact "time/-to-long for java.util datastructures" (time/-to-long 0) => 0 (time/-to-long (Date. 0)) => 0 (time/-to-long (common/calendar (Date. 0) (TimeZone/getTimeZone "GMT"))) => 0 (time/-to-long (common/calendar (Date. 0) (TimeZone/getTimeZone "Asia/Kolkata"))) => 0 (time/-to-long {:type clojure.lang.PersistentArrayMap, :timezone "GMT", :long 0, :year 1970, :month 1, :day 1, :hour 0, :minute 0, :second 0, :millisecond 0}) => 0 (time/-to-long {:type clojure.lang.PersistentArrayMap, :timezone "Asia/Kolkata", :long 0, :year 1970, :month 1, :day 1, :hour 5, :minute 30, :second 0, :millisecond 0}) => 0) (env/init {:java {:major 1 :minor 8}} (:import [java.time Instant Clock ZonedDateTime]) (:require [hara.time.data.instant java-time-instant java-time-clock java-time-zoneddatetime] [hara.time.data.zone java-time-zoneid])) (env/run {:java {:major 1 :minor 8}} (fact "time/-now for java.time datastructures" (time/-now {:type Instant}) => #(instance? Instant %) (time/-now {:type Clock}) => #(instance? Clock %) (time/-now {:type ZonedDateTime}) => #(instance? ZonedDateTime %)) (fact "time/-from-long for java.util datastructures" (-> (time/-from-long 0 {:type Instant}) (time/-to-long)) => 0 (-> (time/-from-long 0 {:type Instant}) (map/to-map {:timezone "GMT"} common/+default-keys+)) => {:type java.time.Instant :timezone "GMT", :long 0, :year 1970, :month 1, :day 1, :hour 0, :minute 0, :second 0 :millisecond 0} (-> (time/-from-long 0 {:type Clock :timezone "GMT"}) (map/to-map {:timezone "Asia/Kolkata"} common/+default-keys+)) => {:type java.time.Clock$FixedClock :timezone "Asia/Kolkata", :long 0, :year 1970, :month 1, :day 1, :hour 5, :minute 30, :second 0 :millisecond 0} (-> (time/-from-long 0 {:type Clock :timezone "Asia/Kolkata"}) (time/-get-timezone)) => "Asia/Kolkata" (-> (time/-from-long 0 {:type Clock :timezone "Asia/Kolkata"}) (map/to-map {} common/+default-keys+)) => {:type java.time.Clock$FixedClock, :timezone "Asia/Kolkata", :long 0, :year 1970, :month 1, :day 1, :hour 5, :minute 30, :second 0 :millisecond 0} (-> (time/-from-long 0 {:type ZonedDateTime :timezone "Asia/Kolkata"}) (map/to-map {} common/+default-keys+)) => {:type java.time.ZonedDateTime :timezone "Asia/Kolkata", :long 0, :year 1970, :month 1, :day 1, :hour 5, :minute 30, :second 0 :millisecond 0}))
package com.power.common.util; import org.junit.Test; import java.util.HashMap; import java.util.Map; /** * Description: * OkHttp3Util单元测试,单元测试中不支持OkHttp3的异步请求测试 * * @author yu 2018/06/19. */ public class OkHttp3UtilTest { @Test public void testSyncGet() { String url = "http://smarthome.dq.ott4china.com:8899/iptv_oms_center/ProvinceControl"; Map<String, String> params = new HashMap<>(); params.put("res", "mnLue%2FPmm7oHWsqfMeWJC9svT6OsJ2wG4VkjAhQ8IAYT2%2FpRviOQpG%2FuDc1T7RrhAJgq34Zdrh%2FbyxwyZONt5XiPVVCs9Ahtcwb5ePFldwhsP8z51ICKQj3XDnPyQB5VDt83FQJ%2FgaxDBZSC0cA5Bw%3D%3D"); params.put("ver", "ver_0.0.1"); System.out.println(OkHttp3Util.syncGet(url, params)); } }
require 'spec_helper' describe 'ruby_basic::default' do let :chef_run do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '14.04') end before do stub_command("ruby -v | grep \"2.1.5p273\"").and_return(false) end it 'should have default install_method as package' do chef_run.converge(described_recipe) expect(chef_run.node['ruby_basic']['install_method']).to eq('source') end it 'should include the package recipe' do chef_run.converge(described_recipe) expect(chef_run).to include_recipe('ruby_basic::package') end it 'should include the source recipe' do chef_run.node.set['ruby_basic']['install_method'] = 'source' chef_run.converge(described_recipe) expect(chef_run).to include_recipe('ruby_basic::source') end end
/* * Copyright (c) 2021 Oleksii Orel * This program is made available under the terms of the MIT License * which is available at https://opensource.org/licenses/MIT/ * * SPDX short identifier: MIT */ export const PUBLIC_CRT_PATH = '/public-certs'; export const SS_CRT_PATH = '/tmp/che/secret/ca.crt';
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.text.styling.renderer.spans import android.graphics.Canvas import android.graphics.Paint import android.graphics.Path import android.text.Layout import android.text.Spanned import android.text.style.BulletSpan import android.text.style.LeadingMarginSpan import androidx.annotation.ColorInt import androidx.annotation.Px import androidx.annotation.VisibleForTesting /** * Creating a bullet span with bigger bullets than [BulletSpan] and with a left margin */ class BulletPointSpan( @field:Px @param:Px private val gapWidth: Int, @field:ColorInt @param:ColorInt private val color: Int ) : LeadingMarginSpan { /** * Returns the amount by which to adjust the leading margin. Positive values move away from the * leading edge of the paragraph, negative values move towards it. We just return 2 times our * constant [BULLET_RADIUS] plus 2 times our property [gapWidth]. * * @param first `true` if the request is for the first line of a paragraph, `false` for * subsequent lines * @return the offset for the margin in pixels. */ override fun getLeadingMargin(first: Boolean): Int { return (2 * BULLET_RADIUS + 2 * gapWidth).toInt() } /** * Renders the leading margin. This is called before the margin has been adjusted by the value * returned by [getLeadingMargin]. If the beginning of the range of text to which our [CharSequence] * parameter [text] is attached is not equal to our [Int] parameter [start] we return having done * nothing. Otherwise we save the style of our [Paint] parameter [paint] in our variable `val style` * and its sRGB color in our variable `val oldcolor` in order to restore them before returning. * Then we set the color of [paint] to our [color] property, and its style to [Paint.Style.FILL] * (Geometry and text drawn with this style will be filled, ignoring all stroke-related settings * in the paint). We initialize our [Float] variable `val y` to the sum of our [top] parameter * and our [bottom] parameter divided by 2f. Then we branch on whether or not our [Canvas] parameter * [canvas] uses hardware acceleration: * - It **does** use hardware acceleration -- if our [Path] static field [bulletPath] is `null` * this is the first time we have been called for we initialize [bulletPath] to a new instance * of [Path] and add a circle to it centered at (0,0) of radius [BULLET_RADIUS] with a direction * of [Path.Direction.CW]. Now that we have a [Path] we save the state of [canvas] onto its * private stack, translate [canvas] to X coordinate [gapWidth] plus [x] plus [dir] times * [BULLET_RADIUS] and Y coordinate `y`, draw [bulletPath] on it using [paint] as the [paint], * and then restore the state of [canvas] to the state that existed before we were caller. * - It **does NOT** use hardware acceleration -- we just call the [Canvas.drawCircle] method * of [canvas] to have it draw a circle at X coordinate [gapWidth] plus [x] plus [dir] times * [BULLET_RADIUS] and Y coordinate `y`, of radius [BULLET_RADIUS] using [paint] as its [Paint]. * * Finally we restore the color of [paint] to `oldcolor` and its style to `style` * * @param canvas the [Canvas] to draw on. * @param paint the [Paint] to use. The this should be left unchanged on exit. * @param x the current position of the margin. * @param dir the base direction of the paragraph; if negative, the margin * is to the right of the text, otherwise it is to the left. * @param top the top of the line * @param baseline the baseline of the line * @param bottom the bottom of the line * @param text the text * @param start the start of the line * @param end the end of the line * @param first true if this is the first line of its paragraph * @param l the layout containing this line */ override fun drawLeadingMargin( canvas: Canvas, paint: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, first: Boolean, l: Layout ) { if ((text as Spanned).getSpanStart(this) == start) { val style = paint.style val oldcolor = paint.color paint.color = color paint.style = Paint.Style.FILL val y: Float = (top + bottom) / 2f if (canvas.isHardwareAccelerated) { if (bulletPath == null) { bulletPath = Path() bulletPath!!.addCircle(0.0f, 0.0f, BULLET_RADIUS, Path.Direction.CW) } canvas.save() canvas.translate(gapWidth + x + dir * BULLET_RADIUS, y) canvas.drawPath(bulletPath!!, paint) canvas.restore() } else { canvas.drawCircle(gapWidth + x + dir * BULLET_RADIUS, y, BULLET_RADIUS, paint) } // restore paint.color = oldcolor paint.style = style } } companion object { /** * The radius of the bullet point circle. */ @VisibleForTesting const val BULLET_RADIUS = 15.0f /** * The [Path] we use to draw a circle if the [Canvas] is hardware accelerated */ private var bulletPath: Path? = null } }
package org.openinfralabs.caerus.cache.common.plans import org.apache.spark.sql.catalyst.expressions.{Attribute, ExprId, Expression, Unevaluable} import org.apache.spark.sql.types.{DataType, Metadata} case class CaerusAttribute(index: Int, dataType: DataType) extends Attribute with Unevaluable { override def withNullability(newNullability: Boolean): Attribute = this override def withQualifier(newQualifier: Seq[String]): Attribute = this override def withName(newName: String): Attribute = this override def withMetadata(newMetadata: Metadata): Attribute = this override def withExprId(newExprId: ExprId): Attribute = this override def newInstance(): Attribute = CaerusAttribute(index, dataType) override def name: String = "none" override def exprId: ExprId = ExprId(index.toLong) override def qualifier: Seq[String] = Seq.empty[String] override def nullable: Boolean = true def sameRef(other: CaerusAttribute): Boolean = index == other.index override def equals(other: Any): Boolean = other match { case otherCaerusAttribute: CaerusAttribute => index == otherCaerusAttribute.index && dataType == otherCaerusAttribute.dataType case _ => false } override def semanticEquals(other: Expression): Boolean = other match { case otherCaerusAttribute: CaerusAttribute => sameRef(otherCaerusAttribute) case _ => false } override def toString: String = "%s#%s: %s".format(name, index, dataType) override def simpleString(maxFields: Int): String = "%s#%s: %s".format(name, index, dataType.simpleString(maxFields)) override def sql: String = "%s#%s".format(name, index) }
enum class ENUM { AAAA, BBBB, CCCC } fun foo(e: ENUM?) { when (e) { <caret> } } // EXIST: ENUM.AAAA // EXIST: ENUM.BBBB // EXIST: ENUM.CCCC // EXIST: { lookupString: "else -> "} // EXIST: null // NOTHING_ELSE // FIR_COMPARISON
package gigigo.com.orchextrasdk.adonservices; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; /** * Created by Alberto on 16/03/2016. */ public class MotionServiceUtility { private Context context; private PendingIntent pintent; private AlarmManager alarm; private Intent iService; public MotionServiceUtility(Context context) { super(); this.context = context; iService = new Intent(context, MotionService.class); alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); pintent = PendingIntent.getService(context, 0, iService, 0); } public void start() { startBackgroundScan(); } public void stop() { stopBackgroundScan(); } private void stopBackgroundScan() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { alarm.cancel(pintent); context.stopService(iService); } } private void startBackgroundScan() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) context.startService(iService); } }
#!/usr/bin/env python2 #! -*- coding: UTF-8 -*- import os, sys, cfscrape import json import requests as reqs from bs4 import BeautifulSoup from MeTh.core.modules import * from MeTh.utils import * class Checker(Checker): __info__ = { "Name":"MinecraftChecker", "Version": "v0.1", "Authors": ( "Mr-Z3r0" ), "LastModified": "13-02-2020", "StartText":"Minecraft Checker it can ban you :)", "Description": "Minecraft Account Account checker" } combo = OptString("", "Insert your combolist") def run(self): if self.combo == "": print_error("You must set options after run") else: self.save = raw_input("Want you save hits y/n ") if self.save in ["y", "yes"]: self.file = raw_input("File > ") with open(self.combo) as f: for lines in f: users, passwords = lines.split(':') self.Threat(users.strip(), passwords.strip()) def Threat(self, user, passw): session = cfscrape.create_scraper() login_page = "https://authserver.mojang.com/authenticate" #csrftok = login_soup.find(id='login_form__token')['value'] params = { "agent": { "name": "Minecraft", "version": 1 }, "username": user, "password": passw } try: source = reqs.post(login_page, json=params, timeout=15, headers={"Content-Type": "application/json"}) except reqs.exceptions.Timeout as e: print_error(e) return json_data = json.loads(source.text) if source.status_code == 403: print("\033[1;31mFailed\033[0m: {}:{}".format(user, passw)) if "availableProfiles" in json_data: print('\033[1;32mHit\033[0m {}:{}'.format(user, passw)) Hit = user+':'+passw if self.save in ["y", "yes"]: try: f = open(self.file, "a+") f.write(Hit) f.close() except IOError: print_error("Unknown error")
<?php namespace flo\Test\Command; use flo\Console\Application; use flo\SymfonyOverwrite\Filesystem; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Process\Process; class RunScriptCommandTest extends \PHPUnit_Framework_TestCase { /** * The root project directory. * * @var string */ private $root; /** * Filesystem object. * * @var Filesystem */ private $fs; /** * Set up test environment filesystem. */ public function setUp() { $this->fs = new Filesystem(); // Attempt to create a temporary directory for the tests and change the // current working directory to that directory. try { $this->root = sys_get_temp_dir() . '/' . str_replace('\\', '-', __CLASS__); if ($this->fs->exists($this->root)) { $this->fs->remove($this->root); } $this->fs->mkdir($this->root); } catch (\Exception $e) { $this->tearDown(); // Throw the exception again so the tests will be skipped. throw $e; } chdir($this->root); // Setup a git repo. $process = new Process('git init'); $process->run(); } /** * Test running a script with arguments. */ public function testRunScript() { $this->writeConfig(); // Create scripts/post-deploy.sh. $post_deploy_script = <<<EOT #!/usr/bin/env bash echo "hello $1" EOT; $this->fs->dumpFile($this->root . "/scripts/post-deploy.sh", $post_deploy_script); // Run the command. $application = new Application(); $command_run_script = $application->find('run-script'); $command_tester = new CommandTester($command_run_script); $command_tester->execute(array( 'command' => $command_run_script->getName(), 'script' => 'post_deploy_cmd', 'args' => array('world'), )); // Check the output of the command. $this->assertEquals("hello world", trim($command_tester->getDisplay())); } /** * Test that attempting to run an undefined script throws an exception. * * @expectedException Exception * @expectedExceptionMessageRegExp #Could not find script 'invalid'.*# */ public function testRunScriptNotFoundException() { $this->writeConfig(); // Run the command. $application = new Application(); $command_run_script = $application->find('run-script'); $command_tester = new CommandTester($command_run_script); $command_tester->execute(array( 'command' => $command_run_script->getName(), 'script' => 'invalid', 'args' => array('script'), )); } /** * Test run-script sh process failing. */ public function testSHScripException() { $this->writeConfig(); // Create scripts/post-deploy.sh. $post_deploy_script = <<<EOT #!/usr/bin/env bash echo "hello $1" EOT; $this->fs->dumpFile($this->root . "/scripts/post-deploy.sh", $post_deploy_script); // Create a Mock Process Object. $process = $this->getMockBuilder('Symfony\Component\Process\Process') ->disableOriginalConstructor() ->getMock(); // Make sure the isSuccessful method return FALSE so flo throws an exception. $process->method('isSuccessful')->willReturn(FALSE); $process->method('getErrorOutput')->willReturn('sh failed'); // Run the command. $app = new Application(); // Set autoExit to false when testing & do not let it catch exceptions. $app->setAutoExit(TRUE); $app->setCatchExceptions(FALSE); $app->setProcess($process); $command_run_script = $app->find('run-script'); $command_tester = new CommandTester($command_run_script); $command_tester->execute(array( 'command' => $command_run_script->getName(), 'script' => 'post_deploy_cmd', 'args' => array('world'), )); // Check the output of the command. $this->assertEquals("sh failed", trim($command_tester->getDisplay())); } /** * Helper function to write configuration file. */ private function writeConfig() { // Create a sample flo.yml file. $project_config = <<<EOT --- organization: NBCUOTS repository: Publisher7_nbcuflo shortname: Publisher7_nbcuflo github_git_uri: git@github.com:NBCUOTS/Publisher7_nbcuflo.git pull_request: domain: pr.publisher7.com prefix: flo-test scripts: pre_deploy_cmd: - scripts/pre-deploy.sh post_deploy_cmd: - scripts/post-deploy.sh EOT; $this->fs->dumpFile($this->root . "/flo.yml", $project_config); } /** * Remove the files and directories created for this test. */ public function tearDown() { if ($this->fs->exists($this->root)) { $this->fs->remove($this->root); } } }
//------------------------------------------------------------------------------ /// @file /// @author ハル研究所プログラミングコンテスト実行委員会 /// /// @copyright Copyright (c) 2016 HAL Laboratory, Inc. /// @attention このファイルの利用は、同梱のREADMEにある /// 利用条件に従ってください。 //------------------------------------------------------------------------------ #include "RandomSeed.hpp" namespace hpc { //------------------------------------------------------------------------------ /// デフォルトのシードを取得します。 const RandomSeed RandomSeed::DefaultSeed() { const uint DefaultSeedX = 0xf70c0303; const uint DefaultSeedY = 0x7b1cf62d; const uint DefaultSeedZ = 0x727ff30d; const uint DefaultSeedW = 0x433d684d; return RandomSeed( DefaultSeedX, DefaultSeedY, DefaultSeedZ, DefaultSeedW ); } //------------------------------------------------------------------------------ /// RandomSeed クラスのインスタンスを生成します。 RandomSeed::RandomSeed(uint aX, uint aY, uint aZ, uint aW) : x(aX) , y(aY) , z(aZ) , w(aW) { } } // namespace // EOF
;;;; package.lisp (cl:in-package cl-user) (defpackage "https://github.com/g000001/srfi-172" (:use "https://github.com/g000001/srfi-0" "https://github.com/g000001/srfi-6" "https://github.com/g000001/srfi-11" "https://github.com/g000001/srfi-13" "https://github.com/g000001/srfi-16" "https://github.com/g000001/srfi-23" "https://github.com/g000001/srfi-34" "https://github.com/g000001/srfi-39" "https://github.com/g000001/srfi-45" quasiquote1 rnrs) (:shadowing-import-from "https://github.com/g000001/srfi-45" force delay) (:shadowing-import-from "https://github.com/g000001/srfi-23" error) (:shadowing-import-from quasiquote1 quasiquote) (:shadowing-import-from cl-user => else ***) (:shadowing-import-from "https://github.com/g000001/srfi-61" cond) (:shadowing-import-from "https://github.com/g000001/srfi-87" case) (:shadowing-import-from "https://github.com/g000001/srfi-46" syntax-rules define-syntax let-syntax letrec-syntax) (:shadowing-import-from "https://github.com/g000001/srfi-13" string string-length string->list string-fill! string? string-append string-ref string-set! string-copy list->string make-string) (:export - * / + < <= = => > >= abs acos and angle append apply asin assoc assq assv atan begin boolean? boolean=? bytevector bytevector? bytevector-append bytevector-copy bytevector-copy! bytevector-length bytevector-u8-ref bytevector-u8-set! caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call/cc call-with-current-continuation call-with-port call-with-values car case case-lambda cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling char? char<? char<=? char=? char>? char>=? char->integer char-alphabetic? char-ci<? char-ci<=? char-ci=? char-ci>? char-ci>=? char-downcase char-foldcase char-lower-case? char-numeric? char-upcase char-upper-case? char-whitespace? close-input-port close-output-port close-port complex? cond cond-expand cons cos delay delay-force denominator digit-value do dynamic-wind else eof-object eof-object? eq? equal? eqv? error error-object? error-object-irritants error-object-message even? exact exact? exact-integer? exact-integer-sqrt exp expt finite? floor floor/ floor-quotient floor-remainder force for-each gcd get-output-bytevector get-output-string guard if imag-part inexact inexact? infinite? input-port? integer? integer->char lambda lcm length let let* let*-values letrec letrec* let-values list list? list->string list->vector list-copy list-ref list-set! list-tail log magnitude make-bytevector make-list make-parameter make-polar make-promise make-rectangular make-string make-vector map max member memq memv min modulo nan? negative? newline not null? number? number->string numerator odd? open-input-bytevector open-input-string open-output-bytevector open-output-string or output-port? pair? parameterize peek-char peek-u8 port? positive? procedure? promise? quasiquote quote quotient raise raise-continuable rational? rationalize read-bytevector read-bytevector! read-char read-error? read-line read-string read-u8 real? real-part remainder reverse round set! set-car! set-cdr! sin sqrt square string string? string<? string<=? string=? string>? string>=? string->list string->number string->utf8 string->vector string-append string-ci<? string-ci<=? string-ci=? string-ci>? string-ci>=? string-copy string-copy! string-downcase string-fill! string-foldcase string-for-each string-length string-map string-ref string-set! string-upcase substring symbol? symbol=? symbol->string tan textual-port? truncate truncate/ truncate-quotient truncate-remainder unless unquote unquote-splicing utf8->string values vector vector? vector->list vector->string vector-append vector-copy vector-copy! vector-fill! vector-for-each vector-length vector-map vector-ref vector-set! when with-exception-handler write-bytevector write-char write-string write-u8 zero?) (:export srfi-172-syntax)) (defpackage "https://github.com/g000001/srfi-172#functional" (:use "https://github.com/g000001/srfi-172") (:export srfi-172-syntax) (:export cond-expand asin char->integer char-whitespace? square eof-object char-ci>? list->vector char<=? char>=? error-object? truncate/ quasiquote char-alphabetic? truncate rational? not log do cos memq integer? make-vector eqv? finite? cond truncate-remainder string-map or string-copy char-ci<=? append procedure? string=? bytevector-u8-ref positive? for-each list-copy string>=? denominator symbol? unquote-splicing cdaddr cdadar caaddr caadar with-exception-handler char-ci=? if list-ref and list-tail vector->string unquote list->string utf8->string make-string parameterize open-input-string digit-value string? open-input-bytevector => equal? bytevector-length eof-object? exact? char=? char<? ceiling char-ci>=? bytevector? error-object-message floor-remainder let bytevector-append >= <= open-output-bytevector modulo floor/ rationalize cdadr char-foldcase caaar string-ci=? bytevector call-with-current-continuation open-output-string memv cdar real? cdaadr cdaaar caar cddadr cddaar caaadr integer->char caaaar newline cadadr let-values string<? exact-integer-sqrt char-upper-case? apply make-promise cdr floor-quotient string<=? vector-ref get-output-string infinite? string-length string->list cddar raise-continuable negative? char-downcase cadar char-numeric? call-with-values string error-object-irritants string->utf8 lambda lcm inexact? gcd magnitude string-append make-rectangular cadr cdddr let*-values case-lambda caddr guard make-parameter string-ci<? char>? assoc expt error let* cddr atan assv exact null? even? sqrt imag-part real-part vector char? cons char-ci<? delay cdaar begin else caadr raise list when abs substring force round angle pair? floor symbol->string odd? zero? make-polar vector-copy nan? vector-map vector-for-each quotient map vector-length boolean=? boolean? get-output-bytevector letrec* char-upcase exact-integer? quote max vector->list string->vector complex? reverse remainder letrec tan sin values promise? min eq? car assq symbol=? inexact delay-force call/cc unless make-bytevector length string->number vector-append list? char-lower-case? numerator truncate-quotient number? string-ref string-ci>? make-list string-foldcase number->string bytevector-copy acos string-upcase case cadaar member cddddr vector? cdddar string>? cadddr caddar exp > = < + / - * string-for-each string-ci<=? string-downcase string-ci>=? dynamic-wind)) (defpackage "https://github.com/g000001/srfi-172#internals" (:use "https://github.com/g000001/srfi-4" "https://github.com/g000001/srfi-23" "https://github.com/g000001/srfi-45" cl tg named-readtables babel) (:shadowing-import-from "https://github.com/g000001/srfi-172" srfi-172-syntax) (:shadowing-import-from "https://github.com/g000001/srfi-23" error) (:shadowing-import-from "https://github.com/g000001/srfi-45#internals" box) (:shadowing-import-from rnrs define)) ;;; *EOF*
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.IO; using System.Reflection; using NUnit.Framework; using Umbraco.Cms.Core; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core { [TestFixture] public class HashCodeCombinerTests { private DirectoryInfo PrepareFolder() { DirectoryInfo assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory; DirectoryInfo dir = Directory.CreateDirectory( Path.Combine(assDir.FullName, "HashCombiner", Guid.NewGuid().ToString("N"))); foreach (FileInfo f in dir.GetFiles()) { f.Delete(); } return dir; } [Test] public void HashCombiner_Test_String() { var combiner1 = new HashCodeCombiner(); combiner1.AddCaseInsensitiveString("Hello"); var combiner2 = new HashCodeCombiner(); combiner2.AddCaseInsensitiveString("hello"); Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); combiner2.AddCaseInsensitiveString("world"); Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); } [Test] public void HashCombiner_Test_Int() { var combiner1 = new HashCodeCombiner(); combiner1.AddInt(1234); var combiner2 = new HashCodeCombiner(); combiner2.AddInt(1234); Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); combiner2.AddInt(1); Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); } [Test] public void HashCombiner_Test_DateTime() { DateTime dt = DateTime.Now; var combiner1 = new HashCodeCombiner(); combiner1.AddDateTime(dt); var combiner2 = new HashCodeCombiner(); combiner2.AddDateTime(dt); Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); combiner2.AddDateTime(DateTime.Now); Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); } [Test] public void HashCombiner_Test_File() { DirectoryInfo dir = PrepareFolder(); var file1Path = Path.Combine(dir.FullName, "hastest1.txt"); File.Delete(file1Path); using (StreamWriter file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt"))) { file1.WriteLine("hello"); } var file2Path = Path.Combine(dir.FullName, "hastest2.txt"); File.Delete(file2Path); using (StreamWriter file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt"))) { // even though files are the same, the dates are different file2.WriteLine("hello"); } var combiner1 = new HashCodeCombiner(); combiner1.AddFile(new FileInfo(file1Path)); var combiner2 = new HashCodeCombiner(); combiner2.AddFile(new FileInfo(file1Path)); var combiner3 = new HashCodeCombiner(); combiner3.AddFile(new FileInfo(file2Path)); Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner3.GetCombinedHashCode()); combiner2.AddFile(new FileInfo(file2Path)); Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); } [Test] public void HashCombiner_Test_Folder() { DirectoryInfo dir = PrepareFolder(); var file1Path = Path.Combine(dir.FullName, "hastest1.txt"); File.Delete(file1Path); using (StreamWriter file1 = File.CreateText(Path.Combine(dir.FullName, "hastest1.txt"))) { file1.WriteLine("hello"); } // first test the whole folder var combiner1 = new HashCodeCombiner(); combiner1.AddFolder(dir); var combiner2 = new HashCodeCombiner(); combiner2.AddFolder(dir); Assert.AreEqual(combiner1.GetCombinedHashCode(), combiner2.GetCombinedHashCode()); // now add a file to the folder var file2Path = Path.Combine(dir.FullName, "hastest2.txt"); File.Delete(file2Path); using (StreamWriter file2 = File.CreateText(Path.Combine(dir.FullName, "hastest2.txt"))) { // even though files are the same, the dates are different file2.WriteLine("hello"); } var combiner3 = new HashCodeCombiner(); combiner3.AddFolder(dir); Assert.AreNotEqual(combiner1.GetCombinedHashCode(), combiner3.GetCombinedHashCode()); } } }
require 'quarry/cli/abstract' module Quarry::CLI class Save < Abstract command 'save' # def call(argv) Quarry.save(*argv) end # def opts super do |o| o.banner = "Usage: quarry save <name> [file ...]" o.separator "Save directory/files to named mine." end end end end
#!/bin/bash ############################################################ # Help # ############################################################ Help() { # Display Help echo "Run a loongarch virtual machine." echo echo "Syntax: run_loongarch.sh [-b|c|d|D|g|h|i|k|m|q]" echo "options:" echo "b <bios> use this file as BIOS" echo "c <NCPU> simulated cpu number" echo "d use -s to listen on 1234 debug port" echo "D use -s -S to listen on 1234 debug port and stop waiting for attach" echo "g Use graphic UI." echo "h Print this Help." echo "i <initrd> use this file as initrd" echo "k <kernel> use this file as kernel" echo "m <mem> specify simulated memory size" echo "q <qemu> use this file as qemu" echo } # >= 512M MEM="4G" # 1-4 CPUS="1" #BIOS="./loongarch_bios_0310.bin" BIOS="./loongarch_bios_0310_debug.bin" KERNEL="./vmlinux" INITRD="busybox-rootfs.img" USE_GRAPHIC="no" DEBUG='' QEMU="./qemu-system-loongarch64" # Get the options while getopts ":b:c:dDghi:k:m:q:" option; do case $option in b) BIOS=$OPTARG;; c) CPUS=$OPTARG;; d) DEBUG='-s';; D) DEBUG='-s -S';; g) USE_GRAPHIC="yes";; h) # display Help Help exit;; i) INITRD=$OPTARG;; k) KERNEL=$OPTARG;; q) QEMU=$OPTARG;; \?) # invalid option echo "invalid option" exit;; esac done if [ $USE_GRAPHIC = "no" ] ; then # run without graphic CMDLINE="root=/dev/ram console=ttyS0,115200 rdinit=/init" GRAPHIC="-vga none -nographic" else # run with graphic CMDLINE="root=/dev/ram console=tty0 rdinit=/init" # GRAPHIC="-vga virtio -device virtio-keyboard-pci -device virtio-mouse-pci" GRAPHIC="-vga virtio -device qemu-xhci -device usb-kbd -device usb-mouse" fi set -x $QEMU -m $MEM -smp $CPUS -bios $BIOS -kernel $KERNEL -initrd $INITRD -append "$CMDLINE" $GRAPHIC $DEBUG
'use strict'; /** * The base for navigation views * * @memberof HashBrown.Client.Entity.View.Navigation */ class NavigationBase extends HashBrown.Entity.View.ViewBase { } module.exports = NavigationBase;
use std::fmt::Display; fn message(kind: &str, content: impl Display) -> String { format!("[ convevo : {} ] {}", kind, content) } pub fn info(msg: impl Display) { println!("{}", message("info", msg)); } pub fn warn(msg: impl Display) { println!("{}", message("warn", msg)); } pub fn error(msg: impl Display) { eprintln!("{}", message("error", msg)); }
; ; Amstrad CPC library ; ; ****************************************************** ; ** Librería de rutinas para Amstrad CPC ** ; ** Raúl Simarro, Artaburu 2009 ** ; ****************************************************** ; ; void cpc_RLI(unsigned int pos, unsigned char w, unsigned char h); ; ; $Id: cpc_RLI.asm $ ; SECTION code_clib PUBLIC cpc_RLI PUBLIC _cpc_RLI EXTERN asm_cpc_RLI .cpc_RLI ._cpc_RLI pop af pop de ; h pop bc ; w pop hl ; pos push hl push bc push de push af jp asm_cpc_RLI
{-# LANGUAGE TemplateHaskell,PatternGuards #-} -- | Derives 'CNode' instances for language.c module Data.Derive.CNode(makeCNode) where {- -- For all type variables a, we require (CNode a) -- If we have a data constructor -- X a_1 .. a_n, and exactly one a_k is a polymorphic variable, then return (nodeInfo a_k) data Test3 a = A Test1 a Test1 | B a Test2 | C Test1 a deriving (Show {-! ,CNode !-}) -- Else If we have a data constructor -- X a_1 .. a_n, and exactly one a_k is a Language.C.Data.NodeInfo, then return that a_k data Test1 = X Int NodeInfo | Y NodeInfo String | Z Int NodeInfo Integer deriving (Show {-! ,CNode !-}) -- Else If we have a data constructor -- X a, then return nodeInfo a data Test2 = U Test1 | V Test1 deriving (Show {-! ,CNode !-}) -- Else Fail -} import Language.Haskell.Exts hiding (paren) import Language.Haskell -- helpers from Derive import Data.Derive.Internal.Derivation import Data.Derive.Annotated makeCNode :: Derivation makeCNode = derivationCustom "CNode" (runDeriveM . genNodeInst) nodeInfoTypeName :: [Char] nodeInfoTypeName = "Language.C.Data.Node.NodeInfo" genNodeInst :: FullDataDecl -> DeriveM [Decl] genNodeInst (_,dat) = do nodeInfoDecls <- nodeInfoDefs "nodeInfo" dat return $ [ instanceContext ["CNode"] "CNode" dat [ FunBind $ nodeInfoDecls ] , instanceContext ["CNode"] "Pos" dat [ FunBind $ posOfDef "posOf" ] ] posOfDef :: String -> [Match] posOfDef funName = [ funDecl funName [pvar "x"] (app (var "posOf") (paren $ app (var "nodeInfo") (var "x"))) ] where var = Var . qname pvar = PVar . Ident nodeInfoDefs :: String -> DataDecl -> DeriveM [Match] nodeInfoDefs funName dat = mapM nodeInfoImpl (dataDeclCtors dat) where nodeInfoImpl ctor = case matchNodeInfo ctor of DOk (pat,rhs) -> return $ funDecl funName [pat] rhs DErr err -> fail $ "Failed to derive NodeInfo for " ++ ctorDeclName ctor ++ ": " ++ err matchNodeInfo :: CtorDecl -> DeriveM (Pat, Exp) matchNodeInfo ctor = ctorArgs ctor >>= tryNodeInfoArg where tryNodeInfoArg args = case filter (isNodeInfo.fromBangType.snd) args of [] -> tryDelegate args [(ix,_)] -> return $ (matchIndex ctor args ix (PVar (name "n")), Var (qname "n")) _ -> fail $ "More than one NodeInfo type" where isNodeInfo (TyCon qname) | (Qual _ (Ident "NodeInfo")) <- qname = True | (UnQual (Ident "NodeInfo")) <- qname = True | otherwise = False isNodeInfo _ = False tryDelegate args = case args of [] -> fail $ "cannot derive NodeInfo for nullary constructor" [_c] -> return $ (PApp (qname $ ctorDeclName ctor) [PVar (name "d")], App (Var (qname "nodeInfo")) (Var (qname "d"))) _xs -> delegateToPolymorphic "nodeInfo" ctor delegateToPolymorphic :: String -> CtorDecl -> DeriveM (Pat,Exp) delegateToPolymorphic fun ctor = ctorArgs ctor >>= delegate where delegate args = case filter (isVarName . fromBangType . snd) args of [] -> fail $ "delegateToPolymorphic: no type variable arguments" [(ix,_)] -> return $ (matchIndex ctor args ix (PVar (name "n")), App (Var (qname fun)) (Var (qname "n"))) _xs -> fail $ "delegateToPolymorphic: More than one type variable argument" -- ported from TH.Helpers instanceContext :: [String] -> String -> Decl -> [Decl] -> Decl instanceContext reqs cls dat defs = InstDecl noLoc Nothing [] ctx className [hed] (map InsDecl defs) where vars = [Ident ('t' : show i) | i <- [1..dataDeclArity dat]] ctx = [ ClassA (qname req) [TyVar var] | req <- reqs, var <- vars] className = qname cls hed = (if not (null vars) then TyParen else id) $ tyApp (TyCon $ qname (dataDeclName dat)) (map TyVar vars) -- remove Bang or unpack annotation fromBangType :: Type -> Type fromBangType (TyBang _ ty) = fromBangType ty fromBangType ty = ty
<span class="pull-right-container"> <small class="label pull-right bg-green">new</small> </span>
package duelistmod.helpers.crossover; import java.util.ArrayList; import com.evacipated.cardcrawl.mod.hubris.HubrisMod; import com.evacipated.cardcrawl.mod.hubris.cards.black.*; import com.evacipated.cardcrawl.mod.hubris.relics.*; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.unlock.UnlockTracker; import basemod.BaseMod; import duelistmod.DuelistMod; import duelistmod.helpers.Util; import duelistmod.patches.AbstractCardEnum; public class HubrisHelper { public static void extraRelics() { Util.log("Adding a select set of relics from Hubris to the Duelist relic pool"); BaseMod.addRelicToCustomPool(new IronBody(), AbstractCardEnum.DUELIST); BaseMod.addRelicToCustomPool(new AncientText(), AbstractCardEnum.DUELIST); BaseMod.addRelicToCustomPool(new RGBLights(), AbstractCardEnum.DUELIST); BaseMod.addRelicToCustomPool(new BallOfYels(), AbstractCardEnum.DUELIST); BaseMod.addRelicToCustomPool(new SoftwareUpdate(), AbstractCardEnum.DUELIST); UnlockTracker.markRelicAsSeen(IronBody.ID); UnlockTracker.markRelicAsSeen(AncientText.ID); UnlockTracker.markRelicAsSeen(RGBLights.ID); UnlockTracker.markRelicAsSeen(BallOfYels.ID); UnlockTracker.markRelicAsSeen(SoftwareUpdate.ID); } public static ArrayList<AbstractCard> getAllCards() { ArrayList<AbstractCard> cards = new ArrayList<>(); if (DuelistMod.isInfiniteSpire) { HubrisMod.loadOtherData(); cards.add(new Fate()); cards.add(new InfiniteBlow()); cards.add(new Rewind()); } return cards; } }
// Copyright (c) Source Tree Solutions, LLC. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Author: Joe Audette // Created: 2017-07-10 // Last Modified: 2017-07-10 // using cloudscribe.UserProperties.Models; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Localization; using System.Text.RegularExpressions; namespace cloudscribe.UserProperties.Services { public class UserPropertyValidator : IUserPropertyValidator { public UserPropertyValidator( IStringLocalizer<UserPropertyResources> localizer ) { _localizer = localizer; } private IStringLocalizer<UserPropertyResources> _localizer; public virtual bool IsValid( UserPropertyDefinition prop, string postedValue, ModelStateDictionary modelState = null ) { var result = true; if (prop.Required) { if (string.IsNullOrWhiteSpace(postedValue)) { result = false; if (modelState != null) { modelState.AddModelError(prop.Key + "Error", _localizer[prop.RequiredErrorMessage]); } } } if (prop.MaxLength > -1 && !string.IsNullOrWhiteSpace(prop.MaxLengthErrorMessage)) { if (!string.IsNullOrWhiteSpace(postedValue) && (postedValue.Length > prop.MaxLength)) { result = false; if (modelState != null) { modelState.AddModelError(prop.Key + "Error", _localizer[prop.MaxLengthErrorMessage]); } } } if ( !string.IsNullOrWhiteSpace(prop.RegexValidationExpression) && !string.IsNullOrWhiteSpace(postedValue) ) { var r = new Regex(prop.RegexValidationExpression); var isMatch = r.IsMatch(postedValue); if (!isMatch) { result = false; if (modelState != null) { modelState.AddModelError(prop.Key + "Error", _localizer[prop.RegexErrorMessage]); } } } return result; } } }
# slice() gives meaningfull errors Code (expect_error(slice(df, matrix(c(1, 2), ncol = 2)))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Can't convert <integer[,2]> to <integer>. Cannot decrease dimensions. Code (expect_error(slice(gdf, matrix(c(1, 2), ncol = 2)))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. i The error occurred in group 1: x = 1. Caused by error: ! Can't convert <integer[,2]> to <integer>. Cannot decrease dimensions. Code (expect_error(slice(df, "a"))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Invalid result of type <character>. i Indices must be positive or negative integers. Code (expect_error(slice(gdf, "a"))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. i The error occurred in group 1: x = 1. Caused by error: ! Invalid result of type <character>. i Indices must be positive or negative integers. Code (expect_error(slice(df, c(1, -1)))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Indices must be all positive or all negative. i Got 1 positives, 1 negatives. Code (expect_error(slice(gdf, c(1, -1)))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. i The error occurred in group 1: x = 1. Caused by error: ! Indices must be all positive or all negative. i Got 1 positives, 1 negatives. # slice_*() checks that `n=` is explicitly named Code (expect_error(slice_head(df, 5))) Output <error/rlang_error> Error in `slice_head()`: ! `n` must be explicitly named. i Did you mean `slice_head(n = 5)`? Code (expect_error(slice_tail(df, 5))) Output <error/rlang_error> Error in `slice_tail()`: ! `n` must be explicitly named. i Did you mean `slice_tail(n = 5)`? Code (expect_error(slice_min(df, x, 5))) Output <error/rlang_error> Error in `slice_min()`: ! `n` must be explicitly named. i Did you mean `slice_min(n = 5)`? Code (expect_error(slice_max(df, x, 5))) Output <error/rlang_error> Error in `slice_max()`: ! `n` must be explicitly named. i Did you mean `slice_max(n = 5)`? Code (expect_error(slice_sample(df, 5))) Output <error/rlang_error> Error in `slice_sample()`: ! `n` must be explicitly named. i Did you mean `slice_sample(n = 5)`? # slice_*() checks that for empty `... Code (expect_error(slice_head(df, 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_head()`: ! `...` must be empty. x Problematic arguments: * ..1 = 5 * ..2 = 2 i Did you forget to name an argument? Code (expect_error(slice_tail(df, 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_tail()`: ! `...` must be empty. x Problematic arguments: * ..1 = 5 * ..2 = 2 i Did you forget to name an argument? Code (expect_error(slice_min(df, x, 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_min()`: ! `...` must be empty. x Problematic arguments: * ..1 = 5 * ..2 = 2 i Did you forget to name an argument? Code (expect_error(slice_max(df, x, 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_max()`: ! `...` must be empty. x Problematic arguments: * ..1 = 5 * ..2 = 2 i Did you forget to name an argument? Code (expect_error(slice_sample(df, 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_sample()`: ! `...` must be empty. x Problematic arguments: * ..1 = 5 * ..2 = 2 i Did you forget to name an argument? --- Code (expect_error(slice_head(df, n = 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_head()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_tail(df, n = 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_tail()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_min(df, x, n = 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_min()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_max(df, x, n = 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_max()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_sample(df, n = 5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_sample()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? --- Code (expect_error(slice_head(df, prop = 0.5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_head()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_tail(df, prop = 0.5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_tail()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_min(df, x, prop = 0.5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_min()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_max(df, x, prop = 0.5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_max()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? Code (expect_error(slice_sample(df, prop = 0.5, 2))) Output <error/rlib_error_dots_nonempty> Error in `slice_sample()`: ! `...` must be empty. x Problematic argument: * ..1 = 2 i Did you forget to name an argument? # slice_*() checks for constant n= and prop= Code (expect_error(slice_head(df, n = n()))) Output <error/rlang_error> Error in `slice_head()`: ! `n` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_head(df, prop = n()))) Output <error/rlang_error> Error in `slice_head()`: ! `prop` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_tail(df, n = n()))) Output <error/rlang_error> Error in `slice_tail()`: ! `n` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_tail(df, prop = n()))) Output <error/rlang_error> Error in `slice_tail()`: ! `prop` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_min(df, x, n = n()))) Output <error/rlang_error> Error in `slice_min()`: ! `n` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_min(df, x, prop = n()))) Output <error/rlang_error> Error in `slice_min()`: ! `prop` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_max(df, x, n = n()))) Output <error/rlang_error> Error in `slice_max()`: ! `n` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_max(df, x, prop = n()))) Output <error/rlang_error> Error in `slice_max()`: ! `prop` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_sample(df, n = n()))) Output <error/rlang_error> Error in `slice_sample()`: ! `n` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_sample(df, prop = n()))) Output <error/rlang_error> Error in `slice_sample()`: ! `prop` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. # slice_min/max() check size of `order_by=` (#5922) Code (expect_error(slice_min(data.frame(x = 1:10), 1:6))) Output <error/rlang_error> Error in `slice_min()`: ! Problem while computing indices. Caused by error: ! `order_by` must have size 10, not size 6. Code (expect_error(slice_max(data.frame(x = 1:10), 1:6))) Output <error/rlang_error> Error in `slice_max()`: ! Problem while computing indices. Caused by error: ! `order_by` must have size 10, not size 6. # slice_sample() check size of `weight_by=` (#5922) Code (expect_error(slice_sample(data.frame(x = 1:10), n = 2, weight_by = 1:6))) Output <error/rlang_error> Error in `slice_sample()`: ! Problem while computing indices. Caused by error: ! `weight_by` must have size 10, not size 6. # rename errors with invalid grouped data frame (#640) Code df <- tibble(x = 1:3) (expect_error(slice(mtcars, 1, 1 + ""))) Output <error/rlang_error> Error in `slice()`: ! Problem while evaluating `..2 = 1 + ""`. Caused by error in `1 + ""`: ! non-numeric argument to binary operator Code (expect_error(group_by(mtcars, cyl) %>% slice(1, 1 + ""))) Output <error/rlang_error> Error in `slice()`: ! Problem while evaluating `..2 = 1 + ""`. i The error occurred in group 1: cyl = 4. Caused by error in `1 + ""`: ! non-numeric argument to binary operator Code (expect_error(slice(df, TRUE))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Invalid result of type <logical>. i Indices must be positive or negative integers. Code (expect_error(slice(df, FALSE))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Invalid result of type <logical>. i Indices must be positive or negative integers. Code (expect_error(slice(mtcars, 1, 1, ""))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Can't combine `..1` <double> and `..3` <character>. Code (expect_error(group_by(mtcars, cyl) %>% slice(1, 1, ""))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. i The error occurred in group 1: cyl = 4. Caused by error: ! Can't combine `..1` <double> and `..3` <character>. Code (expect_error(mtcars %>% slice(c(-1, 2)))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Indices must be all positive or all negative. i Got 1 positives, 1 negatives. Code (expect_error(mtcars %>% slice(c(2:3, -1)))) Output <error/rlang_error> Error in `slice()`: ! Problem while computing indices. Caused by error: ! Indices must be all positive or all negative. i Got 2 positives, 1 negatives. Code (expect_error(slice_head(data.frame(), n = 1, prop = 1))) Output <error/rlang_error> Error in `slice_head()`: ! Must supply `n` or `prop`, but not both. Code (expect_error(slice_tail(data.frame(), n = "a"))) Output <error/rlang_error> Error in `slice_tail()`: ! `n` must be a single number. Code (expect_error(slide_head(data.frame(), prop = "a"))) Output <simpleError in slide_head(data.frame(), prop = "a"): could not find function "slide_head"> Code (expect_error(slice_head(data.frame(), n = n()))) Output <error/rlang_error> Error in `slice_head()`: ! `n` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_head(data.frame(), prop = n()))) Output <error/rlang_error> Error in `slice_head()`: ! `prop` must be a constant. Caused by error in `n()`: ! Must be used inside dplyr verbs. Code (expect_error(slice_head(data.frame(), n = NA))) Output <error/rlang_error> Error in `slice_head()`: ! `n` must be a single number. Code (expect_error(slice_head(data.frame(), prop = NA))) Output <error/rlang_error> Error in `slice_head()`: ! `prop` must be a single number.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Accelerider.Windows.TransferService { public class AsyncRemotePathProvider : ConstantRemotePathProvider { private readonly Func<Task<string>> _remotePathGetter; public AsyncRemotePathProvider(Func<Task<string>> remotePathGetter) : base(new HashSet<string>(Enumerable.Empty<string>())) { _remotePathGetter = remotePathGetter; } public override async Task<string> GetAsync() { var path = await _remotePathGetter(); if (path == null) return await base.GetAsync(); RemotePaths.TryAdd(path, 0); return path; } } }
#!/usr/bin/env node import chalk from "chalk"; import * as program from "commander"; import * as path from "path"; import { readFile } from "."; // tslint:disable-next-line:tsr-detect-non-literal-require no-var-requires const pkg = require(path.join(__dirname, "..", "package.json")); program .version(pkg.version) .usage(`[fname]`) .description("reads [fname] in {json, yaml, ini, toml}, prints JSON to stdout.") .parse(process.argv); readFile(program.args[0]).then((obj) => { // tslint:disable:no-console console.log(JSON.stringify(obj, null, 2)); }).catch((err) => { console.error(chalk.red(err.message)); console.error(chalk.red(err.stack)); });
class SubdomainConstraint def self.matches?(request) excluded_subdomains = ExcludedSubdomains.subdomains request.subdomain.present? && !excluded_subdomains.include?(request.subdomain) end # matches? end # class
-- -- Additional api functions attributes -- CREATE TABLE pgwt.func_attrs ( nm text NOT NULL, mandatory boolean NOT NULL DEFAULT false, multiple boolean NOT NULL DEFAULT false, acceptable_values text[] NOT NULL DEFAULT '{}'::text[], conflicts text[] NOT NULL DEFAULT '{}'::text[], CONSTRAINT func_attrs_pkey PRIMARY KEY (nm) ); INSERT INTO pgwt.func_attrs (nm, mandatory, multiple, acceptable_values, conflicts) VALUES ('uri', true, false, default, default), ('methods', true, true, array['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS', 'HEAD'], default), ('raw_error', false, false, default, default), ('logwrite', false, false, default, default), ('logwrite_hidebody', false, false, default, default), ('raw_body', false, false, default, default);
import {SyntaxKind} from "ts-morph"; /** * Searches the file for method calls by the specified names * @param {import('ts-morph').SourceFile} file * @param {Set<string>} names * @return {import('ts-morph').CallExpression[]} */ export function findCallExpressionsByNames(file, names) { return file .getDescendantsOfKind(SyntaxKind.CallExpression) .filter(e => { // Only allow calls by specified names if (!names.has(e.getExpression().getText())) { return false; } // Must contain at least two arguments const args = e.getArguments() if (args.length < 2) { return false } // First argument should be non-empty string if (!args[0].getType().isStringLiteral() || args[0].getType().getLiteralValue().trim() === '') { return false } return true } ) }
package com.xuan.auth.model; import java.util.List; public interface AuthorityDAO_interface { public void insert(AuthorityVO authorityVO); public void delete(String staff_id, String ability_no); public AuthorityVO findByPrimaryKey(String staff_id, String ability_no); public List<AuthorityVO> getAll(); //萬用複合查詢(傳入參數型態Map)(回傳 List) // public List<EmpVO> getAll(Map<String, String[]> map); }
using System; using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.IpV6 { /// <summary> /// RFC 2460. /// <pre> /// +-----+-------------+-------------------------+ /// | Bit | 0-7 | 8-15 | /// +-----+-------------+-------------------------+ /// | 0 | Next Header | Header Extension Length | /// +-----+-------------+-------------------------+ /// | 16 | Options | /// | ... | | /// +-----+---------------------------------------+ /// </pre> /// </summary> public abstract class IpV6ExtensionHeaderOptions : IpV6ExtensionHeaderStandard { /// <summary> /// Extension header options. /// </summary> public IpV6Options Options { get; private set; } /// <summary> /// True iff the extension header parsing didn't encounter an issue. /// </summary> public sealed override bool IsValid { get { return Options.IsValid; } } internal sealed override int DataLength { get { return Options.BytesLength; } } internal sealed override bool EqualsData(IpV6ExtensionHeader other) { return EqualsData(other as IpV6ExtensionHeaderOptions); } internal sealed override int GetDataHashCode() { return Options.GetHashCode(); } internal override void WriteData(byte[] buffer, int offset) { Options.Write(buffer, offset); } internal IpV6ExtensionHeaderOptions(IpV4Protocol? nextHeader, IpV6Options options) : base(nextHeader) { if (options.BytesLength % 8 != 6) options = options.Pad((14 - options.BytesLength % 8) % 8); Options = options; } private bool EqualsData(IpV6ExtensionHeaderOptions other) { return other != null && Options.Equals(other.Options); } } }
# gp-gas-estimation A rust library for advanced ethereum transaction gas estimation. Currently provides interfaces to several online gas estimation services.
if(!Function.prototype.dispatch){ Function.prototype.dispatch = function(eventName) { var listeners = Function._events[eventName] || [], listenersNumber = listeners.length, i, eventObject = { name: eventName, args: Array.prototype.slice.call(arguments, 1) }; for(i = 0; i < listenersNumber; i++){ listeners[i].handler(eventObject); } } }
package com.verygoodsecurity.vgsshow.core.helper import com.verygoodsecurity.vgsshow.core.network.model.data.response.JsonResponseData import com.verygoodsecurity.vgsshow.widget.VGSTextView import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.hamcrest.CoreMatchers import org.json.JSONObject import org.junit.Assert.* import org.junit.Before import org.junit.Test class ViewsStoreTest { private lateinit var sut: ViewsStore private val testView = mockk<VGSTextView>(relaxed = true) private val testView2 = mockk<VGSTextView>(relaxed = true) private val testResponseData = JsonResponseData( JSONObject( mapOf( "number" to "1111", "date" to "0000", ) ) ) @Before fun setUp() { sut = ViewsStore() every { testView.getContentPath() } returns "number" every { testView2.getContentPath() } returns "date" } @Test fun update_setTextCalled() { // Arrange sut.add(testView) sut.add(testView2) // Act sut.update(testResponseData) // Assert verify { testView.setText("1111") } verify { testView2.setText("0000") } } @Test fun add_viewAdded() { // Act sut.add(testView) // Assert assertThat(sut.getViews(), CoreMatchers.hasItem(testView)) } @Test fun add_duplicateViews_oneViewAdded() { // Act sut.add(testView) sut.add(testView) // Assert assertEquals(sut.getViews().size, 1) } @Test fun remove_viewRemoved() { // Act sut.add(testView) sut.remove(testView) // Assert assertTrue(sut.getViews().isEmpty()) } @Test fun remove_twoViewsInside_correctViewRemoved() { // Act sut.add(testView) sut.add(testView2) sut.remove(testView) // Assert assertThat(sut.getViews(), CoreMatchers.hasItem(testView2)) } @Test fun clear_twoViewsInside_allViewRemoved() { // Act sut.add(testView) sut.add(testView2) sut.clear() // Assert assertTrue(sut.getViews().isEmpty()) } @Test fun update_setTextNotCalled_ignoreField() { // Arrange every { testView.ignoreField } returns true // Act sut.update(testResponseData) // Assert verify(exactly = 0) { testView.setText("1111") } } }
DISCLAIMER: work in progress, this plugin needs a lot of cleanup Support for VPP ACL on Network Interfaces. This plugin uses ETCD configuration (see sub folder model/acl) and translates it to the VPP ACL Binary API Calls.
#!/usr/bin/perl -s use strict; use warnings; use IO::Socket::INET; use vars qw/$s/; my $version = 0.991; $| = 1; # autoflush my $iproto_sync = 1; my $iproto_len = 0; sub usage { my $msg = shift; my $name = $0 =~ /([^\/]+)$/ ? $1 : $0; print "$msg\n\n" if $msg; print <<EOD; Shard create/alter: $name -s=<HOST> shard <SID> create por [REPLICA1] [REPLICA2] [REPLICA3] [REPLICA4] $name -s=<HOST> shard <SID> create raft <MASTER2> <MASTER2> $name -s=<HOST> shard <SID> create part <MASTER> $name -s=<HOST> shard <SID> add_replica <NAME> $name -s=<HOST> shard <SID> del_replica <NAME> $name -s=<HOST> shard <SID> master <NAME> $name -s=<HOST> shard <SID> delete $name -s=<HOST> shard <SID> undummy $name -s=<HOST> shard <SID> type <por|raft|part> Object space create/drop/truncate: $name -s=<HOST> shard <SID> obj_space <OID> create [no_snap] [no_wal] <INDEX CONF> $name -s=<HOST> shard <SID> obj_space <OID> drop $name -s=<HOST> shard <SID> obj_space <OID> truncate Index create/drop: $name -s=<HOST> shard <SID> obj_space <OID> index <IID> create <INDEX CONF> $name -s=<HOST> shard <SID> obj_space <OID> index <IID> drop where: HOST: addr:port SID: 0-65535 OID: 0-255 IID: 0-9 MASTER, REPLICA1-4: peer.name from octopus.cfg INDEX CONF: <INDEX TYPE> [unique] <FIELD0 CONF> [FIELD1 CONF] ... [FIELD7 CONF] INDEX TYPE: hash|numhash|tree|sptree|fasttree|compacttree FIELD CONF: <FIELD TYPE> <FID> [desc|asc] FID: 0-255 FIELD TYPE: unum16|snum16|unum32|snum32|unum64|snum64|string EOD exit 1; } sub shift_opt { my %h = @_; foreach (keys %h) { if (defined $ARGV[0] and $_ eq $ARGV[0]) { shift @ARGV; return $h{$_}; } } return undef; } sub shift_cast { my %h = @_; my $r = shift_opt(@_); return $r if defined $r; $ARGV[0] = 'nothing' if not defined $ARGV[0]; usage "expect " . join('|', sort keys %h) . " got $ARGV[0]"; } sub shift_int { my ($what, $max) = @_; my $value = $ARGV[0]; if (not defined $value or $value !~ /^\d+$/ or $value < 0 or $value > $max) { $value = 'nothing' if not defined $value; usage "expect $what: 0-$max, got $value"; } return shift @ARGV; } sub msg_shard { my ($sid) = @_; my $msg_code = 0xff02; my $version = 1; my $msg_subcode = shift_cast(create => 0, delete => 1, undummy => 2, add_replica => 3, del_replica => 4, master => 5, type => 6); my $head = pack("SSLL" . "CC", $msg_code, $sid, $iproto_len, $iproto_sync, $version, $msg_subcode); if ($msg_subcode == 0) { my $type = shift_cast(por => 0, raft => 1, part => 2); my ($peer1, $peer2, $peer3, $peer4) = @ARGV; $peer1 ||= ""; $peer2 ||= ""; $peer3 ||= ""; $peer4 ||= ""; $head .= pack("C", $type); if ($type == 0) { return $head . pack("a16" x 4, $peer1, $peer2, $peer3, $peer4); } elsif ($type == 1) { usage "master not specified" unless $peer1 && $peer2 ; return $head . pack("a16" x 3, $peer1, $peer2, $peer3); } elsif ($type == 2) { usage "master not specified" unless $peer1; return $head . pack("a16", $peer1); } } elsif ($msg_subcode == 1 || $msg_subcode == 2) { return $head; } elsif ($msg_subcode == 3 || $msg_subcode == 4 || $msg_subcode == 5) { return $head . pack("a16", ($ARGV[0] or "")); } elsif ($msg_subcode == 6) { my $type = shift_cast(por => 0, raft => 1, part => 2); return $head . pack("C", $type); } } sub index_conf { my $version = 0x10; my $type = shift_cast(hash => 0, tree => 5, numhash => 1, sptree => 3, fasttree => 3, compacttree => 4, postree => 5); my $unique = shift_opt(unique => 1) || 0; if ($type == 1 || $type == 2) { $unique = 1; } my @fields; do { my $ftype = shift_cast(unum16 => 1, snum16 => 2, unum32 => 3, snum32 => 4, unum64 => 5, snum64 => 6, unum8 => 8, snum8 => 9, string => 7); my $fid = shift_int('FID', 255); my $order = shift_opt(asc => 1, desc => 0xff) || 1; push @fields, $fid, $order, $ftype; } while (scalar @ARGV > 0); my $cardinality = @fields / 3; usage "too many index fields" if $cardinality > 8; pack ('C*', $version, $cardinality, $type, $unique, @fields); } sub msg_obj_space { my ($sid, $oid) = @_; my $msg_code = shift_cast(create => 240, drop => 242, truncate => 244); my $flags = 0; my $req; if ($msg_code == 240) { $flags |= (shift_opt(no_snap => 1) ? 0 : 1); $flags |= (shift_opt(no_wal => 2) ? 0 : 2); my $cardinality = 0; $req = pack("LLC", $oid, $flags, $cardinality) . index_conf(); } else { $req = pack("LL", $oid, $flags); } return pack("SSLL", $msg_code, $sid, $iproto_len, $iproto_sync) . $req; } sub msg_index { my ($sid, $oid, $iid) = @_; my $msg_code = shift_cast(create => 241, drop => 243); my $flags = 0; my $index_conf = $msg_code == 241 ? index_conf() : ""; return pack("SSLL" . "LLC", $msg_code, $sid, $iproto_len, $iproto_sync, $oid, $flags, $iid) . $index_conf; } sub op { if (not defined $ARGV[0] or $ARGV[0] !~ /^$_[0]$/) { $ARGV[0] = 'nothing' if not defined $ARGV[0]; usage "expect $_[0], got $ARGV[0]\n"; } return $ARGV[0]; } usage() unless $s; my ($sid, $oid, $iid, $req, $resp); op('shard'); shift @ARGV; $sid = shift_int('SID', 65535); if (op(qr/create|(add|del)_replica|master|delete|undummy|type|obj_space/) ne 'obj_space') { $req = msg_shard($sid); } else { shift @ARGV; $oid = shift_int('OID', 255); if (op(qr/create|drop|truncate|index/) ne 'index') { $req = msg_obj_space($sid, $oid); } else { shift @ARGV; $iid = shift_int('IID', 9); $req = msg_index($sid, $oid, $iid); } } my $sock = new IO::Socket::INET(PeerHost => $s, Proto => 'tcp')or die "connect: $!"; substr($req, 4, 4) = pack('L', length($req) - 12); $sock->send($req); my $ret = $sock->recv($resp, 1024); die "recv: $!" if not defined $ret; die "recv: unexpected EOF" if length $resp < 16; my ($msg, $len, $sync, $ret_code) = unpack("LLLL", $resp); if ($ret_code != 0) { printf('error: 0x%x %s'."\n", $ret_code, substr($resp, 16)); } else { print "ok\n"; }