text
stringlengths
27
775k
import { connect } from 'react-redux' import { generate } from 'shortid' import { setOrderDelivered, addOrder } from './ordersActions' import OrderList from './OrderList' const mapStateToProps = ({ orders, environments }, { match }) => { const environment = match.params.environment if (!environments[environment]) return { name: false } const ordersForEnvironment = Object.keys(orders).filter( id => orders[id].environment === match.params.environment ) return { name: environments[environment].name, orders: ordersForEnvironment.reduce((pre, id) => ({ ...pre, [id]: orders[id] }), {}), delivered: ordersForEnvironment.filter(id => orders[id].delivered), pending: ordersForEnvironment.filter(id => !orders[id].delivered) } } const mapDispatchToProps = (dispatch, { match }) => ({ onToggle: id => delivered => dispatch(setOrderDelivered({ id, delivered })), onAdd: () => dispatch( addOrder({ id: generate(), environment: match.params.environment }) ) }) export default connect(mapStateToProps, mapDispatchToProps)(OrderList)
from concurrent.futures.process import ProcessPoolExecutor class Book(object): def __init__(self, book_path, book_output, pool: ProcessPoolExecutor, base_assets): self._book_path = book_path self._book_output = book_output self._summary_path = "SUMMARY.md" self._summary_json = {} self._summary_classify_list = [] self._config = {} self._assets_path = ["assets", "RPbook"] self._assets_path_out = "RPbook" self._i18n = {} self.pool = pool self._base_assets = base_assets self._book_js = "" @property def book_path(self): """书籍路径""" return self._book_path @book_path.setter def book_path(self, book_path): """设置书籍路径""" self._book_path = book_path @property def book_output(self): """书籍输出路径""" return self._book_output @book_output.setter def book_output(self, output): """设置书籍输出路径""" self._book_output = output @property def summary_path(self): """目录路径""" return self._summary_path @summary_path.setter def summary_path(self, path): """目录路径""" self._summary_path = path @property def summary(self): """目录结构""" return self._summary_json @summary.setter def summary(self, summary_json): """目录结构""" self._summary_json = summary_json @property def config(self): """配置""" return self._config @config.setter def config(self, json): """配置""" self._config = json @property def assets_path(self): """资源路径""" return self._assets_path @assets_path.setter def assets_path(self, path): """资源路径""" self._assets_path = path @property def assets_path_out(self): """资源输出路径""" return self._assets_path_out @assets_path_out.setter def assets_path_out(self, path): """资源输出路径""" self._assets_path_out = path @property def summary_classify_list(self): """目录分类后结构""" return self._summary_classify_list @property def i18n(self): """语言字符""" return self._i18n @i18n.setter def i18n(self, lang): """语言字符""" self._i18n = lang @property def book_js(self): """自定义 js""" return self._book_js @book_js.setter def book_js(self, book_js): """自定义 js""" self._book_js = book_js @property def base_assets(self): return self._base_assets
require 'shipitron' require 'shipitron/consul_keys' require 'json' module Shipitron module Server module Docker class Configure include Metaractor include ConsulKeys required :application optional :registry before do configure_consul_client! end def call username = fetch_scoped_key('docker_user') password = fetch_scoped_key('docker_password') if username && password Logger.info `docker login --username #{username} --password #{password}` if $? != 0 fail_with_error!(message: 'Docker login failed.') end end if registry case registry when /docker\.io/ # do nothing when /\d+\.dkr\.ecr\.us-east-1\.amazonaws\.com/ # ECR config_file = Pathname.new('/home/shipitron/.docker/config.json') config_file.parent.mkpath config_hash = {} if config_file.file? config_file.open('rb') do |file| json = file.read config_hash = JSON.parse(json) rescue {} end end config_hash['credHelpers'] ||= {} config_hash['credHelpers'][registry] = 'ecr-login' config_file.open('wb') do |file| file.puts(JSON.generate(config_hash)) file.chmod(0600) end end end end private def application context.application end def registry context.registry end def fetch_scoped_key(key) value = fetch_key(key: "shipitron/#{application}/#{key}") value = fetch_key(key: "shipitron/#{key}") if value.nil? value end end end end end
// Load modules var Rule = require('./controller/rule'), Product = require('./controller/product'), Static = require('./static'); // API Server Endpoints exports.endpoints = [ { method: 'GET', path: '/{somethingss*}', config: Static.get }, { method: 'POST', path: '/rule', config: Rule.create}, { method: 'POST', path: '/getFilteredRule', config: Rule.filterRuleData}, { method: 'GET', path: '/rule', config: Rule.getAll}, { method: 'GET', path: '/rule/{id}', config: Rule.getOne}, { method: 'PUT', path: '/rule/{id}', config: Rule.update}, { method: 'POST', path: '/getFilteredProduct', config: Rule.filterRuleData}, { method: 'POST', path: '/createProduct', config: Product.createProduct} ];
<?php namespace Modules\User\Entities\Usher; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Maatwebsite\Usher\Contracts\Roles\Role as RoleInterface; use Maatwebsite\Usher\Domain\Roles\Role as UsherRole; /** * @ORM\Entity * @ORM\Table(name="roles") * @ORM\HasLifecycleCallbacks() */ class Role extends UsherRole implements RoleInterface { /** * @ORM\ManyToMany(targetEntity="User", mappedBy="roles") * @var ArrayCollection|\Maatwebsite\Usher\Contracts\Users\User[] **/ protected $users; /** * @return ArrayCollection */ public function getUsers() { return $this->users; } public function users() { return $this->getUsers(); } /** * @param ArrayCollection $users */ public function setUsers(ArrayCollection $users) { $this->users = $users; } /** * @param $attribute * @return null|string */ public function __get($attribute) { $method = 'get' . studly_case($attribute); if (method_exists($this, $method)) { return $this->{$method}(); } return null; } /** * @param $attribute * @return bool */ public function __isset($attribute) { $method = 'get' . studly_case($attribute); if (method_exists($this, $method)) { return true; } return false; } }
--- title: Counters.Remove method description: Removes a CounterItem instance from the collection. ms.assetid: 88e5907a-8c8f-4a24-9c5d-0c592f61dac0 keywords: - Remove method SysMon - Remove method SysMon , Counters class - Counters class SysMon , Remove method topic_type: - apiref api_name: - Counters.Remove api_location: - Sysmon.ocx api_type: - COM ms.topic: reference ms.date: 05/31/2018 --- # Counters.Remove method Removes a [**CounterItem**](counteritem.md) instance from the collection. ## Syntax ```VB Counters.Remove( _ ByVal index As Object _ ) ``` ## Parameters <dl> <dt> *index* \[in\] </dt> <dd> Index of the [**CounterItem**](counteritem.md) object to remove from the collection. The index is one-based. </dd> </dl> ## Return value This method does not return a value. ## Exceptions | Exception type | Condition | |-------------------------------------------------|----------------------------------------------------------------| | **System.Runtime.InteropServices.COMException** | The specified index is not valid. The Err.Number value is ???. | ## Remarks To remove all counters from the collection, you can call [**SystemMonitor.Reset**](systemmonitor-reset.md). ## Requirements | Requirement | Value | |-------------------------------------|---------------------------------------------------------------------------------------| | Minimum supported client<br/> | Windows 2000 Professional \[desktop apps only\]<br/> | | Minimum supported server<br/> | Windows 2000 Server \[desktop apps only\]<br/> | | DLL<br/> | <dl> <dt>Sysmon.ocx</dt> </dl> | ## See also <dl> <dt> [**Counters**](counters.md) </dt> <dt> [**SystemMonitor.Reset**](systemmonitor-reset.md) </dt> </dl>
#!/usr/bin/env bash # # Summary: Adds the public key (for the current user) to github. This script is # intended to be hosted somewhere, downloaded (wget) and modified to add # github token. # # This script should be called from: # `scripts.pub/Bash/provision/ubuntu/bootstrapper.sh` # # See README.md in this directory. # if [ ! -f "logger.sh" ]; then me=`basename "$0"` errormessage="critical error in '${me}': missing: logger.sh" logthis "${errormessage}" logthis "${errormessage}" >> "${HOME}/bootstrap.error.log" return 1; fi . logger.sh ; loggerstarted "scripts.pub\Bash\provision\add-github-pubkey.sh" if [[ $(($#%4)) > 0 ]] || [[ $1 =~ ^((-[hH])|(--[hH][eEaA][lL][pP]))$ ]] ; then logthis "Usage: $0 \"machine-name\" \"username\" \"github-token\"" logthis "actual: 0='$0' 1='$1' 2='$2' 3='$3' 4='$4' 5='$5' 6='$6'" sleep 5 return 1 fi machinename="${1}" githubusername="${2}" githubtoken="${3}" githubpassword="${4}" # # Preparation # # If you need to change the token (Personal Access Token), jump on another # computer, log in to github, goto: # Settings > (Developer Settings) Personal access tokens, and then # 1. Delete old token(s) # 2. > "Generate new token": add a description and check "write:public_key" keyname="${machinename}" token="${githubtoken}" sshkeypath="${HOME}/.ssh/id_rsa.pub" if [ ! -f "${sshkeypath}" ]; then logthis "ERROR: sshkeypath='${sshkeypath}' does not exist!" return 1; fi logthis "sshkeypath='${sshkeypath}'" logthisfile "${sshkeypath}" data='{"title":"'$keyname'","key":"'`cat "${sshkeypath}"`'"}'; logthis "Uploading private key to ${githubusername}@github: ${data}" curl -v -H "Authorization: token $token" -u "$githubusername" --data "$data" https://api.github.com/user/keys
require File.expand_path(File.dirname(__FILE__) + '/acceptance_helper') feature 'display deals' do context 'guest' do scenario 'no deals' do visit '/' find('#deals_button').click page.should have_content 'No deals yet' end scenario 'one or more deals' do deal = Deal.make!(:complete) visit '/' find('#deals_button').click page.should have_link "deal_#{deal.id.to_s}" page.should_not have_content 'No deals yet' end scenario 'show deal' do deal = Deal.make!(:complete) visit '/' find('#deals_button').click click_link "deal_#{deal.id.to_s}" page.should have_content deal.company_name page.should have_content deal.category page.should have_content deal.round page.should_not have_link 'Edit' page.should_not have_link 'Destroy' page.should have_link 'Back' end end context 'user' do scenario 'show deal' do deal = Deal.make!(:complete) login_normal find('#deals_button').click click_link "deal_#{deal.id.to_s}" page.should have_content deal.company_name page.should have_content deal.category page.should have_content deal.round page.should have_link 'Edit' page.should have_link 'Destroy' page.should have_link 'Back' end end end
<?php declare(strict_types = 1); namespace Bakabot\Payload\Processor\Firewall\Rule; use Amp\Failure; use Amp\Promise; use Amp\Success; use Bakabot\Payload\PayloadInterface; use Bakabot\Payload\Processor\Firewall\RuleViolation; final class IgnoreDirectMessages implements RuleInterface { public function getDetailedMessage(PayloadInterface $payload): string { return 'Ignoring direct message'; } /** * @param PayloadInterface $payload * @return Failure<RuleViolation>|Promise<PayloadInterface> */ public function enforce(PayloadInterface $payload): Failure|Promise { if ($payload->getChannel()->isPrivate()) { /** @var Failure<RuleViolation> $failure */ $failure = new Failure(new RuleViolation($this)); return $failure; } /** @var Success<PayloadInterface> $success */ $success = new Success($payload); return $success; } public function getName(): string { return RuleInterface::PREFIX_INTERNAL . 'ignore-direct-messages'; } }
'use strict'; require('angular').module('app') .factory('PageResource', require('./PageResource')) ;
package com.kevalpatel2106.brew.repo import androidx.paging.ExperimentalPagingApi import androidx.paging.LoadType import androidx.paging.PagingState import androidx.paging.RemoteMediator import androidx.paging.rxjava2.RxRemoteMediator import com.kevalpatel2106.brew.repo.db.BreweryDao import com.kevalpatel2106.brew.repo.dto.BreweryDto import com.kevalpatel2106.brew.repo.network.BreweriesApi import com.kevalpatel2106.brew.repo.network.NetworkConfig import io.reactivex.Single import io.reactivex.schedulers.Schedulers import javax.inject.Inject import kotlin.math.floor /** * [RxRemoteMediator] for the list of [BreweryDto]. This is to handle loading the page from network * when loaded the database cached item. * * @see [RemoteMediator] */ @OptIn(ExperimentalPagingApi::class) class BreweryListRemoteMediator @Inject constructor( private val breweriesApi: BreweriesApi, private val breweryDao: BreweryDao ) : RxRemoteMediator<Int, BreweryDto>() { override fun loadSingle( loadType: LoadType, state: PagingState<Int, BreweryDto> ): Single<MediatorResult> { if (loadType == LoadType.PREPEND) { // We don't support prepend return Single.just(MediatorResult.Success(endOfPaginationReached = true)) } return getLastCachedPageCount() .flatMap { page -> if (page > 0 && loadType == LoadType.REFRESH) { // While refreshing if the data is already cached, we don't want to go over network Single.just(MediatorResult.Success(endOfPaginationReached = false)) } else { breweriesApi.getBreweries(page + 1) .doOnSuccess { dtos -> breweryDao.insertAll(dtos) } .map { dtos -> MediatorResult.Success(dtos.isEmpty()) as MediatorResult } } } .subscribeOn(Schedulers.io()) .onErrorResumeNext { it.printStackTrace() Single.just(MediatorResult.Error(it) as MediatorResult) } } private fun getLastCachedPageCount(): Single<Int> { return breweryDao.getCount() .map { count -> floor((count / NetworkConfig.PER_PAGE_ITEMS).toDouble()).toInt() } } }
# fuge-runner [![npm version][npm-badge]][npm-url] [![npm downloads][npm-downloads-badge]][npm-url] [![Build Status][travis-badge]][travis-url] Process and container runner and watcher for the fuge tool. If you're using this module, and need help, you can: - Post a [github issue][], - Reach out on twitter to @pelger ## Install To install, simply use npm. ```sh npm install fuge-runner ``` ## Test To run tests, simply use npm: ``` npm run test ``` ## Contributing The [apparatus team][] encourage open participation. If you feel you can help in any way, be it with documentation, examples, extra testing, or new features please get in touch. ## License Copyright the apparatus team 2015, Licensed under [MIT][]. [npm-badge]: https://badge.fury.io/js/fuge-runner.svg [npm-url]: https://badge.fury.io/js/fuge-runner [npm-downloads-badge]: https://img.shields.io/npm/dm/fuge-runner.svg?maxAge=2592000 [travis-badge]: https://travis-ci.org/apparatus/fuge-runner.svg?branch=master [travis-url]: https://travis-ci.org/apparatus/fuge-runner [travis-badge]: https://travis-ci.org/apparatus/fuge-runner.svg [apparatus team]: https://github.com/apparatus [MIT]: ./LICENSE [github issue]: https://github.com/apparatus/fuge-runner/issues/new
# msslib The aim of `msslib` is to make it easy to work with Landsat MSS data in Earth Engine. It assembles image collections across the five satellites that carried the MSS sensor, filters images for quality, calculates TOA reflectance, and calculates the MSScvm cloud mask. ## Guide ### Module import Include the following line at the top of every script to import the library. ```js var msslib = require('users/jstnbraaten/modules:msslib/msslib.js'); ``` ### Example workflow This example demonstrates how to assemble an MSS image collection, view thumbnails to assess quality, reassemble collection to remove bad images, transform the images to TOA reflectance, add an NDVI band, and apply QA and cloud/shadow masks. Import the `msslib` module. ```js var msslib = require('users/jstnbraaten/modules:msslib/msslib.js'); ``` Get an MSS image collection filtered by region and day of year, as well as default settings for cloud and RMSE. ```js var mssDnCol = msslib.getCol({ aoi: ee.Geometry.Point([-122.239, 44.018]), doyRange: [170, 240] }); ``` View image thumbnails to get a sense for quality. ```js msslib.viewThumbnails(mssDnCol); ``` Retrieve an image collection again, but this time exclude bad images identified previously. ```js var mssDnCol = msslib.getCol({ aoi: ee.Geometry.Point([-122.239, 44.018]), doyRange: [170, 240], excludeIds: ['LM10480291974234GDS03', 'LM20490291975185GDS03'] }); ``` Convert the collection to top of atmosphere reflectance. ```js var mssToaCol = mssDnCol.map(msslib.calcToa); ``` Add the NDVI transformation as a band to all images in the collection. ```js mssToaCol = mssToaCol.map(msslib.addNdvi); ``` Apply the MSS clear-view-mask ([MSScvm](https://jdbcode.github.io/MSScvm/index.html)) to all images in the collection to remove clouds and cloud shadows. ```js mssToaCol = mssToaCol.map(msslib.applyMsscvm); ``` Apply QA band to all images in the collection. ```js mssToaCol = mssToaCol.map(msslib.applyQaMask); ``` ## Components
import 'dart:convert'; class HttpMethod { final String name; const HttpMethod._(this.name); @override String toString() => 'HttpMethod.$name'; static const httpGet = HttpMethod._('GET'); static const httpPost = HttpMethod._('POST'); static const httpDelete = HttpMethod._('DELETE'); } /// Request data to send to WebDriver. /// /// It should be converted to corresponding object in different implementations /// of [RequestClient]. /// This is useful to remove dependency on implementation specific request /// class. class WebDriverRequest { final HttpMethod? method; final String? uri; final String? body; WebDriverRequest(this.method, this.uri, this.body); WebDriverRequest.postRequest(this.uri, [params]) : method = HttpMethod.httpPost, body = params == null ? '{}' : json.encode(params); WebDriverRequest.getRequest(this.uri) : method = HttpMethod.httpGet, body = null; WebDriverRequest.deleteRequest(this.uri) : method = HttpMethod.httpDelete, body = null; /// Represents request that has no http request to make. /// /// Useful when the endpoint is not supported but can be inferred in some /// degree locally. WebDriverRequest.nullRequest(this.body) : method = null, uri = null; @override String toString() => '${method!.name} $uri: $body'; } /// Request data got from WebDriver. /// /// It should be converted from corresponding object in different /// implementations of [RequestClient]. /// This is useful to remove dependency on implementation specific response /// class. class WebDriverResponse { final int? statusCode; final String? reasonPhrase; final String? body; WebDriverResponse(this.statusCode, this.reasonPhrase, this.body); @override String toString() => '$reasonPhrase ($statusCode): $body'; }
package com.yapp.web2.domain.remind.entity.dto import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty @ApiModel(description = "리마인드 읽음처리 할 북마크 ID 리스트") class ReadRemindListRequest( @ApiModelProperty( value = "북마크 ID 리스트", required= true, example = "bookmarkIdList : \"61bdbbaa72b0f85372ad57c8\", \"61bdbbaa72b0f8551ac8adn\" ... ") val bookmarkIdList: MutableList<String> )
# ~FC015 define :manual_installer do include_recipe 'ohai' include_recipe 'build-essential' include_recipe 'rbenv::default' include_recipe 'rbenv::ruby_build' include_recipe 'awscli' ark 'download-codedeploy' do url node['aws-codedeploy-agent']['git-archive'] path '/opt' action :put end link '/opt/codedeploy-agent' do to '/opt/download-codedeploy' not_if 'test -f /opt/codedeploy-agent' end file '/opt/codedeploy-agent/bin/codedeploy-agent' do mode '0755' owner 'root' group 'root' end rbenv_ruby node['aws-codedeploy-agent']['ruby-version'] do ruby_version node['aws-codedeploy-agent']['ruby-version'] global true end %w(simple_pid gli logging zip).each do |gem| rbenv_gem gem do ruby_version node['aws-codedeploy-agent']['ruby-version'] end end rbenv_gem 'aws-sdk-core' do ruby_version node['aws-codedeploy-agent']['ruby-version'] version node['aws-codedeploy-agent']['aws-sdk-version'] end link '/usr/bin/ruby2.0' do to '/opt/rbenv/versions/2.0.0-p645/bin/ruby' end link '/etc/init.d/codedeploy-agent' do to '/opt/codedeploy-agent/init.d/codedeploy-agent' end %w(/opt/codedeploy-agent/deployment-root /etc/codedeploy-agent/conf).each do |dir| directory dir do action :create recursive true end end link '/etc/codedeploy-agent/conf/codedeployagent.yml' do to '/opt/codedeploy-agent/conf/codedeployagent.yml' end service 'codedeploy-agent' do provider Chef::Provider::Service::Init action [:enable, :start] end end
// Code generated by monitor-code-gen. DO NOT EDIT. package vsphere import ( "github.com/signalfx/golib/v3/datapoint" "github.com/signalfx/signalfx-agent/pkg/monitors" ) const monitorType = "vsphere" const ( groupCPU = "cpu" groupDatastore = "datastore" groupDisk = "disk" groupHbr = "hbr" groupMem = "mem" groupNet = "net" groupPower = "power" groupRescpu = "rescpu" groupStorageAdapter = "storage_adapter" groupStoragePath = "storage_path" groupSys = "sys" groupVirtualDisk = "virtual_disk" ) var groupSet = map[string]bool{ groupCPU: true, groupDatastore: true, groupDisk: true, groupHbr: true, groupMem: true, groupNet: true, groupPower: true, groupRescpu: true, groupStorageAdapter: true, groupStoragePath: true, groupSys: true, groupVirtualDisk: true, } const ( vsphereCPUCoreUtilizationPercent = "vsphere.cpu_core_utilization_percent" vsphereCPUCostopMs = "vsphere.cpu_costop_ms" vsphereCPUDemandEntitlementRatioPercent = "vsphere.cpu_demand_entitlement_ratio_percent" vsphereCPUDemandMhz = "vsphere.cpu_demand_mhz" vsphereCPUEntitlementMhz = "vsphere.cpu_entitlement_mhz" vsphereCPUIdleMs = "vsphere.cpu_idle_ms" vsphereCPULatencyPercent = "vsphere.cpu_latency_percent" vsphereCPUMaxlimitedMs = "vsphere.cpu_maxlimited_ms" vsphereCPUOverlapMs = "vsphere.cpu_overlap_ms" vsphereCPUReadinessPercent = "vsphere.cpu_readiness_percent" vsphereCPUReadyMs = "vsphere.cpu_ready_ms" vsphereCPUReservedCapacityMhz = "vsphere.cpu_reservedCapacity_mhz" vsphereCPURunMs = "vsphere.cpu_run_ms" vsphereCPUSwapwaitMs = "vsphere.cpu_swapwait_ms" vsphereCPUSystemMs = "vsphere.cpu_system_ms" vsphereCPUTotalCapacityMhz = "vsphere.cpu_totalCapacity_mhz" vsphereCPUUsagePercent = "vsphere.cpu_usage_percent" vsphereCPUUsagemhz = "vsphere.cpu_usagemhz" vsphereCPUUsedPercent = "vsphere.cpu_used_percent" vsphereCPUUtilizationPercent = "vsphere.cpu_utilization_percent" vsphereCPUWaitMs = "vsphere.cpu_wait_ms" vsphereDatastoreDatastoreIops = "vsphere.datastore_datastore_iops" vsphereDatastoreMaxTotalLatencyMs = "vsphere.datastore_max_total_latency_ms" vsphereDatastoreReadKbs = "vsphere.datastore_read_kbs" vsphereDatastoreReadLoadMetric = "vsphere.datastore_read_load_metric" vsphereDatastoreSizeNormalizedDatastoreLatencyMs = "vsphere.datastore_size_normalized_datastore_latency_ms" vsphereDatastoreTotalReadLatencyMs = "vsphere.datastore_total_read_latency_ms" vsphereDatastoreTotalWriteLatencyMs = "vsphere.datastore_total_write_latency_ms" vsphereDatastoreVmobservedLatencyMs = "vsphere.datastore_vmobserved_latency_ms" vsphereDatastoreWriteKbs = "vsphere.datastore_write_kbs" vsphereDatastoreWriteLoadMetric = "vsphere.datastore_write_load_metric" vsphereDiskBusResets = "vsphere.disk_bus_resets" vsphereDiskCommands = "vsphere.disk_commands" vsphereDiskCommandsAborted = "vsphere.disk_commands_aborted" vsphereDiskCommandsAveraged = "vsphere.disk_commands_averaged" vsphereDiskDeviceLatencyMs = "vsphere.disk_device_latency_ms" vsphereDiskDeviceReadLatencyMs = "vsphere.disk_device_read_latency_ms" vsphereDiskDeviceWriteLatencyMs = "vsphere.disk_device_write_latency_ms" vsphereDiskKernelLatencyMs = "vsphere.disk_kernel_latency_ms" vsphereDiskKernelReadLatencyMs = "vsphere.disk_kernel_read_latency_ms" vsphereDiskKernelWriteLatencyMs = "vsphere.disk_kernel_write_latency_ms" vsphereDiskMaxQueueDepth = "vsphere.disk_max_queue_depth" vsphereDiskMaxTotalLatencyMs = "vsphere.disk_max_total_latency_ms" vsphereDiskNumberRead = "vsphere.disk_number_read" vsphereDiskNumberReadAveraged = "vsphere.disk_number_read_averaged" vsphereDiskNumberWrite = "vsphere.disk_number_write" vsphereDiskNumberWriteAveraged = "vsphere.disk_number_write_averaged" vsphereDiskQueueLatencyMs = "vsphere.disk_queue_latency_ms" vsphereDiskQueueReadLatencyMs = "vsphere.disk_queue_read_latency_ms" vsphereDiskQueueWriteLatencyMs = "vsphere.disk_queue_write_latency_ms" vsphereDiskReadKbs = "vsphere.disk_read_kbs" vsphereDiskTotalLatencyMs = "vsphere.disk_total_latency_ms" vsphereDiskTotalReadLatencyMs = "vsphere.disk_total_read_latency_ms" vsphereDiskTotalWriteLatencyMs = "vsphere.disk_total_write_latency_ms" vsphereDiskUsageKbs = "vsphere.disk_usage_kbs" vsphereDiskWriteKbs = "vsphere.disk_write_kbs" vsphereHbrNetRxKbs = "vsphere.hbr_net_rx_kbs" vsphereHbrNetTxKbs = "vsphere.hbr_net_tx_kbs" vsphereHbrNumVms = "vsphere.hbr_num_vms" vsphereMemActiveKb = "vsphere.mem_active_kb" vsphereMemActivewriteKb = "vsphere.mem_activewrite_kb" vsphereMemCompressedKb = "vsphere.mem_compressed_kb" vsphereMemCompressionRateKbs = "vsphere.mem_compression_rate_kbs" vsphereMemConsumedKb = "vsphere.mem_consumed_kb" vsphereMemDecompressionRateKbs = "vsphere.mem_decompression_rate_kbs" vsphereMemEntitlementKb = "vsphere.mem_entitlement_kb" vsphereMemGrantedKb = "vsphere.mem_granted_kb" vsphereMemHeapKb = "vsphere.mem_heap_kb" vsphereMemHeapfreeKb = "vsphere.mem_heapfree_kb" vsphereMemLatencyPercent = "vsphere.mem_latency_percent" vsphereMemLlSwapInKb = "vsphere.mem_ll_swap_in_kb" vsphereMemLlSwapInRateKbs = "vsphere.mem_ll_swap_in_rate_kbs" vsphereMemLlSwapOutKb = "vsphere.mem_ll_swap_out_kb" vsphereMemLlSwapOutRateKbs = "vsphere.mem_ll_swap_out_rate_kbs" vsphereMemLlSwapUsedKb = "vsphere.mem_ll_swap_used_kb" vsphereMemLowfreethresholdKb = "vsphere.mem_lowfreethreshold_kb" vsphereMemOverheadKb = "vsphere.mem_overhead_kb" vsphereMemOverheadMaxKb = "vsphere.mem_overhead_max_kb" vsphereMemOverheadTouchedKb = "vsphere.mem_overhead_touched_kb" vsphereMemReservedCapacityMb = "vsphere.mem_reserved_capacity_mb" vsphereMemSharedKb = "vsphere.mem_shared_kb" vsphereMemSharedcommonKb = "vsphere.mem_sharedcommon_kb" vsphereMemState = "vsphere.mem_state" vsphereMemSwapinKb = "vsphere.mem_swapin_kb" vsphereMemSwapinRateKbs = "vsphere.mem_swapin_rate_kbs" vsphereMemSwapoutKb = "vsphere.mem_swapout_kb" vsphereMemSwapoutRateKbs = "vsphere.mem_swapout_rate_kbs" vsphereMemSwappedKb = "vsphere.mem_swapped_kb" vsphereMemSwaptargetKb = "vsphere.mem_swaptarget_kb" vsphereMemSwapusedKb = "vsphere.mem_swapused_kb" vsphereMemSysUsageKb = "vsphere.mem_sys_usage_kb" vsphereMemTotalCapacityMb = "vsphere.mem_total_capacity_mb" vsphereMemUnreservedKb = "vsphere.mem_unreserved_kb" vsphereMemUsagePercent = "vsphere.mem_usage_percent" vsphereMemVmfsPbcCapMissRatioPercent = "vsphere.mem_vmfs_pbc_cap_miss_ratio_percent" vsphereMemVmfsPbcOverheadKb = "vsphere.mem_vmfs_pbc_overhead_kb" vsphereMemVmfsPbcSizeMaxMb = "vsphere.mem_vmfs_pbc_size_max_mb" vsphereMemVmfsPbcSizeMb = "vsphere.mem_vmfs_pbc_size_mb" vsphereMemVmfsPbcWorkingSetMaxTb = "vsphere.mem_vmfs_pbc_working_set_max_tb" vsphereMemVmfsPbcWorkingSetTb = "vsphere.mem_vmfs_pbc_working_set_tb" vsphereMemVmmemctlKb = "vsphere.mem_vmmemctl_kb" vsphereMemVmmemctltargetKb = "vsphere.mem_vmmemctltarget_kb" vsphereMemZeroKb = "vsphere.mem_zero_kb" vsphereMemZipSavedKb = "vsphere.mem_zip_saved_kb" vsphereMemZippedKb = "vsphere.mem_zipped_kb" vsphereNetBroadcastRx = "vsphere.net_broadcast_rx" vsphereNetBroadcastTx = "vsphere.net_broadcast_tx" vsphereNetBytesRxKbs = "vsphere.net_bytes_rx_kbs" vsphereNetBytesTxKbs = "vsphere.net_bytes_tx_kbs" vsphereNetDroppedRx = "vsphere.net_dropped_rx" vsphereNetDroppedTx = "vsphere.net_dropped_tx" vsphereNetErrorsRx = "vsphere.net_errors_rx" vsphereNetErrorsTx = "vsphere.net_errors_tx" vsphereNetMulticastRx = "vsphere.net_multicast_rx" vsphereNetMulticastTx = "vsphere.net_multicast_tx" vsphereNetPacketsRx = "vsphere.net_packets_rx" vsphereNetPacketsTx = "vsphere.net_packets_tx" vsphereNetReceivedKbs = "vsphere.net_received_kbs" vsphereNetTransmittedKbs = "vsphere.net_transmitted_kbs" vsphereNetUnknownProtos = "vsphere.net_unknown_protos" vsphereNetUsageKbs = "vsphere.net_usage_kbs" vspherePowerCapWatts = "vsphere.power_cap_watts" vspherePowerEnergyJoules = "vsphere.power_energy_joules" vspherePowerWatts = "vsphere.power_watts" vsphereRescpuActav1 = "vsphere.rescpu_actav1" vsphereRescpuActav15Percent = "vsphere.rescpu_actav15_percent" vsphereRescpuActav5Percent = "vsphere.rescpu_actav5_percent" vsphereRescpuActpk15Percent = "vsphere.rescpu_actpk15_percent" vsphereRescpuActpk1Percent = "vsphere.rescpu_actpk1_percent" vsphereRescpuActpk5Percent = "vsphere.rescpu_actpk5_percent" vsphereRescpuMaxLimited15Percent = "vsphere.rescpu_max_limited15_percent" vsphereRescpuMaxLimited1Percent = "vsphere.rescpu_max_limited1_percent" vsphereRescpuMaxLimited5Percent = "vsphere.rescpu_max_limited5_percent" vsphereRescpuRunav15Percent = "vsphere.rescpu_runav15_percent" vsphereRescpuRunav1Percent = "vsphere.rescpu_runav1_percent" vsphereRescpuRunav5Percent = "vsphere.rescpu_runav5_percent" vsphereRescpuRunpk15Percent = "vsphere.rescpu_runpk15_percent" vsphereRescpuRunpk1Percent = "vsphere.rescpu_runpk1_percent" vsphereRescpuRunpk5Percent = "vsphere.rescpu_runpk5_percent" vsphereRescpuSampleCount = "vsphere.rescpu_sample_count" vsphereRescpuSamplePeriodMs = "vsphere.rescpu_sample_period_ms" vsphereStorageAdapterCommandsAveraged = "vsphere.storage_adapter_commands_averaged" vsphereStorageAdapterMaxTotalLatencyMs = "vsphere.storage_adapter_max_total_latency_ms" vsphereStorageAdapterNumberReadAveraged = "vsphere.storage_adapter_number_read_averaged" vsphereStorageAdapterNumberWriteAveraged = "vsphere.storage_adapter_number_write_averaged" vsphereStorageAdapterReadKbs = "vsphere.storage_adapter_read_kbs" vsphereStorageAdapterTotalReadLatencyMs = "vsphere.storage_adapter_total_read_latency_ms" vsphereStorageAdapterTotalWriteLatencyMs = "vsphere.storage_adapter_total_write_latency_ms" vsphereStorageAdapterWriteKbs = "vsphere.storage_adapter_write_kbs" vsphereStoragePathCommandsAveraged = "vsphere.storage_path_commands_averaged" vsphereStoragePathMaxTotalLatencyMs = "vsphere.storage_path_max_total_latency_ms" vsphereStoragePathNumberReadAveraged = "vsphere.storage_path_number_read_averaged" vsphereStoragePathNumberWriteAveraged = "vsphere.storage_path_number_write_averaged" vsphereStoragePathReadKbs = "vsphere.storage_path_read_kbs" vsphereStoragePathTotalReadLatencyMs = "vsphere.storage_path_total_read_latency_ms" vsphereStoragePathTotalWriteLatencyMs = "vsphere.storage_path_total_write_latency_ms" vsphereStoragePathWriteKbs = "vsphere.storage_path_write_kbs" vsphereSysHeartbeat = "vsphere.sys_heartbeat" vsphereSysOsUptimeSeconds = "vsphere.sys_os_uptime_seconds" vsphereSysResourceCPUAct1Percent = "vsphere.sys_resource_cpu_act1_percent" vsphereSysResourceCPUAct5 = "vsphere.sys_resource_cpu_act5" vsphereSysResourceCPUAllocMinMhz = "vsphere.sys_resource_cpu_alloc_min_mhz" vsphereSysResourceCPUAllocShares = "vsphere.sys_resource_cpu_alloc_shares" vsphereSysResourceCPUMaxLimited1Percent = "vsphere.sys_resource_cpu_max_limited1_percent" vsphereSysResourceCPUMaxLimited5Percent = "vsphere.sys_resource_cpu_max_limited5_percent" vsphereSysResourceCPURun1Percent = "vsphere.sys_resource_cpu_run1_percent" vsphereSysResourceCPURun5Percent = "vsphere.sys_resource_cpu_run5_percent" vsphereSysResourceCPUUsageMhz = "vsphere.sys_resource_cpu_usage_mhz" vsphereSysResourceFdUsage = "vsphere.sys_resource_fd_usage" vsphereSysResourceMemAllocMaxKb = "vsphere.sys_resource_mem_alloc_max_kb" vsphereSysResourceMemAllocMinKb = "vsphere.sys_resource_mem_alloc_min_kb" vsphereSysResourceMemAllocShares = "vsphere.sys_resource_mem_alloc_shares" vsphereSysResourceMemConsumedKb = "vsphere.sys_resource_mem_consumed_kb" vsphereSysResourceMemCowKb = "vsphere.sys_resource_mem_cow_kb" vsphereSysResourceMemMappedKb = "vsphere.sys_resource_mem_mapped_kb" vsphereSysResourceMemOverheadKb = "vsphere.sys_resource_mem_overhead_kb" vsphereSysResourceMemSharedKb = "vsphere.sys_resource_mem_shared_kb" vsphereSysResourceMemSwappedKb = "vsphere.sys_resource_mem_swapped_kb" vsphereSysResourceMemTouchedKb = "vsphere.sys_resource_mem_touched_kb" vsphereSysResourceMemZeroKb = "vsphere.sys_resource_mem_zero_kb" vsphereSysUptimeSeconds = "vsphere.sys_uptime_seconds" vsphereVirtualDiskLargeSeeks = "vsphere.virtual_disk_large_seeks" vsphereVirtualDiskMediumSeeks = "vsphere.virtual_disk_medium_seeks" vsphereVirtualDiskNumberReadAveraged = "vsphere.virtual_disk_number_read_averaged" vsphereVirtualDiskNumberWriteAveraged = "vsphere.virtual_disk_number_write_averaged" vsphereVirtualDiskReadIosize = "vsphere.virtual_disk_read_iosize" vsphereVirtualDiskReadKbs = "vsphere.virtual_disk_read_kbs" vsphereVirtualDiskReadLatencyUs = "vsphere.virtual_disk_read_latency_us" vsphereVirtualDiskReadLoadMetric = "vsphere.virtual_disk_read_load_metric" vsphereVirtualDiskReadOio = "vsphere.virtual_disk_read_oio" vsphereVirtualDiskSmallSeeks = "vsphere.virtual_disk_small_seeks" vsphereVirtualDiskTotalReadLatencyMs = "vsphere.virtual_disk_total_read_latency_ms" vsphereVirtualDiskTotalWriteLatencyMs = "vsphere.virtual_disk_total_write_latency_ms" vsphereVirtualDiskWriteIosize = "vsphere.virtual_disk_write_iosize" vsphereVirtualDiskWriteKbs = "vsphere.virtual_disk_write_kbs" vsphereVirtualDiskWriteLatencyUs = "vsphere.virtual_disk_write_latency_us" vsphereVirtualDiskWriteLoadMetric = "vsphere.virtual_disk_write_load_metric" vsphereVirtualDiskWriteOio = "vsphere.virtual_disk_write_oio" ) var metricSet = map[string]monitors.MetricInfo{ vsphereCPUCoreUtilizationPercent: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUCostopMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUDemandEntitlementRatioPercent: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUDemandMhz: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUEntitlementMhz: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUIdleMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPULatencyPercent: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUMaxlimitedMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUOverlapMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUReadinessPercent: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUReadyMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUReservedCapacityMhz: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPURunMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUSwapwaitMs: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUSystemMs: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUTotalCapacityMhz: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUUsagePercent: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUUsagemhz: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUUsedPercent: {Type: datapoint.Count, Group: groupCPU}, vsphereCPUUtilizationPercent: {Type: datapoint.Gauge, Group: groupCPU}, vsphereCPUWaitMs: {Type: datapoint.Count, Group: groupCPU}, vsphereDatastoreDatastoreIops: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreMaxTotalLatencyMs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreReadKbs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreReadLoadMetric: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreSizeNormalizedDatastoreLatencyMs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreTotalReadLatencyMs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreTotalWriteLatencyMs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreVmobservedLatencyMs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreWriteKbs: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDatastoreWriteLoadMetric: {Type: datapoint.Gauge, Group: groupDatastore}, vsphereDiskBusResets: {Type: datapoint.Count, Group: groupDisk}, vsphereDiskCommands: {Type: datapoint.Count, Group: groupDisk}, vsphereDiskCommandsAborted: {Type: datapoint.Count, Group: groupDisk}, vsphereDiskCommandsAveraged: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskDeviceLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskDeviceReadLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskDeviceWriteLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskKernelLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskKernelReadLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskKernelWriteLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskMaxQueueDepth: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskMaxTotalLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskNumberRead: {Type: datapoint.Count, Group: groupDisk}, vsphereDiskNumberReadAveraged: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskNumberWrite: {Type: datapoint.Count, Group: groupDisk}, vsphereDiskNumberWriteAveraged: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskQueueLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskQueueReadLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskQueueWriteLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskReadKbs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskTotalLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskTotalReadLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskTotalWriteLatencyMs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskUsageKbs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereDiskWriteKbs: {Type: datapoint.Gauge, Group: groupDisk}, vsphereHbrNetRxKbs: {Type: datapoint.Gauge, Group: groupHbr}, vsphereHbrNetTxKbs: {Type: datapoint.Gauge, Group: groupHbr}, vsphereHbrNumVms: {Type: datapoint.Gauge, Group: groupHbr}, vsphereMemActiveKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemActivewriteKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemCompressedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemCompressionRateKbs: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemConsumedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemDecompressionRateKbs: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemEntitlementKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemGrantedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemHeapKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemHeapfreeKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLatencyPercent: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLlSwapInKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLlSwapInRateKbs: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLlSwapOutKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLlSwapOutRateKbs: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLlSwapUsedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemLowfreethresholdKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemOverheadKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemOverheadMaxKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemOverheadTouchedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemReservedCapacityMb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSharedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSharedcommonKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemState: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwapinKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwapinRateKbs: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwapoutKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwapoutRateKbs: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwappedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwaptargetKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSwapusedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemSysUsageKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemTotalCapacityMb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemUnreservedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemUsagePercent: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmfsPbcCapMissRatioPercent: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmfsPbcOverheadKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmfsPbcSizeMaxMb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmfsPbcSizeMb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmfsPbcWorkingSetMaxTb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmfsPbcWorkingSetTb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmmemctlKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemVmmemctltargetKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemZeroKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemZipSavedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereMemZippedKb: {Type: datapoint.Gauge, Group: groupMem}, vsphereNetBroadcastRx: {Type: datapoint.Count, Group: groupNet}, vsphereNetBroadcastTx: {Type: datapoint.Count, Group: groupNet}, vsphereNetBytesRxKbs: {Type: datapoint.Gauge, Group: groupNet}, vsphereNetBytesTxKbs: {Type: datapoint.Gauge, Group: groupNet}, vsphereNetDroppedRx: {Type: datapoint.Count, Group: groupNet}, vsphereNetDroppedTx: {Type: datapoint.Count, Group: groupNet}, vsphereNetErrorsRx: {Type: datapoint.Count, Group: groupNet}, vsphereNetErrorsTx: {Type: datapoint.Count, Group: groupNet}, vsphereNetMulticastRx: {Type: datapoint.Count, Group: groupNet}, vsphereNetMulticastTx: {Type: datapoint.Count, Group: groupNet}, vsphereNetPacketsRx: {Type: datapoint.Count, Group: groupNet}, vsphereNetPacketsTx: {Type: datapoint.Count, Group: groupNet}, vsphereNetReceivedKbs: {Type: datapoint.Gauge, Group: groupNet}, vsphereNetTransmittedKbs: {Type: datapoint.Gauge, Group: groupNet}, vsphereNetUnknownProtos: {Type: datapoint.Count, Group: groupNet}, vsphereNetUsageKbs: {Type: datapoint.Gauge, Group: groupNet}, vspherePowerCapWatts: {Type: datapoint.Gauge, Group: groupPower}, vspherePowerEnergyJoules: {Type: datapoint.Count, Group: groupPower}, vspherePowerWatts: {Type: datapoint.Gauge, Group: groupPower}, vsphereRescpuActav1: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuActav15Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuActav5Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuActpk15Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuActpk1Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuActpk5Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuMaxLimited15Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuMaxLimited1Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuMaxLimited5Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuRunav15Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuRunav1Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuRunav5Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuRunpk15Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuRunpk1Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuRunpk5Percent: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuSampleCount: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereRescpuSamplePeriodMs: {Type: datapoint.Gauge, Group: groupRescpu}, vsphereStorageAdapterCommandsAveraged: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterMaxTotalLatencyMs: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterNumberReadAveraged: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterNumberWriteAveraged: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterReadKbs: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterTotalReadLatencyMs: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterTotalWriteLatencyMs: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStorageAdapterWriteKbs: {Type: datapoint.Gauge, Group: groupStorageAdapter}, vsphereStoragePathCommandsAveraged: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathMaxTotalLatencyMs: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathNumberReadAveraged: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathNumberWriteAveraged: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathReadKbs: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathTotalReadLatencyMs: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathTotalWriteLatencyMs: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereStoragePathWriteKbs: {Type: datapoint.Gauge, Group: groupStoragePath}, vsphereSysHeartbeat: {Type: datapoint.Count, Group: groupSys}, vsphereSysOsUptimeSeconds: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUAct1Percent: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUAct5: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUAllocMinMhz: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUAllocShares: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUMaxLimited1Percent: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUMaxLimited5Percent: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPURun1Percent: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPURun5Percent: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceCPUUsageMhz: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceFdUsage: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemAllocMaxKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemAllocMinKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemAllocShares: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemConsumedKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemCowKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemMappedKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemOverheadKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemSharedKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemSwappedKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemTouchedKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysResourceMemZeroKb: {Type: datapoint.Gauge, Group: groupSys}, vsphereSysUptimeSeconds: {Type: datapoint.Gauge, Group: groupSys}, vsphereVirtualDiskLargeSeeks: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskMediumSeeks: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskNumberReadAveraged: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskNumberWriteAveraged: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskReadIosize: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskReadKbs: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskReadLatencyUs: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskReadLoadMetric: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskReadOio: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskSmallSeeks: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskTotalReadLatencyMs: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskTotalWriteLatencyMs: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskWriteIosize: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskWriteKbs: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskWriteLatencyUs: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskWriteLoadMetric: {Type: datapoint.Gauge, Group: groupVirtualDisk}, vsphereVirtualDiskWriteOio: {Type: datapoint.Gauge, Group: groupVirtualDisk}, } var defaultMetrics = map[string]bool{ vsphereCPUUsagePercent: true, vsphereDiskMaxQueueDepth: true, vsphereDiskMaxTotalLatencyMs: true, vsphereDiskReadKbs: true, vsphereDiskUsageKbs: true, vsphereDiskWriteKbs: true, vsphereMemSwapinRateKbs: true, vsphereMemSwapoutRateKbs: true, vsphereMemUsagePercent: true, vsphereNetReceivedKbs: true, vsphereNetTransmittedKbs: true, vsphereNetUsageKbs: true, vsphereVirtualDiskReadKbs: true, vsphereVirtualDiskWriteKbs: true, } var groupMetricsMap = map[string][]string{ groupCPU: []string{ vsphereCPUCoreUtilizationPercent, vsphereCPUCostopMs, vsphereCPUDemandEntitlementRatioPercent, vsphereCPUDemandMhz, vsphereCPUEntitlementMhz, vsphereCPUIdleMs, vsphereCPULatencyPercent, vsphereCPUMaxlimitedMs, vsphereCPUOverlapMs, vsphereCPUReadinessPercent, vsphereCPUReadyMs, vsphereCPUReservedCapacityMhz, vsphereCPURunMs, vsphereCPUSwapwaitMs, vsphereCPUSystemMs, vsphereCPUTotalCapacityMhz, vsphereCPUUsagePercent, vsphereCPUUsagemhz, vsphereCPUUsedPercent, vsphereCPUUtilizationPercent, vsphereCPUWaitMs, }, groupDatastore: []string{ vsphereDatastoreDatastoreIops, vsphereDatastoreMaxTotalLatencyMs, vsphereDatastoreReadKbs, vsphereDatastoreReadLoadMetric, vsphereDatastoreSizeNormalizedDatastoreLatencyMs, vsphereDatastoreTotalReadLatencyMs, vsphereDatastoreTotalWriteLatencyMs, vsphereDatastoreVmobservedLatencyMs, vsphereDatastoreWriteKbs, vsphereDatastoreWriteLoadMetric, }, groupDisk: []string{ vsphereDiskBusResets, vsphereDiskCommands, vsphereDiskCommandsAborted, vsphereDiskCommandsAveraged, vsphereDiskDeviceLatencyMs, vsphereDiskDeviceReadLatencyMs, vsphereDiskDeviceWriteLatencyMs, vsphereDiskKernelLatencyMs, vsphereDiskKernelReadLatencyMs, vsphereDiskKernelWriteLatencyMs, vsphereDiskMaxQueueDepth, vsphereDiskMaxTotalLatencyMs, vsphereDiskNumberRead, vsphereDiskNumberReadAveraged, vsphereDiskNumberWrite, vsphereDiskNumberWriteAveraged, vsphereDiskQueueLatencyMs, vsphereDiskQueueReadLatencyMs, vsphereDiskQueueWriteLatencyMs, vsphereDiskReadKbs, vsphereDiskTotalLatencyMs, vsphereDiskTotalReadLatencyMs, vsphereDiskTotalWriteLatencyMs, vsphereDiskUsageKbs, vsphereDiskWriteKbs, }, groupHbr: []string{ vsphereHbrNetRxKbs, vsphereHbrNetTxKbs, vsphereHbrNumVms, }, groupMem: []string{ vsphereMemActiveKb, vsphereMemActivewriteKb, vsphereMemCompressedKb, vsphereMemCompressionRateKbs, vsphereMemConsumedKb, vsphereMemDecompressionRateKbs, vsphereMemEntitlementKb, vsphereMemGrantedKb, vsphereMemHeapKb, vsphereMemHeapfreeKb, vsphereMemLatencyPercent, vsphereMemLlSwapInKb, vsphereMemLlSwapInRateKbs, vsphereMemLlSwapOutKb, vsphereMemLlSwapOutRateKbs, vsphereMemLlSwapUsedKb, vsphereMemLowfreethresholdKb, vsphereMemOverheadKb, vsphereMemOverheadMaxKb, vsphereMemOverheadTouchedKb, vsphereMemReservedCapacityMb, vsphereMemSharedKb, vsphereMemSharedcommonKb, vsphereMemState, vsphereMemSwapinKb, vsphereMemSwapinRateKbs, vsphereMemSwapoutKb, vsphereMemSwapoutRateKbs, vsphereMemSwappedKb, vsphereMemSwaptargetKb, vsphereMemSwapusedKb, vsphereMemSysUsageKb, vsphereMemTotalCapacityMb, vsphereMemUnreservedKb, vsphereMemUsagePercent, vsphereMemVmfsPbcCapMissRatioPercent, vsphereMemVmfsPbcOverheadKb, vsphereMemVmfsPbcSizeMaxMb, vsphereMemVmfsPbcSizeMb, vsphereMemVmfsPbcWorkingSetMaxTb, vsphereMemVmfsPbcWorkingSetTb, vsphereMemVmmemctlKb, vsphereMemVmmemctltargetKb, vsphereMemZeroKb, vsphereMemZipSavedKb, vsphereMemZippedKb, }, groupNet: []string{ vsphereNetBroadcastRx, vsphereNetBroadcastTx, vsphereNetBytesRxKbs, vsphereNetBytesTxKbs, vsphereNetDroppedRx, vsphereNetDroppedTx, vsphereNetErrorsRx, vsphereNetErrorsTx, vsphereNetMulticastRx, vsphereNetMulticastTx, vsphereNetPacketsRx, vsphereNetPacketsTx, vsphereNetReceivedKbs, vsphereNetTransmittedKbs, vsphereNetUnknownProtos, vsphereNetUsageKbs, }, groupPower: []string{ vspherePowerCapWatts, vspherePowerEnergyJoules, vspherePowerWatts, }, groupRescpu: []string{ vsphereRescpuActav1, vsphereRescpuActav15Percent, vsphereRescpuActav5Percent, vsphereRescpuActpk15Percent, vsphereRescpuActpk1Percent, vsphereRescpuActpk5Percent, vsphereRescpuMaxLimited15Percent, vsphereRescpuMaxLimited1Percent, vsphereRescpuMaxLimited5Percent, vsphereRescpuRunav15Percent, vsphereRescpuRunav1Percent, vsphereRescpuRunav5Percent, vsphereRescpuRunpk15Percent, vsphereRescpuRunpk1Percent, vsphereRescpuRunpk5Percent, vsphereRescpuSampleCount, vsphereRescpuSamplePeriodMs, }, groupStorageAdapter: []string{ vsphereStorageAdapterCommandsAveraged, vsphereStorageAdapterMaxTotalLatencyMs, vsphereStorageAdapterNumberReadAveraged, vsphereStorageAdapterNumberWriteAveraged, vsphereStorageAdapterReadKbs, vsphereStorageAdapterTotalReadLatencyMs, vsphereStorageAdapterTotalWriteLatencyMs, vsphereStorageAdapterWriteKbs, }, groupStoragePath: []string{ vsphereStoragePathCommandsAveraged, vsphereStoragePathMaxTotalLatencyMs, vsphereStoragePathNumberReadAveraged, vsphereStoragePathNumberWriteAveraged, vsphereStoragePathReadKbs, vsphereStoragePathTotalReadLatencyMs, vsphereStoragePathTotalWriteLatencyMs, vsphereStoragePathWriteKbs, }, groupSys: []string{ vsphereSysHeartbeat, vsphereSysOsUptimeSeconds, vsphereSysResourceCPUAct1Percent, vsphereSysResourceCPUAct5, vsphereSysResourceCPUAllocMinMhz, vsphereSysResourceCPUAllocShares, vsphereSysResourceCPUMaxLimited1Percent, vsphereSysResourceCPUMaxLimited5Percent, vsphereSysResourceCPURun1Percent, vsphereSysResourceCPURun5Percent, vsphereSysResourceCPUUsageMhz, vsphereSysResourceFdUsage, vsphereSysResourceMemAllocMaxKb, vsphereSysResourceMemAllocMinKb, vsphereSysResourceMemAllocShares, vsphereSysResourceMemConsumedKb, vsphereSysResourceMemCowKb, vsphereSysResourceMemMappedKb, vsphereSysResourceMemOverheadKb, vsphereSysResourceMemSharedKb, vsphereSysResourceMemSwappedKb, vsphereSysResourceMemTouchedKb, vsphereSysResourceMemZeroKb, vsphereSysUptimeSeconds, }, groupVirtualDisk: []string{ vsphereVirtualDiskLargeSeeks, vsphereVirtualDiskMediumSeeks, vsphereVirtualDiskNumberReadAveraged, vsphereVirtualDiskNumberWriteAveraged, vsphereVirtualDiskReadIosize, vsphereVirtualDiskReadKbs, vsphereVirtualDiskReadLatencyUs, vsphereVirtualDiskReadLoadMetric, vsphereVirtualDiskReadOio, vsphereVirtualDiskSmallSeeks, vsphereVirtualDiskTotalReadLatencyMs, vsphereVirtualDiskTotalWriteLatencyMs, vsphereVirtualDiskWriteIosize, vsphereVirtualDiskWriteKbs, vsphereVirtualDiskWriteLatencyUs, vsphereVirtualDiskWriteLoadMetric, vsphereVirtualDiskWriteOio, }, } var monitorMetadata = monitors.Metadata{ MonitorType: "vsphere", DefaultMetrics: defaultMetrics, Metrics: metricSet, SendUnknown: false, Groups: groupSet, GroupMetricsMap: groupMetricsMap, SendAll: false, }
RSpec.describe Message do describe "validations" do it "cannot have a nil sender" do message = build(:message) message.sender = nil expect(message).not_to be_valid end it "can have a zero sender_id to represent site messages" do message = build(:message) message.sender_id = 0 expect(message).to be_valid expect(message.sender_name).to eq('Glowfic Constellation') end end describe "#notify_recipient" do before(:each) do ResqueSpec.reset! end it "does not send with notifications off" do message = create(:message) expect(message.recipient.email_notifications).not_to eq(true) expect(UserMailer).to have_queue_size_of(0) end it "does not send with no email" do user = create(:user) user.update_columns(email: nil) # rubocop:disable Rails/SkipsModelValidations create(:message, recipient: user) expect(UserMailer).to have_queue_size_of(0) end it "sends with notifications on" do notified_user = create(:user, email_notifications: true) message = create(:message, recipient: notified_user) expect(UserMailer).to have_queue_size_of(1) expect(UserMailer).to have_queued(:new_message, [message.id]) end it "does not notify blocking recipients" do recipient = create(:user, email_notifications: true) block = create(:block, block_interactions: true, blocking_user: recipient) create(:message, sender: block.blocked_user, recipient: recipient) expect(UserMailer).to have_queue_size_of(0) end end describe "#unread_count_for" do let(:user) { create(:user) } it "returns unread inbox count" do expect(Message.unread_count_for(user)).to eq(0) create_list(:message, 2, recipient: user) expect(Message.unread_count_for(user)).to eq(2) end it "clears cache on new inbox message" do create_list(:message, 2, recipient: user) expect(Message.unread_count_for(user)).to eq(2) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(true) create(:message, recipient: user) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(false) expect(Message.unread_count_for(user)).to eq(3) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(true) end it "clears cache when inbox message marked read" do create(:message, recipient: user) message = create(:message, recipient: user) create_list(:message, 2, recipient: user) expect(Message.unread_count_for(user)).to eq(4) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(true) message.update!(unread: false) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(false) expect(Message.unread_count_for(user)).to eq(3) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(true) end it "does not clear cache on unrelated message" do create_list(:message, 2, recipient: user) expect(Message.unread_count_for(user)).to eq(2) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(true) create(:message) expect(Rails.cache.exist?(Message.cache_string_for(user.id))).to eq(true) end end it "hides blocked messages from recipient without erroring to sender" do block = create(:block, block_interactions: true) message = build(:message, sender: block.blocked_user, recipient: block.blocking_user) expect(message.save).to be true expect(message.visible_inbox).to eq(false) expect(message.unread).to eq(false) end it "errors to sender if messaging a blocked user" do block = create(:block, block_interactions: true) message = build(:message, sender: block.blocking_user, recipient: block.blocked_user) expect(message.save).to eq(false) expect(message.errors.full_messages.first).to eq("Recipient must not be blocked by you") end it "does not error to blocked user if updating an existing message" do message = create(:message) create(:block, blocking_user: message.sender, blocked_user: message.recipient) message.unread = false message.save! end it "errors to sender if messaging a deleted user" do message = build(:message, recipient: create(:user, deleted: true)) expect(message).not_to be_valid expect(message.recipient).to be_nil end end
#!/bin/bash # This script installs mongodb apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list apt-get update apt-get install -y mongodb-org #Wait for mongodb initialization while [[ ! -d "/var/lib/mongodb/_tmp" ]]; do echo "Waiting for mongodb initialization ..." sleep 5 done
unit Anon.Interfaces; interface uses System.SysUtils, Data.DB; type TParameters = record FileName: string; Password: string; end; TDatabaseConfig = record Engine: string; ConnectionString: string; UserName: string; Password: string; AutoCreateDatabase: Boolean; end; TLogLevel = (lError, lWarning, lInfo, lDebug); IUserInterface = interface ['{44C93849-EF14-4695-A045-5F8F29452F2B}'] procedure Run; end; ILogger = interface ['{118A7D52-FFC4-4F11-8215-458A0F4C8CE3}'] procedure Log(LogLevel: TLogLevel; const AMessage: string); end; IAnonimizer = interface ['{F4535069-590C-40FC-96C0-9F97504EB118}'] procedure Anonimize(const Params: TParameters); end; IConnection = interface ['{FACCB00F-98BE-436F-9F25-C969DAE9EB4F}'] procedure Connect(DatabaseConfig: TDatabaseConfig); procedure FetchTable(const TableName: string; AProc: TProc<TDataSet>); end; IGenerator = interface ['{A6F43EAC-2023-4453-87B3-2F4EB8DE34C3}'] procedure SetParams(const Params: TArray<string>); function GenerateValue: Variant; end; implementation end.
# https://practice.geeksforgeeks.org/problems/sequence-of-sequence1155/1 # Recusive calls # start with 1 # find a greatest 1,2,4,8...k (k<=m), count = 1 # revert back to last 2^p and increase it by 1 and try to find a string again # if not possible return # if there it count +=1, repeate step 3 class Solution: def noSeqRec(self, arr, m, n): if len(arr)==n and arr[len(arr)-1] <= m: return m-arr[len(arr)-1]+1 elif len(arr)==n: return 0 count = 0 if len(arr) < n: count_local = self.noSeqRec(arr+[arr[len(arr)-1]*2], m, n) count+=count_local while count_local != 0: arr[len(arr)-1]+=1 count_local = self.noSeqRec(arr+[arr[len(arr)-1]*2], m, n) count+=count_local return count def numberSequence(self, m, n): return self.noSeqRec([1], m, n) if __name__ == '__main__': t = int(input()) for _ in range (t): arr = input().split() m = int(arr[0]) n = int(arr[1]) ob = Solution() print(ob.numberSequence(m, n))
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Linq; using System.Linq.Expressions; using Xunit; namespace Tests.ExpressionCompiler.New { public static unsafe class NewTests { #region Test methods [Fact] public static void CheckNewCustomTest() { Expression<Func<C>> e = Expression.Lambda<Func<C>>( Expression.New(typeof(C)), Enumerable.Empty<ParameterExpression>()); Func<C> f = e.Compile(); Assert.Equal(new C(), f()); } [Fact] public static void CheckNewEnumTest() { Expression<Func<E>> e = Expression.Lambda<Func<E>>( Expression.New(typeof(E)), Enumerable.Empty<ParameterExpression>()); Func<E> f = e.Compile(); Assert.Equal(new E(), f()); } [Fact] public static void CheckNewNullableEnumTest() { Expression<Func<E?>> e = Expression.Lambda<Func<E?>>( Expression.New(typeof(E?)), Enumerable.Empty<ParameterExpression>()); Func<E?> f = e.Compile(); Assert.Equal(new E?(), f()); } [Fact] public static void CheckNewNullableIntTest() { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.New(typeof(int?)), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(); Assert.Equal(new int?(), f()); } [Fact] public static void CheckNewStructTest() { Expression<Func<S>> e = Expression.Lambda<Func<S>>( Expression.New(typeof(S)), Enumerable.Empty<ParameterExpression>()); Func<S> f = e.Compile(); Assert.Equal(new S(), f()); } [Fact] public static void CheckNewNullableStructTest() { Expression<Func<S?>> e = Expression.Lambda<Func<S?>>( Expression.New(typeof(S?)), Enumerable.Empty<ParameterExpression>()); Func<S?> f = e.Compile(); Assert.Equal(new S?(), f()); } [Fact] public static void CheckNewStructWithStringTest() { Expression<Func<Sc>> e = Expression.Lambda<Func<Sc>>( Expression.New(typeof(Sc)), Enumerable.Empty<ParameterExpression>()); Func<Sc> f = e.Compile(); Assert.Equal(new Sc(), f()); } [Fact] public static void CheckNewNullableStructWithStringTest() { Expression<Func<Sc?>> e = Expression.Lambda<Func<Sc?>>( Expression.New(typeof(Sc?)), Enumerable.Empty<ParameterExpression>()); Func<Sc?> f = e.Compile(); Assert.Equal(new Sc?(), f()); } [Fact] public static void CheckNewStructWithStringAndFieldTest() { Expression<Func<Scs>> e = Expression.Lambda<Func<Scs>>( Expression.New(typeof(Scs)), Enumerable.Empty<ParameterExpression>()); Func<Scs> f = e.Compile(); Assert.Equal(new Scs(), f()); } [Fact] public static void CheckNewNullableStructWithStringAndFieldTest() { Expression<Func<Scs?>> e = Expression.Lambda<Func<Scs?>>( Expression.New(typeof(Scs?)), Enumerable.Empty<ParameterExpression>()); Func<Scs?> f = e.Compile(); Assert.Equal(new Scs?(), f()); } [Fact] public static void CheckNewStructWithTwoValuesTest() { Expression<Func<Sp>> e = Expression.Lambda<Func<Sp>>( Expression.New(typeof(Sp)), Enumerable.Empty<ParameterExpression>()); Func<Sp> f = e.Compile(); Assert.Equal(new Sp(), f()); } [Fact] public static void CheckNewNullableStructWithTwoValuesTest() { Expression<Func<Sp?>> e = Expression.Lambda<Func<Sp?>>( Expression.New(typeof(Sp?)), Enumerable.Empty<ParameterExpression>()); Func<Sp?> f = e.Compile(); Assert.Equal(new Sp?(), f()); } [Fact] public static void CheckNewGenericWithStructRestrictionWithEnumTest() { CheckNewGenericWithStructRestrictionHelper<E>(); } [Fact] public static void CheckNewGenericWithStructRestrictionWithStructTest() { CheckNewGenericWithStructRestrictionHelper<S>(); } [Fact] public static void CheckNewGenericWithStructRestrictionWithStructWithStringAndFieldTest() { CheckNewGenericWithStructRestrictionHelper<Scs>(); } [Fact] public static void CheckNewNullableGenericWithStructRestrictionWithEnumTest() { CheckNewNullableGenericWithStructRestrictionHelper<E>(); } [Fact] public static void CheckNewNullableGenericWithStructRestrictionWithStructTest() { CheckNewNullableGenericWithStructRestrictionHelper<S>(); } [Fact] public static void CheckNewNullableGenericWithStructRestrictionWithStructWithStringAndFieldTest() { CheckNewNullableGenericWithStructRestrictionHelper<Scs>(); } #endregion #region Generic helpers private static void CheckNewGenericWithStructRestrictionHelper<Ts>() where Ts : struct { Expression<Func<Ts>> e = Expression.Lambda<Func<Ts>>( Expression.New(typeof(Ts)), Enumerable.Empty<ParameterExpression>()); Func<Ts> f = e.Compile(); Assert.Equal(new Ts(), f()); } private static void CheckNewNullableGenericWithStructRestrictionHelper<Ts>() where Ts : struct { Expression<Func<Ts?>> e = Expression.Lambda<Func<Ts?>>( Expression.New(typeof(Ts?)), Enumerable.Empty<ParameterExpression>()); Func<Ts?> f = e.Compile(); Assert.Equal(new Ts?(), f()); } #endregion } }
<?php /** * Created by PhpStorm. * User: david * Date: 23/01/15 * Time: 20:42 */ class CountryController extends Controller { private $countryFolder = "country/"; /** @var CountryService $countryService */ private $countryService; function __construct(CountryService $countryService) { $this->countryService = $countryService; } public function getCountries(){ return array_map(function($item){ $adapter = new CountryToJsonAdapter($item); return $adapter->mapToJson(); }, $this->countryService->getCountries()->all()); } public function editCountry() { $id = Input::get('pk'); $name = Input::get('value'); $this->countryService->editCountryName($id, $name); } public function deleteCountry() { $this->countryService->deleteCountry(Input::get('countryId')); } public function mergeCountries() { $this->countryService->mergeCountries(Input::get('country1_id'), Input::get('country2_id')); } }
import { SFCWithInstall } from '@vue-cesium/utils/types' import { App } from 'vue' import Entity from './src' Entity.install = (app: App): void => { app.component(Entity.name, Entity) } const _Entity = Entity as SFCWithInstall<typeof Entity> export default _Entity export const VcEntity = _Entity
#!/bin/bash #This is an example script which launches a cluster, moniters the #execution of the cluster, and collects resources, and cleans up #afterwards. cluster=../control/master/ClusterControl.sh #server parameters threshold=0.01 samplerate=1 #curator parameters curatorname="CuratorCerf" model="models" minClients=25 #client parameters dataset="credit" clientcount=25 latency=0 goodpercent=100 tor=true servername=198.162.52.147 onionservice="33bwoexeu3sjrxoe.onion" diffpriv=0.5 #TODO launch TOR first $cluster "kill" #$cluster "pull" $cluster "server" $threshold $samplerate #give the server time to warm up sleep 5 $cluster "curator" $curatorname $model $minClients #give the curator time to commit its model sleep 5 $cluster "clients" $model $dataset $clientcount $latency $goodpercent $tor $servername $onionservice $diffpriv sleep 120 $cluster "kill" $cluster "getpings" #TODO graph a dule cdf with the two ping sets
class Campaign::Entrance attr_accessor :location_name, :index, :displayed_title def initialize(location_name, index = nil, displayed_title = nil) @location_name = location_name raise StandardError, "Empty location name." if @location_name.blank? @index = index @displayed_title = displayed_title end end
import App from "next/app"; import { AppProps } from "next/app"; import Page from "../components/Page"; import i18n from "../i18n.js"; import * as React from "react"; import {useRouter} from 'next/router' function MyApp({ Component, pageProps }: AppProps) { const router = useRouter(); // Apply language based on NextJS internationalized route i18n.changeLanguage(router.locale); return ( <Page> <Component {...pageProps} /> </Page> ) } MyApp.getInitialProps = async (appContext) => { const appProps = await App.getInitialProps(appContext); return { ...appProps }; }; export default MyApp;
PLAYER_COLOR = $2A PLAYER_BITMAP = $80 MAC SETUP LDA #$00 STA NUSIZ0 LDA #PLAYER_COLOR STA COLUP0 LDA #PLAYER_BITMAP STA GRP0 ENDM MAC RESP_SPRITE STA RESP0 ENDM INCLUDE main.inc
#! /bin/bash cd /home/harrison/dev/harrisonschultz.github.io # cp -r ../idle_rpg ./ # git add idle_rpg/ # git commit -m 'new idle_rpg build' # git push origin master
export const state = { currentPage: "home", pageTitle: "Home" }
import { Router } from "express"; import controller from "./course.controller"; import { sendResults } from "../../utils/crud"; const router = Router(); router.delete("/:id", controller.removeOne); router.get("/", controller.getMany); router.get("/:id", controller.getOne); router.post("/", controller.createOne); router.put("/:id", controller.updateOne); router.use(sendResults); export default router;
// $Id$ # ifndef CPPAD_LOCAL_ASINH_HPP # define CPPAD_LOCAL_ASINH_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-16 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Eclipse Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- $begin asinh$$ $spell asinh const Vec std cmath CppAD $$ $section The Inverse Hyperbolic Sine Function: asinh$$ $head Syntax$$ $icode%y% = asinh(%x%)%$$ $head Description$$ The inverse hyperbolic sine function is defined by $icode%x% == sinh(%y%)%$$. $head x, y$$ See the $cref/possible types/unary_standard_math/Possible Types/$$ for a unary standard math function. $head CPPAD_USE_CPLUSPLUS_2011$$ $subhead true$$ If this preprocessor symbol is true ($code 1$$), and $icode x$$ is an AD type, this is an $cref/atomic operation/glossary/Operation/Atomic/$$. $subhead false$$ If this preprocessor symbol is false ($code 0$$), CppAD uses the representation $latex \[ \R{asinh} (x) = \log \left( x + \sqrt{ 1 + x^2 } \right) \] $$ to compute this function. $head Example$$ $children% example/asinh.cpp %$$ The file $cref asinh.cpp$$ contains an example and test of this function. It returns true if it succeeds and false otherwise. $end ------------------------------------------------------------------------------- */ # include <cppad/configure.hpp> # if ! CPPAD_USE_CPLUSPLUS_2011 // BEGIN CppAD namespace namespace CppAD { template <class Type> Type asinh_template(const Type &x) { return CppAD::log( x + CppAD::sqrt( Type(1) + x * x ) ); } inline float asinh(const float &x) { return asinh_template(x); } inline double asinh(const double &x) { return asinh_template(x); } template <class Base> inline AD<Base> asinh(const AD<Base> &x) { return asinh_template(x); } template <class Base> inline AD<Base> asinh(const VecAD_reference<Base> &x) { return asinh_template( x.ADBase() ); } } // END CppAD namespace # endif // CPPAD_USE_CPLUSPLUS_2011 # endif // CPPAD_ASINH_INCLUDED
package com.ansere.mobile.wifidirect import android.util.Log import java.lang.Math.toDegrees import java.util.EnumSet.range import kotlin.math.atan2 import kotlin.math.hypot import kotlin.math.max import kotlin.math.min data class BlueDotPosition(private val _x: Double, private val _y: Double){ val x: Float get() = this.clamped(_x.toFloat()) val y: Float get() = this.clamped(_y.toFloat()) val angle: Double get(){ return toDegrees(atan2(this.x, this.y).toDouble()) } val distance: Double get() = this.clamped(hypot(this.x,this.y)).toDouble() private fun clamped(v: Float): Float{ return max(-1.0, min(1.0,v.toDouble())).toFloat() } fun pos(): String { when{ (this.distance <= 0.5) -> return "middle" (this.distance > 0.5 ) -> when{ ((this.angle > -135.0) && (this.angle <= -45.0)) -> return "left" (this.angle > -45.0) && (this.angle <= 45.0) -> return "top" ((this.angle > 45.0) && (this.angle <= 135.0)) -> return "right" ((this.angle > 135.0) || (this.angle <= -135.0)) -> return "bottom" } } return "UNKNOWN 2" } }
package typingsSlinky.antvEventEmitter import typingsSlinky.std.Record import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object mod { @JSImport("@antv/event-emitter", JSImport.Default) @js.native class default () extends EventEmitter @js.native trait EventEmitter extends StObject { var _events: js.Any = js.native /** * 触发一个事件 * @param evt * @param args */ def emit(evt: String, args: js.Any*): Unit = js.native def getEvents(): Record[String, js.Array[EventType]] = js.native /** * 取消监听一个事件,或者一个channel * @param evt * @param callback */ def off(): this.type = js.native def off(evt: js.UndefOr[scala.Nothing], callback: js.Function): this.type = js.native def off(evt: String): this.type = js.native def off(evt: String, callback: js.Function): this.type = js.native /** * 监听一个事件 * @param evt * @param callback * @param once */ def on(evt: String, callback: js.Function): this.type = js.native def on(evt: String, callback: js.Function, once: Boolean): this.type = js.native /** * 监听一个事件一次 * @param evt * @param callback */ def once(evt: String, callback: js.Function): this.type = js.native } @js.native trait EventType extends StObject { val callback: js.Function = js.native val once: Boolean = js.native } object EventType { @scala.inline def apply(callback: js.Function, once: Boolean): EventType = { val __obj = js.Dynamic.literal(callback = callback.asInstanceOf[js.Any], once = once.asInstanceOf[js.Any]) __obj.asInstanceOf[EventType] } @scala.inline implicit class EventTypeMutableBuilder[Self <: EventType] (val x: Self) extends AnyVal { @scala.inline def setCallback(value: js.Function): Self = StObject.set(x, "callback", value.asInstanceOf[js.Any]) @scala.inline def setOnce(value: Boolean): Self = StObject.set(x, "once", value.asInstanceOf[js.Any]) } } }
(function(){ "use strict"; var Util = require("../modules/util"); function Synchronizer(world) { this.world = world; this.cmd = this.world.proto.PkgCmd; this.err = this.world.proto.ErrCode; } Synchronizer.prototype = { constructor: Synchronizer, }; Synchronizer.prototype.sendPkg = function(socket, body, cmd, result) { var pkg = new this.world.proto.Pkg(); pkg.frame = this.world.frame; pkg.cmd = cmd; if (result) { pkg.result = result; } switch (cmd) { case this.cmd.SYNC_START_REQ: pkg.syncStartReq = body; break; case this.cmd.SYNC_START_RES: pkg.syncStartRes = body; break; case this.cmd.SYNC_COMMANDERS: pkg.syncCommanders = body; break; default: Util.logError("invalid cmd=" + cmd); return; } if (socket) { socket.emit('pkg', pkg.encode().toArrayBuffer()); Util.logTrace("send message cmd=" + pkg.cmd); } }; Synchronizer.prototype.syncStartReq = function(name) { var req = new this.world.proto.SyncStartReq(); req.name = name; this.sendPkg(this.world.socket, req, this.cmd.SYNC_START_REQ); }; Synchronizer.prototype.syncStartRes = function(socket, result, connid) { var res = new this.world.proto.SyncStartRes(); res.connid = connid; res.unitBaseId = this.world.unitBaseId; if (result == this.err.SUCCESS) { res.units = []; this.world.dumpUnits(res.units); res.unitsToAdd = []; this.world.dumpUnitsToAdd(res.unitsToAdd); res.players = []; this.world.dumpPlayers(res.players); } this.sendPkg(socket, res, this.cmd.SYNC_START_RES, result); }; Synchronizer.prototype.syncReborn = function(name) { var commander = new this.world.proto.SyncCommander(); commander.cmd = this.world.proto.CommanderType.CT_REBORN; commander.reborn = new this.world.proto.SyncCommander.Reborn(); commander.reborn.name = name; var commanders = []; commanders.push(commander); this.sendPkg(this.world.socket, commanders, this.cmd.SYNC_COMMANDERS); }; Synchronizer.prototype.syncMove = function(angle, force) { var commander = new this.world.proto.SyncCommander(); commander.cmd = this.world.proto.CommanderType.CT_MOVE; commander.move = new this.world.proto.SyncCommander.Move(); commander.move.angle = angle; commander.move.force = force; var commanders = []; commanders.push(commander); this.sendPkg(this.world.socket, commanders, this.cmd.SYNC_COMMANDERS); }; Synchronizer.prototype.syncRotate = function(angle) { var commander = new this.world.proto.SyncCommander(); commander.cmd = this.world.proto.CommanderType.CT_ROTATE; commander.rotate = new this.world.proto.SyncCommander.Rotate(); commander.rotate.angle = angle; var commanders = []; commanders.push(commander); this.sendPkg(this.world.socket, commanders, this.cmd.SYNC_COMMANDERS); }; Synchronizer.prototype.syncFire = function() { var commander = new this.world.proto.SyncCommander(); commander.cmd = this.world.proto.CommanderType.CT_FIRE; var commanders = []; commanders.push(commander); this.sendPkg(this.world.socket, commanders, this.cmd.SYNC_COMMANDERS); }; Synchronizer.prototype.syncAddProp = function(propType) { var commander = new this.world.proto.SyncCommander(); commander.cmd = this.world.proto.CommanderType.CT_ADD_PROP; commander.addProp = new this.world.proto.SyncCommander.AddProp(); commander.addProp.propType = propType; var commanders = []; commanders.push(commander); this.sendPkg(this.world.socket, commanders, this.cmd.SYNC_COMMANDERS); }; Synchronizer.prototype.syncCommanders = function(commanders) { this.sendPkg(this.world.socket, commanders, this.cmd.SYNC_COMMANDERS); }; module.exports = Synchronizer; })();
--- layout: post microblog: true date: 2017-06-18 01:09 +0300 guid: http://desparoz.micro.blog/2017/06/17/t876200189907922945.html --- Something I like: Attention Required! | Cloudflare… An interesting look into just how much data can be ... [t.co/TzOvI2j10...](https://t.co/TzOvI2j10S)
%% %% %CopyrightBegin% %% %% Copyright Ericsson AB 2003-2012. All Rights Reserved. %% %% The contents of this file are subject to the Erlang Public License, %% Version 1.1, (the "License"); you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at http://www.erlang.org/. %% %% Software distributed under the License is distributed on an "AS IS" %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %% %%%---------------------------------------------------------------------- %%% Purpose : Test suite for the backends of the IDL compiler %%%---------------------------------------------------------------------- -module(java_client_erl_server_SUITE). -include_lib("test_server/include/test_server.hrl"). -export([all/0, suite/0,groups/0,init_per_group/2,end_per_group/2, init_per_suite/1,end_per_suite/1, init_per_testcase/2,end_per_testcase/2]). -export([marshal_ll/1,marshal_ull/1, marshal_l/1,marshal_ul/1, marshal_s/1,marshal_us/1, marshal_c/1,marshal_wc/1, marshal_str/1, marshal_any_3/1,marshal_any_2/1]). %% Top of cases suite() -> [{ct_hooks,[ts_install_cth]}]. all() -> cases(). groups() -> []. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. cases() -> [marshal_ll, marshal_ull, marshal_l, marshal_ul, marshal_s, marshal_us, marshal_c, marshal_wc, marshal_str, marshal_any_3, marshal_any_2]. init_per_suite(Config) when is_list(Config) -> case case code:priv_dir(jinterface) of {error,bad_name} -> false; P -> case filelib:wildcard(filename:join(P, "*.jar")) of [_|_] -> true; [] -> false end end of true -> case find_executable(["java"]) of false -> {skip,"Found no Java VM"}; Path -> [{java,Path}|Config] end; false -> {skip,"No jinterface application"} end. find_executable([]) -> false; find_executable([E|T]) -> case os:find_executable(E) of false -> find_executable(T); Path -> Path end. end_per_suite(Config) -> Config. %% Add/remove code path and watchdog before/after each test case. %% init_per_testcase(_Case, Config) -> DataDir = ?config(data_dir, Config), code:add_patha(DataDir), %% Since other test suites use the module m_i et,al, we have %% to make sure we are using the right modules. code:purge(m_i), code:purge(m_i_impl), code:purge(oe_java_erl_test), code:load_file(m_i), code:load_file(m_i_impl), code:load_file(oe_java_erl_test), WatchDog = test_server:timetrap(test_server:seconds(20)), [{watchdog, WatchDog}| Config]. end_per_testcase(_Case, Config) -> DataDir = ?config(data_dir, Config), code:del_path(DataDir), WatchDog = ?config(watchdog, Config), test_server:timetrap_cancel(WatchDog). %%-------------------------------------------------------------------- %% %% Test cases marshal_ll(doc) -> ["Testing marshalling of IDL long long"]; marshal_ll(suite) -> []; marshal_ll(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_ll}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_ll]), ?line ok = m_i:stop(Server), ok. marshal_ull(doc) -> ["Testing marshalling of IDL unsigned long long"]; marshal_ull(suite) -> []; marshal_ull(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_ull}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_ull]), ?line ok = m_i:stop(Server), ok. marshal_l(doc) -> ["Testing marshalling of IDL long"]; marshal_l(suite) -> []; marshal_l(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_l}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_l]), ?line ok = m_i:stop(Server), ok. marshal_ul(doc) -> ["Testing marshalling of IDL unsigned long"]; marshal_ul(suite) -> []; marshal_ul(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_ul}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_ul]), ?line ok = m_i:stop(Server), ok. marshal_s(doc) -> ["Testing marshalling of IDL short"]; marshal_s(suite) -> []; marshal_s(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_s}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_s]), ?line ok = m_i:stop(Server), ok. marshal_us(doc) -> ["Testing marshalling of IDL unsigned short"]; marshal_us(suite) -> []; marshal_us(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_us}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_us]), ?line ok = m_i:stop(Server), ok. marshal_c(doc) -> ["Testing marshalling of IDL char"]; marshal_c(suite) -> []; marshal_c(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_c}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_c]), ?line ok = m_i:stop(Server), ok. marshal_wc(doc) -> ["Testing marshalling of IDL char"]; marshal_wc(suite) -> []; marshal_wc(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_wc}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_wc]), ?line ok = m_i:stop(Server), ok. marshal_str(doc) -> ["Testing marshalling of IDL string"]; marshal_str(suite) -> []; marshal_str(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_str}), ?line ok = java(?config(java, Config), DataDir, %%% "-DOtpConnection.trace=4 " "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_str]), ?line ok = m_i:stop(Server), ok. marshal_any_3(doc) -> ["Testing marshalling of IDL any"]; marshal_any_3(suite) -> []; marshal_any_3(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_any_3}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_any_3]), ?line ok = m_i:stop(Server), ok. marshal_any_2(doc) -> ["Testing marshalling of IDL any"]; marshal_any_2(suite) -> []; marshal_any_2(Config) when is_list(Config) -> ?line DataDir = ?config(data_dir, Config), ?line {ok,Server} = m_i:oe_create_link([], {local,marshal_any_2}), ?line ok = java(?config(java, Config), DataDir, "JavaClient", ["JavaClient",node(),erlang:get_cookie(),marshal_any_2]), ?line ok = m_i:stop(Server), ok. %%-------------------------------------------------------------------- %% %% Utilities java(Java, Dir, ClassAndArgs) -> cmd(Java++" -classpath \""++classpath(Dir)++"\" "++ClassAndArgs). java(Java, Dir, Class, Args) -> java(Java, Dir, Class++" "++to_string(Args)). to_string([H|T]) when is_integer(H) -> integer_to_list(H)++" "++to_string(T); to_string([H|T]) when is_atom(H) -> atom_to_list(H)++" "++to_string(T); to_string([H|T]) when is_list(H) -> lists:flatten(H)++" "++to_string(T); to_string([]) -> []. % javac(Dir, File) -> % cmd("javac -d "++Dir++" -classpath "++classpath(Dir)++" "++ % filename:join(Dir, File)). classpath(Dir) -> PS = case os:type() of {win32, _} -> ";"; _ -> ":" end, Dir++PS++ filename:join([code:lib_dir(ic),"priv","ic.jar"])++PS++ filename:join([code:lib_dir(jinterface),"priv","OtpErlang.jar"])++PS++ case os:getenv("CLASSPATH") of false -> ""; Classpath -> Classpath end. cmd(Cmd) -> PortOpts = [{line,80},eof,exit_status,stderr_to_stdout], io:format("<cmd> ~s~n", [Cmd]), case catch open_port({spawn,Cmd}, PortOpts) of Port when is_port(Port) -> Result = cmd_loop(Port, []), io:format("<cmd=~w>~n", [Result]), case Result of 0 -> ok; ExitCode when is_integer(ExitCode) -> {error,ExitCode}; Error -> Error end; {'EXIT',Reason} -> {error,Reason} end. cmd_loop(Port, Line) -> receive {Port,eof} -> receive {Port,{exit_status,ExitStatus}} -> ExitStatus after 1 -> undefined end; {Port,{exit_status,ExitStatus}} -> receive {Port,eof} -> ok after 1 -> ok end, ExitStatus; {Port,{data,{Tag,Data}}} -> case Tag of eol -> io:put_chars([Line|cr_to_nl(Data)]), io:nl(), cmd_loop(Port, []); noeol -> cmd_loop(Port, [Line|cr_to_nl(Data)]) end; {'EXIT',Port,Reason} -> {error,Reason}; Other -> io:format("WARNING: Unexpected at ~s:~p: ~p~n", [?MODULE_STRING,?LINE,Other]), cmd_loop(Port, Line) end. %% Convert lonely CR to NL, and CRLF to NL %% cr_to_nl([$\r,$\n|T]) -> [$\n|cr_to_nl(T)]; cr_to_nl([$\r|T]) -> [$\n|cr_to_nl(T)]; cr_to_nl([C|T]) -> [C|cr_to_nl(T)]; cr_to_nl([]) -> [].
: <<'END' Copyright 2021 Rabia Research Team and Developers 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. END # install.sh installs Rabia and copies a SSH public key to a fresh VM so that the benchmark controller server # could use Shell scripts to control this VM. # Remove the corresponding function calls at the bottom if Rabia is not installed on a fresh machine. # OS assumption: Ubuntu 16.04, Ubuntu 18.04 # Root access are required for some operations during installation, see commands prefixed with "sudo." # However, Rabia does not need to go to /root/go/src, instead, it can sits inside some non-root user's ~/go/src folder # Rabia runs does not require the root access rabia_folder=~/go/src/rabia # the path to the Rabia folder redis_folder=~ # the path where Redis is installed go_tar=go1.15.8.linux-amd64.tar.gz # the version of Golang to be downloaded in install_go py_ver=python3.8 # the version of Python to be downloaded in install_python redis_ver=redis-6.2.2 # Copies the SSH public key to the "authorized_keys" file so that the benchmark controller could control this VM function install_key() { mkdir -p ~/.ssh/ cat "${rabia_folder}"/deployment/install/id_rsa.pub >>~/.ssh/authorized_keys chmod 400 "${rabia_folder}"/deployment/install/id_rsa } # Installs a version of Python, which is used by the analysis program function install_python() { sudo apt update sudo apt install -y gcc sudo apt install -y software-properties-common sudo add-apt-repository -y ppa:deadsnakes/ppa sudo apt update sudo apt install -y ${py_ver} ${py_ver} --version } # Installs a version of Golang since Rabia is written in Golang function install_go() { wget -q https://golang.org/dl/${go_tar} sudo tar -C /usr/local -xzf ${go_tar} rm ${go_tar} echo 'export PATH=${PATH}:/usr/local/go/bin' >>~/.bashrc echo 'export GOPATH=~/go' >>~/.bashrc echo 'export GO111MODULE="auto"' >>~/.bashrc source ~/.bashrc go version } # Installs pip and numpy for python3. Used for non-pipelined Paxos and EPaxos testing. function install_numpy() { sudo apt install -y python3.8-distutils wget https://bootstrap.pypa.io/get-pip.py sudo python3.8 get-pip.py pip install numpy } # Installs some Golang packages used by Rabia function install_go_deps() { go get -u github.com/gogo/protobuf/gogoproto # gogo-protobuf go get -u google.golang.org/protobuf/cmd/protoc-gen-go # vanilla protobuf go get -u github.com/rs/zerolog/log go get -u github.com/go-redis/redis/v8 } function install_redis() { cd ${redis_folder} sudo apt install -y tar make wget https://download.redis.io/releases/${redis_ver}.tar.gz tar xzf ${redis_ver}.tar.gz rm ${redis_ver}.tar.gz cd ${redis_ver} make cd ~/go/src/rabia/deployment } install_key install_python #install_numpy # install_go install_go_deps # install_redis
package com.thomaskioko.paybillmanager.mobile.util object StringUtils { fun upperCaseFirstLetter(value: String): String { val array = value.toCharArray() array[0] = Character.toUpperCase(array[0]) for (i in 1 until array.size) { if (Character.isWhitespace(array[i - 1])) { array[i] = Character.toLowerCase(array[i]) } } return String(array) } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mc_compiled.Modding.Behaviors { /// <summary> /// A subject to run an event on. /// </summary> public enum EventSubject { /// <summary> /// The block involved with the interaction. /// </summary> block, /// <summary> /// The damaging actor involved with the interaction. /// </summary> damager, /// <summary> /// The other member of an interaction, not the caller. /// </summary> other, /// <summary> /// The caller's current parent. /// </summary> parent, /// <summary> /// The player involved with the interaction. /// </summary> player, /// <summary> /// The entity or object calling the test. /// </summary> self, /// <summary> /// The caller's current target. /// </summary> target } }
# frozen_string_literal: true require 'active_support/core_ext/string' RSpec.shared_examples 'command' do let(:test) do test = [] var = command.new(cmd).instance_variable_get(:@command) cmd.each_with_index do |_value, index| test << var[index].split('=').last end test end let(:to) do to = [] cmd.each { |value| to << value.last } to end it { expect(test).to eql(to) } end RSpec.shared_examples 'command raise' do let(:cmd) { { argument => arg_value } } it do expect { command.new(cmd) }.to \ raise_error(Evostream::Commands::Errors::MissingMandatory) end end
import { expect } from '../../../setup' /* External Imports */ import { ethers } from 'hardhat' import { Contract, BigNumber } from 'ethers' import { MerkleTree } from 'merkletreejs' import { fromHexString, toHexString } from '@eth-optimism/core-utils' /* Internal Imports */ import { NON_NULL_BYTES32 } from '../../../helpers' const NODE_COUNTS = [ 2, 3, 7, 9, 13, 63, 64, 123, 128, 129, 255, 1021, 1023, 1024, ] const hash = (el: Buffer | string): Buffer => { return Buffer.from(ethers.utils.keccak256(el).slice(2), 'hex') } const fillDefaultHashes = (elements: string[]): string[] => { const filled: string[] = [] for (let i = 0; i < Math.pow(2, Math.ceil(Math.log2(elements.length))); i++) { if (i < elements.length) { filled.push(elements[i]) } else { filled.push(ethers.utils.keccak256('0x' + '00'.repeat(32))) } } return filled } describe('Lib_MerkleTree', () => { let Lib_MerkleTree: Contract before(async () => { Lib_MerkleTree = await ( await ethers.getContractFactory('TestLib_MerkleTree') ).deploy() }) describe('getMerkleRoot', () => { describe('when no elements are provided', () => { const elements = [] it('should revert', async () => { await expect(Lib_MerkleTree.getMerkleRoot(elements)).to.be.revertedWith( 'Lib_MerkleTree: Must provide at least one leaf hash.' ) }) }) describe('when a single element is provided', () => { const elements = [ethers.utils.keccak256('0x1234')] it('should return the input element', async () => { expect(await Lib_MerkleTree.getMerkleRoot(elements)).to.equal( elements[0] ) }) }) describe('when more than one element is provided', () => { for (const size of NODE_COUNTS) { it(`should generate the correct root when ${size} elements are provided`, async () => { const elements = [...Array(size)].map((_, i) => { return ethers.utils.keccak256(BigNumber.from(i).toHexString()) }) const bufs = fillDefaultHashes(elements).map((element) => { return fromHexString(element) }) const tree = new MerkleTree(bufs, hash) expect(await Lib_MerkleTree.getMerkleRoot(bufs)).to.equal( toHexString(tree.getRoot()) ) }) } }) }) describe('verify', () => { describe('when total elements is zero', () => { const totalLeaves = 0 it('should revert', async () => { await expect( Lib_MerkleTree.verify( ethers.constants.HashZero, ethers.constants.HashZero, 0, [], totalLeaves ) ).to.be.revertedWith( 'Lib_MerkleTree: Total leaves must be greater than zero.' ) }) }) describe('when an index is out of bounds', () => { const totalLeaves = 1 const index = 2 it('should revert', async () => { await expect( Lib_MerkleTree.verify( ethers.constants.HashZero, ethers.constants.HashZero, index, [], totalLeaves ) ).to.be.revertedWith('Lib_MerkleTree: Index out of bounds.') }) }) describe('when total siblings does not match provided total leaves', () => { const totalLeaves = 8 const siblings = [ethers.constants.HashZero, ethers.constants.HashZero] it('should revert', async () => { await expect( Lib_MerkleTree.verify( ethers.constants.HashZero, ethers.constants.HashZero, 0, siblings, totalLeaves ) ).to.be.revertedWith( 'Lib_MerkleTree: Total siblings does not correctly correspond to total leaves.' ) }) }) describe('with valid proof for a single element', () => { const root = NON_NULL_BYTES32 const leaf = NON_NULL_BYTES32 const index = 0 const siblings = [] const totalLeaves = 1 it('should succeed', async () => { expect( await Lib_MerkleTree.verify(root, leaf, index, siblings, totalLeaves) ).to.equal(true) }) }) describe('with valid proof for more than one element', () => { for (const size of NODE_COUNTS) { describe(`for a tree with ${size} total elements`, () => { const elements = [...Array(size)].map((_, i) => { return ethers.utils.keccak256(BigNumber.from(i).toHexString()) }) const bufs = fillDefaultHashes(elements).map((element) => { return fromHexString(element) }) const tree = new MerkleTree(bufs, hash) for (let i = 0; i < size; i += Math.ceil(size / 8)) { it(`should verify a proof for the ${i}(th/st/rd, whatever) element`, async () => { const proof = tree.getProof(bufs[i], i).map((element) => { return element.data }) expect( await Lib_MerkleTree.verify( tree.getRoot(), bufs[i], i, proof, size ) ).to.equal(true) }) } }) } }) }) })
module JwPlayerOnRails module ViewHelper # This counter is used to generated unique IDs @@player_count = 0 # This module contains the view helper <tt>jw_player</tt> def jw_player path, options = {} increment_player_count options.merge!(flashplayer: "/jwplayer/player.swf", file: path) %Q[ <div id="jwplayer_#{@@player_count}">Loading the player...</div> <script type="text/javascript"> //<![CDATA[ jwplayer("jwplayer_#{@@player_count}").setup(#{options.to_json}); //]]> </script> ].html_safe end def increment_player_count @@player_count += 1 end def self.reset_player_count @@player_count = 0 end end end
#include <bindings.dsl.h> #include "cvsu_pixel_image.h" module CVSU.Bindings.PixelImage where #strict_import import CVSU.Bindings.Types import Foreign.C.String import Foreign.Ptr #starttype pixel_image #field parent , Ptr <pixel_image> #field data , Ptr () #field rows , Ptr Word8 #field type , <pixel_type> #field format , <pixel_format> #field dx , CULong #field dy , CULong #field width , CULong #field height , CULong #field offset , CULong #field step , CULong #field stride , CULong #field size , CULong #stoptype #ccall pixel_image_alloc , IO (Ptr <pixel_image>) #ccall pixel_image_free , Ptr <pixel_image> -> IO () #ccall pixel_image_create , Ptr <pixel_image> -> <pixel_type> \ -> <pixel_format> -> CULong -> CULong -> CULong -> CULong -> IO <result> #ccall pixel_image_create_from_data , Ptr <pixel_image> -> Ptr () \ -> <pixel_type> -> <pixel_format> -> CULong -> CULong -> CULong -> CULong \ -> IO <result> #ccall pixel_image_destroy , Ptr <pixel_image> -> IO <result> #ccall pixel_image_nullify , Ptr <pixel_image> -> IO <result> #ccall pixel_image_is_null , Ptr <pixel_image> -> IO <truth_value> #ccall pixel_image_create_roi , Ptr <pixel_image> -> Ptr <pixel_image> \ -> CULong -> CULong -> CULong -> CULong -> IO <result> #ccall pixel_image_convert , Ptr <pixel_image> -> Ptr <pixel_image> \ -> IO <result> #ccall pixel_image_clear , Ptr <pixel_image> -> IO <result> #ccall pixel_image_read , Ptr <pixel_image> -> CString -> IO <result> #ccall pixel_image_write , Ptr <pixel_image> -> CString -> <truth_value> \ -> IO <result> #ccall pixel_image_find_min_byte , Ptr <pixel_image> -> CLong -> CLong \ -> CLong -> CLong -> CULong -> IO CDouble #ccall pixel_image_find_max_byte , Ptr <pixel_image> -> CLong -> CLong \ -> CLong -> CLong -> CULong -> IO CDouble #ccall pixel_image_calculate_mean_byte , Ptr <pixel_image> -> CLong -> CLong \ -> CLong -> CLong -> CULong -> IO CDouble #ccall pixel_image_calculate_variance_byte , Ptr <pixel_image> -> CLong \ -> CLong -> CLong -> CLong -> CULong -> IO CDouble
package com.vrondakis.zap; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import hudson.model.Run; /** * ZapDriver Controls ZAP using HTTP api * * @see <a href="https://github.com/zaproxy/zaproxy/wiki/ApiDetails">ZAP API Documentation</a> */ public class ZapDriverController { static final String CMD_DAEMON = "-daemon"; static final String CMD_HOST = "-host"; static final String CMD_PORT = "-port"; static final String CMD_DIR = "-dir"; static final String CMD_CONFIG = "-config"; static final String CMD_DISABLEKEY = "api.disablekey=true"; static final String CMD_REGEX = "api.addrs.addr.regex=true"; static final String CMD_NAME = "api.addrs.addr.name=.*"; static final String CMD_TIMEOUT = "connection.timeoutInSecs=600"; static final String CMD_CERTLOAD = "-certload"; static final String ZAP_UNIX_PROGRAM = "zap.sh"; static final String ZAP_WIN_PROGRAM = "zap.bat"; static Class<? extends ZapDriver> zapDriverClass = ZapDriverImpl.class; private static HashMap<String, ZapDriver> zapDrivers = new HashMap<>(); public static ZapDriver getZapDriver(Run run) { ZapDriver driver = zapDrivers.get(run.getUrl()); if (driver != null) { return driver; } System.out.println("zap: Creating new ZAP driver for build URL: " + run.getUrl()); return newDriver(run); } public static <T extends ZapDriver> ZapDriver newDriver(Run run, Class<T> zapDriver) { ZapDriver zDriver; try { zDriver = zapDriver.getDeclaredConstructor().newInstance(); zapDrivers.put(run.getUrl(), zDriver); return zDriver; } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); return null; } } public static ZapDriver newDriver(Run run) { return ZapDriverController.newDriver(run, zapDriverClass); } public static boolean zapDriverExists(Run run) { return zapDrivers.containsKey(run.getUrl()); } public static void shutdownZap(Run run) throws ZapExecutionException { getZapDriver(run).shutdownZap(); if (zapDrivers.get(run.getUrl()) instanceof ZapDriverImpl) { zapDrivers.remove(run.getUrl()); } } // Converts map of parameters to URL parameters static String formatParams(Map<String, String> params) { return params.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining("&")); } public static <T extends ZapDriver> void setZapDriverClass(Class<T> zapDriver) { zapDriverClass = zapDriver; } public static void clearAll() { zapDrivers.clear(); } }
require 'rubygems' require 'bundler/setup' require 'minitest/autorun' require 'minitest/mock' require 'fileutils' require 'pathname' require 'configy' module Configy::TestHelpers def assert_equal_with_hash(config, hash) hash.each do |key, value| assert_equal config.send(key), value end end def with_config_file(conf, file='config') path = file_path(file) File.open(path, 'w') { |f| f.write conf.is_a?(String) ? conf : conf.to_yaml } yield(path, conf) ensure FileUtils.rm path end def file_path(file) File.join(scratch_dir, "#{file}.yml") end def scratch_dir @scratch_dir ||= File.expand_path("../scratch", __FILE__) end def with_const(const, value) Object.const_set const, value yield Object.send :remove_const, const end def with_env(name, value) old = ENV[name] ENV[name] = value yield ENV[name] = old end end class MiniTest::Unit::TestCase include Configy::TestHelpers end
package main import ( "fmt" "github.com/facebookgo/inject" ) type DBEngine struct { Name string } type UserDB struct { Db *DBEngine `inject:""` } type UserService struct { Db *UserDB `inject:""` } type App struct { Name string User *UserService `inject:""` } func (a *App) Create() string { return "create app, in db name:" + a.User.Db.Db.Name + " app name :" + a.Name } type Object struct { App *App } func Init() *Object { db := DBEngine{Name: "db1"} var g inject.Graph app := App{Name: "go-app"} _ = g.Provide( &inject.Object{Value: &app}, &inject.Object{Value: &db}, ) _ = g.Populate() return &Object{ App: &app, } } func main() { obj := Init() fmt.Println(obj.App.Create()) }
/* * Created by Onkar Nene on 17/8/19 3:11 PM * * Copyright (c) 2019 Onkar Nene. All rights reserved. */ package com.onkar.android.gojekdemo.utilities /** * Application constants */ const val EMPTY_STRING = "" const val NA = "N/A" const val AUTHOR = "author" const val NAME = "name" const val AVATAR = "avatar" const val URL = "url" const val DESCRIPTION = "description" const val LANGUAGE = "language" const val LANGUAGE_COLOR = "languageColor" const val STARTS = "stars" const val FORKS = "forks" const val CURRENT_PERIOD_STARS = "currentPeriodStars" const val BUILT_BY = "builtBy" const val USERNAME = "username" const val HREF = "href" const val TABLE_GITHUB_REPO = "github_repo" const val PREF_KEY_DATA_EXPIRE_TIME = "key_data_expire_time"
import 'package:snaxdart/snaxdart.dart'; import 'package:test/test.dart'; void main() { group('SNAX Client', () { SNAXClient client; setUp(() { client = SNAXClient('https://cdn.snax.one', 'v1'); }); test('Get Info', () { client.getInfo().then((NodeInfo nodeInfo) { expect(nodeInfo.headBlockNum > 0, isTrue); }); }); test('Get Abi', () { client.getAbi('snax.token').then((AbiResp abi) { expect(abi.accountName, equals('snax.token')); }); }); test('Get Raw Abi', () { client.getRawAbi('snax.token').then((AbiResp abi) { expect(abi.accountName, equals('snax.token')); expect(abi.codeHash, '01bd013c4f8be142b9cadf511f007c6ac201c068d529f01ed5661803c575befa'); expect(abi.abiHash, 'f8f677996a8ca68388bc41cf55e727949c161b624a47e497e3b2f71a0e635dad'); expect(abi.abi, isNotNull); }); }); test('Get Raw code and Abi', () { client.getRawCodeAndAbi('snax.token').then((AbiResp abi) { expect(abi.accountName, equals('snax.token')); expect(abi.wasm.length > 0, isTrue); expect(abi.abi, isNotNull); }); }); test('Get Block', () { client.getBlock('43743575').then((Block block) { expect(block.blockNum > 0, isTrue); expect(block.producer, 'zbsnaxbp11111'); expect(block.confirmed, 0); expect(block.transactionMRoot, '8fb685526d58dfabd05989b45b8576197acc1be59d753bb396386d5d718f9fa9'); expect(block.transactions.length > 10, isTrue); }); }); test('Get Account', () { client.getAccount('snax.stake').then((Account account) { expect(account.accountName, equals('snax.stake')); expect(account.coreLiquidBalance.amount > 0, isTrue); }); }); test('Get currency balance', () { client .getCurrencyBalance('parslseed123', 'newdexpocket', 'SEED') .then((List<Holding> tokens) { expect(tokens.length > 0, isTrue); expect(tokens[0].amount > 0, isTrue); expect(tokens[0].currency, 'SEED'); }); }); test('Get Transaction', () { client .getTransaction( '8ca0fea82370a2dbbf2c4bd1026bf9fd98a57685bee3672c4ddbbc9be21de984') .then((TransactionBlock transaction) { expect(transaction.blockNum, 43743575); expect(transaction.trx.receipt.cpuUsageUs, 132); expect(transaction.trx.receipt.netUsageWords, 0); expect(transaction.traces.length, 2); expect(transaction.traces[0].receipt.receiver, 'trustdicelog'); expect(transaction.traces[0].inlineTraces.length, 1); expect(transaction.traces[0].inlineTraces[0].receipt.receiver, 'ge4tcnrxgyge'); }); }); }); }
// Magica Cloth. // Copyright (c) MagicaSoft, 2020-2021. // https://magicasoft.jp using System.Collections.Generic; namespace MagicaCloth { public static class DataUtility { /// <summary> /// 2つのインデックスを1つのUint型にパッキングする /// 上位16ビット、下位16ビットにv0/v1番号を結合する /// ただし番号が若いものが上位に来るように配置 /// </summary> /// <param name="v0"></param> /// <param name="v1"></param> /// <returns></returns> public static uint PackPair(int v0, int v1) { if (v0 > v1) { return (uint)v1 << 16 | (uint)v0 & 0xffff; } else { return (uint)v0 << 16 | (uint)v1 & 0xffff; } } /// <summary> /// パックデータを2つの番号(v0/v1)に分離する /// </summary> /// <param name="pack"></param> /// <param name="v0"></param> /// <param name="v1"></param> public static void UnpackPair(uint pack, out int v0, out int v1) { // 辺の頂点分解 v0 = (int)((pack >> 16) & 0xffff); v1 = (int)(pack & 0xffff); } /// <summary> /// 2つのintを1つのuintにパッキングする /// </summary> /// <param name="hi"></param> /// <param name="low"></param> /// <returns></returns> public static uint Pack16(int hi, int low) { return (uint)hi << 16 | (uint)low & 0xffff; } /// <summary> /// uintパックデータから上位16bitをintにして返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack16Hi(uint pack) { return (int)((pack >> 16) & 0xffff); } /// <summary> /// uintパックデータから下位16bitをintにして返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack16Low(uint pack) { return (int)(pack & 0xffff); } /// <summary> /// 2つのintを1つのuintにパッキングする(4bit/28bit) /// </summary> /// <param name="hi"></param> /// <param name="low"></param> /// <returns></returns> public static uint Pack4_28(int hi, int low) { return (uint)hi << 28 | (uint)low & 0xfffffff; } /// <summary> /// uintパックデータから上位4bitをintにして返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack4_28Hi(uint pack) { return (int)((pack >> 28) & 0xf); } /// <summary> /// uintパックデータから下位28bitをintにして返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack4_28Low(uint pack) { return (int)(pack & 0xfffffff); } /// <summary> /// 2つのintを1つのuintにパッキングする(8bit/24bit) /// </summary> /// <param name="hi"></param> /// <param name="low"></param> /// <returns></returns> public static uint Pack8_24(int hi, int low) { return (uint)hi << 24 | (uint)low & 0xffffff; } /// <summary> /// uintパックデータから上位8bitをintにして返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack8_24Hi(uint pack) { return (int)((pack >> 24) & 0xf); } /// <summary> /// uintパックデータから下位24bitをintにして返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack8_24Low(uint pack) { return (int)(pack & 0xffffff); } /// <summary> /// 2つのintを1つのulongにパッキングする /// </summary> /// <param name="hi"></param> /// <param name="low"></param> /// <returns></returns> public static ulong Pack32(int hi, int low) { return (ulong)hi << 32 | (ulong)low & 0xffffffff; } /// <summary> /// ulongパックデータから上位データを返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack32Hi(ulong pack) { return (int)((pack >> 32) & 0xffffffff); } /// <summary> /// ulongパックデータから下位データを返す /// </summary> /// <param name="pack"></param> /// <returns></returns> public static int Unpack32Low(ulong pack) { return (int)(pack & 0xffffffff); } /// <summary> /// 3つのインデックスを1つのulong型にパッキングする /// 番号が若いものが上位に来るように配置 /// ※この関数はジョブシステムでは利用できません /// </summary> /// <param name="v0"></param> /// <param name="v1"></param> /// <param name="v2"></param> /// <returns></returns> public static ulong PackTriple(int v0, int v1, int v2) { List<ulong> indexList = new List<ulong>(); indexList.Add((ulong)v0); indexList.Add((ulong)v1); indexList.Add((ulong)v2); indexList.Sort(); ulong hash = (indexList[0] << 32) | (indexList[1] << 16) | (indexList[2]); return hash; } /// <summary> /// パックデータを3つの番号に分離する /// </summary> /// <param name="pack"></param> /// <param name="v0"></param> /// <param name="v1"></param> /// <param name="v2"></param> public static void UnpackTriple(ulong pack, out int v0, out int v1, out int v2) { v0 = (int)((pack >> 32) & 0xffff); v1 = (int)((pack >> 16) & 0xffff); v2 = (int)(pack & 0xffff); } /// <summary> /// 4つのインデックスを1つのulong型にパッキングする /// 番号が若いものが上位に来るように配置 /// ※この関数はジョブシステムでは利用できません /// </summary> /// <param name="v0"></param> /// <param name="v1"></param> /// <param name="v2"></param> /// <returns></returns> public static ulong PackQuater(int v0, int v1, int v2, int v3) { List<ulong> indexList = new List<ulong>(); indexList.Add((ulong)v0); indexList.Add((ulong)v1); indexList.Add((ulong)v2); indexList.Add((ulong)v3); indexList.Sort(); ulong hash = (indexList[0] << 48) | (indexList[1] << 32) | (indexList[2] << 16) | (indexList[3]); return hash; } /// <summary> /// パックデータを4つの番号に分離する /// </summary> /// <param name="pack"></param> /// <param name="v0"></param> /// <param name="v1"></param> /// <param name="v2"></param> public static void UnpackQuater(ulong pack, out int v0, out int v1, out int v2, out int v3) { v0 = (int)((pack >> 48) & 0xffff); v1 = (int)((pack >> 32) & 0xffff); v2 = (int)((pack >> 16) & 0xffff); v3 = (int)(pack & 0xffff); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.purnama.gui.inner.detail.util; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import javax.swing.JCheckBox; import javax.swing.JPanel; import net.purnama.gui.library.MyLabel; import net.purnama.util.GlobalFields; /** * * @author Purnama */ public class TitlePaymentPanel extends JPanel{ private final JCheckBox jcb; private final JPanel valuepanel; public TitlePaymentPanel(){ super(new FlowLayout(FlowLayout.LEFT)); setMinimumSize(new Dimension(550, 30)); setMaximumSize(new Dimension(550, 30)); setPreferredSize(new Dimension(550, 30)); jcb = new JCheckBox(); valuepanel = new JPanel(new GridLayout(1, 5, 5, 0)); valuepanel.setPreferredSize(new Dimension(500, 20)); add(jcb); add(valuepanel); valuepanel.add(new MyLabel(GlobalFields.PROPERTIES.getProperty("LABEL_INVOICENO"))); valuepanel.add(new MyLabel(GlobalFields.PROPERTIES.getProperty("LABEL_DATE"))); valuepanel.add(new MyLabel(GlobalFields.PROPERTIES.getProperty("LABEL_TYPE"))); valuepanel.add(new MyLabel(GlobalFields.PROPERTIES.getProperty("LABEL_TOTAL"))); valuepanel.add(new MyLabel(GlobalFields.PROPERTIES.getProperty("LABEL_UNPAID"))); } public JCheckBox getCheckBox(){ return jcb; } }
require "spec_helper" RSpec.describe Rqlisp::Runtime do describe "#run" do it "returns literal strings and integers" do expect(described_class.new.run("1")).to eq int(1) expect(described_class.new.run('"foo"')).to eq str("foo") end it "returns quoted objects from 'quote'" do expect(described_class.new.run("(quote (1))")).to eq list(int(1)) end it "evals unique constants specially" do expect(described_class.new.run("true")).to eq Rqlisp::TRUE expect(described_class.new.run("false")).to eq Rqlisp::FALSE expect(described_class.new.run("nil")).to eq Rqlisp::NIL end it "applies builtin functions" do expect(described_class.new.run("(+ 1 2)")).to eq int(3) end describe "fn" do it "creates function objects from 'fn' lists" do func = fn(an_instance_of(Rqlisp::Env), list(var(:foo)), list(int(1))) expect(described_class.new.run("(fn (foo) 1)")).to eq func end it "applies functions defined by 'fn'" do expect(described_class.new.run("((fn (i) (+ i 3)) 1)")).to eq int(4) end it "throws an error if there aren't enough args to a function" do expect { described_class.new.run("((fn (a) a))") }.to raise_error(/Not enough arguments/) end it "throws an error if there are too many args to a function" do expect { described_class.new.run("((fn () 1) 2)") }.to raise_error(/Too many arguments/) end it "allows functions with &rest args to take more arguments" do expect(described_class.new.run("((fn (a &rest b) b) 1 2 3)")).to eq list(int(2), int(3)) end end describe "if" do it "calls the first branch if the condition is true" do expect(described_class.new.run("(if true 1 2)")).to eq int(1) end it "calls the first branch if the condition is true-ish" do expect(described_class.new.run("(if 31337 1 2)")).to eq int(1) end it "returns nil if the condition is false but there's no second branch" do expect(described_class.new.run("(if false 1)")).to eq Rqlisp::NIL end it "calls the second branch if the condition is false" do expect(described_class.new.run("(if false 1 2)")).to eq int(2) end it "calls the second branch if the condition is nil" do expect(described_class.new.run("(if nil 1 2)")).to eq int(2) end end describe "defmacro" do it "defines a new macro with the given name in the current env" do macro = described_class.new.run('(defmacro foo () 1) foo') expect(macro).to be_a Rqlisp::Macro end end # describe "defn" do # it "defines a new function with the given name in the current env" do # function = described_class.new.run('(defn foo () 1) foo') # expect(function).to be_a Rqlisp::Function # expect(described_class.new.run('(defn foo () 1) (foo)')).to eq int(1) # end # end end end
<?php namespace Hx\Interop; use Hx\Interop\Error\AlreadyClosed; /** * Interface ByteWriter * @package Hx\Interop */ interface ByteWriter { /** * Write the given byte string to the underlying resource. * @param string $buf The string of bytes to be written. * @throws AlreadyClosed when the underlying stream is closed. */ public function writeBytes(string $buf): void; }
<?php namespace AppClassExtends; use PHPStan\Analyser\MutatingScope; use PHPStan\Type\FileTypeMapper; use PHPStan\Type\ObjectType; class Foo extends FileTypeMapper { } class Bar extends ObjectType { } class MyScope extends MutatingScope { }
<?php // Jivoo // Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk) // Licensed under the MIT license. // See the LICENSE file or http://opensource.org/licenses/MIT for more information. namespace Jivoo\Data\Query; use Jivoo\Data\DataSource; use Jivoo\Data\DataType; use Jivoo\Data\Query\Builders\ReadSelectionBuilder; use Jivoo\Data\Record; use Jivoo\Data\Definition; /** * A trait that implements {@see Readable}. */ trait ReadableTrait { /** * Return the data source to make selections on. * * @return \Jivoo\Data\DataSource */ abstract protected function getSource(); /** * Set offset. * * @param int $offset * Offset. * @return ReadSelectionBuilder A read selection. */ public function offset($offset) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->offset($offset); } /** * Set alias for selection source. * * @param string $alias * Alias. * @return ReadSelectionBuilder A read selection. */ public function alias($alias) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->alias($alias); } /** * Make a projection. * * @param string|string[]|Expression|Expression[] $expression * Expression or array of expressions (if the keys are strings, * they are used as aliases). * @param string $alias * Alias. * @return \Iterator A {@see Record} iterator. * @todo Rename to 'project' ? */ public function select($expression, $alias = null) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->select($expression, $alias); } /** * Append an extra virtual field to the returned records. * * @param string $field * Name of new field. * @param Expression|string $expression * Expression for field, e.g. 'COUNT(*)'. * @param DataType|null $type * Optional type of field. * @return ReadSelectionBuilder A read selection. */ public function with($field, $expression, DataType $type = null) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->with($field, $expression, $type); } /** * Append an extra virtual field (with a record as the value) to the returned * records. * * @param string $field * Name of new field, expects the associated model to be * aliased with the same name. * @param Definition $schema * Schema of associated record. * @return ReadSelectionBuilder A read selection. */ public function withRecord($field, Definition $schema) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->withRecord($field, $schema); } /** * Group by one or more columns. * * @param string|string[] $columns * A single column name or a list of column * names. * @param Expression|string $predicate * Grouping predicate. * @return ReadSelectionBuilder A read selection. */ public function groupBy($columns, $predicate = null) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->groupBy($columns, $predicate); } /** * Perform an inner join with another data source. * * @param DataSource $other * Other source. * @param string|Expression $condition * Join condition. * @param string $alias * Alias for joined model/table. * @return ReadSelectionBuilder A read selection. */ public function innerJoin(DataSource $other, $condition, $alias = null) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->innerJoin($other, $condition, $alias); } /** * Perform a left join with another data source. * * @param DataSource $other * Other source. * @param string|Expression $condition * Join condition. * @param string $alias * Alias for joined model/table. * @return ReadSelectionBuilder A read selection. */ public function leftJoin(DataSource $other, $condition, $alias = null) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->leftJoin($other, $condition, $alias); } /** * Perform a right join with another data source. * * @param DataSource $other * Other source. * @param string|Expression $condition * Join condition. * @param string $alias * Alias for joined model/table. * @return ReadSelectionBuilder A read selection. */ public function rightJoin(DataSource $other, $condition, $alias = null) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->rightJoin($other, $condition, $alias); } /** * Fetch only distinct records (i.e. * prevent duplicate records in result). * * @param bool $distinct * Whether to fetch only distinct records. * @return ReadSelectionBuilder A read selection. */ public function distinct($distinct = true) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->distinct($distinct); } /** * Return first record in selection. * * @return Record|null A record if available.. */ public function first() { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->first(); } /** * Return last record in selection. * * @return Record|null A record if available. */ public function last() { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->last(); } /** * Count number of records in selection. * * @return int Number of records. */ public function count() { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->count(); } /** * Find row number of a record in selection. * * @param \Jivoo\Data\Record $record * A record. * @return int Row number. */ public function rowNumber(Record $record) { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->rowNumber($record); } /** * Convert selection to an array. * * @return Record[] Array of records. */ public function toArray() { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->toArray(); } /** * Get iterator. * * @return \Iterator Iterator */ public function getIterator() { $selection = new ReadSelectionBuilder($this->getSource()); return $selection->getIterator(); } }
<?php namespace app\models; use Yii; use app\models\general\GeneralLabel; /** * This is the model class for table "tbl_profil_konsultan_kontrak". * * @property integer $profil_konsultan_kontrak_id * @property integer $profil_konsultan_id * @property string $tarikh_kontrak_mula * @property string $tarikh_kontrak_akhir * @property string $session_id * @property integer $created_by * @property integer $updated_by * @property string $created * @property string $updated */ class ProfilKonsultanKontrak extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'tbl_profil_konsultan_kontrak'; } /** * @inheritdoc */ public function rules() { return [ [['profil_konsultan_id', 'created_by', 'updated_by'], 'integer'], [['tarikh_kontrak_mula', 'tarikh_kontrak_akhir'], 'required'], [['tarikh_kontrak_mula', 'tarikh_kontrak_akhir', 'created', 'updated'], 'safe'], [['session_id'], 'string', 'max' => 100], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'profil_konsultan_kontrak_id' => 'Profil Konsultan Kontrak ID', 'profil_konsultan_id' => 'Profil Konsultan ID', 'tarikh_kontrak_mula' => GeneralLabel::tarikh_kontrak_mula, //'Tarikh Kontrak (Mula)', 'tarikh_kontrak_akhir' => GeneralLabel::tarikh_kontrak_tamat, //'Tarikh Kontrak (Akhir)', 'session_id' => 'Session ID', 'created_by' => 'Created By', 'updated_by' => 'Updated By', 'created' => 'Created', 'updated' => 'Updated', ]; } }
<?php namespace MayMeow; use MayMeow\UUID\UuidFactory as BaseFactory; /** * @deprecated * @see MayMeow\UUID\UuidFactory * ! Will be removed on next release 3.* */ class UuidFactory extends BaseFactory { // }
import Vue from "vue/dist/vue.js"; import VueRouter from "vue-router"; import Login from "../views/login/login.vue"; import Console from "../views/Console/index.vue"; import Layout from "../views/Console/index.vue"; Vue.use(VueRouter); const routes = [ { path: "/", redirect: Login, hidden: true, meta: { name: "首页", } }, { path: "/login", name: "Login", component: Login, hidden: true, meta: { name: "主页" } }, { path: "/console", name: "Console", component: Layout, hiddden: false, meta: { name: "控制台", icon: 'console' } }, { path: "/info", name: "Info", hidden: false, component: Layout, meta: { name: "信息管理", icon:'info' }, children: [ { path: "/infoList", name: "Infolist", component: () => import("../views/Info/InfoList.vue"), meta: { name: "信息列表" } }, { path: "/infoClass", name: "Infoclass", component: () => import("../views/Info/InfoClass.vue"), meta: { name: "信息分类" } }, { path: "/infoDetail", name: "Infodetail", component: () => import("../views/Info/InfoDetail.vue"), meta: { name: "信息详情" } } ] }, { path: "/users", name: "Users", hidden: false, meta: { name: "用户管理", icon: 'user' }, component: Layout, children: [ { path: "/usersList", name: "Userslist", component: ()=> import("../views/Users/UsersList.vue"), meta: { name: "用户列表" } } ] } ]; const router = new VueRouter({ routes }); export default router;
import React from 'react' import { AsyncState } from 'react-async' type Props<T> = { state: AsyncState<T> children: (data: T) => React.ReactNode } export default function AsyncContent<T>({ children, state }: Props<T>) { switch (state.status) { case 'pending': return null case 'fulfilled': return <>{children(state.data)}</> case 'rejected': // @TODO: Perhaps show a skeleton structure // of the element we're trying to fetch data for. return null default: // @TODO: Probably better handle edge cases return null } }
<?php use Gc7\FragmentCaching; use Gc7\CacheAdapterInterface; use PHPUnit\Framework\TestCase; class FakeCacheAdapter implements CacheAdapterInterface { public function get($key) { return FALSE; } public function set($key, $value) { // $this->$key=$value; } } class FakeModel { private $key; public function __construct($key) { $this->key = $key; } public function cache_key():string { return $this->key; } public function __toString():string { return $this->cache_key(); } } class FragmentCachingTest extends TestCase { public function testConstructorCache() { // Le test échoue car c'est le bon type d'objet // $adapter= new FakeCacheAdapter(); $adapter = new StdClass(); $this->expectException(TypeError::class); $cache = new FragmentCaching($adapter); } public function testCacheWithCache() { $cache = $this->getInstanceWithOutExpectedGet('en cache'); $this->expectOutputString('en cache'); $cache->cache('testCache', function () { echo 'Salut !'; }); } public function testCacheWithOutCache() { $cache = $this->getInstanceWithOutExpectedGet(); $this->expectOutputString('Salut !'); $cache->cache('testCache', function () { echo 'Salut !'; }); } public function testCacheWithoutCacheSetCache() { $cacheAdapter = $this->getMockBuilder(FakeCacheAdapter::class) ->setMethods(['get', 'set']) ->getMock(); $cacheAdapter->method('get')->willReturn(FALSE); $cacheAdapter->expects($this->once())->method('set')->with('testCache', 'Salut !'); $cache = new FragmentCaching($cacheAdapter); $cache->cache('testCache', function () { echo 'Salut !'; }); } public function testKeyWithArray() { $cache = $this->getInstanceWithExpectedGet('test-je-suis'); $cache->cache(['test', 'je', 'suis'], function () { return FALSE; }); } public function testKeyWithBooleanTrue() { $cache = $this->getInstanceWithExpectedGet('test-1-suis'); $cache->cache(['test', TRUE, 'suis'], function () { return FALSE; }); } public function testKeyWithBooleanFalse() { $cache = $this->getInstanceWithExpectedGet('test-0-suis'); $cache->cache(['test', FALSE, 'suis'], function () { return FALSE; }); } public function testKeyWithObject() { $fake = new FakeModel('model'); $cache = $this->getInstanceWithExpectedGet('test-model-suis'); $cache->cache(['test', $fake, 'suis'], function () { return FALSE; }); } public function getInstanceWithOutExpectedGet($value = FALSE) { $cacheAdapter = $this->getMockBuilder(FakeCacheAdapter::class) ->setMethods(['get']) ->getMock(); $cacheAdapter->method('get')->willReturn($value); return new FragmentCaching($cacheAdapter); } public function getInstanceWithExpectedGet($value = FALSE) { $cacheAdapter = $this->getMockBuilder(FakeCacheAdapter::class) ->setMethods(['get']) ->getMock(); $cacheAdapter->expects($this->once())->method('get')->with($value); return new FragmentCaching($cacheAdapter); } public function testCacheIfWithFalseCondition() { $cache = $this->getMockBuilder(FragmentCaching::class) ->setConstructorArgs([new FakeCacheAdapter()]) ->setMethods(['cache']) ->getMock(); $cache->expects($this->never())->method('cache'); $this->expectOutputString('salut'); $cache->cacheIf(FALSE, 'key', function () { echo 'salut'; }); } public function testCacheIfWithTrueCondition() { $cache = $this->getMockBuilder(FragmentCaching::class) ->setConstructorArgs([new FakeCacheAdapter()]) ->setMethods(['cache']) ->getMock(); $cache->expects($this->once())->method('cache'); $cache->cacheIf(TRUE, 'key', function () { echo 'salut'; }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpDX.DirectComposition { public partial class Device { /// <summary> /// Creates a new device object that can be used to create other Microsoft DirectComposition objects. /// </summary> /// <param name="device">The DXGI device to use to create DirectComposition surface objects.</param> public Device(DXGI.Device device) { IntPtr temp; DComp.CreateDevice(device, Utilities.GetGuidFromType(typeof(Device)), out temp); NativePointer = temp; } } }
<?php return array( // '<packagename>', // ... );
This is the source repository for Roboto: Google’s signature family of fonts, the default font on Android and Chrome OS, and the recommended font for Google’s visual language, Material Design. It also contains the toolchain used in creating Roboto. The font family supports all Latin, Cyrillic, and Greek characters in Unicode 7.0, as well as the currency symbol for the Georgian lari, to be published in Unicode 8.0. The fonts are currently available in eighteen different styles. [Subsetted webfonts](https://fonts.google.com/specimen/Roboto) are also available from Google Fonts. ## Setup Create a clean directory for Roboto: ```bash mkdir -p $HOME/roboto-src cd $HOME/roboto-src ``` Download the Roboto tools and sources: ```bash git clone https://github.com/google/roboto.git ``` Create a virtual Python environment (optional but recommended): ```bash pip install --user virtualenv virtualenv roboto-env source roboto-env/bin/activate ``` Download and install the dependencies (currently requires Python 2, not 3): ```bash cd roboto pip install -r requirements.txt ``` #### Optional additional setup for running tests Download the latest tarball release of HarfBuzz [here](http://www.freedesktop.org/wiki/Software/HarfBuzz/) and extract it into the **home** directory as `$HOME/harfbuzz` (alternatively, you can download the latest source from GitHub via `git clone https://github.com/behdad/harfbuzz.git`). Build and install HarfBuzz: ```bash cd $HOME/harfbuzz ./configure make sudo make install cd $HOME/roboto-src/ ``` On Ubuntu (or other distributions of GNU/Linux, using the appropriate package manager), make sure eog is installed: ```bash sudo apt-get install eog ``` ## Run ```bash cd roboto make ```
package sqlupdate import ( "github.com/stretchr/testify/assert" "testing" ) var testData = []struct { ov, cv string b bool }{ {"0.0.1", "0.2.0", true}, {"v1.0.2", "v3.0.1", true}, {"v1.3.2", "v1.2.4", false}, {"2.3.4", "2.4", true}, {"2.3.4", "2.3.2.20180809", false}, {"2.3.4", "2.3.4.20180809", true}, } func TestSqlUpdate_Decode(t *testing.T) { s := new(SqlUpdate) err := s.decode("./testdata/record.json") assert.NoError(t, err) assert.Equal(t, "test", s.Project) assert.Equal(t, "0.0.1", s.Update[0].Version) // 比较版本号 res1 := s.compareResult("0.0.0", "1.1.1") assert.Equal(t, 4, len(res1)) res2 := s.compareResult("0.1.0", "1.1.1") assert.Equal(t, 3, len(res2)) assert.Equal(t, "1.0.0", res2[0].Version) } func TestCompare(t *testing.T) { for _, v := range testData { assert.Equal(t, v.b, compare(v.ov, v.cv)) } } func TestSqlUpdate_GetSqls(t *testing.T) { s := new(SqlUpdate) str, err := s.GetSqls("./testdata/record.json", "0.0.0", "3.0.2") assert.NoError(t, err) assert.Contains(t, str, "COMMENT ON COLUMN public.account.balance IS") }
#pragma once #include "Utils.h" #include <iostream> #include <string> #include <sstream> inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const char* data, int length) { return v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(data), v8::NewStringType::kNormal, length).ToLocalChecked(); } inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const signed char* data, int length) { return v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(data), v8::NewStringType::kNormal, length).ToLocalChecked(); } inline v8::Local<v8::String> OneByteString(v8::Isolate* isolate, const unsigned char* data, int length) { return v8::String::NewFromOneByte( isolate, data, v8::NewStringType::kNormal, length) .ToLocalChecked(); } inline std::string report_exception(v8::Isolate* isolate, v8::Local<v8::Context> ctx, v8::TryCatch& try_catch) { std::stringstream ss; ss << "Uncaught exception: "; std::string exceptionStr = str(isolate, try_catch.Exception()); ss << exceptionStr; // TODO(aroman) JSON-ify objects? if (!try_catch.Message().IsEmpty()) { if (!try_catch.Message()->GetScriptResourceName()->IsUndefined()) { ss << std::endl << "at " << str(isolate, try_catch.Message()->GetScriptResourceName()); v8::Maybe<int> line_no = try_catch.Message()->GetLineNumber(ctx); v8::Maybe<int> start = try_catch.Message()->GetStartColumn(ctx); v8::Maybe<int> end = try_catch.Message()->GetEndColumn(ctx); v8::MaybeLocal<v8::String> sourceLine = try_catch.Message()->GetSourceLine(ctx); if (line_no.IsJust()) { ss << ":" << line_no.ToChecked(); } if (start.IsJust()) { ss << ":" << start.ToChecked(); } if (!sourceLine.IsEmpty()) { ss << std::endl << " " << str(isolate, sourceLine.ToLocalChecked()); } if (start.IsJust() && end.IsJust()) { ss << std::endl << " "; for (int i = 0; i < start.ToChecked(); i++) { ss << " "; } for (int i = start.ToChecked(); i < end.ToChecked(); i++) { ss << "^"; } } } } if (!try_catch.StackTrace(ctx).IsEmpty()) { ss << std::endl << "Stack trace: " << str(isolate, try_catch.StackTrace(ctx).ToLocalChecked()); } return ss.str(); }
mvn install && java -jar target/benchmarks.jar -wi 5 -i 3 -f 1 runcontainer
require 'rails_helper' module BeachApiCore describe ProfileCustomField, type: :model do subject { build(:profile_custom_field) } it 'should be valid with factory attributes' do expect(subject).to be_valid end it 'should have basic validations' do should validate_presence_of :title should define_enum_for(:status).with(enabled: 0, disabled: 1) should validate_uniqueness_of(:name).scoped_to(%i(keeper_id keeper_type)) end it 'should generate name' do profile_custom_field = create :profile_custom_field, title: 'Birth Date ' expect(profile_custom_field.name).to eq 'birth_date' end end end
# lyrics-spam Cutting lyrics into words and spamming them in your friends group chat This code will cut up lyrics you put in a file and will output them as keyboard inputs. Simply said, it will send lyrics word for word.
#!/bin/bash #│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ # # LICENSE UPL 1.0 # # Copyright (c) 1982-2020 Oracle and/or its affiliates. All rights reserved. # # NAME # 10_gi_setup.sh # # DESCRIPTION # GI Setup # # NOTES # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. # # AUTHOR # ruggero.citton@oracle.com # # MODIFIED (MM/DD/YY) # rcitton 03/30/20 - VBox libvirt & kvm support # rcitton 10/01/19 - Creation # # REVISION # 20200330 - $Revision: 2.0.2.1 $ # #│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒│ . /vagrant/config/setup.env sh ${ORA_INVENTORY}/orainstRoot.sh sh ${GI_HOME}/root.sh #---------------------------------------------------------- # EndOfFile #----------------------------------------------------------
namespace Transmute { using System; public interface IConverter { Type Source { get; } Type Target { get; } object Convert(object source); bool HasSameTypes(IConverter other); } public interface IConverter<TSource,TTarget> : IConverter { TTarget Convert(TSource source); } }
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, settled } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | nypr popup menu', function(hooks) { setupRenderingTest(hooks); let isOpen = function(context, selectorPrefix = '') { let selector = selectorPrefix + '.nypr-popupmenu'; return context.$(selector).hasClass('is-open'); }; let isClosed = function(context, selectorPrefix) { return !isOpen(context, selectorPrefix); }; test('it renders', async function(assert) { await render(hbs` {{#nypr-popup-menu text='Text'}} <div class='find-me'></div> {{/nypr-popup-menu}} `); assert.dom('.nypr-popupmenu-button').hasText('Text', 'button text should render'); assert.dom('.find-me').exists({ count: 1 }, 'block contents should render'); }); test('it toggles the popup when you click the button', async function(assert) { assert.expect(3); await render(hbs`{{nypr-popup-menu}}`); assert.ok(isClosed(this), 'popup should begin closed'); this.$('.nypr-popupmenu-button')[0].click(); settled().then(() => { assert.ok(isOpen(this), 'popup should open after clicking the button'); this.$('.nypr-popupmenu-button')[0].click(); }); return settled().then(() => { assert.ok(isClosed(this), 'popup should close after clicking the button again'); }); }); test('it closes the popup when you click outside', async function(assert) { assert.expect(1); await render(hbs`{{nypr-popup-menu}} <div id="outside">outside</div>`); this.$('.nypr-popupmenu-button')[0].click(); settled().then(() => { this.$('#outside')[0].click(); }); return settled().then(() => { assert.ok(isClosed(this), 'popup should close after clicking outside'); }); }); test('it closes the popup when you send a close action', async function(assert) { assert.expect(1); await render( hbs`{{#nypr-popup-menu as |close|}} <button id="close" {{action close}}>close</button> {{/nypr-popup-menu}}` ); this.$('.nypr-popupmenu-button')[0].click(); settled().then(() => { this.$('#close')[0].click(); }); return settled().then(() => { assert.ok(isClosed(this), 'popup should close after clicking button with close action'); }); }); test('it does not close the popup when you click on the bubble', async function(assert) { assert.expect(1); await render(hbs`{{nypr-popup-menu}}`); this.$('.nypr-popupmenu-button')[0].click(); settled().then(() => { this.$('.nypr-popupmenu-popup')[0].click(); }); return settled().then(() => { assert.ok(isOpen(this), 'popup should remain open after clicking bubble'); }); }); test('it works correctly with two buttons', async function(assert) { assert.expect(6); await render(hbs` {{#nypr-popup-menu class="b1" text="1"}}{{/nypr-popup-menu}} {{#nypr-popup-menu class="b2" text="2"}}{{/nypr-popup-menu}} `); assert.ok(isClosed(this, '.b1'), 'popup 1 should begin closed'); assert.ok(isClosed(this, '.b2'), 'popup 2 should begin closed'); this.$('.b1 .nypr-popupmenu-button')[0].click(); settled().then(() => { assert.ok(isOpen(this, '.b1'), 'popup 1 should open after clicking button 1'); assert.ok(isClosed(this, '.b2'), 'popup 2 should remain closed after clicking button 1'); this.$('.b2 .nypr-popupmenu-button')[0].click(); }); return settled().then(() => { assert.ok(isClosed(this, '.b1'), 'popup 1 should close after clicking button 2'); assert.ok(isOpen(this, '.b2'), 'popup 2 should open after clicking button 2'); }); }); });
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'seconscreen.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form,MainWindow,ocr): Form.setObjectName("Form") Form.resize(600, 460) icon = QtGui.QIcon("sajanimage_with_boxes.jpg") Form.setWindowIcon(icon) self.verticalLayout_2 = QtWidgets.QVBoxLayout(Form) self.verticalLayout_2.setObjectName("verticalLayout_2") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.Image = QtWidgets.QLabel(Form) self.Image.setText("") self.Image.setObjectName("Image") self.verticalLayout.addWidget(self.Image) self.TextEdit = QtWidgets.QTextEdit(Form) self.TextEdit.setMinimumSize(QtCore.QSize(0, 100)) self.TextEdit.setObjectName("listWidget") self.verticalLayout.addWidget(self.TextEdit) self.exitbtn = QtWidgets.QPushButton(Form) self.exitbtn.setObjectName("exitbtn") self.verticalLayout.addWidget(self.exitbtn) self.verticalLayout_2.addLayout(self.verticalLayout) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.exitbtn.clicked.connect(lambda :self.closewin(MainWindow,Form)) pixmap = QtGui.QPixmap(ocr[0]) # Setup pixmap with the provided image pixmap = pixmap.scaled(640,480, QtCore.Qt.KeepAspectRatio) # Scale pixmap self.Image.setPixmap(pixmap) # Set the pixmap onto the label self.Image.setAlignment(QtCore.Qt.AlignCenter) # Align the label to center self.TextEdit.clear() # Clear the text self.TextEdit.append(ocr[1]) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.exitbtn.setText(_translate("Form", "Exit")) def closewin(self,MainWindow,Form): MainWindow.show() Form.hide()
<?php namespace AEMR\Bundle\MarketResearchBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * GeoIndicatorSeries */ class GeoIndicatorSeries { /** * @var integer */ private $geoindicator_id; /** * @var integer */ private $geography_id; /** * @var string */ private $value; /** * @var string */ private $date; /** * @var integer */ private $id; /** * Set geoindicator_id * * @param integer $geoindicatorId * @return GeoIndicatorSeries */ public function setGeoindicatorId($geoindicatorId) { $this->geoindicator_id = $geoindicatorId; return $this; } /** * Get geoindicator_id * * @return integer */ public function getGeoindicatorId() { return $this->geoindicator_id; } /** * Set geography_id * * @param integer $geographyId * @return GeoIndicatorSeries */ public function setGeographyId($geographyId) { $this->geography_id = $geographyId; return $this; } /** * Get geography_id * * @return integer */ public function getGeographyId() { return $this->geography_id; } /** * Set value * * @param string $value * @return GeoIndicatorSeries */ public function setValue($value) { $this->value = $value; return $this; } /** * Get value * * @return string */ public function getValue() { return $this->value; } /** * Set date * * @param string $date * @return GeoIndicatorSeries */ public function setDate($date) { $this->date = $date; return $this; } /** * Get date * * @return string */ public function getDate() { return $this->date; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * @var string */ private $summary; /** * Set summary * * @param string $summary * @return GeoIndicatorSeries */ public function setSummary($summary) { $this->summary = $summary; return $this; } /** * Get summary * * @return string */ public function getSummary() { return $this->summary; } /** * @var integer */ private $prev_id; /** * Set prev_id * * @param integer $prevId * @return GeoIndicatorSeries */ public function setPrevId($prevId) { $this->prev_id = $prevId; return $this; } /** * Get prev_id * * @return integer */ public function getPrevId() { return $this->prev_id; } }
use std::io; use std::str; use builtin::status; use object; use object::Object; use refs; use work_dir; #[derive(Debug)] pub enum Error { AlreadyOnIt, IoError(io::Error), ObjectError(object::Error), ReferenceNotACommit, WorkDirError(work_dir::Error), WorkDirNotClean, } impl From<io::Error> for Error { fn from(e: io::Error) -> Error { Error::IoError(e) } } pub fn cmd_checkout(args: &[String]) { if args.is_empty() { println!("checkout: command takes a 'ref' argument."); } else { let ref_name = &args[0]; if let Err(why) = checkout(ref_name) { println!("Could not checkout: {:?}", why); } } } fn checkout(ref_name: &str) -> Result<(), Error> { if !status::is_clean_work_dir() { return Err(Error::WorkDirNotClean); } let will_detach_head = !refs::is_branch(&ref_name); let commit = match will_detach_head { true => ref_name.to_string(), false => refs::get_ref_hash(&ref_name)?, }; let object = Object::new(&commit).map_err(Error::ObjectError)?; if object.obj_type != "commit" { return Err(Error::ReferenceNotACommit); } let head = refs::get_ref_hash("HEAD")?; if ref_name == head { return Err(Error::AlreadyOnIt); } work_dir::update_from_commit(&commit).map_err(Error::WorkDirError)?; refs::write_to_ref("HEAD", ref_name)?; if will_detach_head { println!("Note: checking out {}", ref_name); println!("You are in detached HEAD state."); } else { println!("Switched to branch {}", ref_name); } Ok(()) }
require 'nokogiri' require 'kconv' require 'open-uri' class Keibado BASE_URL = "http://www.keibado.ne.jp/keibabook" class << self def get_horse_list_of_week(bn) html = self.get_page("#{BASE_URL}/#{bn}/index.html") horses = [] doc = Nokogiri::HTML(html.toutf8) # doc.css('table[class="mini"] tr td a').each do |elm| # name = elm.text # file = elm.attr(:href) # url = "#{BASE_URL}/#{bn}/#{file}" # horses << {name: name, url: url, bn: bn} # end race = "" td_elms = doc.css('table[class="mini"] tr td') td_elms = doc.css('table[bgcolor="#003300"][width="145"] tr td') if td_elms.size == 0 td_elms = doc.css('table[bgcolor="#003300"][width="140"] tr td') if td_elms.size == 0 td_elms.each do |elm| if elm.css('a').size == 0 race = elm.css('font b').text if elm.css('font b').size > 0 race = elm.css('b font').text if elm.css('b font').size > 0 race = elm.css('font').text if elm.css('font').size > 0 race = race.gsub("◆", '') else links = elm.css("a") links = elm.css("font a") if links.size == 0 links = elm.css("p font a") if links.size == 0 links.each do |a_elm| name = a_elm.text file = a_elm.attr(:href) url = "#{BASE_URL}/#{bn}/#{file}" name = "プロディガルサン" if url == "http://www.keibado.ne.jp/keibabook/160919/photo12.html" # forced correction horses << {name: name, url: url, bn: bn, race: race} end end end horses end def get_horse_padock_image_url(url) html = self.get_page(url) doc = Nokogiri::HTML(html.toutf8) elms = doc.css('table tr td img') elms.map { |elm| elm.attr(:src) }.select { |s| s =~ /images\/pp\d\d\.jpg/ }.first end def get_backnumber_list(year) html = self.get_page("#{BASE_URL}/bn/#{year}.html") doc = Nokogiri::HTML(html.toutf8) elms = doc.css('table tr td font a') bn_list = elms.map { |elm| elm.attr(:href) } .select { |s| s =~ /\.\.\/\d\d\d\d\d\d\/index\.html/ } .map { |s| s.split('/')[1] } .uniq .sort end def get_page(url) open(url).read end end end
#!/bin/bash echo "Shutting Down Liferay Server" ./opt/liferay-portal-7.2.0-ga1//tomcat-9.0.17/bin/shutdown.sh sudo rm -rf /opt/liferay-portal-7.2.0-ga1/ ls -latr /home/dtpuser ls -latr /opt/
unit Basic; {$include kcontrols.inc} interface uses {$IFDEF FPC} LCLType, LCLIntf, LResources, {$ELSE} Windows, Messages, {$ENDIF} Classes, SysUtils, Graphics, StdCtrls, KHexEditor, KControls; type TEnvironmentPacked = packed record Version: Byte; // options DropFiles, GroupUndo, UndoAfterSave: Boolean; // appearance ShowAddress, ShowDigits, ShowText, ShowHorzLines, ShowVertLines, ShowSeparators, ShowInactiveCaret: Boolean; // settings AddressMode, AddressSize, CharSpacing, DigitGrouping, DisabledDrawStyle, LineHeightPercent, LineSize, UndoLimit: Integer; // font FontSize: Integer; FontStyle: TFontStyles; end; TEnvironment = record P: TEnvironmentPacked; AddressPrefix: string; FontName: string; end; PEnvironment = ^TEnvironment; var Environment: TEnvironment; Colors: TKColorArray; AppName: string; IniPath: string; IniVersion: Integer; const secSettings = 'Settings'; secMRUFs = 'MRUFs'; secColors = 'Custom colors'; procedure DataToString(Buffer: Pointer; Size: Integer; var S: string); procedure StringToData(const S: string; Buffer: Pointer; Size: Integer); function Modified2Text(Modified: Boolean): string; function InsertMode2Text(Mode: Boolean): string; procedure AddFontsToList(DC: HDC; L: TStrings; Pitch: TFontPitch); function EditStrToInt(Handle: HWND; Edit: TEdit; AMin, AMax, Default: Integer; var Ok: Boolean): Integer; procedure InitEnvironment(var Data: TEnvironment); procedure InitColors(var Colors: TKColorArray); procedure CopyColors(Src, Dest: TKColorArray); implementation uses Math, Res, Forms, KEditCommon; type PEnumFontData = ^TEnumFontData; TEnumFontData = record List: TStrings; Pitch: TFontPitch; end; procedure DataToString(Buffer: Pointer; Size: Integer; var S: string); var I: Integer; T: string; begin SetLength(S, Size * 2); for I := 1 to Size do begin T := Format('%.2x' , [PByteArray(Buffer)^[I - 1]]); S[I * 2 - 1] := T[1]; S[I * 2] := T[2]; end; end; procedure StringToData(const S: string; Buffer: Pointer; Size: Integer); var I, Code: Integer; T: string; begin T := '$00'; for I := 1 to Min(Size, Length(S) div 2) do begin T[2] := S[I * 2 - 1]; T[3] := S[I * 2]; Val(T, PByteArray(Buffer)^[I - 1], Code); end; end; function EditStrToInt(Handle: HWND; Edit: TEdit; AMin, AMax, Default: Integer; var Ok: Boolean): Integer; var I, Code: Integer; S: string; begin Result := Default; if Ok then begin Val(Edit.Text, I, Code); if Code > 0 then S := sErrIntegerValue else if (I < AMin) or (I > AMax) then S := Format(sErrIntegerValueOutOfRange, [AMin, AMax]) else S := ''; if S <> '' then begin MessageBox(Handle, PChar(S), PChar(sAppName), MB_OK); Ok := False; // Edit.Text := IntToStr(Default); if Edit.CanFocus then try GetParentForm(Edit).ActiveControl := Edit; except end; end else Result := I; end; end; function Modified2Text(Modified: Boolean): string; begin if Modified then Result := sModified else Result := ''; end; function InsertMode2Text(Mode: Boolean): string; begin if Mode then Result := sInsert else Result := sOverWrite; end; function EnumFontFamProc(var LFData: TEnumLogFont; var PFData: TNewTextMetric; FontType: Integer; Data: PEnumFontData): Integer; stdcall; begin if Data.Pitch = fpFixed then begin if LFData.elfLogFont.lfPitchAndFamily and 1 = 1 then Data.List.Add(LFData.elfLogFont.lfFaceName); end else Data.List.Add(LFData.elfLogFont.lfFaceName); Result := 1; end; procedure AddFontsToList(DC: HDC; L: TStrings; Pitch: TFontPitch); var Data: TEnumFontData; begin Data.List := L; Data.Pitch := Pitch; EnumFontFamilies(DC, nil, @EnumFontFamProc, LParam(@Data)); end; procedure InitEnvironment(var Data: TEnvironment); begin with Data.P do begin Version := IniVersion; DropFiles := True; GroupUndo := True; UndoAfterSave := False; ShowAddress := True; ShowDigits := True; ShowText := True; ShowHorzLines := False; ShowVertLines := False; ShowSeparators := True; ShowInactiveCaret := True; DisabledDrawStyle := Integer(cEditDisabledDrawStyleDef); AddressMode := Integer(cAddressModeDef); AddressSize := cAddressSizeDef; CharSpacing := cCharSpacingDef; LineSize := cLineSizeDef; DigitGrouping := cDigitGroupingDef; LineHeightPercent := cLineHeightPercentDef; UndoLimit := cUndoLimitDef; FontSize := cFontSizeDef; FontStyle := cFontStyleDef; end; with Data do begin AddressPrefix := cAddressPrefixDef; FontName := cFontNameDef; end; end; procedure InitColors(var Colors: TKColorArray); var I: TKHexEditorColorIndex; begin SetLength(Colors, ciHexEditorColorsMax + 1); for I := 0 to Length(Colors) - 1 do Colors[I] := GetColorSpec(I).Def; end; procedure CopyColors(Src, Dest: TKColorArray); var I: TKHexEditorColorIndex; begin for I := 0 to Min(Length(Src), Length(Dest)) - 1 do Dest[I] := Src[I]; end; initialization AppName := 'Hex Editor (Demo)'; IniPath := ExtractFilePath(Application.ExeName) + 'hexeditor.ini'; IniVersion := 103 end.
import * as fs from 'fs' import { name as PACKAGE_NAME } from '../../package.json' // Example usage: // /** // * @example // * import { example } from '{:PACKAGE_NAME:}' // * // * example() // */ // function example(): void { // return undefined // } const REPLACEMENTS = { 'PACKAGE_NAME': PACKAGE_NAME, } const FILES_TO_PROCESS = [ './lib/types/index.d.ts', ] console.log('Post-processing docs...') for (const filePath of FILES_TO_PROCESS) { console.log(` * ${filePath}`) let fileContents = fs.readFileSync(filePath, 'utf-8') forEachChild(REPLACEMENTS, (replacementKey, replacementValue) => { fileContents = fileContents.replace( new RegExp(`{:${replacementKey}:}`, 'g'), replacementValue ) }) // console.log(fileContents) fs.writeFileSync(filePath, fileContents, 'utf-8') } // ====================================================================== /** * Loops through each child in an object. * @param collection - The object to loop through. * @param callback - A function that receives the key and value of each item in * the object. * @example * const collection = { * 'id1': { value: 1 }, * 'id2': { value: 2 }, * 'id3': { value: 3 }, * 'id4': { value: 4 }, * } * const output = { concat: '', sum: 0 } * forEachChild(collection, (key, child, breakLoop) => { * output.concat += key * output.sum += child.value * if (output.sum >= 6) { breakLoop() } * }) * @public */ function forEachChild<T>( collection: T, callback: ( /** * Key of the current child. */ key: keyof T, /** * Value of the current child. */ child: T[keyof T], /** * Invoke this function to break the loop. */ breakLoop: (() => void) ) => void ): void { const keyStack = Object.keys(collection) as Array<keyof T> let shouldBreakLoop = false const breakLoop = (): void => { shouldBreakLoop = true } for (const key of keyStack) { callback(key, collection[key], breakLoop) if (shouldBreakLoop) { break } } }
package com.example.data.module import com.example.data.source.repository.SwapiRepositoryImpl import com.example.domain.repository.SwapiRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class SwapiRepositoryModule { @Binds abstract fun bindRepositoryModule( swapiRepositoryImpl: SwapiRepositoryImpl ): SwapiRepository }
SELECT * FROM BoloesMembros WHERE Username = '-' SELECT * FROM UserInRole WHERE UserName = '-' SELECT * FROM Usuarios WHERE UserName = '-' DELETE FROM BoloesMembros WHERE Username = '-' DELETE FROM UserInRole WHERE UserName = '-' DELETE FROM Usuarios WHERE UserName = '-'
package pythonproviders import ( "encoding/json" "fmt" "math" "sort" "github.com/kiteco/kiteco/kite-golib/errors" "github.com/kiteco/kiteco/kite-golib/licensing" "github.com/kiteco/kiteco/kite-golib/rollbar" "github.com/kiteco/kiteco/kite-go/lang/python/pythonast" "github.com/kiteco/kiteco/kite-go/lang/python/pythoncode" "github.com/kiteco/kiteco/kite-go/lang/python/pythonimports" "github.com/kiteco/kiteco/kite-go/response" "github.com/kiteco/kiteco/kite-golib/complete/data" "github.com/kiteco/kiteco/kite-golib/kitectx" ) const maxTypesForPlaceholder = 1 // KWArgs provides semantic keyword argument completions. type KWArgs struct{} // Name implements Provider func (KWArgs) Name() data.ProviderName { return data.PythonKWArgsProvider } // Provide implements Provider func (a KWArgs) Provide(ctx kitectx.Context, g Global, in Inputs, out OutputFunc) error { ctx.CheckAbort() if _, ok := SmartProviders[a.Name()]; ok && g.Product.GetProduct() != licensing.Pro { return data.ProviderNotApplicableError{} } if in.Selection.Len() > 0 { // Fix for issue 8162 : https://github.com/kiteco/kiteco/issues/8162 // Title: kwarg completion shown when positional arg completion is clearly the user's intention // The selection is not empty, so it's either a value either a placeholder, so we don't want to replace it // by a keyword argument (as it was a positional argument before or a placeholder for it) return data.ProviderNotApplicableError{} } cursor := in.Selection.Begin underPos := in.UnderSelection() var call *pythonast.CallExpr for i := len(underPos) - 1; i >= 0; i-- { n := underPos[i] if call, _ = n.(*pythonast.CallExpr); call != nil { break } } if call == nil || cursor <= int(call.LeftParen.Begin) || (call.RightParen != nil && cursor > int(call.RightParen.Begin)) { return data.ProviderNotApplicableError{} } // compute the replacement range by finding the argument under the cursor replace := data.Cursor(cursor) var arg *pythonast.Argument if len(call.Args) > len(call.Commas) { // by default, assume we're in the argument after the last comma arg = call.Args[len(call.Args)-1] } for i, comma := range call.Commas { // check if we're not in the argument after the last comma if cursor <= int(comma.Begin) { if i < len(call.Args) { arg = call.Args[i] } else { // TODO how can this happen? it's observed in Rollbar rollbar.Error(errors.New("unexpected call with more commas than args"), call) arg = nil replace.Begin = int(comma.Begin) replace.End = int(comma.Begin) } break } } if arg != nil { replace = data.Selection{ Begin: int(arg.Begin()), End: int(arg.End()), } } val := in.ResolvedAST().References[call.Func] if val == nil { return nil } // TODO: better ranking for the value constituents var cs []MetaCompletion for _, fi := range funcInfos(ctx, g.ResourceManager, g.LocalIndex, val) { cs = append(cs, a.keywordCompletions(fi, replace, call)...) } // TODO(naman) use frequencies for scores? n := float64(len(cs)) for i, c := range cs { // P(i) = 2/n - (2i + 1)/n^2 if valid, ok := c.Validate(in.SelectedBuffer); ok { c.Completion = valid } else { continue } c.Score = 2./n - (2.*float64(i)+1)/(n*n) out(ctx, in.SelectedBuffer, c) } return nil } // MarshalJSON implements Provider func (a KWArgs) MarshalJSON() ([]byte, error) { return json.Marshal(struct { Type data.ProviderName `json:"type"` }{ Type: a.Name(), }) } func (a KWArgs) keywordCompletions(fi funcInfo, s data.Selection, call *pythonast.CallExpr) []MetaCompletion { ci := newCallInfo(s, call, fi.Spec) if ci.FirstKeyword == -1 || ci.Selected < ci.FirstKeyword { // have not seen a keyword arg or the slot we are in is before the first keyword if fi.Spec == nil { // no arg spec so we have to wait until the selected argument is past the first keyword return nil } // NOTE: we ignore required keyword only args for now var required int for _, arg := range fi.Spec.Args { if receiverParam(arg.Name) { continue } if arg.DefaultValue == "" { required++ } else { break } } if ci.Selected < required { return nil } } skip := func(p string) bool { return ci.Filled[p] || receiverParam(p) } _, isSmart := SmartProviders[a.Name()] comp := func(name, hole string, score float64) MetaCompletion { // NOTE: we explicitly do not set `RenderMeta` since // we do not want to show documentation for the function // when the user is inside the call. return MetaCompletion{ Provider: a.Name(), Source: response.ArgSpecCompletionSource, KeywordModelMeta: true, Score: score, Completion: data.Completion{ Snippet: data.BuildSnippet(fmt.Sprintf("%s=%s", name, hole)), Replace: s, }, ArgSpecMeta: &ArgSpecMeta{ArgSpec: fi.Spec, ArgumentCount: getArgCount(call.Args)}, FromSmartProvider: isSmart, } } var cs []MetaCompletion if fi.Spec != nil { for _, param := range fi.Spec.Args { if skip(param.Name) { continue } // just use a score of 1 since we do not have a better score // and the caller assumes the returned completions are already in sorted order cs = append(cs, comp(param.Name, holeForPlaceholderTypes(param.Types), 1.)) } } if fi.Kwargs != nil { for _, kw := range fi.Kwargs.Kwargs { if skip(kw.Name) { continue } // just use a score of 1 since we assume the kwargs // are already sorted by score and the caller assumes // the returned completions are already in sorted order cs = append(cs, comp(kw.Name, holeForPlaceholderTypes(kw.Types), 1.)) } } if fi.Patterns != nil { ts := func(scs []*pythoncode.StringCount) []string { var ts []string for i, sc := range scs { if i == maxTypesForPlaceholder { break } ts = append(ts, sc.Value) } return ts } // maintain a separate list that we will sort // and then append after the arg spec arguments var scored []MetaCompletion for _, a := range fi.Patterns.Args { if skip(a.Name) { continue } scored = append(scored, comp(a.Name, holeForPlaceholderTypes(ts(a.Types)), float64(a.Count))) } for _, kw := range fi.Patterns.Kwargs { if skip(kw.Name) { continue } scored = append(scored, comp(kw.Name, holeForPlaceholderTypes(ts(kw.Types)), float64(kw.Count))) } sort.Slice(scored, func(i, j int) bool { si, sj := scored[i].Score, scored[j].Score if math.Abs(si-sj) < 1e-6 { return scored[i].Snippet.Text < scored[j].Snippet.Text } return si > sj }) cs = append(cs, scored...) } return cs } type callInfo struct { Filled map[string]bool FirstKeyword int Selected int } func newCallInfo(s data.Selection, call *pythonast.CallExpr, spec *pythonimports.ArgSpec) callInfo { argCount := getArgCount(call.Args) ci := callInfo{ Filled: make(map[string]bool, argCount-1), Selected: -1, FirstKeyword: -1, } for i, comma := range call.Commas { if s.End <= int(comma.Begin) { ci.Selected = i break } } if ci.Selected == -1 { // must be at the final argument ci.Selected = len(call.Commas) } var numBoundArgs int if spec != nil && len(spec.Args) > 0 && receiverParam(spec.Args[0].Name) { numBoundArgs++ } for i := 0; i < argCount; i++ { arg := call.Args[i] if name, ok := arg.Name.(*pythonast.NameExpr); ok { ci.Filled[name.Ident.Literal] = true if ci.FirstKeyword == -1 { ci.FirstKeyword = i } } else if i != ci.Selected && spec != nil && (i+numBoundArgs) < len(spec.Args) && ci.FirstKeyword == -1 { ci.Filled[spec.Args[i+numBoundArgs].Name] = true } } return ci } func receiverParam(name string) bool { return name == "cls" || name == "self" }
# frozen_string_literal: true describe Sneakers::Laces, '.api_client' do subject(:api_client) { described_class.api_client } let!(:current_endpoint) { described_class.config.rabbitmq_api_endpoint } before { described_class.configure { |c| c.rabbitmq_api_endpoint = 'https://foo:bar@rmq.example.com/' } } after { described_class.configure { |c| c.rabbitmq_api_endpoint = current_endpoint } } it { is_expected.to be_a RabbitMQ::HTTP::Client } it 'has proper endpoint' do expect(api_client.endpoint).to eq 'https://foo:bar@rmq.example.com/' end end
const BuyMessage = props => { if (props.buySuccess === '') return null if (props.buySuccess === 'Not Enough') { return "You don't have enough in your account to complete this transaction." } if (props.buySuccess === 'Purchased') { return 'Purchase Successful!' } } export default BuyMessage
require 'wilson_interval' describe "Wilson::Interval" do it "returns correct z" do wilson = Wilson::Interval.new(p_hat: 0.5, total: 1000, confidence: 0.99) wilson.send(:z).round(8).should == 2.57582933 wilson = Wilson::Interval.new(p_hat: 0.5, total: 1000, confidence: 0.95) wilson.send(:z).round(8).should == 1.95996397 wilson = Wilson::Interval.new(p_hat: 0.5, total: 1000, confidence: 0.50) wilson.send(:z).round(8).should == 0.67448976 wilson = Wilson::Interval.new(p_hat: 0.5, total: 1000, confidence: 0.25) wilson.send(:z).round(8).should == 0.31863936 end it "correctly calculates p_hat" do wilson = Wilson::Interval.new(p_hat: 0.5, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0.4691 wilson.upper_bound.round(4).should == 0.5309 wilson = Wilson::Interval.new(successes: 500, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0.4691 wilson.upper_bound.round(4).should == 0.5309 end it "correctly calculates lower and upper bounds" do wilson = Wilson::Interval.new(successes: 500, total: 1000, confidence: 0.99) wilson.lower_bound.round(4).should == 0.4594 wilson.upper_bound.round(4).should == 0.5406 wilson = Wilson::Interval.new(successes: 500, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0.4691 wilson.upper_bound.round(4).should == 0.5309 wilson = Wilson::Interval.new(successes: 500, total: 1000, confidence: 0.50) wilson.lower_bound.round(4).should == 0.4893 wilson.upper_bound.round(4).should == 0.5107 wilson = Wilson::Interval.new(successes: 1000, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0.9962 wilson.upper_bound.round(4).should == 1 wilson = Wilson::Interval.new(successes: 0, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0 wilson.upper_bound.round(4).should == 0.0038 wilson = Wilson::Interval.new(successes: 250, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0.2242 wilson.upper_bound.round(4).should == 0.2778 wilson = Wilson::Interval.new(successes: 750, total: 1000, confidence: 0.95) wilson.lower_bound.round(4).should == 0.7222 wilson.upper_bound.round(4).should == 0.7758 end end
<?php /** * This file is part of the Zephir. * * (c) Phalcon Team <team@zephir-lang.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Zephir\Logger\Formatter; use Monolog\Formatter\LineFormatter; use Zephir\Config; /** * Formatter for warnings/notices/errors generated in compilation. */ final class CompilerFormatter extends LineFormatter { const SIMPLE_FORMAT = " %level_name%: %message% in %file% on line %line% %type%\n"; /** * @var Config */ private $config; /** * The contents of the files that are involved in the log message. * * @var array */ private $filesContent = []; public function __construct(Config $config) { parent::__construct(); $this->config = $config; } /** * {@inheritdoc} */ public function format(array $record) { if ($this->config->get('silent')) { return ''; } $vars = parent::normalize($record); $output = $this->format; // unused unset($vars['extra']); $output = str_replace('%extra%', '', $output); $output = str_replace('%context%', '', $output); // ignore empty context or invalid format if (!empty($vars['context']) && \is_array($vars['context']) && 2 == \count($vars['context']) ) { $type = $vars['context'][0]; $node = $vars['context'][1]; if (!$this->config->get($type, 'warnings')) { return ''; } $vars['type'] = "[{$type}]"; if (!isset($node['file'])) { $vars['file'] = 'unknown'; $vars['line'] = '0'; } else { $vars['file'] = $node['file']; $vars['line'] = $node['line']; $output .= PHP_EOL; $lines = $this->getFileContents($node['file']); if (isset($lines[$node['line'] - 1])) { $line = $lines[$node['line'] - 1]; $output .= "\t".str_replace("\t", ' ', $line); if (($node['char'] - 1) > 0) { $output .= PHP_EOL."\t".str_repeat('-', $node['char'] - 1).'^'.PHP_EOL; } } } $output = str_replace('%file%', $this->stringify($vars['file']), $output); $output = str_replace('%line%', $this->stringify($vars['line']), $output); $output = str_replace('%type%', $this->stringify($vars['type']), $output); } $output = $this->replacePlaceholders($vars, $output); $output = $this->cleanExtraPlaceholders($output); return $output; } private function replacePlaceholders(array $vars, $output) { // WARNING -> Warning if (\array_key_exists('level_name', $vars)) { $vars['level_name'] = ucfirst(strtolower($vars['level_name'])); } foreach ($vars as $var => $val) { $placeholder = '%'.$var.'%'; $realValue = $this->stringify($val); if (false === strpos($output, $placeholder)) { continue; } // Strip level name from entries like "Info: Installing..." if ('%level_name%' === $placeholder) { switch ($realValue) { case 'Debug': case 'Info': $output = str_replace('%level_name%: ', '', $output); continue 2; } } $output = str_replace('%'.$var.'%', $realValue, $output); } return $output; } /** * Remove leftover %extra.xxx% and %context.xxx% (if any). * * @param string $output * * @return string */ private function cleanExtraPlaceholders($output) { if (false !== strpos($output, '%')) { $output = preg_replace('/%(?:extra|context)\..+?%/', '', $output); $output = preg_replace('/ %type%\n/', "\n", $output); $output = preg_replace('/on line %line%/', '', $output); $output = preg_replace('/ in %file% /', '', $output); } return $output; } /** * Gets the contents of the files that are involved in the log message. * * @param string $file File path * * @return array */ private function getFileContents($file) { if (!isset($this->filesContent[$file])) { $this->filesContent[$file] = file_exists($file) ? file($file) : []; } return $this->filesContent[$file]; } }
const chalk = require('chalk'); module.exports = bot => { console.log(chalk.bgGreen.white(`Logged in as ${bot.user.tag}!`)); console.log(chalk.bgGreen.white('Booted up!')); };
<?php require_once '../../../src/DocuSign_Client.php'; require_once '../../../src/service/DocuSign_UserService.php'; $client = new DocuSign_Client(); if( $client->hasError() ) { echo "\nError encountered in client, error is: " . $client->getErrorMessage() . "\n"; return; } $service = new DocuSign_UserService($client); // // Get the full user list // $response = $service->user->getUserList(); echo "\n-- User List --\n\n"; print_r($response); // // Add a new user // $user = new DocuSign_AddUser(); $user->setEmail("bob.testname@example.com"); $user->setUserName("Bob Testname"); // NOTE: Uncomment the following two lines if you are using an account with silent user activation, // such as would be setup if you were using the Single Sign-On (SSO) functionality. //$user->setPassword("PasswordNotKnown"); //$user->setForgottenPasswordInfo("Q1", "A1", "Q2", "A2", "Q3", "A3", "Q4", "A4"); $user->setCanSendEnvelope(true); $response = $service->user->addUser($user); echo "\n-- Add User --\n\n"; print_r($response); // // Extract the userId from the create response // $userId = $response->newUsers[0]->userId; // // Get the settings for that new user // $response = $service->user->getUserInfo($userId, "true"); echo "\n-- User Info --\n\n"; print_r($response); // // Get the settings for that new user // $response = $service->user->getUserSettingList($userId); echo "\n-- User Setting List --\n\n"; print_r($response); // // Close the new user membership // $response = $service->user->closeUser($userId); echo "\n-- Close User --\n\n"; print_r($response); ?>
// Copyright (c) 2019 AUTHORS // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // Original Fortran source: http://cococubed.asu.edu/research_pages/sedov.shtml /* sedov3.f -- translated by f2c (version 20160102). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as ina cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include <cmath> #include <vector> #include <unordered_map> #include <memory> //#include "f2c.h" #include <memory> #include <assert.h> #if !defined(OCTOTIGER_HAVE_BOOST_MULTIPRECISION) #include <quadmath.h> using sed_real = __float128; sed_real _exp(sed_real a) { return expq(a); } sed_real pow_dd(sed_real *a, sed_real *b) { return powq(*a, *b); } sed_real d_sign(sed_real *a, sed_real * b) { return copysignq(*a, *b); } #else #include <boost/multiprecision/cpp_bin_float.hpp> using sed_real = boost::multiprecision::cpp_bin_float_quad; sed_real _exp(sed_real a) { return boost::multiprecision::exp(a); } sed_real pow_dd(sed_real *a, sed_real *b) { return boost::multiprecision::pow(*a, *b); } sed_real d_sign(sed_real *a, sed_real * b) { if ((*a > static_cast<sed_real>(0.) && (*b > static_cast<sed_real>(0.))) || (*a < static_cast<sed_real>(0.) && (*b < static_cast<sed_real>(0.)))) { return *a; } return *b; } #endif /* Subroutine */int sed_1d__(sed_real *time, int *nstep, sed_real * xpos, sed_real *eblast, sed_real *omega_in__, sed_real * xgeom_in__, sed_real *rho0, sed_real *vel0, sed_real *ener0, sed_real *pres0, sed_real *cs0, sed_real *gam0, sed_real *den, sed_real *ener, sed_real *pres, sed_real *vel, sed_real *cs); /* Common Block Declarations */ struct { sed_real gamma, gamm1, gamp1, gpogm, xgeom, xg2, rwant, r2, a0, a1, a2, a3, a4, a5, a_val__, b_val__, c_val__, d_val__, e_val__, omega, vv, xlam_want__, vwant, rvv; bool lsingular, lstandard, lvacuum, lomega2, lomega3; } slap_; #define slap_1 slap_ struct { sed_real gam_int__; } cmidp_; #define cmidp_1 cmidp_ /* Table of constant values */ using D_fp = sed_real (*)(sed_real*); using S_fp = int (*)( D_fp, sed_real*, sed_real*, sed_real*, int*); //Subroutine using U_fp = int (*)(); // Unknown procedure type static sed_real c_b52 = 2.; static sed_real c_b53 = 1e-10; static sed_real c_b79 = 0.f; static sed_real c_b80 = 1e-30; static int c__3 = 3; static int c__5 = 5; static sed_real efun01_(sed_real *v); static sed_real efun02_(sed_real *v); static sed_real sed_v_find__(sed_real *v); static sed_real sed_r_find__(sed_real *r__); /* Subroutine */int sedov_funcs__(sed_real *v, sed_real *l_fun__, sed_real *dlamdv, sed_real *f_fun__, sed_real *g_fun__, sed_real *h_fun__); /* Subroutine */static int midpnt_(D_fp func, sed_real *a, sed_real *b, sed_real *s, int *n); /* Subroutine */static int midpowl_(D_fp funk, sed_real *aa, sed_real *bb, sed_real *s, int *n); /* Subroutine */static int midpowl2_(D_fp funk, sed_real *aa, sed_real *bb, sed_real *s, int *n); /* Subroutine */static int qromo_(D_fp func, sed_real *a, sed_real *b, sed_real *eps, sed_real *ss, S_fp choose); /* Subroutine */static int polint_(sed_real *xa, sed_real *ya, int *n, sed_real *x, sed_real *y, sed_real *dy); static sed_real zeroin_(sed_real *ax, sed_real *bx, D_fp f, sed_real *tol); int pow_ii(int * a, int * b) { return std::pow(*a, *b); } /* Subroutine */int sed_1d__(sed_real *time, int *nstep, sed_real * xpos, sed_real *eblast, sed_real *omega_in__, sed_real * xgeom_in__, sed_real *rho0, sed_real *vel0, sed_real *ener0, sed_real *pres0, sed_real *cs0, sed_real *gam0, sed_real *den, sed_real *ener, sed_real *pres, sed_real *vel, sed_real *cs) { /* System generated locals */ int i__1; sed_real d__1, d__2, d__3; /* Builtin functions */ /* Local variables */ static int i__; static sed_real p2, v0, u2, v2, us; static sed_real vat, rho1, rho2; static sed_real vmin, eval1, eval2, alpha, f_fun__; static sed_real g_fun__, h_fun__, l_fun__; static sed_real vstar, denom2, denom3, dlamdv; sed_real zeroin_(sed_real *ax, sed_real *bx, D_fp f, sed_real *tol); /* ..this routine produces 1d solutions for a sedov blast wave propagating */ /* ..through a density gradient rho = rho**(-omega) */ /* ..in planar, cylindrical or spherical geometry */ /* ..for the standard, singular and vaccum cases. */ /* ..standard case: a nonzero solution extends from the shock to the origin, */ /* .. where the pressure is finite. */ /* ..singular case: a nonzero solution extends from the shock to the origin, */ /* .. where the pressure vanishes. */ /* ..vacuum case : a nonzero solution extends from the shock to a boundary point, */ /* .. where the density vanishes making the pressure meaningless. */ /* ..input: */ /* ..time = temporal point where solution is desired seconds */ /* ..xpos(i) = spatial points where solution is desired cm */ /* ..eblast = energy of blast erg */ /* ..rho0 = ambient density g/cm**3 rho = rho0 * r**(-omega_in) */ /* ..omegain = density power law _exponent rho = rho0 * r**(-omega_in) */ /* ..vel0 = ambient material speed cm/s */ /* ..pres0 = ambient pressure erg/cm**3 */ /* ..cs0 = ambient sound speed cm/s */ /* ..gam0 = gamma law equation of state */ /* ..xgeom_in = geometry factor, 3=spherical, 2=cylindircal, 1=planar */ /* ..for efficiency reasons (doing the energy integrals only once), */ /* ..this routine returns the solution for an array of spatial points */ /* ..at the desired time point. */ /* ..output: */ /* ..den(i) = density g/cm**3 */ /* ..ener(i) = specific internal energy erg/g */ /* ..pres(i) = presssure erg/cm**3 */ /* ..vel(i) = velocity cm/s */ /* ..cs(i) = sound speed cm/s */ /* ..this routine is based upon two papers: */ /* .."evaluation of the sedov-von neumann-taylor blast wave solution" */ /* ..jim kamm, la-ur-00-6055 */ /* .."the sedov self-similiar point blast solutions in nonuniform media" */ /* ..david book, shock waves, 4, 1, 1994 */ /* ..although the ordinary differential equations are analytic, */ /* ..the sedov _expressions appear to become singular for various */ /* ..combinations of parameters and at the lower limits of the integration */ /* ..range. all these singularies are removable and done so by this routine. */ /* ..these routines are written in sed_real*8 precision because the */ /* ..sed_real*8 implementations simply run out of precision "near" the origin */ /* ..in the standard case or the transition region in the vacuum case. */ /* ..declare the pass */ /* ..local variables */ /* ..eps controls the integration accuracy, don't get too greedy or the number */ /* ..of function evaluations required kills. */ /* ..eps2 controls the root find accuracy */ /* ..osmall controls the size of transition regions */ /* ..common block communication */ /* ..common block communication with the integration stepper */ /* ..popular formats */ /* ..initialize the solution */ /* Parameter adjustments */ --cs; --vel; --pres; --ener; --den; --xpos; /* Function Body */ /* L87: */ /* L88: */ i__1 = *nstep; for (i__ = 1; i__ <= i__1; ++i__) { den[i__] = 0.f; vel[i__] = 0.f; pres[i__] = 0.f; ener[i__] = 0.f; cs[i__] = 0.f; } /* ..return on unphysical cases */ /* ..infinite mass */ if (*omega_in__ >= *xgeom_in__) { return 0; } /* ..transfer the pass to common block and create some frequent combinations */ slap_1.gamma = *gam0; slap_1.gamm1 = slap_1.gamma - 1.f; slap_1.gamp1 = slap_1.gamma + 1.f; slap_1.gpogm = slap_1.gamp1 / slap_1.gamm1; slap_1.xgeom = *xgeom_in__; slap_1.omega = *omega_in__; slap_1.xg2 = slap_1.xgeom + 2.f - slap_1.omega; denom2 = slap_1.gamm1 * 2.f + slap_1.xgeom - slap_1.gamma * slap_1.omega; denom3 = slap_1.xgeom * (2.f - slap_1.gamma) - slap_1.omega; /* ..post shock location v2 and location of singular point vstar */ /* ..kamm equation 18 and 19 */ v2 = 4.f / (slap_1.xg2 * slap_1.gamp1); vstar = 2.f / (slap_1.gamm1 * slap_1.xgeom + 2.f); /* ..set two bools that determines the type of solution */ slap_1.lstandard = false; slap_1.lsingular = false; slap_1.lvacuum = false; if ((d__1 = v2 - vstar, fabs(static_cast<double>(d__1))) <= 1e-4) { slap_1.lsingular = true; } else if (v2 < vstar - 1e-4) { slap_1.lstandard = true; } else if (v2 > vstar + 1e-4) { slap_1.lvacuum = true; } /* ..two apparent singularies, book's notation for omega2 and omega3 */ slap_1.lomega2 = false; slap_1.lomega3 = false; if (fabs(static_cast<double>(denom2)) <= 1e-4) { slap_1.lomega2 = true; denom2 = 1e-8f; } else if (fabs(static_cast<double>(denom3)) <= 1e-4) { slap_1.lomega3 = true; denom3 = 1e-8f; } /* ..various _exponents, kamm equations 42-47 */ /* ..in terms of book's notation: */ /* ..a0=beta6 a1=beta1 a2=-beta2 a3=beta3 a4=beta4 a5=-beta5 */ slap_1.a0 = 2.f / slap_1.xg2; slap_1.a2 = -slap_1.gamm1 / denom2; slap_1.a1 = slap_1.xg2 * slap_1.gamma / (slap_1.xgeom * slap_1.gamm1 + 2.f) * ((slap_1.xgeom * (2.f - slap_1.gamma) - slap_1.omega) * 2.f / (slap_1.gamma * slap_1.xg2 * slap_1.xg2) - slap_1.a2); slap_1.a3 = (slap_1.xgeom - slap_1.omega) / denom2; slap_1.a4 = slap_1.xg2 * (slap_1.xgeom - slap_1.omega) * slap_1.a1 / denom3; slap_1.a5 = (slap_1.omega * slap_1.gamp1 - slap_1.xgeom * 2.f) / denom3; /* ..frequent combinations, kamm equations 33-37 */ slap_1.a_val__ = slap_1.xg2 * .25f * slap_1.gamp1; slap_1.b_val__ = slap_1.gpogm; slap_1.c_val__ = slap_1.xg2 * .5f * slap_1.gamma; slap_1.d_val__ = slap_1.xg2 * slap_1.gamp1 / (slap_1.xg2 * slap_1.gamp1 - (slap_1.xgeom * slap_1.gamm1 + 2.f) * 2.f); slap_1.e_val__ = (slap_1.xgeom * slap_1.gamm1 + 2.f) * .5f; /* ..evaluate the energy integrals */ /* ..the singular case can be done by hand; save some cpu cycles */ /* ..kamm equations 80, 81, and 85 */ if (slap_1.lsingular) { /* Computing 2nd power */ d__1 = slap_1.gamm1 * slap_1.xgeom + 2.f; eval2 = slap_1.gamp1 / (slap_1.xgeom * (d__1 * d__1)); eval1 = 2.f / slap_1.gamm1 * eval2; /* Computing 2nd power */ d__1 = slap_1.gamm1 * slap_1.xgeom + 2.f; alpha = slap_1.gpogm * pow_dd(&c_b52, &slap_1.xgeom) / (slap_1.xgeom * (d__1 * d__1)); if (static_cast<int>(slap_1.xgeom) != 1) { alpha *= 3.1415926535897932384626433832795029; } /* ..for the standard or vacuum cases */ /* ..v0 = post-shock origin v0 and vv = vacuum boundary vv */ /* ..set the radius corespondin to vv to zero for now */ /* ..kamm equations 18, and 28. */ } else { v0 = 2.f / (slap_1.xg2 * slap_1.gamma); slap_1.vv = 2.f / slap_1.xg2; slap_1.rvv = 0.; if (slap_1.lstandard) { vmin = v0; } if (slap_1.lvacuum) { vmin = slap_1.vv; } /* ..the first energy integral */ /* ..in the standard case the term (c_val*v - 1) might be singular at v=vmin */ if (slap_1.lstandard) { cmidp_1.gam_int__ = slap_1.a3 - slap_1.a2 * slap_1.xg2 - 1.f; if (cmidp_1.gam_int__ >= 0.) { qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1, static_cast<S_fp>(midpnt_)); } else { cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__)); qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1, static_cast<S_fp>(midpowl_)); } /* ..in the vacuum case the term (1 - c_val/gamma*v) might be singular at v=vmin */ } else if (slap_1.lvacuum) { cmidp_1.gam_int__ = slap_1.a5; if (cmidp_1.gam_int__ >= 0.) { qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1, static_cast<S_fp>(midpnt_)); } else { cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__)); qromo_(static_cast<D_fp>(efun01_), &vmin, &v2, &c_b53, &eval1, static_cast<S_fp>(midpowl2_)); } } /* ..the second energy integral */ /* ..in the standard case the term (c_val*v - 1) might be singular at v=vmin */ if (slap_1.lstandard) { cmidp_1.gam_int__ = slap_1.a3 - slap_1.a2 * slap_1.xg2 - 2.f; if (cmidp_1.gam_int__ >= 0.) { qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2, static_cast<S_fp>(midpnt_)); } else { cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__)); qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2, static_cast<S_fp>(midpowl_)); } /* ..in the vacuum case the term (1 - c_val/gamma*v) might be singular at v=vmin */ } else if (slap_1.lvacuum) { cmidp_1.gam_int__ = slap_1.a5; if (cmidp_1.gam_int__ >= 0.) { qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2, static_cast<S_fp>(midpnt_)); } else { cmidp_1.gam_int__ = fabs(static_cast<double>(cmidp_1.gam_int__)); qromo_(static_cast<D_fp>(efun02_), &vmin, &v2, &c_b53, &eval2, static_cast<S_fp>(midpowl2_)); } } /* ..kamm equations 57 and 58 for alpha, in a slightly different form. */ if (static_cast<int>(slap_1.xgeom) == 1) { alpha = eval1 * .5f + eval2 / slap_1.gamm1; } else { alpha = (slap_1.xgeom - 1.f) * 3.1415926535897932384626433832795029 * (eval1 + eval2 * 2.f / slap_1.gamm1); } } /* ..write what we have for the energy integrals */ if (true) { // s_wsfe(&io___42); // do_fio(&c__1, "xgeom =", (ftnlen) 7); // do_fio(&c__1, (char *) &slap_1.xgeom, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "eblast=", (ftnlen) 7); // do_fio(&c__1, (char *) &(*eblast), (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "omega =", (ftnlen) 7); // do_fio(&c__1, (char *) &slap_1.omega, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "alpha =", (ftnlen) 7); // do_fio(&c__1, (char *) &alpha, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "j1 =", (ftnlen) 7); // do_fio(&c__1, (char *) &eval1, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "j2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &eval2, (ftnlen) sizeof(sed_real)); // e_wsfe(); } /* write(6,87) omega,alpha */ /* ..immediate post-shock values */ /* ..kamm page 14 or equations 14, 16, 5, 13 */ /* ..r2 = shock position, u2 = shock speed, rho1 = pre-shock density, */ /* ..u2 = post-shock material speed, rho2 = post-shock density, */ /* ..p2 = post-shock pressure, e2 = post-shoock specific internal energy, */ /* ..and cs2 = post-shock sound speed */ d__1 = *eblast / (alpha * *rho0); d__2 = 1.f / slap_1.xg2; d__3 = 2.f / slap_1.xg2; slap_1.r2 = pow_dd(&d__1, &d__2) * pow_dd(time, &d__3); us = 2.f / slap_1.xg2 * slap_1.r2 / *time; d__1 = -slap_1.omega; rho1 = *rho0 * pow_dd(&slap_1.r2, &d__1); u2 = us * 2.f / slap_1.gamp1; rho2 = slap_1.gpogm * rho1; /* Computing 2nd power */ d__1 = us; p2 = rho1 * 2.f * (d__1 * d__1) / slap_1.gamp1; // e2 = p2 / (slap_1.gamm1 * rho2); // cs2 = sqrt(slap_1.gamma * p2 / rho2); /* ..find the radius corresponding to vv */ if (slap_1.lvacuum) { slap_1.vwant = slap_1.vv; slap_1.rvv = zeroin_(&c_b79, &slap_1.r2, static_cast<D_fp>(sed_r_find__), &c_b80); } // if (slap_1.lstandard) { // s_wsfe(&io___50); // do_fio(&c__1, "r2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &slap_1.r2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "rho2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &rho2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "u2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &u2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "e2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &e2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "p2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &p2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "cs2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &cs2, (ftnlen) sizeof(sed_real)); // e_wsfe(); // } // if (slap_1.lvacuum) { // s_wsfe(&io___51); // do_fio(&c__1, "rv =", (ftnlen) 7); // do_fio(&c__1, (char *) &slap_1.rvv, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "r2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &slap_1.r2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "rho2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &rho2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "u2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &u2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "e2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &e2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "p2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &p2, (ftnlen) sizeof(sed_real)); // do_fio(&c__1, "cs2 =", (ftnlen) 7); // do_fio(&c__1, (char *) &cs2, (ftnlen) sizeof(sed_real)); // e_wsfe(); // } /* ..now start the loop over spatial positions */ i__1 = *nstep; for (i__ = 1; i__ <= i__1; ++i__) { slap_1.rwant = xpos[i__]; /* ..if we are upstream from the shock front */ if (slap_1.rwant > slap_1.r2) { d__1 = -slap_1.omega; den[i__] = *rho0 * pow_dd(&slap_1.rwant, &d__1); vel[i__] = *vel0; pres[i__] = *pres0; ener[i__] = *ener0; cs[i__] = *cs0; /* ..if we are between the origin and the shock front */ /* ..find the correct similarity value for this radius in the standard or vacuum cases */ } else { if (slap_1.lstandard) { d__1 = v0 * .9f; vat = zeroin_(&d__1, &v2, static_cast<D_fp>(sed_v_find__), &c_b80); } else if (slap_1.lvacuum) { d__1 = slap_1.vv * 1.2f; vat = zeroin_(&v2, &d__1, static_cast<D_fp>(sed_v_find__), &c_b80); } /* ..the physical solution */ sedov_funcs__(&vat, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__); den[i__] = rho2 * g_fun__; vel[i__] = u2 * f_fun__; pres[i__] = p2 * h_fun__; ener[i__] = 0.f; cs[i__] = 0.f; if (den[i__] != 0.f) { ener[i__] = pres[i__] / (slap_1.gamm1 * den[i__]); cs[i__] = sqrt(static_cast<double>(slap_1.gamma * pres[i__] / den[i__])); } } /* ..end of loop over positions */ } return 0; } /* sed_1d__ */ sed_real efun01_(sed_real *v) { /* System generated locals */ sed_real ret_val, d__1, d__2; ret_val = 0; /* Builtin functions */ sed_real pow_dd(sed_real *, sed_real *); /* Local variables */ static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv; /* ..evaluates the first energy integrand, kamm equations 67 and 10. */ /* ..the (c_val*v - 1) term might be singular at v=vmin in the standard case. */ /* ..the (1 - c_val/gamma * v) term might be singular at v=vmin in the vacuum case. */ /* ..due care should be taken for these removable singularities by the integrator. */ /* ..declare the pass */ /* ..common block communication */ /* ..local variables */ /* ..go */ sedov_funcs__(v, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__); d__1 = slap_1.xgeom + 1.f; /* Computing 2nd power */ d__2 = *v; ret_val = dlamdv * pow_dd(&l_fun__, &d__1) * slap_1.gpogm * g_fun__ * (d__2 * d__2); return ret_val; } /* efun01_ */ sed_real efun02_(sed_real *v) { /* System generated locals */ sed_real ret_val, d__1; ret_val = 0; /* Builtin functions */ sed_real pow_dd(sed_real *, sed_real *); /* Local variables */ static sed_real z__; static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv; /* ..evaluates the second energy integrand, kamm equations 68 and 11. */ /* ..the (c_val*v - 1) term might be singular at v=vmin in the standard case. */ /* ..the (1 - c_val/gamma * v) term might be singular at v=vmin in the vacuum case. */ /* ..due care should be taken for these removable singularities by the integrator. */ /* ..declare the pass */ /* ..common block communication */ /* ..local variables */ /* ..go */ sedov_funcs__(v, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__); /* Computing 2nd power */ d__1 = slap_1.xgeom + 2.f - slap_1.omega; z__ = 8.f / (d__1 * d__1 * slap_1.gamp1); d__1 = slap_1.xgeom - 1.f; ret_val = dlamdv * pow_dd(&l_fun__, &d__1) * h_fun__ * z__; return ret_val; } /* efun02_ */ sed_real sed_v_find__(sed_real *v) { /* System generated locals */ sed_real ret_val; ret_val = 0; /* Local variables */ static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv; /* ..given corresponding physical distances, find the similarity variable v */ /* ..kamm equation 38 as a root find */ /* ..declare the pass */ /* ..common block communication */ /* ..local variables */ sedov_funcs__(v, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__); ret_val = slap_1.r2 * l_fun__ - slap_1.rwant; return ret_val; } /* sed_v_find__ */ sed_real sed_r_find__(sed_real *r__) { /* System generated locals */ sed_real ret_val; ret_val = 0; /* Local variables */ static sed_real f_fun__, g_fun__, h_fun__, l_fun__, dlamdv; /* ..given the similarity variable v, find the corresponding physical distance */ /* ..kamm equation 38 as a root find */ /* ..declare the pass */ /* ..common block communication */ /* ..local variables */ sedov_funcs__(&slap_1.vwant, &l_fun__, &dlamdv, &f_fun__, &g_fun__, &h_fun__); ret_val = slap_1.r2 * l_fun__ - *r__; return ret_val; } /* sed_r_find__ */ /* Subroutine */int sedov_funcs__(sed_real *v, sed_real *l_fun__, sed_real *dlamdv, sed_real *f_fun__, sed_real *g_fun__, sed_real *h_fun__) { /* System generated locals */ sed_real d__1, d__2, d__3; /* Builtin functions */ // sed_real pow_dd(sed_real *, sed_real *), _exp(sed_real); /* Local variables */ static sed_real y, z__, c2, c6, x1, x2, x3, x4, pp1, pp2, pp3, pp4, cbag, ebag, beta0, dx1dv, dx2dv, dx3dv, dx4dv, dpp2dv; /* ..given the similarity variable v, returns functions */ /* ..lambda, f, g, and h and the derivative of lambda with v dlamdv */ /* ..although the ordinary differential equations are analytic, */ /* ..the sedov _expressions appear to become singular for various */ /* ..combinations of parameters and at the lower limits of the integration */ /* ..range. all these singularies are removable and done so by this routine. */ /* ..declare the pass */ /* ..common block communication */ /* ..local variables */ /* ..frequent combinations and their derivative with v */ /* ..kamm equation 29-32, x4 a bit different to save a divide */ /* ..x1 is book's F */ x1 = slap_1.a_val__ * *v; dx1dv = slap_1.a_val__; /* Computing MAX */ d__1 = 1e-30, d__2 = slap_1.c_val__ * *v - 1.f; cbag = fmax(static_cast<double>(d__1), static_cast<double>(d__2)); x2 = slap_1.b_val__ * cbag; dx2dv = slap_1.b_val__ * slap_1.c_val__; ebag = 1.f - slap_1.e_val__ * *v; x3 = slap_1.d_val__ * ebag; dx3dv = -slap_1.d_val__ * slap_1.e_val__; x4 = slap_1.b_val__ * (1.f - slap_1.xg2 * .5f * *v); dx4dv = -slap_1.b_val__ * .5f * slap_1.xg2; /* ..transition region between standard and vacuum cases */ /* ..kamm page 15 or equations 88-92 */ /* ..lambda = l_fun is book's zeta */ /* ..f_fun is books V, g_fun is book's D, h_fun is book's P */ if (slap_1.lsingular) { *l_fun__ = slap_1.rwant / slap_1.r2; *dlamdv = 0.f; *f_fun__ = *l_fun__; d__1 = slap_1.xgeom - 2.f; *g_fun__ = pow_dd(l_fun__, &d__1); *h_fun__ = pow_dd(l_fun__, &slap_1.xgeom); /* ..for the vacuum case in the hole */ } else if (slap_1.lvacuum && slap_1.rwant < slap_1.rvv) { *l_fun__ = 0.f; *dlamdv = 0.f; *f_fun__ = 0.f; *g_fun__ = 0.f; *h_fun__ = 0.f; /* ..omega = omega2 = (2*(gamma -1) + xgeom)/gamma case, denom2 = 0 */ /* ..book _expressions 20-22 */ } else if (slap_1.lomega2) { beta0 = 1.f / (slap_1.e_val__ * 2.f); pp1 = slap_1.gamm1 * beta0; c6 = slap_1.gamp1 * .5f; c2 = c6 / slap_1.gamma; y = 1.f / (x1 - c2); z__ = (1.f - x1) * y; pp2 = slap_1.gamp1 * beta0 * z__; dpp2dv = -slap_1.gamp1 * beta0 * dx1dv * y * (z__ + 1.f); pp3 = (4.f - slap_1.xgeom - slap_1.gamma * 2.f) * beta0; pp4 = -slap_1.xgeom * slap_1.gamma * beta0; d__1 = -slap_1.a0; *l_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp1) * _exp(pp2); *dlamdv = (-slap_1.a0 * dx1dv / x1 + pp1 * dx2dv / x2 + dpp2dv) * *l_fun__; *f_fun__ = x1 * *l_fun__; d__1 = slap_1.a0 * slap_1.omega; *g_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp3) * pow_dd(&x4, & slap_1.a5) * _exp(pp2 * -2.f); d__1 = slap_1.a0 * slap_1.xgeom; d__2 = slap_1.a5 + 1.f; *h_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp4) * pow_dd(&x4, &d__2); /* ..omega = omega3 = xgeom*(2 - gamma) case, denom3 = 0 */ /* ..book _expressions 23-25 */ } else if (slap_1.lomega3) { beta0 = 1.f / (slap_1.e_val__ * 2.f); pp1 = slap_1.a3 + slap_1.omega * slap_1.a2; pp2 = 1.f - beta0 * 4.f; c6 = slap_1.gamp1 * .5f; pp3 = -slap_1.xgeom * slap_1.gamma * slap_1.gamp1 * beta0 * (1.f - x1) / (c6 - x1); pp4 = (slap_1.xgeom * slap_1.gamm1 - slap_1.gamma) * 2.f * beta0; d__1 = -slap_1.a0; d__2 = -slap_1.a2; d__3 = -slap_1.a1; *l_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &d__2) * pow_dd(&x4, &d__3); *dlamdv = -(slap_1.a0 * dx1dv / x1 + slap_1.a2 * dx2dv / x2 + slap_1.a1 * dx4dv / x4) * *l_fun__; *f_fun__ = x1 * *l_fun__; d__1 = slap_1.a0 * slap_1.omega; *g_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &pp1) * pow_dd(&x4, &pp2) * _exp(pp3); d__1 = slap_1.a0 * slap_1.xgeom; *h_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x4, &pp4) * _exp(pp3); /* ..for the standard or vacuum case not in the hole */ /* ..kamm equations 38-41 */ } else { d__1 = -slap_1.a0; d__2 = -slap_1.a2; d__3 = -slap_1.a1; *l_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &d__2) * pow_dd(&x3, &d__3); *dlamdv = -(slap_1.a0 * dx1dv / x1 + slap_1.a2 * dx2dv / x2 + slap_1.a1 * dx3dv / x3) * *l_fun__; *f_fun__ = x1 * *l_fun__; d__1 = slap_1.a0 * slap_1.omega; d__2 = slap_1.a3 + slap_1.a2 * slap_1.omega; d__3 = slap_1.a4 + slap_1.a1 * slap_1.omega; *g_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x2, &d__2) * pow_dd(&x3, &d__3) * pow_dd(&x4, &slap_1.a5); d__1 = slap_1.a0 * slap_1.xgeom; d__2 = slap_1.a4 + slap_1.a1 * (slap_1.omega - 2.f); d__3 = slap_1.a5 + 1.f; *h_fun__ = pow_dd(&x1, &d__1) * pow_dd(&x3, &d__2) * pow_dd(&x4, &d__3); } return 0; } /* sedov_funcs__ */ /* Subroutine */int midpnt_(D_fp func, sed_real *a, sed_real *b, sed_real *s, int *n) { /* System generated locals */ int i__1; sed_real d__1; /* Builtin functions */ int pow_ii(int *, int *); /* Local variables */ static int j; static sed_real x; static int it; static sed_real del, tnm, sum, ddel; /* ..this routine computes the n'th stage of refinement of an extended midpoint */ /* ..rule. func is input as the name of the function to be integrated between */ /* ..limits a and b. when called with n=1, the routine returns as s the crudest */ /* ..estimate of the integralof func from a to b. subsequent calls with n=2,3... */ /* ..improve the accuracy of s by adding 2/3*3**(n-1) addtional interior points. */ /* ..declare */ if (*n == 1) { d__1 = (*a + *b) * .5f; *s = (*b - *a) * (*func)(&d__1); } else { i__1 = *n - 2; it = pow_ii(&c__3, &i__1); tnm = static_cast<sed_real>(it); del = (*b - *a) / (tnm * 3.f); ddel = del + del; x = *a + del * .5f; sum = 0.f; i__1 = it; for (j = 1; j <= i__1; ++j) { sum += (*func)(&x); x += ddel; sum += (*func)(&x); x += del; } *s = (*s + (*b - *a) * sum / tnm) / 3.f; } return 0; } /* midpnt_ */ /* Subroutine */int midpowl_(D_fp funk, sed_real *aa, sed_real *bb, sed_real *s, int *n) { /* System generated locals */ int i__1; sed_real d__1, d__2, d__3, d__4; /* Builtin functions */ sed_real pow_dd(sed_real *, sed_real *); int pow_ii(int *, int *); /* Local variables */ static sed_real a, b; static int j; static sed_real x; static int it; static sed_real del, tnm, sum, ddel; /* ..this routine is an exact replacement for midpnt, except that it allows for */ /* ..an integrable power-law singularity of the form (x - a)**(-gam_int) */ /* ..at the lower limit aa for 0 < gam_int < 1. */ /* ..declare */ /* ..common block communication */ /* ..a little conversion, recipe equation 4.4.3 */ d__1 = *bb - *aa; d__2 = 1.f - cmidp_1.gam_int__; b = pow_dd(&d__1, &d__2); a = 0.f; /* ..now exactly as midpnt */ if (*n == 1) { d__1 = (a + b) * .5f; d__2 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__); d__4 = 1.f / (1.f - cmidp_1.gam_int__); d__3 = pow_dd(&d__1, &d__4) + *aa; *s = (b - a) * (1.f / (1.f - cmidp_1.gam_int__) * pow_dd(&d__1, &d__2) * (*funk)(&d__3)); } else { i__1 = *n - 2; it = pow_ii(&c__3, &i__1); tnm = static_cast<sed_real>(it); del = (b - a) / (tnm * 3.f); ddel = del + del; x = a + del * .5f; sum = 0.f; i__1 = it; for (j = 1; j <= i__1; ++j) { d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__); d__3 = 1.f / (1.f - cmidp_1.gam_int__); d__2 = pow_dd(&x, &d__3) + *aa; sum += 1.f / (1.f - cmidp_1.gam_int__) * pow_dd(&x, &d__1) * (*funk)(&d__2); x += ddel; d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__); d__3 = 1.f / (1.f - cmidp_1.gam_int__); d__2 = pow_dd(&x, &d__3) + *aa; sum += 1.f / (1.f - cmidp_1.gam_int__) * pow_dd(&x, &d__1) * (*funk)(&d__2); x += del; } *s = (*s + (b - a) * sum / tnm) / 3.f; } return 0; } /* midpowl_ */ /* Subroutine */int midpowl2_(D_fp funk, sed_real *aa, sed_real *bb, sed_real *s, int *n) { /* System generated locals */ int i__1; sed_real d__1, d__2, d__3, d__4; /* Builtin functions */ /* Local variables */ static sed_real a, b; static int j; static sed_real x; static int it; static sed_real del, tnm, sum, ddel; /* ..this routine is an exact replacement for midpnt, except that it allows for */ /* ..an integrable power-law singularity of the form (a - x)**(-gam_int) */ /* ..at the lower limit aa for 0 < gam_int < 1. */ /* ..declare */ /* ..common block communication */ /* ..a little conversion, modulo recipe equation 4.4.3 */ d__1 = *aa - *bb; d__2 = 1.f - cmidp_1.gam_int__; b = pow_dd(&d__1, &d__2); a = 0.f; /* ..now exactly as midpnt */ if (*n == 1) { d__1 = (a + b) * .5f; d__2 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__); d__4 = 1.f / (1.f - cmidp_1.gam_int__); d__3 = *aa - pow_dd(&d__1, &d__4); *s = (b - a) * (1.f / (cmidp_1.gam_int__ - 1.f) * pow_dd(&d__1, &d__2) * (*funk)(&d__3)); } else { i__1 = *n - 2; it = pow_ii(&c__3, &i__1); tnm = static_cast<sed_real>(it); del = (b - a) / (tnm * 3.f); ddel = del + del; x = a + del * .5f; sum = 0.f; i__1 = it; for (j = 1; j <= i__1; ++j) { d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__); d__3 = 1.f / (1.f - cmidp_1.gam_int__); d__2 = *aa - pow_dd(&x, &d__3); sum += 1.f / (cmidp_1.gam_int__ - 1.f) * pow_dd(&x, &d__1) * (*funk)(&d__2); x += ddel; d__1 = cmidp_1.gam_int__ / (1.f - cmidp_1.gam_int__); d__3 = 1.f / (1.f - cmidp_1.gam_int__); d__2 = *aa - pow_dd(&x, &d__3); sum += 1.f / (cmidp_1.gam_int__ - 1.f) * pow_dd(&x, &d__1) * (*funk)(&d__2); x += del; } *s = (*s + (b - a) * sum / tnm) / 3.f; } return 0; } /* midpowl2_ */ /* Subroutine */int qromo_(D_fp func, sed_real *a, sed_real *b, sed_real *eps, sed_real *ss, S_fp choose) { /* Builtin functions */ /* Local variables */ static sed_real h__[15]; static int j; static sed_real s[15], dss; /* Fortran I/O blocks */ /* ..this routine returns as s the integral of the function func from a to b */ /* ..with fractional accuracy eps. *//* ..jmax limits the number of steps; nsteps = 3**(jmax-1) */ /* ..integration is done via romberg algorithm. */ /* ..it is assumed the call to choose triples the number of steps on each call */ /* ..and that its error series contains only even powers of the number of steps. */ /* ..the external choose may be any of the above drivers, i.e midpnt,midinf... */ /* ..declare */ h__[0] = 1.f; for (j = 1; j <= 14; ++j) { (*choose)(static_cast<D_fp>(func), a, b, &s[j - 1], &j); if (j >= 5) { polint_(&h__[j - 5], &s[j - 5], &c__5, &c_b79, ss, &dss); if (fabs(static_cast<double>(dss)) <= *eps * fabs(static_cast<double>(*ss))) { return 0; } } s[j] = s[j - 1]; h__[j] = h__[j - 1] / 9.f; } return 0; } /* qromo_ */ /* Subroutine */int polint_(sed_real *xa, sed_real *ya, int *n, sed_real *x, sed_real *y, sed_real *dy) { /* System generated locals */ int i__1, i__2; sed_real d__1; /* Local variables */ static sed_real c__[20], d__[20]; static int i__, m; static sed_real w, ho, hp; static int ns; static sed_real dif, den, dift; /* ..given arrays xa and ya of length n and a value x, this routine returns a */ /* ..value y and an error estimate dy. if p(x) is the polynomial of degree n-1 */ /* ..such that ya = p(xa) ya then the returned value is y = p(x) */ /* ..declare */ /* ..find the index ns of the closest table entry; initialize the c and d tables */ /* Parameter adjustments */ --ya; --xa; /* Function Body */ ns = 1; dif = (d__1 = *x - xa[1], fabs(static_cast<double>(d__1))); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dift = (d__1 = *x - xa[i__], fabs(static_cast<double>(d__1))); if (dift < dif) { ns = i__; dif = dift; } c__[i__ - 1] = ya[i__]; d__[i__ - 1] = ya[i__]; } /* ..first guess for y */ *y = ya[ns]; /* ..for each column of the table, loop over the c's and d's and update them */ --ns; i__1 = *n - 1; for (m = 1; m <= i__1; ++m) { i__2 = *n - m; for (i__ = 1; i__ <= i__2; ++i__) { ho = xa[i__] - *x; hp = xa[i__ + m] - *x; w = c__[i__] - d__[i__ - 1]; den = ho - hp; if (den == 0.f) { // s_stop(" 2 xa entries are the same in polint", (ftnlen) 36); } den = w / den; d__[i__ - 1] = hp * den; c__[i__ - 1] = ho * den; } /* ..after each column is completed, decide which correction c or d, to add */ /* ..to the accumulating value of y, that is, which path to take in the table */ /* ..by forking up or down. ns is updated as we go to keep track of where we */ /* ..are. the last dy added is the error indicator. */ if (ns << 1 < *n - m) { *dy = c__[ns]; } else { *dy = d__[ns - 1]; --ns; } *y += *dy; } return 0; } /* polint_ */ sed_real zeroin_(sed_real *ax, sed_real *bx, D_fp f, sed_real *tol) { /* System generated locals */ sed_real ret_val, d__1; ret_val = 0; /* Local variables */ static sed_real a, b, c__, d__, e, p, q, r__, s, fa, fb, fc, xm, eps, tol1; /* ----------------------------------------------------------------------- */ /* This subroutine solves for a zero of the function f(x) in the */ /* interval ax,bx. */ /* input.. */ /* ax left endpoint of initial interval */ /* bx right endpoint of initial interval */ /* f function subprogram which evaluates f(x) for any x in */ /* the interval ax,bx */ /* tol desired length of the interval of uncertainty of the */ /* final result ( .ge. 0.0) */ /* output.. */ /* zeroin abcissa approximating a zero of f in the interval ax,bx */ /* it is assumed that f(ax) and f(bx) have opposite signs */ /* without a check. zeroin returns a zero x in the given interval */ /* ax,bx to within a tolerance 4*macheps*fabs(x) + tol, where macheps */ /* is the relative machine precision. */ /* this function subprogram is a slightly modified translation of */ /* the algol 60 procedure zero given in richard brent, algorithms for */ /* minimization without derivatives, prentice - hall, inc. (1973). */ /* ----------------------------------------------------------------------- */ /* .... call list variables */ /* ---------------------------------------------------------------------- */ /* compute eps, the relative machine precision */ eps = 1.f; L10: eps /= 2.f; tol1 = eps + 1.f; if (tol1 > 1.f) { goto L10; } /* initialization */ a = *ax; b = *bx; fa = (*f)(&a); fb = (*f)(&b); /* begin step */ L20: c__ = a; fc = fa; d__ = b - a; e = d__; L30: if (fabs(static_cast<double>(fc)) >= fabs(static_cast<double>(fb))) { goto L40; } a = b; b = c__; c__ = a; fa = fb; fb = fc; fc = fa; /* convergence test */ L40: tol1 = eps * 2.f * fabs(static_cast<double>(b)) + *tol * .5f; xm = (c__ - b) * .5f; if (fabs(static_cast<double>(xm)) <= tol1) { goto L90; } if (fb == 0.f) { goto L90; } /* is bisection necessary? */ if (fabs(static_cast<double>(e)) < tol1) { goto L70; } if (fabs(static_cast<double>(fa)) <= fabs(static_cast<double>(fb))) { goto L70; } /* is quadratic interpolation possible? */ if (a != c__) { goto L50; } /* linear interpolation */ s = fb / fa; p = xm * 2.f * s; q = 1.f - s; goto L60; /* inverse quadratic interpolation */ L50: q = fa / fc; r__ = fb / fc; s = fb / fa; p = s * (xm * 2.f * q * (q - r__) - (b - a) * (r__ - 1.f)); q = (q - 1.f) * (r__ - 1.f) * (s - 1.f); /* adjust signs */ L60: if (p > 0.f) { q = -q; } p = fabs(static_cast<double>(p)); /* is interpolation acceptable? */ if (p * 2.f >= xm * 3.f * q - (d__1 = tol1 * q, fabs(static_cast<double>(d__1)))) { goto L70; } if (p >= (d__1 = e * .5f * q, fabs(static_cast<double>(d__1)))) { goto L70; } e = d__; d__ = p / q; goto L80; /* bisection */ L70: d__ = xm; e = d__; /* complete step */ L80: a = b; fa = fb; if (fabs(static_cast<double>(d__)) > tol1) { b += d__; } if (fabs(static_cast<double>(d__)) <= tol1) { b += d_sign(&tol1, &xm); } fb = (*f)(&b); if (fb * (fc / fabs(static_cast<double>(fc))) > 0.f) { goto L20; } goto L30; /* done */ L90: ret_val = b; return ret_val; } /* zeroin_ */ #include <functional> #include <mutex> #ifndef NO_HPX #include <hpx/synchronization/spinlock.hpp> using mutex_type = hpx::lcos::local::spinlock; #else #include <unordered_map> #include <memory> #include <cassert> using mutex_type = std::mutex; #endif namespace sedov { void solution(double time, double r, double rmax, double& d, double& v, double& p, int ndim) { int nstep = 10000; constexpr int bw = 2; using function_type = std::function<void(double,double&,double&,double&)>; using map_type = std::unordered_map<double,std::shared_ptr<function_type>>; static map_type map; static mutex_type mutex; sed_real rho0 = 1.0; sed_real vel0 = 0.0; sed_real ener0 = 0.0; sed_real pres0 = 0.0; sed_real cs0 = 0.0; sed_real gamma = 7.0/5.0; sed_real omega = 0.0; sed_real eblast = 1.0; sed_real xgeom = sed_real(ndim); std::vector<sed_real> xpos(nstep+2*bw); std::vector<sed_real> den(nstep+2*bw); std::vector<sed_real> ener(nstep+2*bw); std::vector<sed_real> pres(nstep+2*bw); std::vector<sed_real> vel(nstep+2*bw); std::vector<sed_real> cs(nstep+2*bw); std::vector<double> den1(nstep+2*bw); std::vector<double> pres1(nstep+2*bw); std::vector<double> vel1(nstep+2*bw); std::shared_ptr<function_type> ptr; for( int i = 0; i < nstep + 2*bw; i++) { xpos[i] = (i - bw + 0.5)*rmax/(nstep); } nstep += bw; std::unique_lock<mutex_type> lock(mutex); auto iter = map.find(time); if (iter == map.end()) { sed_real sed_time = time; printf( "Computing sedov solution\n"); sed_1d__(&sed_time, &nstep, xpos.data() + bw, &eblast, &omega, &xgeom, &rho0, &vel0, &ener0, &pres0, &cs0, &gamma, den.data() + bw, ener.data() + bw, pres.data() + bw, vel.data() + bw, cs.data() + bw); xpos[0] = -xpos[3]; den[0] = den[3]; ener[0] = ener[3]; pres[0] = pres[3]; vel[0] = -vel[3]; cs[0] = cs[3]; xpos[1] = -xpos[2]; den[1] = den[2]; ener[1] = ener[2]; pres[1] = pres[2]; vel[1] = -vel[2]; cs[1] = cs[2]; #if defined(OCTOTIGER_HAVE_BOOST_MULTIPRECISION) std::transform(den.begin(), den.end(), den1.begin(), [](sed_real v) { return v.convert_to<double>(); }); std::transform(vel.begin(), vel.end(), vel1.begin(), [](sed_real v) { return v.convert_to<double>(); }); std::transform(pres.begin(), pres.end(), pres1.begin(), [](sed_real v) { return v.convert_to<double>(); }); #else std::copy(den.begin(), den.end(), den1.begin()); std::copy(vel.begin(), vel.end(), vel1.begin()); std::copy(pres.begin(), pres.end(), pres1.begin()); #endif function_type func = [nstep,rmax,den1,pres1,vel1,bw](double r, double& d, double& v, double & p) { double dr = rmax / (nstep); std::array<int,4> i; i[1] = (r + (bw - 0.5)*dr) / dr; i[0] = i[1] - 1; i[2] = i[1] + 1; i[3] = i[1] + 2; double r0 = (r - (i[1]-bw + 0.5)*dr)/dr; // printf( "%i %e\n", i[0], r, dr ); assert( i[0] >= 0 ); assert( i[3] < int(vel1.size())); const auto interp = [r0,i](const std::vector<double>& data) { double sum = 0.0; sum += (-0.5 * data[i[0]] + 1.5 * data[i[1]] - 1.5 * data[i[2]] + 0.5 * data[i[3]]) * r0 * r0 * r0; sum += (+1.0 * data[i[0]] - 2.5 * data[i[1]] + 2.0 * data[i[2]] - 0.5 * data[i[3]]) * r0 * r0; sum += (-0.5 * data[i[0]] + 0.5 * data[i[2]]) * r0; sum += data[i[1]]; return sum; }; d = interp(den1); v = interp(vel1); p = interp(pres1); }; ptr = std::make_shared<function_type>(std::move(func)); map[time] = ptr; lock.unlock(); } else { lock.unlock(); ptr = iter->second; } const auto& func = *(ptr); func(r, d, v, p); } }
--- layout: archive permalink: /contact/ description: "Qi Yu - Ph.D. Candidate in Marketing at Wharton" author_profile: true redirect_from: - /contact.html --- **Email** qiyu@wharton.upenn.edu **Address** 700 Jon M. Huntsman Hall 3730 Walnut Street Philadelphia, PA 19104
namespace MassTransit.AzureServiceBusTransport.Configuration { public interface IServiceBusReceiveEndpointConfiguration : IServiceBusEntityEndpointConfiguration { ReceiveSettings Settings { get; } } }
package frc.robot.subsystems.drive; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import frc.robot.config.Config; import frc.robot.subsystems.BitBucketsSubsystem; import frc.robot.utils.DashboardConfig; public class DriveSubsystem extends BitBucketsSubsystem{ public DriveSubsystem(Config config, DashboardConfig dashboardConfig) { super(config, dashboardConfig); //TODO Auto-generated constructor stub } private WPI_TalonSRX leftDriveLeader; private WPI_TalonSRX rightDriveLeader; private WPI_TalonSRX rightDriveFollower; private WPI_TalonSRX leftDriveFollower; private DifferentialDrive differentialDrive; @Override public void init() { rightDriveLeader = new WPI_TalonSRX(config.RIGHT_DRIVE_LEADER_ID); leftDriveLeader = new WPI_TalonSRX(config.LEFT_DRIVE_LEADER_ID); rightDriveFollower = new WPI_TalonSRX(config.RIGHT_DRIVE_FOLLOWER_ID); leftDriveFollower = new WPI_TalonSRX(config.LEFT_DRIVE_FOLLOWER_ID); //rightDriveLeader.setInverted(true); rightDriveFollower.follow(rightDriveLeader); leftDriveFollower.follow(leftDriveLeader); //DifferentialDrive m_drive = new DifferentialDrive(leftDriveLeader, rightDriveLeader); } public void prevent(double leftStick, double rightStick){ leftStick = Math.abs(leftStick); rightStick = Math.abs(rightStick); } @Override protected void addMotorsToList() { // TODO Auto-generated method stub } @Override public void periodic() { // TODO Auto-generated method stub } @Override public void disable() { // TODO Auto-generated method stub } double slowdown = 0.5; public void drive(double speed, double turn) { leftDriveLeader.set(ControlMode.PercentOutput, (speed + turn) * slowdown); rightDriveLeader.set(ControlMode.PercentOutput, (speed - turn) * -1 * slowdown); } }
package org.mintflow.handler.sync; import org.mintflow.handler.HandlerType; import org.mintflow.param.ParamWrapper; import org.mintflow.scheduler.sync.SyncScheduler; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Reorder Handler -> used to sub-pack all washable handle components */ public abstract class SyncReorderFnHandler extends SyncToolsFnHandler { public SyncReorderFnHandler(String name){ this(name, HandlerType.REORDER_HANDLE_SYNC); } private SyncReorderFnHandler(String name, HandlerType handleType) { super(name, handleType); } public void addChilds(SyncFnHandler... fnHandlers) { this.getSyncChildren().addAll(Arrays.asList(fnHandlers)); } public void addChilds(List<SyncFnHandler> fnHandlers) { this.getSyncChildren().addAll(fnHandlers); } @Override public final ParamWrapper handle(ParamWrapper paramWrapper, SyncScheduler syncScheduler) { if (this.getSyncChildren() == null || this.getSyncChildren().size() == 0) { return paramWrapper; } if (syncScheduler != null) { List<SyncFnHandler> newFnHandlerList = new ArrayList<>(this.getSyncChildren()); reorderHandlerList(paramWrapper,newFnHandlerList); return syncScheduler.run(paramWrapper, newFnHandlerList); } else { return paramWrapper; } } public abstract void reorderHandlerList(ParamWrapper paramWrapper,List<SyncFnHandler> fnHandlers); }
require 'rails_helper' RSpec.describe Filter::Resource::Contact do include SomlengScfm::SpecHelpers::FilterHelpers let(:filterable_factory) { :contact } let(:association_chain) { Contact } describe "#resources" do include_examples "metadata_attribute_filter" include_examples "msisdn_attribute_filter" include_examples "timestamp_attribute_filter" end end
require 'rspec' require 'krypt-core' describe Krypt::Digest do describe Krypt::Digest::SHA1 do subject { Krypt::Digest::SHA1.new } describe '#hexdigest' do it "should calculate SHA1" do subject.hexdigest('hello,world').should == '74f4f4eb1947b9ca08e5e68d04d081808777f9a0' end end end end
#### Parser Content ```Java { Name = windows-rdp-login Vendor = Microsoft Product = Windows Lms = Splunk DataType = "remote-logon" TimeFormat = "yyyy-MM-dd'T'HH:mm:ss" Conditions = [ """Microsoft-Windows-TerminalServices-LocalSessionManager""", """<EventID>21<""" ] Fields = [ """exabeam_host=({host}[\w\-.]{1,2000})""", """<TimeCreated SystemTime=('+|"{1,20})({time}\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d)""", """<EventID>({event_code}\d{1,100})<""", """<Execution ProcessID='({process_id}\d{1,100})'\s{1,100}ThreadID='({thread_id}\d{1,100})'""", """<Computer>({dest_host}[^<]{1,2000})<""", """<Security UserID=('+|"{1,20})({user_sid}[^'"]{1,2000})'""", """<User>(({domain}\S+)\\+)?({user}[^<]{1,2000})<""", """<SessionID>({session_id}\d{1,100})<""", """<Address>({src_ip}[a-fA-F\d.-]{1,2000})<""", ] } ```
: ' 20282. Game Show! 작성자: xCrypt0r 언어: Bash 사용 메모리: 18,280 KB 소요 시간: 16 ms 해결 날짜: 2021년 11월 10일 ' main() { local C V local sum=0 res=0 read C for (( i = 0; i < C; i++ )); do read V (( sum += V )) (( sum > res )) && res=$sum done echo $(( res + 100 )) } main
getClosing :: Char -> Char getClosing '(' = ')' getClosing c = c isOpening :: Char -> Bool isOpening c | c == '(' = True | otherwise = False checkBrackets :: String -> Bool checkBrackets str = check str [] where check :: String -> String -> Bool check [] [] = True check [] (top : bottom) = False check (x : xs) [] | not (isOpening x) = False | otherwise = check xs [x] check (x : xs) stack@(top : bottom) | isOpening x = check xs ((getClosing x) : stack) | getClosing x == top = check xs bottom
fun f() = IntArray(1) { run { return@IntArray 1 } } // On JVM_IR, the return is an assignment to a captured var followed by // a non-local `break` from a `do ... while (false)`. The var should be optimized. // 0 IntRef
--- title: What is Alameda? description: Context about what problems Alameda is designed to solve. weight: 1 --- Alameda is an open platform ...
package com.reactmq.queue import akka.actor.Actor.Receive import akka.persistence.RecoveryCompleted import com.reactmq.Logging trait QueueActorRecover extends Logging { this: QueueActorStorage => def handleQueueEvent: Receive = { case MessageAdded(id, nextDelivery, content) => messagesById(id) = InternalMessage(id, nextDelivery, content) case MessageNextDeliveryUpdated(id, nextDelivery) => messagesById.get(id).foreach(_.nextDelivery = nextDelivery) case MessageDeleted(id) => messagesById.remove(id) case RecoveryCompleted => messageQueue ++= messagesById.values logger.info(s"Recovered ${messagesById.size} messages.") } }