repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ipsod/psml
examples/attic/dice.py
import sys sys.path.append( "../psml" ) from psml import * def dice_text1( n, t, f, r ): return ( shift( n / 2.0, n / 2.0, 0 ) ** extrude( 1 ) ** text( t, ( ( n - r ) * f ) / 100 ), halign = "center", valign = "center") def dice_text2( n, t1, t2, f, r ): return ( shift( n / 2.0, 7.0 * n / 10.0, 0 ) ** extrude( 1 ) ** text( t1, ( ( n - r ) * f ) / 100 ) + shift( n / 2.0, 3.5 * n / 10.0, 0 ) ** extrude( 1 ) ** text( t2, ( ( n - r ) * f ) / 100 ) ) def dice( s, r = 0 ): return box( dup3( s ), r) - ( shift( s, 0, 0 ) ** mirror( 1, 0, 0 ) ** dice_text1( s, "TI", 62, r ) + shift( s, s - 1, 0 ) ** rotate( 90, 0, 180 ) ** dice_text1( s, "CSC", 25, r ) + shift( s - 1, 0, s ) ** rotate( 0, 90, 0 ) ** dice_text1( s, "SD", 38, r ) + shift( 1, 0, 0 ) ** rotate( 0, -90, 0 ) ** dice_text1( s, "BIM", 32, r ) + shift( 0, 1, 0 ) ** rotate( [ 90, 0, 0 ] ) ** dice_text1( s, "AI", 65, r ) + shift( 0, 0, s - 1 ) ** dice_text2( s, "Open", "ICT", 22, r ) ) dice( 30, 3 ).write()
sebtelko/pulumi-azure-native
sdk/go/azure/hardwaresecuritymodules/dedicatedHsm.go
<filename>sdk/go/azure/hardwaresecuritymodules/dedicatedHsm.go<gh_stars>0 // *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package hardwaresecuritymodules import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Resource information with extended details. // API Version: 2018-10-31-preview. type DedicatedHsm struct { pulumi.CustomResourceState // The supported Azure location where the dedicated HSM should be created. Location pulumi.StringOutput `pulumi:"location"` // The name of the dedicated HSM. Name pulumi.StringOutput `pulumi:"name"` // Specifies the network interfaces of the dedicated hsm. NetworkProfile NetworkProfileResponsePtrOutput `pulumi:"networkProfile"` // Provisioning state. ProvisioningState pulumi.StringOutput `pulumi:"provisioningState"` // SKU details Sku SkuResponseOutput `pulumi:"sku"` // This field will be used when RP does not support Availability zones. StampId pulumi.StringPtrOutput `pulumi:"stampId"` // Resource Status Message. StatusMessage pulumi.StringOutput `pulumi:"statusMessage"` // Resource tags Tags pulumi.StringMapOutput `pulumi:"tags"` // The resource type of the dedicated HSM. Type pulumi.StringOutput `pulumi:"type"` // The Dedicated Hsm zones. Zones pulumi.StringArrayOutput `pulumi:"zones"` } // NewDedicatedHsm registers a new resource with the given unique name, arguments, and options. func NewDedicatedHsm(ctx *pulumi.Context, name string, args *DedicatedHsmArgs, opts ...pulumi.ResourceOption) (*DedicatedHsm, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.ResourceGroupName == nil { return nil, errors.New("invalid value for required argument 'ResourceGroupName'") } if args.Sku == nil { return nil, errors.New("invalid value for required argument 'Sku'") } aliases := pulumi.Aliases([]pulumi.Alias{ { Type: pulumi.String("azure-nextgen:hardwaresecuritymodules:DedicatedHsm"), }, { Type: pulumi.String("azure-native:hardwaresecuritymodules/v20181031preview:DedicatedHsm"), }, { Type: pulumi.String("azure-nextgen:hardwaresecuritymodules/v20181031preview:DedicatedHsm"), }, }) opts = append(opts, aliases) var resource DedicatedHsm err := ctx.RegisterResource("azure-native:hardwaresecuritymodules:DedicatedHsm", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetDedicatedHsm gets an existing DedicatedHsm resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetDedicatedHsm(ctx *pulumi.Context, name string, id pulumi.IDInput, state *DedicatedHsmState, opts ...pulumi.ResourceOption) (*DedicatedHsm, error) { var resource DedicatedHsm err := ctx.ReadResource("azure-native:hardwaresecuritymodules:DedicatedHsm", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering DedicatedHsm resources. type dedicatedHsmState struct { // The supported Azure location where the dedicated HSM should be created. Location *string `pulumi:"location"` // The name of the dedicated HSM. Name *string `pulumi:"name"` // Specifies the network interfaces of the dedicated hsm. NetworkProfile *NetworkProfileResponse `pulumi:"networkProfile"` // Provisioning state. ProvisioningState *string `pulumi:"provisioningState"` // SKU details Sku *SkuResponse `pulumi:"sku"` // This field will be used when RP does not support Availability zones. StampId *string `pulumi:"stampId"` // Resource Status Message. StatusMessage *string `pulumi:"statusMessage"` // Resource tags Tags map[string]string `pulumi:"tags"` // The resource type of the dedicated HSM. Type *string `pulumi:"type"` // The Dedicated Hsm zones. Zones []string `pulumi:"zones"` } type DedicatedHsmState struct { // The supported Azure location where the dedicated HSM should be created. Location pulumi.StringPtrInput // The name of the dedicated HSM. Name pulumi.StringPtrInput // Specifies the network interfaces of the dedicated hsm. NetworkProfile NetworkProfileResponsePtrInput // Provisioning state. ProvisioningState pulumi.StringPtrInput // SKU details Sku SkuResponsePtrInput // This field will be used when RP does not support Availability zones. StampId pulumi.StringPtrInput // Resource Status Message. StatusMessage pulumi.StringPtrInput // Resource tags Tags pulumi.StringMapInput // The resource type of the dedicated HSM. Type pulumi.StringPtrInput // The Dedicated Hsm zones. Zones pulumi.StringArrayInput } func (DedicatedHsmState) ElementType() reflect.Type { return reflect.TypeOf((*dedicatedHsmState)(nil)).Elem() } type dedicatedHsmArgs struct { // The supported Azure location where the dedicated HSM should be created. Location *string `pulumi:"location"` // Name of the dedicated Hsm Name *string `pulumi:"name"` // Specifies the network interfaces of the dedicated hsm. NetworkProfile *NetworkProfile `pulumi:"networkProfile"` // The name of the Resource Group to which the resource belongs. ResourceGroupName string `pulumi:"resourceGroupName"` // SKU details Sku Sku `pulumi:"sku"` // This field will be used when RP does not support Availability zones. StampId *string `pulumi:"stampId"` // Resource tags Tags map[string]string `pulumi:"tags"` // The Dedicated Hsm zones. Zones []string `pulumi:"zones"` } // The set of arguments for constructing a DedicatedHsm resource. type DedicatedHsmArgs struct { // The supported Azure location where the dedicated HSM should be created. Location pulumi.StringPtrInput // Name of the dedicated Hsm Name pulumi.StringPtrInput // Specifies the network interfaces of the dedicated hsm. NetworkProfile NetworkProfilePtrInput // The name of the Resource Group to which the resource belongs. ResourceGroupName pulumi.StringInput // SKU details Sku SkuInput // This field will be used when RP does not support Availability zones. StampId pulumi.StringPtrInput // Resource tags Tags pulumi.StringMapInput // The Dedicated Hsm zones. Zones pulumi.StringArrayInput } func (DedicatedHsmArgs) ElementType() reflect.Type { return reflect.TypeOf((*dedicatedHsmArgs)(nil)).Elem() } type DedicatedHsmInput interface { pulumi.Input ToDedicatedHsmOutput() DedicatedHsmOutput ToDedicatedHsmOutputWithContext(ctx context.Context) DedicatedHsmOutput } func (*DedicatedHsm) ElementType() reflect.Type { return reflect.TypeOf((*DedicatedHsm)(nil)) } func (i *DedicatedHsm) ToDedicatedHsmOutput() DedicatedHsmOutput { return i.ToDedicatedHsmOutputWithContext(context.Background()) } func (i *DedicatedHsm) ToDedicatedHsmOutputWithContext(ctx context.Context) DedicatedHsmOutput { return pulumi.ToOutputWithContext(ctx, i).(DedicatedHsmOutput) } type DedicatedHsmOutput struct { *pulumi.OutputState } func (DedicatedHsmOutput) ElementType() reflect.Type { return reflect.TypeOf((*DedicatedHsm)(nil)) } func (o DedicatedHsmOutput) ToDedicatedHsmOutput() DedicatedHsmOutput { return o } func (o DedicatedHsmOutput) ToDedicatedHsmOutputWithContext(ctx context.Context) DedicatedHsmOutput { return o } func init() { pulumi.RegisterOutputType(DedicatedHsmOutput{}) }
ganeshsp1/javaWebHook
src/main/java/vo/Contexts.java
package vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Contexts { private String name; private Parameters parameters; private String lifespan; public String getName () { return name; } public void setName (String name) { this.name = name; } public Parameters getParameters () { return parameters; } public void setParameters (Parameters parameters) { this.parameters = parameters; } public String getLifespan () { return lifespan; } public void setLifespan (String lifespan) { this.lifespan = lifespan; } @Override public String toString() { return "ClassPojo [name = "+name+", parameters = "+parameters+", lifespan = "+lifespan+"]"; } }
KASTKING/KASTKING-CLOUD1
kastking-salesforecast-server/src/main/java/com/kastking/warehouse/controller/WarehouseController.java
package com.kastking.warehouse.controller; import java.util.List; import com.kastking.warehouse.domain.Warehouse; import com.kastking.warehouse.service.IWarehouseService; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.kastking.common.annotation.Log; import com.kastking.common.enums.BusinessType; import com.kastking.common.core.controller.BaseController; import com.kastking.common.core.domain.AjaxResult; import com.kastking.common.utils.poi.ExcelUtil; import org.springframework.web.multipart.MultipartFile; import com.kastking.framework.util.ShiroUtils; import com.kastking.common.core.page.TableDataInfo; /** * 仓库Controller * * @author Michael * @date 2020-02-28 */ @Controller @RequestMapping("/salesForecast/warehouse") public class WarehouseController extends BaseController { private String prefix = "salesForecast/warehouse"; @Autowired private IWarehouseService warehouseService; @RequiresPermissions("salesForecast:warehouse:view") @GetMapping() public String warehouse() { return prefix + "/warehouse"; } /** * 查询仓库列表 */ @RequiresPermissions("salesForecast:warehouse:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(Warehouse warehouse) { startPage(); List<Warehouse> list = warehouseService.selectWarehouseList(warehouse); return getDataTable(list); } /** * 导入仓库列表 */ @RequiresPermissions("salesForecast:warehouse:import") @PostMapping("/importData") @ResponseBody public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { ExcelUtil<Warehouse> util = new ExcelUtil<Warehouse>(Warehouse.class); List<Warehouse> warehouseList = util.importExcel(file.getInputStream()); String operName = ShiroUtils.getSysUser().getLoginName(); String message = warehouseService.importWarehouse(warehouseList, updateSupport, operName); return AjaxResult.success(message); } /** * 导出仓库列表 */ @RequiresPermissions("salesForecast:warehouse:export") @Log(title = "仓库" , businessType = BusinessType.EXPORT) @PostMapping("/export") @ResponseBody public AjaxResult export(Warehouse warehouse) { List<Warehouse> list = warehouseService.selectWarehouseList(warehouse); ExcelUtil<Warehouse> util = new ExcelUtil<Warehouse>(Warehouse.class); return util.exportExcel(list, "warehouse"); } /** * 新增仓库 */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存仓库 */ @RequiresPermissions("salesForecast:warehouse:add") @Log(title = "仓库" , businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(Warehouse warehouse) { return toAjax(warehouseService.insertWarehouse(warehouse)); } /** * 详情仓库 */ @GetMapping("/detail/{warehouseId}") public String detail(@PathVariable("warehouseId") Long warehouseId, ModelMap mmap) { Warehouse warehouse = warehouseService.selectWarehouseById(warehouseId); mmap.put("warehouse" , warehouse); return prefix + "/detail"; } /** * 修改仓库 */ @GetMapping("/edit/{warehouseId}") public String edit(@PathVariable("warehouseId") Long warehouseId, ModelMap mmap) { Warehouse warehouse = warehouseService.selectWarehouseById(warehouseId); mmap.put("warehouse" , warehouse); return prefix + "/edit"; } /** * 修改保存仓库 */ @RequiresPermissions("salesForecast:warehouse:edit") @Log(title = "仓库" , businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(Warehouse warehouse) { return toAjax(warehouseService.updateWarehouse(warehouse)); } /** * 删除仓库 */ @RequiresPermissions("salesForecast:warehouse:remove") @Log(title = "仓库" , businessType = BusinessType.DELETE) @PostMapping("/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(warehouseService.deleteWarehouseByIds(ids)); } /** * 下载仓库模板 */ @RequiresPermissions("salesForecast:warehouse:view") @GetMapping("/importTemplate") @ResponseBody public AjaxResult importTemplate() { ExcelUtil<Warehouse> util = new ExcelUtil<Warehouse>(Warehouse.class); return util.importTemplateExcel("仓库数据"); } }
mailrest/maildal
src/main/java/com/mailrest/maildal/repository/MessageLogRepository.java
/* * Copyright (C) 2015 Noorq, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mailrest.maildal.repository; import static com.noorq.casser.core.Query.desc; import static com.noorq.casser.core.Query.eq; import static com.noorq.casser.core.Query.lt; import java.util.Date; import scala.collection.immutable.Stream; import scala.concurrent.Future; import com.datastax.driver.core.ResultSet; import com.mailrest.maildal.model.Message; import com.mailrest.maildal.model.MessageAction; import com.mailrest.maildal.model.MessageDelivery; import com.mailrest.maildal.model.MessageLog; import com.mailrest.maildal.model.MessageRecipient; import com.mailrest.maildal.model.MessageSender; import com.mailrest.maildal.support.MessageToHeadersAdapter; import com.noorq.casser.core.Casser; import com.noorq.casser.support.Timeuuid; public interface MessageLogRepository extends AbstractRepository { static final MessageLog messageLog = Casser.dsl(MessageLog.class); static final long ONE_DAY_MILLISECONDS = 24L * 3600L * 1000L; default Future<Stream<MessageLog>> findMessageLogs(DayRef dayRef, int max) { return session() .select(MessageLog.class) .where(messageLog::accountId, eq(dayRef.accountId())) .and(messageLog::domainId, eq(dayRef.domainId())) .and(messageLog::dayAt, eq(dayRef.dayAt())) .orderBy(desc(messageLog::eventAt)) .limit(max) .future(); } default Future<Stream<MessageLog>> findMessageLogs(DayRef dayRef, Date before, int max) { return session() .select(MessageLog.class) .where(messageLog::accountId, eq(dayRef.accountId())) .and(messageLog::domainId, eq(dayRef.domainId())) .and(messageLog::dayAt, eq(dayRef.dayAt())) .and(messageLog::eventAt, lt(before)) .orderBy(desc(messageLog::eventAt)) .limit(max) .future(); } default ResultSet logMessageDeliveryAttempt( Message message, MessageRecipient recipient, int dayAt, long timestamp, MessageAction action, MessageSender sender, MessageDelivery delivery) { return session() .insert() .value(messageLog::accountId, message.accountId()) .value(messageLog::domainId, message.domainId()) .value(messageLog::dayAt, dayAt) .value(messageLog::eventAt, Timeuuid.of(timestamp)) .value(messageLog::messageId, message.messageId()) .value(messageLog::collisionId, message.collisionId()) .value(messageLog::action, action) .value(messageLog::delivery, delivery) .value(messageLog::sender, sender) .value(messageLog::recipient, recipient) .value(messageLog::headers, new MessageToHeadersAdapter(message)) .sync(); } }
yeelin/betweenus
app/src/main/java/com/example/yeelin/projects/betweenus/data/google/query/GooglePlacePhotosHelper.java
package com.example.yeelin.projects.betweenus.data.google.query; import android.net.Uri; import android.util.Log; import com.example.yeelin.projects.betweenus.data.LocalConstants; import java.net.MalformedURLException; import java.net.URL; /** * Created by ninjakiki on 3/21/16. */ public class GooglePlacePhotosHelper { private static final String TAG = GooglePlacePhotosHelper.class.getCanonicalName(); /** * Builds the URL for getting google place photos (via appengine). Note that this URL will be used * by Piccasso. * @param photoReference * @param maxHeight * @param maxWidth * @return * @throws MalformedURLException */ public static URL buildPlacePhotosUrl(String photoReference, int maxHeight, int maxWidth) throws MalformedURLException { Uri uri = new Uri.Builder() .scheme(LocalConstants.SCHEME) .authority(LocalConstants.AUTHORITY) .appendPath(LocalConstants.GOOGLE_PATH) .appendPath(LocalConstants.PLACE_PHOTOS_PATH) .appendQueryParameter(GoogleConstants.PlacePhotosParamNames.PHOTO_REFERENCE, photoReference) .appendQueryParameter(GoogleConstants.PlacePhotosParamNames.MAX_HEIGHT, String.valueOf(maxHeight)) .appendQueryParameter(GoogleConstants.PlacePhotosParamNames.MAX_WIDTH, String.valueOf(maxWidth)) .build(); Log.d(TAG, "buildPlacePhotosUrl:" + uri.toString()); return new URL(uri.toString()); } }
adnansorg/kibana_calendar_vis
public/__tests__/lib/dispatcher.js
<reponame>adnansorg/kibana_calendar_vis /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { expect } from 'chai'; import sinon from 'sinon'; import { Dispatcher } from '../../lib'; describe('Dispatcher', () => { let dispatcher; const callback = sinon.spy(); beforeEach(() => { dispatcher = new Dispatcher(); }); afterEach(() => { dispatcher = null; }); it('should reject calls to addEvent and removeEvent if source and dataTarget not set', () => { let errorAdd; try { dispatcher.addEvent('click', callback); } catch (e) { errorAdd = e.message; } expect(errorAdd).to.equal('source or dataTarget is not defined'); let errorRemove; try { dispatcher.removeEvent('click', callback); } catch (e) { errorRemove = e.message; } expect(errorRemove).to.equal('source or dataTarget is not defined'); }); it('should reject when invalid container is added', () => { let error; try { dispatcher.addContainer('wrongType'); } catch (e) { error = e.message; } expect(error).to.equal('invalid type wrongType, should be HTMLElement'); }); it('should reject when invalid dataTarget is added', () => { let error; try { dispatcher.addDataTarget('wrong'); } catch (e) { error = e.message; } expect(error).to.equal('invalid type string, should be in a form [data-...]'); }); it('should add and remove event', () => { const targets = document.createDocumentFragment(); for (let i = 0; i < 3; ++i) { const elem = document.createElement('div'); targets.appendChild(elem); elem.setAttribute('data-test', i); } const div = document.createElement('div'); div.appendChild(targets); document.body.appendChild(div); dispatcher.addContainer(div).addDataTarget('[data-test]').addEvent('click', callback); document.querySelector('[data-test]').click(); expect(callback.calledOnce).to.equal(true); }); });
Automedon/CodeWars-7-kata
Valid HK Phone Number.js
<reponame>Automedon/CodeWars-7-kata<filename>Valid HK Phone Number.js /* Description: Valid HK Phone Number Overview In Hong Kong, a valid phone number has the format xxxx xxxx where x is a decimal digit (0-9). For example: "1234 5678" // is valid "2359 1478" // is valid "85748475" // invalid, as there are no spaces separating the first 4 and last 4 digits "3857 4756" // invalid; there should be exactly 1 whitespace separating the first 4 and last 4 digits respectively "sklfjsdklfjsf" // clearly invalid " 1234 5678 " // is NOT a valid phone number but CONTAINS a valid phone number "skldfjs287389274329dklfj84239029043820942904823480924293042904820482409209438dslfdjs9345 8234sdklfjsdkfjskl28394723987jsfss2343242kldjf23423423SDLKFJSLKsdklf" // also contains a valid HK phone number (9345 8234) Task Define two functions, isValidHKPhoneNumber and hasValidHKPhoneNumber, that returns whether a given string is a valid HK phone number and contains a valid HK phone number respectively (i.e. true/false values). If in doubt please refer to the example tests. */ const isValidHKPhoneNumber=string=>{ return /^\d{4}\s\d{4}$/.test(string) } const hasValidHKPhoneNumber=string=>{ return /\d{4}\s\d{4}/.test(string) }
hbxie/bullet-ui
tests/unit/validators/group-metric-presence-test.js
/* * Copyright 2016, Yahoo Inc. * Licensed under the terms of the Apache License, Version 2.0. * See the LICENSE file associated with the project for terms. */ import { A } from '@ember/array'; import EmberObject from '@ember/object'; import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; import { AGGREGATIONS } from 'bullet-ui/models/aggregation'; module('Unit | Validator | group-metric-presence', function(hooks) { setupTest(hooks); test('it checks to see if grouped data has groups or metrics', function(assert) { var validator = this.owner.lookup('validator:group-metric-presence'); let mockModel = EmberObject.create({ type: AGGREGATIONS.get('GROUP') }); let expected = 'If you are grouping data, you must add at least one Group Field and/or Metric Field'; assert.equal(validator.validate(null, null, mockModel), expected); mockModel.set('groups', A([1, 2])); assert.ok(validator.validate(null, null, mockModel)); mockModel.set('groups', A()); assert.equal(validator.validate(null, null, mockModel), expected); mockModel.set('metrics', A([1, 2])); assert.ok(validator.validate(null, null, mockModel)); }); });
jumpingfella/JBookTrader
jsystemtrader/src/main/java/com/jsystemtrader/chart/FastXYPlot.java
package com.jsystemtrader.chart; import java.awt.*; import java.awt.geom.*; import java.util.*; import org.jfree.chart.axis.*; import org.jfree.chart.plot.*; import org.jfree.chart.renderer.xy.*; import org.jfree.data.general.*; import org.jfree.data.xy.*; public class FastXYPlot extends XYPlot { private final Map<Integer, Long> lastRenderedX = new HashMap<Integer, Long> (); public FastXYPlot() { this(null, null, null, null); } public FastXYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer) { super(dataset, domainAxis, rangeAxis, renderer); } public void renderFast(ValueAxis xAxis, ValueAxis yAxis, XYDataset dataset, int series, XYItemRenderer renderer, XYItemRendererState state, int pass, Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info, CrosshairState crosshairState) { int firstItem = findFirstItemIndex(xAxis.getLowerBound(), dataset, series); int lastItem = findLastItemIndex(xAxis.getUpperBound(), dataset, series); for (int item = firstItem; item < lastItem; item++) { double x = dataset.getXValue(series, item); double xx = xAxis.valueToJava2D(x, dataArea, getDomainAxisEdge()); long lastRendered = lastRenderedX.containsKey(series) ? lastRenderedX.get(series) : 0; long rounded = (long) ( (xx * 100) / 10); if (rounded != lastRendered) { lastRenderedX.put(series, rounded); renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } } } public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CrosshairState crosshairState) { boolean foundData = false; XYDataset dataset = getDataset(index); if (!DatasetUtilities.isEmptyOrNull(dataset)) { lastRenderedX.clear(); foundData = true; ValueAxis xAxis = getDomainAxisForDataset(index); ValueAxis yAxis = getRangeAxisForDataset(index); XYItemRenderer renderer = getRenderer(index); if (renderer == null) { renderer = getRenderer(); } XYItemRendererState state = renderer.initialise(g2, dataArea, this, dataset, info); int passCount = renderer.getPassCount(); SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder(); if (seriesOrder == SeriesRenderingOrder.REVERSE) { //render series in reverse order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = seriesCount - 1; series >= 0; series--) { renderFast(xAxis, yAxis, dataset, series, renderer, state, pass, g2, dataArea, info, crosshairState); } } } else { //render series in forward order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { renderFast(xAxis, yAxis, dataset, series, renderer, state, pass, g2, dataArea, info, crosshairState); } } } } return foundData; } /** * * @return int idx of first item less than xval */ private int findFirstItemIndex(double xval, XYDataset ds, int series) { if (Double.isNaN(xval)) { return 0; } int bin = binarySearch(ds, series, xval); if (bin < 0) { bin = -bin - 1; } return Math.max(0, Math.min(bin, ds.getItemCount(series) - 1)); } /** * * @return int idx of first item greater than xval */ private int findLastItemIndex(double xval, XYDataset ds, int series) { if (Double.isNaN(xval)) { return ds.getItemCount(series); } int bin = binarySearch(ds, series, xval); if (bin < 0) { bin = -bin - 1; } if (bin > 0) { bin++; } return Math.max(0, Math.min(bin, ds.getItemCount(series))); } private int binarySearch(XYDataset ds, int series, double xval) { int low = 0; int high = ds.getItemCount(series) - 1; while (low <= high) { int mid = (low + high) >> 1; double diff = ds.getXValue(series, mid) - xval; if (diff < 0) { low = mid + 1; } else if (diff > 0) { high = mid - 1; } else { return mid; // key found } } return - (low + 1); // key not found } }
zbmain/PGL
legacy/examples/distribute_metapath2vec/utils.py
<reponame>zbmain/PGL # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved # # 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. """Implementation of some helper functions""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import os import time import yaml import numpy as np from pgl.utils.logger import log class AttrDict(dict): """Attr dict """ def __init__(self, d): self.dict = d def __getattr__(self, attr): value = self.dict[attr] if isinstance(value, dict): return AttrDict(value) else: return value def __str__(self): return str(self.dict) def load_config(config_file): """Load config file""" with open(config_file) as f: if hasattr(yaml, 'FullLoader'): config = yaml.load(f, Loader=yaml.FullLoader) else: config = yaml.load(f) return AttrDict(config)
angainor/prrte
src/mca/routed/radix/routed_radix_component.c
<gh_stars>0 /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2007-2015 Los Alamos National Security, LLC. * All rights reserved. * Copyright (c) 2004-2008 The Trustees of Indiana University. * All rights reserved. * Copyright (c) 2013 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2013-2019 Intel, Inc. All rights reserved. * Copyright (c) 2019 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "prrte_config.h" #include "constants.h" #include "src/mca/base/base.h" #include "src/mca/routed/base/base.h" #include "routed_radix.h" static int prrte_routed_radix_component_register(void); static int prrte_routed_radix_component_query(prrte_mca_base_module_t **module, int *priority); /** * component definition */ prrte_routed_radix_component_t prrte_routed_radix_component = { { /* First, the prrte_mca_base_component_t struct containing meta information about the component itself */ .base_version = { PRRTE_ROUTED_BASE_VERSION_3_0_0, .mca_component_name = "radix", PRRTE_MCA_BASE_MAKE_VERSION(component, PRRTE_MAJOR_VERSION, PRRTE_MINOR_VERSION, PRRTE_RELEASE_VERSION), .mca_query_component = prrte_routed_radix_component_query, .mca_register_component_params = prrte_routed_radix_component_register, }, .base_data = { /* This component can be checkpointed */ PRRTE_MCA_BASE_METADATA_PARAM_CHECKPOINT }, } }; static int prrte_routed_radix_component_register(void) { prrte_mca_base_component_t *c = &prrte_routed_radix_component.super.base_version; prrte_routed_radix_component.radix = 64; (void) prrte_mca_base_component_var_register(c, NULL, "Radix to be used for routed radix tree", PRRTE_MCA_BASE_VAR_TYPE_INT, NULL, 0, 0, PRRTE_INFO_LVL_9, PRRTE_MCA_BASE_VAR_SCOPE_READONLY, &prrte_routed_radix_component.radix); return PRRTE_SUCCESS; } static int prrte_routed_radix_component_query(prrte_mca_base_module_t **module, int *priority) { if (0 > prrte_routed_radix_component.radix) { return PRRTE_ERR_BAD_PARAM; } *priority = 70; *module = (prrte_mca_base_module_t *) &prrte_routed_radix_module; return PRRTE_SUCCESS; }
muit/FecoEngine
Source/Engine/Tools/Profiler.h
<filename>Source/Engine/Tools/Profiler.h<gh_stars>1-10 // Copyright 2015-2019 Piperift - All rights reserved #pragma once #include <tracy/Tracy.hpp> #include "Core/Log.h" #define ScopedZone(Name, Color) ZoneScopedNC(Name, 0x##Color) #define ScopedGameZone(Name) ScopedZone(Name, 459bd1) #define ScopedGraphicsZone(Name) ScopedZone(Name, 94d145) #define ScopedStackZone(Color) ZoneScopedC(0x##Color) #define ScopedStackGameZone() ScopedStackZone(459bd1) #define ScopedStackGraphicsZone() ScopedStackZone(94d145) #define Ensure(condition, ...) if(!(condition)) { Log::Error(__VA_ARGS__); } #define EnsureIf(condition, ...) Ensure(condition, __VA_ARGS__) else
astefanova/xsk
modules/parsers/parser-hdbcalculationview/src/main/java/com/sap/ndb/searchmodelsearch/SearchableElementProperties.java
<reponame>astefanova/xsk<gh_stars>0 /* * Copyright (c) 2019-2021 SAP SE or an SAP affiliate company and XSK contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, v2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * SPDX-FileCopyrightText: 2019-2021 SAP SE or an SAP affiliate company and XSK contributors * SPDX-License-Identifier: Apache-2.0 */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 // See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.11.26 at 10:54:28 AM EET // package com.sap.ndb.searchmodelsearch; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * Search specific properties of an Element * * * <p>Java class for SearchableElementProperties complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SearchableElementProperties"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="freestyleSearch" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/&gt; * &lt;element name="rankingWeight" type="{http://www.sap.com/ndb/SearchModelSearch.ecore}RankingWeight" minOccurs="0"/&gt; * &lt;element name="fuzzySearch" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/&gt; * &lt;element name="fuzzinessThreshold" type="{http://www.sap.com/ndb/SearchModelSearch.ecore}FuzzinessThreshold" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SearchableElementProperties", propOrder = { "freestyleSearch", "rankingWeight", "fuzzySearch", "fuzzinessThreshold" }) public class SearchableElementProperties { protected Boolean freestyleSearch; @XmlElement(defaultValue = "0.5") protected Float rankingWeight; protected Boolean fuzzySearch; protected Float fuzzinessThreshold; /** * Gets the value of the freestyleSearch property. * * @return possible object is * {@link Boolean } */ public Boolean isFreestyleSearch() { return freestyleSearch; } /** * Sets the value of the freestyleSearch property. * * @param value allowed object is * {@link Boolean } */ public void setFreestyleSearch(Boolean value) { this.freestyleSearch = value; } /** * Gets the value of the rankingWeight property. * * @return possible object is * {@link Float } */ public Float getRankingWeight() { return rankingWeight; } /** * Sets the value of the rankingWeight property. * * @param value allowed object is * {@link Float } */ public void setRankingWeight(Float value) { this.rankingWeight = value; } /** * Gets the value of the fuzzySearch property. * * @return possible object is * {@link Boolean } */ public Boolean isFuzzySearch() { return fuzzySearch; } /** * Sets the value of the fuzzySearch property. * * @param value allowed object is * {@link Boolean } */ public void setFuzzySearch(Boolean value) { this.fuzzySearch = value; } /** * Gets the value of the fuzzinessThreshold property. * * @return possible object is * {@link Float } */ public Float getFuzzinessThreshold() { return fuzzinessThreshold; } /** * Sets the value of the fuzzinessThreshold property. * * @param value allowed object is * {@link Float } */ public void setFuzzinessThreshold(Float value) { this.fuzzinessThreshold = value; } }
ScalablyTyped/SlinkyTyped
e/expo-font/src/main/scala/typingsSlinky/expoFont/anon.scala
package typingsSlinky.expoFont import typingsSlinky.expoFont.fontTypesMod.FontDisplay import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object anon { /* Inlined std.Pick<expo-font.expo-font/build/Font.types.FontResource, 'display'> */ @js.native trait PickFontResourcedisplay extends StObject { var display: js.UndefOr[FontDisplay] = js.native } object PickFontResourcedisplay { @scala.inline def apply(): PickFontResourcedisplay = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[PickFontResourcedisplay] } @scala.inline implicit class PickFontResourcedisplayMutableBuilder[Self <: PickFontResourcedisplay] (val x: Self) extends AnyVal { @scala.inline def setDisplay(value: FontDisplay): Self = StObject.set(x, "display", value.asInstanceOf[js.Any]) @scala.inline def setDisplayUndefined: Self = StObject.set(x, "display", js.undefined) } } }
jensonwe/mvvmFX
mvvmfx/src/main/java/de/saxsys/mvvmfx/ViewTuple.java
<reponame>jensonwe/mvvmFX<gh_stars>100-1000 /******************************************************************************* * Copyright 2013 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.saxsys.mvvmfx; import javafx.scene.Parent; import de.saxsys.mvvmfx.internal.viewloader.View; /** * <p> * Tuple for carrying view / code-behind pair. The code-behind part is the class which is known as the controller class * behind a FXML file. * </p> * * <p> * As a user you typically won't create instances of this class on your own. Instead you will obtain instances of this * class with the {@link FluentViewLoader} when you are loading a view. * </p> * * <p> * Instances of this class are immutable. * </p> * * * @param <ViewType> * the generic type of the view that was loaded. * @param <ViewModelType> * the generic type of the viewModel that was loaded. */ public class ViewTuple<ViewType extends View<? extends ViewModelType>, ViewModelType extends ViewModel> { private final ViewType codeBehind; private final Parent view; private final ViewModelType viewModel; /** * @param codeBehind * the codeBehind for this viewTuple * @param view * the view for this viewTuple * @param viewModel * the viewModel for this viewTuple */ public ViewTuple(final ViewType codeBehind, final Parent view, final ViewModelType viewModel) { this.codeBehind = codeBehind; this.view = view; this.viewModel = viewModel; } /** * <p> * The code behind part of the view. When using FXML ({@link FxmlView}) this will be an instance of the class that * is specified in the fxml file with <code>fx:controller</code>. * </p> * * <p> * When the view is implemented in pure java ({@link JavaView}) the instance returned by this method will typically * be the same instance that is returned by {@link #getView()}. * </p> * * @return the code behind of the View. */ public ViewType getCodeBehind() { return codeBehind; } /** * The root object of the view. This can be added to the scene graph. * * @return the view */ public Parent getView() { return view; } /** * @return the viewModel */ public ViewModelType getViewModel() { return viewModel; } }
NightOfTwelve/android_device_huawei_hwp7
kernel/huawei/hwp7/drivers/misc/gpu_drv/arch/XAQ2/hal/user/gc_hal_user_hardware_precomp.h
<gh_stars>1-10 /**************************************************************************** * * Copyright (c) 2005 - 2013 by Vivante Corp. All rights reserved. * * The material in this file is confidential and contains trade secrets * of Vivante Corporation. This is proprietary information owned by * Vivante Corporation. No part of this work may be disclosed, * reproduced, copied, transmitted, or used in any way for any purpose, * without the express written permission of Vivante Corporation. * *****************************************************************************/ #ifndef __gc_hal_user_hardware_precomp_h_ #define __gc_hal_user_hardware_precomp_h_ #include "gc_hal_user.h" #include "gc_hal_user_hardware.h" /* Workaround GCC optimizer's bug */ #if defined(__GNUC__) && !gcmIS_DEBUG(gcdDEBUG_TRACE) gcmINLINE static void __do_nothing( IN gctUINT32 Level, IN gctUINT32 Zone, IN gctCONST_STRING Message, ... ) { static volatile int c; c++; } # undef gcmTRACE_ZONE # define gcmTRACE_ZONE __do_nothing #endif #endif /* __gc_hal_user_hardware_precomp_h_ */
crazysal/chemml
chemml/models/__init__.py
<gh_stars>0 """ The 'chemml.models' module includes (please click on links adjacent to function names for more information): - OrganicLorentzLorenz: :func:`~chemml.models.keras.trained.OrganicLorentzLorenz` - MLP: :func:`~chemml.models.keras.mlp.MLP` """ from chemml.models.keras.mlp import MLP from chemml.models.keras.trained import OrganicLorentzLorenz __all__ = [ 'OrganicLorentzLorenz', 'MLP' ]
corvus-ch/bilocation
main.go
<reponame>corvus-ch/bilocation package main import ( "fmt" "github.com/corvus-ch/bilocation/cmd" stdLog "log" "os" "github.com/bketelsen/logr" "github.com/corvus-ch/logr/std" "github.com/corvus-ch/logr/writer_adapter" "gopkg.in/alecthomas/kingpin.v2" ) var ( version = "dev" commit = "none" date = "unknown" ) func App(log logr.Logger) *kingpin.Application { w := writer_adapter.NewBufferedErrorWriter(log) app := kingpin.New("bilocation", "file management with tags") app.ErrorWriter(w) app.UsageWriter(w) app.Version(fmt.Sprintf("%v, commit %v, built at %v", version, commit, date)) cfg := cmd.NewConfig(log) cmd.Tag(app, cfg) cmd.Untag(app, cfg) cmd.Inspect(app, cfg) cmd.Search(app, cfg) cmd.Summary(app, cfg) return app } func main() { log := std.New(0, stdLog.New(os.Stderr, "", 0), stdLog.New(os.Stdout, "", 0)) if _, err := App(log).Parse(os.Args[1:]); err != nil { log.Errorf("%s, try --help", err) os.Exit(1) } }
ndtung01061999/catiny
.generate/template/skote/skote-admin/src/pages/Icons/IconDripicons.js
import React from "react" import MetaTags from 'react-meta-tags'; import { Row, Col, Card, CardBody, Container } from "reactstrap" //Import Breadcrumb import Breadcrumbs from "../../components/Common/Breadcrumb" const IconDripicons = () => { return ( <React.Fragment> <div className="page-content"> <MetaTags> <title>Dripicons | Skote - React Admin & Dashboard Template</title> </MetaTags> <Container fluid> <Breadcrumbs title="Icons" breadcrumbItem="Dripicons" /> <Row> <Col xs="12"> <Card> <CardBody> <h4 className="card-title">Examples</h4> <p className="card-title-desc mb-2"> Use{" "} <code>&lt;i className="dripicons-alarm"&gt;&lt;/i&gt;</code> . </p> <Row className="icon-demo-content"> <Col xl="3" lg="4" sm="6"> <i className="dripicons-alarm" /> dripicons-alarm </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-align-center" />{" "} dripicons-align-center </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-align-justify" />{" "} dripicons-align-justify </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-align-left" />{" "} dripicons-align-left </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-align-right" />{" "} dripicons-align-right </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-anchor" /> dripicons-anchor </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-archive" /> dripicons-archive </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-down" />{" "} dripicons-arrow-down </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-left" />{" "} dripicons-arrow-left </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-right" />{" "} dripicons-arrow-right </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-thin-down" />{" "} dripicons-arrow-thin-down </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-thin-left" />{" "} dripicons-arrow-thin-left </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-thin-right" />{" "} dripicons-arrow-thin-right </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-thin-up" />{" "} dripicons-arrow-thin-up </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-arrow-up" /> dripicons-arrow-up </Col> <Col xl="3" lg="4" sm="6"> <i className=" dripicons-article" /> dripicons-article </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-backspace" />{" "} dripicons-backspace </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-basket" /> dripicons-basket </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-basketball" />{" "} dripicons-basketball </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-battery-empty" />{" "} dripicons-battery-empty </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-battery-full" />{" "} dripicons-battery-full </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-battery-low" />{" "} dripicons-battery-low </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-battery-medium" />{" "} dripicons-battery-medium </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-bell" /> dripicons-bell </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-blog" /> dripicons-blog </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-bluetooth" />{" "} dripicons-bluetooth </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-bold" /> dripicons-bold </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-bookmark" /> dripicons-bookmark </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-bookmarks" />{" "} dripicons-bookmarks </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-box" /> dripicons-box </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-briefcase" />{" "} dripicons-briefcase </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-brightness-low" />{" "} dripicons-brightness-low </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-brightness-max" />{" "} dripicons-brightness-max </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-brightness-medium" />{" "} dripicons-brightness-medium </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-broadcast" />{" "} dripicons-broadcast </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-browser" /> dripicons-browser </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-browser-upload" />{" "} dripicons-browser-upload </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-brush" /> dripicons-brush </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-calendar" /> dripicons-calendar </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-camcorder" />{" "} dripicons-camcorder </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-camera" /> dripicons-camera </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-card" /> dripicons-card </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-cart" /> dripicons-cart </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-checklist" />{" "} dripicons-checklist </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-checkmark" />{" "} dripicons-checkmark </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-chevron-down" />{" "} dripicons-chevron-down </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-chevron-left" />{" "} dripicons-chevron-left </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-chevron-right" />{" "} dripicons-chevron-right </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-chevron-up" />{" "} dripicons-chevron-up </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-clipboard" />{" "} dripicons-clipboard </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-clock" /> dripicons-clock </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-clockwise" />{" "} dripicons-clockwise </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-cloud" /> dripicons-cloud </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-cloud-download" />{" "} dripicons-cloud-download </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-cloud-upload" />{" "} dripicons-cloud-upload </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-code" /> dripicons-code </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-contract" /> dripicons-contract </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-contract-2" />{" "} dripicons-contract-2 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-conversation" />{" "} dripicons-conversation </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-copy" /> dripicons-copy </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-crop" /> dripicons-crop </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-cross" /> dripicons-cross </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-crosshair" />{" "} dripicons-crosshair </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-cutlery" /> dripicons-cutlery </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-device-desktop" />{" "} dripicons-device-desktop </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-device-mobile" />{" "} dripicons-device-mobile </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-device-tablet" />{" "} dripicons-device-tablet </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-direction" />{" "} dripicons-direction </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-disc" /> dripicons-disc </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-document" /> dripicons-document </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-document-delete" />{" "} dripicons-document-delete </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-document-edit" />{" "} dripicons-document-edit </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-document-new" />{" "} dripicons-document-new </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-document-remove" />{" "} dripicons-document-remove </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-dot" /> dripicons-dot </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-dots-2" /> dripicons-dots-2 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-dots-3" /> dripicons-dots-3 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-download" /> dripicons-download </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-duplicate" />{" "} dripicons-duplicate </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-enter" /> dripicons-enter </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-exit" /> dripicons-exit </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-expand" /> dripicons-expand </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-expand-2" /> dripicons-expand-2 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-experiment" />{" "} dripicons-experiment </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-export" /> dripicons-export </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-feed" /> dripicons-feed </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-flag" /> dripicons-flag </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-flashlight" />{" "} dripicons-flashlight </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-folder" /> dripicons-folder </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-folder-open" />{" "} dripicons-folder-open </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-forward" /> dripicons-forward </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-gaming" /> dripicons-gaming </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-gear" /> dripicons-gear </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-graduation" />{" "} dripicons-graduation </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-graph-bar" />{" "} dripicons-graph-bar </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-graph-line" />{" "} dripicons-graph-line </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-graph-pie" />{" "} dripicons-graph-pie </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-headset" /> dripicons-headset </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-heart" /> dripicons-heart </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-help" /> dripicons-help </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-home" /> dripicons-home </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-hourglass" />{" "} dripicons-hourglass </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-inbox" /> dripicons-inbox </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-information" />{" "} dripicons-information </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-italic" /> dripicons-italic </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-jewel" /> dripicons-jewel </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-lifting" /> dripicons-lifting </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-lightbulb" />{" "} dripicons-lightbulb </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-link" /> dripicons-link </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-link-broken" />{" "} dripicons-link-broken </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-list" /> dripicons-list </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-loading" /> dripicons-loading </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-location" /> dripicons-location </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-lock" /> dripicons-lock </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-lock-open" />{" "} dripicons-lock-open </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-mail" /> dripicons-mail </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-map" /> dripicons-map </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-loop" />{" "} dripicons-media-loop </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-next" />{" "} dripicons-media-next </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-pause" />{" "} dripicons-media-pause </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-play" />{" "} dripicons-media-play </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-previous" />{" "} dripicons-media-previous </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-record" />{" "} dripicons-media-record </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-shuffle" />{" "} dripicons-media-shuffle </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-media-stop" />{" "} dripicons-media-stop </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-medical" /> dripicons-medical </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-menu" /> dripicons-menu </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-message" /> dripicons-message </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-meter" /> dripicons-meter </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-microphone" />{" "} dripicons-microphone </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-minus" /> dripicons-minus </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-monitor" /> dripicons-monitor </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-move" /> dripicons-move </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-music" /> dripicons-music </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-network-1" />{" "} dripicons-network-1 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-network-2" />{" "} dripicons-network-2 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-network-3" />{" "} dripicons-network-3 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-network-4" />{" "} dripicons-network-4 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-network-5" />{" "} dripicons-network-5 </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-pamphlet" /> dripicons-pamphlet </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-paperclip" />{" "} dripicons-paperclip </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-pencil" /> dripicons-pencil </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-phone" /> dripicons-phone </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-photo" /> dripicons-photo </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-photo-group" />{" "} dripicons-photo-group </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-pill" /> dripicons-pill </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-pin" /> dripicons-pin </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-plus" /> dripicons-plus </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-power" /> dripicons-power </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-preview" /> dripicons-preview </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-print" /> dripicons-print </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-pulse" /> dripicons-pulse </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-question" /> dripicons-question </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-reply" /> dripicons-reply </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-reply-all" />{" "} dripicons-reply-all </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-return" /> dripicons-return </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-retweet" /> dripicons-retweet </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-rocket" /> dripicons-rocket </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-scale" /> dripicons-scale </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-search" /> dripicons-search </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-shopping-bag" />{" "} dripicons-shopping-bag </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-skip" /> dripicons-skip </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-stack" /> dripicons-stack </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-star" /> dripicons-star </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-stopwatch" />{" "} dripicons-stopwatch </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-store" /> dripicons-store </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-suitcase" /> dripicons-suitcase </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-swap" /> dripicons-swap </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-tag" /> dripicons-tag </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-tag-delete" />{" "} dripicons-tag-delete </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-tags" /> dripicons-tags </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-thumbs-down" />{" "} dripicons-thumbs-down </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-thumbs-up" />{" "} dripicons-thumbs-up </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-ticket" /> dripicons-ticket </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-time-reverse" />{" "} dripicons-time-reverse </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-to-do" /> dripicons-to-do </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-toggles" /> dripicons-toggles </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-trash" /> dripicons-trash </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-trophy" /> dripicons-trophy </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-upload" /> dripicons-upload </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-user" /> dripicons-user </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-user-group" />{" "} dripicons-user-group </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-user-id" /> dripicons-user-id </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-vibrate" /> dripicons-vibrate </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-view-apps" />{" "} dripicons-view-apps </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-view-list" />{" "} dripicons-view-list </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-view-list-large" />{" "} dripicons-view-list-large </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-view-thumb" />{" "} dripicons-view-thumb </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-volume-full" />{" "} dripicons-volume-full </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-volume-low" />{" "} dripicons-volume-low </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-volume-medium" />{" "} dripicons-volume-medium </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-volume-off" />{" "} dripicons-volume-off </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-wallet" /> dripicons-wallet </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-warning" /> dripicons-warning </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-web" /> dripicons-web </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-weight" /> dripicons-weight </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-wifi" /> dripicons-wifi </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-wrong" /> dripicons-wrong </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-zoom-in" /> dripicons-zoom-in </Col> <Col xl="3" lg="4" sm="6"> <i className="dripicons-zoom-out" /> dripicons-zoom-out </Col> </Row> </CardBody> </Card> </Col> </Row> </Container> </div> </React.Fragment> ) } export default IconDripicons
DasLixou/cloudsystem
polocloud-modules/npc-module/src/main/java/de/polocloud/npcs/service/INPCService.java
package de.polocloud.npcs.service; public interface INPCService { void loadNPCs(); void reloadNPCs(); void updateNPCs(); void registerListeners(); }
almondtools/stringbench
src/main/java/com/almondtools/stringbench/analyzer/UpdateBenchmarks.java
<reponame>almondtools/stringbench package com.almondtools.stringbench.analyzer; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.maxBy; import static java.util.stream.Collectors.toList; import static org.simpleflatmapper.csv.CsvColumnDefinition.customReaderDefinition; import static org.simpleflatmapper.csv.CsvColumnDefinition.identity; import static org.simpleflatmapper.csv.CsvColumnDefinition.ignoreDefinition; import static org.simpleflatmapper.csv.CsvColumnDefinition.renameDefinition; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.simpleflatmapper.csv.CellValueReader; import org.simpleflatmapper.csv.CsvColumnDefinition; import org.simpleflatmapper.csv.CsvParser; import org.simpleflatmapper.csv.CsvParser.MapToDSL; import org.simpleflatmapper.csv.ParsingContext; import com.almondtools.stringbench.analyzer.json.BenchmarkCollection; import com.almondtools.stringbench.analyzer.json.Candidate; import com.almondtools.stringbench.analyzer.json.Result; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class UpdateBenchmarks { private static final Pattern BENCHMARK_FILE = Pattern.compile("result(-[ans]*)?-(\\d{4}-\\d{2}-\\d{2})(-\\d+)?\\.csv"); private Map<String, String> names; private Map<String, String> families; private BenchmarkRecords benchmarks; public UpdateBenchmarks() { names = new HashMap<>(); families = new HashMap<>(); benchmarks = new BenchmarkRecords(); } public static void main(String[] args) throws IOException { UpdateBenchmarks updateBenchmarks = new UpdateBenchmarks(); updateBenchmarks.run(); } public void run() throws IOException { Path root = Paths.get("benchmarkresults"); List<File> csvFiles = Files.list(root) .filter(path -> BENCHMARK_FILE.matcher(path.getFileName().toString()).matches()) .map(path -> path.toFile()) .collect(toList()); File namesFile = root.resolve("names.csv").toFile(); CsvParser .mapTo(Mapping.class) .columnDefinition("name", renameDefinition("from")) .columnDefinition("normalization", renameDefinition("to")) .forEach(namesFile, mapping -> names.put(mapping.from, mapping.to)); File familiesFile = root.resolve("families.csv").toFile(); CsvParser .mapTo(Mapping.class) .columnDefinition("name", renameDefinition("from")) .columnDefinition("family", renameDefinition("to")) .forEach(familiesFile, mapping -> families.put(mapping.from, mapping.to)); for (File file : csvFiles) { Matcher matcher = BENCHMARK_FILE.matcher(file.getName()); boolean matches = matcher.matches(); String format = matches ? matcher.group(1) != null ? matcher.group(1) : "ans" : "ans"; Date date = matches ? parseDate(matcher.group(2)) : null; MapToDSL<BenchmarkRecord> parser = CsvParser .skip(1) .mapTo(BenchmarkRecord.class) .columnDefinition("Benchmark", identity()) .columnDefinition("Mode", ignoreDefinition()) .columnDefinition("Threads", ignoreDefinition()) .columnDefinition("Samples", ignoreDefinition()) .columnDefinition("Score", doubleReader()) .columnDefinition("Score Error (99,9%)", ignoreDefinition()) .columnDefinition("Unit", ignoreDefinition()); if (format.contains("a")) { parser = parser.columnDefinition("Param: alphabetSize", renameDefinition("alphabet")); } if (format.contains("n")) { parser = parser.columnDefinition("Param: patternNumber", intReader().addRename("number")); } if (format.contains("s")) { parser = parser.columnDefinition("Param: patternSize", renameDefinition("pattern")); } parser.forEach(file, benchmark -> benchmarks.add(benchmark.withDefaultPatternNumber(1) .withDate(date) .withAlgorithm(names.getOrDefault(benchmark.getAlgorithm(), benchmark.getAlgorithm())) .withType(names.getOrDefault(benchmark.getType(), benchmark.getType())) .withFamily(families.get(benchmark.getAlgorithm())))); } List<BenchmarkCollection> bestscenarios = toCollection(benchmarks.getRecords()); new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValue(root.resolve("best.json").toFile(), bestscenarios); } private List<BenchmarkCollection> toCollection(List<BenchmarkRecord> records) { List<BenchmarkRecord> maxrecords = records.stream() .collect(groupingBy(record -> new BenchmarkKey(record.getNumber(), record.getType(), record.getPattern(), record.getAlphabet()), maxBy(new BenchmarkScore()))) .values().stream().map(record -> record.orElse(null)).filter(Objects::nonNull).collect(toList()); return maxrecords.stream() .collect(groupingBy(record -> new CollectionKey(record.getNumber(), record.getType()))).entrySet() .stream().map(entry -> new BenchmarkCollection(entry.getKey().number, entry.getKey().type, toCandidate(entry.getValue()))) .sorted() .collect(toList()); } private List<Candidate> toCandidate(List<BenchmarkRecord> records) { return records.stream().collect(groupingBy(record -> new Algorithm(record.getAlgorithm(), record.getFamily()))) .entrySet().stream().map(entry -> new Candidate(entry.getKey().algorithm, entry.getKey().family, toResult(entry.getValue()))) .collect(toList()); } private List<Result> toResult(List<BenchmarkRecord> records) { return records.stream().map( record -> new Result(record.getAlphabet(), record.getPattern(), record.getScore(), record.getDate())) .collect(toList()); } public CsvColumnDefinition doubleReader() { return customReaderDefinition(new DoubleReader(Double.NaN)); } public CsvColumnDefinition intReader() { return customReaderDefinition(new IntReader(0)); } public Date parseDate(String group) { try { return new SimpleDateFormat("yyyy-MM-dd").parse(group); } catch (ParseException | NullPointerException e) { return null; } } private static class DoubleReader implements CellValueReader<Double> { private double defaultValue; public DoubleReader(double defaultValue) { this.defaultValue = defaultValue; } @Override public Double read(char[] chars, int offset, int length, ParsingContext parsingContext) { try { return NumberFormat.getInstance(Locale.GERMANY).parse(new String(chars, offset, length)).doubleValue(); } catch (ParseException e) { return defaultValue; } } } private static class IntReader implements CellValueReader<Integer> { private int defaultValue; public IntReader(int defaultValue) { this.defaultValue = defaultValue; } @Override public Integer read(char[] chars, int offset, int length, ParsingContext parsingContext) { try { String str = new String(chars, offset, length); return Integer.parseInt(str); } catch (NumberFormatException e) { return defaultValue; } } } private static class Algorithm { public String algorithm; public String family; public Algorithm(String algorithm, String family) { this.algorithm = algorithm; this.family = family; } @Override public int hashCode() { return algorithm.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Algorithm that = (Algorithm) obj; return this.algorithm.equals(that.algorithm); } } private static class CollectionKey { public int number; public String type; public CollectionKey(int number, String type) { this.number = number; this.type = type; } @Override public int hashCode() { return number * 13 + type.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CollectionKey that = (CollectionKey) obj; return this.number == that.number && this.type.equals(that.type); } } private static class BenchmarkKey { public int number; public String type; public int pattern; public int alphabet; public BenchmarkKey(int number, String type, int pattern, int alphabet) { this.number = number; this.type = type; this.pattern = pattern; this.alphabet = alphabet; } @Override public int hashCode() { return number * 13 + type.hashCode() + pattern * 7 + alphabet * 3; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BenchmarkKey that = (BenchmarkKey) obj; return this.number == that.number && this.type.equals(that.type) && this.pattern == that.pattern && this.alphabet == that.alphabet; } } private static class BenchmarkScore implements Comparator<BenchmarkRecord> { @Override public int compare(BenchmarkRecord o1, BenchmarkRecord o2) { return o1.getScore() > o2.getScore() ? -1 : 1; } } }
manongzcg/dsjksh
src/main/java/cn/epi/datasource/dao/FDatabaseDao.java
<reponame>manongzcg/dsjksh<filename>src/main/java/cn/epi/datasource/dao/FDatabaseDao.java package cn.epi.datasource.dao; import cn.epi.common.ICrudDao; import cn.epi.common.annotation.MyBatisDao; import cn.epi.datasource.entity.DataSourceEntity; import cn.epi.datasource.entity.FileSource; /** * Created by mwu on 5/11/17 5:05 PM. */ @MyBatisDao public interface FDatabaseDao extends ICrudDao<FileSource> { }
maulikpatel93/salonreact
src/component/form/Validation.js
const digitOnly = (value) => { if (value !== undefined) { return (/^\d+$/.test(value)); } return true; }; const decimalOnly = (value) => { if (value !== undefined) { return (/^\d{1,6}(\.\d{1,2})?$/.test(value)); } return true; }; export { digitOnly, decimalOnly };
challabeehyv/commcare-hq
corehq/apps/userreports/tests/test_report_builder.py
<reponame>challabeehyv/commcare-hq from django.test import TestCase from mock import patch from corehq.apps.app_manager.models import Application, Module from corehq.apps.app_manager.tests.app_factory import AppFactory from corehq.apps.userreports.app_manager.data_source_meta import ( DATA_SOURCE_TYPE_CASE, DATA_SOURCE_TYPE_FORM, DATA_SOURCE_TYPE_RAW, ) from corehq.apps.userreports.app_manager.helpers import ( get_case_data_source, get_form_data_source, ) from corehq.apps.userreports.dbaccessors import delete_all_report_configs from corehq.apps.userreports.models import ( DataSourceConfiguration, ReportConfiguration, ) from corehq.apps.userreports.reports.builder.columns import ( MultiselectQuestionColumnOption, ) from corehq.apps.userreports.reports.builder.const import ( COMPUTED_OWNER_LOCATION_PROPERTY_ID, COMPUTED_OWNER_LOCATION_WITH_DESENDANTS_PROPERTY_ID, COMPUTED_OWNER_LOCATION_ARCHIVED_WITH_DESCENDANTS_PROPERTY_ID, ) from corehq.apps.userreports.reports.builder.forms import ( ConfigureListReportForm, ConfigureTableReportForm, DataSourceBuilder, ReportBuilderDataSourceReference, ) from corehq.apps.userreports.tests.utils import get_simple_xform from corehq.util.test_utils import flag_enabled class ReportBuilderDBTest(TestCase): domain = 'domain' case_type = 'report_builder_case_type' @classmethod def setUpClass(cls): super(ReportBuilderDBTest, cls).setUpClass() factory = AppFactory(domain=cls.domain) module, form = factory.new_basic_module('Untitled Module', cls.case_type) form.source = get_simple_xform() cls.form = form factory.form_requires_case(form, case_type=cls.case_type, update={ 'first_name': '/data/first_name', 'last_name': '/data/last_name', }) cls.app = factory.app cls.app.save() @classmethod def tearDownClass(cls): cls.app.delete() for config in DataSourceConfiguration.all(): config.delete() delete_all_report_configs() super(ReportBuilderDBTest, cls).tearDownClass() class DataSourceBuilderTest(ReportBuilderDBTest): def test_builder_bad_type(self): with self.assertRaises(AssertionError): DataSourceBuilder(self.domain, self.app, 'invalid-type', self.form.unique_id) def test_builder_for_forms(self): builder = DataSourceBuilder(self.domain, self.app, DATA_SOURCE_TYPE_FORM, self.form.unique_id) self.assertEqual('XFormInstance', builder.source_doc_type) expected_filter = { "type": "and", "filters": [ { "type": "boolean_expression", "operator": "eq", "expression": { "type": "property_name", "property_name": "xmlns" }, "property_value": self.form.xmlns, }, { "type": "boolean_expression", "operator": "eq", "expression": { "type": "property_name", "property_name": "app_id" }, "property_value": self.app.get_id, } ] } self.assertEqual(expected_filter, builder.filter) expected_property_names = [ 'username', 'userID', 'timeStart', 'timeEnd', 'deviceID', '/data/first_name', '/data/last_name', '/data/children', '/data/dob', '/data/state' ] self.assertEqual(expected_property_names, list(builder.data_source_properties.keys())) user_id_prop = builder.data_source_properties['userID'] self.assertEqual('userID', user_id_prop.get_id()) self.assertEqual('User ID', user_id_prop.get_text()) name_prop = builder.data_source_properties['/data/first_name'] self.assertEqual('/data/first_name', name_prop.get_id()) self.assertEqual('First Name', name_prop.get_text()) def test_builder_for_cases(self): builder = DataSourceBuilder(self.domain, self.app, DATA_SOURCE_TYPE_CASE, self.case_type) self.assertEqual('CommCareCase', builder.source_doc_type) expected_filter = { "operator": "eq", "expression": { "type": "property_name", "property_name": "type" }, "type": "boolean_expression", "property_value": self.case_type, } self.assertEqual(expected_filter, builder.filter) expected_property_names = { "closed", "closed_on", "first_name", "last_name", "modified_on", "name", "opened_on", "@owner_id", "user_id", "computed/owner_name", "computed/user_name", } self.assertSetEqual(expected_property_names, set(builder.data_source_properties.keys())) owner_name_prop = builder.data_source_properties['computed/owner_name'] self.assertEqual('computed/owner_name', owner_name_prop.get_id()) self.assertEqual('Case Owner', owner_name_prop.get_text()) first_name_prop = builder.data_source_properties['first_name'] self.assertEqual('first_name', first_name_prop.get_id()) self.assertEqual('first name', first_name_prop.get_text()) @flag_enabled('SHOW_OWNER_LOCATION_PROPERTY_IN_REPORT_BUILDER') def test_owner_as_location(self): builder = DataSourceBuilder(self.domain, self.app, DATA_SOURCE_TYPE_CASE, self.case_type) self.assertTrue(COMPUTED_OWNER_LOCATION_PROPERTY_ID in builder.data_source_properties) self.assertTrue(COMPUTED_OWNER_LOCATION_WITH_DESENDANTS_PROPERTY_ID in builder.data_source_properties) self.assertTrue(COMPUTED_OWNER_LOCATION_ARCHIVED_WITH_DESCENDANTS_PROPERTY_ID in builder.data_source_properties) owner_location_prop = builder.data_source_properties[COMPUTED_OWNER_LOCATION_PROPERTY_ID] self.assertEqual(COMPUTED_OWNER_LOCATION_PROPERTY_ID, owner_location_prop.get_id()) self.assertEqual('Case Owner (Location)', owner_location_prop.get_text()) owner_location_prop_w_descendants = \ builder.data_source_properties[COMPUTED_OWNER_LOCATION_WITH_DESENDANTS_PROPERTY_ID] self.assertEqual(COMPUTED_OWNER_LOCATION_WITH_DESENDANTS_PROPERTY_ID, owner_location_prop_w_descendants.get_id()) self.assertEqual('Case Owner (Location w/ Descendants)', owner_location_prop_w_descendants.get_text()) owner_location_prop_archived_w_descendants = \ builder.data_source_properties[COMPUTED_OWNER_LOCATION_ARCHIVED_WITH_DESCENDANTS_PROPERTY_ID] self.assertEqual(COMPUTED_OWNER_LOCATION_ARCHIVED_WITH_DESCENDANTS_PROPERTY_ID, owner_location_prop_archived_w_descendants.get_id()) self.assertEqual( 'Case Owner (Location w/ Descendants and Archived Locations)', owner_location_prop_archived_w_descendants.get_text() ) class DataSourceReferenceTest(ReportBuilderDBTest): def test_reference_for_forms(self): form_data_source = get_form_data_source(self.app, self.form) form_data_source.save() reference = ReportBuilderDataSourceReference( self.domain, self.app, DATA_SOURCE_TYPE_RAW, form_data_source._id, ) # todo: we should filter out some of these columns expected_property_names = [ "doc_id", "inserted_at", "completed_time", "started_time", "username", "userID", "@xmlns", "@name", "App Version", "deviceID", "location", "app_id", "build_id", "@version", "state", "last_sync_token", "partial_submission", "received_on", "edited_on", "submit_ip", "form.first_name", "form.last_name", "form.children", "form.dob", "form.state", "form.case.@date_modified", '<EMAIL>', '<EMAIL>', 'form.case.update.first_name', 'form.case.update.last_name', "count", "hq_user", ] self.assertItemsEqual(expected_property_names, list(reference.data_source_properties)) user_id_prop = reference.data_source_properties['userID'] self.assertEqual('userID', user_id_prop.get_id()) self.assertEqual('userID', user_id_prop.get_text()) name_prop = reference.data_source_properties['form.first_name'] self.assertEqual('form.first_name', name_prop.get_id()) self.assertEqual('form.first_name', name_prop.get_text()) def test_reference_for_cases(self): case_data_source = get_case_data_source(self.app, self.case_type) case_data_source.save() reference = ReportBuilderDataSourceReference( self.domain, self.app, DATA_SOURCE_TYPE_RAW, case_data_source._id, ) # todo: we should filter out some of these columns expected_property_names = [ "doc_id", "inserted_at", "name", "case_type", "closed", "closed_by_user_id", "closed_date", "external_id", "last_modified_by_user_id", "last_modified_date", "opened_by_user_id", "opened_date", "owner_id", "server_last_modified_date", "state", "first_name", "last_name", "count", ] self.assertEqual(expected_property_names, list(reference.data_source_properties.keys())) owner_id_prop = reference.data_source_properties['owner_id'] self.assertEqual('owner_id', owner_id_prop.get_id()) self.assertEqual('owner_id', owner_id_prop.get_text()) first_name_prop = reference.data_source_properties['first_name'] self.assertEqual('first_name', first_name_prop.get_id()) self.assertEqual('first_name', first_name_prop.get_text()) class ReportBuilderTest(ReportBuilderDBTest): def test_data_source_exclusivity(self): """ Report builder reports based on the same form/case_type should have different data sources (they were previously sharing them) """ # Make report builder_form = ConfigureListReportForm( self.domain, "Report one", self.app._id, "form", self.form.unique_id, existing_report=None, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': '[{"property": "/data/first_name", "display_text": "<NAME>", "calculation": "Group By"}]', } ) self.assertTrue(builder_form.is_valid()) report_one = builder_form.create_report() # Make another report builder_form = ConfigureListReportForm( self.domain, "Report two", self.app._id, "form", self.form.unique_id, existing_report=None, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': '[{"property": "/data/first_name", "display_text": "<NAME>", "calculation": "Group By"}]', } ) self.assertTrue(builder_form.is_valid()) report_two = builder_form.create_report() self.assertNotEqual(report_one.config_id, report_two.config_id) def test_updating_report_data_source(self): """ Test that changing the app or number column for a report results in an update to the data source next time the report is saved. """ # Make report builder_form = ConfigureTableReportForm( self.domain, "Test Report", self.app._id, "case", "some_case_type", existing_report=None, data={ 'group_by': ['closed'], 'chart': 'bar', 'user_filters': '[]', 'default_filters': '[]', 'columns': '[{"property": "closed", "display_text": "closed", "calculation": "Count per Choice"}]', } ) self.assertTrue(builder_form.is_valid()) report = builder_form.create_report() self.assertEqual(report.config.configured_indicators[0]['datatype'], "string") # Make an edit to the first report builder report builder_form = ConfigureTableReportForm( self.domain, "Test Report", self.app._id, "case", "some_case_type", existing_report=report, data={ 'group_by': ['user_id'], 'chart': 'bar', 'user_filters': '[]', 'default_filters': '[]', # Note that a "Sum" calculation on the closed case property isn't very sensical, but doing it so # that I can have a numeric calculation without having to create real case properties for this case # type. 'columns': '[{"property": "closed", "display_text": "closed", "calculation": "Sum"}]', } ) self.assertTrue(builder_form.is_valid()) builder_form.update_report() # reload report data source, because report.config is memoized data_source = DataSourceConfiguration.get(report.config._id) # The closed property indicator should now be decimal type because the user indicated that it was numeric # by giving the column the "Sum" aggregation. self.assertEqual(data_source.configured_indicators[0]['datatype'], "decimal") def test_updating_report_that_shares_data_source(self): """ If a report builder builder report shares a data source with another report, then editing the report builder report should result in a new data source being created for the report. """ # Make report builder_form = ConfigureListReportForm( self.domain, "Test Report", self.app._id, "form", self.form.unique_id, existing_report=None, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': '[{"property": "/data/first_name", "display_text": "first name", "calculation":"Group By"}]', } ) self.assertTrue(builder_form.is_valid()) report = builder_form.create_report() # Make another report that references the same data source report_two = ReportConfiguration( domain="domain", config_id=report.config_id ) report_two.save() # Make an edit to the first report builder report builder_form = ConfigureListReportForm( self.domain, "Test Report", self.app._id, "form", self.form.unique_id, existing_report=report, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': '[{"property": "/data/first_name", "display_text": "first name", "calculation": "Group By"}]', } ) self.assertTrue(builder_form.is_valid()) report = builder_form.update_report() self.assertNotEqual(report.config_id, report_two.config_id) def test_data_source_columns(self): """ Report Builder should create a data source that includes columns for all possible aggregations, so that if the user switches between a list report and a summary report the data source has all the required columns (FB 268655) """ builder_form = ConfigureListReportForm( self.domain, "My Report", self.app._id, "form", self.form.unique_id, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': """[ {"property": "/data/first_name", "display_text": "first name"}, {"property": "/data/last_name", "display_text": "last name"}, {"property": "/data/children", "display_text": "children"} ]""", } ) self.assertTrue(builder_form.is_valid()) with patch('corehq.apps.userreports.tasks.delete_data_source_task'): data_source_config_id = builder_form.create_temp_data_source_if_necessary('<EMAIL>') data_source = DataSourceConfiguration.get(data_source_config_id) indicators = sorted([(ind['column_id'], ind['type']) for ind in data_source.configured_indicators]) expected_indicators = [ ('count', 'boolean'), ('data_children_25bd0e0d', 'expression'), # "children" should have 2 columns because it is ('data_children_25bd0e0d_decimal', 'expression'), # numeric ('data_dob_b6293169', 'expression'), ('data_first_name_ac8c51a7', 'expression'), ('data_last_name_ce36e9e1', 'expression'), ('data_state_6e36b993', 'choice_list'), ('data_state_6e36b993', 'expression'), ('deviceID_a7307e7d', 'expression'), ('timeEnd_09f40526', 'expression'), ('timeStart_c5a1ba73', 'expression'), ('userID_41e1d44e', 'expression'), ('username_ea02198f', 'expression'), ] self.assertEqual(indicators, expected_indicators) class MultiselectQuestionTest(ReportBuilderDBTest): """ Test class for report builder interactions with MultiSelect questions. """ def testReportColumnOptions(self): """ Confirm that form.report_column_options contains MultiselectQuestionColumnOption objects for mselect questions. """ builder_form = ConfigureListReportForm( self.domain, "My Report", self.app._id, "form", self.form.unique_id, ) self.assertEqual( type(builder_form.report_column_options["/data/state"]), MultiselectQuestionColumnOption ) def testDataSource(self): """ Confirm that data sources for reports with multiselects use "choice_list" indicators for mselect questions. """ builder_form = ConfigureListReportForm( self.domain, "My Report", self.app._id, "form", self.form.unique_id, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': '[' ' {"property": "/data/first_name", "display_text": "<NAME>", "calculation": "Group By"},' ' {"property": "/data/state", "display_text": "state", "calculation": "Count Per Choice"}' ']', } ) self.assertTrue(builder_form.is_valid()) report = builder_form.create_report() data_source = report.config mselect_indicators = [i for i in data_source.configured_indicators if i["type"] == "choice_list"] self.assertEqual(len(mselect_indicators), 1) mselect_indicator = mselect_indicators[0] self.assertEqual(set(mselect_indicator['choices']), {'MA', 'MN', 'VT'}) def test_multiselect_aggregation(self): """ Check report column aggregation for multi-select questions set to "group by" """ builder_form = ConfigureTableReportForm( self.domain, "My Report", self.app._id, "form", self.form.unique_id, data={ 'user_filters': '[]', 'default_filters': '[]', 'columns': '[{"property": "/data/state", "display_text": "state", "calculation": "Group By"}]', 'chart': 'pie', } ) self.assertTrue(builder_form.is_valid()) report = builder_form.create_report() self.assertEqual(report.columns[0]['aggregation'], 'simple')
awatson1978/inferno-core
lib/inferno/dsl/fhir_client_builder.rb
require 'fhir_client' module Inferno module DSL # DSL for configuring FHIR clients class FHIRClientBuilder attr_accessor :runnable # @private def build(runnable, block) self.runnable = runnable instance_exec(self, &block) FHIR::Client.new(url).tap do |client| client.additional_headers = headers if headers client.default_json client.set_bearer_token bearer_token if bearer_token end end # Define the base FHIR url for a client. A string or symbol can be provided. # A string is interpreted as a url. A symbol is interpreted as the name of # an input to the Runnable. # # @param url [String, Symbol] # @return [void] def url(url = nil) @url ||= if url.is_a? Symbol runnable.send(url) else url end end # Define the bearer token for a client. A string or symbol can be provided. # A string is interpreted as a token. A symbol is interpreted as the name of # an input to the Runnable. # # @param bearer_token [String, Symbol] # @return [void] def bearer_token(bearer_token = nil) @bearer_token ||= if bearer_token.is_a? Symbol runnable.send(bearer_token) else bearer_token end end # Define custom headers for a client # # @param headers [Hash] # @return [void] def headers(headers = nil) @headers ||= headers end # @private def method_missing(name, *args, &block) return runnable.call(name, *args, &block) if runnable.respond_to? name super end # @private def respond_to_missing?(name) runnable.respond_to?(name) || super end end end end
nakedible/vpnease-l2tp
openswan/openswan-2.4.0rc4.quilt/programs/pluto/rcv_whack.c
<reponame>nakedible/vpnease-l2tp /* whack communicating routines * Copyright (C) 1997 <NAME>. * Copyright (C) 1998-2001 <NAME>. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * RCSID $Id: rcv_whack.c,v 1.116 2005/05/19 14:58:55 mcr Exp $ */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <arpa/inet.h> #include <resolv.h> #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */ #include <sys/queue.h> #include <openswan.h> #include "pfkeyv2.h" #include "constants.h" #include "defs.h" #include "id.h" #include "x509.h" #include "pgp.h" #include "certs.h" #include "paths.h" #include "ac.h" #include "smartcard.h" #ifdef XAUTH_USEPAM #include <security/pam_appl.h> #endif #include "connections.h" /* needs id.h */ #include "foodgroups.h" #include "whack.h" /* needs connections.h */ #include "packet.h" #include "demux.h" /* needs packet.h */ #include "state.h" #include "ipsec_doi.h" /* needs demux.h and state.h */ #include "kernel.h" /* needs connections.h */ #include "rcv_whack.h" #include "log.h" #include "keys.h" #include "secrets.h" #include "adns.h" /* needs <resolv.h> */ #include "dnskey.h" /* needs keys.h and adns.h */ #include "server.h" #include "fetch.h" #include "ocsp.h" #include "timer.h" #include "kernel_alg.h" #include "ike_alg.h" /* bits loading keys from asynchronous DNS */ enum key_add_attempt { ka_TXT, #ifdef USE_KEYRR ka_KEY, #endif ka_roof /* largest value + 1 */ }; struct key_add_common { int refCount; char *diag[ka_roof]; int whack_fd; bool success; }; struct key_add_continuation { struct adns_continuation ac; /* common prefix */ struct key_add_common *common; /* common data */ enum key_add_attempt lookingfor; }; static void key_add_ugh(const struct id *keyid, err_t ugh) { char name[IDTOA_BUF]; /* longer IDs will be truncated in message */ (void)idtoa(keyid, name, sizeof(name)); loglog(RC_NOKEY , "failure to fetch key for %s from DNS: %s", name, ugh); } /* last one out: turn out the lights */ static void key_add_merge(struct key_add_common *oc, const struct id *keyid) { if (oc->refCount == 0) { enum key_add_attempt kaa; /* if no success, print all diagnostics */ if (!oc->success) for (kaa = ka_TXT; kaa != ka_roof; kaa++) key_add_ugh(keyid, oc->diag[kaa]); for (kaa = ka_TXT; kaa != ka_roof; kaa++) pfreeany(oc->diag[kaa]); close(oc->whack_fd); pfree(oc); } } static void key_add_continue(struct adns_continuation *ac, err_t ugh) { struct key_add_continuation *kc = (void *) ac; struct key_add_common *oc = kc->common; passert(whack_log_fd == NULL_FD); whack_log_fd = oc->whack_fd; if (ugh != NULL) { oc->diag[kc->lookingfor] = clone_str(ugh, "key add error"); } else { oc->success = TRUE; transfer_to_public_keys(kc->ac.gateways_from_dns #ifdef USE_KEYRR , &kc->ac.keys_from_dns #endif /* USE_KEYRR */ ); } oc->refCount--; key_add_merge(oc, &ac->id); whack_log_fd = NULL_FD; } static void key_add_request(const struct whack_message *msg) { struct id keyid; err_t ugh = atoid(msg->keyid, &keyid, FALSE); if (ugh != NULL) { loglog(RC_BADID, "bad --keyid \"%s\": %s", msg->keyid, ugh); } else { if (!msg->whack_addkey) delete_public_keys(&keyid, msg->pubkey_alg); if (msg->keyval.len == 0) { struct key_add_common *oc = alloc_thing(struct key_add_common , "key add common things"); enum key_add_attempt kaa; /* initialize state shared by queries */ oc->refCount = 0; oc->whack_fd = dup_any(whack_log_fd); oc->success = FALSE; for (kaa = ka_TXT; kaa != ka_roof; kaa++) { struct key_add_continuation *kc = alloc_thing(struct key_add_continuation , "key add continuation"); oc->diag[kaa] = NULL; oc->refCount++; kc->common = oc; kc->lookingfor = kaa; switch (kaa) { case ka_TXT: ugh = start_adns_query(&keyid , &keyid /* same */ , T_TXT , key_add_continue , &kc->ac); break; #ifdef USE_KEYRR case ka_KEY: ugh = start_adns_query(&keyid , NULL , T_KEY , key_add_continue , &kc->ac); break; #endif /* USE_KEYRR */ default: bad_case(kaa); /* suppress gcc warning */ } if (ugh != NULL) { oc->diag[kaa] = clone_str(ugh, "early key add failure"); oc->refCount--; } } /* Done launching queries. * Handle total failure case. */ key_add_merge(oc, &keyid); } else { ugh = add_public_key(&keyid, DAL_LOCAL, msg->pubkey_alg , &msg->keyval, &pubkeys); if (ugh != NULL) loglog(RC_LOG_SERIOUS, "%s", ugh); } } } /* Handle a kernel request. Supposedly, there's a message in * the kernelsock socket. */ void whack_handle(int whackctlfd) { struct whack_message msg; struct sockaddr_un whackaddr; int whackaddrlen = sizeof(whackaddr); int whackfd = accept(whackctlfd, (struct sockaddr *)&whackaddr, &whackaddrlen); /* Note: actual value in n should fit in int. To print, cast to int. */ ssize_t n; //DBG_log("whack_crash %d\n", msg.whack_crash); if (whackfd < 0) { log_errno((e, "accept() failed in whack_handle()")); return; } n = read(whackfd, &msg, sizeof(msg)); if (n == -1) { log_errno((e, "read() failed in whack_handle()")); close(whackfd); return; } whack_log_fd = whackfd; /* sanity check message */ { err_t ugh = NULL; struct whackpacker wp; wp.msg = &msg; wp.n = n; wp.str_next = msg.string; wp.str_roof = (char *)&msg + n; if ((size_t)n < offsetof(struct whack_message, whack_shutdown) + sizeof(msg.whack_shutdown)) { ugh = builddiag("ignoring runt message from whack: got %d bytes", (int)n); } else if (msg.magic != WHACK_MAGIC) { if (msg.magic == WHACK_BASIC_MAGIC) { /* Only basic commands. Simpler inter-version compatability. */ if (msg.whack_status) show_status(); if (msg.whack_shutdown) { openswan_log("shutting down"); exit_pluto(0); /* delete lock and leave, with 0 status */ } ugh = ""; /* bail early, but without complaint */ } else { ugh = builddiag("ignoring message from whack with bad magic %d; should be %d; Mismatched versions of userland tools and KLIPS code." , msg.magic, WHACK_MAGIC); } } else if ((ugh = unpack_whack_msg(&wp)) != NULL) { /* nothing, ugh is already set */ } else { msg.keyval.ptr = wp.str_next; /* grab chunk */ } if (ugh != NULL) { if (*ugh != '\0') loglog(RC_BADWHACKMESSAGE, "%s", ugh); whack_log_fd = NULL_FD; close(whackfd); return; } } //DBG_log("whack_crash %d\n", msg.whack_crash); if (msg.whack_options) { #ifdef DEBUG if (msg.name == NULL) { /* we do a two-step so that if either old or new would * cause the message to print, it will be printed. */ set_debugging(cur_debugging | msg.debugging); DBG(DBG_CONTROL , DBG_log("base debugging = %s" , bitnamesof(debug_bit_names, msg.debugging))); base_debugging = msg.debugging; set_debugging(base_debugging); } else if (!msg.whack_connection) { struct connection *c = con_by_name(msg.name, TRUE); if (c != NULL) { c->extra_debugging = msg.debugging; DBG(DBG_CONTROL , DBG_log("\"%s\" extra_debugging = %s" , c->name , bitnamesof(debug_bit_names, c->extra_debugging))); } } #endif } if (msg.whack_myid) set_myid(MYID_SPECIFIED, msg.myid); /* Deleting combined with adding a connection works as replace. * To make this more useful, in only this combination, * delete will silently ignore the lack of the connection. */ if (msg.whack_delete) delete_connections_by_name(msg.name, !msg.whack_connection); if (msg.whack_deletestate) { struct state *st = state_with_serialno(msg.whack_deletestateno); if (st == NULL) { loglog(RC_UNKNOWN_NAME, "no state #%lu to delete" , msg.whack_deletestateno); } else { delete_state(st); } } if (msg.whack_crash) delete_states_by_peer(&msg.whack_crash_peer); if (msg.whack_connection) add_connection(&msg); /* process "listen" before any operation that could require it */ if (msg.whack_listen) { close_peerlog(); /* close any open per-peer logs */ openswan_log("listening for IKE messages"); listening = TRUE; daily_log_reset(); reset_adns_restart_count(); set_myFQDN(); find_ifaces(); load_preshared_secrets(NULL_FD); load_groups(); } if (msg.whack_unlisten) { openswan_log("no longer listening for IKE messages"); listening = FALSE; } if (msg.whack_reread & REREAD_SECRETS) { load_preshared_secrets(whackfd); } if (msg.whack_list & LIST_PUBKEYS) { list_public_keys(msg.whack_utc); } if (msg.whack_reread & REREAD_CACERTS) { load_authcerts("CA cert", CA_CERT_PATH, AUTH_CA); } if (msg.whack_reread & REREAD_AACERTS) { load_authcerts("AA cert", AA_CERT_PATH, AUTH_AA); } if (msg.whack_reread & REREAD_OCSPCERTS) { load_authcerts("OCSP cert", OCSP_CERT_PATH, AUTH_OCSP); } if (msg.whack_reread & REREAD_ACERTS) { load_acerts(); } if (msg.whack_reread & REREAD_CRLS) { load_crls(); } #ifdef HAVE_OCSP if (msg.whack_purgeocsp) { free_ocsp_fetch(); free_ocsp_cache(); } #endif if (msg.whack_list & LIST_CERTS) { list_certs(msg.whack_utc); } if (msg.whack_list & LIST_AACERTS) { list_authcerts("AA", AUTH_AA, msg.whack_utc); } if (msg.whack_list & LIST_OCSPCERTS) { list_authcerts("OCSP", AUTH_OCSP, msg.whack_utc); } if (msg.whack_list & LIST_ACERTS) { list_acerts(msg.whack_utc); } if (msg.whack_list & LIST_GROUPS) { list_groups(msg.whack_utc); } if (msg.whack_list & LIST_CACERTS) { list_authcerts("CA", AUTH_CA, msg.whack_utc); } if (msg.whack_list & LIST_CRLS) { list_crls(msg.whack_utc, strict_crl_policy); #ifdef HAVE_THREADS list_crl_fetch_requests(msg.whack_utc); #endif } #ifdef HAVE_OCSP if (msg.whack_list & LIST_OCSP) { list_ocsp_cache(msg.whack_utc, strict_crl_policy); list_ocsp_fetch_requests(msg.whack_utc); } #endif #ifdef SMARTCARD if (msg.whack_list & LIST_CARDS) { scx_list(msg.whack_utc); } #endif if (msg.whack_list & LIST_EVENTS) { timer_list(); } if (msg.whack_key) { /* add a public key */ key_add_request(&msg); } if (msg.whack_route) { if (!listening) whack_log(RC_DEAF, "need --listen before --route"); else { struct connection *c = con_by_name(msg.name, TRUE); if (c != NULL) { set_cur_connection(c); if (!oriented(*c)) whack_log(RC_ORIENT , "we cannot identify ourselves with either end of this connection"); else if (c->policy & POLICY_GROUP) route_group(c); else if (!trap_connection(c)) whack_log(RC_ROUTE, "could not route"); reset_cur_connection(); } } } if (msg.whack_unroute) { struct connection *c = con_by_name(msg.name, TRUE); if (c != NULL) { struct spd_route *sr; int fail = 0; set_cur_connection(c); for (sr = &c->spd; sr != NULL; sr = sr->next) { if (sr->routing >= RT_ROUTED_TUNNEL) fail++; } if (fail > 0) whack_log(RC_RTBUSY, "cannot unroute: route busy"); else if (c->policy & POLICY_GROUP) unroute_group(c); else unroute_connection(c); reset_cur_connection(); } } if (msg.whack_initiate) { if (!listening) whack_log(RC_DEAF, "need --listen before --initiate"); else initiate_connection(msg.name , msg.whack_async? NULL_FD : dup_any(whackfd) , msg.debugging , pcim_demand_crypto); } if (msg.whack_oppo_initiate) { if (!listening) whack_log(RC_DEAF, "need --listen before opportunistic initiation"); else initiate_opportunistic(&msg.oppo_my_client, &msg.oppo_peer_client, 0 , FALSE , msg.whack_async? NULL_FD : dup_any(whackfd), "whack"); } if (msg.whack_terminate) terminate_connection(msg.name); if (msg.whack_status) show_status(); if (msg.whack_shutdown) { openswan_log("shutting down"); exit_pluto(0); /* delete lock and leave, with 0 status */ } whack_log_fd = NULL_FD; close(whackfd); } /* * interactive input from the whack user, using current whack_fd */ bool whack_prompt_for(int whackfd , const char *prompt1 , const char *prompt2 , bool echo , char *ansbuf, size_t ansbuf_len) { int savewfd = whack_log_fd; ssize_t n; whack_log_fd = whackfd; DBG(DBG_CONTROLMORE, DBG_log("prompting for %s:", prompt2)); whack_log(echo ? RC_XAUTHPROMPT : RC_ENTERSECRET , "%s prompt for %s:" , prompt1, prompt2); whack_log_fd = savewfd; n = read(whackfd, ansbuf, ansbuf_len); if(n == -1) { whack_log(RC_LOG_SERIOUS, "read(whackfd) failed: %s", strerror(errno)); return FALSE; } if(strlen(ansbuf) == 0) { whack_log(RC_LOG_SERIOUS, "no %s entered, aborted", prompt2); return FALSE; } return TRUE; } /* * Local Variables: * c-basic-offset:4 * c-style: pluto * End: */
ChronicallySerious/Rootex
rootex/vendor/Effekseer/effekseer/src/EffekseerRendererDX11/EffekseerRenderer/Shader/EffekseerRenderer.ModelRenderer.ShaderTexture_VS.h
#if 0 // // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111 // // // fxc /Zpc /Tvs_5_0 /EVS /D __EFFEKSEER_BUILD_VERSION16__=1 /Fh // Shader/EffekseerRenderer.ModelRenderer.ShaderTexture_VS.h // Shader/model_renderer_texture_VS.fx // // // Buffer Definitions: // // cbuffer VS_ConstantBuffer // { // // float4x4 mCameraProj; // Offset: 0 Size: 64 // float4x4 mModel[40]; // Offset: 64 Size: 2560 // float4 fUV[40]; // Offset: 2624 Size: 640 // float4 fAlphaUV[40]; // Offset: 3264 Size: 640 // float4 fFlipbookParameter; // Offset: 3904 Size: 16 // float4 fFlipbookIndexAndNextRate[40];// Offset: 3920 Size: 640 // float4 fModelAlphaThreshold[40]; // Offset: 4560 Size: 640 // float4 fModelColor[40]; // Offset: 5200 Size: 640 // float4 fLightDirection; // Offset: 5840 Size: 16 [unused] // float4 fLightColor; // Offset: 5856 Size: 16 [unused] // float4 fLightAmbient; // Offset: 5872 Size: 16 [unused] // float4 mUVInversed; // Offset: 5888 Size: 16 // // } // // // Resource Bindings: // // Name Type Format Dim Slot Elements // ------------------------------ ---------- ------- ----------- ---- -------- // VS_ConstantBuffer cbuffer NA NA 0 1 // // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------ ------ // POSITION 0 xyz 0 NONE float xyz // NORMAL 0 xyz 1 NONE float // NORMAL 1 xyz 2 NONE float // NORMAL 2 xyz 3 NONE float // TEXCOORD 0 xy 4 NONE float xy // NORMAL 3 xyzw 5 NONE float xyzw // BLENDINDICES 0 xyzw 6 NONE uint x // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------ ------ // SV_POSITION 0 xyzw 0 POS float xyzw // TEXCOORD 0 xy 1 NONE float xy // TEXCOORD 1 zw 1 NONE float zw // TEXCOORD 2 x 2 NONE float x // TEXCOORD 3 yz 2 NONE float yz // TEXCOORD 4 w 2 NONE float w // COLOR 0 xyzw 3 NONE float xyzw // vs_5_0 dcl_globalFlags refactoringAllowed dcl_constantbuffer cb0[369], dynamicIndexed dcl_input v0.xyz dcl_input v4.xy dcl_input v5.xyzw dcl_input v6.x dcl_output_siv o0.xyzw, position dcl_output o1.xy dcl_output o1.zw dcl_output o2.x dcl_output o2.yz dcl_output o2.w dcl_output o3.xyzw dcl_temps 5 ishl r0.x, v6.x, l(2) mov r0.y, v6.x mul o3.xyzw, v5.xyzw, cb0[r0.y + 325].xyzw mul r1.xyzw, v0.yyyy, cb0[r0.x + 5].xyzw mad r1.xyzw, cb0[r0.x + 4].xyzw, v0.xxxx, r1.xyzw mad r1.xyzw, cb0[r0.x + 6].xyzw, v0.zzzz, r1.xyzw add r1.xyzw, r1.xyzw, cb0[r0.x + 7].xyzw mul r2.xyzw, r1.yyyy, cb0[1].xyzw mad r2.xyzw, cb0[0].xyzw, r1.xxxx, r2.xyzw mad r2.xyzw, cb0[2].xyzw, r1.zzzz, r2.xyzw mad o0.xyzw, cb0[3].xyzw, r1.wwww, r2.xyzw mad o1.x, v4.x, cb0[r0.y + 164].z, cb0[r0.y + 164].x mad r0.x, v4.y, cb0[r0.y + 164].w, cb0[r0.y + 164].y mad o1.z, v4.x, cb0[r0.y + 204].z, cb0[r0.y + 204].x mad r0.z, v4.y, cb0[r0.y + 204].w, cb0[r0.y + 204].y lt r0.w, l(0.000000), cb0[244].x if_nz r0.w frc r1.x, cb0[r0.y + 245].x round_ni r0.w, cb0[r0.y + 245].x add r0.w, r0.w, l(1.000000) eq r2.x, cb0[244].y, l(0.000000) if_nz r2.x mul r2.x, cb0[244].w, cb0[244].z ge r2.x, r0.w, r2.x mad r2.y, cb0[244].z, cb0[244].w, l(-1.000000) movc r2.x, r2.x, r2.y, r0.w else mul r2.y, cb0[244].w, cb0[244].z mul r2.z, r0.w, r2.y ge r2.z, r2.z, -r2.z movc r2.z, r2.z, r2.y, -r2.y div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.z mul r2.w, r0.w, r2.w frc r2.w, r2.w mul r3.x, r2.w, r2.z eq r3.yz, cb0[244].yyyy, l(0.000000, 1.000000, 2.000000, 0.000000) div r2.y, r0.w, r2.y add r3.w, r2.y, r2.y ge r3.w, r3.w, -r3.w movc r4.xy, r3.wwww, l(2.000000,0.500000,0,0), l(-2.000000,-0.500000,0,0) mul r2.y, r2.y, r4.y frc r2.y, r2.y mul r2.y, r2.y, r4.x eq r2.y, r2.y, l(1.000000) mad r3.w, cb0[244].z, cb0[244].w, l(-1.000000) mad r2.z, -r2.z, r2.w, r3.w movc r2.y, r2.y, r2.z, r3.x movc r0.w, r3.z, r2.y, r0.w movc r2.x, r3.y, r3.x, r0.w endif ftoi r0.w, r2.x ftoi r2.xy, cb0[244].zwzz and r2.z, r0.w, l(0x80000000) imax r2.w, r0.w, -r0.w imax r3.xy, r2.xyxx, -r2.xyxx udiv null, r2.x, r2.w, r3.x ineg r3.x, r2.x movc r2.x, r2.z, r3.x, r2.x itof r4.y, r2.x xor r0.w, r0.w, r2.y udiv r2.x, null, r2.w, r3.y ineg r2.y, r2.x and r0.w, r0.w, l(0x80000000) movc r0.w, r0.w, r2.y, r2.x itof r4.z, r0.w div r2.xy, l(1.000000, 1.000000, 1.000000, 1.000000), cb0[244].zwzz mul r2.zw, r2.xxxy, r4.yyyz mad r1.yz, v4.xxyx, r2.xxyx, r2.zzwz else mov r1.xyz, l(0,0,0,0) endif mad o1.y, cb0[368].y, r0.x, cb0[368].x mad o1.w, cb0[368].y, r0.z, cb0[368].x mov r1.w, cb0[r0.y + 285].x mov o2.xyzw, r1.xyzw ret // Approximately 76 instruction slots used #endif const BYTE g_VS[] = { 68, 88, 66, 67, 240, 136, 119, 47, 74, 233, 127, 148, 181, 45, 84, 16, 231, 26, 100, 44, 1, 0, 0, 0, 56, 17, 0, 0, 5, 0, 0, 0, 52, 0, 0, 0, 184, 4, 0, 0, 152, 5, 0, 0, 108, 6, 0, 0, 156, 16, 0, 0, 82, 68, 69, 70, 124, 4, 0, 0, 1, 0, 0, 0, 112, 0, 0, 0, 1, 0, 0, 0, 60, 0, 0, 0, 0, 5, 254, 255, 16, 1, 0, 0, 74, 4, 0, 0, 82, 68, 49, 49, 60, 0, 0, 0, 24, 0, 0, 0, 32, 0, 0, 0, 40, 0, 0, 0, 36, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 86, 83, 95, 67, 111, 110, 115, 116, 97, 110, 116, 66, 117, 102, 102, 101, 114, 0, 171, 171, 92, 0, 0, 0, 12, 0, 0, 0, 136, 0, 0, 0, 16, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 104, 2, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 2, 0, 0, 0, 128, 2, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 164, 2, 0, 0, 64, 0, 0, 0, 0, 10, 0, 0, 2, 0, 0, 0, 172, 2, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 208, 2, 0, 0, 64, 10, 0, 0, 128, 2, 0, 0, 2, 0, 0, 0, 220, 2, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 3, 0, 0, 192, 12, 0, 0, 128, 2, 0, 0, 2, 0, 0, 0, 12, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 48, 3, 0, 0, 64, 15, 0, 0, 16, 0, 0, 0, 2, 0, 0, 0, 68, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 104, 3, 0, 0, 80, 15, 0, 0, 128, 2, 0, 0, 2, 0, 0, 0, 132, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 168, 3, 0, 0, 208, 17, 0, 0, 128, 2, 0, 0, 2, 0, 0, 0, 192, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 228, 3, 0, 0, 80, 20, 0, 0, 128, 2, 0, 0, 2, 0, 0, 0, 240, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 20, 4, 0, 0, 208, 22, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 68, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 36, 4, 0, 0, 224, 22, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 68, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 48, 4, 0, 0, 240, 22, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 68, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 62, 4, 0, 0, 0, 23, 0, 0, 16, 0, 0, 0, 2, 0, 0, 0, 68, 3, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 109, 67, 97, 109, 101, 114, 97, 80, 114, 111, 106, 0, 102, 108, 111, 97, 116, 52, 120, 52, 0, 171, 171, 171, 3, 0, 3, 0, 4, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 2, 0, 0, 109, 77, 111, 100, 101, 108, 0, 171, 3, 0, 3, 0, 4, 0, 4, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 2, 0, 0, 102, 85, 86, 0, 102, 108, 111, 97, 116, 52, 0, 171, 1, 0, 3, 0, 1, 0, 4, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 0, 0, 102, 65, 108, 112, 104, 97, 85, 86, 0, 171, 171, 171, 1, 0, 3, 0, 1, 0, 4, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 0, 0, 102, 70, 108, 105, 112, 98, 111, 111, 107, 80, 97, 114, 97, 109, 101, 116, 101, 114, 0, 171, 1, 0, 3, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 0, 0, 102, 70, 108, 105, 112, 98, 111, 111, 107, 73, 110, 100, 101, 120, 65, 110, 100, 78, 101, 120, 116, 82, 97, 116, 101, 0, 171, 171, 1, 0, 3, 0, 1, 0, 4, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 0, 0, 102, 77, 111, 100, 101, 108, 65, 108, 112, 104, 97, 84, 104, 114, 101, 115, 104, 111, 108, 100, 0, 171, 171, 171, 1, 0, 3, 0, 1, 0, 4, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 0, 0, 102, 77, 111, 100, 101, 108, 67, 111, 108, 111, 114, 0, 1, 0, 3, 0, 1, 0, 4, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212, 2, 0, 0, 102, 76, 105, 103, 104, 116, 68, 105, 114, 101, 99, 116, 105, 111, 110, 0, 102, 76, 105, 103, 104, 116, 67, 111, 108, 111, 114, 0, 102, 76, 105, 103, 104, 116, 65, 109, 98, 105, 101, 110, 116, 0, 109, 85, 86, 73, 110, 118, 101, 114, 115, 101, 100, 0, 77, 105, 99, 114, 111, 115, 111, 102, 116, 32, 40, 82, 41, 32, 72, 76, 83, 76, 32, 83, 104, 97, 100, 101, 114, 32, 67, 111, 109, 112, 105, 108, 101, 114, 32, 57, 46, 50, 57, 46, 57, 53, 50, 46, 51, 49, 49, 49, 0, 171, 73, 83, 71, 78, 216, 0, 0, 0, 7, 0, 0, 0, 8, 0, 0, 0, 176, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 185, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 7, 0, 0, 0, 185, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 7, 0, 0, 0, 185, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 7, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 3, 3, 0, 0, 185, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 5, 0, 0, 0, 15, 15, 0, 0, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 6, 0, 0, 0, 15, 1, 0, 0, 80, 79, 83, 73, 84, 73, 79, 78, 0, 78, 79, 82, 77, 65, 76, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 66, 76, 69, 78, 68, 73, 78, 68, 73, 67, 69, 83, 0, 171, 171, 79, 83, 71, 78, 204, 0, 0, 0, 7, 0, 0, 0, 8, 0, 0, 0, 176, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 188, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 3, 12, 0, 0, 188, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 12, 3, 0, 0, 188, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 1, 14, 0, 0, 188, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 6, 9, 0, 0, 188, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 8, 7, 0, 0, 197, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 15, 0, 0, 0, 83, 86, 95, 80, 79, 83, 73, 84, 73, 79, 78, 0, 84, 69, 88, 67, 79, 79, 82, 68, 0, 67, 79, 76, 79, 82, 0, 171, 83, 72, 69, 88, 40, 10, 0, 0, 80, 0, 1, 0, 138, 2, 0, 0, 106, 8, 0, 1, 89, 8, 0, 4, 70, 142, 32, 0, 0, 0, 0, 0, 113, 1, 0, 0, 95, 0, 0, 3, 114, 16, 16, 0, 0, 0, 0, 0, 95, 0, 0, 3, 50, 16, 16, 0, 4, 0, 0, 0, 95, 0, 0, 3, 242, 16, 16, 0, 5, 0, 0, 0, 95, 0, 0, 3, 18, 16, 16, 0, 6, 0, 0, 0, 103, 0, 0, 4, 242, 32, 16, 0, 0, 0, 0, 0, 1, 0, 0, 0, 101, 0, 0, 3, 50, 32, 16, 0, 1, 0, 0, 0, 101, 0, 0, 3, 194, 32, 16, 0, 1, 0, 0, 0, 101, 0, 0, 3, 18, 32, 16, 0, 2, 0, 0, 0, 101, 0, 0, 3, 98, 32, 16, 0, 2, 0, 0, 0, 101, 0, 0, 3, 130, 32, 16, 0, 2, 0, 0, 0, 101, 0, 0, 3, 242, 32, 16, 0, 3, 0, 0, 0, 104, 0, 0, 2, 5, 0, 0, 0, 41, 0, 0, 7, 18, 0, 16, 0, 0, 0, 0, 0, 10, 16, 16, 0, 6, 0, 0, 0, 1, 64, 0, 0, 2, 0, 0, 0, 54, 0, 0, 5, 34, 0, 16, 0, 0, 0, 0, 0, 10, 16, 16, 0, 6, 0, 0, 0, 56, 0, 0, 10, 242, 32, 16, 0, 3, 0, 0, 0, 70, 30, 16, 0, 5, 0, 0, 0, 70, 142, 32, 6, 0, 0, 0, 0, 69, 1, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 56, 0, 0, 10, 242, 0, 16, 0, 1, 0, 0, 0, 86, 21, 16, 0, 0, 0, 0, 0, 70, 142, 32, 6, 0, 0, 0, 0, 5, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 50, 0, 0, 12, 242, 0, 16, 0, 1, 0, 0, 0, 70, 142, 32, 6, 0, 0, 0, 0, 4, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 6, 16, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 1, 0, 0, 0, 50, 0, 0, 12, 242, 0, 16, 0, 1, 0, 0, 0, 70, 142, 32, 6, 0, 0, 0, 0, 6, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 166, 26, 16, 0, 0, 0, 0, 0, 70, 14, 16, 0, 1, 0, 0, 0, 0, 0, 0, 10, 242, 0, 16, 0, 1, 0, 0, 0, 70, 14, 16, 0, 1, 0, 0, 0, 70, 142, 32, 6, 0, 0, 0, 0, 7, 0, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 56, 0, 0, 8, 242, 0, 16, 0, 2, 0, 0, 0, 86, 5, 16, 0, 1, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 1, 0, 0, 0, 50, 0, 0, 10, 242, 0, 16, 0, 2, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 16, 0, 1, 0, 0, 0, 70, 14, 16, 0, 2, 0, 0, 0, 50, 0, 0, 10, 242, 0, 16, 0, 2, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 2, 0, 0, 0, 166, 10, 16, 0, 1, 0, 0, 0, 70, 14, 16, 0, 2, 0, 0, 0, 50, 0, 0, 10, 242, 32, 16, 0, 0, 0, 0, 0, 70, 142, 32, 0, 0, 0, 0, 0, 3, 0, 0, 0, 246, 15, 16, 0, 1, 0, 0, 0, 70, 14, 16, 0, 2, 0, 0, 0, 50, 0, 0, 15, 18, 32, 16, 0, 1, 0, 0, 0, 10, 16, 16, 0, 4, 0, 0, 0, 42, 128, 32, 6, 0, 0, 0, 0, 164, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 10, 128, 32, 6, 0, 0, 0, 0, 164, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 50, 0, 0, 15, 18, 0, 16, 0, 0, 0, 0, 0, 26, 16, 16, 0, 4, 0, 0, 0, 58, 128, 32, 6, 0, 0, 0, 0, 164, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 26, 128, 32, 6, 0, 0, 0, 0, 164, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 50, 0, 0, 15, 66, 32, 16, 0, 1, 0, 0, 0, 10, 16, 16, 0, 4, 0, 0, 0, 42, 128, 32, 6, 0, 0, 0, 0, 204, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 10, 128, 32, 6, 0, 0, 0, 0, 204, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 50, 0, 0, 15, 66, 0, 16, 0, 0, 0, 0, 0, 26, 16, 16, 0, 4, 0, 0, 0, 58, 128, 32, 6, 0, 0, 0, 0, 204, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 26, 128, 32, 6, 0, 0, 0, 0, 204, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 49, 0, 0, 8, 130, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 10, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 31, 0, 4, 3, 58, 0, 16, 0, 0, 0, 0, 0, 26, 0, 0, 8, 18, 0, 16, 0, 1, 0, 0, 0, 10, 128, 32, 6, 0, 0, 0, 0, 245, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 65, 0, 0, 8, 130, 0, 16, 0, 0, 0, 0, 0, 10, 128, 32, 6, 0, 0, 0, 0, 245, 0, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 7, 130, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 63, 24, 0, 0, 8, 18, 0, 16, 0, 2, 0, 0, 0, 26, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 31, 0, 4, 3, 10, 0, 16, 0, 2, 0, 0, 0, 56, 0, 0, 9, 18, 0, 16, 0, 2, 0, 0, 0, 58, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 42, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 29, 0, 0, 7, 18, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 50, 0, 0, 11, 34, 0, 16, 0, 2, 0, 0, 0, 42, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 58, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 191, 55, 0, 0, 9, 18, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 18, 0, 0, 1, 56, 0, 0, 9, 34, 0, 16, 0, 2, 0, 0, 0, 58, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 42, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 56, 0, 0, 7, 66, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 29, 0, 0, 8, 66, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 128, 65, 0, 0, 0, 2, 0, 0, 0, 55, 0, 0, 10, 66, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 128, 65, 0, 0, 0, 2, 0, 0, 0, 14, 0, 0, 10, 130, 0, 16, 0, 2, 0, 0, 0, 2, 64, 0, 0, 0, 0, 128, 63, 0, 0, 128, 63, 0, 0, 128, 63, 0, 0, 128, 63, 42, 0, 16, 0, 2, 0, 0, 0, 56, 0, 0, 7, 130, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 2, 0, 0, 0, 26, 0, 0, 5, 130, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 2, 0, 0, 0, 56, 0, 0, 7, 18, 0, 16, 0, 3, 0, 0, 0, 58, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 0, 2, 0, 0, 0, 24, 0, 0, 11, 98, 0, 16, 0, 3, 0, 0, 0, 86, 133, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 0, 0, 14, 0, 0, 7, 34, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 0, 0, 0, 7, 130, 0, 16, 0, 3, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 29, 0, 0, 8, 130, 0, 16, 0, 3, 0, 0, 0, 58, 0, 16, 0, 3, 0, 0, 0, 58, 0, 16, 128, 65, 0, 0, 0, 3, 0, 0, 0, 55, 0, 0, 15, 50, 0, 16, 0, 4, 0, 0, 0, 246, 15, 16, 0, 3, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 64, 0, 0, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 192, 0, 0, 0, 191, 0, 0, 0, 0, 0, 0, 0, 0, 56, 0, 0, 7, 34, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 4, 0, 0, 0, 26, 0, 0, 5, 34, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 56, 0, 0, 7, 34, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 4, 0, 0, 0, 24, 0, 0, 7, 34, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 63, 50, 0, 0, 11, 130, 0, 16, 0, 3, 0, 0, 0, 42, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 58, 128, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 1, 64, 0, 0, 0, 0, 128, 191, 50, 0, 0, 10, 66, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 128, 65, 0, 0, 0, 2, 0, 0, 0, 58, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 3, 0, 0, 0, 55, 0, 0, 9, 34, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 3, 0, 0, 0, 55, 0, 0, 9, 130, 0, 16, 0, 0, 0, 0, 0, 42, 0, 16, 0, 3, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 55, 0, 0, 9, 18, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 3, 0, 0, 0, 10, 0, 16, 0, 3, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 21, 0, 0, 1, 27, 0, 0, 5, 130, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 27, 0, 0, 6, 50, 0, 16, 0, 2, 0, 0, 0, 230, 138, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 1, 0, 0, 7, 66, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 128, 36, 0, 0, 8, 130, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 128, 65, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 8, 50, 0, 16, 0, 3, 0, 0, 0, 70, 0, 16, 0, 2, 0, 0, 0, 70, 0, 16, 128, 65, 0, 0, 0, 2, 0, 0, 0, 78, 0, 0, 8, 0, 208, 0, 0, 18, 0, 16, 0, 2, 0, 0, 0, 58, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 3, 0, 0, 0, 40, 0, 0, 5, 18, 0, 16, 0, 3, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 55, 0, 0, 9, 18, 0, 16, 0, 2, 0, 0, 0, 42, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 3, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 43, 0, 0, 5, 34, 0, 16, 0, 4, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 87, 0, 0, 7, 130, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 78, 0, 0, 8, 18, 0, 16, 0, 2, 0, 0, 0, 0, 208, 0, 0, 58, 0, 16, 0, 2, 0, 0, 0, 26, 0, 16, 0, 3, 0, 0, 0, 40, 0, 0, 5, 34, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 1, 0, 0, 7, 130, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 128, 55, 0, 0, 9, 130, 0, 16, 0, 0, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 26, 0, 16, 0, 2, 0, 0, 0, 10, 0, 16, 0, 2, 0, 0, 0, 43, 0, 0, 5, 66, 0, 16, 0, 4, 0, 0, 0, 58, 0, 16, 0, 0, 0, 0, 0, 14, 0, 0, 11, 50, 0, 16, 0, 2, 0, 0, 0, 2, 64, 0, 0, 0, 0, 128, 63, 0, 0, 128, 63, 0, 0, 128, 63, 0, 0, 128, 63, 230, 138, 32, 0, 0, 0, 0, 0, 244, 0, 0, 0, 56, 0, 0, 7, 194, 0, 16, 0, 2, 0, 0, 0, 6, 4, 16, 0, 2, 0, 0, 0, 86, 9, 16, 0, 4, 0, 0, 0, 50, 0, 0, 9, 98, 0, 16, 0, 1, 0, 0, 0, 6, 17, 16, 0, 4, 0, 0, 0, 6, 1, 16, 0, 2, 0, 0, 0, 166, 11, 16, 0, 2, 0, 0, 0, 18, 0, 0, 1, 54, 0, 0, 8, 114, 0, 16, 0, 1, 0, 0, 0, 2, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 0, 0, 1, 50, 0, 0, 11, 34, 32, 16, 0, 1, 0, 0, 0, 26, 128, 32, 0, 0, 0, 0, 0, 112, 1, 0, 0, 10, 0, 16, 0, 0, 0, 0, 0, 10, 128, 32, 0, 0, 0, 0, 0, 112, 1, 0, 0, 50, 0, 0, 11, 130, 32, 16, 0, 1, 0, 0, 0, 26, 128, 32, 0, 0, 0, 0, 0, 112, 1, 0, 0, 42, 0, 16, 0, 0, 0, 0, 0, 10, 128, 32, 0, 0, 0, 0, 0, 112, 1, 0, 0, 54, 0, 0, 8, 130, 0, 16, 0, 1, 0, 0, 0, 10, 128, 32, 6, 0, 0, 0, 0, 29, 1, 0, 0, 26, 0, 16, 0, 0, 0, 0, 0, 54, 0, 0, 5, 242, 32, 16, 0, 2, 0, 0, 0, 70, 14, 16, 0, 1, 0, 0, 0, 62, 0, 0, 1, 83, 84, 65, 84, 148, 0, 0, 0, 76, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 8, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Vizzuality/sustainable-cities-api
db/migrate/20170315152630_create_notifications.rb
# frozen_string_literal: true class CreateNotifications < ActiveRecord::Migration[5.1] def change create_table :notifications do |t| t.belongs_to :user, index: true, foreign_key: true t.references :notificable, polymorphic: true t.text :summary t.integer :counter, default: 1 t.datetime :emailed_at t.timestamps end add_index :notifications, [:notificable_id, :notificable_type], name: 'notifications_notificable_index' end end
alexey-anufriev/intellij-community
platform/statistics/src/com/intellij/internal/statistic/eventLog/validator/storage/ValidationRulesPersistedStorage.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.eventLog.validator.storage; import com.intellij.internal.statistic.eventLog.EventLogBuild; import com.intellij.internal.statistic.eventLog.EventLogConfiguration; import com.intellij.internal.statistic.eventLog.EventLogSystemLogger; import com.intellij.internal.statistic.eventLog.connection.metadata.EventGroupRemoteDescriptors; import com.intellij.internal.statistic.eventLog.connection.metadata.EventLogMetadataLoadException; import com.intellij.internal.statistic.eventLog.connection.metadata.EventLogMetadataParseException; import com.intellij.internal.statistic.eventLog.connection.metadata.EventLogMetadataUtils; import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventLogMetadataPersistence; import com.intellij.internal.statistic.eventLog.validator.rules.beans.EventGroupRules; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.concurrency.Semaphore; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ValidationRulesPersistedStorage extends BaseValidationRulesPersistedStorage { private static final Logger LOG = Logger.getInstance(ValidationRulesPersistedStorage.class); protected final ConcurrentMap<String, EventGroupRules> eventsValidators = new ConcurrentHashMap<>(); private final @NotNull Semaphore mySemaphore; private final @NotNull String myRecorderId; private @Nullable String myVersion; private final @NotNull EventLogMetadataPersistence myMetadataPersistence; private final @NotNull EventLogMetadataLoader myMetadataLoader; ValidationRulesPersistedStorage(@NotNull String recorderId) { myRecorderId = recorderId; mySemaphore = new Semaphore(); myMetadataPersistence = new EventLogMetadataPersistence(recorderId); myMetadataLoader = new EventLogServerMetadataLoader(recorderId); myVersion = loadValidatorsFromLocalCache(recorderId); } @TestOnly protected ValidationRulesPersistedStorage(@NotNull String recorderId, @NotNull EventLogMetadataPersistence persistence, @NotNull EventLogMetadataLoader loader) { myRecorderId = recorderId; mySemaphore = new Semaphore(); myMetadataPersistence = persistence; myMetadataLoader = loader; myVersion = loadValidatorsFromLocalCache(recorderId); } @Override public @Nullable EventGroupRules getGroupRules(@NotNull String groupId) { return eventsValidators.get(groupId); } private @Nullable String loadValidatorsFromLocalCache(@NotNull String recorderId) { String rawEventsScheme = myMetadataPersistence.getCachedEventsScheme(); if (rawEventsScheme != null) { try { String newVersion = updateValidators(rawEventsScheme); EventLogSystemLogger.logMetadataLoad(recorderId, newVersion); return newVersion; } catch (EventLogMetadataParseException e) { EventLogSystemLogger.logMetadataErrorOnLoad(myRecorderId, e); } } return null; } private @Nullable String updateValidators(@NotNull String rawEventsScheme) throws EventLogMetadataParseException { mySemaphore.down(); try { EventGroupRemoteDescriptors groups = EventLogMetadataUtils.parseGroupRemoteDescriptors(rawEventsScheme); EventLogBuild build = EventLogBuild.fromString(EventLogConfiguration.INSTANCE.getBuild()); Map<String, EventGroupRules> result = createValidators(build, groups); isInitialized.set(false); eventsValidators.clear(); eventsValidators.putAll(result); isInitialized.set(true); return groups.version; } finally { mySemaphore.up(); } } @Override public void update() { long lastModifiedLocally = myMetadataPersistence.getLastModified(); long lastModifiedOnServer = myMetadataLoader.getLastModifiedOnServer(); if (LOG.isTraceEnabled()) { LOG.trace( "Loading events scheme, last modified cached=" + lastModifiedLocally + ", last modified on the server=" + lastModifiedOnServer ); } try { if (lastModifiedOnServer <= 0 || lastModifiedOnServer > lastModifiedLocally || isUnreachable()) { String rawEventsSchemeFromServer = myMetadataLoader.loadMetadataFromServer(); String version = updateValidators(rawEventsSchemeFromServer); myMetadataPersistence.cacheEventsScheme(rawEventsSchemeFromServer, lastModifiedOnServer); if (LOG.isTraceEnabled()) { LOG.trace("Update local events scheme, last modified cached=" + myMetadataPersistence.getLastModified()); } if (version != null && !StringUtil.equals(version, myVersion)) { myVersion = version; EventLogSystemLogger.logMetadataUpdated(myRecorderId, myVersion); } } } catch (EventLogMetadataLoadException | EventLogMetadataParseException e) { EventLogSystemLogger.logMetadataErrorOnUpdate(myRecorderId, e); } } @Override public void reload() { myVersion = loadValidatorsFromLocalCache(myRecorderId); } }
Ybalrid/orbiter
Src/Orbiter/BodyIntegrator.cpp
<reponame>Ybalrid/orbiter // Copyright (c) <NAME> // Licensed under the MIT License // ======================================================================= // BodyIntegrator.cpp // Part of RigidBody class implementation // // Integrators for dynamic body state vector propagation // // This includes versions which propagate // - linear state vectors only (position, velocity) - deprecated // - angular state vectors only (orientation, angular velocity) - deprecated // - linear and angular state vectors simultaneously // - perturbations of a 2-body orbit // // Parameters for linear state propagators: // double h: step interval [s] // // Parameters for angular state propagators: // AngIntData data: angular state information // // Parameters for linear+angular state propagators: // double h: step interval for full step [s] // int nsub: number of subsamples // int isub: current subsample // double dt: subsample step interval [s] // // Parameters for perturbation propagators: // PertIntData data: orbit state informations // // All functions rely on the following Body-provided functions: // GetLinAcc: returns linear acceleration for an arbitrary position at an // arbitrary time within the current interval. (The basic RigidBody // method applies gravitational acceleration; overloaded classes can // add their own components) // GetTorque: returns the (mass-normalised) torque for an arbitrary // position, angular velocity and orientation at an arbitrary time // within the current interval. (The basic RigidBody method applies // gravity gradient torque with optional damping; overloaded classes // can add their own components) // ======================================================================= #include "Orbiter.h" #include "Rigidbody.h" #include "Element.h" #include "Log.h" #include <stdio.h> extern TimeData td; extern char DBG_MSG[256]; // =========================================================================== // Runge-Kutta integration parameters (RK5-RK8) // Used by the driver routines below // (Note that RK2 and RK4 are implemented directly without using the driver // routines) // =========================================================================== // --------------------------------------------------------------------------- // RK5 6-stage parameters // --------------------------------------------------------------------------- static const int RK5_n = 6; static const double RK5_alpha[RK5_n-1] = { 1.0/5.0, 3.0/10.0, 4.0/5.0, 8.0/9.0, 1.0 }; static const double RK5_beta[(RK5_n-1)*(RK5_n-1)] = { 1.0/5.0, 0, 0, 0, 0, 3.0/40.0, 9.0/40.0, 0, 0, 0, 44.0/45.0, -56.0/15.0, 32.0/9.0, 0, 0, 19372.0/6561.0, -25360.0/2187.0, 64448.0/6561.0, -212.0/729.0, 0, 9017.0/3168.0, -355.0/33.0, 46732.0/5247.0, 49.0/176.0, -5103.0/18656.0 }; static const double RK5_gamma[RK5_n] = { 35.0/384.0, 0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0 }; // --------------------------------------------------------------------------- // RK6 8-stage parameters // --------------------------------------------------------------------------- static const int RK6_n = 8; static const double RK6_alpha[RK6_n-1] = { 1.0/6.0, 4.0/15.0, 2.0/3.0, 5.0/6.0, 1.0, 1.0/15.0, 1.0 }; static const double RK6_beta[(RK6_n-1)*(RK6_n-1)] = { 1.0/6.0, 0, 0, 0, 0, 0, 0, 4.0/75.0, 16.0/75.0, 0, 0, 0, 0, 0, 5.0/6.0, -8.0/3.0, 5.0/2.0, 0, 0, 0, 0, -165.0/64.0, 55.0/6.0, -425.0/64.0, 85.0/96.0, 0, 0, 0, 12.0/5.0, -8.0, 4015.0/612.0, -11.0/36.0, 88.0/255.0, 0, 0, -8263.0/15000.0, 124.0/75.0, -643.0/680.0, -81.0/250.0, 2484.0/10625.0, 0, 0, 3501.0/1720.0, -300.0/43.0, 297275.0/52632.0, -319.0/2322.0, 24068.0/84065.0, 0, 3850.0/26703.0 }; static const double RK6_gamma[RK6_n] = { 3.0/40.0, 0, 875.0/2244.0, 23.0/72.0, 264.0/1955.0, 0, 125.0/11592.0, 43.0/616.0 }; // --------------------------------------------------------------------------- // RK7 11-stage parameters // --------------------------------------------------------------------------- static const int RK7_n = 11; static const double RK7_alpha[RK7_n-1] = { 2.0/27.0, 1.0/9.0, 1.0/6.0, 5.0/12.0, 1.0/2.0, 5.0/6.0, 1.0/6.0, 2.0/3.0, 1.0/3.0, 1.0 }; static const double RK7_beta[(RK7_n-1)*(RK7_n-1)] = { 2.0/27.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0/36.0, 1.0/12.0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0/24.0, 0, 1.0/8.0, 0, 0, 0, 0, 0, 0, 0, 5.0/12.0, 0, -25.0/16.0, 25.0/16.0, 0, 0, 0, 0, 0, 0, 1.0/20.0, 0, 0, 1.0/4.0, 1.0/5.0, 0, 0, 0, 0, 0, -25.0/108.0, 0, 0, 125.0/108.0, -65.0/27.0, 125.0/54.0, 0, 0, 0, 0, 31.0/300.0, 0, 0, 0, 61.0/225.0, -2.0/9.0, 13.0/900.0, 0, 0, 0, 2.0, 0, 0, -53.0/6.0, 704.0/45.0, -107.0/9.0, 67.0/90.0, 3.0, 0, 0, -91.0/108.0, 0, 0, 23.0/108.0, -976.0/135.0, 311.0/54.0, -19.0/60.0, 17.0/6.0, -1.0/12.0, 0, 2383.0/4100.0, 0, 0, -341.0/164.0, 4496.0/1025.0, -301.0/82.0, 2133.0/4100.0, 45.0/82.0, 45.0/164.0, 18.0/41.0 }; static const double RK7_gamma[RK7_n] = { 41.0/840.0, 0, 0, 0, 0, 34.0/105.0, 9.0/35.0, 9.0/35.0, 9.0/280.0, 9.0/280.0, 41.0/840.0 }; // --------------------------------------------------------------------------- // RK8 13-stage parameters // --------------------------------------------------------------------------- static const int RK8_n = 13; static const double RK8_alpha[RK8_n-1] = { 2.0/27.0, 1.0/9.0, 1.0/6.0, 5.0/12.0, 1.0/2.0, 5.0/6.0, 1.0/6.0, 2.0/3.0, 1.0/3.0, 1.0, 0, 1.0 }; static const double RK8_beta[(RK8_n-1)*(RK8_n-1)] = { 2.0/27.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0/36.0, 1.0/12.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0/24.0, 0, 1.0/8.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5.0/12.0, 0, -25.0/16.0, 25.0/16.0, 0, 0, 0, 0, 0, 0, 0, 0, 1.0/20.0, 0, 0, 1.0/4.0, 1.0/5.0, 0, 0, 0, 0, 0, 0, 0, -25.0/108.0, 0, 0, 125.0/108.0, -65.0/27.0, 125.0/54.0, 0, 0, 0, 0, 0, 0, 31.0/300.0, 0, 0, 0, 61.0/225.0, -2.0/9.0, 13.0/900.0, 0, 0, 0, 0, 0, 2.0, 0, 0, -53.0/6.0, 704.0/45.0, -107.0/9.0, 67.0/90.0, 3.0, 0, 0, 0, 0, -91.0/108.0, 0, 0, 23.0/108.0, -976.0/135.0, 311.0/54.0, -19.0/60.0, 17.0/6.0, -1.0/12.0, 0, 0, 0, 2383.0/4100.0, 0, 0, -341.0/164.0, 4496.0/1025.0, -301.0/82.0, 2133.0/4100.0, 45.0/82.0, 45.0/164.0, 18.0/41.0, 0, 0, 3.0/205.0, 0, 0, 0, 0, -6.0/41.0, -3.0/205.0, -3.0/41.0, 3.0/41.0, 6.0/41.0, 0, 0, -1777.0/4100.0, 0, 0, -341.0/164.0, 4496.0/1025.0, -289.0/82.0, 2193.0/4100.0, 51.0/82.0, 33.0/164.0, 12.0/41.0, 0, 1.0 }; static const double RK8_gamma[RK8_n] = { 0, 0, 0, 0, 0, 34.0/105.0, 9.0/35.0, 9.0/35.0, 9.0/280.0, 9.0/280.0, 0, 41.0/840.0, 41.0/840.0 }; // =========================================================================== // Propagators for linear and angular state vectors combined // =========================================================================== // --------------------------------------------------------------------------- // 2nd order 2-stage Runge-Kutta (linear+angular) // --------------------------------------------------------------------------- void RigidBody::RK2_LinAng (double h, int nsub, int isub) { double h05 = h*0.5; Vector acc1, tau; StateVectors s; s.pos.Set (s1->pos+s1->vel*h05); s.vel.Set (s1->vel+acc*h05); s.SetRot (s1->Q.Rot(s1->omega*h05)); s.omega.Set (s1->omega+arot*h05); GetIntermediateMoments (acc1, tau, s, (isub+0.5)/nsub, h); rpos_add += s.vel*h; rvel_add += acc1*h; s1->Q.Rotate (s.omega*h); arot = EulerInv_full (tau, s.omega); // may need to allow use of the simplified versions here s1->omega += arot*h; } // --------------------------------------------------------------------------- // 4th order 4-stage Runge-Kutta (linear+angular) // --------------------------------------------------------------------------- void RigidBody::RK4_LinAng (double h, int nsub, int isub) { double h05 = h*0.5; double hi6 = h/6.0; Vector tau, acc1, aacc1, acc2, aacc2, acc3, aacc3; StateVectors sa, sb, sc; sa.pos.Set (s1->pos+s1->vel*h05); sa.vel.Set (s1->vel+acc*h05); sa.SetRot (s1->Q.Rot(s1->omega*h05)); sa.omega.Set (s1->omega+arot*h05); GetIntermediateMoments (acc1, tau, sa, (isub+0.5)/nsub, h); aacc1.Set (EulerInv_full (tau, sa.omega)); sb.pos.Set (s1->pos+sa.vel*h05); sb.vel.Set (s1->vel+acc1*h05); sb.SetRot (s1->Q.Rot(sa.omega*h05)); sb.omega.Set (s1->omega+aacc1*h05); GetIntermediateMoments (acc2, tau, sb, (isub+0.5)/nsub, h); aacc2.Set (EulerInv_full (tau, sb.omega)); sc.pos.Set (s1->pos+sb.vel*h); sc.vel.Set (s1->vel+acc2*h); sc.SetRot (s1->Q.Rot(sb.omega*h)); sc.omega.Set (s1->omega+aacc2*h); GetIntermediateMoments (acc3, tau, sc, (isub+1.0)/nsub, h); aacc3.Set (EulerInv_full (tau, sc.omega)); rvel_add += (acc +(acc1+acc2)*2.0+acc3)*hi6; rpos_add += (s1->vel+(sa.vel+sb.vel)*2.0+sc.vel)*hi6; s1->Q.Rotate ((s1->omega+(sa.omega+sb.omega)*2.0+sc.omega)*hi6); s1->omega += (arot+(aacc1+aacc2)*2.0+aacc3)*hi6; } // --------------------------------------------------------------------------- // Driver routine for Runge-Kutta solvers RK5-RK8 (linear+angular) // Note: NOT THREADSAFE // --------------------------------------------------------------------------- void RigidBody::RKdrv_LinAng (double h, int nsub, int isub, int n, const double *alpha, const double *beta, const double *gamma) { int i, j; double bh; static int nbuf = 8; static StateVectors *s = new StateVectors[nbuf]; TRACENEW static Vector *a = new Vector[nbuf]; TRACENEW // linear acceleration static Vector *d = new Vector[nbuf]; TRACENEW // angular acceleration Vector tau; if (n > nbuf) { // grow buffers delete []s; delete []a; delete []d; s = new StateVectors[n]; TRACENEW a = new Vector[n]; TRACENEW d = new Vector[n]; TRACENEW nbuf = n; } s[0].Set (s1->vel, s1->pos, s1->omega, s1->Q); a[0].Set (acc); d[0].Set (arot); for (i = 1; i < n; i++) { s[i].Set (s1->vel, s1->pos, s1->omega, s1->Q); for (j = 0; j < i; j++) s[i].Advance (beta[j]*h, a[j], s[j].vel, d[j], s[j].omega); GetIntermediateMoments (a[i],tau,s[i],(isub+alpha[i-1])/nsub, h); d[i].Set (EulerInv_full (tau, s[i].omega)); beta += n-1; } for (i = 0; i < n; i++) { bh = gamma[i]*h; rvel_add += a[i] * bh; rpos_add += s[i].vel * bh; s1->Q.Rotate (s[i].omega * bh); s1->omega += d[i] * bh; } } // --------------------------------------------------------------------------- // 5th order 6-stage Runge-Kutta (linear+angular) // --------------------------------------------------------------------------- void RigidBody::RK5_LinAng (double h, int nsub, int isub) { RKdrv_LinAng (h, nsub, isub, RK5_n, RK5_alpha, RK5_beta, RK5_gamma); } // --------------------------------------------------------------------------- // 6th order 8-stage Runge-Kutta (linear+angular) // --------------------------------------------------------------------------- void RigidBody::RK6_LinAng (double h, int nsub, int isub) { RKdrv_LinAng (h, nsub, isub, RK6_n, RK6_alpha, RK6_beta, RK6_gamma); } // --------------------------------------------------------------------------- // 7th order 11-stage Runge-Kutta (linear+angular) // --------------------------------------------------------------------------- void RigidBody::RK7_LinAng (double h, int nsub, int isub) { RKdrv_LinAng (h, nsub, isub, RK7_n, RK7_alpha, RK7_beta, RK7_gamma); } // --------------------------------------------------------------------------- // 8th order 13-stage Runge-Kutta (linear+angular) // --------------------------------------------------------------------------- void RigidBody::RK8_LinAng (double h, int nsub, int isub) { RKdrv_LinAng (h, nsub, isub, RK8_n, RK8_alpha, RK8_beta, RK8_gamma); } // --------------------------------------------------------------------------- // 2nd order symplectic propagator (linear+angular) // Note: the propagation of angular state is guesswork ... // --------------------------------------------------------------------------- void RigidBody::SY2_LinAng (double h, int nsub, int isub) { double h05 = h*0.5; StateVectors s; Vector tau; rpos_add += (rvel_base+rvel_add)*h05; s1->Q.Rotate (s1->omega*h05); s.Set (s1->vel, rpos_base+rpos_add, s1->omega, s1->Q); GetIntermediateMoments (acc, tau, s, (isub+0.5)/nsub, h); arot.Set (EulerInv_full (tau, s.omega)); rvel_add += acc*h; s1->omega += arot*h; rpos_add += (rvel_base+rvel_add)*h05; s1->Q.Rotate (s1->omega*h05); } // --------------------------------------------------------------------------- // 4nd order symplectic propagator (linear+angular) // Note: the propagation of angular state is guesswork ... // --------------------------------------------------------------------------- void RigidBody::SY4_LinAng (double h, int nsub, int isub) { int i; double sec = 0.0; static const double b = 1.25992104989487319066654436028; // 2^1/3 static const double a = 2 - b; static const double x0 = -b / a; static const double x1 = 1. / a; static const double d4[3] = {x1, x0, x1}; static const double c4[4] = {x1/2, (x0+x1)/2, (x0+x1)/2, x1/2}; StateVectors s; Vector tau; for (i = 0; i < 4; i++) { double step = h * c4[i]; rpos_add += (rvel_base+rvel_add)*step; s1->Q.Rotate (s1->omega*step); sec += c4[i]; if (i != 3) { s.Set (rvel_base+rvel_add, rpos_base+rpos_add, s1->omega, s1->Q); GetIntermediateMoments (acc, tau, s, (isub+sec)/nsub, h); arot.Set (EulerInv_full (tau, s.omega)); rvel_add += acc * (h*d4[i]); s1->omega += arot * (h*d4[i]); } } } // --------------------------------------------------------------------------- // 6nd order symplectic propagator (linear+angular) // Note: the propagation of angular state is guesswork ... // --------------------------------------------------------------------------- void RigidBody::SY6_LinAng (double h, int nsub, int isub) { int i; double sec = 0.0; static const double w1 = -0.117767998417887E1; static const double w2 = 0.235573213359357E0; static const double w3 = 0.784513610477560E0; static const double w0 = (1-2*(w1+w2+w3)); static const double d6[7] = { w3, w2, w1, w0, w1, w2, w3 }; static const double c6[8] = { w3/2, (w3+w2)/2, (w2+w1)/2, (w1+w0)/2, (w1+w0)/2, (w2+w1)/2, (w3+w2)/2, w3/2 }; StateVectors s; Vector tau; for (i = 0; i < 8; i++) { double step = h * c6[i]; rpos_add += (rvel_base+rvel_add)*step; s1->Q.Rotate (s1->omega*step); sec += c6[i]; if (i != 7) { s.Set (rvel_base+rvel_add, rpos_base+rpos_add, s1->omega, s1->Q); GetIntermediateMoments (acc, tau, s, (isub+sec)/nsub, h); arot.Set (EulerInv_full (tau, s.omega)); rvel_add += acc * (h*d6[i]); s1->omega += arot * (h*d6[i]); } } } // --------------------------------------------------------------------------- // 8nd order symplectic propagator (linear+angular) // Note: the propagation of angular state is guesswork ... // --------------------------------------------------------------------------- void RigidBody::SY8_LinAng (double h, int nsub, int isub) { int i; double sec = 0.0; // set 3 from Yoshida's Table 2 const double W1 = 0.311790812418427e0; const double W2 = -0.155946803821447e1; const double W3 = -0.167896928259640e1; const double W4 = 0.166335809963315e1; const double W5 = -0.106458714789183e1; const double W6 = 0.136934946416871e1; const double W7 = 0.629030650210433e0; const double W0 = (1-2*(W1+W2+W3+W4+W5+W6+W7)); const static double d8[15] = {W7, W6, W5, W4, W3, W2, W1, W0, W1, W2, W3, W4, W5, W6, W7}; const static double c8[16] = { W7/2, (W7+W6)/2, (W6+W5)/2, (W5+W4)/2, (W4+W3)/2, (W3+W2)/2, (W2+W1)/2, (W1+W0)/2, (W1+W0)/2, (W2+W1)/2, (W3+W2)/2, (W4+W3)/2, (W5+W4)/2, (W6+W5)/2, (W7+W6)/2, W7/2 }; StateVectors s; Vector tau; for (i = 0; i < 16; i++) { double step = h * c8[i]; rpos_add += (rvel_base+rvel_add)*step; s1->Q.Rotate (s1->omega*step); sec += c8[i]; if (i != 15) { s.Set (rvel_base+rvel_add, rpos_base+rpos_add, s1->omega, s1->Q); GetIntermediateMoments (acc, tau, s, (isub+sec)/nsub, h); arot.Set (EulerInv_full (tau, s.omega)); rvel_add += acc * (h*d8[i]); s1->omega += arot * (h*d8[i]); } } } #ifdef UNDEF // =========================================================================== // Propagators for 2-body orbit perturbations // =========================================================================== // --------------------------------------------------------------------------- // 2nd order 2-stage Runge-Kutta (perturbation) // --------------------------------------------------------------------------- void RigidBody::RK2_LinAng_Encke (double h, int nsub, int isub) { double t = td.SimT0 + h; double mu = Ggrav * ((Body*)cbody)->Mass(); Vector Rb, Vb, alpha, beta; double rb, r, f; el->PosVel (Rb, Vb, t); rb = Rb.length(); r = cpos.length(); f = rb/r; sprintf (DBG_MSG, "fac=%e", 1.0-f*f*f); beta = cpos*(mu*h*(1.0-f*f*f)/(rb*rb*rb)) + acc_pert*h; alpha = beta*h; cpos = Rb+alpha; cvel = Vb+beta; } void RigidBody::RK2_Pert (const PertIntData &data) { double h05 = data.dt*0.5; Vector cpos05 = el->Pos (data.t1-h05); // unperturbed position at half the current step Vector accp (GetPertAcc (data, data.p0, 0.0)); Vector v1 (data.dv + accp*h05); Vector a1 (GetPertAcc (data, cpos05+data.dv*h05, 0.5)); cpos += v1*data.dt; cvel += data.dv+a1*data.dt; } // --------------------------------------------------------------------------- // 4th order 4-stage Runge-Kutta (perturbation) // --------------------------------------------------------------------------- void RigidBody::RK4_Pert (const PertIntData &data) { double h05 = data.dt*0.5; double hi6 = data.dt/6.0; Vector cpos05 = el->Pos (data.t1-h05); // unperturbed position at half the current step Vector accp (GetPertAcc (data, data.p0, 0.0)); Vector v1 (data.dv + accp*h05); Vector a1 (GetPertAcc (data, cpos05+data.dv*h05, 0.5)); Vector v2 (data.dv + a1*h05); Vector a2 (GetPertAcc (data, cpos05+v1*h05, 0.5)); Vector v3 (data.dv + a2*data.dt); Vector a3 (GetPertAcc (data, cpos+v2*data.dt, 1.0)); cpos += (data.dv+(v1+v2)*2.0+v3)*hi6; cvel += (accp+(a1+a2)*2.0+a3)*hi6; } // --------------------------------------------------------------------------- // Driver routine for Runge-Kutta solvers RK5-RK8 (perturbation) // Note: NOT THREADSAFE // --------------------------------------------------------------------------- void RigidBody::RKdrv_Pert (const PertIntData &data, int n, const double *alpha, const double *beta, const double *gamma) { int i, j; static int nbuf = 8; static Vector *v = new Vector[nbuf]; static Vector *a = new Vector[nbuf]; if (n > nbuf) { // grow buffers delete []v; delete []a; v = new Vector[n]; TRACENEW a = new Vector[n]; TRACENEW nbuf = n; } Vector pos, vtmp; v[0] = data.dv; a[0] = GetPertAcc (data, data.p0, 0.0); for (i =1; i < n; i++) { v[i] = data.dv; pos = el->Pos (data.t1+data.dt*(alpha[i-1]-1.0)); for (j = 0; j < i; j++) { v[i] += a[j]*(beta[j]*data.dt); pos += v[j]*(beta[j]*data.dt); } a[i] = GetPertAcc (data, pos, alpha[i-1]); beta += n-1; } for (i = 0; i < n; i++) { cpos += v[i]*(gamma[i]*data.dt); cvel += a[i]*(gamma[i]*data.dt); } } // --------------------------------------------------------------------------- // 8th order 13-stage Runge-Kutta (perturbation) // --------------------------------------------------------------------------- void RigidBody::RK8_Pert (const PertIntData &data) { RKdrv_Pert (data, RK8_n, RK8_alpha, RK8_beta, RK8_gamma); } #endif void RigidBody::Encke () { static double ch[13] = { 0, 0, 0, 0, 0, 34.0/105.0, 9.0/35.0, 9.0/35.0, 9.0/280.0, 9.0/280.0, 0, 41.0/840.0, 41.0/840.0 }; static double alph[13] = { 0, 2.0/27.0, 1.0/9.0, 1.0/6.0, 5.0/12.0, 0.5, 5.0/6.0, 1.0/6.0, 2.0/3.0, 1.0/3.0, 1, 0, 1 }; static double beta[13][12] = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0 }, { 2.0/27.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0 }, { 1.0/36.0, 1.0/12.0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0 }, { 1.0/24.0, 0, 1.0/8.0, 0, 0, 0, 0, 0, 0, 0, 0,0 }, { 5.0/12.0, 0, -25.0/16.0,25.0/16.0, 0, 0, 0, 0, 0, 0, 0,0 }, { 0.05, 0, 0, 0.25, 0.2, 0, 0, 0, 0, 0, 0,0 }, {-25.0/108.0, 0, 0, 125.0/108.0,-65.0/27.0, 125.0/54.0, 0, 0, 0, 0, 0,0 }, { 31.0/300.0, 0, 0, 0, 61.0/225.0, -2.0/9.0, 13.0/900.0, 0, 0, 0, 0,0 }, { 2.0, 0, 0, -53.0/6.0, 704.0/45.0, -107.0/9.0, 67.0/90.0, 3.0, 0, 0, 0,0 }, {-91.0/108.0, 0, 0, 23.0/108.0, -976.0/135.0, 311.0/54.0,-19.0/60.0, 17.0/6.0, -1.0/12.0, 0, 0,0 }, { 2383.0/4100.0, 0, 0, -341.0/164.0, 4496.0/1025.0,-301.0/82.0, 2133.0/4100.0,45.0/82.0, 45.0/164.0,18.0/41.0,0,0 }, { 3.0/205.0, 0, 0, 0, 0, -6.0/41.0, -3.0/205.0, -3.0/41.0, 3.0/41.0, 6.0/41.0, 0,0 }, {-1777.0/4100.0, 0, 0, -341.0/164.0, 4496.0/1025.0,-289.0/82.0, 2193.0/4100.0,51.0/82.0, 33.0/164.0,12.0/41.0,0,1.0}}; const int neq = 6; int i, j, k, kk; double f[6][13], x[6], xwrk[6], temp, t0, ti, tf, twrk, dt, tfrac; Vector d[13], omega[13], tau; // angular state parameters StateVectors s; ti = t0 = td.SimT0; tf = td.SimT1; dt = (tf-ti)*1; for (i = 0; i < 6; i++) x[i] = 0.0; while (1) { twrk = ti; for (i = 0; i < 6; i++) xwrk[i] = x[i]; // check for last step if (dt > tf-ti) dt = tf-ti; // check for end of integration period if (fabs (ti-tf) < 1e-8) break; tfrac = (ti-t0)/(tf-t0); for (i = 0; i < 3; i++) { s.pos.data[i] = cpos.data[i]+x[i]; s.vel.data[i] = cvel.data[i]+x[i+3]; } GetIntermediateMoments_pert (acc_pert, tau, s, tfrac, dt, cbody); for (i = 0; i < 3; i++) { f[i][0] = x[i+3]; f[i+3][0] = acc_pert.data[i]; } // angular state omega[0].Set (s1->omega); d[0].Set (arot); for (k = 1; k < 13; k++) { kk = k-1; for (i = 0; i < neq; i++) { temp = 0.0; for (j = 0; j < kk; j++) { temp += beta[k][j] * f[i][j]; } x[i] = xwrk[i] + dt*temp; } omega[k].Set (s1->omega); for (j = 0; j < kk; j++) { omega[k] += d[j]*(beta[k][j]*dt); } ti = twrk + alph[k] * dt; tfrac = (ti-t0)/(tf-t0); el->PosVel (cpos, cvel, ti); for (i = 0; i < 3; i++) { s.pos.data[i] = cpos.data[i]+x[i]; s.vel.data[i] = cvel.data[i]+x[i+3]; } GetIntermediateMoments_pert (acc_pert, tau, s, tfrac, dt, cbody); for (i = 0; i < 3; i++) { f[i][k] = x[i+3]; f[i+3][k] = acc_pert.data[i]; } d[k].Set (EulerInv_simple (tau, omega[k])); } for (i = 0; i < neq; i++) { temp = 0.0; for (k = 0; k < 13; k++) { temp += ch[k] * f[i][k]; } x[i] = xwrk[i] + dt*temp; } for (k = 0; k < 13; k++) { s1->Q.Rotate (omega[k] * (ch[k]*dt)); s1->omega += d[k] * (ch[k]*dt); } // truncation error const double tetol = 1e-8; double xerr = tetol; for (i = 0; i < neq; i++) { double ter = fabs((f[i][0] + f[i][10] - f[i][11] - f[i][12]) * ch[11]*dt); double tol = fabs(x[i]) * tetol + tetol; double tconst = ter/tol; if (tconst > xerr) xerr = tconst; } el->PosVel (cpos, cvel, ti); for (i = 0; i < 3; i++) { cpos.data[i] += x[i]; cvel.data[i] += x[i+3]; } // rectify elements el->Calculate (cpos, cvel, ti); for (i = 0; i < 6; i++) x[i] = 0.0; } }
SANBI-SA-archive/s_bvc_pipeline
USAP_H37Rv/Tools/smalt-0.7.5/config.h
<reponame>SANBI-SA-archive/s_bvc_pipeline<gh_stars>0 /* config.h. Generated from config.hin by configure. */ /* config.hin. Generated from configure.ac by autoheader. */ /* Define if you have the package bambamc installed as a library */ /* #undef HAVE_BAMBAMC */ /* Define to 1 if you have <emmintrin.h>. */ #define HAVE_EMMINTRIN_H 1 /* Define to 1 if you have the <float.h> header file. */ #define HAVE_FLOAT_H 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the <math.h> header file. */ #define HAVE_MATH_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if you have the <pthread.h> header file. */ #define HAVE_PTHREAD_H 1 /* Define if you have samtools installed as a library */ /* #undef HAVE_SAMTOOLS_API */ /* Define to 1 if you have the <semaphore.h> header file. */ #define HAVE_SEMAPHORE_H 1 /* Define to 1 if you have the <stddef.h> header file. */ #define HAVE_STDDEF_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have zlib */ #define HAVE_ZLIB 1 /* Name of package */ #define PACKAGE "smalt" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "<EMAIL>" /* Define to the full name of this package. */ #define PACKAGE_NAME "smalt" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "smalt 0.7.5" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "smalt" /* Define to the home page for this package. */ #define PACKAGE_URL "http://smalt.sourceforge.net" /* Define to the version of this package. */ #define PACKAGE_VERSION "0.7.5" /* ICC on 32bit: avoid undefined references to __svml_exp2 */ /* #undef SMALT_AUTOCONF_ICC_OPT */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ #define VERSION "0.7.5" /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus /* #undef inline */ #endif /* Define to `unsigned int' if <sys/types.h> does not define. */ /* #undef size_t */
andrenjunior/Linguagem-de-Programa-o-Python
Tele_Aula 3/Classe.py
class conta: def __init__(self, nome, numero): self.cliente = nome self.num = numero self.saldo = 0.0 def Saldo (self ): return self.saldo def getcliente (self): return self.cliente def depositar (self, valor): self.saldo += valor def transferencia (self, conta, valor): self.saldo = self.saldo - valor conta.saldo = conta.saldo + valor
netzling/jmeter
src/core/org/apache/jmeter/report/core/TimeHelper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.report.core; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.jmeter.util.JMeterUtils; /** * The class TimeHelper provides helper functions to ease time displaying. * * @since 3.0 */ public class TimeHelper { private static final String TIMESTAMP_FORMAT_PROPERTY = "jmeter.save.saveservice.timestamp_format"; public static String time(long t) { long h = t / 3600000; t %= 3600000; long m = t / 60000; t %= 60000; long s = t / 1000; t %= 1000; long ms = t; if (h > 0) { return h + "h " + m + "m " + s + "s " + ms + " ms"; } if (m > 0) { return m + "m " + s + "s " + ms + " ms"; } if (s > 0) { return s + "s " + ms + " ms"; } if (ms > 0) { return ms + "ms"; } return "0 ms"; } /** * Format the specified time stamp to string using JMeter properties. * * @param timeStamp * the time stamp * @return the string */ public static String formatTimeStamp(long timeStamp) { return formatTimeStamp(timeStamp, JMeterUtils.getProperty(TIMESTAMP_FORMAT_PROPERTY)); } /** * Format the specified time stamp to string using the format. * * @param timeStamp * the time stamp * @param format * the format * @return the string */ public static String formatTimeStamp(long timeStamp, String format) { SimpleDateFormat dateFormat = format != null ? new SimpleDateFormat( format) : new SimpleDateFormat(); return dateFormat.format(new Date(timeStamp)); } }
athasv/Codewars-data
python/8Kyu/Parse nice int from char problem.py
def get_age(age): return int(age[0])
BibiNiao/urgoo_client
src/com/urgoo/service/model/PlanEntity.java
<gh_stars>0 package com.urgoo.service.model; /** * Created by dff on 2016/8/23. */ public class PlanEntity { private String color; private String deadDay; private String title; private String deadLine; private String taskId; private String type; public String getType() { return type; } public void setType(String mType) { type = mType; } public String getTaskId() { return taskId; } public void setTaskId(String mTaskId) { taskId = mTaskId; } public String getColor() { return color; } public void setColor(String mColor) { color = mColor; } public String getDeadDay() { return deadDay; } public void setDeadDay(String mDeadDay) { deadDay = mDeadDay; } public String getTitle() { return title; } public void setTitle(String mTitle) { title = mTitle; } public String getDeadLine() { return deadLine; } public void setDeadLine(String mDeadLine) { deadLine = mDeadLine; } }
Programmer-alliance/moonbox
catalyst/src/main/scala/moonbox/catalyst/adapter/elasticsearch5/util/EsRowIter.scala
/*- * << * Moonbox * == * Copyright (C) 2016 - 2019 EDP * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ package moonbox.catalyst.adapter.elasticsearch5.util import moonbox.catalyst.adapter.elasticsearch5.client.{ActionResponse, EsRestClient} import moonbox.catalyst.adapter.util.SparkUtil.colId2colNameMap import org.apache.spark.sql.types.StructType import org.elasticsearch.client.Response import org.json.JSONObject import scala.collection.mutable.ArrayBuffer /** use java iterator, because scala iterator can not set break point in idea evn*/ class EsRowIter[T](index: String, tpe: String, query: String, schema: StructType, mapping: Seq[(String, String)], convert: (Option[StructType], Seq[Any]) => T, limitSize: Int, client: EsRestClient) extends java.util.Iterator[T] { //T ==> ROW private val actionRsp: ActionResponse = new ActionResponse() private val result: ArrayBuffer[T] = new ArrayBuffer[T]() private var hasProcessLines: Long = 0 private var shouldProcessLines: Long = 0 private var isFirstTime: Boolean = true private var scrollId: String = _ private var continue: Boolean = false private var resultIter: Iterator[T] = _ private var hasPassedLines: Long = 0 //use for limit private var runtime: Int = 0 private def sendBulkMessage(jquery: String, firstQuery: Boolean): Unit = { val response: Response = client.performRequestWithScroll(index, tpe, jquery, firstQuery) actionRsp.clear() result.clear() if (!client.isSucceeded(response)) { throw new Exception("performScrollRequest to Server return ERROR " + response.getStatusLine.getStatusCode) } val jsonReqObject = new JSONObject(query) val requestLines = jsonReqObject.optLong("size", 10000l) //default 10000 val content = client.getContent(response) val jsonRspObject: JSONObject = new JSONObject(content) val responseLines = client.getFieldAsLong(jsonRspObject, "hits/total") if(limitSize != -1 ){ //has limit size shouldProcessLines = math.min(limitSize, responseLines) //min } else { shouldProcessLines = math.max(limitSize, responseLines) //max } //if has limit size, we should use the min size of send and receive size, if no limit size, we should use the max size of send and receive size var fetchSize: Long = client.handleResponse(content, actionRsp) //handle runtime = runtime +1 hasProcessLines += fetchSize if(client.containsAggs(jsonRspObject)){ continue = false }else{ scrollId = client.getFieldAsString(jsonRspObject, "_scroll_id") //update scroll id if (hasProcessLines < shouldProcessLines && hasProcessLines != 0) { continue = true }else{ continue = false } } val resultColumn: Seq[Seq[Any]] = actionRsp.getResult(schema, colId2colNameMap(mapping)) val resultRow: Seq[T] = resultColumn.map(convert(Some(schema), _)) //SparkUtil.resultListToJdbcRow(Some(schema), _) result.append(resultRow: _*) resultIter = result.iterator } def getNextBulk(): Boolean = { if(isFirstTime){ //if the first , get the first one sendBulkMessage(query, true) isFirstTime = false } if(!resultIter.hasNext) { //not the first, if result has one, true; else, try another one if (continue) { val leftQuery = s"""{"scroll":"2m","scroll_id":"$scrollId"}""" sendBulkMessage(leftQuery, false) resultIter.hasNext }else{ false } } else { true } } def close(): Unit = { if(client != null) { client.close() } } override def hasNext = { //if can get next message, and no exceed the limit size, shouldProcessLines update in getNextBulk getNextBulk() && (hasPassedLines < shouldProcessLines) } override def next() = { hasPassedLines = hasPassedLines + 1 resultIter.next() } }
YiGuangLee/gamer
src/Tables/Table_SiblingSharingSameEdge.cpp
<reponame>YiGuangLee/gamer #include "GAMER.h" //------------------------------------------------------------------------------------------------------- // Function : TABLE_SiblingSharingSameEdge // Description : Return the three sibling direction indices sharing the same patch edge as the input one // // Note : 1. Results are stored in SibID[] // 2. Direction of edge indices (EdgeID) are defined in the same way as the sibling indices // 3. If SibSibID != NULL, this function also returns the sibling directions **from the // sibling patches associated with SibID[] to the target patch edge** // // Parameter : EdgeID : Sibling index corresponding to the target patch edge // SibID : Output array (see the notes above) // SibSibID : Output array (see the notes above) // // Return : SibID[], SibSibID[] //------------------------------------------------------------------------------------------------------- void TABLE_SiblingSharingSameEdge( const int EdgeID, int SibID[], int SibSibID[] ) { # ifdef GAMER_DEBUG if ( EdgeID < 6 || EdgeID >= 18 ) Aux_Error( ERROR_INFO, "EdgeID (%d) not in the accepted range [6 ... 17] !!\n", EdgeID ); # endif switch ( EdgeID ) { case 6 : SibID[0] = 0; SibID[1] = 2; SibID[2] = 6; if ( SibSibID != NULL ) { SibSibID[0] = 7; SibSibID[1] = 8; SibSibID[2] = 9; } break; case 7 : SibID[0] = 1; SibID[1] = 2; SibID[2] = 7; if ( SibSibID != NULL ) { SibSibID[0] = 6; SibSibID[1] = 9; SibSibID[2] = 8; } break; case 8 : SibID[0] = 0; SibID[1] = 3; SibID[2] = 8; if ( SibSibID != NULL ) { SibSibID[0] = 9; SibSibID[1] = 6; SibSibID[2] = 7; } break; case 9 : SibID[0] = 1; SibID[1] = 3; SibID[2] = 9; if ( SibSibID != NULL ) { SibSibID[0] = 8; SibSibID[1] = 7; SibSibID[2] = 6; } break; case 10 : SibID[0] = 2; SibID[1] = 4; SibID[2] = 10; if ( SibSibID != NULL ) { SibSibID[0] = 11; SibSibID[1] = 12; SibSibID[2] = 13; } break; case 11 : SibID[0] = 3; SibID[1] = 4; SibID[2] = 11; if ( SibSibID != NULL ) { SibSibID[0] = 10; SibSibID[1] = 13; SibSibID[2] = 12; } break; case 12 : SibID[0] = 2; SibID[1] = 5; SibID[2] = 12; if ( SibSibID != NULL ) { SibSibID[0] = 13; SibSibID[1] = 10; SibSibID[2] = 11; } break; case 13 : SibID[0] = 3; SibID[1] = 5; SibID[2] = 13; if ( SibSibID != NULL ) { SibSibID[0] = 12; SibSibID[1] = 11; SibSibID[2] = 10; } break; case 14 : SibID[0] = 0; SibID[1] = 4; SibID[2] = 14; if ( SibSibID != NULL ) { SibSibID[0] = 16; SibSibID[1] = 15; SibSibID[2] = 17; } break; case 15 : SibID[0] = 0; SibID[1] = 5; SibID[2] = 15; if ( SibSibID != NULL ) { SibSibID[0] = 17; SibSibID[1] = 14; SibSibID[2] = 16; } break; case 16 : SibID[0] = 1; SibID[1] = 4; SibID[2] = 16; if ( SibSibID != NULL ) { SibSibID[0] = 14; SibSibID[1] = 17; SibSibID[2] = 15; } break; case 17 : SibID[0] = 1; SibID[1] = 5; SibID[2] = 17; if ( SibSibID != NULL ) { SibSibID[0] = 15; SibSibID[1] = 16; SibSibID[2] = 14; } break; default: Aux_Error( ERROR_INFO, "incorrect parameter %s = %d !!\n", "EdgeID", EdgeID ); break; } // switch ( EdgeID ) } // FUNCTION : TABLE_SiblingSharingSameEdge
osgcc/descent-mac
main/mission.c
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. */ /* * $Source: BigRed:miner:source:main::RCS:mission.c $ * $Revision: 1.4 $ * $Author: allender $ * $Date: 1995/10/31 10:21:40 $ * * Code to handle multiple missions * * $Log: mission.c $ * Revision 1.4 1995/10/31 10:21:40 allender * no mission support in shareware * * Revision 1.3 1995/10/21 22:53:04 allender * moved missions to data folder * * Revision 1.2 1995/09/13 08:47:29 allender * made to work with Chris' direct stuff * * Revision 1.1 1995/05/16 15:27:48 allender * Initial revision * * Revision 2.8 1995/03/20 09:49:31 mike * Remove eof char from comment which confused make depend, causing * no mission.obj: line in makefile. Pretty stupid tool, huh? * * Revision 2.7 1995/03/20 12:12:11 john * Added ifdef SATURN. * * Revision 2.6 1995/03/15 14:32:49 john * Added code to force the Descent CD-rom in the drive. * * Revision 2.5 1995/03/15 11:41:15 john * Better Saturn CD-ROM support. * * Revision 2.4 1995/03/14 18:24:14 john * Force Destination Saturn to use CD-ROM drive. * * Revision 2.3 1995/03/07 14:19:41 mike * More destination saturn stuff. * * Revision 2.2 1995/03/06 23:09:03 mike * more saturn stuff: make briefings work for saturn mission. * * Revision 2.1 1995/03/06 16:47:48 mike * destination saturn * * Revision 2.0 1995/02/27 11:27:49 john * New version 2.0, which has no anonymous unions, builds with * Watcom 10.0, and doesn't require parsing BITMAPS.TBL. * * Revision 1.14 1995/02/15 11:30:37 john * Fixed bug with potential mem overwrite on line 160. * * Revision 1.13 1995/02/10 17:53:20 matt * Changed mission name again * * Revision 1.12 1995/02/10 17:35:38 matt * Changed name of built-in mission * * Revision 1.11 1995/02/07 17:13:51 allender * removed return statement in load_mission so that built in mission will * actually set the Current_mission_name and _filename * * Revision 1.10 1995/01/31 01:19:45 matt * Made build_mission_list() sort missions by name * * Revision 1.9 1995/01/30 13:49:58 allender * changed build_mission_list in load_mission_by_name to include * anarchy levels. * * Revision 1.8 1995/01/30 13:03:51 matt * Fixed dumb mistake * * Revision 1.7 1995/01/30 12:55:22 matt * Added vars to point to mission names * * Revision 1.6 1995/01/22 18:57:28 matt * Made player highest level work with missions * * Revision 1.5 1995/01/22 14:13:08 matt * Added flag in mission list for anarchy-only missions * * Revision 1.4 1995/01/21 23:13:12 matt * Made high scores with (not work, really) with loaded missions * Don't give player high score when quit game * * Revision 1.3 1995/01/21 16:27:12 matt * Made endlevel briefing work with missions * * Revision 1.2 1995/01/20 22:47:50 matt * Mission system implemented, though imcompletely * * Revision 1.1 1995/01/20 13:42:19 matt * Initial revision * * */ #pragma off (unreferenced) static char rcsid[] = "$Id: mission.c 1.4 1995/10/31 10:21:40 allender Exp allender $"; #pragma on (unreferenced) #include <stdio.h> #include <stdlib.h> #include <string.h> //#include <dos.h> #include <ctype.h> #include "cfile.h" #include "inferno.h" #include "mission.h" #include "gameseq.h" #include "titles.h" #include "mono.h" #include "error.h" #include "direct.h" #ifndef MAC_SHAREWARE mle Mission_list[MAX_MISSIONS]; int Current_mission_num; char *Current_mission_filename,*Current_mission_longname; //this stuff should get defined elsewhere char Level_names[MAX_LEVELS_PER_MISSION][13]; char Secret_level_names[MAX_SECRET_LEVELS_PER_MISSION][13]; //strips damn newline from end of line char *mfgets(char *s,int n,FILE *f) { char *r; r = fgets(s,n,f); if (r && s[strlen(s)-1] == '\n') s[strlen(s)-1] = 0; return r; } //compare a string for a token. returns true if match int istok(char *buf,char *tok) { return strnicmp(buf,tok,strlen(tok)) == 0; } //adds a terminating 0 after a string at the first white space add_term(char *s) { while (*s && !isspace(*s)) s++; *s = 0; //terminate! } #undef isspace #define isspace(c) ((c == ' ') || (c == '\t')) //returns ptr to string after '=' & white space, or NULL if no '=' //adds 0 after parm at first white space char *get_value(char *buf) { char *t; t = strchr(buf,'=')+1; if (t) { while (*t && isspace(*t)) t++; if (*t) return t; } return NULL; //error! } //reads a line, returns ptr to value of passed parm. returns NULL if none char *get_parm_value(char *parm,FILE *f) { static char buf[80]; if (!mfgets(buf,80,f)) return NULL; if (istok(buf,parm)) return get_value(buf); else return NULL; } ml_sort_func(const mle *e0,const mle *e1) { return strcmp(e0->mission_name,e1->mission_name); } //fills in the global list of missions. Returns the number of missions //in the list. If anarchy_mode set, don't include non-anarchy levels. //if there is only one mission, this function will call load_mission on it. int build_mission_list(int anarchy_mode) { int count=0; DIRPtr dir; direntPtr entry; //fill in built-in level #ifndef SATURN strcpy(Mission_list[0].filename,""); //no filename for builtin strcpy(Mission_list[0].mission_name,"Descent: First Strike"); count = 1; #endif //now search for levels on disk dir = opendir(":Data:*.msn"); while ((entry = readdir(dir)) && (count < MAX_MISSIONS) ) { FILE *mfile; int is_anarchy; char temp[13],*t, msn_path[128]; strcpy(temp,entry->d_name); if ((t = strchr(temp,'.')) == NULL) continue; *t = 0; //kill extension strncpy( Mission_list[count].filename, temp, 9 ); Mission_list[count].anarchy_only_flag = is_anarchy = 0; strcpy(msn_path, ":Data:"); strcat(msn_path, entry->d_name); mfile = fopen(msn_path,"rt"); if (mfile) { char *p; p = get_parm_value("name",mfile); if (p) { char *t; if ((t=strchr(p,';'))!=NULL) *t=0; t = p + strlen(p)-1; while (isspace(*t)) t--; strncpy(Mission_list[count].mission_name,p,MISSION_NAME_LEN); } else { fclose(mfile); continue; //abort this mission file } p = get_parm_value("type",mfile); //get mission type if (p) Mission_list[count].anarchy_only_flag = is_anarchy = istok(p,"anarchy"); fclose(mfile); if (!anarchy_mode && is_anarchy) continue; //skip this mission count++; } } closedir(dir); #ifdef SATURN if ( strlen(destsat_cdpath) ) { int i; char temp_spec[128]; strcpy( temp_spec, destsat_cdpath ); strcat( temp_spec, "*.MSN" ); if( !_dos_findfirst( temp_spec, 0, &find ) ) { do { FILE *mfile; int is_anarchy; char temp[13],*t; strcpy(temp,find.name); if ((t = strchr(temp,'.')) == NULL) continue; *t = 0; //kill extension for (i=0; i<count; i++ ) { if (!stricmp( Mission_list[i].filename, temp)) break; } if ( i < count ) continue; // Don't use same mission twice! strncpy( Mission_list[count].filename, temp, 9 ); Mission_list[count].anarchy_only_flag = is_anarchy = 0; mfile = fopen(find.name,"rt"); #ifdef SATURN if (!mfile) { strcpy( temp_spec, destsat_cdpath ); strcat( temp_spec, find.name ); mfile = fopen(temp_spec,"rt"); } #endif if (mfile) { char *p; p = get_parm_value("name",mfile); if (p) { char *t; if ((t=strchr(p,';'))!=NULL) *t=0; t = p + strlen(p)-1; while (isspace(*t)) t--; strncpy(Mission_list[count].mission_name,p,MISSION_NAME_LEN); } else { fclose(mfile); continue; //abort this mission file } p = get_parm_value("type",mfile); //get mission type if (p) Mission_list[count].anarchy_only_flag = is_anarchy = istok(p,"anarchy"); fclose(mfile); if (!anarchy_mode && is_anarchy) continue; //skip this mission count++; } } while( !_dos_findnext( &find ) && count<MAX_MISSIONS); } } #endif if (count>1) qsort(&Mission_list[1],count-1,sizeof(*Mission_list),ml_sort_func); load_mission(0); //set built-in mission as default return count; } //values for built-in mission #define BIM_LAST_LEVEL 27 #define BIM_LAST_SECRET_LEVEL -3 #define BIM_BRIEFING_FILE "briefing.tex" #define BIM_ENDING_FILE "endreg.tex" //loads the specfied mission from the mission list. build_mission_list() //must have been called. If build_mission_list() returns 0, this function //does not need to be called. Returns true if mission loaded ok, else false. int load_mission(int mission_num) { #ifdef MAC_SHAREWARE return 0; #endif Current_mission_num = mission_num; mprintf(( 0, "Loading mission %d\n", mission_num )); #ifndef SATURN if (mission_num == 0) { //built-in mission int i; Last_level = BIM_LAST_LEVEL; Last_secret_level = BIM_LAST_SECRET_LEVEL; //build level names for (i=0;i<Last_level;i++) sprintf(Level_names[i], "LEVEL%02d.RDL", i+1); for (i=0;i<-Last_secret_level;i++) sprintf(Secret_level_names[i], "LEVELS%1d.RDL", i+1); strcpy(Briefing_text_filename,BIM_BRIEFING_FILE); strcpy(Ending_text_filename,BIM_ENDING_FILE); Secret_level_table[0] = 10; Secret_level_table[1] = 21; Secret_level_table[2] = 24; cfile_use_alternate_hogfile(NULL); //disable alternate } else #endif { //NOTE LINK TO ABOVE IF!!!!! //read mission from file FILE *mfile; char buf[80], tmp[80], *v; strcpy(buf, ":Data:"); strcat(buf,Mission_list[mission_num].filename); strcat(buf,".MSN"); strcpy(tmp, ":Data:"); strcat(tmp,Mission_list[mission_num].filename); strcat(tmp,".HOG"); cfile_use_alternate_hogfile(tmp); mfile = fopen(buf,"rt"); #ifdef SATURN if (mfile == NULL) { if ( strlen(destsat_cdpath) ) { char temp_spec[128]; strcpy( temp_spec, destsat_cdpath ); strcat( temp_spec, buf ); mfile = fopen( temp_spec, "rt" ); } } #endif if (mfile == NULL) { Current_mission_num = -1; return 0; //error! } #ifndef MAC_SHAREWARE //init vars Last_level = 0; Last_secret_level = 0; #endif Briefing_text_filename[0] = 0; Ending_text_filename[0] = 0; #ifdef SATURN if (!stricmp(Mission_list[mission_num].filename, "DESTSAT")) { // Destination Saturn. strcpy(Briefing_text_filename,"briefsat.tex"); strcpy(Ending_text_filename,"endsat.tex"); } #endif while (mfgets(buf,80,mfile)) { if (istok(buf,"name")) continue; //already have name, go to next line else if (istok(buf,"type")) continue; //already have name, go to next line else if (istok(buf,"hog")) { char new_path[128]; char *bufp = buf; while (*(bufp++) != '=') ; if (*bufp == ' ') while (*(++bufp) == ' ') ; strcpy(new_path, ":Data:"); strcat(new_path, bufp); cfile_use_alternate_hogfile(new_path); mprintf((0, "Hog file override = [%s]\n", bufp)); } else if (istok(buf,"briefing")) { if ((v = get_value(buf)) != NULL) { add_term(v); if (strlen(v) < 13) strcpy(Briefing_text_filename,v); } } else if (istok(buf,"ending")) { if ((v = get_value(buf)) != NULL) { add_term(v); if (strlen(v) < 13) strcpy(Ending_text_filename,v); } } else if (istok(buf,"num_levels")) { if ((v=get_value(buf))!=NULL) { int n_levels,i; n_levels = atoi(v); for (i=0;i<n_levels && mfgets(buf,80,mfile);i++) { add_term(buf); if (strlen(buf) <= 12) { strcpy(Level_names[i],buf); Last_level++; } else break; } } } else if (istok(buf,"num_secrets")) { if ((v=get_value(buf))!=NULL) { int n_secret_levels,i; n_secret_levels = atoi(v); for (i=0;i<n_secret_levels && mfgets(buf,80,mfile);i++) { char *t; if ((t=strchr(buf,','))!=NULL) *t++=0; else break; add_term(buf); if (strlen(buf) <= 12) { strcpy(Secret_level_names[i],buf); Secret_level_table[i] = atoi(t); if (Secret_level_table[i]<1 || Secret_level_table[i]>Last_level) break; Last_secret_level--; } else break; } } } } fclose(mfile); if (Last_level <= 0) { Current_mission_num = -1; //no valid mission loaded return 0; } } Current_mission_filename = Mission_list[Current_mission_num].filename; Current_mission_longname = Mission_list[Current_mission_num].mission_name; return 1; } //loads the named mission if exists. //Returns true if mission loaded ok, else false. int load_mission_by_name(char *mission_name) { int n,i; n = build_mission_list(1); for (i=0;i<n;i++) if (!stricmp(mission_name,Mission_list[i].filename)) return load_mission(i); return 0; //couldn't find mission } #endif
andronix3/UIO
com/imagero/uio/ba/ByteArrayInput.java
package com.imagero.uio.ba; import com.imagero.uio.ba.ByteArray; /** * ByteArrayIO - this class gives the possibility to read from and write to given ByteArray. * It supports bit offsets and bitwise writing. * It does not extends InputStream or OutputStream, but has similar methods. * * Date: 09.04.2008 * * @author <NAME> */ public class ByteArrayInput { public static int read(ByteArray ba, Position position) { return ba.buffer[position.position++] & 0xFF; } public static int read(ByteArray ba, Position position, byte b[]) { return read(ba, position, b, 0, b.length); } public static int read(ByteArray ba, Position position, byte b[], int off, int len) { if (len <= 0) { return 0; } int c = read(ba, position); if (c == -1) { return -1; } b[off] = (byte) c; int i = 1; for (; i < len; ++i) { c = read(ba, position); if (c == -1) { break; } b[off + i] = (byte) c; } return i; } }
DTAIEB/Thoughtful-Data-Science
chapter 9/sampleCode19.py
[[USFlightsAnalysis]] @route(visualize_graph="*") @captureOutput def visualize_graph_screen(self, visualize_graph): visualize_neighbors(visualize_graph, (5,5))
hanfengzhe-hi/suitesparse-matrix-collection-website
db/collection_data/matrices/Schenk_IBMSDS/2D_27628_bjtcai.rb
<reponame>hanfengzhe-hi/suitesparse-matrix-collection-website<filename>db/collection_data/matrices/Schenk_IBMSDS/2D_27628_bjtcai.rb { matrix_id: '954', name: '2D_27628_bjtcai', group: 'Schenk_IBMSDS', description: '<NAME>, Univ. Basel: IBM TJ Watson, Yorktown, semiconductor device', author: 'IBM', editor: '<NAME>', date: '2003', kind: 'semiconductor device problem', problem_2D_or_3D: '1', num_rows: '27628', num_cols: '27628', nonzeros: '206670', num_explicit_zeros: '236228', num_strongly_connected_components: '6361', num_dmperm_blocks: '6361', structural_full_rank: 'true', structural_rank: '27628', pattern_symmetry: '1.000', numeric_symmetry: '0.219', rb_type: 'real', structure: 'unsymmetric', cholesky_candidate: 'no', positive_definite: 'no', b_field: 'full 27628-by-1 ', norm: '4.725594e+05', min_singular_value: '3.005080e-15', condition_number: '1.572535e+20', svd_rank: '18442', sprank_minus_rank: '9186', null_space_dimension: '9186', full_numerical_rank: 'no', svd_gap: '1745196.182892', image_files: '2D_27628_bjtcai.png,2D_27628_bjtcai_dmperm.png,2D_27628_bjtcai_svd.png,2D_27628_bjtcai_APlusAT_graph.gif,2D_27628_bjtcai_graph.gif,', }
romsha28/hospital_python
hospital/migrations/0010_policies.py
<filename>hospital/migrations/0010_policies.py # Generated by Django 3.2.9 on 2021-12-02 11:00 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('hospital', '0009_auto_20211202_1539'), ] operations = [ migrations.CreateModel( name='Policies', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, default='heading text', max_length=50, null=True)), ('title', models.CharField(blank=True, default='heading text', max_length=200, null=True)), ('description', models.TextField(blank=True, null=True)), ('long_description', models.TextField(blank=True, null=True)), ('slug', models.CharField(blank=True, max_length=150, null=True)), ('primary_image', models.FileField(blank=True, null=True, upload_to='page_images/', verbose_name='primary_image')), ('policy_file', models.FileField(blank=True, null=True, upload_to='policy_files/', verbose_name='primary_image')), ('sort_id', models.IntegerField(blank=True, null=True)), ('status', models.BooleanField(default=False)), ('is_deleted', models.BooleanField(default=False)), ('created_by', models.IntegerField(blank=True, null=True)), ('updated_by', models.IntegerField(blank=True, null=True)), ('deleted_by', models.IntegerField(blank=True, null=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now)), ('updated_at', models.DateTimeField(blank=True, null=True)), ('deleted_at', models.DateTimeField(blank=True, null=True)), ], ), ]
celandro/pogoprotos-java
src/main/java/POGOProtos/Rpc/AssetStreamDownloadTelemetryOrBuilder.java
<reponame>celandro/pogoprotos-java // Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos.Rpc.proto package POGOProtos.Rpc; public interface AssetStreamDownloadTelemetryOrBuilder extends // @@protoc_insertion_point(interface_extends:POGOProtos.Rpc.AssetStreamDownloadTelemetry) com.google.protobuf.MessageOrBuilder { /** * <code>.POGOProtos.Rpc.AssetTelemetryIds asset_event_id = 1;</code> * @return The enum numeric value on the wire for assetEventId. */ int getAssetEventIdValue(); /** * <code>.POGOProtos.Rpc.AssetTelemetryIds asset_event_id = 1;</code> * @return The assetEventId. */ POGOProtos.Rpc.AssetTelemetryIds getAssetEventId(); /** * <code>string url = 2;</code> * @return The url. */ java.lang.String getUrl(); /** * <code>string url = 2;</code> * @return The bytes for url. */ com.google.protobuf.ByteString getUrlBytes(); /** * <code>uint32 size = 3;</code> * @return The size. */ int getSize(); }
xformation/xformation-alertmanager-service
alertmanager-server/src/main/java/com/synectiks/process/common/plugins/sidecar/rest/resources/SidecarResource.java
/* * */ package com.synectiks.process.common.plugins.sidecar.rest.resources; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.synectiks.process.common.plugins.sidecar.audit.SidecarAuditEventTypes; import com.synectiks.process.common.plugins.sidecar.filter.ActiveSidecarFilter; import com.synectiks.process.common.plugins.sidecar.mapper.SidecarStatusMapper; import com.synectiks.process.common.plugins.sidecar.permissions.SidecarRestPermissions; import com.synectiks.process.common.plugins.sidecar.rest.models.CollectorAction; import com.synectiks.process.common.plugins.sidecar.rest.models.CollectorActions; import com.synectiks.process.common.plugins.sidecar.rest.models.NodeConfiguration; import com.synectiks.process.common.plugins.sidecar.rest.models.Sidecar; import com.synectiks.process.common.plugins.sidecar.rest.models.SidecarRegistrationConfiguration; import com.synectiks.process.common.plugins.sidecar.rest.models.SidecarSummary; import com.synectiks.process.common.plugins.sidecar.rest.requests.ConfigurationAssignment; import com.synectiks.process.common.plugins.sidecar.rest.requests.NodeConfigurationRequest; import com.synectiks.process.common.plugins.sidecar.rest.requests.RegistrationRequest; import com.synectiks.process.common.plugins.sidecar.rest.responses.RegistrationResponse; import com.synectiks.process.common.plugins.sidecar.rest.responses.SidecarListResponse; import com.synectiks.process.common.plugins.sidecar.services.ActionService; import com.synectiks.process.common.plugins.sidecar.services.SidecarService; import com.synectiks.process.common.plugins.sidecar.system.SidecarConfiguration; import com.synectiks.process.server.audit.jersey.AuditEvent; import com.synectiks.process.server.audit.jersey.NoAuditEvent; import com.synectiks.process.server.database.PaginatedList; import com.synectiks.process.server.plugin.cluster.ClusterConfigService; import com.synectiks.process.server.plugin.rest.PluginRestResource; import com.synectiks.process.server.search.SearchQuery; import com.synectiks.process.server.search.SearchQueryField; import com.synectiks.process.server.search.SearchQueryParser; import com.synectiks.process.server.shared.rest.resources.RestResource; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.hibernate.validator.constraints.NotEmpty; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import javax.inject.Inject; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.BadRequestException; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.NotFoundException; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.stream.Collectors; @Api(value = "Sidecar", description = "Manage Sidecar fleet") @Path("/sidecars") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RequiresAuthentication public class SidecarResource extends RestResource implements PluginRestResource { protected static final ImmutableMap<String, SearchQueryField> SEARCH_FIELD_MAPPING = ImmutableMap.<String, SearchQueryField>builder() .put("id", SearchQueryField.create(Sidecar.FIELD_ID)) .put("node_id", SearchQueryField.create(Sidecar.FIELD_NODE_ID)) .put("name", SearchQueryField.create(Sidecar.FIELD_NODE_NAME)) .put("sidecar_version", SearchQueryField.create(Sidecar.FIELD_SIDECAR_VERSION)) .put("last_seen", SearchQueryField.create(Sidecar.FIELD_LAST_SEEN, SearchQueryField.Type.DATE)) .put("operating_system", SearchQueryField.create(Sidecar.FIELD_OPERATING_SYSTEM)) .put("status", SearchQueryField.create(Sidecar.FIELD_STATUS, SearchQueryField.Type.INT)) .build(); private final SidecarService sidecarService; private final ActionService actionService; private final ActiveSidecarFilter activeSidecarFilter; private final SearchQueryParser searchQueryParser; private final SidecarStatusMapper sidecarStatusMapper; private final SidecarConfiguration sidecarConfiguration; @Inject public SidecarResource(SidecarService sidecarService, ActionService actionService, ClusterConfigService clusterConfigService, SidecarStatusMapper sidecarStatusMapper) { this.sidecarService = sidecarService; this.sidecarConfiguration = clusterConfigService.getOrDefault(SidecarConfiguration.class, SidecarConfiguration.defaultConfiguration()); this.actionService = actionService; this.activeSidecarFilter = new ActiveSidecarFilter(sidecarConfiguration.sidecarInactiveThreshold()); this.sidecarStatusMapper = sidecarStatusMapper; this.searchQueryParser = new SearchQueryParser(Sidecar.FIELD_NODE_NAME, SEARCH_FIELD_MAPPING); } @GET @Timed @Path("/all") @ApiOperation(value = "Lists all existing Sidecar registrations") @RequiresPermissions(SidecarRestPermissions.SIDECARS_READ) public SidecarListResponse all() { final List<Sidecar> sidecars = sidecarService.all(); final List<SidecarSummary> sidecarSummaries = sidecarService.toSummaryList(sidecars, activeSidecarFilter); return SidecarListResponse.create("", PaginatedList.PaginationInfo.create(sidecarSummaries.size(), sidecarSummaries.size(), 1, sidecarSummaries.size()), sidecarSummaries.size(), false, null, null, sidecarSummaries); } @GET @Timed @ApiOperation(value = "Lists existing Sidecar registrations using pagination") @RequiresPermissions(SidecarRestPermissions.SIDECARS_READ) public SidecarListResponse sidecars(@ApiParam(name = "page") @QueryParam("page") @DefaultValue("1") int page, @ApiParam(name = "per_page") @QueryParam("per_page") @DefaultValue("50") int perPage, @ApiParam(name = "query") @QueryParam("query") @DefaultValue("") String query, @ApiParam(name = "sort", value = "The field to sort the result on", required = true, allowableValues = "title,description,name,id") @DefaultValue(Sidecar.FIELD_NODE_NAME) @QueryParam("sort") String sort, @ApiParam(name = "order", value = "The sort direction", allowableValues = "asc, desc") @DefaultValue("asc") @QueryParam("order") String order, @ApiParam(name = "only_active") @QueryParam("only_active") @DefaultValue("false") boolean onlyActive) { final String mappedQuery = sidecarStatusMapper.replaceStringStatusSearchQuery(query); SearchQuery searchQuery; try { searchQuery = searchQueryParser.parse(mappedQuery); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid argument in search query: " + e.getMessage()); } final PaginatedList<Sidecar> sidecars = onlyActive ? sidecarService.findPaginated(searchQuery, activeSidecarFilter, page, perPage, sort, order) : sidecarService.findPaginated(searchQuery, page, perPage, sort, order); final List<SidecarSummary> collectorSummaries = sidecarService.toSummaryList(sidecars, activeSidecarFilter); final long total = sidecarService.count(); return SidecarListResponse.create(query, sidecars.pagination(), total, onlyActive, sort, order, collectorSummaries); } @GET @Timed @Path("/{sidecarId}") @ApiOperation(value = "Returns at most one Sidecar summary for the specified id") @ApiResponses(value = { @ApiResponse(code = 404, message = "No Sidecar with the specified id exists") }) @RequiresPermissions(SidecarRestPermissions.SIDECARS_READ) public SidecarSummary get(@ApiParam(name = "sidecarId", required = true) @PathParam("sidecarId") @NotEmpty String sidecarId) { final Sidecar sidecar = sidecarService.findByNodeId(sidecarId); if (sidecar == null) { throw new NotFoundException("Could not find sidecar <" + sidecarId + ">"); } return sidecar.toSummary(activeSidecarFilter); } @PUT @Timed @Path("/{sidecarId}") @ApiOperation(value = "Create/update a Sidecar registration", notes = "This is a stateless method which upserts a Sidecar registration") @ApiResponses(value = { @ApiResponse(code = 400, message = "The supplied request is not valid.") }) @RequiresPermissions(SidecarRestPermissions.SIDECARS_UPDATE) @NoAuditEvent("this is only a ping from Sidecars, and would overflow the audit log") public Response register(@ApiParam(name = "sidecarId", value = "The id this Sidecar is registering as.", required = true) @PathParam("sidecarId") @NotEmpty String sidecarId, @ApiParam(name = "JSON body", required = true) @Valid @NotNull RegistrationRequest request, @HeaderParam(value = "X-alertmanager-Sidecar-Version") @NotEmpty String sidecarVersion) { final Sidecar newSidecar; final Sidecar oldSidecar = sidecarService.findByNodeId(sidecarId); List<ConfigurationAssignment> assignments = null; if (oldSidecar != null) { assignments = oldSidecar.assignments(); newSidecar = oldSidecar.toBuilder() .nodeName(request.nodeName()) .nodeDetails(request.nodeDetails()) .sidecarVersion(sidecarVersion) .lastSeen(DateTime.now(DateTimeZone.UTC)) .build(); } else { newSidecar = sidecarService.fromRequest(sidecarId, request, sidecarVersion); } sidecarService.save(newSidecar); final CollectorActions collectorActions = actionService.findActionBySidecar(sidecarId, true); List<CollectorAction> collectorAction = null; if (collectorActions != null) { collectorAction = collectorActions.action(); } RegistrationResponse sidecarRegistrationResponse = RegistrationResponse.create( SidecarRegistrationConfiguration.create( this.sidecarConfiguration.sidecarUpdateInterval().toStandardDuration().getStandardSeconds(), this.sidecarConfiguration.sidecarSendStatus()), this.sidecarConfiguration.sidecarConfigurationOverride(), collectorAction, assignments); return Response.accepted(sidecarRegistrationResponse).build(); } @PUT @Timed @Path("/configurations") @ApiOperation(value = "Assign configurations to sidecars") @RequiresPermissions(SidecarRestPermissions.SIDECARS_UPDATE) @AuditEvent(type = SidecarAuditEventTypes.SIDECAR_UPDATE) public Response assignConfiguration(@ApiParam(name = "JSON body", required = true) @Valid @NotNull NodeConfigurationRequest request) throws NotFoundException { List<String> nodeIdList = request.nodes().stream() .filter(distinctByKey(NodeConfiguration::nodeId)) .map(NodeConfiguration::nodeId) .collect(Collectors.toList()); for (String nodeId : nodeIdList) { List<ConfigurationAssignment> nodeRelations = request.nodes().stream() .filter(a -> a.nodeId().equals(nodeId)) .flatMap(a -> a.assignments().stream()) .collect(Collectors.toList()); try { Sidecar sidecar = sidecarService.assignConfiguration(nodeId, nodeRelations); sidecarService.save(sidecar); } catch (com.synectiks.process.server.database.NotFoundException e) { throw new NotFoundException(e.getMessage()); } } return Response.accepted().build(); } private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } }
lorenzojcd/linux-system-programming
src/getsid-example.c
#include <unistd.h> #include <stdio.h> int main (void) { pid_t sid; sid = getsid (0); if (sid == -1) { perror ("getsid"); return 1; } printf ("My session id=%d\n", sid); return 0; }
mitixx/abilitysheet
app/models/concerns/user/ist.rb
<reponame>mitixx/abilitysheet<gh_stars>10-100 # frozen_string_literal: true require 'ist_client' module User::Ist extend ActiveSupport::Concern FROM_IST_TO_AB = { '旋律のドグマ~Miserables~' => '旋律のドグマ ~Misérables~', '火影' => '焱影' }.freeze SEARCH_PARAMS = { q: { chart_level_eq: 12, chart_play_type_status_eq: 0, version_eq: Abilitysheet::Application.config.iidx_version } }.freeze def find_pref(pref) User::Static::PREF.index(pref) end # NOTE: 見つからなかったやつは無段位 def find_grade(grade) User::Static::GRADE.index(grade.split[1]) || User::Static::GRADE.size - 1 end def update_user(user) old_djname = djname self.djname = old_djname unless update(djname: user['user_activity']['djname']) pref = find_pref(user['user_activity']['pref_status']) grade = find_grade(user['user_activity']['sp_grade_status']) update!(grade: grade, pref: pref) avatar.attach(io: URI.parse(user['image_path']).open, filename: 'avatar.png') unless Rails.env.development? end def find_sheet_id(score, sheets) if score['title'] == 'gigadelic' || score['title'] == 'Innocent Walls' difficulty_type = score['difficulty_type_status'] == 'HYPER' ? '[H]' : '[A]' sheets[score['title'] + difficulty_type] elsif FROM_IST_TO_AB.key?(score['title']) sheets[FROM_IST_TO_AB[score['title']]] elsif score['difficulty_type_status'] == 'LEGGENDARIA' sheets["#{score['title']}†"] else sheets[score['title']] end end included do def check_ist_user ist_client.get_user(iidxid) end def update_ist user = ist_client.get_user(iidxid) return false if user['iidxid'] != iidxid result = ist_client.get_scores(iidxid, SEARCH_PARAMS) return false if result['error'] == 'Not Found' update_user(user) sheets = Sheet.active.pluck(:title, :id).to_h result['scores'].each do |score| sheet_id = find_sheet_id(score, sheets) # 削除曲だけunlessになる可能性がある next unless sheet_id s = scores.find_or_initialize_by(sheet_id: sheet_id, version: Abilitysheet::Application.config.iidx_version) state = ::Static::LAMP_OFFICIAL.index(score['clear_type_status']) # NO PLAYのものは更新しない next if state == 7 # ランプに変動がある、あるいはスコアが変動しているパターンでは更新する next if s.state == state && score['score'].zero? scores.find_or_create_by!( sheet_id: sheet_id, version: Abilitysheet::Application.config.iidx_version ).update_with_logs( sheet_id: sheet_id, state: state, score: score['score'], bp: score['miss_count'] ) end end def ist_client IstClient.new end end end
MalikuMane/TerraForge3D
TerraForge3D/include/Sky/CubeMap.h
<gh_stars>100-1000 #pragma once #include <glm/glm.hpp> #include "Base/TextureCubemap.h" class ApplicationState; class Shader; class TextureCubemap; class Model; class CubeMapManager { public: CubeMapManager(ApplicationState *appState); ~CubeMapManager(); void RenderSkybox(glm::mat4 view, glm::mat4 proj, bool useBox, bool useProcedural, float cirrus, float cumulus, float time, float *fsun, float upF); TextureCubemap *GetSkyboxCubemapTexture(); public: ApplicationState *appState = nullptr; Shader *skyboxShader = nullptr; Shader *skyproShader = nullptr; TextureCubemap *cubemap = nullptr; Model *skySphere = nullptr; uint32_t textureID = 0; uint32_t vao = 0; };
hyller/GladiatorCots
QP/v5.4.2/qpc/examples/arm-cm/game_ek-lm3s811/mine2.c
/***************************************************************************** * Model: game.qm * File: ./mine2.c * * This code has been generated by QM tool (see state-machine.com/qm). * DO NOT EDIT THIS FILE MANUALLY. All your changes will be lost. * * This program is open source software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. *****************************************************************************/ /*${.::mine2.c} ............................................................*/ #include "qpc.h" #include "bsp.h" #include "game.h" Q_DEFINE_THIS_FILE /* encapsulated delcaration of the Mine2 HSM -------------------------------*/ /*${AOs::Mine2} ............................................................*/ typedef struct { /* protected: */ QMsm super; /* private: */ uint8_t x; uint8_t y; /* public: */ uint8_t exp_ctr; } Mine2; /* protected: */ static QState Mine2_initial(Mine2 * const me, QEvt const * const e); static QState Mine2_unused (Mine2 * const me, QEvt const * const e); static QMState const Mine2_unused_s = { (QMState const *)0, /* superstate (top) */ Q_STATE_CAST(&Mine2_unused), Q_ACTION_CAST(0), /* no entry action */ Q_ACTION_CAST(0), /* no exit action */ Q_ACTION_CAST(0) /* no intitial tran. */ }; static QState Mine2_used (Mine2 * const me, QEvt const * const e); static QState Mine2_used_x(Mine2 * const me); static QMState const Mine2_used_s = { (QMState const *)0, /* superstate (top) */ Q_STATE_CAST(&Mine2_used), Q_ACTION_CAST(0), /* no entry action */ Q_ACTION_CAST(&Mine2_used_x), Q_ACTION_CAST(0) /* no intitial tran. */ }; static QState Mine2_planted (Mine2 * const me, QEvt const * const e); static QMState const Mine2_planted_s = { &Mine2_used_s, /* superstate */ Q_STATE_CAST(&Mine2_planted), Q_ACTION_CAST(0), /* no entry action */ Q_ACTION_CAST(0), /* no exit action */ Q_ACTION_CAST(0) /* no intitial tran. */ }; static QState Mine2_exploding (Mine2 * const me, QEvt const * const e); static QState Mine2_exploding_e(Mine2 * const me); static QMState const Mine2_exploding_s = { &Mine2_used_s, /* superstate */ Q_STATE_CAST(&Mine2_exploding), Q_ACTION_CAST(&Mine2_exploding_e), Q_ACTION_CAST(0), /* no exit action */ Q_ACTION_CAST(0) /* no intitial tran. */ }; /* local objects -----------------------------------------------------------*/ static Mine2 l_mine2[GAME_MINES_MAX]; /* a pool of type-2 mines */ /* helper macro to provide the ID of this mine */ #define MINE_ID(me_) ((uint8_t)((me_) - l_mine2)) /* Mine2 class definition --------------------------------------------------*/ /*${AOs::Mine2_ctor} .......................................................*/ QMsm * Mine2_ctor(uint8_t id) { Mine2 *me; Q_REQUIRE(id < GAME_MINES_MAX); me = &l_mine2[id]; /* superclass' ctor */ QMsm_ctor(&me->super, Q_STATE_CAST(&Mine2_initial)); return (QMsm *)me; } /*${AOs::Mine2} ............................................................*/ /*${AOs::Mine2::SM} ........................................................*/ static QState Mine2_initial(Mine2 * const me, QEvt const * const e) { static QMTranActTable const tatbl_ = { /* transition-action table */ &Mine2_unused_s, { Q_ACTION_CAST(0) /* zero terminator */ } }; /* ${AOs::Mine2::SM::initial} */ static uint8_t dict_sent; if (!dict_sent) { /* object dictionaries for Mine2 pool... */ QS_OBJ_DICTIONARY(&l_mine2[0]); QS_OBJ_DICTIONARY(&l_mine2[1]); QS_OBJ_DICTIONARY(&l_mine2[2]); QS_OBJ_DICTIONARY(&l_mine2[3]); QS_OBJ_DICTIONARY(&l_mine2[4]); /*function dictionaries for Mine2 HSM... */ QS_FUN_DICTIONARY(&Mine2_initial); QS_FUN_DICTIONARY(&Mine2_unused); QS_FUN_DICTIONARY(&Mine2_used); QS_FUN_DICTIONARY(&Mine2_planted); QS_FUN_DICTIONARY(&Mine2_exploding); dict_sent = 1U; } /* local signals... */ QS_SIG_DICTIONARY(MINE_PLANT_SIG, me); QS_SIG_DICTIONARY(MINE_DISABLED_SIG, me); QS_SIG_DICTIONARY(MINE_RECYCLE_SIG, me); QS_SIG_DICTIONARY(SHIP_IMG_SIG, me); QS_SIG_DICTIONARY(MISSILE_IMG_SIG, me); (void)e; /* avoid the "unreferenced parameter" warning */ return QM_TRAN_INIT(&tatbl_); } /*${AOs::Mine2::SM::unused} ................................................*/ /* ${AOs::Mine2::SM::unused} */ static QState Mine2_unused(Mine2 * const me, QEvt const * const e) { QState status_; switch (e->sig) { /* ${AOs::Mine2::SM::unused::MINE_PLANT} */ case MINE_PLANT_SIG: { static QMTranActTable const tatbl_ = { /* transition-action table */ &Mine2_planted_s, { Q_ACTION_CAST(0) /* zero terminator */ } }; me->x = Q_EVT_CAST(ObjectPosEvt)->x; me->y = Q_EVT_CAST(ObjectPosEvt)->y; status_ = QM_TRAN(&tatbl_); break; } default: { status_ = QM_SUPER(); break; } } return status_; } /*${AOs::Mine2::SM::used} ..................................................*/ /* ${AOs::Mine2::SM::used} */ static QState Mine2_used_x(Mine2 * const me) { /* tell the Tunnel that this mine is becoming disabled */ MineEvt *mev = Q_NEW(MineEvt, MINE_DISABLED_SIG); mev->id = MINE_ID(me); QACTIVE_POST(AO_Tunnel, (QEvt *)mev, me); return QM_EXIT(&Mine2_used_s); } /* ${AOs::Mine2::SM::used} */ static QState Mine2_used(Mine2 * const me, QEvt const * const e) { QState status_; switch (e->sig) { /* ${AOs::Mine2::SM::used::MINE_RECYCLE} */ case MINE_RECYCLE_SIG: { static struct { QMState const *target; QActionHandler act[2]; } const tatbl_ = { /* transition-action table */ &Mine2_unused_s, /* target state */ { Q_ACTION_CAST(&Mine2_used_x), /* exit */ Q_ACTION_CAST(0) /* zero terminator */ } }; status_ = QM_TRAN(&tatbl_); break; } default: { status_ = QM_SUPER(); break; } } return status_; } /*${AOs::Mine2::SM::used::planted} .........................................*/ /* ${AOs::Mine2::SM::used::planted} */ static QState Mine2_planted(Mine2 * const me, QEvt const * const e) { QState status_; switch (e->sig) { /* ${AOs::Mine2::SM::used::planted::TIME_TICK} */ case TIME_TICK_SIG: { /* ${AOs::Mine2::SM::used::planted::TIME_TICK::[me->x>=GAME_SPEED_X]} */ if (me->x >= GAME_SPEED_X) { ObjectImageEvt *oie; me->x -= GAME_SPEED_X; /* move the mine 1 step */ /* tell the Tunnel to draw the Mine */ oie = Q_NEW(ObjectImageEvt, MINE_IMG_SIG); oie->x = me->x; oie->y = me->y; oie->bmp = MINE2_BMP; QACTIVE_POST(AO_Tunnel, (QEvt *)oie, me); status_ = QM_HANDLED(); } /* ${AOs::Mine2::SM::used::planted::TIME_TICK::[else]} */ else { static struct { QMState const *target; QActionHandler act[2]; } const tatbl_ = { /* transition-action table */ &Mine2_unused_s, /* target state */ { Q_ACTION_CAST(&Mine2_used_x), /* exit */ Q_ACTION_CAST(0) /* zero terminator */ } }; status_ = QM_TRAN(&tatbl_); } break; } /* ${AOs::Mine2::SM::used::planted::SHIP_IMG} */ case SHIP_IMG_SIG: { uint8_t x = Q_EVT_CAST(ObjectImageEvt)->x; uint8_t y = Q_EVT_CAST(ObjectImageEvt)->y; uint8_t bmp = Q_EVT_CAST(ObjectImageEvt)->bmp; /* ${AOs::Mine2::SM::used::planted::SHIP_IMG::[collisionwithMINE2_BMP?]} */ if (do_bitmaps_overlap(MINE2_BMP, me->x, me->y, bmp, x, y)) { static struct { QMState const *target; QActionHandler act[2]; } const tatbl_ = { /* transition-action table */ &Mine2_unused_s, /* target state */ { Q_ACTION_CAST(&Mine2_used_x), /* exit */ Q_ACTION_CAST(0) /* zero terminator */ } }; static MineEvt const mine1_hit = { { HIT_MINE_SIG, 0U, 0U }, /* the QEvt base instance */ 2U /* type of the mine (2 for Mine type-2) */ }; QACTIVE_POST(AO_Ship, (QEvt *)&mine1_hit, me); /* go straight to 'disabled' and let the Ship do * the exploding */ status_ = QM_TRAN(&tatbl_); } else { status_ = QM_UNHANDLED(); } break; } /* ${AOs::Mine2::SM::used::planted::MISSILE_IMG} */ case MISSILE_IMG_SIG: { uint8_t x = Q_EVT_CAST(ObjectImageEvt)->x; uint8_t y = Q_EVT_CAST(ObjectImageEvt)->y; uint8_t bmp = Q_EVT_CAST(ObjectImageEvt)->bmp; /* ${AOs::Mine2::SM::used::planted::MISSILE_IMG::[collisionwithMINE2_MISSILE_BMP?~} */ if (do_bitmaps_overlap(MINE2_MISSILE_BMP, me->x, me->y, bmp, x, y)) { static struct { QMState const *target; QActionHandler act[2]; } const tatbl_ = { /* transition-action table */ &Mine2_exploding_s, /* target state */ { Q_ACTION_CAST(&Mine2_exploding_e), /* entry */ Q_ACTION_CAST(0) /* zero terminator */ } }; /* NOTE: Mine type-2 is nastier than Mine type-1. * The type-2 mine can hit the Ship with any of its * "tentacles". However, it can be destroyed by the * Missile only by hitting its center, defined as * a smaller bitmap MINE2_MISSILE_BMP. */ static ScoreEvt const mine2_destroyed = { { DESTROYED_MINE_SIG, 0U, 0U }, /* the QEvt base instance */ 45U /* score for destroying Mine type-2 */ }; QACTIVE_POST(AO_Missile, (QEvt *)&mine2_destroyed, me); status_ = QM_TRAN(&tatbl_); } else { status_ = QM_UNHANDLED(); } break; } default: { status_ = QM_SUPER(); break; } } return status_; } /*${AOs::Mine2::SM::used::exploding} .......................................*/ /* ${AOs::Mine2::SM::used::exploding} */ static QState Mine2_exploding_e(Mine2 * const me) { me->exp_ctr = 0U; return QM_ENTRY(&Mine2_exploding_s); } /* ${AOs::Mine2::SM::used::exploding} */ static QState Mine2_exploding(Mine2 * const me, QEvt const * const e) { QState status_; switch (e->sig) { /* ${AOs::Mine2::SM::used::exploding::TIME_TICK} */ case TIME_TICK_SIG: { /* ${AOs::Mine2::SM::used::exploding::TIME_TICK::[stillonscreen?]} */ if ((me->x >= GAME_SPEED_X) && (me->exp_ctr < 15U)) { ObjectImageEvt *oie; ++me->exp_ctr; /* advance the explosion counter */ me->x -= GAME_SPEED_X; /* move explosion by 1 step */ /* tell the Game to render the current stage of Explosion */ oie = Q_NEW(ObjectImageEvt, EXPLOSION_SIG); oie->x = me->x + 1U; /* x of explosion */ oie->y = (int8_t)((int)me->y - 4 + 2); /* y of explosion */ oie->bmp = EXPLOSION0_BMP + (me->exp_ctr >> 2); QACTIVE_POST(AO_Tunnel, (QEvt *)oie, me); status_ = QM_HANDLED(); } /* ${AOs::Mine2::SM::used::exploding::TIME_TICK::[else]} */ else { static struct { QMState const *target; QActionHandler act[2]; } const tatbl_ = { /* transition-action table */ &Mine2_unused_s, /* target state */ { Q_ACTION_CAST(&Mine2_used_x), /* exit */ Q_ACTION_CAST(0) /* zero terminator */ } }; status_ = QM_TRAN(&tatbl_); } break; } default: { status_ = QM_SUPER(); break; } } return status_; }
DiaLight/OpenCVClient
src/main/c++/native/ClientApp.cpp
<reponame>DiaLight/OpenCVClient /* * File: Main.cpp * Author: dialight * * Created on 13 октября 2016 г., 8:42 */ #include <App.hpp> #include <opencv2/opencv.hpp> #include <utils/Profiler.hpp> #include <network/stream/UDPSocketClient.hpp> #include <network/stream/protocol/ImagePacket.hpp> #include <network/stream/StreamClient.hpp> #include <Properties.hpp> #include <frame/source/FrameSource.hpp> #include <frame/source/WebCamSrc.hpp> #include <frame/source/ImageSrc.hpp> #include <frame/source/RaspiCamSrc.hpp> #include <utils/DiaUtils.hpp> #include <utils/PointerGuard.hpp> #include <IntelEdison.hpp> #include <network/properties/PropertiesClient.hpp> #include <frame/processor/ObjectDetect.hpp> #include <frame/processor/Loop.hpp> using namespace std; using namespace cv; int main(int argc, const char* const argv[]) { app.init(); SimpleConfig cfg(argc, (const char **) argv); if(!cfg.read()) return 0; // if(showProperties) { // props.registerListener(&propertiesLogger); // } if(cfg.edisonDebug >= 0) { IntelEdison e; int i = 0; while(app.isAlive()) { e.transmit(); cout << i << endl; usleep((__useconds_t) cfg.edisonDebug * 1000 * 1000); } return 0; } //get target address from command line ServerAddr addr(cfg.remote); try { PointerGuard<FrameSource> frameSrc; if (cfg.deviceIndex >= 0) { frameSrc.set(new WebCamSrc(cfg.deviceIndex)); } else if(!cfg.imagePath.empty()) { frameSrc.set(new ImageSrc(cfg.imagePath)); } else { frameSrc.set(new RaspiCamSrc()); } if(!frameSrc->init()) { return -1; } if(!cfg.resolution.empty()) { cout << "Set resolution to " << cfg.resolution << endl; vector<string> spl = strSplit(cfg.resolution, 'x'); frameSrc->setResolution(stoi(spl[0]), stoi(spl[1])); } if(cfg.fps > 0) { cout << "Set fps to " << cfg.fps << endl; frameSrc->setFps(cfg.fps); } //init tcp properties client bound to target address PropertiesClient propc(&addr); propc.runAsync(); PointerGuard<FrameProcessor> frameProc; if(!cfg.xmlPath.empty()) { frameProc.set(new ObjectDetect(cfg.xmlPath)); } else { frameProc.set(new Loop(&cfg)); } //init udp stream client bound to target address StreamClient scli; scli.bind(); if(cfg.local) { // TODO: build properties in local window // createTrackbar( "Sigma", "Laplacian", &sigma, 15, 0 ); namedWindow("image", 1); } Profiler prof(cfg.profiler); Mat frame; frameSrc->capture(frame); frameProc->init(frame); while (app.isAlive()) { prof.start(); frameSrc->capture(frame); prof.point("Capture"); if(flip) cv::flip(frame, frame, -1); frameProc->handle(frame); prof.point("OpenCV"); ImagePacket packet(frame); //network structure prof.point("Compress"); scli.sendPacket(&packet, &addr); //very fast operation ( < 1 ms) if(cfg.local) { imshow("image", frame); waitKey(1); } int del = props.getInt("loop.delayms", 0); if(del > 0) { usleep((__useconds_t) del * 1000); } prof.end(); } } catch(cv::Exception e) { // throw e; cerr << "err: " << e.err << endl; cerr << "file: " << e.file << endl; cerr << "func: " << e.func << endl; cerr << "msg: " << e.msg << endl; } app.close(); cout << "Exit main thread gracefully" << endl; return 0; }
amosnothing/ClickHouse
src/Processors/Sources/DelayedSource.cpp
#include <Processors/Sources/DelayedSource.h> #include "NullSource.h" namespace DB { DelayedSource::DelayedSource(const Block & header, Creator processors_creator) : IProcessor({}, OutputPorts(3, header)) , creator(std::move(processors_creator)) { } IProcessor::Status DelayedSource::prepare() { /// At first, wait for main input is needed and expand pipeline. if (inputs.empty()) { auto & first_output = outputs.front(); /// If main port was finished before callback was called, stop execution. if (first_output.isFinished()) { for (auto & output : outputs) output.finish(); return Status::Finished; } if (!first_output.isNeeded()) return Status::PortFull; /// Call creator callback to get processors. if (processors.empty()) return Status::Ready; return Status::ExpandPipeline; } /// Process ports in order: main, totals, extremes auto output = outputs.begin(); for (auto input = inputs.begin(); input != inputs.end(); ++input, ++output) { if (output->isFinished()) { input->close(); continue; } if (!output->isNeeded()) return Status::PortFull; if (input->isFinished()) { output->finish(); continue; } input->setNeeded(); if (!input->hasData()) return Status::PortFull; output->pushData(input->pullData(true)); return Status::PortFull; } return Status::Finished; } void DelayedSource::work() { auto pipe = creator(); main_output = &pipe.getPort(); totals_output = pipe.getTotalsPort(); extremes_output = pipe.getExtremesPort(); processors = std::move(pipe).detachProcessors(); if (!totals_output) { processors.emplace_back(std::make_shared<NullSource>(main_output->getHeader())); totals_output = &processors.back()->getOutputs().back(); } if (!extremes_output) { processors.emplace_back(std::make_shared<NullSource>(main_output->getHeader())); extremes_output = &processors.back()->getOutputs().back(); } } Processors DelayedSource::expandPipeline() { /// Add new inputs. They must have the same header as output. for (const auto & output : {main_output, totals_output, extremes_output}) { inputs.emplace_back(outputs.front().getHeader(), this); /// Connect checks that header is same for ports. connect(*output, inputs.back()); inputs.back().setNeeded(); } /// Executor will check that all processors are connected. return std::move(processors); } Pipe createDelayedPipe(const Block & header, DelayedSource::Creator processors_creator) { auto source = std::make_shared<DelayedSource>(header, std::move(processors_creator)); Pipe pipe(&source->getPort(DelayedSource::Main)); pipe.setTotalsPort(&source->getPort(DelayedSource::Totals)); pipe.setExtremesPort(&source->getPort(DelayedSource::Extremes)); pipe.addProcessors({std::move(source)}); return pipe; } }
Kney-Delach/OpenGL-Rendering
OpenGL-Rendering-Engine/Exalted/src/Platform/OpenGL/OpenGLFrameBuffer.h
/*************************************************************************** * Filename : OpenGLFrameBuffer.h * Name : <NAME> * Date : 08/11/2019 * Description : Implements the OpenGL Framebuffer wrapper .---. .'_:___". |__ --==| [ ] :[| |__| I=[| / / ____| |-/.____.' /___\ /___\ ***************************************************************************/ #include "Core/Renderer/FrameBuffer.h" #pragma once namespace Exalted { class OpenGLFrameBuffer : public FrameBuffer { public: OpenGLFrameBuffer(uint32_t width, uint32_t height); // framebuffer for point light shadows OpenGLFrameBuffer(uint32_t width, uint32_t height, FrameBufferFormat format); OpenGLFrameBuffer(uint32_t width, uint32_t height, bool generateBorderColor); // framebuffer for directional light shadows virtual ~OpenGLFrameBuffer(); virtual void Resize(uint32_t width, uint32_t height) override; virtual void Bind() const override; virtual void Unbind() const override; virtual void UnbindMiniFrame() const override; virtual void BindTexture(uint32_t slot = 0) const override; virtual void BindTextureCube(uint32_t slot = 0) const override; virtual uint32_t GetRendererID() const override { return m_RendererID; } virtual uint32_t GetColorAttachmentRendererID() const override { return m_ColorAttachment; } virtual uint32_t GetRenderBufferAttachmentRendererID() const override { return m_RenderBufferID; } virtual uint32_t GetWidth() const { return m_Width; } virtual uint32_t GetHeight() const { return m_Height; } virtual FrameBufferFormat GetFormat() const { return m_Format; } private: uint32_t m_RendererID = 0; uint32_t m_Width; uint32_t m_Height; FrameBufferFormat m_Format; uint32_t m_ColorAttachment; uint32_t m_RenderBufferID; }; }
CityOfVernonia/cov-arcgis-esm
dist/viewModels/UnitsViewModel.js
/** * A view model for managing location, length, area and elevation units and providing utility methods for returning unit <select>s. */ import { __decorate } from "tslib"; import Accessor from '@arcgis/core/core/Accessor'; import { property, subclass } from '@arcgis/core/core/accessorSupport/decorators'; import { tsx } from '@arcgis/core/widgets/support/widget'; let KEY = 0; let UnitsViewModel = class UnitsViewModel extends Accessor { constructor(properties) { super(properties); /** * CSS class string for <select>s. * * @default 'esri-select' */ this.selectClass = 'esri-select'; /** * Current location unit. */ this.locationUnit = 'dec'; /** * Available location unit and display text key/value pairs. */ this.locationUnits = { dec: 'Decimal Degrees', dms: 'Degrees Minutes Seconds', }; /** * Current length unit. */ this.lengthUnit = 'feet'; /** * Available length unit and display text key/value pairs. */ this.lengthUnits = { meters: 'Meters', feet: 'Feet', kilometers: 'Kilometers', miles: 'Miles', 'nautical-miles': 'Nautical Miles', yards: 'Yards', }; /** * Current area unit. */ this.areaUnit = 'acres'; /** * Available area unit and display text key/value pairs. */ this.areaUnits = { acres: 'Acres', ares: 'Ares', hectares: 'Hectacres', 'square-feet': 'Square Feet', 'square-meters': 'Square Meters', 'square-yards': 'Square Yards', 'square-kilometers': 'Square Kilometers', 'square-miles': 'Square Miles', }; /** * Current elevation unit. */ this.elevationUnit = 'feet'; /** * Available elevation unit and display text key/value pairs. */ this.elevationUnits = { feet: 'Feet', meters: 'Meters', }; } /** * Return location <select> which updates `locationUnit` property on change. * * @param name <select> `name` attribute * @param title <select> `title` attribute */ locationSelect(name, title) { return (tsx("select", { class: this.selectClass, name: name || '', title: title || '', bind: this, onchange: (evt) => { this.locationUnit = evt.target.value; } }, this._createUnitOptions(this.locationUnits, this.locationUnit))); } /** * Return length <select> which updates `lengthUnit` property on change. * * @param name <select> `name` attribute * @param title <select> `title` attribute */ lengthSelect(name, title) { return (tsx("select", { class: this.selectClass, name: name || '', title: title || '', bind: this, onchange: (evt) => { this.lengthUnit = evt.target.value; } }, this._createUnitOptions(this.lengthUnits, this.lengthUnit.toString()))); } /** * Return area <select> which updates `areaUnit` property on change. * * @param name <select> `name` attribute * @param title <select> `title` attribute */ areaSelect(name, title) { return (tsx("select", { class: this.selectClass, name: name || '', title: title || '', bind: this, onchange: (evt) => { this.areaUnit = evt.target.value; } }, this._createUnitOptions(this.areaUnits, this.areaUnit.toString()))); } /** * Return elevation <select> which updates `elevationUnit` property on change. * * @param name <select> `name` attribute * @param title <select> `title` attribute */ elevationSelect(name, title) { return (tsx("select", { class: this.selectClass, name: name || '', title: title || '', bind: this, onchange: (evt) => { this.elevationUnit = evt.target.value; } }, this._createUnitOptions(this.elevationUnits, this.elevationUnit))); } // create <options> _createUnitOptions(units, defaultUnit) { const options = []; for (const unit in units) { options.push(tsx("option", { key: KEY++, value: unit, selected: unit === defaultUnit }, units[unit])); } return options; } }; __decorate([ property() ], UnitsViewModel.prototype, "selectClass", void 0); __decorate([ property() ], UnitsViewModel.prototype, "locationUnit", void 0); __decorate([ property() ], UnitsViewModel.prototype, "locationUnits", void 0); __decorate([ property() ], UnitsViewModel.prototype, "lengthUnit", void 0); __decorate([ property() ], UnitsViewModel.prototype, "lengthUnits", void 0); __decorate([ property() ], UnitsViewModel.prototype, "areaUnit", void 0); __decorate([ property() ], UnitsViewModel.prototype, "areaUnits", void 0); __decorate([ property() ], UnitsViewModel.prototype, "elevationUnit", void 0); __decorate([ property() ], UnitsViewModel.prototype, "elevationUnits", void 0); UnitsViewModel = __decorate([ subclass('cov.viewModels.UnitsViewModel') ], UnitsViewModel); export default UnitsViewModel;
jgraichen/codeocean
spec/controllers/statistics_controller_spec.rb
require 'rails_helper' describe StatisticsController do let(:user) { FactoryBot.create(:admin) } before(:each) { allow(controller).to receive(:current_user).and_return(user) } [:show, :graphs].each do |route| describe "GET ##{route}" do before(:each) { get route } expect_status(200) expect_template(route) end end [:user_activity_history, :rfc_activity_history].each do |route| describe "GET ##{route}" do before(:each) { get route } expect_status(200) expect_template(:activity_history) end end [:show, :user_activity, :user_activity_history, :rfc_activity, :rfc_activity_history].each do |route| describe "GET ##{route}.json" do before(:each) { get route, format: :json } expect_status(200) expect_json end end end
d0si/vortex
Server/Server/Http/HttpListener.cpp
<filename>Server/Server/Http/HttpListener.cpp #include <Server/Http/HttpListener.h> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/beast/core/bind_handler.hpp> #include <Core/Logging.h> #include <Server/Http/HttpSession.h> namespace asio = boost::asio; namespace beast = boost::beast; using asio::ip::tcp; using boost::system::error_code; namespace Vortex::Server::Http { HttpListener::HttpListener( const Maze::Element& config, asio::io_context& io_ctx, tcp::endpoint endpoint, Core::Modules::DependencyInjector* server_di) : _config(config), _io_ctx(io_ctx), _acceptor(asio::make_strand(io_ctx)), _server_di(server_di) { error_code ec; _acceptor.open(endpoint.protocol(), ec); if (ec) { VORTEX_CRITICAL("Listener open failed. {0}", ec.message()); return; } _acceptor.set_option(asio::socket_base::reuse_address(true), ec); if (ec) { VORTEX_CRITICAL("Listener set option REUSE_ADDRESS failed. {0}", ec.message()); return; } _acceptor.bind(endpoint, ec); if (ec) { VORTEX_CRITICAL("Listener bind failed. {0}", ec.message()); return; } _acceptor.listen(asio::socket_base::max_listen_connections, ec); if (ec) { VORTEX_CRITICAL("Listener listen failed. {0}", ec.message()); return; } } void HttpListener::run() { if (!_acceptor.is_open()) { return; } do_accept(); } void HttpListener::do_accept() { _acceptor.async_accept( asio::make_strand(_io_ctx), beast::bind_front_handler( &HttpListener::on_accept, shared_from_this())); } void HttpListener::on_accept(error_code ec, tcp::socket socket) { if (ec) { VORTEX_CRITICAL("Listener accept failed. {0}", ec.message()); } else { std::make_shared<HttpSession>( _config, std::move(socket), _server_di->di_scope()) ->run(); } do_accept(); } }
saltyan007/kill_test
simulation/navigator_gazebo/include/navigator_gazebo/navigator_thrusters.hpp
<reponame>saltyan007/kill_test #pragma once #include <mutex> #include <algorithm> #include <vector> #include <map> #include <cmath> #include "gazebo/common/Assert.hh" #include "gazebo/common/Events.hh" #include "gazebo/common/Event.hh" #include "gazebo/common/Plugin.hh" #include "gazebo/math/Vector3.hh" #include "gazebo/physics/physics.hh" #include "roboteq_msgs/Command.h" #include <ros/ros.h> namespace gazebo { struct Thruster { Thruster(){ } Thruster(std::string param_name) { std::vector<double> v_position; double v_effort_limit, v_effort_ratio, v_rotation; ros::param::get("/thrust_mapper/thruster_" + param_name + "_cog", v_position); ros::param::get("/thrust_mapper/thruster_" + param_name + "_theta", v_rotation); ros::param::get("/thrust_mapper/effort_ratio", v_effort_ratio); ros::param::get("/thrust_mapper/effort_limit", v_effort_limit); position = math::Vector3(v_position[0], v_position[1], 0); // Direction is give as rotation about the z axis. // This assumes that it's ONLY a 2d rotation about the z-axis. direction = math::Vector3(cos(v_rotation), sin(v_rotation), 0); ROS_INFO("%s position: %f, %f, %f", param_name.c_str(), position[0], position[1], position[2]); ROS_INFO("%s direction: %f, %f, %f", param_name.c_str(), direction[0], direction[1], direction[2]); effort_ratio = v_effort_ratio; effort_limit = v_effort_limit; } math::Vector3 position, direction; double effort_ratio, effort_limit; }; class ThrusterPlugin : public ModelPlugin { public: ThrusterPlugin(); virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf); virtual void Init(); void BLCallback(const roboteq_msgs::Command::ConstPtr &command); void BRCallback(const roboteq_msgs::Command::ConstPtr &command); void FLCallback(const roboteq_msgs::Command::ConstPtr &command); void FRCallback(const roboteq_msgs::Command::ConstPtr &command); protected: ros::NodeHandle nh; ros::Subscriber blSub; ros::Subscriber brSub; ros::Subscriber flSub; ros::Subscriber frSub; virtual void OnUpdate(); protected: std::mutex mtx; event::ConnectionPtr updateConnection; physics::ModelPtr model; physics::PhysicsEnginePtr physicsEngine; sdf::ElementPtr sdf; std::string layoutParam; physics::LinkPtr targetLink; ros::Time lastTime; std::vector<double> commands {0, 0, 0, 0}; std::vector<Thruster> thrusters; // BL, BR, FL, FR }; }
henryjtaylor/VoogaSalad
src/gameView/displayComponents/LevelComponent.java
<reponame>henryjtaylor/VoogaSalad<filename>src/gameView/displayComponents/LevelComponent.java package gameView.displayComponents; import javafx.beans.property.ReadOnlyIntegerProperty; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import javafx.scene.text.Font; import gameView.tools.DisplayEnum; import gamedata.IRestrictedGameData; public class LevelComponent extends UIDisplayComponent { private HBox myBox; private Label myLabel; private ReadOnlyIntegerProperty myLevel; public LevelComponent(String name, IRestrictedGameData gameData) { super(name, gameData); } @Override protected void changedValue() { setLabel(); } @Override public Region getDisplay() { if (myLevel == null) { return null; } return myBox; } @Override public DisplayEnum getPos() { return DisplayEnum.TOP_LEFT; } @Override protected void setID() { myLevel = (ReadOnlyIntegerProperty) setValue(getData().getLevel()); myLabel = new Label(); setLabel(); myBox = new HBox(myLabel); } private void setLabel() { myLabel.setText("Level: " + myLevel.doubleValue()); myLabel.setFont(new Font("Arial", 30)); } }
mandeepshetty/iotivity
service/protocol-plugin/lib/cpluff/libcpluff/psymbol.c
/*------------------------------------------------------------------------- * C-Pluff, a plug-in framework for C * Copyright 2007 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *-----------------------------------------------------------------------*/ /** @file * Dynamic plug-in symbols */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "../kazlib/hash.h" #include "cpluff.h" #include "defines.h" #include "internal.h" #include "util.h" /* ------------------------------------------------------------------------ * Data structures * ----------------------------------------------------------------------*/ /// Information about symbol providing plug-in typedef struct symbol_provider_info_t { // The providing plug-in cp_plugin_t *plugin; // Whether there is also an import dependency for the plug-in int imported; // Total symbol usage count int usage_count; } symbol_provider_info_t; /// Information about used symbol typedef struct symbol_info_t { // Symbol usage count int usage_count; // Information about providing plug-in symbol_provider_info_t *provider_info; } symbol_info_t; /* ------------------------------------------------------------------------ * Function definitions * ----------------------------------------------------------------------*/ CP_C_API cp_status_t cp_define_symbol(cp_context_t *context, const char *name, void *ptr) { cp_status_t status = CP_OK; CHECK_NOT_NULL(context); CHECK_NOT_NULL(name); // CHECK_NOT_NULL(ptr); if (context->plugin == NULL) { cpi_fatalf(_("Only plug-ins can define context specific symbols.")); } cpi_lock_context(context); cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER, __func__); do { char *n; // Create a symbol hash if necessary if (context->plugin->defined_symbols == NULL) { if ((context->plugin->defined_symbols = hash_create(HASHCOUNT_T_MAX, (int (*)(const void *, const void *)) strcmp, NULL)) == NULL) { status = CP_ERR_RESOURCE; break; } } // Check for a previously defined symbol if (hash_lookup(context->plugin->defined_symbols, name) != NULL) { status = CP_ERR_CONFLICT; break; } // Insert the symbol into the symbol hash n = strdup(name); if (n == NULL || !hash_alloc_insert(context->plugin->defined_symbols, n, ptr)) { free(n); status = CP_ERR_RESOURCE; break; } } while (0); // Report error if (status != CP_OK) { switch (status) { case CP_ERR_RESOURCE: cpi_errorf(context, N_("Plug-in %s could not define symbol %s due to insufficient memory."), context->plugin->plugin->identifier, name); break; case CP_ERR_CONFLICT: cpi_errorf(context, N_("Plug-in %s tried to redefine symbol %s."), context->plugin->plugin->identifier, name); break; default: break; } } cpi_unlock_context(context); return status; } CP_C_API void * cp_resolve_symbol(cp_context_t *context, const char *id, const char *name, cp_status_t *error) { cp_status_t status = CP_OK; int error_reported = 1; hnode_t *node; void *symbol = NULL; symbol_info_t *symbol_info = NULL; symbol_provider_info_t *provider_info = NULL; cp_plugin_t *pp = NULL; CHECK_NOT_NULL(context); CHECK_NOT_NULL(id); CHECK_NOT_NULL(name); // Resolve the symbol cpi_lock_context(context); cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER | CPI_CF_STOP, __func__); do { // Allocate space for symbol hashes, if necessary if (context->resolved_symbols == NULL) { context->resolved_symbols = hash_create(HASHCOUNT_T_MAX, cpi_comp_ptr, cpi_hashfunc_ptr); } if (context->symbol_providers == NULL) { context->symbol_providers = hash_create(HASHCOUNT_T_MAX, cpi_comp_ptr, cpi_hashfunc_ptr); } if (context->resolved_symbols == NULL || context->symbol_providers == NULL) { status = CP_ERR_RESOURCE; break; } // Look up the symbol defining plug-in node = hash_lookup(context->env->plugins, id); if (node == NULL) { cpi_warnf(context, N_("Symbol %s in unknown plug-in %s could not be resolved."), name, id); status = CP_ERR_UNKNOWN; break; } pp = hnode_get(node); // Make sure the plug-in has been started if ((status = cpi_start_plugin(context, pp)) != CP_OK) { cpi_errorf(context, N_("Symbol %s in plug-in %s could not be resolved because the plug-in could not be started."), name, id); error_reported = 1; break; } // Check for a context specific symbol if (pp->defined_symbols != NULL && (node = hash_lookup(pp->defined_symbols, name)) != NULL) { symbol = hnode_get(node); } // Fall back to global symbols, if necessary if (symbol == NULL && pp->runtime_lib != NULL) { symbol = DLSYM(pp->runtime_lib, name); } if (symbol == NULL) { const char *error = DLERROR(); if (error == NULL) { error = _("Unspecified error."); } cpi_warnf(context, N_("Symbol %s in plug-in %s could not be resolved: %s"), name, id, error); status = CP_ERR_UNKNOWN; break; } // Lookup or initialize symbol provider information if ((node = hash_lookup(context->symbol_providers, pp)) != NULL) { provider_info = hnode_get(node); } else { if ((provider_info = malloc(sizeof(symbol_provider_info_t))) == NULL) { status = CP_ERR_RESOURCE; break; } memset(provider_info, 0, sizeof(symbol_provider_info_t)); provider_info->plugin = pp; provider_info->imported = (context->plugin == NULL || cpi_ptrset_contains(context->plugin->imported, pp)); if (!hash_alloc_insert(context->symbol_providers, pp, provider_info)) { status = CP_ERR_RESOURCE; break; } } // Lookup or initialize symbol information if ((node = hash_lookup(context->resolved_symbols, symbol)) != NULL) { symbol_info = hnode_get(node); } else { if ((symbol_info = malloc(sizeof(symbol_info_t))) == NULL) { status = CP_ERR_RESOURCE; break; } memset(symbol_info, 0, sizeof(symbol_info_t)); symbol_info->provider_info = provider_info; if (!hash_alloc_insert(context->resolved_symbols, symbol, symbol_info)) { status = CP_ERR_RESOURCE; break; } } // Add dependencies (for plug-in) if (provider_info != NULL && !provider_info->imported && provider_info->usage_count == 0) { if (!cpi_ptrset_add(context->plugin->imported, pp)) { status = CP_ERR_RESOURCE; break; } if (!cpi_ptrset_add(pp->importing, context->plugin)) { cpi_ptrset_remove(context->plugin->imported, pp); status = CP_ERR_RESOURCE; break; } cpi_debugf(context, "A dynamic dependency was created from plug-in %s to plug-in %s.", context->plugin->plugin->identifier, pp->plugin->identifier); } // Increase usage counts symbol_info->usage_count++; provider_info->usage_count++; if (cpi_is_logged(context, CP_LOG_DEBUG)) { char owner[64]; /* TRANSLATORS: First %s is the context owner */ cpi_debugf(context, "%s resolved symbol %s defined by plug-in %s.", cpi_context_owner(context, owner, sizeof(owner)), name, id); } } while (0); // Clean up if (symbol_info != NULL && symbol_info->usage_count == 0) { if ((node = hash_lookup(context->resolved_symbols, symbol)) != NULL) { hash_delete_free(context->resolved_symbols, node); } free(symbol_info); } if (provider_info != NULL && provider_info->usage_count == 0) { if ((node = hash_lookup(context->symbol_providers, pp)) != NULL) { hash_delete_free(context->symbol_providers, node); } free(provider_info); } // Report insufficient memory error if (status == CP_ERR_RESOURCE && !error_reported) { cpi_errorf(context, N_("Symbol %s in plug-in %s could not be resolved due to insufficient memory."), name, id); } cpi_unlock_context(context); // Return error code if (error != NULL) { *error = status; } // Return symbol return symbol; } CP_C_API void cp_release_symbol(cp_context_t *context, const void *ptr) { hnode_t *node; symbol_info_t *symbol_info; symbol_provider_info_t *provider_info; CHECK_NOT_NULL(context); CHECK_NOT_NULL(ptr); cpi_lock_context(context); cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER, __func__); do { // Look up the symbol if ((node = hash_lookup(context->resolved_symbols, ptr)) == NULL) { cpi_errorf(context, N_("Could not release unknown symbol at address %p."), ptr); break; } symbol_info = hnode_get(node); provider_info = symbol_info->provider_info; // Decrease usage count assert(symbol_info->usage_count > 0); symbol_info->usage_count--; assert(provider_info->usage_count > 0); provider_info->usage_count--; // Check if the symbol is not being used anymore if (symbol_info->usage_count == 0) { hash_delete_free(context->resolved_symbols, node); free(symbol_info); if (cpi_is_logged(context, CP_LOG_DEBUG)) { char owner[64]; /* TRANSLATORS: First %s is the context owner */ cpi_debugf(context, _("%s released the symbol at address %p defined by plug-in %s."), cpi_context_owner(context, owner, sizeof(owner)), ptr, provider_info->plugin->plugin->identifier); } } // Check if the symbol providing plug-in is not being used anymore if (provider_info->usage_count == 0) { node = hash_lookup(context->symbol_providers, provider_info->plugin); assert(node != NULL); hash_delete_free(context->symbol_providers, node); if (!provider_info->imported) { cpi_ptrset_remove(context->plugin->imported, provider_info->plugin); cpi_ptrset_remove(provider_info->plugin->importing, context->plugin); cpi_debugf(context, _("A dynamic dependency from plug-in %s to plug-in %s was removed."), context->plugin->plugin->identifier, provider_info->plugin->plugin->identifier); } free(provider_info); } } while (0); cpi_unlock_context(context); }
dlatikaynen/blooDot
src/sound/orchester/Pipeline.h
<filename>src/sound/orchester/Pipeline.h #pragma once #include "OrchestratorException.h" #include "OrchestratorBase.h" #include "AudioFrames.h" #include <vector> #include <algorithm> #include <cmath> namespace blooDot { namespace Orchestrator { class Pipeline : public OrchestratorBase { public: Pipeline(void); unsigned int GetChannelsIn(void) const; unsigned int GetChannelsOut(void) const; virtual void Reset(void); void SetGain(double gain); double GetGain(void) const; double GetPhaseDelay(double frequency); const AudioFrames& GetLastFrame(void) const; virtual AudioFrames& Render(AudioFrames& frames, unsigned int channel = 0) = 0; protected: unsigned int m_channelsIn; double m_Gain; AudioFrames m_lastFrame; AudioFrames m_Inputs; AudioFrames m_Outputs; std::vector<double> m_pipelineA; std::vector<double> m_pipelineB; }; } }
youngdaLee/Baekjoon
src/11/11966.py
""" 11966. 2의 제곱인가? 작성자: xCrypt0r 언어: Python 3 사용 메모리: 29,380 KB 소요 시간: 76 ms 해결 날짜: 2020년 9월 23일 """ def main(): a = [2 ** x for x in range(31)] N = int(input()) print(1 if N in a else 0) if __name__ == '__main__': main()
JadielTeofilo/General-Algorithms
src/interviewbit/backtracking/combinations.py
<gh_stars>0 """ Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n. Make sure the combinations are sorted. To elaborate, Within every entry, elements should be sorted. [1, 4] is a valid entry while [4, 1] is not. Entries should be sorted within themselves. Example : If n = 4 and k = 2, a solution is: [ [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], ] In - number: int, size: int Out - List[List[int]] [1 2 3 4] solve(size: int, current: List[int]) stops when the size is zero _ 1 _ 2 _ 2 _ X 3 _ 3 _ 3 _ X X 4 _ X """ from typing import List class Solution: # @param A : integer # @param B : integer # @return a list of list of integers def combine(self, number:int, size: int) -> List[List[int]]: self.result: List[List[int]] = [] self.update_result(size, start=1, end=number+1, current=[]) self.result.sort() return self.result def update_result(self, size: int, start: int, end: int, current: List[int]) -> None: if size == 0: current.sort() self.result.append(current) for num in range(start, end): self.update_result(size - 1, num + 1, end, current + [num])
kjlubick/bazel
third_party/java/proguard/proguard6.2.2/src/proguard/io/ZipOutput.java
<reponame>kjlubick/bazel<gh_stars>1000+ /* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2019 Guardsquare NV * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.io; import proguard.util.StringUtil; import java.io.*; import java.util.*; import java.util.zip.*; /** * This class writes zip data to a given output stream. It returns a new * output stream for each zip entry that is opened. An entry can be compressed * or uncompressed. Uncompressed entries can be aligned to a multiple of a * given number of bytes. * * Multiple entries and output streams can be open at the same time. The entries * are added to the central directory in the order in which they are opened, but * the corresponding data are only written when their output streams are closed. * * The code automatically computes the CRC and lengths of the data, for * compressed and uncompressed data. * * @author <NAME> */ public class ZipOutput { private static final int MAGIC_LOCAL_FILE_HEADER = 0x04034b50; private static final int MAGIC_CENTRAL_DIRECTORY_FILE_HEADER = 0x02014b50; private static final int MAGIC_END_OF_CENTRAL_DIRECTORY = 0x06054b50; private static final int VERSION = 10; private static final int GENERAL_PURPOSE_FLAG = 0; private static final int METHOD_UNCOMPRESSED = 0; private static final int METHOD_COMPRESSED = 8; private static final boolean DEBUG = false; private DataOutputStream outputStream; private final int uncompressedAlignment; private final String comment; private List zipEntries = new ArrayList(); private Set zipEntryNames = new HashSet(); private long centralDirectoryOffset; /** * Creates a new ZipOutput. * @param outputStream the output stream to which the zip data will be * written. */ public ZipOutput(OutputStream outputStream) throws IOException { this(outputStream, null, null, 1); } /** * Creates a new ZipOutput that aligns uncompressed entries. * @param outputStream the output stream to which the zip data will * be written. * @param header an optional header for the jar file. * @param comment optional comment for the entire zip file. * @param uncompressedAlignment the requested alignment of uncompressed data. */ public ZipOutput(OutputStream outputStream, byte[] header, String comment, int uncompressedAlignment) throws IOException { this.outputStream = new DataOutputStream(outputStream); this.comment = comment; this.uncompressedAlignment = uncompressedAlignment; if (header != null) { outputStream.write(header); } } /** * Creates a new zip entry, returning an output stream to write its data. * It is the caller's responsibility to close the output stream. * @param name the name of the zip entry. * @param compress specifies whether the entry should be compressed. * @param modificationTime the modification date and time of the zip entry, * in DOS format. * @return an output stream for writing the data of the * zip entry. */ public OutputStream createOutputStream(String name, boolean compress, int modificationTime) throws IOException { return createOutputStream(name, compress, modificationTime, null, null); } /** * Creates a new zip entry, returning an output stream to write its data. * It is the caller's responsibility to close the output stream. * @param name the name of the zip entry. * @param compress specifies whether the entry should be compressed. * @param modificationTime the modification date and time of the zip entry, * in DOS format. * @param extraField optional extra field data. These should contain * chunks, each with a short ID, a short length * (little endian), and their corresponding data. * The IDs 0-31 are reserved for Pkware. * Java's jar tool just specifies an ID 0xcafe on * its first entry. * @param comment optional comment. * @return an output stream for writing the data of the * zip entry. */ public OutputStream createOutputStream(String name, boolean compress, int modificationTime, byte[] extraField, String comment) throws IOException { // Check if the name hasn't been used yet. if (!zipEntryNames.add(name)) { throw new IOException("Duplicate jar entry ["+name+"]"); } ZipEntry entry = new ZipEntry(name, compress, modificationTime, extraField, comment); // Add the entry to the list that will be put in the central directory. zipEntries.add(entry); return entry.createOutputStream(); } /** * Closes the zip archive, also closing the underlying output stream. */ public void close() throws IOException { // Write the central directory. writeStartOfCentralDirectory(); for (int index = 0; index < zipEntries.size(); index++) { ZipEntry entry = (ZipEntry)zipEntries.get(index); entry.writeCentralDirectoryFileHeader(); } writeEndOfCentralDirectory(); // Close the underlying output stream. outputStream.close(); // Make sure the archive can't be used any further. outputStream = null; zipEntries = null; zipEntryNames = null; } /** * Starts the central directory. */ private void writeStartOfCentralDirectory() { // The central directory as such doesn't have a header. centralDirectoryOffset = outputStream.size(); } /** * Ends the central directory. */ private void writeEndOfCentralDirectory() throws IOException { if (DEBUG) { System.out.println("ZipOutput.writeEndOfCentralDirectory ("+zipEntries.size()+" entries)"); } // The size of the central directory, not counting this trailer. long centralDirectorySize = outputStream.size() - centralDirectoryOffset; writeInt(MAGIC_END_OF_CENTRAL_DIRECTORY); writeShort(0); // Number of this disk. writeShort(0); // Number of disk with central directory. writeShort(zipEntries.size()); // Number of records on this disk. writeShort(zipEntries.size()); // Total number of records. writeInt(centralDirectorySize); // Size of central directory, in bytes. writeInt(centralDirectoryOffset); // Offset of central directory. if (comment == null) { // No comment. writeShort(0); } else { // Comment length and comment. byte[] commentBytes = StringUtil.getUtf8Bytes(comment); writeShort(commentBytes.length); outputStream.write(commentBytes); } } /** * This class represents a zip entry in its enclosing zip file. It can * provide an output stream and write its headers and its data to the main * zip output stream. In fact, it automatically writes its local header and * data when the output stream is closed. */ private class ZipEntry { private boolean compressed; private int modificationTime; private int crc; private long compressedSize; private long uncompressedSize; private long offset; private String name; private byte[] extraField; private String comment; /** * Creates a new zip entry, returning output stream to write its data. * It is the caller's responsibility to close the output stream. * @param name the name of the zip entry. * @param compressed specifies whether the entry should be * compressed. * @param modificationTime the modification date and time of the zip * entry, in DOS format. * @param extraField optional extra field data. These should * contain chunks, each with a short ID, a short * length (little endian), and their * corresponding data. The IDs 0-31 are reserved * for Pkware. Java's jar tool just specifies an * ID 0xcafe on its first entry. * @param comment optional comment. * @return an output stream for writing the zip data. */ private ZipEntry(String name, boolean compressed, int modificationTime, byte[] extraField, String comment) { this.name = name; this.compressed = compressed; this.modificationTime = modificationTime; this.extraField = extraField; this.comment = comment; } public OutputStream createOutputStream() throws IOException { return compressed ? (OutputStream)new CompressedZipEntryOutputStream() : (OutputStream)new UncompressedZipEntryOutputStream(); } /** * Writes the local file header, which precedes the data, to the main * zip output stream. */ private void writeLocalFileHeader() throws IOException { if (DEBUG) { System.out.println("ZipOutput.writeLocalFileHeader ["+name+"] (compressed = "+compressed+", offset = "+offset+", "+compressedSize+"/"+uncompressedSize+" bytes)"); } writeInt(MAGIC_LOCAL_FILE_HEADER); writeShort(VERSION); writeShort(GENERAL_PURPOSE_FLAG); writeShort(compressed ? METHOD_COMPRESSED : METHOD_UNCOMPRESSED); writeInt(modificationTime); writeInt(crc); writeInt(compressedSize); writeInt(uncompressedSize); byte[] nameBytes = StringUtil.getUtf8Bytes(name); int nameLength = nameBytes.length; int extraFieldLength = extraField == null ? 0 : extraField.length; writeShort(nameLength); writeShort(extraFieldLength); outputStream.write(nameBytes); if (extraField != null) { outputStream.write(extraField); } } /** * Writes the file header for the central directory to the main zip * output stream. */ public void writeCentralDirectoryFileHeader() throws IOException { if (DEBUG) { System.out.println("ZipOutput.writeCentralDirectoryFileHeader ["+name+"] (compressed = "+compressed+", offset = "+offset+", "+compressedSize+"/"+uncompressedSize+" bytes)"); } writeInt(MAGIC_CENTRAL_DIRECTORY_FILE_HEADER); writeShort(VERSION); // Creation version. writeShort(VERSION); // Extraction Version. writeShort(GENERAL_PURPOSE_FLAG); writeShort(compressed ? METHOD_COMPRESSED : METHOD_UNCOMPRESSED); writeInt(modificationTime); writeInt(crc); writeInt(compressedSize); writeInt(uncompressedSize); byte[] nameBytes = StringUtil.getUtf8Bytes(name); byte[] commentBytes = comment == null ? null : StringUtil.getUtf8Bytes(comment); writeShort(nameBytes.length); writeShort(extraField == null ? 0 : extraField.length); writeShort(commentBytes == null ? 0 : commentBytes.length); writeShort(0); // Disk number of file start. writeShort(0); // Internal file attributes. writeInt(0); // External file attributes. writeInt(offset); outputStream.write(nameBytes); if (extraField != null) { outputStream.write(extraField); } if (commentBytes != null) { outputStream.write(commentBytes); } } /** * This OutputStream writes its uncompressed zip entry out to its zip * output stream when it is closed. */ private class UncompressedZipEntryOutputStream extends ByteArrayOutputStream { private CRC32 crc32 = new CRC32(); private UncompressedZipEntryOutputStream() { super(16 * 1024); } // Overridden methods for OutputStream. public void write(int b) { super.write(b); crc32.update(b); } //public void write(byte[] b) throws IOException //{ // // The super implementation delegates to the method below. // super.write(b); //} public void write(byte[] b, int off, int len) { super.write(b, off, len); crc32.update(b, off, len); } public void close() throws IOException { super.close(); byte[] bytes = super.toByteArray(); offset = outputStream.size(); crc = (int)crc32.getValue(); compressedSize = bytes.length; uncompressedSize = bytes.length; writeLocalFileHeader(); outputStream.write(bytes); } } /** * This OutputStream writes its compressed zip entry out to its zip * output stream when it is closed. */ private class CompressedZipEntryOutputStream extends DeflaterOutputStream { private CRC32 crc32 = new CRC32(); private CompressedZipEntryOutputStream() { super(new ByteArrayOutputStream(16 * 1024), new Deflater(Deflater.BEST_COMPRESSION, true), 1024); } // Overridden methods for OutputStream. //public void write(int b) throws IOException //{ // // The super implementation delegates to the method below. // super.write(b); //} // // //public void write(byte[] b) throws IOException //{ // // The super implementation delegates to the method below. // super.write(b); //} public void write(byte[] b, int off, int len) throws IOException { super.write(b, off, len); crc32.update(b, off, len); uncompressedSize += len; } public void close() throws IOException { // Make sure the memory is freed. [JDK-4797189] super.finish(); super.def.end(); super.close(); ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream)super.out; byte[] compressedBytes = byteArrayOutputStream.toByteArray(); offset = outputStream.size(); crc = (int)crc32.getValue(); compressedSize = compressedBytes.length; writeLocalFileHeader(); outputStream.write(compressedBytes); } } } // Small utility methods. /** * Writes out a little-endian short value to the zip output stream. */ private void writeShort(int value) throws IOException { outputStream.write(value); outputStream.write(value >>> 8); } /** * Writes out a little-endian int value to the zip output stream. */ private void writeInt(int value) throws IOException { outputStream.write(value); outputStream.write(value >>> 8); outputStream.write(value >>> 16); outputStream.write(value >>> 24); } /** * Writes out a little-endian int value to the zip output stream. */ private void writeInt(long value) throws IOException { outputStream.write((int)value); outputStream.write((int)(value >>> 8)); outputStream.write((int)(value >>> 16)); outputStream.write((int)(value >>> 24)); } /** * Provides a simple test for this class, creating a zip file with the * given name and a few aligned/compressed/uncompressed zip entries. */ public static void main(String[] args) { try { ZipOutput output = new ZipOutput(new FileOutputStream(args[0]), null, "Main file comment", 4); PrintWriter printWriter1 = new PrintWriter(output.createOutputStream("file1.txt", false, 0, new byte[] { 0x34, 0x12, 4, 0, 0x48, 0x65, 0x6c, 0x6c, 0x6f }, "Comment")); printWriter1.println("This is file 1."); printWriter1.println("Hello, world!"); printWriter1.close(); PrintWriter printWriter2 = new PrintWriter(output.createOutputStream("file2.txt", true, 0, null, "Another comment")); printWriter2.println("This is file 2."); printWriter2.println("Hello, world!"); printWriter2.close(); PrintWriter printWriter3 = new PrintWriter(output.createOutputStream("file3.txt", false, 0, null, "Last comment")); printWriter3.println("This is file 3."); printWriter3.println("Hello, world!"); printWriter3.close(); output.close(); } catch (IOException e) { e.printStackTrace(); } } }
oxtra/oxtra
src/oxtra/codegen/instructions/control-flow/conditional-jumps/jno.h
#ifndef OXTRA_JNO_H #define OXTRA_JNO_H namespace codegen { class Jno : public Jcc { public: explicit Jno(const fadec::Instruction& inst) : Jcc{inst, flags::overflow} {} void generate(CodeBatch& batch) const final; }; } #endif //OXTRA_JNO_H
liming1010/sql4j
core/src/main/java/com/tpy/core/manager/UpdateManager.java
<reponame>liming1010/sql4j package com.tpy.core.manager; public interface UpdateManager<T> { UpdateFun1Manager update(T t1); UpdateFun4Manager updateById(T t); /** * 逻辑删除 * @param t * @return */ UpdateFun1Manager delByLogic(T t); /** * 根据PrimaryKkey删除 * @param t * @return */ UpdateFun4Manager delByLogicByPrimaryKkey(T t); /** * 物理删除,删除了没有了 * @param t * @return */ UpdateFun1Manager delByPhysics(T t); /** * 物理删除,删除了没有了 * @param t * @return */ UpdateFun4Manager delPhysicsByPrimaryKkey(T t); }
FairyEver/WebBasicCommonDemos
书籍学习源码练习/Head First Javascript学习代码/chapter10/youcube/youcube.js
<gh_stars>100-1000 //Date类扩展一个类方法 Date.prototype.shortFormat = function() { return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear(); }; //Blog类的初始化方法 function Blog (body, date, image) { this.body = body; this.date = date; this.image = image; } //Blog类的实例方法,所有实例对象都只有这么一份 Blog.prototype.toString = function(){ return "[" + this.date.shortFormat() + "]" + this.body; }; Blog.prototype.toHTML = function(highlight) { var blogHTML = ""; blogHTML += highlight ? "<p style='background-color:#EEEEEE'>" : "<p>"; //blog对象是否有image元素 if (this.image) { blogHTML += "<strong>" + this.date.shortFormat() + "</strong><br /><table><tr><td><img src='" + this.image + "'/></td><td style='vertical-align:top'>" + this.body + "</td></tr></table><em>" + this.signature + "</em></p>"; } else { blogHTML += "<strong>" + this.date.shortFormat() + "</strong><br />" + this.body + "<br /><em>" + this.signature + "</em></p>"; } return blogHTML; }; Blog.prototype.containsText = function(text){ return (this.body.toLowerCase().indexOf(text.toLowerCase()) != -1); }; //添加一个类属性,所有的Blog对象分享一份。 Blog.prototype.signature = "签名:黄成都你还"; //类方法。这个方法只有Blog类可以调用。Blog类的对象也不可以调用,而且不能访问Blog的成员属性 Blog.blogSorter = function(blog1, blog2){ return blog2.date - blog1.date; }; var blog = [ new Blog("Got the new cube I ordered. It's a real pearl.", new Date("08/14/2008")), new Blog("Solved the new cube but of course, now I'm bored and shopping for a new one.", new Date("08/19/2008")), new Blog("Managed to get a headache toiling over the new cube. Gotta nap.", new Date("08/16/2008")), new Blog("Found a 7x7x7 cube for sale online. Yikes! That one could be a beast.", new Date("08/21/2008")), new Blog("Met up with some fellow cubers to discuss the prospect of a 7x7x7 cube. Mixed feelings.", new Date("08/29/2008")), new Blog("Went ahead and ordered the scary 7x7x7 cube. Starting a mental exercise regimen to prepare.", new Date("09/01/2008")), new Blog("Attended a rally outside of a local toy store that stopped carrying cube puzzles. Power to the puzzlers!", new Date("09/03/2008")), new Blog("Got the new 7x7x7 cube. Could be my last blog post for a while...", new Date("09/05/2008")), new Blog("Wow, it took me a couple of weeks but the new cube is finally solved!", new Date("09/19/2008"), "cube777.png") ]; // Show the list of blog entries function showBlog(numEntries) { // First sort the blog blog.sort(Blog.blogSorter); // Adjust the number of entries to show the full blog, if necessary if (!numEntries) numEntries = blog.length; // Show the blog entries var i = 0, blogListHTML = ""; while (i < blog.length && i < numEntries) { blogListHTML += blog[i].toHTML(i % 2 == 0); i++; } // Set the blog HTML code on the page document.getElementById("blog").innerHTML = blogListHTML; } // Search the list of blog entries for a piece of text function searchBlog() { var searchText = document.getElementById("searchtext").value; for (var i = 0; i < blog.length; i++) { // See if the blog entry contains the search text if (blog[i].containsText(searchText)) { alert(blog[i]); break; } } // If the search text wasn't found, display a message if (i == blog.length) alert("Sorry, there are no blog entries containing the search text."); } // Display a randomly chosen blog entry function randomBlog() { // Pick a random number between 0 and blog.length - 1 var i = Math.floor(Math.random() * blog.length); alert(blog[i]); }
phpmob/chang-admin
src/PhpMob/ChangMinBundle/Resources/private/js/lib/vsubmit.js
(function (factory) { "use strict"; if (typeof define === "function" && define.amd) { define(["jquery"], factory); } else { /* jshint sub:true */ factory(jQuery); } })(function ($) { "use strict"; $.fn.vsubmit = function (options) { var defaults = { debug: true, errorClass: 'has-error', validClass: 'success', errorElement: "span", // add error class highlight: function (element, errorClass, validClass) { $(element).parents("div.form-group") .addClass(errorClass) .removeClass(validClass); }, // add error class unhighlight: function (element, errorClass, validClass) { $(element).parents(".has-error") .removeClass(errorClass) .addClass(validClass); }, // submit handler submitHandler: function (form) { form.submit(); }, invalidHandler: function (form) { $(form).animate('shake'); } }; $(this).validate($.extend(defaults, options)); return this; }; });
addison-howenstine/cell-society
src/xml/SchellingSimulationFactory.java
package xml; import java.util.Collection; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import cell.GridPosition; import grid.Parameters; import schelling.SLParameters; /** * * @author Brian * Generate Schelling parameters based on XML File of Simulation Type "Schelling". Depending on format * of the XML file, can either initialize cells randomly based on parameters or can specify exact condition * of each cell; returns an instance of SLParameters */ public class SchellingSimulationFactory extends SimulationFactory { public SchellingSimulationFactory(Element rootElement) { super(rootElement); } @Override public Parameters createParameters (Parameters basicParams, NodeList listOfNodes) { double idealRatio = getDoubleValue("idealRatio"); double redBlueRatio = getDoubleValue("redBlueRatio"); double emptyRatio = getDoubleValue("emptyRatio"); Collection<GridPosition> listOfRed = createListOfLocations("X", listOfNodes); Collection<GridPosition> listOfBlue = createListOfLocations("O", listOfNodes); Collection<GridPosition> listOfEmpty = createListOfLocations("Vacant", listOfNodes); if (listOfRed.size() > 0 | listOfBlue.size() > 0 | listOfEmpty.size() > 0){ return new SLParameters(basicParams, idealRatio, listOfRed, listOfBlue, listOfEmpty); } return new SLParameters(basicParams, idealRatio, redBlueRatio, emptyRatio); } }
ganorberg/algorithms-javascript
math/number-base-conversion/dec-to-bin.js
<reponame>ganorberg/algorithms-javascript // Using native method function decToBin(dec) { return dec.toString(2); } // Manually function decToBin(dec) { if (dec == 0) { return '0'; } let bin = ''; let quotient = dec; // Each digit in binary represents remainder when divided by 2 (built right to left) while (quotient > 0) { const remainder = quotient % 2; bin = String(remainder) + bin; quotient = Math.floor(quotient / 2); } return bin; } // ALTERNATE SOLUTION // function decToBin(dec) { // let bin = ''; // let value = dec; // // grab exponent of 2 that exceeds our value // let exponent = 0; // while (true) { // if (2 ** ++exponent >= dec) { break; } // } // // chop off largest power of 2 until exponent decrements to 0 // while (exponent >= 0) { // let raised = 2 ** exponent; // if (value >= raised) { // bin += '1'; // value -= raised; // // only append zeros // } else if (bin[0] === '1' || exponent === 0) { // bin += '0'; // } // exponent--; // } // return bin; // } console.log('0', decToBin(0)); console.log('11', decToBin(3)); console.log('100', decToBin(4)); console.log('101', decToBin(5)); console.log('1010', decToBin(10)); console.log('1000000', decToBin(64));
wenyuanyu/GraphScope
interactive_engine/src/api/sdk-common/src/main/generated/com/alibaba/maxgraph/proto/MetricInfoRespOrBuilder.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: sdk/common.proto package com.alibaba.maxgraph.proto; public interface MetricInfoRespOrBuilder extends // @@protoc_insertion_point(interface_extends:MetricInfoResp) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .ServerMetricValue values = 1;</code> */ java.util.List<com.alibaba.maxgraph.proto.ServerMetricValue> getValuesList(); /** * <code>repeated .ServerMetricValue values = 1;</code> */ com.alibaba.maxgraph.proto.ServerMetricValue getValues(int index); /** * <code>repeated .ServerMetricValue values = 1;</code> */ int getValuesCount(); /** * <code>repeated .ServerMetricValue values = 1;</code> */ java.util.List<? extends com.alibaba.maxgraph.proto.ServerMetricValueOrBuilder> getValuesOrBuilderList(); /** * <code>repeated .ServerMetricValue values = 1;</code> */ com.alibaba.maxgraph.proto.ServerMetricValueOrBuilder getValuesOrBuilder( int index); /** * <code>optional .Response resp = 2;</code> */ boolean hasResp(); /** * <code>optional .Response resp = 2;</code> */ com.alibaba.maxgraph.proto.Response getResp(); /** * <code>optional .Response resp = 2;</code> */ com.alibaba.maxgraph.proto.ResponseOrBuilder getRespOrBuilder(); }
yitongxue/xinxintong
views/default/pl/fe/matter/group/plan-loader.js
var timestamp, minutes; timestamp = new Date(); minutes = timestamp.getMinutes(); minutes = Math.floor(minutes / 5) * 5; timestamp.setMinutes(minutes); timestamp.setMilliseconds(0); timestamp.setSeconds(0); require.config({ waitSeconds: 0, paths: { "domReady": '/static/js/domReady', "frame": '/views/default/pl/fe/matter/group/plan', }, urlArgs: function(id, url) { if (/domReady/.test(id)) { return ''; } return "?bust=" + (timestamp * 1); } }); require(['frame']);
medismailben/llvm-project
clang/test/Modules/Inputs/merge-anon-in-template/c.h
<reponame>medismailben/llvm-project<filename>clang/test/Modules/Inputs/merge-anon-in-template/c.h<gh_stars>1000+ template<typename T> struct is_floating { enum { value = 0 }; typedef int type; }; #include "b.h" bool n20 = is_floating<int>::value;
scastiel/livre-react-exemples
05-composants-reutilisables/02-hoc/src/App.js
import React, { Component } from 'react' import PhoneNumberInput from './PhoneNumberInput' class App extends Component { constructor(props) { super(props) this.state = { phoneNumber: '' } } onChange = event => { this.setState({ phoneNumber: event.target.value }) } render() { return ( <div> <PhoneNumberInput value={this.state.phoneNumber} onChange={this.onChange} style={{ padding: 5, fontSize: 'large' }} /> <br /> <code>{JSON.stringify(this.state)}</code> </div> ) } } export default App
schmurgon/serenity-core
serenity-core/src/main/java/net/thucydides/core/webdriver/stubs/WebElementFacadeStub.java
package net.thucydides.core.webdriver.stubs; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.gson.Gson; import net.serenitybdd.core.pages.WebElementFacade; import net.serenitybdd.core.pages.WebElementState; import net.serenitybdd.core.time.InternalSystemClock; import net.thucydides.core.webdriver.javascript.JavascriptExecutorFacade; import org.openqa.selenium.*; import org.openqa.selenium.interactions.internal.Coordinates; import org.openqa.selenium.support.ui.Duration; import org.openqa.selenium.support.ui.Wait; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class WebElementFacadeStub implements WebElementFacade { protected WebElement getElement() { return this; } protected JavascriptExecutorFacade getJavascriptExecutorFacade() { return new JavascriptExecutorFacade() { @Override protected Gson getGson() { return null; } @Override public void registerTypeAdapter(Type type, Object typeAdapter) { } @Override public Object executeScript(String script) { return null; } @Override public Object executeScript(String script, Object... params) { return null; } @Override public <T> T deserializeScriptResultAs(Class<T> classOfT, String script, Map<String, Object> injectedFields, Object... params) throws IllegalAccessException { return null; } @Override public <T> T deserializeScriptResultAs(Class<T> classOfT, String script, Object... params) throws IllegalAccessException { return null; } @Override public <T> List<T> deserializeScriptResultAsListOf(String script, Object... params) { return null; } }; } protected InternalSystemClock getClock() { return new InternalSystemClock(); } @Override public WebElementFacade then(String xpathOrCssSelector) { return this; } @Override public WebElementFacade findBy(String xpathOrCssSelector) { return this; } @Override public List<WebElementFacade> thenFindAll(String xpathOrCssSelector) { return Lists.newArrayList(); } private List<WebElementFacade> webElementFacadesFrom(List<WebElement> nestedElements) { return Lists.newArrayList(); } @Override public WebElementFacade findBy(By selector) { return this; } @Override public WebElementFacade find(By bySelector) { return this; } @Override public WebElementFacade then(By bySelector) { return this; } @Override public String getAttribute(String name) { return ""; } @Override public List<WebElementFacade> thenFindAll(By selector) { return Lists.newArrayList(); } @Override public long getImplicitTimeoutInMilliseconds() { return 0; } @Override public WebElementFacade withTimeoutOf(int timeout, TimeUnit unit) { return this; } /** * Is this web element present and visible on the screen * This method will not throw an exception if the element is not on the screen at all. * If the element is not visible, the method will wait a bit to see if it appears later on. */ @Override public boolean isVisible() { return false; } /** * Convenience method to chain method calls more fluently. */ @Override public WebElementFacade and() { return this; } /** * Convenience method to chain method calls more fluently. */ @Override public WebElementFacade then() { return this; } /** * Is this web element present and visible on the screen * This method will not throw an exception if the element is not on the screen at all. * The method will fail immediately if the element is not visible on the screen. * There is a little black magic going on here - the web element class will detect if it is being called * by a method called "isCurrently*" and, if so, fail immediately without waiting as it would normally do. */ @Override public boolean isCurrentlyVisible() { return false; } @Override public boolean isCurrentlyEnabled() { return false; } /** * Checks whether a web element is visible. * Throws an AssertionError if the element is not rendered. */ @Override public void shouldBeVisible() { } /** * Checks whether a web element is visible. * Throws an AssertionError if the element is not rendered. */ @Override public void shouldBeCurrentlyVisible() { } /** * Checks whether a web element is not visible. * Throws an AssertionError if the element is not rendered. */ @Override public void shouldNotBeVisible() { } /** * Checks whether a web element is not visible straight away. * Throws an AssertionError if the element is not rendered. */ @Override public void shouldNotBeCurrentlyVisible() { } /** * Does this element currently have the focus. */ @Override public boolean hasFocus() { return false; } /** * Does this element contain a given text? */ @Override public boolean containsText(final String value) { return false; } /** * Does this element exactly match given text? */ @Override public boolean containsOnlyText(final String value) { return false; } /** * Does this dropdown contain the specified value. */ @Override public boolean containsSelectOption(final String value) { return false; } @Override public List<String> getSelectOptions() { return Lists.newArrayList(); } /** * Check that an element contains a text value * * @param textValue */ @Override public void shouldContainText(String textValue) { } /** * Check that an element exactly matches a text value * * @param textValue */ @Override public void shouldContainOnlyText(String textValue) { } @Override public void shouldContainSelectedOption(String textValue) { } /** * Check that an element does not contain a text value * * @param textValue */ @Override public void shouldNotContainText(String textValue) { } @Override public void shouldBeEnabled() { } @Override public boolean isEnabled() { return false; } @Override public void shouldNotBeEnabled() { } /** * Type a value into a field, making sure that the field is empty first. * * @param value */ @Override public WebElementFacade type(final String value) { return this; } /** * Type a value into a field and then press Enter, making sure that the field is empty first. * * @param value */ @Override public WebElementFacade typeAndEnter(final String value) { return this; } /** * Type a value into a field and then press TAB, making sure that the field is empty first. * This currently is not supported by all browsers, notably Firefox. * * @param value */ @Override public WebElementFacade typeAndTab(final String value) { return this; } @Override public void setWindowFocus() { } @Override public WebElementFacade selectByVisibleText(final String label) { return this; } @Override public String getSelectedVisibleTextValue() { return ""; } @Override public WebElementFacade selectByValue(String value) { return this; } @Override public String getSelectedValue() { return ""; } @Override public WebElementFacade selectByIndex(int indexValue) { return this; } private void waitUntilElementAvailable() { } private boolean driverIsDisabled() { return false; } public boolean isPresent() { return false; } @Override public void shouldBePresent() { } @Override public void shouldNotBePresent() { } @Override public WebElementFacade waitUntilVisible() { return this; } @Override public WebElementFacade waitUntilPresent() { return this; } @Override public Wait<WebDriver> waitForCondition() { return new Wait<WebDriver>() { @Override public <T> T until(Function<? super WebDriver, T> function) { return null; } }; } @Override public WebElementFacade waitUntilNotVisible() { return this; } @Override public String getValue() { return null; } @Override public boolean isSelected() { return false; } @Override public String getText() { return ""; } @Override public <T extends WebElementFacade> T waitUntilClickable() { return null; } @Override public WebElementFacade waitUntilEnabled() { return this; } @Override public WebElementFacade waitUntilDisabled() { return this; } @Override public String getTextValue() { return ""; } @Override public WebElementState expect(String errorMessage) { return this; } protected WebElementState expectingErrorMessage(String errorMessage) { return this; } /** * Wait for an element to be visible and enabled, and then click on it. */ @Override public void click() { } @Override public void clear() { } @Override public String toString() { return ""; } public void submit() { } public void sendKeys(CharSequence... keysToSend) { } public String getTagName() { return ""; } public List<WebElement> findElements(By by) { return Lists.newArrayList(); } public WebElement findElement(By by) { return this; } public boolean isDisplayed() { return false; } public Point getLocation() { return new Point(0, 0); } public Dimension getSize() { return new Dimension(0, 0); } public String getCssValue(String propertyName) { return ""; } public WebElement getWrappedElement() { return this; } @Override public Coordinates getCoordinates() { return new Coordinates() { @Override public Point onScreen() { return new Point(0, 0); } @Override public Point inViewPort() { return new Point(0, 0); } @Override public Point onPage() { return new Point(0, 0); } @Override public Object getAuxiliary() { return new Point(0, 0); } }; } @Override public WebElement findElementByAccessibilityId(String using) { return this; } @Override public List<WebElement> findElementsByAccessibilityId(String using) { return Lists.newArrayList(); } @Override public WebElement findElementByAndroidUIAutomator(String using) { return this; } @Override public List<WebElement> findElementsByAndroidUIAutomator(String using) { return Lists.newArrayList(); } @Override public WebElement findElementByIosUIAutomation(String using) { return this; } @Override public List<WebElement> findElementsByIosUIAutomation(String using) { return Lists.newArrayList(); } @Override public void setImplicitTimeout(Duration implicitTimeout) { } @Override public Duration getCurrentImplicitTimeout() { return null; } @Override public void resetTimeouts() { } @Override public boolean containsElements(By selector) { return false; } @Override public boolean containsElements(String xpathOrCssSelector) { return false; } @Override public void shouldContainElements(By selector) { } @Override public void shouldContainElements(String xpathOrCssSelector) { } @Override public boolean hasClass(String cssClassName) { return false; } @Override public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException { return null; } }
DevelopByTarun/TODAY-HELP
MONGO-DB/chapter2/chp2.2-2.4_code.js
<reponame>DevelopByTarun/TODAY-HELP<gh_stars>0 // *********** 2.2.2 Indexing and Explain ****************************8 db.numbers.find({num: {"$gt": 199995}}).explain() /* results like: { "cursor" : "BasicCursor", "isMultiKey" : false, "n" : 4, // result documents returned "nscannedObjects" : 200000, "nscanned" : 200000, "nscannedObjectsAllPlans" : 200000, "nscannedAllPlans" : 200000, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 171, // time the query took "indexBounds" : { }, "server" : "hostname:27017" } */ // create index db.numbers.ensureIndex({num: 1}) // verify index db.numbers.getIndexes() // explain for indexed collection db.numbers.find({num: {"$gt": 199995 }}).explain() /* results like: { "cursor" : "BtreeCursor num_1", #A// using the num_1 index "isMultiKey" : false, "n" : 4, #B// 4 documents returned "nscannedObjects" : 4, "nscanned" : 4, #C// only 4 documents scanned "nscannedObjectsAllPlans" : 4, "nscannedAllPlans" : 4, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 0, #D// much faster! "indexBounds" : { "num" : [ [ 199995, 1.7976931348623157e+308 ] ] }, "server" : "hostname:27017" } */ // ***************** 2.3.1 getting db info ***************************** // show databases show dbs // show collections in current database show collections // db details db.stats() /* results like: { "db" : "tutorial", "collections" : 4, "objects" : 200010, "avgObjSize" : 36.00065996700165, "dataSize" : 7200492, "storageSize" : 11268096, "numExtents" : 10, "indexes" : 3, "indexSize" : 11560864, "fileSize" : 201326592, "nsSizeMB" : 16, "dataFileVersion" : { "major" : 4, "minor" : 5 }, "ok" : 1 } */ // stats for one collection db.numbers.stats() /* results like { "ns" : "tutorial.numbers", "count" : 200000, "size" : 7200036, "avgObjSize" : 36.00018, "storageSize" : 11255808, "numExtents" : 7, "nindexes" : 2, "lastExtentSize" : 5664768, "paddingFactor" : 1, "systemFlags" : 1, "userFlags" : 0, "totalIndexSize" : 11552688, "indexSizes" : { "_id_" : 6508096, "num_1" : 5044592 }, "ok" : 1 } */ // ******************* 2.3.2 how commands work ****************************** // db.stats() is a helper for db.runCommand( {dbstats: 1} ) // db.numbers.stats() is a helper for db.runCommand( {collstats: "numbers"} ) // see definition for a function, such as "runCommand" - type without () db.runCommand // which leads to this version of the command for db.numbers.stats() db.$cmd.findOne( {collstats: "numbers"} ); // **************** 2.4 getting help ********************** // what does this save command do? db.numbers.save({num: 123123123}) // see save function code db.numbers.save
dengdengdengpan/lt-ui-vue
vue.config.js
<filename>vue.config.js const { defineConfig } = require('@vue/cli-service') const path = require('path') function pathResolve (dir) { return path.resolve(__dirname, dir) } module.exports = defineConfig({ transpileDependencies: true, chainWebpack: config => { config.module .rule('svg') .exclude .add(pathResolve('icons/svgs')) .end() config.module .rule('svg-icon') .test(/\.svg$/) .include .add(pathResolve('icons/svgs')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() config.resolve.alias .set('~', pathResolve('components')) .end() } })
itonov/Java-OOP-Advanced
07_OpenClosedLiskovPrinciples/src/logger/appenders/BaseAppender.java
<gh_stars>0 package logger.appenders; import logger.ReportLevel; import logger.interfaces.Layout; public abstract class BaseAppender { private Layout layout; private ReportLevel level; private int messagesCount; protected BaseAppender(Layout layout) { this.layout = layout; this.level = Enum.valueOf(ReportLevel.class, "INFO"); this.messagesCount = 0; } protected Layout getLayout() { return this.layout; } protected void setLevel(ReportLevel level) { this.level = level; } protected ReportLevel getLevel() { return this.level; } protected int getMessagesCount() { return this.messagesCount; } protected void increaseMessages() { this.messagesCount++; } }
rom1119/pacgame-fx
src/main/java/com/pacgame/movement/Movement.java
package com.pacgame.movement; public interface Movement { void start(); void stop(); void restart(); void pause(); }
ycdtosa/sbgECom
src/protocol/sbgEComProtocol.h
/*! * \file sbgEComProtocol.h * \author SBG Systems * \date 06 February 2013 * * \brief Implementation of the sbgECom binary communication protocol. * * You will find below, the frame definition used by Ekinox devices.<br> * <br> * <table> * <caption>Frame structure</caption> * <tr align="center"><td>Fields</td> <td>SYNC 1</td> <td>SYNC 2</td> <td>CMD</td> <td>LEN</td> <td>DATA</td> <td>CRC</td> <td>ETX</td></tr> * <tr align="center"><td>Size in bytes</td> <td>1</td> <td>1</td> <td>2</td> <td>2</td> <td>(0-4086)</td> <td>2</td> <td>1</td></tr> * <tr align="center"><td>Value</td> <td>0xFF</td> <td>0x5A</td> <td>?</td> <td>?</td> <td>?</td> <td>?</td> <td>0x33</td></tr> * </table> * <br> * Size in bytes indicates the size of the data field.<br> * The minimum frame size is 9 bytes and the maximum is 512 bytes.<br> * <br> * The CRC is calculated on the whole frame without:<br> * SYNC STX CRC and ETX fields.<br> * * \copyright Copyright (C) 2022, SBG Systems SAS. All rights reserved. * \beginlicense The MIT license * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * \endlicense */ #ifndef SBG_ECOM_PROTOCOL_H #define SBG_ECOM_PROTOCOL_H // sbgCommonLib headers #include <sbgCommon.h> #include <interfaces/sbgInterface.h> #include <streamBuffer/sbgStreamBuffer.h> #ifdef __cplusplus extern "C" { #endif //----------------------------------------------------------------------// //- Constant definitions -// //----------------------------------------------------------------------// #define SBG_ECOM_MAX_BUFFER_SIZE (4096) /*!< Maximum reception buffer size in bytes. */ #define SBG_ECOM_MAX_PAYLOAD_SIZE (4086) /*!< Maximum payload size in bytes. */ #define SBG_ECOM_MAX_EXTENDED_PAYLOAD_SIZE (4081) /*!< Maximum payload size in an extended frame, in bytes. */ #define SBG_ECOM_SYNC_1 (0xFF) /*!< First synchronization char of the frame. */ #define SBG_ECOM_SYNC_2 (0x5A) /*!< Second synchronization char of the frame. */ #define SBG_ECOM_ETX (0x33) /*!< End of frame byte. */ #define SBG_ECOM_RX_TIME_OUT (450) /*!< Default time out for new frame reception. */ //----------------------------------------------------------------------// //- Structure definitions -// //----------------------------------------------------------------------// /*! * Payload. * * This class is used to abstract whether some payload is received from a single * or multiple frames. */ typedef struct _SbgEComProtocolPayload { bool allocated; /*!< True if the buffer is allocated with malloc(). */ void *pBuffer; /*!< Buffer. */ size_t size; /*!< Buffer size, in bytes. */ } SbgEComProtocolPayload; /*! * Struct containing all protocol related data. * * The member variables related to large transfers are valid if and only if the large buffer is valid. */ typedef struct _SbgEComProtocol { SbgInterface *pLinkedInterface; /*!< Associated interface used by the protocol to read/write bytes. */ uint8_t rxBuffer[SBG_ECOM_MAX_BUFFER_SIZE]; /*!< The reception buffer. */ size_t rxBufferSize; /*!< The current reception buffer size in bytes. */ size_t discardSize; /*!< Number of bytes to discard on the next receive attempt. */ uint8_t nextLargeTxId; /*!< Transfer ID of the next large send. */ // // Member variables related to large transfer reception. // uint8_t *pLargeBuffer; /*!< Buffer for large transfers, allocated with malloc() if valid. */ size_t largeBufferSize; /*!< Size of the large transfer buffer, in bytes. */ uint8_t msgClass; /*!< Message class for the current large transfer. */ uint8_t msgId; /*!< Message ID for the current large transfer. */ uint8_t transferId; /*!< ID of the current large transfer. */ uint16_t pageIndex; /*!< Expected page index of the next frame. */ uint16_t nrPages; /*!< Number of pages in the current transfer. */ } SbgEComProtocol; //----------------------------------------------------------------------// //- Public methods (SbgEComProtocolPayload) -// //----------------------------------------------------------------------// /*! * Payload constructor. * * \param[in] pPayload Payload. */ void sbgEComProtocolPayloadConstruct(SbgEComProtocolPayload *pPayload); /*! * Payload destructor. * * \param[in] pPayload Payload. */ void sbgEComProtocolPayloadDestroy(SbgEComProtocolPayload *pPayload); /*! * Get the buffer of a payload. * * \param[in] pPayload Payload. * \return Payload buffer. */ const void *sbgEComProtocolPayloadGetBuffer(const SbgEComProtocolPayload *pPayload); /*! * Get the size of a payload buffer. * * \param[in] pPayload Payload. * \return Size of the payload buffer, in bytes. */ size_t sbgEComProtocolPayloadGetSize(const SbgEComProtocolPayload *pPayload); /*! * Move the buffer of a payload. * * If successful, the ownership of the buffer is passed to the caller. Otherwise, the payload * is unchanged. * * The buffer must be released with free() once unused. * * \param[in] pPayload Payload. * \return Payload buffer if successful, NULL otherwise. */ void *sbgEComProtocolPayloadMoveBuffer(SbgEComProtocolPayload *pPayload); //----------------------------------------------------------------------// //- Public methods (SbgEComProtocol) -// //----------------------------------------------------------------------// /*! * Initialize the protocol system used to communicate with the product and return the created handle. * * \param[in] pProtocol Pointer on an allocated protocol structure to initialize. * \param[in] pInterface Interface to use for read/write operations. * \return SBG_NO_ERROR if we have initialised the protocol system. */ SbgErrorCode sbgEComProtocolInit(SbgEComProtocol *pProtocol, SbgInterface *pInterface); /*! * Close the protocol system. * * \param[in] pProtocol A valid protocol handle to close. * \return SBG_NO_ERROR if we have closed and released the protocol system. */ SbgErrorCode sbgEComProtocolClose(SbgEComProtocol *pProtocol); /*! * Purge the interface rx buffer as well as the sbgECom rx work buffer. * * For example, if the program flow has been interrupted, this method can be helpful to discard all trash received data. * * WARNING: This method is blocking for 100ms and actively tries to read incoming data. * * \param[in] pProtocol A valid SbgEComProtocol handle. * \return SBG_NO_ERROR if the incoming data has been purged successfully. */ SbgErrorCode sbgEComProtocolPurgeIncoming(SbgEComProtocol *pProtocol); /*! * Send data. * * If the size is SBG_ECOM_MAX_PAYLOAD_SIZE or less, the data is sent in a single frame. Otherwise, * is it fragmented into multiple extended frames, each sent in order, which may block. * * \param[in] pProtocol A valid protocol handle. * \param[in] msgClass Message class. * \param[in] msg Message ID. * \param[in] pData Data buffer. * \param[in] size Data buffer size, in bytes. * \return SBG_NO_ERROR if the frame has been sent. */ SbgErrorCode sbgEComProtocolSend(SbgEComProtocol *pProtocol, uint8_t msgClass, uint8_t msg, const void *pData, size_t size); /*! * Receive a frame. * * \param[in] pProtocol A valid protocol handle. * \param[out] pMsgClass Message class, may be NULL. * \param[out] pMsgId Message ID, may be NULL. * \param[out] pData Data buffer. * \param[out] pSize Number of bytes received. * \param[in] maxSize Data buffer size, in bytes. * \return SBG_NO_ERROR if successful, * SBG_NOT_READY if no complete frame has been received, * SBG_BUFFER_OVERFLOW if the payload of the received frame couldn't fit into the data buffer. */ SbgErrorCode sbgEComProtocolReceive(SbgEComProtocol *pProtocol, uint8_t *pMsgClass, uint8_t *pMsgId, void *pData, size_t *pSize, size_t maxSize); /*! * Receive a frame. * * This function is equivalent to sbgEComProtocolReceive() with two exceptions : * - the use of a payload object allows handling payloads not limited by the size of a user-provided buffer * - the payload object allows direct access to the protocol work buffer to avoid an extra copy per call * * Any allocated resource associated with the given payload is released when calling this function. * * Because the payload buffer may directly refer to the protocol work buffer on return, it is only valid until * the next attempt to receive a frame, with any of the receive functions. * * \param[in] pProtocol A valid protocol handle. * \param[out] pMsgClass Message class, may be NULL. * \param[out] pMsgId Message ID, may be NULL. * \param[out] pPayload Payload. * \return SBG_NO_ERROR if successful, * SBG_NOT_READY if no complete frame has been received. */ SbgErrorCode sbgEComProtocolReceive2(SbgEComProtocol *pProtocol, uint8_t *pMsgClass, uint8_t *pMsgId, SbgEComProtocolPayload *pPayload); /*! * Initialize an output stream for an sbgECom frame generation. * * This function is helpful to avoid memory copy compared to sbgEComProtocolSend one. * * Only standard frames may be sent with this function. * * \param[in] pOutputStream Pointer to an allocated and initialized output stream. * \param[in] msgClass Message class. * \param[in] msg Message ID. * \param[out] pStreamCursor The initial output stream cursor that thus points to the begining of the generated message. * This value should be passed to sbgEComFinalizeFrameGeneration for correct operations. * \return SBG_NO_ERROR in case of good operation. */ SbgErrorCode sbgEComStartFrameGeneration(SbgStreamBuffer *pOutputStream, uint8_t msgClass, uint8_t msg, size_t *pStreamCursor); /*! * Finalize an output stream that has been initialized with sbgEComStartFrameGeneration. * * At return, the output stream buffer should point at the end of the generated message. * You can thus easily create consecutive SBG_ECOM_LOGS with these methods. * * \param[in] pOutputStream Pointer to an allocated and initialized output stream. * \param[in] streamCursor Position in the stream buffer of the generated message first byte. * This value is returned by sbgEComStartFrameGeneration and is mandatory for correct operations. * \return SBG_NO_ERROR in case of good operation. */ SbgErrorCode sbgEComFinalizeFrameGeneration(SbgStreamBuffer *pOutputStream, size_t streamCursor); #ifdef __cplusplus } #endif #endif // SBG_ECOM_PROTOCOL_H
manoelmenezes/gswgg
src/test/java/chapter03/DateFormatFunctionTest.java
package chapter03; import org.hamcrest.core.Is; import org.junit.Assert; import org.junit.Test; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class DateFormatFunctionTest { @Test public void testFormatDate() { LocalDate localDate = LocalDate.of(2017, 8, 10); Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); DateFormatFunction dff = new DateFormatFunction(); String result = dff.apply(date); Assert.assertThat(result, Is.is("10/08/2017")); } }
ProjectFFF/FFF
sizecompares/models.py
<filename>sizecompares/models.py from django.db import models # Create your models here. class Compare(models.Model): shoulder_compare = models.DecimalField(max_digits=6, decimal_places=3) chest_compare = models.DecimalField(max_digits=6, decimal_places=3) arm_compare = models.DecimalField(max_digits=6, decimal_places=3) total_length_compare = models.DecimalField(max_digits=6, decimal_places=3) class Result(models.Model): shoulder_result = models.DecimalField(max_digits=6, decimal_places=3) chest_result = models.DecimalField(max_digits=6, decimal_places=3) arm_result = models.DecimalField(max_digits=6, decimal_places=3) total_length_result = models.DecimalField(max_digits=6, decimal_places=3)
OpenMPDK/SMDK
lib/linux-5.18-rc3-smdk/drivers/gpu/drm/tiny/ili9163.c
<filename>lib/linux-5.18-rc3-smdk/drivers/gpu/drm/tiny/ili9163.c // SPDX-License-Identifier: GPL-2.0+ #include <linux/backlight.h> #include <linux/delay.h> #include <linux/gpio/consumer.h> #include <linux/module.h> #include <linux/property.h> #include <linux/spi/spi.h> #include <drm/drm_atomic_helper.h> #include <drm/drm_drv.h> #include <drm/drm_fb_helper.h> #include <drm/drm_gem_atomic_helper.h> #include <drm/drm_gem_cma_helper.h> #include <drm/drm_mipi_dbi.h> #include <drm/drm_modeset_helper.h> #include <video/mipi_display.h> #define ILI9163_FRMCTR1 0xb1 #define ILI9163_PWCTRL1 0xc0 #define ILI9163_PWCTRL2 0xc1 #define ILI9163_VMCTRL1 0xc5 #define ILI9163_VMCTRL2 0xc7 #define ILI9163_PWCTRLA 0xcb #define ILI9163_PWCTRLB 0xcf #define ILI9163_EN3GAM 0xf2 #define ILI9163_MADCTL_BGR BIT(3) #define ILI9163_MADCTL_MV BIT(5) #define ILI9163_MADCTL_MX BIT(6) #define ILI9163_MADCTL_MY BIT(7) static void yx240qv29_enable(struct drm_simple_display_pipe *pipe, struct drm_crtc_state *crtc_state, struct drm_plane_state *plane_state) { struct mipi_dbi_dev *dbidev = drm_to_mipi_dbi_dev(pipe->crtc.dev); struct mipi_dbi *dbi = &dbidev->dbi; u8 addr_mode; int ret, idx; if (!drm_dev_enter(pipe->crtc.dev, &idx)) return; DRM_DEBUG_KMS("\n"); ret = mipi_dbi_poweron_conditional_reset(dbidev); if (ret < 0) goto out_exit; if (ret == 1) goto out_enable; /* Gamma */ mipi_dbi_command(dbi, MIPI_DCS_SET_GAMMA_CURVE, 0x04); mipi_dbi_command(dbi, ILI9163_EN3GAM, 0x00); /* Frame Rate */ mipi_dbi_command(dbi, ILI9163_FRMCTR1, 0x0a, 0x14); /* Power Control */ mipi_dbi_command(dbi, ILI9163_PWCTRL1, 0x0a, 0x00); mipi_dbi_command(dbi, ILI9163_PWCTRL2, 0x02); /* VCOM */ mipi_dbi_command(dbi, ILI9163_VMCTRL1, 0x2f, 0x3e); mipi_dbi_command(dbi, ILI9163_VMCTRL2, 0x40); /* Memory Access Control */ mipi_dbi_command(dbi, MIPI_DCS_SET_PIXEL_FORMAT, MIPI_DCS_PIXEL_FMT_16BIT); mipi_dbi_command(dbi, MIPI_DCS_EXIT_SLEEP_MODE); msleep(100); mipi_dbi_command(dbi, MIPI_DCS_SET_DISPLAY_ON); msleep(100); out_enable: switch (dbidev->rotation) { default: addr_mode = ILI9163_MADCTL_MX | ILI9163_MADCTL_MY; break; case 90: addr_mode = ILI9163_MADCTL_MX | ILI9163_MADCTL_MV; break; case 180: addr_mode = 0; break; case 270: addr_mode = ILI9163_MADCTL_MY | ILI9163_MADCTL_MV; break; } addr_mode |= ILI9163_MADCTL_BGR; mipi_dbi_command(dbi, MIPI_DCS_SET_ADDRESS_MODE, addr_mode); mipi_dbi_enable_flush(dbidev, crtc_state, plane_state); out_exit: drm_dev_exit(idx); } static const struct drm_simple_display_pipe_funcs ili9163_pipe_funcs = { .enable = yx240qv29_enable, .disable = mipi_dbi_pipe_disable, .update = mipi_dbi_pipe_update, .prepare_fb = drm_gem_simple_display_pipe_prepare_fb, }; static const struct drm_display_mode yx240qv29_mode = { DRM_SIMPLE_MODE(128, 160, 28, 35), }; DEFINE_DRM_GEM_CMA_FOPS(ili9163_fops); static struct drm_driver ili9163_driver = { .driver_features = DRIVER_GEM | DRIVER_MODESET | DRIVER_ATOMIC, .fops = &ili9163_fops, DRM_GEM_CMA_DRIVER_OPS_VMAP, .debugfs_init = mipi_dbi_debugfs_init, .name = "ili9163", .desc = "Ilitek ILI9163", .date = "20210208", .major = 1, .minor = 0, }; static const struct of_device_id ili9163_of_match[] = { { .compatible = "newhaven,1.8-128160EF" }, { } }; MODULE_DEVICE_TABLE(of, ili9163_of_match); static const struct spi_device_id ili9163_id[] = { { "nhd-1.8-128160EF", 0 }, { } }; MODULE_DEVICE_TABLE(spi, ili9163_id); static int ili9163_probe(struct spi_device *spi) { struct device *dev = &spi->dev; struct mipi_dbi_dev *dbidev; struct drm_device *drm; struct mipi_dbi *dbi; struct gpio_desc *dc; u32 rotation = 0; int ret; dbidev = devm_drm_dev_alloc(dev, &ili9163_driver, struct mipi_dbi_dev, drm); if (IS_ERR(dbidev)) return PTR_ERR(dbidev); dbi = &dbidev->dbi; drm = &dbidev->drm; spi_set_drvdata(spi, drm); dbi->reset = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH); if (IS_ERR(dbi->reset)) { DRM_DEV_ERROR(dev, "Failed to get gpio 'reset'\n"); return PTR_ERR(dbi->reset); } dc = devm_gpiod_get_optional(dev, "dc", GPIOD_OUT_LOW); if (IS_ERR(dc)) { DRM_DEV_ERROR(dev, "Failed to get gpio 'dc'\n"); return PTR_ERR(dc); } dbidev->backlight = devm_of_find_backlight(dev); if (IS_ERR(dbidev->backlight)) return PTR_ERR(dbidev->backlight); device_property_read_u32(dev, "rotation", &rotation); ret = mipi_dbi_spi_init(spi, dbi, dc); if (ret) return ret; ret = mipi_dbi_dev_init(dbidev, &ili9163_pipe_funcs, &yx240qv29_mode, rotation); if (ret) return ret; drm_mode_config_reset(drm); ret = drm_dev_register(drm, 0); if (ret) return ret; drm_fbdev_generic_setup(drm, 0); return 0; } static void ili9163_remove(struct spi_device *spi) { struct drm_device *drm = spi_get_drvdata(spi); drm_dev_unplug(drm); drm_atomic_helper_shutdown(drm); } static void ili9163_shutdown(struct spi_device *spi) { drm_atomic_helper_shutdown(spi_get_drvdata(spi)); } static struct spi_driver ili9163_spi_driver = { .driver = { .name = "ili9163", .of_match_table = ili9163_of_match, }, .id_table = ili9163_id, .probe = ili9163_probe, .remove = ili9163_remove, .shutdown = ili9163_shutdown, }; module_spi_driver(ili9163_spi_driver); MODULE_DESCRIPTION("Ilitek ILI9163 DRM driver"); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_LICENSE("GPL");
eeguney/mern-react-budget-planner-app
clientside/src/pages/index.js
import React from "react"; import Home from "./Home/Home"; import Logout from "./Logout/Logout"; import SignIn from "./SignIn/SignIn"; import SignUp from "./SignIn/SignUp"; import Transactions from "./Transactions/Transactions"; const Page = { Home: (props) => { return <Home {...props} /> }, SignIn: (props) => { return <SignIn {...props} /> }, SignUp: (props) => { return <SignUp {...props} /> }, Logout: (props) => { return <Logout {...props} /> }, Transactions: (props) => { return <Transactions {...props} /> } }; export default Page;
asinha04/Servlets
service/impl/HandlebarsComponentClientLibRecompileServiceImpl.java
<filename>service/impl/HandlebarsComponentClientLibRecompileServiceImpl.java package org.kp.foundation.core.service.impl; import com.day.cq.replication.ReplicationActionType; import com.day.cq.replication.ReplicationException; import com.day.cq.replication.Replicator; //Replication APIs import com.day.cq.wcm.api.PageManager; import org.kp.foundation.core.exception.DynamicClientLibException; import org.kp.foundation.core.exception.DynamicClientLibRuntimeException; import org.kp.foundation.core.service.DynamicClientLibExecutorService; import org.kp.foundation.core.service.DynamicClientLibProcessorService; import org.kp.foundation.core.service.HandlebarsComponentClientLibRecompileService; import org.kp.foundation.core.service.SystemUserResources; import org.kp.foundation.core.utils.ClientLibraryUtil; import org.kp.foundation.core.utils.JCRUtil; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.sling.api.resource.Resource; import org.apache.commons.lang.StringUtils; import org.apache.sling.api.resource.ResourceResolver; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import java.util.*; import static javax.jcr.query.Query.JCR_SQL2; import static org.kp.foundation.core.constants.HandlebarConstants.KP_COMPILER_SERVICE; import static org.kp.foundation.core.utils.ClientLibraryUtil.JS_TXT; import static org.kp.foundation.core.utils.JCRUtil.isValidComponentToCreateHandlebarsDynamicClientLib; @Component(service = HandlebarsComponentClientLibRecompileService.class, property = { "compiler-type" +"=Handlebars", "service.vendor" +"=Kaiser Permanente"}) public class HandlebarsComponentClientLibRecompileServiceImpl implements HandlebarsComponentClientLibRecompileService { private static final Logger LOGGER = LoggerFactory.getLogger(HandlebarsComponentClientLibRecompileService.class); @Reference private SystemUserResources systemUserResources; @Reference private Replicator replicator; @Reference(target="(clientlib-type=Handlebars)") private DynamicClientLibProcessorService dynamicClientLibProcessorService; @Reference(target="(clientlib-type=Handlebars)") private DynamicClientLibExecutorService dynamicClientLibExecutorService; /** * Given a contentPath and a component path {/apps} recompile handlebars component * Optional: Replicate content to publisher instances * @param componentPath * @param contentPath * @param isReplicate * @throws DynamicClientLibException */ public ArrayList<String> recompileHandlebarComponents(String componentPath, String contentPath, boolean isReplicate, Session currentUserSession) throws DynamicClientLibException { final String PAGE_CONTENT_SQL2 = "SELECT * FROM [nt:unstructured] AS node\n" + "WHERE ISDESCENDANTNODE(node, \""+contentPath+"\")\n" + "AND [sling:resourceType] = \""+componentPath+"\" option(traversal ok)"; final ResourceResolver resourceResolver = systemUserResources.getSystemUserResourceResolver(KP_COMPILER_SERVICE); final Session session = systemUserResources.getSystemUserSession(KP_COMPILER_SERVICE); ArrayList<String> modifiedPages = new ArrayList<>(); ArrayList<String> modifiedClientLibs = new ArrayList<>(); if (resourceResolver != null && session != null) { final PageManager pageManager = resourceResolver.adaptTo(PageManager.class); if (pageManager != null) { Iterator<Resource> resources = resourceResolver.findResources(PAGE_CONTENT_SQL2, JCR_SQL2); Iterable<Resource> iterable = () -> resources; iterable.forEach(currentResource -> { try { String currentComponentPath = currentResource.getPath(); // only select the node with the "sling:resourceType" for more robust search if (StringUtils.isNotBlank(currentResource.getValueMap().get("sling:resourceType", ""))) { // execute handlebars compilation validateAndExecuteDynamicClientLibsProcessor(session, currentResource); String pageUUID = JCRUtil.getUUID(Objects.requireNonNull(currentResource.adaptTo(Node.class))); String pagePath = pageManager.getContainingPage(currentResource).getPath(); modifiedPages.add(pagePath); Optional<Node> clientLibNode = dynamicClientLibExecutorService.processPageDataForClientLibNode(pagePath,ClientLibraryUtil.getFeatureNameFromEventPath(session, currentComponentPath)); // checking to satisfy non-null; hence, will always be true at this point if (clientLibNode.isPresent()){ // add clientlib main folder String clientLibNodeParentPath = clientLibNode.get().getPath(); modifiedClientLibs.add(clientLibNodeParentPath); // jsfile path final String hbarClientlibGeneratePath = clientLibNodeParentPath + "/"+ ClientLibraryUtil.JS_FOLDER+"/"+ pageUUID + ClientLibraryUtil.JAVASCRIPT_SUFFIX; // js.txt path final String jsTxtPath = clientLibNodeParentPath + "/" + JS_TXT; modifiedClientLibs.add(jsTxtPath); modifiedClientLibs.add(hbarClientlibGeneratePath); } } } catch (RepositoryException | DynamicClientLibException e) { LOGGER.error("Unable to execute handlebars compilation " + e); } }); } //replicate modified pages if (isReplicate) { replicateListOfContent(modifiedClientLibs, currentUserSession); } } return modifiedClientLibs; } /** * Validates and executes clientLib processor * @param session * @param componentResource */ private void validateAndExecuteDynamicClientLibsProcessor(Session session, Resource componentResource) { String currentComponentPath = componentResource.getPath(); try { if (isValidComponentToCreateHandlebarsDynamicClientLib(session, currentComponentPath)) { dynamicClientLibProcessorService.execute( currentComponentPath, ClientLibraryUtil.getFeatureNameFromEventPath(session, currentComponentPath) ); } } catch (RepositoryException | DynamicClientLibException e) { throw new DynamicClientLibRuntimeException("Repository or DynamicClientLibException: ", e); } } /** * Replicates content to publish instance * @param session * @param path */ private void replicateContent(Session session, String path) { try { replicator.replicate(session, ReplicationActionType.ACTIVATE, path); LOGGER.info("Page activated: "+ path); } catch (ReplicationException e) { LOGGER.error("Replication failed "+e.getMessage(), path); } } /** * Replicates list of content * @param contentList * @param session */ private void replicateListOfContent(List<String> contentList,Session session) { contentList.stream() .distinct() .forEach(path -> replicateContent(session, path)); } }
carderne/raster-vision
rastervision/v2/core/__init__.py
<filename>rastervision/v2/core/__init__.py # flake8: noqa import logging import importlib import json ''' root_logger = logging.getLogger('rastervision.v2') sh = logging.StreamHandler() sh.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s:%(name)s: %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S') sh.setFormatter(formatter) root_logger.addHandler(sh) ''' from rastervision.v2.core.registry import Registry _registry = Registry() from rastervision.v2.core.rv_config import RVConfig _rv_config = RVConfig() from rastervision.v2.core.verbosity import Verbosity loaded_plugins = [] def load_builtins(): from rastervision.v2.core.runner import (InProcessRunner, INPROCESS, AWSBatchRunner, AWS_BATCH) from rastervision.v2.core.filesystem import (HttpFileSystem, S3FileSystem, LocalFileSystem) _registry.runners = {INPROCESS: InProcessRunner, AWS_BATCH: AWSBatchRunner} _registry.filesystems = [ HttpFileSystem, S3FileSystem, # This is the catch-all case, ensure it's on the bottom of the search stack. LocalFileSystem ] def load_conf_list(s): """Loads a list of items from the config. Lists should be comma separated. This takes into account that previous versions of Raster Vision allowed for a `[ "module" ]` like syntax, even though that didn't work for multi-value lists. """ try: # A comma separated list of values will be transformed to # having a list-like string, with ' instead of ". Replacing # single quotes with double quotes lets us parse it as a JSON list. return json.loads(s.replace("'", '"')) except json.JSONDecodeError: return list(map(lambda x: x.strip(), s.split(','))) def system_init(profile=None, verbosity=Verbosity.NORMAL): _rv_config.reset(profile=profile, verbosity=verbosity) plugin_config = _rv_config.get_subconfig('PLUGINS') if plugin_config: plugin_modules = load_conf_list(plugin_config('modules')) for pm in plugin_modules: if pm not in loaded_plugins: loaded_plugins.append(pm) pm = importlib.import_module(pm) register_plugin = getattr(pm, 'register_plugin', None) if register_plugin: register_plugin(_registry) load_builtins() system_init() ''' from rastervision.v2.core.config import * from rastervision.v2.core.pipeline import * from rastervision.v2.core.pipeline_config import * '''
arteptiber/clio
packages/highlight/index.js
import { existsSync, readFileSync } from "fs"; import chalk from "chalk"; const { blue, cyan, gray, green, magenta, white, yellow } = chalk; export function highlight(source) { if (!source) { throw new Error("The path to the Clio souce file is required."); } if (!existsSync(source)) { throw new Error("The provided Clio source file does not exist."); } const contents = readFileSync(source, "utf8"); return colorize(contents); } export function colorize(text) { let patterns = [ { pattern: /^fn +[a-z_][a-z_0-9]*/i, action: function (match, colorized) { let name = match.slice(2).trim(" "); let spaces = match.length - name.length - 2; colorized.push(magenta("fn")); colorized.push(white(" ".repeat(spaces))); colorized.push(blue(name)); }, }, { pattern: /^[-=]> +[a-z_][a-z_0-9]*/i, action: function (match, colorized) { let name = match.slice(2).trim(" "); let spaces = match.length - name.length - 2; colorized.push(magenta(match.slice(0, 2))); colorized.push(white(" ".repeat(spaces))); colorized.push(blue(name)); }, }, { pattern: /^-> *\* *[a-z_][a-z_0-9]*/i, action: function (match, colorized) { let name = match.match(/[a-z_][a-z_0-9]*/)[0]; let operator = match.match(/-> *\*/)[0]; let spaces = match.length - name.length - operator.length; colorized.push(magenta(operator)); colorized.push(white(" ".repeat(spaces))); colorized.push(blue(name)); }, }, { color: gray, pattern: /^--.*?($|\n)/ }, { color: green, pattern: /^#[^\[\] \r\n]+/i }, { color: magenta, pattern: /^(export|fn|else|if|not|or|and|import|from|as)(?![a-zA-Z_-])/, }, { color: yellow, pattern: /^(true|false)/ }, { color: green, pattern: /^https?:[^ \r\n]+/ }, { color: cyan, pattern: /^(->|=>)/ }, { color: cyan, pattern: /^(!|!=|=|>|<|>=|<=)/ }, { color: cyan, pattern: /^([\[\]()])/ }, { color: cyan, pattern: /^[-+/*%^]/ }, { color: cyan, pattern: /^(([@][a-z][a-z0-9_]*)|[.:@])/i }, { color: yellow, pattern: /^(0|-?[1-9][0-9']*)(\.[0-9']+)?/ }, { color: white, pattern: /^[a-z_][a-z_0-9]*('s? )?/i }, { color: green, pattern: /^('([^\\]|\\.)*?'|:\S+)/ }, { color: white, pattern: /^\S+/ }, { color: white, pattern: /^(\r\n|[\r\n])/ }, { color: white, pattern: /\s+/ }, ]; let colorized = []; let i = 0; while (i <= text.length) { for (let j = 0; j < patterns.length; j++) { let match = text.slice(i).match(patterns[j].pattern); if (match != null) { if (patterns[j].action != undefined) { patterns[j].action(match[0], colorized); } else { colorized.push(patterns[j].color(match[0])); } i += match[0].length - 1; break; } } i++; } return colorized.join(""); }
ethansaxenian/RosettaDecode
lang/Java/abundant,-deficient-and-perfect-number-classifications.java
<gh_stars>1-10 import java.util.stream.LongStream; public class NumberClassifications { public static void main(String[] args) { int deficient = 0; int perfect = 0; int abundant = 0; for (long i = 1; i <= 20_000; i++) { long sum = properDivsSum(i); if (sum < i) deficient++; else if (sum == i) perfect++; else abundant++; } System.out.println("Deficient: " + deficient); System.out.println("Perfect: " + perfect); System.out.println("Abundant: " + abundant); } public static long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n != i && n % i == 0).sum(); } }
alexmadeira/apps-leagueofchampions
src/pages/index.js
<reponame>alexmadeira/apps-leagueofchampions<gh_stars>0 import React, { useState } from 'react'; import Background from '~/components/Background'; import ChampionInfo from '~/components/ChampionInfo'; import Header from '~/components/Header'; import Nav from '~/components/Nav'; import Search from '~/components/Search'; import Footer from '~/components/Statics/Footer'; import RiotLogo from '~/components/Statics/RiotLogo'; import { ChampionsProvider } from '~/contexts/ChampionContext'; import Routes from '~/routes'; import { Container, PageContent, Page } from './styles'; function Pages() { const [currentChampion, setCurrentChampion] = useState({ find: 'Aatrox', search: false, loading: true, activeSkill: false, searchList: {}, }); return ( <ChampionsProvider value={{ currentChampion, setCurrentChampion }}> <Background /> <Search /> <PageContent> <Header /> <ChampionInfo /> <Nav /> <Container> <Page> <Routes /> </Page> <RiotLogo /> </Container> <Footer /> </PageContent> </ChampionsProvider> ); } export default Pages;
jakob-bagterp/browserist
src/browserist/browser/check_if/is_disabled.py
<filename>src/browserist/browser/check_if/is_disabled.py<gh_stars>1-10 from ...model.type.xpath import XPath from .is_enabled import check_if_is_enabled def check_if_is_disabled(driver: object, xpath: str) -> bool: xpath = XPath(xpath) return not check_if_is_enabled(driver, xpath)
Internship1/Frontend
app/partials/previewCV/previewCV.js
'use strict'; angular.module('myApp.previewCV', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/previewCV', { templateUrl: 'partials/previewCV/previewCV.html', controller: 'addCVsCtrl' }); }]) .controller('addCVsCtrl', [function() { }]);
swissbilling-sa/swissbilling-client-java
src/main/java/ch/swissbilling/framework/einvoice/models/PartyType.java
<gh_stars>0 // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.03.26 at 06:45:41 PM EET // package ch.swissbilling.framework.einvoice.models; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PartyType", propOrder = { "customerID", "address", "taxID", "additionalReference" }) public class PartyType { @XmlElement(name = "CustomerID") protected String customerID; @XmlElement(name = "Address", required = true) protected AddressType address; @XmlElement(name = "TaxID") protected String taxID; @XmlElement(name = "AdditionalReference") protected List<Reference> additionalReference; /** * Gets the value of the customerID property. * * @return * possible object is * {@link String } * */ public String getCustomerID() { return customerID; } /** * Sets the value of the customerID property. * * @param value * allowed object is * {@link String } * */ public void setCustomerID(String value) { this.customerID = value; } /** * Gets the value of the address property. * * @return * possible object is * {@link AddressType } * */ public AddressType getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link AddressType } * */ public void setAddress(AddressType value) { this.address = value; } /** * Gets the value of the taxID property. * * @return * possible object is * {@link String } * */ public String getTaxID() { return taxID; } /** * Sets the value of the taxID property. * * @param value * allowed object is * {@link String } * */ public void setTaxID(String value) { this.taxID = value; } /** * Gets the value of the additionalReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Reference } * * */ public List<Reference> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<Reference>(); } return this.additionalReference; } }
jffc-dev/Python-Django-Tecshop
aplicacion/migrations/0001_initial.py
# Generated by Django 3.1.4 on 2020-12-21 21:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Categoria', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('categoria', models.CharField(max_length=100)), ('ruta', models.CharField(max_length=100)), ('fecha', models.DateTimeField()), ], ), migrations.CreateModel( name='Usuario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=100)), ('password', models.CharField(max_length=100)), ('email', models.EmailField(max_length=254)), ('modo', models.CharField(max_length=100)), ('foto', models.CharField(max_length=100)), ('verificacion', models.IntegerField()), ('email_encriptado', models.CharField(max_length=100)), ('fecha', models.DateTimeField()), ], ), migrations.CreateModel( name='Subcategoria', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('subcategoria', models.CharField(max_length=100)), ('ruta', models.CharField(max_length=100)), ('fecha', models.DateTimeField()), ('categoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.categoria')), ], ), migrations.CreateModel( name='Producto', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tipo', models.CharField(max_length=100)), ('ruta', models.CharField(max_length=100)), ('titulo', models.CharField(max_length=200)), ('titular', models.CharField(max_length=200)), ('descripcion', models.TextField()), ('multimedia', models.CharField(max_length=100)), ('detalles', models.TextField()), ('precio', models.DecimalField(decimal_places=2, max_digits=6)), ('portada', models.CharField(max_length=100)), ('vistas', models.IntegerField()), ('ventas', models.IntegerField()), ('vistas_gratis', models.IntegerField()), ('ventas_gratis', models.IntegerField()), ('ofertado_por_categoria', models.IntegerField()), ('ofertado_por_sub_categoria', models.IntegerField()), ('oferta', models.IntegerField()), ('precio_oferta', models.DecimalField(decimal_places=2, max_digits=6)), ('descuento_oferta', models.IntegerField()), ('img_oferta', models.CharField(max_length=100)), ('fin_oferta', models.DateTimeField()), ('nuevo', models.IntegerField()), ('peso', models.DecimalField(decimal_places=2, max_digits=6)), ('entrega', models.DecimalField(decimal_places=2, max_digits=6)), ('fecha', models.DateTimeField()), ('categoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.categoria')), ('subcategoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.subcategoria')), ], ), migrations.CreateModel( name='Deseo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fecha', models.DateTimeField()), ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.producto')), ('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.usuario')), ], ), migrations.CreateModel( name='Compra', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('envio', models.IntegerField()), ('metodo', models.CharField(max_length=100)), ('direccion', models.CharField(max_length=300)), ('pais', models.CharField(max_length=100)), ('fecha', models.DateTimeField()), ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.producto')), ('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.usuario')), ], ), migrations.CreateModel( name='Comentario', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('calificacion', models.FloatField()), ('comentario', models.CharField(max_length=200)), ('fecha', models.DateTimeField()), ('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.producto')), ('usuario', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='aplicacion.usuario')), ], ), ]
ComputerArchitectureGroupPWr/JGenerilo
src/main/java/edu/byu/ece/rapidSmith/timing/Path.java
/* * Copyright (c) 2010 Brigham Young University * * This file is part of the BYU RapidSmith Tools. * * BYU RapidSmith Tools is free software: you may redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 2 of * the License, or (at your option) any later version. * * BYU RapidSmith Tools is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License is included with the BYU * RapidSmith Tools. It can be found at doc/gpl2.txt. You may also * get a copy of the license at <http://www.gnu.org/licenses/>. * */ package edu.byu.ece.rapidSmith.timing; import edu.byu.ece.rapidSmith.design.Net; import java.util.ArrayList; public abstract class Path { /** * The source of this connection delay */ private String source; /** * The destination of this connection delay */ private String destination; /** * Data path delay in nanoseconds */ private float dataPathDelay; /** * Number of logic levels the data path traverses */ private int levelsOfLogic; /** * The net driving the clock on the destination register */ private Net destinationClock; /** * The uncertainty in the clock as determined by Xilinx trce */ private float clockUncertainty; /** * List of physical / logical resources */ private ArrayList<PathElement> maxDataPath = new ArrayList<PathElement>(); /** * @return the source */ public String getSource() { return source; } /** * @param source the source to set */ public void setSource(String source) { this.source = source; } /** * @return the destination */ public String getDestination() { return destination; } /** * @param destination the destination to set */ public void setDestination(String destination) { this.destination = destination; } /** * @return the dataPathDelay */ public float getDataPathDelay() { return dataPathDelay; } /** * @param dataPathDelay the dataPathDelay to set */ public void setDataPathDelay(float dataPathDelay) { this.dataPathDelay = dataPathDelay; } /** * @return the levelsOfLogic */ public int getLevelsOfLogic() { return levelsOfLogic; } /** * @param levelsOfLogic the levelsOfLogic to set */ public void setLevelsOfLogic(int levelsOfLogic) { this.levelsOfLogic = levelsOfLogic; } /** * @return the destinationClock */ public Net getDestinationClock() { return destinationClock; } /** * @param destinationClock the destinationClock to set */ public void setDestinationClock(Net destinationClock) { this.destinationClock = destinationClock; } /** * @return the clockUncertainty */ public float getClockUncertainty() { return clockUncertainty; } /** * @param clockUncertainty the clockUncertainty to set */ public void setClockUncertainty(float clockUncertainty) { this.clockUncertainty = clockUncertainty; } /** * @param maxDataPath the maxDataPath to set */ public void setMaxDataPath(ArrayList<PathElement> maxDataPath) { this.maxDataPath = maxDataPath; } /** * @return the maxDataPath */ public ArrayList<PathElement> getMaxDataPath() { return maxDataPath; } }
taikusa/rcrs-server
modules/maps/src/maps/convert/osm2gml/ComputePassableEdgesStep.java
<reponame>taikusa/rcrs-server package maps.convert.osm2gml; import maps.convert.ConvertStep; import java.util.Collection; /** This step computes which edges are passable and sets up neighbours accordingly. */ public class ComputePassableEdgesStep extends ConvertStep { private TemporaryMap map; /** Construct a ComputePassableEdgesStep. @param map The TemporaryMap to use. */ public ComputePassableEdgesStep(TemporaryMap map) { this.map = map; } @Override public String getDescription() { return "Computing passable edges"; } @Override protected void step() { setProgressLimit(map.getAllEdges().size()); // For each edge see if it is shared by two road faces // If so, make it passable. int count = 0; for (Edge next : map.getAllEdges()) { int roadCount = 0; Collection<TemporaryObject> attached = map.getAttachedObjects(next); for (TemporaryObject o : attached) { if (o instanceof TemporaryRoad || o instanceof TemporaryIntersection) { ++roadCount; } } if (roadCount > 1) { // Edge is passable. Make the neighbours. for (TemporaryObject o1 : attached) { for (TemporaryObject o2 : attached) { if (o1 == o2) { continue; } o1.setNeighbour(next, o2); } } ++count; } bumpProgress(); } setStatus("Made " + count + " edges passable"); } }
MiltosD/CEFELRC
lib/python2.7/site-packages/django_jenkins/tasks/run_pyflakes.py
# -*- coding: utf-8 -*- import os import re import sys from pyflakes.scripts import pyflakes from cStringIO import StringIO from django_jenkins.functions import relpath from django_jenkins.tasks import BaseTask, get_apps_locations class Task(BaseTask): def __init__(self, test_labels, options): super(Task, self).__init__(test_labels, options) self.test_all = options['test_all'] if options.get('pyflakes_file_output', True): output_dir = options['output_dir'] if not os.path.exists(output_dir): os.makedirs(output_dir) self.output = open(os.path.join(output_dir, 'pyflakes.report'), 'w') else: self.output = sys.stdout def teardown_test_environment(self, **kwargs): locations = get_apps_locations(self.test_labels, self.test_all) # run pyflakes tool with captured output old_stdout, pyflakes_output = sys.stdout, StringIO() sys.stdout = pyflakes_output try: for location in locations: if os.path.isdir(location): for dirpath, dirnames, filenames in os.walk(relpath(location)): for filename in filenames: if filename.endswith('.py'): pyflakes.checkPath(os.path.join(dirpath, filename)) else: pyflakes.checkPath(relpath(location)) finally: sys.stdout = old_stdout # save report pyflakes_output.reset() while True: line = pyflakes_output.readline() if not line: break message = re.sub(r': ', r': [E] PYFLAKES:', line) self.output.write(message) self.output.close()
lancetw/react-isomorphic-bundle
src/client/admin.js
<gh_stars>10-100 require('babel-polyfill') require('./admin/index')
testnetopeer/libyang
src/schema_compile_amend.h
<reponame>testnetopeer/libyang<gh_stars>0 /** * @file schema_compile_amend.h * @author <NAME> <<EMAIL>> * @brief Header for schema compilation of augments, deviations, and refines. * * Copyright (c) 2015 - 2020 CESNET, z.s.p.o. * * This source code is licensed under BSD 3-Clause License (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause */ #ifndef LY_SCHEMA_COMPILE_AMEND_H_ #define LY_SCHEMA_COMPILE_AMEND_H_ #include "log.h" struct ly_ctx; struct lysp_qname; struct lysp_node; struct lysc_node; struct lysc_ctx; struct lysp_node_uses; struct lys_module; /** * @brief Compiled parsed augment structure. Just a temporary storage for applying the augment to data. */ struct lysc_augment { struct lyxp_expr *nodeid; /**< augment target */ const struct lysp_module *aug_pmod; /**< module where the augment is defined, for top-level augments used to resolve prefixes, for uses augments used as the context pmod */ const struct lysc_node *nodeid_ctx_node; /**< nodeid context node for relative targets */ struct lysp_node_augment *aug_p; /**< pointer to the parsed augment to apply */ }; /** * @brief Compiled parsed deviation structure. Just a temporary storage for applying the deviation to data. */ struct lysc_deviation { struct lyxp_expr *nodeid; /**< deviation target, taken from the first deviation in ::lysc_deviation.dev_pmods array, this module is used for resolving prefixes used in the nodeid. */ struct lysp_deviation **devs; /**< sized array of all the parsed deviations for one target node */ const struct lysp_module **dev_pmods; /**< sized array of parsed modules of @p devs (where the specific deviations are defined). */ ly_bool not_supported; /**< whether this is a not-supported deviation */ }; /** * @brief Compiled parsed refine structure. Just a temporary storage for applying the refine to data. */ struct lysc_refine { struct lyxp_expr *nodeid; /**< refine target */ const struct lysp_module *nodeid_pmod; /**< module where the nodeid is defined, used to resolve prefixes */ const struct lysc_node *nodeid_ctx_node; /**< nodeid context node */ struct lysp_node_uses *uses_p; /**< parsed uses node of the refine, for tracking recursive refines */ struct lysp_refine **rfns; /**< sized array of parsed refines to apply */ }; /** * @brief Prepare any uses augments and refines in the context to be applied during uses descendant node compilation. * * @param[in] ctx Compile context. * @param[in] uses_p Parsed uses structure with augments and refines. * @param[in] ctx_node Context node of @p uses_p meaning its first data definiition parent. * @return LY_ERR value. */ LY_ERR lys_precompile_uses_augments_refines(struct lysc_ctx *ctx, struct lysp_node_uses *uses_p, const struct lysc_node *ctx_node); /** * @brief Duplicate qname structure. * * @param[in] ctx libyang context. * @param[in,out] qname Structure to fill. * @param[in] orig_qname Structure to read from. * @return LY_ERR value. */ LY_ERR lysp_qname_dup(const struct ly_ctx *ctx, struct lysp_qname *qname, const struct lysp_qname *orig_qname); /** * @brief Free a compiled augment temporary structure. * * @param[in] ctx libyang context. * @param[in] aug Structure to free. */ void lysc_augment_free(const struct ly_ctx *ctx, struct lysc_augment *aug); /** * @brief Free a compiled deviation temporary structure. * * @param[in] ctx libyang context. * @param[in] dev Structure to free. */ void lysc_deviation_free(const struct ly_ctx *ctx, struct lysc_deviation *dev); /** * @brief Free a compiled refine temporary structure. * * @param[in] ctx libyang context. * @param[in] rfn Structure to free. */ void lysc_refine_free(const struct ly_ctx *ctx, struct lysc_refine *rfn); /** * @brief Free a duplicate of parsed node. It is returned by ::lys_compile_node_deviations_refines(). * * @param[in] ctx libyang context. * @param[in] dev_pnode Parsed node to free. */ void lysp_dev_node_free(const struct ly_ctx *ctx, struct lysp_node *dev_pnode); /** * @brief Compile and apply any precompiled deviations and refines targetting a node. * * @param[in] ctx Compile context. * @param[in] pnode Parsed node to consider. * @param[in] parent First compiled parent of @p pnode. * @param[out] dev_pnode Copy of parsed node @p pnode with deviations and refines, if any. NULL if there are none. * @param[out] no_supported Whether a not-supported deviation is defined for the node. * @return LY_ERR value. */ LY_ERR lys_compile_node_deviations_refines(struct lysc_ctx *ctx, const struct lysp_node *pnode, const struct lysc_node *parent, struct lysp_node **dev_pnode, ly_bool *not_supported); /** * @brief Compile and apply any precompiled top-level or uses augments targetting a node. * * @param[in] ctx Compile context. * @param[in] node Compiled node to consider. * @return LY_ERR value. */ LY_ERR lys_compile_node_augments(struct lysc_ctx *ctx, struct lysc_node *node); /** * @brief Prepare all top-level augments for the current module to be applied during data nodes compilation. * * @param[in] ctx Compile context. * @return LY_ERR value. */ LY_ERR lys_precompile_own_augments(struct lysc_ctx *ctx); /** * @brief Prepare all deviations for the current module to be applied during data nodes compilation. * * @param[in] ctx Compile context. * @return LY_ERR value. */ LY_ERR lys_precompile_own_deviations(struct lysc_ctx *ctx); /** * @brief Compile top-level augments and deviations defined in the current module. * Generally, just add the module refence to the target modules. But in case * of foreign augments, they are directly applied. * * @param[in] ctx Compile context. * @return LY_ERR value. */ LY_ERR lys_precompile_augments_deviations(struct lysc_ctx *ctx); /** * @brief Revert precompilation of module augments and deviations. Meaning remove its reference from * all the target modules. * * @param[in] ctx libyang context. * @param[in] mod Mod whose precompilation to revert. */ void lys_precompile_augments_deviations_revert(struct ly_ctx *ctx, const struct lys_module *mod); #endif /* LY_SCHEMA_COMPILE_AMEND_H_ */
mrubli/dns-proxy-server
events/local/storagev2/storagev2_test.go
package storagev2 import ( "github.com/mageddo/dns-proxy-server/events/local/localvo" "github.com/stretchr/testify/assert" "testing" ) func TestValueOf(t *testing.T) { // arrange var config = localvo.Configuration{ Version: 3, RemoteDnsServers: nil, Envs: nil, ActiveEnv: "", WebServerPort: 80, DnsServerPort: 53, DefaultDns: nil, LogLevel: "DEBUG", LogFile: "console", RegisterContainerNames: nil, HostMachineHostname: "", Domain: "docker", DpsNetwork: nil, DpsNetworkAutoConnect: nil, } // act v2Config := ValueOf(&config) // assert assert.Equal(t, int64(2), v2Config.Version) assert.Equal(t, make([]string, 0), v2Config.RemoteDnsServers) assert.Equal(t, make([]EnvV2, 0), v2Config.Envs) assert.Equal(t, "", v2Config.ActiveEnv) assert.Equal(t, 80, v2Config.WebServerPort) assert.Equal(t, 53, v2Config.DnsServerPort) assert.Nil(t, nil, v2Config.DefaultDns) assert.Equal(t, "DEBUG", v2Config.LogLevel) assert.Equal(t, "console", v2Config.LogFile) assert.Nil(t, v2Config.RegisterContainerNames) assert.Equal(t, "", v2Config.HostMachineHostname) assert.Equal(t, "docker", v2Config.Domain) assert.Nil(t, v2Config.DpsNetwork) assert.Nil(t, v2Config.DpsNetworkAutoConnect) }
mahajrod/MAVR
scripts/annotation/trim_cds_and_remove_terminal_stop_codons.py
#!/usr/bin/env python __author__ = '<NAME>' import argparse from RouToolPa.Routines import SequenceRoutines parser = argparse.ArgumentParser() parser.add_argument("-i", "--input", action="store", dest="input", required=True, help="Input fasta with raw cDS") parser.add_argument("-s", "--stop_codons", action="store", dest="stop_codons_list", default=["TGA", "TAA", "TAG"], type=lambda s: s.split(","), help="Comma-separated list of stop codons. Can be set using any case and both RNA and DNA alphabet." "Default: TGA, TAA, TAG") parser.add_argument("-o", "--output", action="store", dest="output", required=True, help="Output file to write trimmed CDS") args = parser.parse_args() print("Using %s as stop codons" % ",".join(args.stop_codons_list)) SequenceRoutines.trim_cds_and_remove_terminal_stop_codons(args.input, args.output, args.stop_codons_list)
basis-technology-corp/tcl-regex-java
src/test/java/com/basistech/tclre/LexTest.java
/* * Copyright 2014 Basis Technology Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basistech.tclre; import org.junit.Test; import static com.basistech.tclre.Utils.Matches.matches; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; /** * Test for the lexer. */ public class LexTest extends Utils { private void assertCatchCompileTime(String regex) { try { HsrePattern.compile(regex, PatternFlags.ADVANCED); assertTrue(false); /* should throw! */ } catch (RegexException ree) { assertTrue(true); } } //CHECKSTYLE:OFF @Test public void testLex() throws Exception { RePattern exp = HsrePattern.compile("a.*+[bc]d$+", PatternFlags.QUOTE); assertThat("a.*+[bc]d$+", matches(exp)); assertThat("a.*+[ef]d$+", not(matches(exp))); assertCatchCompileTime("***?kaboom"); assertCatchCompileTime("***qkaboum"); assertCatchCompileTime("(?z)"); HsrePattern.compile("(?b)", PatternFlags.ADVANCED); exp = HsrePattern.compile("(?i)aaBB", PatternFlags.ADVANCED); assertThat("aAbB", matches(exp)); exp = HsrePattern.compile("(?c)aaBB", PatternFlags.ADVANCED); assertThat("aaBB", matches(exp)); assertThat("aAbB", not(matches(exp))); exp = HsrePattern.compile("a\\nb", PatternFlags.ADVANCED); assertThat("a\nb", matches(exp)); exp = HsrePattern.compile("(?e)a\\nb", PatternFlags.ADVANCED); assertThat("a\nb", not(matches(exp))); /* ERE mode */ exp = HsrePattern.compile("(?n)^bcd$", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", matches(exp)); exp = HsrePattern.compile("(?s)^bcd$", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", not(matches(exp))); exp = HsrePattern.compile("(?s)^01.*fg$", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", matches(exp)); exp = HsrePattern.compile("(?p)^01.*fg$", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", not(matches(exp))); exp = HsrePattern.compile("(?p)^.*\n.*\n.*fg$", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", matches(exp)); exp = HsrePattern.compile("(?q)^01.*fg$", PatternFlags.ADVANCED); assertThat("^01.*fg$", matches(exp)); /* quote */ exp = HsrePattern.compile("(?x)abc #bar baz", PatternFlags.ADVANCED); assertThat("abcbarbaz", matches(exp)); exp = HsrePattern.compile("(?t)abc #bar baz", PatternFlags.ADVANCED); assertThat("abcbarbaz", not(matches(exp))); exp = HsrePattern.compile("(?w).*", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", matches(exp)); exp = HsrePattern.compile("(?w)^.*fg$", PatternFlags.ADVANCED); assertThat("01a\nbcd\nefg", matches(exp)); assertCatchCompileTime("(?p"); exp = HsrePattern.compile("[[.number-sign.]]"); assertThat("#", matches(exp)); assertThat("n", not(matches(exp))); exp = HsrePattern.compile("a{3,5}?", PatternFlags.ADVANCED); /*non-greedy*/ assertThat("aaaa", matches(exp)); assertCatchCompileTime("a[3,4"); assertCatchCompileTime("a{3,4"); assertCatchCompileTime("[[:digit:}"); exp = HsrePattern.compile("a\\x123q", PatternFlags.ADVANCED); assertThat("a\u0123q", matches(exp)); assertCatchCompileTime("a[\\"); exp = HsrePattern.compile("a[\\d]", PatternFlags.ADVANCED); assertThat("a3", matches(exp)); assertThat("ab", not(matches(exp))); exp = HsrePattern.compile("a[\\w]", PatternFlags.ADVANCED); assertThat("aQ", matches(exp)); assertThat("a$", not(matches(exp))); assertCatchCompileTime("a[["); exp = HsrePattern.compile("a\\{3,5\\}", PatternFlags.BASIC); assertThat("aaaa", matches(exp)); assertThat("aa", not(matches(exp))); exp = HsrePattern.compile("a[\\]b", PatternFlags.BASIC); assertThat("a\\b", matches(exp)); assertCatchCompileTime("a{3,q}"); assertCatchCompileTime("a[\\q]"); HsrePattern.compile("[[q]]", PatternFlags.ADVANCED); /* not clear what this (above) means, but code special-cases it. */ exp = HsrePattern.compile("a.+?b", PatternFlags.ADVANCED); assertThat("acwwdcdbwfefwb", matches(exp)); /* won't say which*/ assertThat("ab", not(matches(exp))); exp = HsrePattern.compile("a.??b", PatternFlags.ADVANCED); /* meaning.?? */ assertThat("ab", matches(exp)); /* won't say which*/ exp = HsrePattern.compile("a{b", PatternFlags.EXPANDED); /* meaning.?? */ assertThat("a{b", matches(exp)); assertThat("a[b", not(matches(exp))); exp = HsrePattern.compile("a(?#foo)b", PatternFlags.ADVANCED); assertThat("ab", matches(exp)); exp = HsrePattern.compile("a(?!foo)b", PatternFlags.ADVANCED); assertThat("ab", matches(exp)); assertCatchCompileTime("a(?&)b"); exp = HsrePattern.compile("[\\r][\\b][\\f][\\a][\\e][\\v][\\t]", PatternFlags.ADVANCED); assertThat("\r\b\f\007\033\u000b\t", matches(exp)); assertCatchCompileTime("\\c"); assertCatchCompileTime("\\"); exp = HsrePattern.compile("\\cC\\B\\w\\D\\S\\W", PatternFlags.ADVANCED); assertThat("\u0003\\_!$@", matches(exp)); exp = HsrePattern.compile("[\\uABCD][\\uEF89][\\U0001039F]?", PatternFlags.ADVANCED); assertThat("\uABCD\uEF89", matches(exp)); HsrePattern.compile(".*[[:<:]].*[[:>:]].*", PatternFlags.ADVANCED); /* TODO:This works against C++, but doesn't work here. It's deprecated, though. */ // assertThat("^%*&^AbulBakr@#$#@$", matches(exp)); exp = HsrePattern.compile("*a*b$a$", PatternFlags.BASIC); assertThat("*aaab$a", matches(exp)); exp = HsrePattern.compile("^q^b$c$", PatternFlags.BASIC); assertThat("q^b$c", matches(exp)); assertCatchCompileTime("(?b)\\"); exp = HsrePattern.compile("\\(a|b\\)", PatternFlags.BASIC); assertThat("a|b", matches(exp, new String[]{"a|b"})); exp = HsrePattern.compile("[ab]", PatternFlags.BASIC); assertThat("a", matches(exp)); exp = HsrePattern.compile("\\(.*\\)\\<\\(.*\\)\\>\\(.*\\)", PatternFlags.BASIC); /* Amazingly, this works in this form in BASIC */ assertThat("^%*&^AbulBakr@#$#@$", matches(exp, new String[]{"^%*&^", "AbulBakr", "@#$#@$"})); } }
CETONI-Software/sila_cetoni_pumps
sila_cetoni/pumps/syringepumps/sila/syringepump_service/generated/forcemonitoringservice/forcemonitoringservice_base.py
<reponame>CETONI-Software/sila_cetoni_pumps from __future__ import annotations from abc import ABC, abstractmethod from queue import Queue from typing import Any, Dict, Optional from sila2.framework import FullyQualifiedIdentifier from sila2.server import FeatureImplementationBase from .forcemonitoringservice_types import ( ClearForceSafetyStop_Responses, DisableForceMonitoring_Responses, EnableForceMonitoring_Responses, Force, SetForceLimit_Responses, ) class ForceMonitoringServiceBase(FeatureImplementationBase, ABC): _ForceSensorValue_producer_queue: Queue[Force] _ForceLimit_producer_queue: Queue[Force] _MaxDeviceForce_producer_queue: Queue[Force] _ForceMonitoringEnabled_producer_queue: Queue[bool] _ForceSafetyStopActive_producer_queue: Queue[bool] def __init__(self): """ Functionality to control the force monitoring, read the force sensor and set a custom force limit for pump devices that support this functionality such as Nemesys S and Nemesys M. """ self._ForceSensorValue_producer_queue = Queue() self._ForceLimit_producer_queue = Queue() self._MaxDeviceForce_producer_queue = Queue() self._ForceMonitoringEnabled_producer_queue = Queue() self._ForceSafetyStopActive_producer_queue = Queue() def update_ForceSensorValue(self, ForceSensorValue: Force, queue: Optional[Queue[Force]] = None): """ The currently measured force as read by the force sensor. This method updates the observable property 'ForceSensorValue'. """ if queue is None: queue = self._ForceSensorValue_producer_queue queue.put(ForceSensorValue) def ForceSensorValue_on_subscription( self, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> Optional[Queue[Force]]: """ The currently measured force as read by the force sensor. This method is called when a client subscribes to the observable property 'ForceSensorValue' :param metadata: The SiLA Client Metadata attached to the call :return: Optional `Queue` that should be used for updating this property. If None, the default Queue will be used. """ pass def update_ForceLimit(self, ForceLimit: Force, queue: Optional[Queue[Force]] = None): """ The current force limit. This method updates the observable property 'ForceLimit'. """ if queue is None: queue = self._ForceLimit_producer_queue queue.put(ForceLimit) def ForceLimit_on_subscription(self, *, metadata: Dict[FullyQualifiedIdentifier, Any]) -> Optional[Queue[Force]]: """ The current force limit. This method is called when a client subscribes to the observable property 'ForceLimit' :param metadata: The SiLA Client Metadata attached to the call :return: Optional `Queue` that should be used for updating this property. If None, the default Queue will be used. """ pass def update_MaxDeviceForce(self, MaxDeviceForce: Force, queue: Optional[Queue[Force]] = None): """ The maximum device force (i.e. the maximum force the pump hardware can take in continuous operation). This method updates the observable property 'MaxDeviceForce'. """ if queue is None: queue = self._MaxDeviceForce_producer_queue queue.put(MaxDeviceForce) def MaxDeviceForce_on_subscription( self, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> Optional[Queue[Force]]: """ The maximum device force (i.e. the maximum force the pump hardware can take in continuous operation). This method is called when a client subscribes to the observable property 'MaxDeviceForce' :param metadata: The SiLA Client Metadata attached to the call :return: Optional `Queue` that should be used for updating this property. If None, the default Queue will be used. """ pass def update_ForceMonitoringEnabled(self, ForceMonitoringEnabled: bool, queue: Optional[Queue[bool]] = None): """ Whether force monitoring is enabled. This method updates the observable property 'ForceMonitoringEnabled'. """ if queue is None: queue = self._ForceMonitoringEnabled_producer_queue queue.put(ForceMonitoringEnabled) def ForceMonitoringEnabled_on_subscription( self, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> Optional[Queue[bool]]: """ Whether force monitoring is enabled. This method is called when a client subscribes to the observable property 'ForceMonitoringEnabled' :param metadata: The SiLA Client Metadata attached to the call :return: Optional `Queue` that should be used for updating this property. If None, the default Queue will be used. """ pass def update_ForceSafetyStopActive(self, ForceSafetyStopActive: bool, queue: Optional[Queue[bool]] = None): """ Whether force safety stop is active. This method updates the observable property 'ForceSafetyStopActive'. """ if queue is None: queue = self._ForceSafetyStopActive_producer_queue queue.put(ForceSafetyStopActive) def ForceSafetyStopActive_on_subscription( self, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> Optional[Queue[bool]]: """ Whether force safety stop is active. This method is called when a client subscribes to the observable property 'ForceSafetyStopActive' :param metadata: The SiLA Client Metadata attached to the call :return: Optional `Queue` that should be used for updating this property. If None, the default Queue will be used. """ pass @abstractmethod def ClearForceSafetyStop(self, *, metadata: Dict[FullyQualifiedIdentifier, Any]) -> ClearForceSafetyStop_Responses: """ Clear/acknowledge a force safety stop. :param metadata: The SiLA Client Metadata attached to the call """ pass @abstractmethod def EnableForceMonitoring( self, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> EnableForceMonitoring_Responses: """ Enable the force monitoring. :param metadata: The SiLA Client Metadata attached to the call """ pass @abstractmethod def DisableForceMonitoring( self, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> DisableForceMonitoring_Responses: """ Disable the force monitoring. :param metadata: The SiLA Client Metadata attached to the call """ pass @abstractmethod def SetForceLimit( self, ForceLimit: Force, *, metadata: Dict[FullyQualifiedIdentifier, Any] ) -> SetForceLimit_Responses: """ Set a custom limit. :param ForceLimit: The force limit to set. If higher than MaxDeviceForce, MaxDeviceForce will be used instead. :param metadata: The SiLA Client Metadata attached to the call """ pass