repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
icclab/watchtower
README.md
4856
*Please note that all watchtower components are under heavy development and the norm is that things will break. Please be patient with us until the first stable release.* <div align="center"> <img src="https://raw.githubusercontent.com/icclab/watchtower-common/master/watchtower.png" alt="Watchtower" title="Watchtower"> </div> # Overview This repository provides documentation for **Watchtower** and pointers to the other repositories that make up the system. ### Features The following are partially or fully implemented features: * Automated Cloud Incident Lifecycle Management * Flexible API designed for easy integration of 3rd Party Solutions * Designed with scalability in mind * Integrated with HP Monasca, Apache Kafka, Camunda, and Rundeck * Multi-tenant support ### Components As of v1.0.0, it has 6 components of which four provide running services: * **watchtower-common** - contains common, reusable, code for all watchtower components. It facilitates communication between components through common objects and provides Json serialization for them * **watchtower-monitoring** - its primary role is to get, process, and forward events from the monitoring solutions to **watchtower-workflow** * **watchtower-automation** - handles communication with automation engines * **watchtower-workflow** - provides an interface between the workflow engine and the rest of Watchtower's components * **watchtower-workflow-camunda** - is a component of watchtower which is deployed onto Camunda and contains both the BPM workflow and the REST service to which **watchtower-workflow** connects * **ansible-watchtower** – is Ansible role script which allows easy installation of Watchtower on a single host ### Roadmap The current roadmap is focused on extending current functionality through additional components: * Python client * User interface in Horizon * Anomaly detection and prediction in Monasca * Event aggregation and correlation * Root cause analysis tools in Horizon * Integration with Keystone or another Identity Management Solution * Integration with Hurdle and Cyclops # Getting started Soon to come! # Repositories | Component | Status | |-----------|--------| | [watchtower-common](https://github.com/icclab/watchtower-common) | [![Build Status](https://travis-ci.org/icclab/watchtower-common.svg?branch=master)](https://travis-ci.org/icclab/watchtower-common) [![Coverage Status](https://coveralls.io/repos/icclab/watchtower-common/badge.svg?branch=master)](https://coveralls.io/r/icclab/watchtower-common?branch=master) | | [watchtower-monitoring](https://github.com/icclab/watchtower-monitoring) | [![Build Status](https://travis-ci.org/icclab/watchtower-monitoring.svg?branch=master)](https://travis-ci.org/icclab/watchtower-monitoring) [![Coverage Status](https://coveralls.io/repos/icclab/watchtower-monitoring/badge.svg?branch=master)](https://coveralls.io/r/icclab/watchtower-monitoring?branch=master) | | [watchtower-automation](https://github.com/icclab/watchtower-automation) | [![Build Status](https://travis-ci.org/icclab/watchtower-automation.svg?branch=master)](https://travis-ci.org/icclab/watchtower-automation) [![Coverage Status](https://coveralls.io/repos/icclab/watchtower-automation/badge.svg?branch=master)](https://coveralls.io/r/icclab/watchtower-automation?branch=master) | | [watchtower-workflow](https://github.com/icclab/watchtower-workflow) | [![Build Status](https://travis-ci.org/icclab/watchtower-workflow.svg?branch=master)](https://travis-ci.org/icclab/watchtower-workflow) [![Coverage Status](https://coveralls.io/repos/icclab/watchtower-workflow/badge.svg?branch=master)](https://coveralls.io/r/icclab/watchtower-workflow?branch=master) | | [watchtower-workflow-camunda](https://github.com/icclab/watchtower-workflow-camunda) | [![Build Status](https://travis-ci.org/icclab/watchtower-workflow-camunda.svg?branch=master)](https://travis-ci.org/icclab/watchtower-workflow-camunda) [![Coverage Status](https://coveralls.io/repos/icclab/watchtower-workflow-camunda/badge.svg?branch=master)](https://coveralls.io/r/icclab/watchtower-workflow-camunda?branch=master) | # License Copyright 2015 Zurich University of Applied Sciences 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. # Author Information For further information or assistance please contact [**Andy Edmonds**](https://github.com/dizz).
apache-2.0
NitorCreations/willow
willow-servers/src/main/java/com/nitorcreations/willow/auth/GitHubOAuthAuthenticatingFilter.java
6779
package com.nitorcreations.willow.auth; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singletonMap; import static java.util.Collections.unmodifiableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.SimpleAccount; import org.apache.shiro.authz.Permission; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.common.collect.ImmutableMap; import mx.com.inftel.shiro.oauth2.AbstractOAuth2AuthenticatingFilter; public class GitHubOAuthAuthenticatingFilter extends AbstractOAuth2AuthenticatingFilter { private static final String SCOPE = "user:email,read:org"; private final Map<String,? extends Permission> PERMISSIONS; private final GitHubOAuthAccounts accounts; @Inject public GitHubOAuthAuthenticatingFilter(GitHubOAuthConfig config, GitHubOAuthAccounts accounts) throws IOException { setRedirectUri(config.getRedirectUri()); setClientId(config.getClientId()); setClientSecret(config.getClientSecret()); setLoginUrl("/"); this.accounts = accounts; PERMISSIONS = ImmutableMap.of( config.getOrganization() + "." + config.getAdminTeam(), Permissions.ADMIN, config.getOrganization(), Permissions.MONITOR); } @Override public String getName() { return getClass().getName(); } @Override protected String getAuthorizeURL(ServletRequest request, ServletResponse response) throws Exception { return makeStandardAuthorizeURL(request, response, "https://github.com/login/oauth/authorize", SCOPE); } @Override protected JSONObject getOAuth2Principal(ServletRequest request, ServletResponse response) throws Exception { String tokenResponse = httpPost("https://github.com/login/oauth/access_token", "client_id=" + getClientId() + "&client_secret=" + getClientSecret() + "&redirect_uri=" + encodeURL(getRedirectUri()) + "&code=" + encodeURL(request.getParameter("code"))); String token = getAccessToken(tokenResponse); Map<String,String> headers = singletonMap("Authorization", "token " + token); JSONArray memberOf = JSONTool.toArray(getOrganizations(headers), getTeams(headers)); String loginId = new JSONObject(httpGet("https://api.github.com/user", headers)).getString("login"); JSONObject ret = new JSONObject() .put("login", loginId) .put("member_of", memberOf) .put("token", token); SimpleAccount acco = doGetAuthenticationInfo(ret); accounts.add(acco); return ret; } @Override protected String getOAuth2Credentials(JSONObject principal) throws Exception { return principal.getString("login"); } private String getAccessToken(String response) throws Exception { for(String param : response.split("&")) { if(param.startsWith("access_token=")) { return decodeURL(param.substring(param.indexOf('=') + 1)); } } throw new IllegalStateException("access_token param not sent by idp"); } private List<String> getOrganizations(Map<String,String> headers) throws Exception { JSONArray organizations = new JSONArray(httpGet("https://api.github.com/user/orgs", headers)); List<String> names = new ArrayList<>(); for(int i = 0; i < organizations.length(); i++) { names.add(organizations.getJSONObject(i).getString("login")); } return Collections.unmodifiableList(names); } private List<String> getTeams(Map<String,String> headers) throws Exception { JSONArray teams = new JSONArray(httpGet("https://api.github.com/user/teams", headers)); List<String> names = new ArrayList<>(); for(int i = 0; i < teams.length(); i++) { JSONObject team = teams.getJSONObject(i); names.add(team.getJSONObject("organization").getString("login") + "." + team.getString("name")); } return Collections.unmodifiableList(names); } private String httpGet(String url, Map<String, String> headers) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); for(Map.Entry<String,String> header : headers.entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return readResponseBody(conn); } private String httpPost(String url, String data) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); try(OutputStream out = conn.getOutputStream()) { out.write(data.getBytes(UTF_8)); } return readResponseBody(conn); } @SuppressFBWarnings(value={"RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE"}, justification="null check in try-with-resources magic bytecode") private String readResponseBody(HttpURLConnection conn) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; try(InputStream in = conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream()) { for(int i = in.read(buf); i != -1; i = in.read(buf)) { baos.write(buf, 0, i); } } String body = new String(baos.toByteArray(), UTF_8); if(conn.getResponseCode() != 200) { throw new IllegalStateException(String.format("idp responded with HTTP %s %s: %s", conn.getResponseCode(), conn.getResponseMessage(), body)); } return body; } public SimpleAccount doGetAuthenticationInfo(JSONObject user) throws AuthenticationException { try { String userId = user.getString("login"); Set<String> memberOf = JSONTool.toStringSet(user.getJSONArray("member_of")); return new SimpleAccount(userId, userId, getName(), memberOf, memberShipsToPermissions(memberOf)); } catch (JSONException e) { throw new AuthenticationException(e); } } protected Set<Permission> memberShipsToPermissions(Set<String> organizations) { Set<Permission> permissions = new HashSet<>(); for(String team : organizations) { Permission permission = PERMISSIONS.get(team); if(permission != null) { permissions.add(permission); } } return unmodifiableSet(permissions); } }
apache-2.0
oaqa/baseqa
src/main/java/edu/cmu/lti/oaqa/type/answer/AnswerType_Type.java
4196
/* First created by JCasGen Sat Apr 11 19:49:33 EDT 2015 */ package edu.cmu.lti.oaqa.type.answer; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** A Named Entity type that represents the type of the answer being sought. * Updated by JCasGen Sun Apr 19 19:46:49 EDT 2015 * @generated */ public class AnswerType_Type extends Annotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (AnswerType_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = AnswerType_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new AnswerType(addr, AnswerType_Type.this); AnswerType_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new AnswerType(addr, AnswerType_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = AnswerType.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.cmu.lti.oaqa.type.answer.AnswerType"); /** @generated */ final Feature casFeat_label; /** @generated */ final int casFeatCode_label; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getLabel(int addr) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.answer.AnswerType"); return ll_cas.ll_getStringValue(addr, casFeatCode_label); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setLabel(int addr, String v) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.answer.AnswerType"); ll_cas.ll_setStringValue(addr, casFeatCode_label, v);} /** @generated */ final Feature casFeat_targetType; /** @generated */ final int casFeatCode_targetType; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public int getTargetType(int addr) { if (featOkTst && casFeat_targetType == null) jcas.throwFeatMissing("targetType", "edu.cmu.lti.oaqa.type.answer.AnswerType"); return ll_cas.ll_getRefValue(addr, casFeatCode_targetType); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setTargetType(int addr, int v) { if (featOkTst && casFeat_targetType == null) jcas.throwFeatMissing("targetType", "edu.cmu.lti.oaqa.type.answer.AnswerType"); ll_cas.ll_setRefValue(addr, casFeatCode_targetType, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public AnswerType_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_label = jcas.getRequiredFeatureDE(casType, "label", "uima.cas.String", featOkTst); casFeatCode_label = (null == casFeat_label) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_label).getCode(); casFeat_targetType = jcas.getRequiredFeatureDE(casType, "targetType", "uima.tcas.Annotation", featOkTst); casFeatCode_targetType = (null == casFeat_targetType) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_targetType).getCode(); } }
apache-2.0
ArmstrongYang/StudyShare
Python-matplotlib/scatter_demo.py
295
""" Simple demo of a scatter plot. """ import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radii plt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show()
apache-2.0
oriontribunal/CoffeeMud
com/planet_ink/coffee_mud/Abilities/Traps/Trap_CaveIn.java
4993
package com.planet_ink.coffee_mud.Abilities.Traps; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2016 Bo Zimmerman 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. */ public class Trap_CaveIn extends StdTrap { @Override public String ID() { return "Trap_CaveIn"; } private final static String localizedName = CMLib.lang().L("cave-in"); @Override public String name() { return localizedName; } @Override protected int canAffectCode() { return Ability.CAN_ROOMS; } @Override protected int canTargetCode() { return 0; } @Override protected int trapLevel() { return 22; } @Override public String requiresToSet() { return "100 pounds of wood"; } @Override public int baseRejuvTime(int level) { return 6; } @Override public List<Item> getTrapComponents() { final List<Item> V=new Vector<Item>(); for(int i=0;i<100;i++) V.add(CMLib.materials().makeItemResource(RawMaterial.RESOURCE_WOOD)); return V; } @Override public Trap setTrap(MOB mob, Physical P, int trapBonus, int qualifyingClassLevel, boolean perm) { if(P==null) return null; if(mob!=null) { final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_WOODEN); if(I!=null) super.destroyResources(mob.location(),I.material(),100); } return super.setTrap(mob,P,trapBonus,qualifyingClassLevel,perm); } @Override public boolean canSetTrapOn(MOB mob, Physical P) { if(!super.canSetTrapOn(mob,P)) return false; if(mob!=null) { final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_WOODEN); if((I==null) ||(super.findNumberOfResource(mob.location(),I.material())<100)) { mob.tell(L("You'll need to set down at least 100 pounds of wood first.")); return false; } } if(P instanceof Room) { final Room R=(Room)P; if(R.domainType()!=Room.DOMAIN_INDOORS_CAVE) { if(mob!=null) mob.tell(L("You can only set this trap in caves.")); return false; } } return true; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if((sprung) &&(affected!=null) &&(!disabled()) &&(tickDown>=0)) { if(((msg.targetMinor()==CMMsg.TYP_LEAVE) ||(msg.targetMinor()==CMMsg.TYP_ENTER) ||(msg.targetMinor()==CMMsg.TYP_FLEE)) &&(msg.amITarget(affected))) { msg.source().tell(L("The cave-in prevents entry or exit from here.")); return false; } } return super.okMessage(myHost,msg); } @Override public void spring(MOB target) { if((target!=invoker())&&(target.location()!=null)) { if((doesSaveVsTraps(target)) ||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))) target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) setting off a cave-in!")); else if(target.location().show(target,target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> trigger(s) a cave-in!"))) { super.spring(target); if((affected!=null) &&(affected instanceof Room)) { final Room R=(Room)affected; for(int i=0;i<R.numInhabitants();i++) { final MOB M=R.fetchInhabitant(i); if((M!=null)&&(M!=invoker())) if(invoker().mayIFight(M)) { final int damage=CMLib.dice().roll(trapLevel()+abilityCode(),20,1); CMLib.combat().postDamage(invoker(),M,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,Weapon.TYPE_BASHING,L("The cave-in <DAMAGE> <T-NAME>!")); } } } } } } }
apache-2.0
qq54903099/atom-lang
dalgen/gen.bat
116
@echo off echo ¿ªÊ¼Éú³ÉµÄDAS´úÂë[build.xml]... rm -rf ./target rm -rf ./logs call ant -f ./build.xml rem exit
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Iresine/Iresine pilgeri/README.md
172
# Iresine pilgeri Suess. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mirkosertic/Bytecoder
core/src/main/java/de/mirkosertic/bytecoder/backend/wasm/ast/I32Or.java
902
/* * Copyright 2018 Mirko Sertic * * 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.mirkosertic.bytecoder.backend.wasm.ast; import de.mirkosertic.bytecoder.ssa.Expression; public class I32Or extends BinaryExpression { I32Or(final WASMValue left, final WASMValue right, final Expression expression) { super(left, right,"i32.or", (byte) 0x72, expression); } }
apache-2.0
OHDSI/Circe
js/modules/cohortbuilder/components/ConditionOccurrenceTemplate.html
6023
<div class="criteriaSection" data-bind="with: Criteria"> <div style="position: relative"> <table class="criteriaTable"> <col style="width:16px" /> <col /> <tr> <td colspan="2"> a condition occurrence of <select data-bind="options: $component.expression.ConceptSets.sorted, optionsText: function(item) { return item.name }, optionsCaption: 'Any Condition', optionsValue: 'id', value: CodesetId" class="mediumInputField"> </select><button type="button" class="btn btn-default addConceptSet" aria-expanded="false"><span class="glyphicon glyphicon-plus-sign"></span></button> </td> </tr> <tr data-bind="if: First() != null, visible: First() != null"> <td><img data-bind="click: function() { $component.removeCriterion('First') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td><div style="padding-left: 5px">for the first time in the person's history</div></td> </tr> <tr data-bind="if: OccurrenceStartDate() != null, visible: OccurrenceStartDate() != null"> <td><img data-bind="click: function() { $component.removeCriterion('OccurrenceStartDate') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> occurrence start is: <date-range params="Range: OccurrenceStartDate"></date-range> </td> </tr> <tr data-bind="if: OccurrenceEndDate() != null, visible: OccurrenceEndDate() != null"> <td><img data-bind="click: function() { $component.removeCriterion('OccurrenceEndDate') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> occurrence end is: <date-range params="Range: OccurrenceEndDate"></date-range> </td> </tr> <tr data-bind="if: ConditionType() != null, visible: ConditionType() != null"> <td><img data-bind="click: function() { $component.removeCriterion('ConditionType') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> Condition Type is: <concept-list params="PickerParams: { DefaultDomain: 'Condition Type', DefaultQuery: ''}, ConceptList: ConditionType()"></concept-list> </td> </tr> <tr data-bind="if: StopReason() != null, visible: StopReason() != null"> <td><img data-bind="click: function() { $component.removeCriterion('StopReason') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> with a Stop Reason <text-filter-input params="Filter: StopReason"></text-filter-input> </td> </tr> <tr data-bind="if: ConditionSourceConcept() != null, visible: ConditionSourceConcept() != null"> <td><img data-bind="click: function() { $component.removeCriterion('ConditionSourceConcept') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> <div> Condition Source Concept is <select data-bind="options: $component.expression.ConceptSets, optionsText: function(item) { return item.name }, optionsCaption: 'Select Concept Set...', optionsValue: 'id', value: ConditionSourceConcept()" class="mediumInputField"> </select> </div> </td> </tr> <tr data-bind="if: Age() != null, visible: Age() != null"> <td><img data-bind="click: function() { $component.removeCriterion('Age') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> with age <numeric-range params="Range: Age"></numeric-range> </td> </tr> <tr data-bind="if: Gender() != null, visible: Gender() != null"> <td><img data-bind="click: function() { $component.removeCriterion('Gender') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> <div> with a gender of: <concept-list params="PickerParams: { DefaultDomain: 'Gender', DefaultQuery: ''}, ConceptList: Gender()"></concept-list> </div> </td> </tr> <!-- <tr data-bind="if: PriorEnrollDays() != null, visible: PriorEnrollDays() != null"> <td><img data-bind="click: function() { $component.removeCriterion('PriorEnrollDays') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td>with at least <span contenteditable="true" class="numericInputField dropdown" data-bind="htmlValue: PriorEnrollDays.numeric(), ko_autocomplete: { source: $component.options.dayOptions, minLength: 0, maxShowItems: 10, scroll: true }" />days of observation prior to diagnosis </td> </tr> <tr data-bind="if: AfterEnrollDays() != null, visible: AfterEnrollDays() != null"> <td><img data-bind="click: function() { $component.removeCriterion('AfterEnrollDays') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td>with at least <span contenteditable="true" class="numericInputField dropdown" data-bind="htmlValue: AfterEnrollDays.numeric(), ko_autocomplete: { source: $component.options.dayOptions, minLength: 0, maxShowItems: 10, scroll: true }" />days of observation after diagnosis </td> </tr> --> <tr data-bind="if: ProviderSpecialty() != null, visible: ProviderSpecialty() != null"> <td><img data-bind="click: function() { $component.removeCriterion('ProviderSpecialty') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> <div> with a Provider Specialty of: <concept-list params="PickerParams: { DefaultDomain: 'Provider Specialty' }, ConceptList: ProviderSpecialty()"></concept-list> </div> </td> </tr> <tr data-bind="if: VisitType() != null, visible: VisitType() != null"> <td><img data-bind="click: function() { $component.removeCriterion('VisitType') }" class="deleteIcon" src="images/cohortbuilder/delete.png" /></td> <td> with a Visit occurrance of: <concept-list params="PickerParams: { DefaultDomain: 'Visit', DefaultQuery: ''}, ConceptList: VisitType()"></concept-list> </td> </tr> </table> </div> <div class="addCriterion" data-bind="ddSlickAction: $component.addCriterionSettings"></div> </div>
apache-2.0
jianzhichun/mongodb-spring-cloud-config-server
src/main/frontend/src/app/app.routes.ts
211
import { Routes } from '@angular/router'; import { EditorComponent } from './editor/editor.component' export const routes: Routes = [ { path: 'config/:id', component: EditorComponent } ];
apache-2.0
mdoering/backbone
life/Plantae/Pteridophyta/Polypodiopsida/Hymenophyllales/Hymenophyllaceae/Hymenophyllum/Sphaerocionium capillare/README.md
189
# Sphaerocionium capillare (Desv.) Copel. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
lq2677/myweather
app/src/main/java/com/coolweather/android/gson/AQI.java
223
package com.coolweather.android.gson; /** * Created by LanQ on 2017/8/21 0021. */ public class AQI { public AQICity city; public class AQICity{ public String aqi; public String pm25; } }
apache-2.0
youtongluan/sumk
src/main/java/org/yx/validate/FieldParameterHolder.java
2939
/** * Copyright (C) 2016 - 2030 youtongluan. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yx.validate; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.yx.annotation.spec.ParamSpec; import org.yx.annotation.spec.Specs; import org.yx.util.CollectionUtil; public final class FieldParameterHolder { private static final ConcurrentMap<Class<?>, List<FieldParameterInfo>> map = new ConcurrentHashMap<>(); public static void put(Class<?> clz, List<FieldParameterInfo> infos) { if (clz == null || infos == null || infos.isEmpty()) { return; } map.put(clz, infos); } public static Set<Class<?>> keys() { return new HashSet<>(map.keySet()); } public static List<FieldParameterInfo> get(Class<?> clz) { return map.get(clz); } public static Map<Field, FieldParameterInfo> getFieldParameterMap(Class<?> clz) { List<FieldParameterInfo> infos = get(clz); if (infos == null) { return Collections.emptyMap(); } Map<Field, FieldParameterInfo> infoMap = new HashMap<>(); for (FieldParameterInfo info : infos) { infoMap.put(info.getField(), info); } return infoMap; } public static void registerFieldInfo(final Class<?> clazz) { if (clazz.isArray()) { registerFieldInfo(clazz.getComponentType()); return; } if (!Validators.supportComplex(clazz)) { return; } if (get(clazz) != null) { return; } List<FieldParameterInfo> list = new ArrayList<>(); Class<?> tempClz = clazz; while (tempClz != null && !tempClz.getName().startsWith("java.")) { Field[] fs = tempClz.getDeclaredFields(); for (Field f : fs) { if (Modifier.isStatic(f.getModifiers())) { continue; } ParamSpec p = Specs.extractParamField(f); if (p == null) { continue; } FieldParameterInfo info = new FieldParameterInfo(p, f); if (!info.maybeCheck()) { continue; } list.add(info); if (info.isComplex()) { registerFieldInfo(info.getParamType()); } } tempClz = tempClz.getSuperclass(); } if (list.size() > 0) { put(clazz, CollectionUtil.unmodifyList(list.toArray(new FieldParameterInfo[list.size()]))); } } }
apache-2.0
FrodeRanders/ensure
ppe/src/main/java/eu/ensure/ppe/AggregationLevelScore.java
1778
package eu.ensure.ppe; import org.gautelis.vopn.lang.Number; import org.gautelis.vopn.statistics.MovingAverage; import eu.ensure.ppe.model.Consequence; import java.util.Collection; import java.util.LinkedList; public class AggregationLevelScore { public static final double FAILURE_SCORE = 0.0; final String id; // Id of aggregation final String name; final double score; final double stdDev; final double cv; final long datasetSize; final Collection<String> storyLine; final Collection<Consequence> consequences; AggregationLevelScore(String aggrId, String aggrName, MovingAverage stats, Collection<String> storyLine, Collection<Consequence> consequences) { this.id = aggrId; this.name = aggrName; this.storyLine = storyLine; if (null == consequences) { this.consequences = new LinkedList<Consequence>(); } else { this.consequences = consequences; } // this.score = Number.roundTwoDecimals(stats.getAverage()); this.stdDev = Number.roundTwoDecimals(stats.getStdDev()); this.cv = Number.roundTwoDecimals(stats.getCV()); this.datasetSize = stats.getCount(); } public String getId() { return id; } public String getName() { return name; } public double getScore() { return score; } public double getStdDev() { return stdDev; } public double getCV() { return cv; } public long getDatasetSize() { return datasetSize; } public Collection<String> getStoryLine() { return storyLine; } public Collection<Consequence> getConsequences() { return consequences; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/DescribePlacementRequest.java
5307
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iot1clickprojects.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iot1click-projects-2018-05-14/DescribePlacement" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribePlacementRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The name of the placement within a project. * </p> */ private String placementName; /** * <p> * The project containing the placement to be described. * </p> */ private String projectName; /** * <p> * The name of the placement within a project. * </p> * * @param placementName * The name of the placement within a project. */ public void setPlacementName(String placementName) { this.placementName = placementName; } /** * <p> * The name of the placement within a project. * </p> * * @return The name of the placement within a project. */ public String getPlacementName() { return this.placementName; } /** * <p> * The name of the placement within a project. * </p> * * @param placementName * The name of the placement within a project. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePlacementRequest withPlacementName(String placementName) { setPlacementName(placementName); return this; } /** * <p> * The project containing the placement to be described. * </p> * * @param projectName * The project containing the placement to be described. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * <p> * The project containing the placement to be described. * </p> * * @return The project containing the placement to be described. */ public String getProjectName() { return this.projectName; } /** * <p> * The project containing the placement to be described. * </p> * * @param projectName * The project containing the placement to be described. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribePlacementRequest withProjectName(String projectName) { setProjectName(projectName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPlacementName() != null) sb.append("PlacementName: ").append(getPlacementName()).append(","); if (getProjectName() != null) sb.append("ProjectName: ").append(getProjectName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribePlacementRequest == false) return false; DescribePlacementRequest other = (DescribePlacementRequest) obj; if (other.getPlacementName() == null ^ this.getPlacementName() == null) return false; if (other.getPlacementName() != null && other.getPlacementName().equals(this.getPlacementName()) == false) return false; if (other.getProjectName() == null ^ this.getProjectName() == null) return false; if (other.getProjectName() != null && other.getProjectName().equals(this.getProjectName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPlacementName() == null) ? 0 : getPlacementName().hashCode()); hashCode = prime * hashCode + ((getProjectName() == null) ? 0 : getProjectName().hashCode()); return hashCode; } @Override public DescribePlacementRequest clone() { return (DescribePlacementRequest) super.clone(); } }
apache-2.0
ntgnst/ProjectManagementSystem
PMS.Data/Models/Status.cs
389
using System; using System.Collections.Generic; namespace PMS.Data.Models { public partial class Status { public Status() { Issue = new HashSet<Issue>(); } public int Id { get; set; } public string Name { get; set; } public short Priority { get; set; } public ICollection<Issue> Issue { get; set; } } }
apache-2.0
SSEHUB/EASyProducer
Plugins/VarModel/Utils/src/net/ssehub/easy/basics/modelManagement/VersionedModelInfos.java
21315
/* * Copyright 2009-2015 University of Hildesheim, Software Systems Engineering * * 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 net.ssehub.easy.basics.modelManagement; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Stores model information objects of the same version. * * @param <M> the specific type of model * * @author Holger Eichelberger */ public class VersionedModelInfos <M extends IModel> { private Version version; private List<ModelInfo<M>> infos = new ArrayList<ModelInfo<M>>(); /** * Creates a new versioned model information container. * * @param version the version of this container (may be <b>null</b>) */ public VersionedModelInfos(Version version) { this.version = version; } /** * Adds a model information object. * * @param info the object to be added * @throws IllegalArgumentException if the version of <code>info</code> does * not match {@link #version} or the name of <code>info</code> does not match * the name of the first stored model information object (if there is any) */ public void add(ModelInfo<M> info) { assert null != info; if (!Version.equals(info.getVersion(), version)) { throw new IllegalArgumentException("versions do not match"); } if (!infos.isEmpty()) { ModelInfo<M> first = infos.get(0); if (!first.getName().equals(info.getName())) { throw new IllegalArgumentException("names do not match"); } } for (int i = 0; i < infos.size(); i++) { ModelInfo<M> tmp = infos.get(i); if (isSame(tmp.getLocation(), info.getLocation()) && tmp.getLoader() == info.getLoader()) { throw new IllegalArgumentException("URI and loader match"); } } // multiple equal URIs may exist due to different loaders -> any shall be fine infos.add(info); } /** * Checks two URIs for equality. * * @param uri1 the first URI (may be <b>null</b>) * @param uri2 the second URI (may be <b>null</b>) * @return <code>true</code> if both are the same, <code>false</code> else */ public static final boolean isSame(URI uri1, URI uri2) { return (null == uri1 && uri1 == uri2) || (null != uri1 && uri1.equals(uri2)); } /** * Returns the specified model information object. * * @param index the index of the object to be returned * @return the specified object * @throws IndexOutOfBoundsException if <code>index&lt;0 * || index&gt;={@link #size()}</code> */ public ModelInfo<M> get(int index) { return infos.get(index); } /** * Returns the model information objects with <code>model</code> as resolved model. * * @param model the (resolved) model to search for * @return the model information object or <b>null</b> if there is none */ public ModelInfo<M> get(M model) { ModelInfo<M> result = null; int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> tmp = infos.get(i); if (tmp.getResolved() == model) { result = tmp; } } return result; } /** * Returns the model information objects with <code>uri</code> as location. * * @param uri the URI to search for * @return the model information object or <b>null</b> if there is none */ public ModelInfo<M> get(URI uri) { ModelInfo<M> result = null; int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> tmp = infos.get(i); if ((null == uri && tmp.getLocation() == uri) || (null != uri && uri.equals(tmp.getLocation()))) { result = tmp; } } return result; } /** * Returns the number of contained version information objects. * * @return the number of version information objects */ public int size() { return infos.size(); } /** * Removes the specified model information object. * @param index the index of the object to be returned * @return the removed object * @throws IndexOutOfBoundsException if <code>index&lt;0 * || index&gt;={@link #size()}</code> */ public ModelInfo<M> remove(int index) { return infos.remove(index); } /** * Removes all stored model information objects. */ public void clear() { infos.clear(); } /** * Removes the specified model information object. * @param info the information object to be removed * @return <code>true</code> if successful <code>false</code> else */ public boolean remove(ModelInfo<M> info) { return infos.remove(info); } /** * Returns the version all information objects in this instance * are assigned to. * * @return the version */ public Version getVersion() { return version; } /** * Returns the model information with the exact match to <code>uri</code>. * * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @return the matching model information (or <b>null</b> if none matches) */ public List<ModelInfo<M>> getByEqualUri(URI uri) { List<ModelInfo<M>> result = null; if (null != uri) { uri = uri.normalize(); int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> info = infos.get(i); if (null != info.getLocation() && uri.equals(info.getLocation())) { if (null == result) { result = new ArrayList<ModelInfo<M>>(); } result.add(info); } } } return result; } /** * Returns the model information with the closest match * to <code>uri</code>, i.e. in closest in the same hierarchy path. * * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ public ModelInfo<M> getByClosestUri(URI uri, List<String> modelPath) { return getByClosestUri(infos, uri, modelPath); } /** * Returns the model information from <code>infos</code> with the closest match * to <code>uri</code>, i.e. in closest in the same hierarchy path. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to match with (may be <b>null</b> then the first * information object is returned) * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ public static <M extends IModel> ModelInfo<M> getByClosestUri(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; int size = infos.size(); if (size > 0) { if (null == uri/* || null == version*/) { result = infos.get(0); } else { // precedence to same file for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); if (isSame(uri, info.getLocation())) { result = info; } } // precedence to own hierarchy String searchUriText = pathWithoutLastFragment(uri.normalize()); if (null == result) { // search according to hierarchical IVML convention result = search(infos, searchUriText, modelPath); // this may fail, in particular for parent projects imported according to EASy convention if (null == result) { result = searchOnParentLevel(infos, uri, modelPath); } // search in folders on the same level if (null == result) { result = searchOnSameFolderLevel(infos, uri, modelPath); } } // containment in model path if (null != modelPath) { for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); for (int m = 0; null == result && m < modelPath.size(); m++) { if (isMatching(info.getLocation().toString(), modelPath.get(m), false)) { result = info; } } } } } } return result; } /** * Searches for the best match according to the IVML search conventions, first down along the given * URI, then up along the hierarchy. * * @param <M> the model type * @param infos the information objects to be considered * @param searchUriText the search folder URI as text * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ private static <M extends IModel> ModelInfo<M> search(List<ModelInfo<M>> infos, String searchUriText, List<String> modelPath) { ModelInfo<M> result = null; int matchLength = 0; // 0 == b: down, 1 == b up in URI hierarchy for (int b = 0; null == result && 0 == matchLength && b < 2; b++) { int size = infos.size(); for (int i = 0; i < size; i++) { ModelInfo<M> info = infos.get(i); URI infoUri = info.getLocation(); if (null == infoUri) { continue; } String infoUriText = pathWithoutLastFragment(infoUri); if (isMatching(searchUriText, modelPath, infoUriText, 0 == b)) { // the first match is a candidate boolean isBestMatch = (0 == matchLength); // down, then minimize match length isBestMatch |= (0 == b && infoUriText.length() < matchLength); // up, then maximize match length isBestMatch |= (1 == b && infoUriText.length() > matchLength); if (isBestMatch) { result = infos.get(i); matchLength = infoUriText.length(); } } } } return result; } /** * Searches for the best match within the parent-parent folders of <code>uri</code> if that folder starts with * ".". This enables cross-links among parent models according to the convention EASy places imported IVML files. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to start searching * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information (or <b>null</b> if none matches) */ private static <M extends IModel> ModelInfo<M> searchOnParentLevel(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; if (isFileScheme(uri)) { File uriFile = new File(uri); File uriParent = uriFile.getParentFile(); File parent = uriParent; // step two levels up... // uri = EASy/.core/core.ivml; uri-parent = EASy/.core; uri-parent-parent = EASy if (null != parent) { if (parent.getName().startsWith(".")) { // do not consider other parents, EASy-folder not known here! parent = parent.getParentFile(); } else { parent = null; } } if (null != parent) { File[] siblings = parent.listFiles(); if (null != siblings) { for (int s = 0; null == result && s < siblings.length; s++) { File sibling = siblings[s]; if (sibling.isDirectory() && !sibling.equals(uriParent)) { URI siblingUri = sibling.toURI().normalize(); result = search(infos, siblingUri.toString(), modelPath); } } } } } return result; } /** * Search in folders on the level of the parent folder of <code>uri</code>. * * @param <M> the model type * @param infos the information objects to be considered * @param uri the URI to start searching * @param modelPath additional URIs prefixes which shall be considered for importing, * similar to the Java classpath, may be <b>null</b> * @return the matching model information but only if this is unique */ private static <M extends IModel> ModelInfo<M> searchOnSameFolderLevel(List<ModelInfo<M>> infos, URI uri, List<String> modelPath) { ModelInfo<M> result = null; if (isFileScheme(uri)) { List<ModelInfo<M>> tmp = new ArrayList<ModelInfo<M>>(); File uriFile = new File(uri).getParentFile(); File searchFolder = uriFile.getParentFile(); if (null != searchFolder) { File[] files = searchFolder.listFiles(); for (int f = 0; null != files && f < files.length; f++) { File file = files[f]; if (file.isDirectory() && !file.equals(uriFile)) { String searchUriText = file.toURI().normalize().toString(); ModelInfo<M> searchResult = search(infos, searchUriText, modelPath); if (null != searchResult) { tmp.add(searchResult); } } } } if (1 == tmp.size()) { result = tmp.get(0); } // else -> result = null; // if not found or multiple are found } return result; } /** * Returns whether the given URI is a file (file scheme). * * @param uri the URI to test for * @return <code>true</code> if it is a file, <code>false</code> else */ public static boolean isFileScheme(URI uri) { return "file".equals(uri.getScheme()); } /** * Checks whether the <code>searchUriText</code> (with precedence) ore one of the * <code>modelPath</code> URI paths match <code>importUri</code>, i.e. whether * <code>importUri</code> is an appropriate URI for import. * * @param searchUriText the textual URI of the model stating the import * @param modelPath additional URI paths, may be <b>null</b> * @param importUriText the URI path of the model being considered for import * @param contained prefer contained or containing URIs * @return <code>true</code> if the specified data match, <code>false</code> if not */ private static boolean isMatching(String searchUriText, List<String> modelPath, String importUriText, boolean contained) { boolean matches = isMatching(searchUriText, importUriText, contained); if (!matches && null != modelPath) { int size = modelPath.size(); for (int p = 0; !matches && p < size; p++) { matches = isMatching(searchUriText, modelPath.get(p), contained); } } return matches; } /** * Checks whether the <code>searchUriText</code> and <code>importUri</code> match. * * @param searchUriText the textual URI of the model stating the import * @param importUriText the URI path of the model being considered for import * @param contained prefer contained or containing URIs * @return <code>true</code> if the specified data match, <code>false</code> if not */ private static boolean isMatching(String searchUriText, String importUriText, boolean contained) { return contained ? importUriText.startsWith(searchUriText) : searchUriText.startsWith(importUriText); } /** * Returns the prefix path of the given <code>uri</code> without the last fragment. * * @param uri the URI to be considered * @return the prefix path if possible, the <code>uri</code> else */ public static String pathWithoutLastFragment(URI uri) { String uriText = uri.toString(); int pos = uriText.lastIndexOf('/'); if (pos > 0) { uriText = uriText.substring(0, pos + 1); } return uriText; } /** * Adds all model information objects to the given <code>list</code>. * * @param list the list to be modified as a side effect (may be <b>null</b> * then a list is created) * @return <code>list</code> or the created list */ public List<ModelInfo<M>> toList(List<ModelInfo<M>> list) { if (null == list) { list = new ArrayList<ModelInfo<M>>(); } for (int i = 0; i < infos.size(); i++) { list.add(infos.get(i)); } return list; } /** * Returns the textual representation of this instance. * * @return the textual representation */ public String toString() { return version + " " + infos; } /** * Finds a model information object based on a give URI. * * @param uri the URI to find the information object * @return the information object or <b>null</b> if not found */ public ModelInfo<M> find(URI uri) { ModelInfo<M> result = null; if (null != uri) { int size = infos.size(); for (int i = 0; null == result && i < size; i++) { ModelInfo<M> info = infos.get(i); if (uri.equals(info.getLocation())) { result = info; } } } return result; } /** * Retrieves the version model information container with the specified version. * * @param <M> the specific type of model * * @param infos a list of model information containers (may be <b>null</b>) * @param version the version to retrieve * @return the first matching container */ public static <M extends IModel> VersionedModelInfos<M> find(List<VersionedModelInfos<M>> infos, Version version) { VersionedModelInfos<M> result = null; if (null != infos) { for (int i = 0; null == result && i < infos.size(); i++) { VersionedModelInfos<M> info = infos.get(i); if (Version.equals(info.getVersion(), version)) { result = info; } } } return result; } /** * Returns the model information object with highest version number from <code>list</code>. * Unspecified versions are treated as implicit minimum. * * @param <M> the actual model type * @param list the list of model information objects to determine the maximum from (may be <b>null</b>) * @return the maximum version */ public static <M extends IModel> ModelInfo<M> maxVersion(List<ModelInfo<M>> list) { ModelInfo<M> result = null; if (null != list) { Version highest = null; for (int i = 0, n = list.size(); i < n; i++) { ModelInfo<M> tmp = list.get(i); Version tmpVersion = tmp.getVersion(); if (null == result || Version.compare(tmpVersion, highest) > 0) { result = tmp; highest = tmpVersion; } } } return result; } }
apache-2.0
dtgm/chocolatey-packages
automatic/_output/firefox-nightly/61.0.1.2018032100/tools/chocolateyUninstall.ps1
817
$packageName = 'firefox-nightly' $softwareVersion = '61.0.1.2018032100-alpha' -Replace "^(\d+)\.(\d+)\.(\d+)[^-]+-([a-z]).*",'$1.$2$4$3' $softwareName = "Nightly $softwareVersion*" $installerType = 'exe' $silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' $validExitCodes = @(0) [array]$key = Get-UninstallRegistryKey -SoftwareName $softwareName $key | ForEach-Object {   Uninstall-ChocolateyPackage -PackageName $packageName `                               -FileType $installerType `                               -SilentArgs $($silentArgs) `                               -File $($_.UninstallString.Replace('"','')) `                               -ValidExitCodes $validExitCodes }
apache-2.0
boyan-velinov/cf-mta-deploy-service
com.sap.cloud.lm.sl.cf.core/src/test/java/com/sap/cloud/lm/sl/cf/core/liquibase/TransformFilterColumnTest.java
3357
package com.sap.cloud.lm.sl.cf.core.liquibase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.sap.cloud.lm.sl.cf.core.model.CloudTarget; import com.sap.cloud.lm.sl.cf.core.util.ConfigurationEntriesUtil; public class TransformFilterColumnTest { private TransformFilterColumn transformFilterColumn = new TransformFilterColumn(); @Test public void testSplitTargetSpaceValue() { CloudTarget targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue("org space"); assertEquals("org", targetSpace.getOrg()); assertEquals("space", targetSpace.getSpace()); targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue("orgspace"); assertEquals("", targetSpace.getOrg()); assertEquals("orgspace", targetSpace.getSpace()); targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue("org test space sap"); assertEquals("org", targetSpace.getOrg()); assertEquals("test space sap", targetSpace.getSpace()); targetSpace = ConfigurationEntriesUtil.splitTargetSpaceValue(""); assertEquals("", targetSpace.getOrg()); assertEquals("", targetSpace.getSpace()); } @Test public void testTransformData() { Map<Long, String> retrievedData = new HashMap<Long, String>(); retrievedData.put(1l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":\"org space\"}"); retrievedData.put(2l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":\"orgspace\"}"); retrievedData.put(3l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":\"org test space sap\"}"); Map<Long, String> transformedData = transformFilterColumn.transformData(retrievedData); assertEquals("{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":{\"space\":\"space\",\"org\":\"org\"}}", transformedData.get(1l)); transformedData = transformFilterColumn.transformData(retrievedData); assertEquals("{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":{\"space\":\"orgspace\",\"org\":\"\"}}", transformedData.get(2l)); transformedData = transformFilterColumn.transformData(retrievedData); assertEquals("{\"requiredContent\":{\"type\":\"com.acme.plugin\"},\"targetSpace\":{\"space\":\"test space sap\",\"org\":\"org\"}}", transformedData.get(3l)); } @Test public void testTransformDataEmptyContent() { Map<Long, String> retrievedData = new HashMap<Long, String>(); Map<Long, String> transformedData = null; retrievedData.put(1l, "{\"requiredContent\":{\"type\":\"com.acme.plugin\"}}"); transformedData = transformFilterColumn.transformData(retrievedData); assertTrue(transformedData.isEmpty()); retrievedData.put(1l, "{}"); transformedData = transformFilterColumn.transformData(retrievedData); assertTrue(transformedData.isEmpty()); retrievedData.put(1l, ""); transformedData = transformFilterColumn.transformData(retrievedData); assertTrue(transformedData.isEmpty()); } }
apache-2.0
shaoxuan-wang/flink
flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/match/BaseRowEventComparator.java
1790
/* * 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.flink.table.runtime.match; import org.apache.flink.cep.EventComparator; import org.apache.flink.table.dataformat.BaseRow; import org.apache.flink.table.generated.GeneratedRecordComparator; import org.apache.flink.table.generated.RecordComparator; /** * An implementation of {@link EventComparator} based on a generated {@link RecordComparator}. */ public class BaseRowEventComparator implements EventComparator<BaseRow> { private static final long serialVersionUID = 1L; private final GeneratedRecordComparator generatedComparator; private transient RecordComparator comparator; public BaseRowEventComparator(GeneratedRecordComparator generatedComparator) { this.generatedComparator = generatedComparator; } @Override public int compare(BaseRow row1, BaseRow row2) { if (comparator == null) { comparator = generatedComparator.newInstance( Thread.currentThread().getContextClassLoader()); } return comparator.compare(row1, row2); } }
apache-2.0
GuillaumeOcculy/anfshift_paris
view/register.php
2939
<?php /** * Created by JetBrains PhpStorm. * User: occul_000 * Date: 03/03/13 * Time: 19:45 * To change this template use File | Settings | File Templates. */ ?> <!DOCTYPE html> <html> <head> <title>AnfShift</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <link rel="stylesheet" href="../docs/assets/css/bootstrap.css"> <meta charset="utf-8"> <link rel="stylesheet" href="../docs/assets/css/style.css"> </head> <body> <header> <div class="navbar navbar-static-top"> <div class="navbar-inner"> <div class="container"> <a class="brand" href="#">Abercrombie & Fitch</a> <ul class="nav pull-right"> <a href="login.php" class="btn btn-large btn-primary">Sign in</a> </ul> </div> </div> </div> </header> <section> <div class="container"> <div class="info"> <h3>Exchange shift,</h3> <h3>Open shift.</h3> <p class="lead">only for associates</p> </div> <div class="container-form"> <form class="form-horizontal" action="../controller/check_register.php" method="POST" > <div class="control-group"> <div class="controls"> <input type="text" name="firstname" placeholder="Firstname" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="text" name="lastname" placeholder="Lastname" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="email" name="email" placeholder="E-mail" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" name="password" placeholder="Password" required> </div> </div> <div class="control-group"> <div class="controls"> <input type="password" name="confirmPassword" placeholder="Confirm Password" required> </div> </div> <div class="control-group"> <div class="controls"> <select name="job" required> <option value="cashier">Cashier</option> <option value="impact_1">Impact 1</option> <option value="impact_2">Impact 2</option> <option value="model">Model</option> <option value="ops">OPS</option> <option value="stylist">Stylist</option> </select> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-large btn-success">Sign up</button> </div> </div> </form> </div> </div> </body> </html>
apache-2.0
jonyadamit/elasticsearch-net
src/Nest/Cluster/ClusterStats/ClusterIndicesStats.cs
1939
 using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { [JsonObject] public class ClusterIndicesStats { [JsonProperty("completion")] public CompletionStats Completion { get; internal set; } [JsonProperty("count")] public long Count { get; internal set; } [JsonProperty("docs")] public DocStats Documents { get; internal set; } [JsonProperty("fielddata")] public FielddataStats Fielddata { get; internal set; } [JsonProperty("percolate")] public PercolateStats Percolate { get; internal set; } [JsonProperty("query_cache")] public QueryCacheStats QueryCache { get; internal set; } [JsonProperty("segments")] public SegmentsStats Segments { get; internal set; } [JsonProperty("shards")] public ClusterIndicesShardsStats Shards { get; internal set; } [JsonProperty("store")] public StoreStats Store { get; internal set; } } [JsonObject] public class ClusterIndicesShardsStats { [JsonProperty("total")] public double Total { get; internal set; } [JsonProperty("primaries")] public double Primaries { get; internal set; } [JsonProperty("replication")] public double Replication { get; internal set; } [JsonProperty("index")] public ClusterIndicesShardsIndexStats Index { get; internal set; } } [JsonObject] public class ClusterIndicesShardsIndexStats { [JsonProperty("shards")] public ClusterShardMetrics Shards { get; internal set; } [JsonProperty("primaries")] public ClusterShardMetrics Primaries { get; internal set; } [JsonProperty("replication")] public ClusterShardMetrics Replication { get; internal set; } } [JsonObject] public class ClusterShardMetrics { [JsonProperty("min")] public double Min { get; internal set; } [JsonProperty("max")] public double Max { get; internal set; } [JsonProperty("avg")] public double Avg { get; internal set; } } }
apache-2.0
bitsetd4d/log999-large-log-viewer
src/test/java/com/log999/task/TestUtil.java
220
package com.log999.task; public class TestUtil { public static void sleepMs(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { // ignore } } }
apache-2.0
mufaddalq/cloudstack-datera-driver
api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java
5997
// 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.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.List; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; @APICommand(name = "addHost", description="Adds a new host.", responseObject=HostResponse.class) public class AddHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddHostCmd.class.getName()); private static final String s_name = "addhostresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, description="the cluster ID for the host") private Long clusterId; @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name for the host") private String clusterName; @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the password for the host") private String password; @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the host URL") private String url; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host") private String username; @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, required=true, description="the Zone ID for the host") private Long zoneId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the host") private String hypervisor; @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Host for allocation of new resources") private String allocationState; @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="list of tags to be added to the host") private List<String> hostTags; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public Long getClusterId() { return clusterId; } public String getClusterName() { return clusterName; } public String getPassword() { return password; } public Long getPodId() { return podId; } public String getUrl() { return url; } public String getUsername() { return username; } public Long getZoneId() { return zoneId; } public String getHypervisor() { return hypervisor; } public List<String> getHostTags() { return hostTags; } public String getAllocationState() { return allocationState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } @Override public void execute(){ try { List<? extends Host> result = _resourceService.discoverHosts(this); ListResponse<HostResponse> response = new ListResponse<HostResponse>(); List<HostResponse> hostResponses = new ArrayList<HostResponse>(); if (result != null && result.size() > 0) { for (Host host : result) { HostResponse hostResponse = _responseGenerator.createHostResponse(host); hostResponses.add(hostResponse); } } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add host"); } response.setResponses(hostResponses); response.setResponseName(getCommandName()); this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } } }
apache-2.0
greyp9/arwo
README.md
3220
# Arwo Web Application Arwo is a web application hosted in the Apache Tomcat web container. It is designed to provide for easy web access to remote servers. Its features include: * browse the filesystems of SSH servers * browse the filesystems of CIFS servers * browse the filesystems of WebDAV servers * run SQL commands on JDBC servers * run shell commands on SSH servers * run shell commands on Windows machines (using DCOM) * send emails using SMTP servers * view recent messages on IMAP email servers * view recent messages on POP3 email servers * manage server connections * store "favorite" filesystem locations and commands for later use * schedule accesses to filesystem resources (folders / files) * schedule execution of server commands Arwo uses additional open-source libraries internally to interface to different server types. For each server type to be accessed, the appropriate library / libraries should be separately downloaded. More information about the usage of these libraries can be found on the webapp "Usage" page [here](https://htmlpreview.github.io/?https://github.com/greyp9/arwo/blob/master/src/main/app/resources/webapp/arwo-war/usage.html). ## Requirements To use the webapp, a version of the Java runtime is needed, as well as a version of the Tomcat web container. Once these are available, the webapp should be installed into the Tomcat container. You would then navigate a web browser to the landing page of the webapp in the running Tomcat instance and authenticate to the application. [sample link](https://localhost/arwo) Because of Tomcat classloader requirements, a standalone JAR needs to be copied into the Tomcat library folder to provide the implementation of the webapp authentication realm. More information is provided on the webapp "Usage" page. ## License This software is licensed under the Apache License, version 2. [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) ## Credits A debt of gratitude is owed to those responsible for the development of the server access libraries. Without their efforts, much of the functionality of this webapp would not be possible. | Name | Description | URL | | --- | --- | --- | | ganymed-ssh-2 | Ganymed SSH-2: Java based SSH-2 Protocol Implementation | https://code.google.com/p/ganymed-ssh-2/ | | jCIFS | JCIFS is an Open Source client library that implements the CIFS/SMB networking protocol in 100% Java | http://jcifs.samba.org | | j-interop-repackaged | j-interop repackaged as a module | http://glassfish.java.net/ | | Sardine WEBDAV client | An easy to use webdav client for java | https://github.com/lookfirst/sardine | | Apache HttpClient | Apache HttpComponents Client | http://hc.apache.org/httpcomponents-client | | Apache HttpCore | Apache HttpComponents Core (blocking I/O) | http://hc.apache.org/httpcomponents-core-ga | | Apache Commons Logging | Apache Commons Logging is a thin adapter allowing configurable bridging to other, well known logging systems. | http://commons.apache.org/proper/commons-logging/ | | javax.mail | JavaMail API | http://www.oracle.com | <!--- /mvn:project/mvn:name /mvn:project/mvn:description /mvn:project/mvn:url --->
apache-2.0
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/user/_content/pwdav.html
526
<fieldset> <legend>$r.translate("pwdav.title")</legend> $r.contextHelpWithWrapper("org.olat.core.commons.modules.bc","bc-webdav.html","help.hover.webdav") <p>$r.translate("pwdav.description")</p> #if($webdavhttps) <p> <code>$webdavhttps</code> </p> #if ($webdavhttp) <p > $r.translate('webdav.link.http') </p> <p> <code>$webdavhttp</code> </p> #end #else <p> <code>$webdavhttp</code> </p> #end <h4>$r.translate("pwdav.access_data")</h4> $r.render("access_data") </fieldset>
apache-2.0
drzaeus77/docker-plugin
iovplug/config.go
694
// Copyright 2015 PLUMgrid // // 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 iovplug type Config struct { Subnet string Socket string Interface string Gateway string }
apache-2.0
yongli3/rt-thread
bsp/stm32f10x-HAL/drivers/drv_usart.c
12506
/* * File : drv_usart.c * This file is part of RT-Thread RTOS * COPYRIGHT (C) 2006-2013, RT-Thread Development Team * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rt-thread.org/license/LICENSE * * Change Logs: * Date Author Notes * 2009-01-05 Bernard the first version * 2010-03-29 Bernard remove interrupt Tx and DMA Rx mode * 2013-05-13 aozima update for kehong-lingtai. * 2015-01-31 armink make sure the serial transmit complete in putc() * 2016-05-13 armink add DMA Rx mode * 2017-01-19 aubr.cool add interrupt Tx mode * 2017-04-13 aubr.cool correct Rx parity err * 2017-10-20 ZYH porting to HAL Libraries(with out DMA) * 2017-11-15 ZYH update to 3.0.0 */ #include "board.h" #include <rtdevice.h> #include <drv_usart.h> /* STM32 uart driver */ struct stm32_uart { UART_HandleTypeDef huart; IRQn_Type irq; }; static rt_err_t stm32_configure(struct rt_serial_device *serial, struct serial_configure *cfg) { struct stm32_uart *uart; RT_ASSERT(serial != RT_NULL); RT_ASSERT(cfg != RT_NULL); uart = (struct stm32_uart *)serial->parent.user_data; uart->huart.Init.BaudRate = cfg->baud_rate; uart->huart.Init.HwFlowCtl = UART_HWCONTROL_NONE; uart->huart.Init.Mode = UART_MODE_TX_RX; uart->huart.Init.OverSampling = UART_OVERSAMPLING_16; switch (cfg->data_bits) { case DATA_BITS_8: uart->huart.Init.WordLength = UART_WORDLENGTH_8B; break; case DATA_BITS_9: uart->huart.Init.WordLength = UART_WORDLENGTH_9B; break; default: uart->huart.Init.WordLength = UART_WORDLENGTH_8B; break; } switch (cfg->stop_bits) { case STOP_BITS_1: uart->huart.Init.StopBits = UART_STOPBITS_1; break; case STOP_BITS_2: uart->huart.Init.StopBits = UART_STOPBITS_2; break; default: uart->huart.Init.StopBits = UART_STOPBITS_1; break; } switch (cfg->parity) { case PARITY_NONE: uart->huart.Init.Parity = UART_PARITY_NONE; break; case PARITY_ODD: uart->huart.Init.Parity = UART_PARITY_ODD; break; case PARITY_EVEN: uart->huart.Init.Parity = UART_PARITY_EVEN; break; default: uart->huart.Init.Parity = UART_PARITY_NONE; break; } if (HAL_UART_Init(&uart->huart) != HAL_OK) { return RT_ERROR; } return RT_EOK; } static rt_err_t stm32_control(struct rt_serial_device *serial, int cmd, void *arg) { struct stm32_uart *uart; RT_ASSERT(serial != RT_NULL); uart = (struct stm32_uart *)serial->parent.user_data; switch (cmd) { /* disable interrupt */ case RT_DEVICE_CTRL_CLR_INT: /* disable rx irq */ NVIC_DisableIRQ(uart->irq); /* disable interrupt */ __HAL_UART_DISABLE_IT(&uart->huart, USART_IT_RXNE); break; /* enable interrupt */ case RT_DEVICE_CTRL_SET_INT: /* enable rx irq */ NVIC_EnableIRQ(uart->irq); /* enable interrupt */ __HAL_UART_ENABLE_IT(&uart->huart, USART_IT_RXNE); break; } return RT_EOK; } static int stm32_putc(struct rt_serial_device *serial, char c) { struct stm32_uart *uart; RT_ASSERT(serial != RT_NULL); uart = (struct stm32_uart *)serial->parent.user_data; while (__HAL_UART_GET_FLAG(&uart->huart, UART_FLAG_TXE) == RESET); uart->huart.Instance->DR = c; return 1; } static int stm32_getc(struct rt_serial_device *serial) { int ch; struct stm32_uart *uart; RT_ASSERT(serial != RT_NULL); uart = (struct stm32_uart *)serial->parent.user_data; ch = -1; if (__HAL_UART_GET_FLAG(&uart->huart, UART_FLAG_RXNE) != RESET) { ch = uart->huart.Instance->DR & 0xff; } return ch; } /** * Uart common interrupt process. This need add to uart ISR. * * @param serial serial device */ static void uart_isr(struct rt_serial_device *serial) { struct stm32_uart *uart = (struct stm32_uart *) serial->parent.user_data; RT_ASSERT(uart != RT_NULL); if ((__HAL_UART_GET_FLAG(&uart->huart, UART_FLAG_RXNE) != RESET) && (__HAL_UART_GET_IT_SOURCE(&uart->huart, UART_IT_RXNE) != RESET)) { rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_IND); __HAL_UART_CLEAR_FLAG(&uart->huart, UART_FLAG_RXNE); } } static const struct rt_uart_ops stm32_uart_ops = { stm32_configure, stm32_control, stm32_putc, stm32_getc, }; #if defined(RT_USING_UART1) /* UART1 device driver structure */ struct stm32_uart uart1 = { {USART1}, USART1_IRQn }; struct rt_serial_device serial1; void USART1_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); uart_isr(&serial1); /* leave interrupt */ rt_interrupt_leave(); } #endif /* RT_USING_UART1 */ #if defined(RT_USING_UART2) /* UART1 device driver structure */ struct stm32_uart uart2 = { {USART2}, USART2_IRQn }; struct rt_serial_device serial2; void USART2_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); uart_isr(&serial2); /* leave interrupt */ rt_interrupt_leave(); } #endif /* RT_USING_UART2 */ #if defined(RT_USING_UART3) /* UART1 device driver structure */ struct stm32_uart uart3 = { {USART3}, USART3_IRQn }; struct rt_serial_device serial3; void USART3_IRQHandler(void) { /* enter interrupt */ rt_interrupt_enter(); uart_isr(&serial3); /* leave interrupt */ rt_interrupt_leave(); } #endif /* RT_USING_UART2 */ static void MX_USART_UART_Init(UART_HandleTypeDef *uartHandle); int rt_hw_usart_init(void) { struct stm32_uart *uart; struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; #if defined(RT_USING_UART1) uart = &uart1; config.baud_rate = BAUD_RATE_115200; serial1.ops = &stm32_uart_ops; serial1.config = config; MX_USART_UART_Init(&uart->huart); /* register UART1 device */ rt_hw_serial_register(&serial1, "uart1", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, uart); #endif /* RT_USING_UART1 */ #if defined(RT_USING_UART2) uart = &uart2; config.baud_rate = BAUD_RATE_115200; serial2.ops = &stm32_uart_ops; serial2.config = config; MX_USART_UART_Init(&uart->huart); /* register UART1 device */ rt_hw_serial_register(&serial2, "uart2", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, uart); #endif /* RT_USING_UART1 */ #if defined(RT_USING_UART3) uart = &uart3; config.baud_rate = BAUD_RATE_115200; serial3.ops = &stm32_uart_ops; serial3.config = config; MX_USART_UART_Init(&uart->huart); /* register UART1 device */ rt_hw_serial_register(&serial3, "uart3", RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, uart); #endif /* RT_USING_UART1 */ return 0; } INIT_BOARD_EXPORT(rt_hw_usart_init); static void MX_USART_UART_Init(UART_HandleTypeDef *uartHandle) { rt_err_t result; uartHandle->Init.BaudRate = 115200; uartHandle->Init.WordLength = UART_WORDLENGTH_8B; uartHandle->Init.StopBits = UART_STOPBITS_1; uartHandle->Init.Parity = UART_PARITY_NONE; uartHandle->Init.Mode = UART_MODE_TX_RX; uartHandle->Init.HwFlowCtl = UART_HWCONTROL_NONE; uartHandle->Init.OverSampling = UART_OVERSAMPLING_16; result = HAL_UART_Init(uartHandle); RT_ASSERT(result == HAL_OK); } /* USART2 init function */ void HAL_UART_MspInit(UART_HandleTypeDef *uartHandle) { GPIO_InitTypeDef GPIO_InitStruct; if (uartHandle->Instance == USART1) { /* USER CODE BEGIN USART1_MspInit 0 */ /* USER CODE END USART1_MspInit 0 */ /* USART1 clock enable */ __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ GPIO_InitStruct.Pin = GPIO_PIN_9; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART1 interrupt Init */ HAL_NVIC_SetPriority(USART1_IRQn, 5, 0); HAL_NVIC_EnableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspInit 1 */ /* USER CODE END USART1_MspInit 1 */ } else if (uartHandle->Instance == USART2) { /* USER CODE BEGIN USART2_MspInit 0 */ /* USER CODE END USART2_MspInit 0 */ /* USART2 clock enable */ __HAL_RCC_USART2_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ GPIO_InitStruct.Pin = GPIO_PIN_2; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_3; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* USART2 interrupt Init */ HAL_NVIC_SetPriority(USART2_IRQn, 5, 0); HAL_NVIC_EnableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspInit 1 */ /* USER CODE END USART2_MspInit 1 */ } else if (uartHandle->Instance == USART3) { /* USER CODE BEGIN USART3_MspInit 0 */ /* USER CODE END USART3_MspInit 0 */ /* USART3 clock enable */ __HAL_RCC_USART3_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /**USART3 GPIO Configuration PB10 ------> USART3_TX PB11 ------> USART3_RX */ GPIO_InitStruct.Pin = GPIO_PIN_10; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); GPIO_InitStruct.Pin = GPIO_PIN_11; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* USART3 interrupt Init */ HAL_NVIC_SetPriority(USART3_IRQn, 5, 0); HAL_NVIC_EnableIRQ(USART3_IRQn); /* USER CODE BEGIN USART3_MspInit 1 */ /* USER CODE END USART3_MspInit 1 */ } } void HAL_UART_MspDeInit(UART_HandleTypeDef *uartHandle) { if (uartHandle->Instance == USART1) { /* USER CODE BEGIN USART1_MspDeInit 0 */ /* USER CODE END USART1_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART1_CLK_DISABLE(); /**USART1 GPIO Configuration PA9 ------> USART1_TX PA10 ------> USART1_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9 | GPIO_PIN_10); /* USART1 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART1_IRQn); /* USER CODE BEGIN USART1_MspDeInit 1 */ /* USER CODE END USART1_MspDeInit 1 */ } else if (uartHandle->Instance == USART2) { /* USER CODE BEGIN USART2_MspDeInit 0 */ /* USER CODE END USART2_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART2_CLK_DISABLE(); /**USART2 GPIO Configuration PA2 ------> USART2_TX PA3 ------> USART2_RX */ HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2 | GPIO_PIN_3); /* USART2 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART2_IRQn); /* USER CODE BEGIN USART2_MspDeInit 1 */ /* USER CODE END USART2_MspDeInit 1 */ } else if (uartHandle->Instance == USART3) { /* USER CODE BEGIN USART3_MspDeInit 0 */ /* USER CODE END USART3_MspDeInit 0 */ /* Peripheral clock disable */ __HAL_RCC_USART3_CLK_DISABLE(); /**USART3 GPIO Configuration PB10 ------> USART3_TX PB11 ------> USART3_RX */ HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10 | GPIO_PIN_11); /* USART3 interrupt Deinit */ HAL_NVIC_DisableIRQ(USART3_IRQn); /* USER CODE BEGIN USART3_MspDeInit 1 */ /* USER CODE END USART3_MspDeInit 1 */ } }
apache-2.0
SAP/openui5
src/sap.ui.core/test/sap/ui/core/demokit/sample/odata/v4/MusicArtists/PublicationObjectPage.controller.js
1423
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/core/mvc/Controller", "sap/ui/core/routing/History", "sap/ui/model/json/JSONModel" ], function (UIComponent, Controller, History, JSONModel) { "use strict"; return Controller.extend("sap.ui.core.sample.odata.v4.MusicArtists.PublicationObjectPage", { _onObjectMatched : function (oEvent) { var oEventArguments = oEvent.getParameter("arguments"), oView = this.getView(), oPublicationContext = oView.getModel() .bindContext("/" + oEventArguments.artistPath + "/" + oEventArguments.publicationPath) .getBoundContext(); oView.setBindingContext(oPublicationContext); oPublicationContext.requestObject("IsActiveEntity").then(function (bIsActiveEntity) { oView.getModel("ui-op").setProperty("/bEditMode", !bIsActiveEntity); }); }, onBack : function () { var sPreviousHash = History.getInstance().getPreviousHash(); this.getView().getModel("ui-op").setProperty("/bEditMode", false); if (sPreviousHash !== undefined) { window.history.go(-1); } else { this.getOwnerComponent().getRouter().navTo("masterList", null, true); } }, onInit : function () { var oRouter = UIComponent.getRouterFor(this); oRouter.getRoute("publicationObjectPage") .attachPatternMatched(this._onObjectMatched, this); this.getView().setModel(new JSONModel({bEditMode : false}), "ui-op"); } }); });
apache-2.0
approvals/Approvals.NodeJS
lib/Reporting/Reporters/beyondcompareReporter.js
860
var autils = require('../../AUtils'); var osTool = require('../../osTools'); var shelljs = require('shelljs'); var GenericDiffReporterBase = require('../GenericDiffReporterBase'); class Reporter extends GenericDiffReporterBase { constructor() { super("BeyondCompare"); var app = null; if (osTool.platform.isMac) { try { app = shelljs.ls('/Applications/Beyond Compare.app/Contents/MacOS/bcomp')[0]; } catch (err) { console.error(err); } app = app || autils.searchForExecutable("bcomp"); } else if (osTool.platform.isWindows) { app = autils.searchForExecutable("Beyond Compare 4", "BCompare.exe") || autils.searchForExecutable("Beyond Compare 3", "BCompare.exe"); } app = app || autils.searchForExecutable("bcomp"); this.exePath = app; } } module.exports = Reporter;
apache-2.0
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/analytics/model/black/BlackDiscountingPositionGammaIRFutureOptionFunction.java
3204
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.black; import static com.opengamma.engine.value.ValueRequirementNames.POSITION_GAMMA; import java.util.Collections; import java.util.Set; import org.threeten.bp.Instant; import com.google.common.collect.Iterables; import com.opengamma.analytics.financial.forex.method.FXMatrix; import com.opengamma.analytics.financial.interestrate.InstrumentDerivative; import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor; import com.opengamma.analytics.financial.provider.calculator.blackstirfutures.PositionGammaSTIRFutureOptionCalculator; import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesProviderInterface; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; /** * Calculates the position gamma of interest rate future options using a Black surface and curves constructed using the discounting method. */ public class BlackDiscountingPositionGammaIRFutureOptionFunction extends BlackDiscountingIRFutureOptionFunction { /** The position gamma calculator */ private static final InstrumentDerivativeVisitor<BlackSTIRFuturesProviderInterface, Double> CALCULATOR = PositionGammaSTIRFutureOptionCalculator .getInstance(); /** * Sets the value requirement to {@link com.opengamma.engine.value.ValueRequirementNames#POSITION_GAMMA}. */ public BlackDiscountingPositionGammaIRFutureOptionFunction() { super(POSITION_GAMMA); } @Override public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) { return new BlackDiscountingCompiledFunction(getTargetToDefinitionConverter(context), getDefinitionToDerivativeConverter(context), true) { @Override protected Set<ComputedValue> getValues(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues, final InstrumentDerivative derivative, final FXMatrix fxMatrix) { final BlackSTIRFuturesProviderInterface blackData = getBlackSurface(executionContext, inputs, target, fxMatrix); final double positionGamma = derivative.accept(CALCULATOR, blackData); final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final ValueProperties properties = desiredValue.getConstraints().copy().get(); final ValueSpecification spec = new ValueSpecification(POSITION_GAMMA, target.toSpecification(), properties); return Collections.singleton(new ComputedValue(spec, positionGamma)); } }; } }
apache-2.0
tmtweb/tmt-web
about.html
8522
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Translating Anything from Anywhere"> <meta name="author" content="TranslateMEthis.com"> <meta name="keywords" content="Translation, Transcription, Ghost Writing, interpreter, Translate languages, translate from Russian to English, translate from Spanish to English, translate, transcribe, resume translation, resume adaptation, job search abroad, translate from German to English, Translate audio, Translate videos, Transcribe audio, Transcribe videos,"> <title>TranslateMEthis</title <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Favicon --> <link rel="shortcut icon"href="http://i.imgur.com/ATNSYj5.jpg" /> <!-- Custom CSS --> <link href="css/modern-business.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">TranslateMEthis.com - Home </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="about.html">About</a> </li> <li> <a href="services.html">Services</a> </li> <li> <a href="contact.html">Contact</a> </li> <li> <a href="pricing.html">Pricing Table</a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Blog <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="why-us.html">Why us?</a> </li> <li> <a href="become.html">Become a Team Member</a> </li> <li> <a href="blog-page-1.html">Blog</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Other Pages <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="terms.html">Terms and Conditions</a> </li> <li> <a href="sidebar.html">Sidebar Page</a> </li> <li> <a href="faq.html">FAQ</a> </li> <li> <a href="404.html">404</a> </li> </ul> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <!-- Page Heading/Breadcrumbs --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">About us <small>And how it started</small> </h1> <ol class="breadcrumb"> <li><a href="index.html">Home</a> </li> <li class="active">About</li> </ol> </div> </div> <!-- /.row --> <!-- Intro Content --> <div class="row"> <div class="col-md-6"> <img class="img-responsive" src="http://i.imgur.com/XHsB8XW.jpg" alt=""> </div> <div class="col-md-6"> <h2>About translateMEthis.com</h2> <p><strong>Translation and Transcripton, that's all there is.</strong> There is no secret story, our company started as many orders doing little assignments online from freelance websites. We realized that often, our clients did not have the money to pay for an in-house translator that would charge over $45 per hour. We thought there was place for some change. We suggested to our clients to outsource their translators. That way, they would get a more accurate translation of their product, and at a cheaper cost. This is how TranslateMEthis was born!</p> <h2>Our Mission</h2> <p><strong>Translate, Transcribe, Change the World.</strong> Nothing less. How goal is to get the world closer and help to create bonds between cultures by being the middle man of your translation business. Your assignments will give experience to an outsource labor. Whereas there work will give you the tools to go forward with that new business deal or with this project that you cherish. We really think that by helping you get the transcription you need, we help the world become a better place.</p> </div> </div> <!-- /.row --> <!-- Call to Action Section --> <div class="well"> <div class="row"> <div class="col-md-8"> <p>We are privileged to have the best customer representatives in the industry. Contact us now to know more about our different products and services. You may email us to get a quote or to set up a live conversation with our customer representatives! </p> </div> <div class="col-md-4"> <a class="btn btn-lg btn-default btn-block" href=404.html>Click to talk to a real person!</a> </div> </div> </div> <hr> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <p>Copyright &copy; TranslateMEthis.com 2015</p> </div> </div> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!--Start of Tawk.to Script--> <script type="text/javascript"> var $_Tawk_API={},$_Tawk_LoadStart=new Date(); (function(){ var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0]; s1.async=true; s1.src='https://embed.tawk.to/553f05cc09e561474e53373e/default'; s1.charset='UTF-8'; s1.setAttribute('crossorigin','*'); s0.parentNode.insertBefore(s1,s0); })(); </script> <!--End of Tawk.to Script--> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-2366119-4', 'auto'); ga('send', 'pageview'); </script> </html> </body>
apache-2.0
wanhao/IRIndex
docs/apidocs/org/apache/hadoop/hbase/rest/model/class-use/TableSchemaModel.html
9245
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Fri Jan 10 21:37:07 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.hbase.rest.model.TableSchemaModel (HBase 0.94.16 API) </TITLE> <META NAME="date" CONTENT="2014-01-10"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.hbase.rest.model.TableSchemaModel (HBase 0.94.16 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/hbase/rest/model//class-useTableSchemaModel.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TableSchemaModel.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.hbase.rest.model.TableSchemaModel</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model">TableSchemaModel</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.hbase.rest"><B>org.apache.hadoop.hbase.rest</B></A></TD> <TD>HBase REST&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.hbase.rest"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model">TableSchemaModel</A> in <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/package-summary.html">org.apache.hadoop.hbase.rest</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/package-summary.html">org.apache.hadoop.hbase.rest</A> with parameters of type <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model">TableSchemaModel</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;javax.ws.rs.core.Response</CODE></FONT></TD> <TD><CODE><B>SchemaResource.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/rest/SchemaResource.html#post(org.apache.hadoop.hbase.rest.model.TableSchemaModel, javax.ws.rs.core.UriInfo)">post</A></B>(<A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model">TableSchemaModel</A>&nbsp;model, javax.ws.rs.core.UriInfo&nbsp;uriInfo)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;javax.ws.rs.core.Response</CODE></FONT></TD> <TD><CODE><B>SchemaResource.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/rest/SchemaResource.html#put(org.apache.hadoop.hbase.rest.model.TableSchemaModel, javax.ws.rs.core.UriInfo)">put</A></B>(<A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model">TableSchemaModel</A>&nbsp;model, javax.ws.rs.core.UriInfo&nbsp;uriInfo)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/hbase/rest/model/TableSchemaModel.html" title="class in org.apache.hadoop.hbase.rest.model"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/apache/hadoop/hbase/rest/model//class-useTableSchemaModel.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TableSchemaModel.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
apache-2.0
oklog/ulid
ulid.go
20673
// Copyright 2016 The Oklog Authors // 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 ulid import ( "bufio" "bytes" "database/sql/driver" "encoding/binary" "errors" "io" "math" "math/bits" "math/rand" "time" ) /* An ULID is a 16 byte Universally Unique Lexicographically Sortable Identifier The components are encoded as 16 octets. Each component is encoded with the MSB first (network byte order). 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_time_high | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 16_bit_uint_time_low | 16_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | 32_bit_uint_random | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type ULID [16]byte var ( // ErrDataSize is returned when parsing or unmarshaling ULIDs with the wrong // data size. ErrDataSize = errors.New("ulid: bad data size when unmarshaling") // ErrInvalidCharacters is returned when parsing or unmarshaling ULIDs with // invalid Base32 encodings. ErrInvalidCharacters = errors.New("ulid: bad data characters when unmarshaling") // ErrBufferSize is returned when marshalling ULIDs to a buffer of insufficient // size. ErrBufferSize = errors.New("ulid: bad buffer size when marshaling") // ErrBigTime is returned when constructing an ULID with a time that is larger // than MaxTime. ErrBigTime = errors.New("ulid: time too big") // ErrOverflow is returned when unmarshaling a ULID whose first character is // larger than 7, thereby exceeding the valid bit depth of 128. ErrOverflow = errors.New("ulid: overflow when unmarshaling") // ErrMonotonicOverflow is returned by a Monotonic entropy source when // incrementing the previous ULID's entropy bytes would result in overflow. ErrMonotonicOverflow = errors.New("ulid: monotonic entropy overflow") // ErrScanValue is returned when the value passed to scan cannot be unmarshaled // into the ULID. ErrScanValue = errors.New("ulid: source value must be a string or byte slice") ) // MonotonicReader is an interface that should yield monotonically increasing // entropy into the provided slice for all calls with the same ms parameter. If // a MonotonicReader is provided to the New constructor, its MonotonicRead // method will be used instead of Read. type MonotonicReader interface { io.Reader MonotonicRead(ms uint64, p []byte) error } // New returns an ULID with the given Unix milliseconds timestamp and an // optional entropy source. Use the Timestamp function to convert // a time.Time to Unix milliseconds. // // ErrBigTime is returned when passing a timestamp bigger than MaxTime. // Reading from the entropy source may also return an error. // // Safety for concurrent use is only dependent on the safety of the // entropy source. func New(ms uint64, entropy io.Reader) (id ULID, err error) { if err = id.SetTime(ms); err != nil { return id, err } switch e := entropy.(type) { case nil: return id, err case MonotonicReader: err = e.MonotonicRead(ms, id[6:]) default: _, err = io.ReadFull(e, id[6:]) } return id, err } // MustNew is a convenience function equivalent to New that panics on failure // instead of returning an error. func MustNew(ms uint64, entropy io.Reader) ULID { id, err := New(ms, entropy) if err != nil { panic(err) } return id } // Parse parses an encoded ULID, returning an error in case of failure. // // ErrDataSize is returned if the len(ulid) is different from an encoded // ULID's length. Invalid encodings produce undefined ULIDs. For a version that // returns an error instead, see ParseStrict. func Parse(ulid string) (id ULID, err error) { return id, parse([]byte(ulid), false, &id) } // ParseStrict parses an encoded ULID, returning an error in case of failure. // // It is like Parse, but additionally validates that the parsed ULID consists // only of valid base32 characters. It is slightly slower than Parse. // // ErrDataSize is returned if the len(ulid) is different from an encoded // ULID's length. Invalid encodings return ErrInvalidCharacters. func ParseStrict(ulid string) (id ULID, err error) { return id, parse([]byte(ulid), true, &id) } func parse(v []byte, strict bool, id *ULID) error { // Check if a base32 encoded ULID is the right length. if len(v) != EncodedSize { return ErrDataSize } // Check if all the characters in a base32 encoded ULID are part of the // expected base32 character set. if strict && (dec[v[0]] == 0xFF || dec[v[1]] == 0xFF || dec[v[2]] == 0xFF || dec[v[3]] == 0xFF || dec[v[4]] == 0xFF || dec[v[5]] == 0xFF || dec[v[6]] == 0xFF || dec[v[7]] == 0xFF || dec[v[8]] == 0xFF || dec[v[9]] == 0xFF || dec[v[10]] == 0xFF || dec[v[11]] == 0xFF || dec[v[12]] == 0xFF || dec[v[13]] == 0xFF || dec[v[14]] == 0xFF || dec[v[15]] == 0xFF || dec[v[16]] == 0xFF || dec[v[17]] == 0xFF || dec[v[18]] == 0xFF || dec[v[19]] == 0xFF || dec[v[20]] == 0xFF || dec[v[21]] == 0xFF || dec[v[22]] == 0xFF || dec[v[23]] == 0xFF || dec[v[24]] == 0xFF || dec[v[25]] == 0xFF) { return ErrInvalidCharacters } // Check if the first character in a base32 encoded ULID will overflow. This // happens because the base32 representation encodes 130 bits, while the // ULID is only 128 bits. // // See https://github.com/oklog/ulid/issues/9 for details. if v[0] > '7' { return ErrOverflow } // Use an optimized unrolled loop (from https://github.com/RobThree/NUlid) // to decode a base32 ULID. // 6 bytes timestamp (48 bits) (*id)[0] = (dec[v[0]] << 5) | dec[v[1]] (*id)[1] = (dec[v[2]] << 3) | (dec[v[3]] >> 2) (*id)[2] = (dec[v[3]] << 6) | (dec[v[4]] << 1) | (dec[v[5]] >> 4) (*id)[3] = (dec[v[5]] << 4) | (dec[v[6]] >> 1) (*id)[4] = (dec[v[6]] << 7) | (dec[v[7]] << 2) | (dec[v[8]] >> 3) (*id)[5] = (dec[v[8]] << 5) | dec[v[9]] // 10 bytes of entropy (80 bits) (*id)[6] = (dec[v[10]] << 3) | (dec[v[11]] >> 2) (*id)[7] = (dec[v[11]] << 6) | (dec[v[12]] << 1) | (dec[v[13]] >> 4) (*id)[8] = (dec[v[13]] << 4) | (dec[v[14]] >> 1) (*id)[9] = (dec[v[14]] << 7) | (dec[v[15]] << 2) | (dec[v[16]] >> 3) (*id)[10] = (dec[v[16]] << 5) | dec[v[17]] (*id)[11] = (dec[v[18]] << 3) | dec[v[19]]>>2 (*id)[12] = (dec[v[19]] << 6) | (dec[v[20]] << 1) | (dec[v[21]] >> 4) (*id)[13] = (dec[v[21]] << 4) | (dec[v[22]] >> 1) (*id)[14] = (dec[v[22]] << 7) | (dec[v[23]] << 2) | (dec[v[24]] >> 3) (*id)[15] = (dec[v[24]] << 5) | dec[v[25]] return nil } // MustParse is a convenience function equivalent to Parse that panics on failure // instead of returning an error. func MustParse(ulid string) ULID { id, err := Parse(ulid) if err != nil { panic(err) } return id } // MustParseStrict is a convenience function equivalent to ParseStrict that // panics on failure instead of returning an error. func MustParseStrict(ulid string) ULID { id, err := ParseStrict(ulid) if err != nil { panic(err) } return id } // Bytes returns bytes slice representation of ULID. func (id ULID) Bytes() []byte { return id[:] } // String returns a lexicographically sortable string encoded ULID // (26 characters, non-standard base 32) e.g. 01AN4Z07BY79KA1307SR9X4MV3. // Format: tttttttttteeeeeeeeeeeeeeee where t is time and e is entropy. func (id ULID) String() string { ulid := make([]byte, EncodedSize) _ = id.MarshalTextTo(ulid) return string(ulid) } // MarshalBinary implements the encoding.BinaryMarshaler interface by // returning the ULID as a byte slice. func (id ULID) MarshalBinary() ([]byte, error) { ulid := make([]byte, len(id)) return ulid, id.MarshalBinaryTo(ulid) } // MarshalBinaryTo writes the binary encoding of the ULID to the given buffer. // ErrBufferSize is returned when the len(dst) != 16. func (id ULID) MarshalBinaryTo(dst []byte) error { if len(dst) != len(id) { return ErrBufferSize } copy(dst, id[:]) return nil } // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface by // copying the passed data and converting it to an ULID. ErrDataSize is // returned if the data length is different from ULID length. func (id *ULID) UnmarshalBinary(data []byte) error { if len(data) != len(*id) { return ErrDataSize } copy((*id)[:], data) return nil } // Encoding is the base 32 encoding alphabet used in ULID strings. const Encoding = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" // MarshalText implements the encoding.TextMarshaler interface by // returning the string encoded ULID. func (id ULID) MarshalText() ([]byte, error) { ulid := make([]byte, EncodedSize) return ulid, id.MarshalTextTo(ulid) } // MarshalTextTo writes the ULID as a string to the given buffer. // ErrBufferSize is returned when the len(dst) != 26. func (id ULID) MarshalTextTo(dst []byte) error { // Optimized unrolled loop ahead. // From https://github.com/RobThree/NUlid if len(dst) != EncodedSize { return ErrBufferSize } // 10 byte timestamp dst[0] = Encoding[(id[0]&224)>>5] dst[1] = Encoding[id[0]&31] dst[2] = Encoding[(id[1]&248)>>3] dst[3] = Encoding[((id[1]&7)<<2)|((id[2]&192)>>6)] dst[4] = Encoding[(id[2]&62)>>1] dst[5] = Encoding[((id[2]&1)<<4)|((id[3]&240)>>4)] dst[6] = Encoding[((id[3]&15)<<1)|((id[4]&128)>>7)] dst[7] = Encoding[(id[4]&124)>>2] dst[8] = Encoding[((id[4]&3)<<3)|((id[5]&224)>>5)] dst[9] = Encoding[id[5]&31] // 16 bytes of entropy dst[10] = Encoding[(id[6]&248)>>3] dst[11] = Encoding[((id[6]&7)<<2)|((id[7]&192)>>6)] dst[12] = Encoding[(id[7]&62)>>1] dst[13] = Encoding[((id[7]&1)<<4)|((id[8]&240)>>4)] dst[14] = Encoding[((id[8]&15)<<1)|((id[9]&128)>>7)] dst[15] = Encoding[(id[9]&124)>>2] dst[16] = Encoding[((id[9]&3)<<3)|((id[10]&224)>>5)] dst[17] = Encoding[id[10]&31] dst[18] = Encoding[(id[11]&248)>>3] dst[19] = Encoding[((id[11]&7)<<2)|((id[12]&192)>>6)] dst[20] = Encoding[(id[12]&62)>>1] dst[21] = Encoding[((id[12]&1)<<4)|((id[13]&240)>>4)] dst[22] = Encoding[((id[13]&15)<<1)|((id[14]&128)>>7)] dst[23] = Encoding[(id[14]&124)>>2] dst[24] = Encoding[((id[14]&3)<<3)|((id[15]&224)>>5)] dst[25] = Encoding[id[15]&31] return nil } // Byte to index table for O(1) lookups when unmarshaling. // We use 0xFF as sentinel value for invalid indexes. var dec = [...]byte{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } // EncodedSize is the length of a text encoded ULID. const EncodedSize = 26 // UnmarshalText implements the encoding.TextUnmarshaler interface by // parsing the data as string encoded ULID. // // ErrDataSize is returned if the len(v) is different from an encoded // ULID's length. Invalid encodings produce undefined ULIDs. func (id *ULID) UnmarshalText(v []byte) error { return parse(v, false, id) } // Time returns the Unix time in milliseconds encoded in the ULID. // Use the top level Time function to convert the returned value to // a time.Time. func (id ULID) Time() uint64 { return uint64(id[5]) | uint64(id[4])<<8 | uint64(id[3])<<16 | uint64(id[2])<<24 | uint64(id[1])<<32 | uint64(id[0])<<40 } // maxTime is the maximum Unix time in milliseconds that can be // represented in an ULID. var maxTime = ULID{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}.Time() // MaxTime returns the maximum Unix time in milliseconds that // can be encoded in an ULID. func MaxTime() uint64 { return maxTime } // Now is a convenience function that returns the current // UTC time in Unix milliseconds. Equivalent to: // Timestamp(time.Now().UTC()) func Now() uint64 { return Timestamp(time.Now().UTC()) } // Timestamp converts a time.Time to Unix milliseconds. // // Because of the way ULID stores time, times from the year // 10889 produces undefined results. func Timestamp(t time.Time) uint64 { return uint64(t.Unix())*1000 + uint64(t.Nanosecond()/int(time.Millisecond)) } // Time converts Unix milliseconds in the format // returned by the Timestamp function to a time.Time. func Time(ms uint64) time.Time { s := int64(ms / 1e3) ns := int64((ms % 1e3) * 1e6) return time.Unix(s, ns) } // SetTime sets the time component of the ULID to the given Unix time // in milliseconds. func (id *ULID) SetTime(ms uint64) error { if ms > maxTime { return ErrBigTime } (*id)[0] = byte(ms >> 40) (*id)[1] = byte(ms >> 32) (*id)[2] = byte(ms >> 24) (*id)[3] = byte(ms >> 16) (*id)[4] = byte(ms >> 8) (*id)[5] = byte(ms) return nil } // Entropy returns the entropy from the ULID. func (id ULID) Entropy() []byte { e := make([]byte, 10) copy(e, id[6:]) return e } // SetEntropy sets the ULID entropy to the passed byte slice. // ErrDataSize is returned if len(e) != 10. func (id *ULID) SetEntropy(e []byte) error { if len(e) != 10 { return ErrDataSize } copy((*id)[6:], e) return nil } // Compare returns an integer comparing id and other lexicographically. // The result will be 0 if id==other, -1 if id < other, and +1 if id > other. func (id ULID) Compare(other ULID) int { return bytes.Compare(id[:], other[:]) } // Scan implements the sql.Scanner interface. It supports scanning // a string or byte slice. func (id *ULID) Scan(src interface{}) error { switch x := src.(type) { case nil: return nil case string: return id.UnmarshalText([]byte(x)) case []byte: return id.UnmarshalBinary(x) } return ErrScanValue } // Value implements the sql/driver.Valuer interface, returning the ULID as a // slice of bytes, by invoking MarshalBinary. If your use case requires a string // representation instead, you can create a wrapper type that calls String() // instead. // // type stringValuer ulid.ULID // // func (v stringValuer) Value() (driver.Value, error) { // return ulid.ULID(v).String(), nil // } // // // Example usage. // db.Exec("...", stringValuer(id)) // // All valid ULIDs, including zero-value ULIDs, return a valid Value with a nil // error. If your use case requires zero-value ULIDs to return a non-nil error, // you can create a wrapper type that special-cases this behavior. // // var zeroValueULID ulid.ULID // // type invalidZeroValuer ulid.ULID // // func (v invalidZeroValuer) Value() (driver.Value, error) { // if ulid.ULID(v).Compare(zeroValueULID) == 0 { // return nil, fmt.Errorf("zero value") // } // return ulid.ULID(v).Value() // } // // // Example usage. // db.Exec("...", invalidZeroValuer(id)) // func (id ULID) Value() (driver.Value, error) { return id.MarshalBinary() } // Monotonic returns an entropy source that is guaranteed to yield // strictly increasing entropy bytes for the same ULID timestamp. // On conflicts, the previous ULID entropy is incremented with a // random number between 1 and `inc` (inclusive). // // The provided entropy source must actually yield random bytes or else // monotonic reads are not guaranteed to terminate, since there isn't // enough randomness to compute an increment number. // // When `inc == 0`, it'll be set to a secure default of `math.MaxUint32`. // The lower the value of `inc`, the easier the next ULID within the // same millisecond is to guess. If your code depends on ULIDs having // secure entropy bytes, then don't go under this default unless you know // what you're doing. // // The returned type isn't safe for concurrent use. func Monotonic(entropy io.Reader, inc uint64) *MonotonicEntropy { m := MonotonicEntropy{ Reader: bufio.NewReader(entropy), inc: inc, } if m.inc == 0 { m.inc = math.MaxUint32 } if rng, ok := entropy.(*rand.Rand); ok { m.rng = rng } return &m } // MonotonicEntropy is an opaque type that provides monotonic entropy. type MonotonicEntropy struct { io.Reader ms uint64 inc uint64 entropy uint80 rand [8]byte rng *rand.Rand } // MonotonicRead implements the MonotonicReader interface. func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { if !m.entropy.IsZero() && m.ms == ms { err = m.increment() m.entropy.AppendTo(entropy) } else if _, err = io.ReadFull(m.Reader, entropy); err == nil { m.ms = ms m.entropy.SetBytes(entropy) } return err } // increment the previous entropy number with a random number // of up to m.inc (inclusive). func (m *MonotonicEntropy) increment() error { if inc, err := m.random(); err != nil { return err } else if m.entropy.Add(inc) { return ErrMonotonicOverflow } return nil } // random returns a uniform random value in [1, m.inc), reading entropy // from m.Reader. When m.inc == 0 || m.inc == 1, it returns 1. // Adapted from: https://golang.org/pkg/crypto/rand/#Int func (m *MonotonicEntropy) random() (inc uint64, err error) { if m.inc <= 1 { return 1, nil } // Fast path for using a underlying rand.Rand directly. if m.rng != nil { // Range: [1, m.inc) return 1 + uint64(m.rng.Int63n(int64(m.inc))), nil } // bitLen is the maximum bit length needed to encode a value < m.inc. bitLen := bits.Len64(m.inc) // byteLen is the maximum byte length needed to encode a value < m.inc. byteLen := uint(bitLen+7) / 8 // msbitLen is the number of bits in the most significant byte of m.inc-1. msbitLen := uint(bitLen % 8) if msbitLen == 0 { msbitLen = 8 } for inc == 0 || inc >= m.inc { if _, err = io.ReadFull(m.Reader, m.rand[:byteLen]); err != nil { return 0, err } // Clear bits in the first byte to increase the probability // that the candidate is < m.inc. m.rand[0] &= uint8(int(1<<msbitLen) - 1) // Convert the read bytes into an uint64 with byteLen // Optimized unrolled loop. switch byteLen { case 1: inc = uint64(m.rand[0]) case 2: inc = uint64(binary.LittleEndian.Uint16(m.rand[:2])) case 3, 4: inc = uint64(binary.LittleEndian.Uint32(m.rand[:4])) case 5, 6, 7, 8: inc = uint64(binary.LittleEndian.Uint64(m.rand[:8])) } } // Range: [1, m.inc) return 1 + inc, nil } type uint80 struct { Hi uint16 Lo uint64 } func (u *uint80) SetBytes(bs []byte) { u.Hi = binary.BigEndian.Uint16(bs[:2]) u.Lo = binary.BigEndian.Uint64(bs[2:]) } func (u *uint80) AppendTo(bs []byte) { binary.BigEndian.PutUint16(bs[:2], u.Hi) binary.BigEndian.PutUint64(bs[2:], u.Lo) } func (u *uint80) Add(n uint64) (overflow bool) { lo, hi := u.Lo, u.Hi if u.Lo += n; u.Lo < lo { u.Hi++ } return u.Hi < hi } func (u uint80) IsZero() bool { return u.Hi == 0 && u.Lo == 0 }
apache-2.0
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/uikit/NSParagraphStyle.java
11103
/* Copyright 2014-2016 Intel Corporation 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 apple.uikit; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSCoder; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.foundation.protocol.NSCopying; import apple.foundation.protocol.NSMutableCopying; import apple.foundation.protocol.NSSecureCoding; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NFloat; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.ProtocolClassMethod; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * NSParagraphStyle */ @Generated @Library("UIKit") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class NSParagraphStyle extends NSObject implements NSCopying, NSMutableCopying, NSSecureCoding { static { NatJ.register(); } @Generated protected NSParagraphStyle(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native NSParagraphStyle alloc(); @Owned @Generated @Selector("allocWithZone:") public static native NSParagraphStyle allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); /** * This class property returns a shared and cached NSParagraphStyle instance with the default style settings, with same value as the result of [[NSParagraphStyle alloc] init]. */ @Generated @Selector("defaultParagraphStyle") public static native NSParagraphStyle defaultParagraphStyle(); /** * languageName is in ISO lang region format */ @Generated @Selector("defaultWritingDirectionForLanguage:") @NInt public static native long defaultWritingDirectionForLanguage(String languageName); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") public static native NSParagraphStyle new_objc(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("supportsSecureCoding") public static native boolean supportsSecureCoding(); @Generated @Selector("version") @NInt public static native long version_static(); @Generated @Selector("alignment") @NInt public native long alignment(); /** * Tightens inter-character spacing in attempt to fit lines wider than the available space if the line break mode is one of the truncation modes before starting to truncate. NO by default. The maximum amount of tightening performed is determined by the system based on contexts such as font, line width, etc. */ @Generated @Selector("allowsDefaultTighteningForTruncation") public native boolean allowsDefaultTighteningForTruncation(); @Generated @Selector("baseWritingDirection") @NInt public native long baseWritingDirection(); @Generated @Owned @Selector("copyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object copyWithZone(VoidPtr zone); /** * The default tab interval used for locations beyond the last element in tabStops */ @Generated @Selector("defaultTabInterval") @NFloat public native double defaultTabInterval(); @Generated @Selector("encodeWithCoder:") public native void encodeWithCoder(NSCoder coder); /** * Distance from margin to edge appropriate for text direction */ @Generated @Selector("firstLineHeadIndent") @NFloat public native double firstLineHeadIndent(); /** * Distance from margin to front edge of paragraph */ @Generated @Selector("headIndent") @NFloat public native double headIndent(); /** * Specifies the threshold for hyphenation. Valid values lie between 0.0 and 1.0 inclusive. Hyphenation will be attempted when the ratio of the text width as broken without hyphenation to the width of the line fragment is less than the hyphenation factor. When this takes on its default value of 0.0, the layout manager's hyphenation factor is used instead. When both are 0.0, hyphenation is disabled. */ @Generated @Selector("hyphenationFactor") public native float hyphenationFactor(); @Generated @Selector("init") public native NSParagraphStyle init(); @Generated @Selector("initWithCoder:") public native NSParagraphStyle initWithCoder(NSCoder coder); @Generated @Selector("lineBreakMode") @NInt public native long lineBreakMode(); /** * Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. */ @Generated @Selector("lineHeightMultiple") @NFloat public native double lineHeightMultiple(); /** * "Leading": distance between the bottom of one line fragment and top of next (applied between lines in the same container). This value is included in the line fragment heights in layout manager. */ @Generated @Selector("lineSpacing") @NFloat public native double lineSpacing(); /** * 0 implies no maximum. */ @Generated @Selector("maximumLineHeight") @NFloat public native double maximumLineHeight(); /** * Line height is the distance from bottom of descenders to top of ascenders; basically the line fragment height. Does not include lineSpacing (which is added after this computation). */ @Generated @Selector("minimumLineHeight") @NFloat public native double minimumLineHeight(); @Owned @Generated @Selector("mutableCopyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object mutableCopyWithZone(VoidPtr zone); /** * Distance between the bottom of this paragraph and top of next (or the beginning of its paragraphSpacingBefore, if any). */ @Generated @Selector("paragraphSpacing") @NFloat public native double paragraphSpacing(); /** * Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. */ @Generated @Selector("paragraphSpacingBefore") @NFloat public native double paragraphSpacingBefore(); @Generated @ProtocolClassMethod("supportsSecureCoding") public boolean _supportsSecureCoding() { return supportsSecureCoding(); } /** * An array of NSTextTabs. Contents should be ordered by location. The default value is an array of 12 left-aligned tabs at 28pt interval */ @Generated @Selector("tabStops") public native NSArray<? extends NSTextTab> tabStops(); /** * Distance from margin to back edge of paragraph; if negative or 0, from other margin */ @Generated @Selector("tailIndent") @NFloat public native double tailIndent(); /** * Specifies the line break strategies that may be used for laying out the paragraph. The default value is NSLineBreakStrategyNone. */ @Generated @Selector("lineBreakStrategy") @NUInt public native long lineBreakStrategy(); /** * A property controlling the hyphenation behavior for the paragraph associated with the paragraph style. The exact hyphenation logic is dynamically determined by the layout context such as language, platform, etc. When YES, it affects the return value from -hyphenationFactor when the property is set to 0.0. */ @Generated @Selector("usesDefaultHyphenation") public native boolean usesDefaultHyphenation(); }
apache-2.0
seasarorg/s2dao
s2-dao/src/main/java/org/seasar/dao/node/IfNode.java
2029
/* * Copyright 2004-2011 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.dao.node; import org.seasar.dao.CommandContext; import org.seasar.dao.IllegalBoolExpressionRuntimeException; import org.seasar.framework.util.OgnlUtil; /** * @author higa * */ public class IfNode extends ContainerNode { private String expression; private Object parsedExpression; private ElseNode elseNode; public IfNode(String expression) { this.expression = expression; this.parsedExpression = OgnlUtil.parseExpression(expression); } public String getExpression() { return expression; } public ElseNode getElseNode() { return elseNode; } public void setElseNode(ElseNode elseNode) { this.elseNode = elseNode; } /** * @see org.seasar.dao.Node#accept(org.seasar.dao.QueryContext) */ public void accept(CommandContext ctx) { Object result = OgnlUtil.getValue(parsedExpression, ctx); if (result instanceof Boolean) { if (((Boolean) result).booleanValue()) { super.accept(ctx); ctx.setEnabled(true); } else if (elseNode != null) { elseNode.accept(ctx); ctx.setEnabled(true); } } else { throw new IllegalBoolExpressionRuntimeException(expression); } } }
apache-2.0
SEEG-Oxford/ABRAID-MP
src/Common/test/uk/ac/ox/zoo/seeg/abraid/mp/common/service/workflow/support/extent/DiseaseExtentGenerationOutputDataTest.java
1345
package uk.ac.ox.zoo.seeg.abraid.mp.common.service.workflow.support.extent; import org.junit.Test; import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.DiseaseExtentClass; import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.DiseaseOccurrence; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for DiseaseExtentGenerationOutputData. * Copyright (c) 2015 University of Oxford */ public class DiseaseExtentGenerationOutputDataTest { @Test public void constructorBindsFieldsCorrectly() { // Arrange Map<Integer, DiseaseExtentClass> diseaseExtentClasses = new HashMap<>(); Map<Integer, Integer> occurrenceCounts = new HashMap<>(); Map<Integer, Collection<DiseaseOccurrence>> latestOccurrences = new HashMap<>(); // Act DiseaseExtentGenerationOutputData result = new DiseaseExtentGenerationOutputData( diseaseExtentClasses, occurrenceCounts, latestOccurrences); // Assert assertThat(result.getDiseaseExtentClassByGaulCode()).isSameAs(diseaseExtentClasses); assertThat(result.getOccurrenceCounts()).isSameAs(occurrenceCounts); assertThat(result.getLatestOccurrencesByGaulCode()).isSameAs(latestOccurrences); } }
apache-2.0
spohnan/geowave
core/mapreduce/src/main/java/org/locationtech/geowave/mapreduce/HadoopDataAdapter.java
1132
/** * Copyright (c) 2013-2019 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.mapreduce; import org.apache.hadoop.io.Writable; import org.locationtech.geowave.core.store.api.DataTypeAdapter; /** * This is an interface that extends data adapter to allow map reduce jobs to easily convert hadoop * writable objects to and from the geowave native representation of the objects. This allow for * generally applicable map reduce jobs to be written using base classes for the mapper that can * handle translations. * * @param <T> the native type * @param <W> the writable type */ public interface HadoopDataAdapter<T, W extends Writable> extends DataTypeAdapter<T> { public HadoopWritableSerializer<T, W> createWritableSerializer(); }
apache-2.0
summerpulse/amlexo
src/com/google/android/exoplayer/MediaFormat.java
8647
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer; import com.google.android.exoplayer.util.Util; import android.annotation.SuppressLint; import android.annotation.TargetApi; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Encapsulates the information describing the format of media data, be it audio * or video. */ public class MediaFormat { public static final int NO_VALUE = -1; public final String mimeType; public final int maxInputSize; public final int width; public final int height; public final int channelCount; public final int sampleRate; private int maxWidth; private int maxHeight; public final List<byte[]> initializationData; // Lazy-initialized hashcode. private int hashCode; // Possibly-lazy-initialized framework media format. private android.media.MediaFormat frameworkMediaFormat; @TargetApi(16) public static MediaFormat createFromFrameworkMediaFormatV16(android.media.MediaFormat format) { return new MediaFormat(format); } public static MediaFormat createVideoFormat(String mimeType, int maxInputSize, int width, int height, List<byte[]> initializationData) { return new MediaFormat(mimeType, maxInputSize, width, height, NO_VALUE, NO_VALUE, initializationData); } public static MediaFormat createAudioFormat(String mimeType, int maxInputSize, int channelCount, int sampleRate, List<byte[]> initializationData) { return new MediaFormat(mimeType, maxInputSize, NO_VALUE, NO_VALUE, channelCount, sampleRate, initializationData); } @TargetApi(16) private MediaFormat(android.media.MediaFormat format) { this.frameworkMediaFormat = format; mimeType = format.getString(android.media.MediaFormat.KEY_MIME); maxInputSize = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_MAX_INPUT_SIZE); width = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_WIDTH); height = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_HEIGHT); channelCount = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_CHANNEL_COUNT); sampleRate = getOptionalIntegerV16(format, android.media.MediaFormat.KEY_SAMPLE_RATE); initializationData = new ArrayList<byte[]>(); for (int i = 0; format.containsKey("csd-" + i); i++) { ByteBuffer buffer = format.getByteBuffer("csd-" + i); byte[] data = new byte[buffer.limit()]; buffer.get(data); initializationData.add(data); buffer.flip(); } maxWidth = NO_VALUE; maxHeight = NO_VALUE; } private MediaFormat(String mimeType, int maxInputSize, int width, int height, int channelCount, int sampleRate, List<byte[]> initializationData) { this.mimeType = mimeType; this.maxInputSize = maxInputSize; this.width = width; this.height = height; this.channelCount = channelCount; this.sampleRate = sampleRate; this.initializationData = initializationData == null ? Collections.<byte[]> emptyList() : initializationData; maxWidth = NO_VALUE; maxHeight = NO_VALUE; } public void setMaxVideoDimensions(int maxWidth, int maxHeight) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; if (frameworkMediaFormat != null) { maybeSetMaxDimensionsV16(frameworkMediaFormat); } } public int getMaxVideoWidth() { return maxWidth; } public int getMaxVideoHeight() { return maxHeight; } @Override public int hashCode() { if (hashCode == 0) { int result = 17; result = 31 * result + mimeType == null ? 0 : mimeType.hashCode(); result = 31 * result + maxInputSize; result = 31 * result + width; result = 31 * result + height; result = 31 * result + maxWidth; result = 31 * result + maxHeight; result = 31 * result + channelCount; result = 31 * result + sampleRate; for (int i = 0; i < initializationData.size(); i++) { result = 31 * result + Arrays.hashCode(initializationData.get(i)); } hashCode = result; } return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } return equalsInternal((MediaFormat) obj, false); } public boolean equals(MediaFormat other, boolean ignoreMaxDimensions) { if (this == other) { return true; } if (other == null) { return false; } return equalsInternal(other, ignoreMaxDimensions); } private boolean equalsInternal(MediaFormat other, boolean ignoreMaxDimensions) { if (maxInputSize != other.maxInputSize || width != other.width || height != other.height || (!ignoreMaxDimensions && (maxWidth != other.maxWidth || maxHeight != other.maxHeight)) || channelCount != other.channelCount || sampleRate != other.sampleRate || !Util.areEqual(mimeType, other.mimeType) || initializationData.size() != other.initializationData.size()) { return false; } for (int i = 0; i < initializationData.size(); i++) { if (!Arrays.equals(initializationData.get(i), other.initializationData.get(i))) { return false; } } return true; } @Override public String toString() { return "MediaFormat(" + mimeType + ", " + maxInputSize + ", " + width + ", " + height + ", " + channelCount + ", " + sampleRate + ", " + maxWidth + ", " + maxHeight + ")"; } /** * @return A {@link MediaFormat} representation of this format. */ @TargetApi(16) public final android.media.MediaFormat getFrameworkMediaFormatV16() { if (frameworkMediaFormat == null) { android.media.MediaFormat format = new android.media.MediaFormat(); format.setString(android.media.MediaFormat.KEY_MIME, mimeType); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_INPUT_SIZE, maxInputSize); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_WIDTH, width); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_HEIGHT, height); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_CHANNEL_COUNT, channelCount); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_SAMPLE_RATE, sampleRate); for (int i = 0; i < initializationData.size(); i++) { format.setByteBuffer("csd-" + i, ByteBuffer.wrap(initializationData.get(i))); } maybeSetMaxDimensionsV16(format); frameworkMediaFormat = format; } return frameworkMediaFormat; } @SuppressLint("InlinedApi") @TargetApi(16) private final void maybeSetMaxDimensionsV16(android.media.MediaFormat format) { maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_WIDTH, maxWidth); maybeSetIntegerV16(format, android.media.MediaFormat.KEY_MAX_HEIGHT, maxHeight); } @TargetApi(16) private static final void maybeSetIntegerV16(android.media.MediaFormat format, String key, int value) { if (value != NO_VALUE) { format.setInteger(key, value); } } @TargetApi(16) private static final int getOptionalIntegerV16(android.media.MediaFormat format, String key) { return format.containsKey(key) ? format.getInteger(key) : NO_VALUE; } }
apache-2.0
wealthfront/kawala
kawala-testing/src/main/java/com/kaching/platform/testing/AllowDNSResolution.java
1246
/** * Copyright 2010 Wealthfront 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.kaching.platform.testing; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Under the regime of {@link LessIOSecurityManager}, only classes annotated * with this annotation may use the DNS system to resolve hostnames or IP * addresses. * * Annotating a class with {@link AllowNetworkMulticast}, * {@link AllowNetworkListen}, or {@link AllowNetworkAccess}, implies permission * to use the DNS system as described above. */ @Retention(RUNTIME) @Target(TYPE) public @interface AllowDNSResolution { }
apache-2.0
gawkermedia/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201601/o/TargetingIdea.java
5645
/** * TargetingIdea.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201601.o; /** * Represents a {@link TargetingIdea} returned by search criteria * specified in * the {@link TargetingIdeaSelector}. Targeting ideas are * keywords or placements * that are similar to those the user inputs. */ public class TargetingIdea implements java.io.Serializable { /* Map of * {@link com.google.ads.api.services.targetingideas.external.AttributeType} * to {@link Attribute}. Stores all data retrieved for each key {@code * AttributeType}. * <span class="constraint Required">This field is required * and should not be {@code null}.</span> */ private com.google.api.ads.adwords.axis.v201601.o.Type_AttributeMapEntry[] data; public TargetingIdea() { } public TargetingIdea( com.google.api.ads.adwords.axis.v201601.o.Type_AttributeMapEntry[] data) { this.data = data; } /** * Gets the data value for this TargetingIdea. * * @return data * Map of * {@link com.google.ads.api.services.targetingideas.external.AttributeType} * to {@link Attribute}. Stores all data retrieved for each key {@code * AttributeType}. * <span class="constraint Required">This field is required * and should not be {@code null}.</span> */ public com.google.api.ads.adwords.axis.v201601.o.Type_AttributeMapEntry[] getData() { return data; } /** * Sets the data value for this TargetingIdea. * * @param data * Map of * {@link com.google.ads.api.services.targetingideas.external.AttributeType} * to {@link Attribute}. Stores all data retrieved for each key {@code * AttributeType}. * <span class="constraint Required">This field is required * and should not be {@code null}.</span> */ public void setData(com.google.api.ads.adwords.axis.v201601.o.Type_AttributeMapEntry[] data) { this.data = data; } public com.google.api.ads.adwords.axis.v201601.o.Type_AttributeMapEntry getData(int i) { return this.data[i]; } public void setData(int i, com.google.api.ads.adwords.axis.v201601.o.Type_AttributeMapEntry _value) { this.data[i] = _value; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof TargetingIdea)) return false; TargetingIdea other = (TargetingIdea) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.data==null && other.getData()==null) || (this.data!=null && java.util.Arrays.equals(this.data, other.getData()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getData() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getData()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getData(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(TargetingIdea.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/o/v201601", "TargetingIdea")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("data"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/o/v201601", "data")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/o/v201601", "Type_AttributeMapEntry")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201511/SwiffyConversionErrorReason.java
1709
package com.google.api.ads.dfp.jaxws.v201511; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SwiffyConversionError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SwiffyConversionError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="SERVER_ERROR"/> * &lt;enumeration value="INVALID_FLASH_FILE"/> * &lt;enumeration value="UNSUPPORTED_FLASH"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "SwiffyConversionError.Reason") @XmlEnum public enum SwiffyConversionErrorReason { /** * * Indicates the Swiffy service has an internal error that prevents the flash * asset being converted. * * */ SERVER_ERROR, /** * * Indicates the uploaded flash asset is not a valid flash file. * * */ INVALID_FLASH_FILE, /** * * Indicates the Swiffy service currently does not support converting this * flash asset. * * */ UNSUPPORTED_FLASH, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static SwiffyConversionErrorReason fromValue(String v) { return valueOf(v); } }
apache-2.0
KnowledgeLinks/dpla-service-hub
api.py
14727
"""REST API for DP.LA Service Hub BIBCAT Aggregator Feed""" __author__ = "Jeremy Nelson, Mike Stabile" import click import datetime import json import math import os import pkg_resources import xml.etree.ElementTree as etree import requests import rdflib import urllib.parse import reports import bibcat.rml.processor as processor from zipfile import ZipFile, ZIP_DEFLATED from elasticsearch_dsl import Search, Q from flask import abort, Flask, jsonify, request, render_template, Response from flask import flash, url_for from flask import flash #from flask_cache import Cache from resync import CapabilityList, ResourceDump, ResourceDumpManifest from resync import ResourceList from resync.resource import Resource from resync.resource_list import ResourceListDupeError from resync.dump import Dump app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile('config.py') from rdfframework.rml import RmlManager from rdfframework.configuration import RdfConfigManager from rdfframework.datamanager import DefinitionManager from rdfframework.datatypes import RdfNsManager RmlManager().register_defs([('package_all', 'bibcat.maps')]) # Define vocabulary and definition file locations DefinitionManager().add_file_locations([('vocabularies', ['rdf', 'rdfs', 'owl', 'schema', 'bf', 'skos', 'dcterm']), ('package_all', 'bibcat.rdfw-definitions')]) # Register RDF namespaces to use RdfNsManager({'acl': '<http://www.w3.org/ns/auth/acl#>', 'bd': '<http://www.bigdata.com/rdf#>', 'bf': 'http://id.loc.gov/ontologies/bibframe/', 'dbo': 'http://dbpedia.org/ontology/', 'dbp': 'http://dbpedia.org/property/', 'dbr': 'http://dbpedia.org/resource/', 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterm': 'http://purl.org/dc/terms/', 'dpla': 'http://dp.la/about/map/', 'edm': 'http://www.europeana.eu/schemas/edm/', 'es': 'http://knowledgelinks.io/ns/elasticsearch/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'loc': 'http://id.loc.gov/authorities/', 'm21': '<http://knowledgelinks.io/ns/marc21/>', 'mads': '<http://www.loc.gov/mads/rdf/v1#>', 'mods': 'http://www.loc.gov/mods/v3#', 'ore': 'http://www.openarchives.org/ore/terms/', 'owl': 'http://www.w3.org/2002/07/owl#', 'relators': 'http://id.loc.gov/vocabulary/relators/', 'schema': 'http://schema.org/', 'skos': 'http://www.w3.org/2004/02/skos/core#', 'xsd': 'http://www.w3.org/2001/XMLSchema#'}) CONFIG_MANAGER = RdfConfigManager(app.config, verify=False) CONNECTIONS = CONFIG_MANAGER.conns BF = rdflib.Namespace("http://id.loc.gov/ontologies/bibframe/") W3C_DATE = "%Y-%m-%dT%H:%M:%SZ" __version__ = "1.0.0" #cache = Cache(app, config={"CACHE_TYPE": "filesystem", # "CACHE_DIR": os.path.join(PROJECT_BASE, "cache")}) def __run_query__(query): """Helper function returns results from sparql query""" result = requests.post(app.config.get("TRIPLESTORE_URL"), data={"query": query, "format": "json"}) if result.status_code < 400: return result.json().get('results').get('bindings') def __get_instances__(offset=0): """Helper function used by siteindex and resourcedump views Args: offset(int): offset number of records """ offset = int(offset)*50000 sparql = """ SELECT DISTINCT ?instance ?date WHERE {{ ?instance rdf:type bf:Instance . OPTIONAL {{ ?instance bf:generationProcess ?process . ?process bf:generationDate ?date . }} }} ORDER BY ?instance LIMIT 50000 OFFSET {0}""".format(offset) instances = CONNECTIONS.datastore.query(sparql) return instances def __get_mod_date__(entity_iri=None): if "MOD_DATE" in app.config: return app.config.get("MOD_DATE") return datetime.datetime.utcnow().strftime(W3C_DATE) def __generate_profile__(instance_uri): search = Search(using=CONNECTIONS.search.es).query( Q("term", uri="{}#Work".format(instance_uri))).source( ["bf_hasInstance.bf_hasItem.rml_map.map4_json_ld"]) result = search.execute() if len(result.hits.hits) < 1: #abort(404) #click.echo("{}#Work not found".format(instance_uri)) return if len(result.hits.hits[0]["_source"]) < 1: #abort(404) #click.echo("{}#Work missing _source".format(instance_uri)) return raw_map4 = result.hits.hits[0]["_source"]["bf_hasInstance"][0]\ ["bf_hasItem"][0]["rml_map"]["map4_json_ld"] return raw_map4 def __generate_resource_dump__(): r_dump = ResourceDump() r_dump.ln.append({"rel": "resourcesync", "href": url_for('capability_list')}) bindings = CONNECTIONS.datastore.query(""" SELECT (count(?s) as ?count) WHERE { ?s rdf:type bf:Instance . ?item bf:itemOf ?s . }""") count = int(bindings[0].get('count').get('value')) shards = math.ceil(count/50000) for i in range(0, shards): zip_info = __generate_zip_file__(i) try: zip_modified = datetime.datetime.fromtimestamp(zip_info.get('date')) last_mod = zip_modified.strftime("%Y-%m-%d") except TypeError: last_mod = zip_info.get('date')[0:10] click.echo("Total errors {:,}".format(len(zip_info.get('errors')))) r_dump.add( Resource(url_for('resource_zip', count=i*50000), lastmod=last_mod, mime_type="application/zip", length=zip_info.get("size") ) ) return r_dump def __generate_zip_file__(offset=0): start = datetime.datetime.utcnow() click.echo("Started at {}".format(start.ctime())) manifest = ResourceDumpManifest() manifest.modified = datetime.datetime.utcnow().isoformat() manifest.ln.append({"rel": "resourcesync", "href": url_for('capability_list')}) file_name = "{}-{:03}.zip".format( datetime.datetime.utcnow().toordinal(), offset) tmp_location = os.path.join(app.config.get("DIRECTORIES")[0].get("path"), "dump/{}".format(file_name)) if os.path.exists(tmp_location) is True: return {"date": os.path.getmtime(tmp_location), "size": os.path.getsize(tmp_location)} dump_zip = ZipFile(tmp_location, mode="w", compression=ZIP_DEFLATED, allowZip64=True) instances = __get_instances__(offset) errors = [] click.echo("Iterating through {:,} instances".format(len(instances))) for i,row in enumerate(instances): instance_iri = row.get("instance").get('value') key = instance_iri.split("/")[-1] if not "date" in row: last_mod = __get_mod_date__() else: last_mod = "{}".format(row.get("date").get("value")[0:10]) path = "resources/{}.json".format(key) if not i%25 and i > 0: click.echo(".", nl=False) if not i%100: click.echo("{:,}".format(i), nl=False) raw_json = __generate_profile__(instance_iri) if raw_json is None: errors.append(instance_iri) continue elif len(raw_json) < 1: click.echo(instance_iri, nl=False) break dump_zip.writestr(path, raw_json) manifest.add( Resource(instance_iri, lastmod=last_mod, length="{}".format(len(raw_json)), path=path)) dump_zip.writestr("manifest.xml", manifest.as_xml()) dump_zip.close() end = datetime.datetime.utcnow() zip_size = os.stat(tmp_location).st_size click.echo("Finished at {}, total time {} min, size={}".format( end.ctime(), (end-start).seconds / 60.0, i)) return {"date": datetime.datetime.utcnow().isoformat(), "size": zip_size, "errors": errors} @app.template_filter("pretty_num") def nice_number(raw_number): if raw_number is None: return '' return "{:,}".format(int(raw_number)) @app.errorhandler(404) def page_not_found(e): return render_template("404.html", error=e), 404 @app.route("/") def home(): """Default page""" result = CONNECTIONS.datastore.query( "SELECT (COUNT(*) as ?count) WHERE {?s ?p ?o }") count = result[0].get("count").get("value") if int(count) < 1: flash("Triplestore is empty, please load service hub RDF data") return render_template("index.html", version=__version__, count="{:,}".format(int(count))) @app.route("/reports/") @app.route("/reports/<path:name>") def reporting(name=None): if name is None: return render_template("reports/index.html") report_output = reports.report_router(name) if report_output is None: abort(404) return render_template( "reports/{0}.html".format(name), data=report_output) @app.route("/<path:type_of>/<path:name>") def authority_view(type_of, name=None): """Generates a RDF:Description view for Service Hub name, topic, agent, and other types of BIBFRAME entities Args: type_of(str): Type of entity name(str): slug of name, title, or other textual identifier """ if name is None: # Display brows view of authorities return "Browse display for {}".format(type_of) uri = "{0}{1}/{2}".format(app.config.get("BASE_URL"), type_of, name) entity_sparql = PREFIX + """ SELECT DISTINCT ?label ?value WHERE {{ <{entity}> rdf:type {type_of} . OPTIONAL {{ <{entity}> rdfs:label ?label }} OPTIONAL {{ <{entity}> rdf:value ?value }} }}""".format(entity=uri, type_of="bf:{}".format(type_of.title())) entity_results = __run_query__(entity_sparql) if len(entity_results) < 1: abort(404) entity_graph = rdflib.Graph() iri = rdflib.URIRef(uri) entity_graph.add((iri, rdflib.RDF.type, getattr(BF, type_of.title()))) for row in entity_results: if 'label' in row: literal = rdflib.Literal(row.get('label').get('value'), datatype=row.get('label').get('datatype')) entity_graph.add((iri, rdflib.RDFS.label, literal)) if 'value' in row: literal = rdflib.Literal(row.get('value').get('value'), datatype=row.get('value').get('datatype')) entity_graph.add((iri, rdflib.RDF.value, literal)) MAPv4_context["bf"] = str(BF) raw_entity = entity_graph.serialize(format='json-ld', context=MAPv4_context) return Response(raw_entity, mimetype="application/json") @app.route("/capabilitylist.xml") def capability_list(): cap_list = CapabilityList() cap_list.modified = __get_mod_date__() cap_list.ln.append({"href": url_for('capability_list'), "rel": "describedby", "type": "application/xml"}) cap_list.add(Resource(url_for('site_index'), capability="resourcelist")) cap_list.add(Resource(url_for('resource_dump'), capability="resourcedump")) return Response(cap_list.as_xml(), mimetype="text/xml") @app.route("/resourcedump.xml") def resource_dump(): xml = __generate_resource_dump__() return Response(xml.as_xml(), "text/xml") @app.route("/resourcedump-<int:count>.zip") def resource_zip(count): zip_location = os.path.join(app.config.get("DIRECTORIES")[0].get("path"), "dump/resour{}".format(file_name)) zip_location = os.path.join(PROJECT_BASE, "dump/{}.zip".format(count)) if not os.path.exists(zip_location): abort(404) return send_file(zip_location) @app.route("/siteindex.xml") #@cache.cached(timeout=86400) # Cached for 1 day def site_index(): """Generates siteindex XML, each sitemap has a maximum of 50k links dynamically generates the necessary number of sitemaps in the template""" result = CONNECTIONS.datastore.query("""SELECT (count(?work) as ?count) WHERE { ?work rdf:type bf:Work . ?instance bf:instanceOf ?work . ?item bf:itemOf ?instance . }""") count = int(result[0].get('count').get('value')) shards = math.ceil(count/50000) mod_date = app.config.get('MOD_DATE') if mod_date is None: mod_date=datetime.datetime.utcnow().strftime("%Y-%m-%d") xml = render_template("siteindex.xml", count=range(1, shards+1), last_modified=mod_date) return Response(xml, mimetype="text/xml") @app.route("/sitemap<int:offset>.xml", methods=["GET"]) #@cache.cached(timeout=86400) def sitemap(offset=0): if offset > 0: offset = offset - 1 instances = __get_instances__(offset) resource_list = ResourceList() dedups = 0 for i,row in enumerate(instances): instance = row.get('instance') if "date" in row: last_mod = row.get("date").get("value")[0:10] else: last_mod = datetime.datetime.utcnow().strftime( W3C_DATE) try: resource_list.add( Resource("{}.json".format(instance.get("value")), lastmod=last_mod) ) except ResourceListDupeError: dedups += 1 continue xml = resource_list.as_xml() return Response(xml, mimetype="text/xml") @app.route("/<path:uid>.json") def detail(uid=None): """Generates DPLA Map V4 JSON-LD""" if uid.startswith('favicon'): return '' click.echo("UID is {}".format(uid)) if uid is None: abort(404) uri = app.config.get("BASE_URL") + uid raw_map_4 = __generate_profile__(uri) return Response(raw_map_4, mimetype="application/json") if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Noccaea/Noccaea sintenisii/Thlaspi sintenisii sintenisii/README.md
181
# Thlaspi sintenisii subsp. sintenisii SUBSPECIES #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
apache-2.0
Clydeside/ALipatov
chapter_003/src/main/java/ru/job4j/convertation/ConvertList.java
1197
package ru.job4j.convertation; import java.util.ArrayList; import java.util.List; public class ConvertList { public ArrayList<Integer> toList(int[][] array) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { list.add(array[i][j]); } } return list; } public int[][] toArray(ArrayList<Integer> list, int rows) { int[][] array = new int[rows][rows]; int mod = list.size() % rows; for (int i = 0; i < mod; i++) { list.add(0); } int[] arr = list.stream().mapToInt(i->i).toArray(); int temp = -1; for (int i = 0; i < arr.length; i++) { if ((i % rows) == 0) temp++; array[temp][i % rows] = arr[i]; } return array; } public List<Integer> convert(List<int[]> list) { List<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < list.size(); i++) { for (Integer elem : list.get(i)) { result.add(elem); } } return result; } }
apache-2.0
copy4dev/jee-base
src/main/java/com/cn/jee/modules/qrtz/web/QrtzJobDetailsController.java
3376
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.cn.jee.modules.qrtz.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.cn.jee.common.config.Global; import com.cn.jee.common.persistence.Page; import com.cn.jee.common.utils.StringUtils; import com.cn.jee.common.web.BaseController; import com.cn.jee.modules.qrtz.entity.QrtzJobDetails; import com.cn.jee.modules.qrtz.service.QrtzJobDetailsService; /** * 触发器Job明细Controller * * @author 1002360 * @version 2017-03-18 */ @Controller @RequestMapping(value = "${adminPath}/qrtz/qrtzJobDetails") public class QrtzJobDetailsController extends BaseController { @Autowired private QrtzJobDetailsService qrtzJobDetailsService; @ModelAttribute public QrtzJobDetails get(@RequestParam(value = "schedName", required = false) String schedName, @RequestParam(value = "jobName", required = false) String jobName, @RequestParam(value = "jobGroup", required = false) String jobGroup) { QrtzJobDetails entity = null; if (StringUtils.isNotBlank(schedName) && StringUtils.isNotBlank(jobName) && StringUtils.isNotBlank(jobGroup)) { entity = qrtzJobDetailsService.get(schedName, jobName, jobGroup); } if (entity == null) { entity = new QrtzJobDetails(); } return entity; } @RequiresPermissions("qrtz:qrtzJobDetails:view") @RequestMapping(value = { "list", "" }) public String list(QrtzJobDetails qrtzJobDetails, HttpServletRequest request, HttpServletResponse response, Model model) { Page<QrtzJobDetails> page = qrtzJobDetailsService.findPage(new Page<QrtzJobDetails>(request, response), qrtzJobDetails); model.addAttribute("page", page); return "modules/qrtz/qrtzJobDetailsList"; } @RequiresPermissions("qrtz:qrtzJobDetails:view") @RequestMapping(value = "form") public String form(QrtzJobDetails qrtzJobDetails, Model model) { model.addAttribute("qrtzJobDetails", qrtzJobDetails); return "modules/qrtz/qrtzJobDetailsForm"; } @RequiresPermissions("qrtz:qrtzJobDetails:edit") @RequestMapping(value = "save") public String save(QrtzJobDetails qrtzJobDetails, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, qrtzJobDetails)) { return form(qrtzJobDetails, model); } qrtzJobDetailsService.save(qrtzJobDetails); addMessage(redirectAttributes, "保存任务明细成功"); return "redirect:" + Global.getAdminPath() + "/qrtz/qrtzJobDetails/?repage"; } @RequiresPermissions("qrtz:qrtzJobDetails:edit") @RequestMapping(value = "delete") public String delete(QrtzJobDetails qrtzJobDetails, RedirectAttributes redirectAttributes) { qrtzJobDetailsService.delete(qrtzJobDetails); addMessage(redirectAttributes, "删除触发器Job明细成功"); return "redirect:" + Global.getAdminPath() + "/qrtz/qrtzJobDetails/?repage"; } }
apache-2.0
ebean-orm/ebean-orm.github.io
apidoc/11/src-html/io/ebean/config/dbplatform/postgres/PostgresDbEncrypt.html
3927
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Source code</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <div class="sourceContainer"> <pre><span class="sourceLineNo">001</span>package io.ebean.config.dbplatform.postgres;<a name="line.1"></a> <span class="sourceLineNo">002</span><a name="line.2"></a> <span class="sourceLineNo">003</span>import io.ebean.config.dbplatform.AbstractDbEncrypt;<a name="line.3"></a> <span class="sourceLineNo">004</span>import io.ebean.config.dbplatform.DbEncryptFunction;<a name="line.4"></a> <span class="sourceLineNo">005</span><a name="line.5"></a> <span class="sourceLineNo">006</span>/**<a name="line.6"></a> <span class="sourceLineNo">007</span> * Postgres pgp_sym_encrypt pgp_sym_decrypt based encryption support.<a name="line.7"></a> <span class="sourceLineNo">008</span> */<a name="line.8"></a> <span class="sourceLineNo">009</span>public class PostgresDbEncrypt extends AbstractDbEncrypt {<a name="line.9"></a> <span class="sourceLineNo">010</span><a name="line.10"></a> <span class="sourceLineNo">011</span> public PostgresDbEncrypt() {<a name="line.11"></a> <span class="sourceLineNo">012</span> this.varcharEncryptFunction = new PgVarcharFunction();<a name="line.12"></a> <span class="sourceLineNo">013</span> this.dateEncryptFunction = new PgDateFunction();<a name="line.13"></a> <span class="sourceLineNo">014</span> }<a name="line.14"></a> <span class="sourceLineNo">015</span><a name="line.15"></a> <span class="sourceLineNo">016</span> private static class PgVarcharFunction implements DbEncryptFunction {<a name="line.16"></a> <span class="sourceLineNo">017</span><a name="line.17"></a> <span class="sourceLineNo">018</span> @Override<a name="line.18"></a> <span class="sourceLineNo">019</span> public String getDecryptSql(String columnWithTableAlias) {<a name="line.19"></a> <span class="sourceLineNo">020</span> return "pgp_sym_decrypt(" + columnWithTableAlias + ",?)";<a name="line.20"></a> <span class="sourceLineNo">021</span> }<a name="line.21"></a> <span class="sourceLineNo">022</span><a name="line.22"></a> <span class="sourceLineNo">023</span> @Override<a name="line.23"></a> <span class="sourceLineNo">024</span> public String getEncryptBindSql() {<a name="line.24"></a> <span class="sourceLineNo">025</span> return "pgp_sym_encrypt(?,?)";<a name="line.25"></a> <span class="sourceLineNo">026</span> }<a name="line.26"></a> <span class="sourceLineNo">027</span> }<a name="line.27"></a> <span class="sourceLineNo">028</span><a name="line.28"></a> <span class="sourceLineNo">029</span> private static class PgDateFunction implements DbEncryptFunction {<a name="line.29"></a> <span class="sourceLineNo">030</span><a name="line.30"></a> <span class="sourceLineNo">031</span> @Override<a name="line.31"></a> <span class="sourceLineNo">032</span> public String getDecryptSql(String columnWithTableAlias) {<a name="line.32"></a> <span class="sourceLineNo">033</span> return "to_date(pgp_sym_decrypt(" + columnWithTableAlias + ",?),'YYYYMMDD')";<a name="line.33"></a> <span class="sourceLineNo">034</span> }<a name="line.34"></a> <span class="sourceLineNo">035</span><a name="line.35"></a> <span class="sourceLineNo">036</span> @Override<a name="line.36"></a> <span class="sourceLineNo">037</span> public String getEncryptBindSql() {<a name="line.37"></a> <span class="sourceLineNo">038</span> return "pgp_sym_encrypt(to_char(?::date,'YYYYMMDD'),?)";<a name="line.38"></a> <span class="sourceLineNo">039</span> }<a name="line.39"></a> <span class="sourceLineNo">040</span> }<a name="line.40"></a> <span class="sourceLineNo">041</span>}<a name="line.41"></a> </pre> </div> </body> </html>
apache-2.0
resin-io-library/base-images
balena-base-images/python/orange-pi-zero/debian/bookworm/3.7.12/run/Dockerfile
4099
# AUTOGENERATED FILE FROM balenalib/orange-pi-zero-debian:bookworm-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <[email protected]>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.7.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \ && echo "d8d0dd3457e8491022d8e736860f4dd747a0a8bb93a3b1319fe9d2610b0006b0 Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-libffi3.3.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bookworm \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.7.12, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
apache-2.0
Gaia3D/mago3d
mago3d-user/src/main/java/gaia3d/domain/YOrN.java
52
package gaia3d.domain; public enum YOrN { Y, N; }
apache-2.0
Shmuma/hbase
docs/apidocs/org/apache/hadoop/hbase/rest/protobuf/generated/class-use/CellMessage.html
6477
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Mon Jul 18 08:23:49 PDT 2011 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage (HBase 0.90.3-cdh3u1 API) </TITLE> <META NAME="date" CONTENT="2011-07-18"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage (HBase 0.90.3-cdh3u1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../org/apache/hadoop/hbase/rest/protobuf/generated/CellMessage.html" title="class in org.apache.hadoop.hbase.rest.protobuf.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?org/apache/hadoop/hbase/rest/protobuf/generated//class-useCellMessage.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CellMessage.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage</B></H2> </CENTER> No usage of org.apache.hadoop.hbase.rest.protobuf.generated.CellMessage <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../org/apache/hadoop/hbase/rest/protobuf/generated/CellMessage.html" title="class in org.apache.hadoop.hbase.rest.protobuf.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?org/apache/hadoop/hbase/rest/protobuf/generated//class-useCellMessage.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CellMessage.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2011 <a href="http://www.cloudera.com">Cloudera</a>. All Rights Reserved. </BODY> </HTML>
apache-2.0
hongqixianfeng/test1111
README.md
23
# test1111 it's a test
apache-2.0
skluth/RooUnfold
src/RooUnfold.h
11186
//=====================================================================-*-C++-*- // File and Version Information: // $Id$ // // Description: // Unfolding framework base class. // // Author: Tim Adye <[email protected]> // //============================================================================== #ifndef ROOUNFOLD_HH #define ROOUNFOLD_HH #include "TNamed.h" #include "TVectorD.h" #include "TMatrixD.h" #include "RooUnfoldResponse.h" class TH1; class TH1D; class RooUnfold : public TNamed { public: enum Algorithm { // Selection of unfolding algorithm: kNone, // no unfolding (dummy routines in RooUnfold) kBayes, // RooUnfoldBayes kSVD, // RooUnfoldSvd kBinByBin, // RooUnfoldBinByBin kTUnfold, // RooUnfoldTUnfold kInvert, // RooUnfoldInvert kDagostini // RooUnfoldDagostini }; enum ErrorTreatment { // Error treatment: kNoError, // no error treatment: returns sqrt(N) kErrors, // bin-by-bin errors (diagonal covariance matrix) kCovariance, // covariance matrix from unfolding kCovToy, // covariance matrix from toy MC kDefault=-1 // not specified }; static RooUnfold* New (Algorithm alg, const RooUnfoldResponse* res, const TH1* meas, Double_t regparm= -1e30, const char* name= 0, const char* title= 0); // Standard methods RooUnfold(); // default constructor RooUnfold (const char* name, const char* title); // named constructor RooUnfold (const TString& name, const TString& title); // named constructor RooUnfold (const RooUnfold& rhs); // copy constructor virtual ~RooUnfold(); // destructor RooUnfold& operator= (const RooUnfold& rhs); // assignment operator virtual RooUnfold* Clone (const char* newname= 0) const; // Special constructors RooUnfold (const RooUnfoldResponse* res, const TH1* meas, const char* name= 0, const char* title= 0); // Set up an existing object virtual RooUnfold& Setup (const RooUnfoldResponse* res, const TH1* meas); virtual void SetMeasured (const TH1* meas); virtual void SetMeasured (const TVectorD& meas, const TMatrixD& cov); virtual void SetMeasured (const TVectorD& meas, const TVectorD& err); virtual void SetMeasuredCov (const TMatrixD& cov); virtual void SetResponse (const RooUnfoldResponse* res); virtual void SetResponse (RooUnfoldResponse* res, Bool_t takeOwnership); virtual void Reset (); // Accessors virtual const RooUnfoldResponse* response() const; virtual const TH1* Hmeasured() const; virtual TH1* Hreco (ErrorTreatment withError=kErrors); const TVectorD& Vmeasured() const; // Measured distribution as a TVectorD const TVectorD& Emeasured() const; // Measured distribution errors as a TVectorD const TMatrixD& GetMeasuredCov() const; // Measured distribution covariance matrix // Methods for unfolding tests virtual TH1* HrecoMeasured(); Double_t Chi2measured(); virtual TVectorD& Vreco(); virtual TMatrixD Ereco (ErrorTreatment witherror=kCovariance); virtual TVectorD ErecoV (ErrorTreatment witherror=kErrors); virtual TMatrixD Wreco (ErrorTreatment witherror=kCovariance); virtual Int_t verbose() const; virtual void SetVerbose (Int_t level); virtual void IncludeSystematics (Int_t dosys= 1); virtual Int_t SystematicsIncluded() const; virtual Int_t NToys() const; // Number of toys virtual void SetNToys (Int_t toys); // Set number of toys virtual Int_t Overflow() const; virtual void PrintTable (std::ostream& o, const TH1* hTrue= 0, ErrorTreatment withError=kDefault); virtual void SetRegParm (Double_t parm); virtual Double_t GetRegParm() const; // Get Regularisation Parameter Double_t Chi2 (const TH1* hTrue,ErrorTreatment DoChi2=kCovariance); Double_t GetMinParm() const; Double_t GetMaxParm() const; Double_t GetStepSizeParm() const; Double_t GetDefaultParm() const; RooUnfold* RunToy() const; void Print(Option_t* opt="") const; static void PrintTable (std::ostream& o, const TH1* hTrainTrue, const TH1* hTrain, const TH1* hTrue, const TH1* hMeas, const TH1* hReco, Int_t _nm=0, Int_t _nt=0, Bool_t _overflow=kFALSE, ErrorTreatment withError=kDefault, Double_t chi_squ=-999.0); static void PrintTable (std::ostream& o, const TVectorD& vTrainTrue, const TVectorD& vTrain, const TVectorD& vMeas, const TVectorD& vReco, Int_t nm, Int_t nt); protected: void Assign (const RooUnfold& rhs); // implementation of assignment operator virtual void SetNameTitleDefault(); virtual void Unfold(); virtual void GetErrors(); virtual void GetCov(); // Get covariance matrix using errors on measured distribution virtual void GetErrMat(); // Get covariance matrix using errors from residuals on reconstructed distribution virtual void GetWgt(); // Get weight matrix using errors on measured distribution virtual void GetSettings(); virtual Bool_t UnfoldWithErrors (ErrorTreatment withError, bool getWeights=false); static TMatrixD CutZeros (const TMatrixD& ereco); static TH1D* HistNoOverflow (const TH1* h, Bool_t overflow); static TMatrixD& ABAT (const TMatrixD& a, const TMatrixD& b, TMatrixD& c); static TMatrixD& ABAT (const TMatrixD& a, const TVectorD& b, TMatrixD& c); static TH1* Resize (TH1* h, Int_t nx, Int_t ny=-1, Int_t nz=-1); static Int_t InvertMatrix (const TMatrixD& mat, TMatrixD& inv, const char* name="matrix", Int_t verbose=1); private: void Init(); void Destroy(); void CopyData (const RooUnfold& rhs); protected: // instance variables Double_t _minparm; // Minimum value to be used in RooUnfoldParms Double_t _maxparm; // Maximum value to be used in RooUnfoldParms Double_t _stepsizeparm; // StepSize value to be used in RooUnfoldParms Double_t _defaultparm; // Recommended value for regularisation parameter Int_t _verbose; // Debug print level Int_t _nm; // Total number of measured bins (including under/overflows if _overflow set) Int_t _nt; // Total number of truth bins (including under/overflows if _overflow set) Int_t _overflow; // Use histogram under/overflows if 1 (set from RooUnfoldResponse) Int_t _NToys; // Number of toys to be used Bool_t _unfolded; // unfolding done Bool_t _haveCov; // have _cov Bool_t _haveWgt; // have _wgt Bool_t _have_err_mat; // have _err_mat Bool_t _fail; // unfolding failed Bool_t _haveErrors; // have _variances Bool_t _haveCovMes; // _covMes was set, not just cached Int_t _dosys; // include systematic errors from response matrix? use _dosys=2 to exclude measurement errors const RooUnfoldResponse* _res; // Response matrix (not owned) RooUnfoldResponse* _resmine; // Owned response matrix const TH1* _meas; // Measured distribution (not owned) TH1* _measmine; // Owned measured histogram TVectorD _rec; // Reconstructed distribution TMatrixD _cov; // Reconstructed distribution covariance TMatrixD _wgt; // Reconstructed distribution weights (inverse of _cov) TVectorD _variances; // Error matrix diagonals TMatrixD _err_mat; // Error matrix from toys mutable TVectorD* _vMes; //! Cached measured vector mutable TVectorD* _eMes; //! Cached measured error mutable TMatrixD* _covMes; // Measurement covariance matrix mutable TMatrixD* _covL; //! Cached lower triangular matrix for which _covMes = _covL * _covL^T. ErrorTreatment _withError; // type of error last calulcated public: ClassDef (RooUnfold, 2) // Unfolding base class: implementations in RooUnfoldBayes, RooUnfoldSvd, RooUnfoldBinByBin, RooUnfoldTUnfold, and RooUnfoldInvert }; //============================================================================== // Inline method definitions //============================================================================== inline RooUnfold::RooUnfold() : TNamed() { // Default constructor. Use Setup() to prepare for unfolding. Init(); } inline RooUnfold::RooUnfold (const char* name, const char* title) : TNamed(name,title) { // Basic named constructor. Use Setup() to prepare for unfolding. Init(); } inline RooUnfold::RooUnfold (const TString& name, const TString& title) : TNamed(name,title) { // Basic named constructor. Use Setup() to prepare for unfolding. Init(); } inline RooUnfold::~RooUnfold() { Destroy(); } inline RooUnfold& RooUnfold::operator= (const RooUnfold& rhs) { // Assignment operator for copying RooUnfold settings. Assign(rhs); return *this; } inline Int_t RooUnfold::verbose() const { // Get verbosity setting which controls amount of information to be printed return _verbose; } inline Int_t RooUnfold::NToys() const { // Get number of toys used in kCovToy error calculation. return _NToys; } inline Int_t RooUnfold::Overflow() const { // Histogram under/overflow bins are used? return _overflow; } inline const RooUnfoldResponse* RooUnfold::response() const { // Response matrix object return _res; } inline const TH1* RooUnfold::Hmeasured() const { // Measured Distribution as a histogram return _meas; } inline TVectorD& RooUnfold::Vreco() { // Unfolded (reconstructed) distribution as a vector if (!_unfolded) { if (!_fail) Unfold(); if (!_unfolded) { _fail= true; if (_nt > 0 && _rec.GetNrows() == 0) _rec.ResizeTo(_nt); // need something } } return _rec; } inline const TVectorD& RooUnfold::Vmeasured() const { // Measured distribution as a vector. if (!_vMes) _vMes= RooUnfoldResponse::H2V (_meas, _res->GetNbinsMeasured(), _overflow); return *_vMes; } inline const TVectorD& RooUnfold::Emeasured() const { // Measured errors as a vector. if (!_eMes) _eMes= RooUnfoldResponse::H2VE (_meas, _res->GetNbinsMeasured(), _overflow); return *_eMes; } inline void RooUnfold::SetVerbose (Int_t level) { // Set verbosity level which controls amount of information to be printed _verbose= level; } inline void RooUnfold::SetNToys (Int_t toys) { // Set number of toys used in kCovToy error calculation. _NToys= toys; } inline void RooUnfold::SetRegParm (Double_t) { // Set Regularisation parameter } inline Double_t RooUnfold::GetRegParm() const { // Get regularisation parameter. return -1; } inline void RooUnfold::IncludeSystematics (Int_t dosys) { // Include systematic errors from response matrix? // Use dosys=2 to exclude measurement errors. if (dosys!=_dosys) _haveWgt= _haveErrors= _haveCov= _have_err_mat= kFALSE; _dosys= dosys; } inline Int_t RooUnfold::SystematicsIncluded() const { // return setting for whether to include systematic errors from response matrix return _dosys; } #endif
apache-2.0
elodina/zipkin-mesos-framework
src/main/scala/net/elodina/mesos/zipkin/Config.scala
4072
/** * 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 net.elodina.mesos.zipkin import java.io.{File, FileInputStream} import java.net.URI import java.util.Properties import net.elodina.mesos.zipkin.utils.{BindAddress, Period} object Config { val DEFAULT_FILE = new File("zipkin-mesos.properties") var debug: Boolean = false var genTraces: Boolean = false var storage: String = "file:zipkin-mesos.json" var master: Option[String] = None var principal: Option[String] = None var secret: Option[String] = None var user: Option[String] = None var frameworkName: String = "zipkin" var frameworkRole: String = "*" var frameworkTimeout: Period = new Period("30d") var log: Option[File] = None var api: Option[String] = None var bindAddress: Option[BindAddress] = None def apiPort: Int = { val port = new URI(getApi).getPort if (port == -1) 80 else port } def replaceApiPort(port: Int): Unit = { val prev: URI = new URI(getApi) api = Some("" + new URI( prev.getScheme, prev.getUserInfo, prev.getHost, port, prev.getPath, prev.getQuery, prev.getFragment )) } def getApi: String = { api.getOrElse(throw new Error("api not initialized")) } def getMaster: String = { master.getOrElse(throw new Error("master not initialized")) } def getZk: String = { master.getOrElse(throw new Error("zookeeper not initialized")) } private[zipkin] def loadFromFile(file: File): Unit = { val props: Properties = new Properties() val stream: FileInputStream = new FileInputStream(file) props.load(stream) stream.close() if (props.containsKey("debug")) debug = java.lang.Boolean.valueOf(props.getProperty("debug")) if (props.containsKey("genTraces")) genTraces = java.lang.Boolean.valueOf(props.getProperty("genTraces")) if (props.containsKey("storage")) storage = props.getProperty("storage") if (props.containsKey("master")) master = Some(props.getProperty("master")) if (props.containsKey("user")) user = Some(props.getProperty("user")) if (props.containsKey("principal")) principal = Some(props.getProperty("principal")) if (props.containsKey("secret")) secret = Some(props.getProperty("secret")) if (props.containsKey("framework-name")) frameworkName = props.getProperty("framework-name") if (props.containsKey("framework-role")) frameworkRole = props.getProperty("framework-role") if (props.containsKey("framework-timeout")) frameworkTimeout = new Period(props.getProperty("framework-timeout")) if (props.containsKey("log")) log = Some(new File(props.getProperty("log"))) if (props.containsKey("api")) api = Some(props.getProperty("api")) if (props.containsKey("bind-address")) bindAddress = Some(new BindAddress(props.getProperty("bind-address"))) } override def toString: String = { s""" |debug: $debug, storage: $storage |mesos: master=$master, user=${if (user.isEmpty || user.get.isEmpty) "<default>" else user} |principal=${principal.getOrElse("<none>")}, secret=${if (secret.isDefined) "*****" else "<none>"} |framework: name=$frameworkName, role=$frameworkRole, timeout=$frameworkTimeout |api: $api, bind-address: ${bindAddress.getOrElse("<all>")}, genTraces: $genTraces """.stripMargin.trim } }
apache-2.0
zynxhealth/zaws
lib/zaws/external/awscli/commands/elb/register_instances_with_load_balancer.rb
1154
module ZAWS class External class AWSCLI class Commands class ELB class RegisterInstancesWithLoadBalancer def initialize(shellout=nil, awscli=nil) @shellout=shellout @awscli=awscli clear_settings self end def aws @aws ||= ZAWS::External::AWSCLI::Commands::AWS.new(self) @aws end def clear_settings @lbn=nil @instances=nil self end def instances(id) @instances=id self end def load_balancer_name(name) @lbn=name self end def get_command command = "elb register-instances-with-load-balancer" command = "#{command} --load-balancer-name #{@lbn}" if @lbn command = "#{command} --instances #{@instances}" if @instances return command end end end end end end end
apache-2.0
chromeos/chromeos.dev
lib/filters/component-has-docs.js
1060
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * 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. */ /** * * @param {string} component - Component name * @param {object[]} collection - Array of objects describing available content * @return {object|false} Either a found item, or false. */ function componentHasDocs(component, collection) { const item = collection.filter((c) => `${c.fileSlug}.njk` === component); return item.length > 0 ? item[0] : false; } module.exports = (eleventy) => { eleventy.addFilter('componentHasDocs', componentHasDocs); };
apache-2.0
obourgain/elasticsearch-http
src/test/java/com/github/obourgain/elasticsearch/http/handler/document/termvectors/TermVectorResponseTest.java
1278
package com.github.obourgain.elasticsearch.http.handler.document.termvectors; import static com.github.obourgain.elasticsearch.http.TestFilesUtils.readFromClasspath; import static org.assertj.core.api.Assertions.assertThat; import org.elasticsearch.common.bytes.BytesArray; import org.junit.Test; import com.github.obourgain.elasticsearch.http.response.entity.TermVector; import com.github.obourgain.elasticsearch.http.response.entity.TermVectorTest; public class TermVectorResponseTest { @Test public void should_parse_response() throws Exception { String json = readFromClasspath("json/termvector/termvector_response.json"); TermVectorResponse response = new TermVectorResponse().parse(new BytesArray(json)); assertTermVectorResponse(response); } public static void assertTermVectorResponse(TermVectorResponse response) { assertThat(response.getId()).isEqualTo("1"); assertThat(response.getIndex()).isEqualTo("twitter"); assertThat(response.getType()).isEqualTo("tweet"); assertThat(response.getVersion()).isEqualTo(1); TermVector termVector = response.getTermVector(); TermVectorTest.assertTermVector(termVector); TermVectorTest.assertFieldStatistics(termVector); } }
apache-2.0
cackharot/ngen-milk-pos
deploy.sh
209
#!/bin/bash (python setup.py bdist_wheel;scp dist/mpos-1.0.0-py2-none-any.whl pi@pi:~/mpos.zip; ssh pi@pi 'unzip -uoq mpos.zip'; ssh pi@pi 'chmod +x ~/mpos/web/runprod.sh'; ssh pi@pi '~/mpos/web/runprod.sh';)
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Argostemma/Argostemma annamiticum/README.md
186
# Argostemma annamiticum Ridl. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
google/brailleback
braille/brailleback/src/com/googlecode/eyesfree/brailleback/DisplayManager.java
48343
/* * Copyright (C) 2012 Google 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.googlecode.eyesfree.brailleback; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.text.Spanned; import android.util.Log; import com.googlecode.eyesfree.braille.display.BrailleInputEvent; import com.googlecode.eyesfree.braille.display.Display; import com.googlecode.eyesfree.braille.display.DisplayClient; import com.googlecode.eyesfree.braille.translate.BrailleTranslator; import com.googlecode.eyesfree.braille.translate.TranslationResult; import com.googlecode.eyesfree.brailleback.wrapping.SimpleWrapStrategy; import com.googlecode.eyesfree.brailleback.wrapping.WordWrapStrategy; import com.googlecode.eyesfree.brailleback.wrapping.WrapStrategy; import com.googlecode.eyesfree.utils.AccessibilityNodeInfoUtils; import com.googlecode.eyesfree.utils.LogUtils; import com.googlecode.eyesfree.utils.SharedPreferencesUtils; import java.util.Arrays; import java.util.Comparator; /** * Keeps track of the current display content and handles panning. */ public class DisplayManager implements Display.OnConnectionStateChangeListener, Display.OnInputEventListener, TranslatorManager.OnTablesChangedListener, SharedPreferences.OnSharedPreferenceChangeListener { /** Dot pattern used to overlay characters under a selection. */ // TODO: Make customizable. private static final int SELECTION_DOTS = 0xC0; /** Dot pattern used to overlay characters in a focused element. */ // TODO: Make customizable. private static final int FOCUS_DOTS = 0xC0; private static final long BLINK_OFF_MILLIS = 800; private static final long BLINK_ON_MILLIS = 600; /** * Callback interface for notifying interested callers when the display is * panned out of the available content. A typical reaction to such an * event would be to move focus to a different area of the screen and * display it. */ public interface OnPanOverflowListener { void onPanLeftOverflow(Content content); void onPanRightOverflow(Content content); } /** * Listener for input events that also get information about the current * display content and position mapping for commands with a positional * argument. */ public interface OnMappedInputEventListener { /** * Handles an input {@code event} that was received when * {@code content} was present on the display. * * If the input event has a positional argument, it is mapped * according to the display pan position in the content so that * it corresponds to the character that the user touched. * * {@code event} and {@code content} are owned by the caller and may * not be referenced after this method returns. * * NOTE: Since the display is updated asynchronously, there is a chance * that the actual content on the display when the user invoked * the command is different from {@code content}. */ void onMappedInputEvent(BrailleInputEvent event, Content content); } /** * Builder-like class used to construct the content to put on the display. * * This object contains a {@link CharSequence} that represents what * characters to put on the display. This sequence can be a * {@link Spannable} so that the characters can be annotated with * information about cursors and focus which will affect how the content * is presented on the display. Arbitrary java objects may also be * included in the {@link Spannable} which can be used to determine what * action to take when the user invokes key commands related to a * particular position on the display (i.e. involving a cursor routing * key). In particular, {@link AccessibilityNodeInfoCompat}s may be * included, in which case they will be recycled by the * {@link Content#recycle} method. To facilitate movement outside the * bounds of the current {@link Content}, * {@link AccessibilityNodeInfoCompat}s that represent the extent of the * content can also be added, but in that case, they are not included in * the {@link Spannable}. */ public static class Content { /** * Pan strategy that moves the display to the leftmost position. * This is the default panning strategy. */ public static final int PAN_RESET = 0; /** * Pan strategy that positions the display so that it overlaps the * start of a selection or focus mark. Falls back on {@code PAN_RESET} * if there is no selection or focus. */ public static final int PAN_CURSOR = 1; /** * Pan strategy that tries to position the display close to the * position that corresponds to the panning position in the previously * displayed content. Spans of type * {@link AccessibilityNodeInfoCompat} are used to identify the * corresponding content in the old and new display content. * Falls back on {@code SPAN_CURSOR} if a corresponding position can't * be found. */ public static final int PAN_KEEP = 2; /** * Default contraction behaviour, allow contractions unless there is a * selection span in the content. */ public static final int CONTRACT_DEFAULT = 0; /** * Allow contraction, regardless of the presence of a selection * span. */ public static final int CONTRACT_ALWAYS_ALLOW = 1; private CharSequence text; private AccessibilityNodeInfoCompat firstNode; private AccessibilityNodeInfoCompat lastNode; private int panStrategy; private int contractionMode; private boolean splitParagraphs; private boolean editable = false; public Content() { } /** Shortcut to just set text for a one-off use. */ public Content(CharSequence textArg) { text = textArg; } public Content setText(CharSequence textArg) { text = textArg; return this; } public CharSequence getText() { return text; } public Spanned getSpanned() { if (text instanceof Spanned) { return (Spanned) text; } return null; } public Content setFirstNode(AccessibilityNodeInfoCompat node) { AccessibilityNodeInfoUtils.recycleNodes(firstNode); firstNode = AccessibilityNodeInfoCompat.obtain(node); return this; } public AccessibilityNodeInfoCompat getFirstNode() { return firstNode; } public Content setLastNode(AccessibilityNodeInfoCompat node) { AccessibilityNodeInfoUtils.recycleNodes(lastNode); lastNode = AccessibilityNodeInfoCompat.obtain(node); return this; } public AccessibilityNodeInfoCompat getLastNode() { return lastNode; } public Content setPanStrategy(int strategy) { panStrategy = strategy; return this; } public int getPanStrategy() { return panStrategy; } public Content setContractionMode(int mode) { contractionMode = mode; return this; } public int getContractionMode() { return contractionMode; } public Content setSplitParagraphs(boolean value) { splitParagraphs = value; return this; } public boolean isSplitParagraphs() { return splitParagraphs; } public Content setEditable(boolean value) { editable = value; return this; } public boolean isEditable() { return editable; } /** * Translates the text content, preserving any verbatim braille that is embedded in a * BrailleSpan. The current implementation of this method only handles the first BrailleSpan; * all subsequent BrailleSpans are ignored. * * @param translator The translator used for translating the subparts of the text without * embedded BrailleSpans. * @param cursorPosition The position of the cursor; if it occurs in a section of the text * without BrailleSpans, then the final cursor position in the output braille by the * translator. Otherwise, if the cursor occurs within a BrailleSpan section, the final * cursor position in the output braille is set to the first braille cell of the * BrailleSpan. * @param computerBrailleAtCursor This parameter is passed through to the translator; if * true,then contracted translators are instructed to translate the word under the cursor * using computer braille (instead of contracted braille) to make editing easier. * @return The result of translation, possibly empty, not null. */ public TranslationResult translateWithVerbatimBraille( BrailleTranslator translator, int cursorPosition, boolean computerBrailleAtCursor) { if (translator == null) { return createEmptyTranslation(text); } // Assume that we have at most one BrailleSpan since we currently // never add more than one BrailleSpan. // Also ignore BrailleSpans with zero-length span or no braille for // now because we don't currently add such BrailleSpans. DisplaySpans.BrailleSpan brailleSpan = null; int start = -1; int end = -1; if (text instanceof Spanned) { Spanned spanned = (Spanned) text; DisplaySpans.BrailleSpan[] spans = spanned.getSpans( 0, spanned.length(), DisplaySpans.BrailleSpan.class); if (spans.length > 1) { LogUtils.log(this, Log.WARN, "More than one BrailleSpan, handling first only"); } if (spans.length != 0) { int spanStart = spanned.getSpanStart(spans[0]); int spanEnd = spanned.getSpanEnd(spans[0]); if (spans[0].braille != null && spans[0].braille.length != 0 && spanStart < spanEnd) { brailleSpan = spans[0]; start = spanStart; end = spanEnd; } } } if (brailleSpan != null) { // Chunk the text into three sections: // left: [0, start) - needs translation // mid: [start, end) - use the literal braille provided // right: [end, length) - needs translation CharSequence left = text.subSequence(0, start); TranslationResult leftTrans = translator.translate( left.toString(), cursorPosition < start ? cursorPosition : -1, cursorPosition < start && computerBrailleAtCursor); CharSequence right = text.subSequence(end, text.length()); TranslationResult rightTrans = translator.translate( right.toString(), cursorPosition >= end ? cursorPosition - end : -1, cursorPosition >= end && computerBrailleAtCursor); // If one of the left or right translations is not valid, then // we will fall back by ignoring the BrailleSpan and // translating everything normally. (Chances are that // translating the whole text will fail also, but it wouldn't // hurt to try.) if (leftTrans == null || rightTrans == null) { LogUtils.log(this, Log.ERROR, "Could not translate left or right subtranslation, " + "falling back on default translation"); return translateOrDefault(translator, cursorPosition, computerBrailleAtCursor); } int startBraille = leftTrans.getCells().length; int endBraille = startBraille + brailleSpan.braille.length; int totalBraille = endBraille + rightTrans.getCells().length; // Copy braille cells. byte[] cells = new byte[totalBraille]; System.arraycopy(leftTrans.getCells(), 0, cells, 0, leftTrans.getCells().length); System.arraycopy(brailleSpan.braille, 0, cells, startBraille, brailleSpan.braille.length); System.arraycopy(rightTrans.getCells(), 0, cells, endBraille, rightTrans.getCells().length); // Copy text-to-braille indices. int[] leftTtb = leftTrans.getTextToBraillePositions(); int[] rightTtb = rightTrans.getTextToBraillePositions(); int[] textToBraille = new int[text.length()]; System.arraycopy(leftTtb, 0, textToBraille, 0, start); for (int i = start; i < end; ++i) { textToBraille[i] = startBraille; } for (int i = end; i < textToBraille.length; ++i) { textToBraille[i] = endBraille + rightTtb[i - end]; } // Copy braille-to-text indices. int[] leftBtt = leftTrans.getBrailleToTextPositions(); int[] rightBtt = rightTrans.getBrailleToTextPositions(); int[] brailleToText = new int[cells.length]; System.arraycopy(leftBtt, 0, brailleToText, 0, startBraille); for (int i = startBraille; i < endBraille; ++i) { brailleToText[i] = start; } for (int i = endBraille; i < totalBraille; ++i) { brailleToText[i] = end + rightBtt[i - endBraille]; } // Get cursor. int cursor; if (cursorPosition < 0) { cursor = -1; } else if (cursorPosition < start) { cursor = leftTrans.getCursorPosition(); } else if (cursorPosition < end) { cursor = startBraille; } else { cursor = endBraille + rightTrans.getCursorPosition(); } return new TranslationResult(cells, textToBraille, brailleToText, cursor); } return translateOrDefault(translator, cursorPosition, computerBrailleAtCursor); } private TranslationResult translateOrDefault( @NonNull BrailleTranslator translator, int cursorPosition, boolean computerBrailleAtCursor) { TranslationResult translation = translator.translate(text.toString(), cursorPosition, computerBrailleAtCursor); if (translation != null) { return translation; } return createEmptyTranslation(text); } public void recycle() { AccessibilityNodeInfoUtils.recycleNodes(firstNode, lastNode); firstNode = lastNode = null; DisplaySpans.recycleSpans(text); text = null; } @Override public String toString() { return String.format("DisplayManager.Content {text=%s}", getText()); } } private final TranslatorManager translatorManager; private final BrailleBackService context; // Not final, because it is initialized in the handler thread. private Display display; private final OnPanOverflowListener panOverflowListener; private final Display.OnConnectionStateChangeListener connectionStateChangeListener; private final OnMappedInputEventListener mappedInputEventListener; private final DisplayHandler displayHandler; private final CallbackHandler callbackHandler; private final HandlerThread handlerThread; private final PowerManager.WakeLock wakeLock; private final SharedPreferences sharedPreferences; // Read and written in display handler thread only. private boolean connected = false; private volatile boolean isSimulatedDisplay = false; /** * Cursor position last passed to the translate method of the translator. We use this because it * is more reliable than the position maps inside contracted words. In the common case where there * is just one selection/focus on the display at the same time, this gives better results. * Otherwise, we fall back on the position map, whic is also used for keeping the pan position. */ private int cursorPositionToTranslate = 0; private TranslationResult currentTranslationResult = createEmptyTranslation(null); /** Display content without overlays for cursors, focus etc. */ private byte[] brailleContent = new byte[0]; /** Braille content, potentially with dots overlaid for cursors and focus. */ private byte[] overlaidBrailleContent = brailleContent; private boolean overlaysOn; private WrapStrategy wrapStrategy; private final WrapStrategy editingWrapStrategy = new SimpleWrapStrategy(); private WrapStrategy preferredWrapStrategy = new SimpleWrapStrategy(); private Content currentContent = new Content(""); // Displayed content, already trimmed based on the display position. // Updated in updateDisplayedContent() and used in refresh(). private byte[] displayedBraille = new byte[0]; private byte[] displayedOverlaidBraille = new byte[0]; private CharSequence displayedText = ""; private int[] displayedBrailleToTextPositions = new int[0]; private boolean blinkNeeded = false; /** * Creates an instance of this class and starts the internal thread to connect to the braille * display service. {@code contextArg} is used to connect to the display service. {@code * translator} is used for braille translation. The various listeners will be called as * appropriate and on the same thread that was used to create this object. The current thread must * have a prepared looper. */ @SuppressLint("InvalidWakeLockTag") public DisplayManager( TranslatorManager translatorManagerArg, BrailleBackService contextArg, OnPanOverflowListener panOverflowListenerArg, Display.OnConnectionStateChangeListener connectionStateChangeListenerArg, OnMappedInputEventListener mappedInputEventListenerArg) { translatorManager = translatorManagerArg; translatorManager.addOnTablesChangedListener(this); context = contextArg; panOverflowListener = panOverflowListenerArg; connectionStateChangeListener = connectionStateChangeListenerArg; mappedInputEventListener = mappedInputEventListenerArg; PowerManager pm = (PowerManager) contextArg.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "BrailleBack"); handlerThread = new HandlerThread("DisplayManager") { @Override public void onLooperPrepared() { display = new OverlayDisplay(context, new DisplayClient(context)); display.setOnConnectionStateChangeListener(DisplayManager.this); display.setOnInputEventListener(DisplayManager.this); } }; handlerThread.start(); displayHandler = new DisplayHandler(handlerThread.getLooper()); callbackHandler = new CallbackHandler(); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(contextArg); sharedPreferences.registerOnSharedPreferenceChangeListener(this); updateWrapStrategyFromPreferences(); } public void shutdown() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); displayHandler.stop(); // Block on display shutdown. We need to make sure this finishes before // we can consider DisplayManager to be shut down. try { handlerThread.join(1000 /*milis*/); } catch (InterruptedException e) { LogUtils.log(this, Log.WARN, "Display handler shutdown interrupted"); } translatorManager.removeOnTablesChangedListener(this); } /** * Asynchronously updates the display to reflect {@code content}. * {@code content} must not be modified after this function is called, and * will eventually be recycled by the display manager. */ public void setContent(Content content) { if (content == null) { throw new NullPointerException("content can't be null"); } if (content.text == null) { throw new NullPointerException("content text is null"); } displayHandler.setContent(content); } /** Returns true if the current display is simulated. */ public boolean isSimulatedDisplay() { return isSimulatedDisplay; } /** * Marks selection spans in the overlaid braille, and returns the position * in braille where the first selection begins. If there are no selection * spans, returns -1. */ private int markSelection(Spanned spanned) { DisplaySpans.SelectionSpan[] spans = spanned.getSpans(0, spanned.length(), DisplaySpans.SelectionSpan.class); int selectionStart = -1; for (DisplaySpans.SelectionSpan span : spans) { int start = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, spanned.getSpanStart(span)); int end = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, spanned.getSpanEnd(span)); if (start == -1 || end == -1) { return -1; } if (start == end) { end = start + 1; } if (end > brailleContent.length) { extendContentForCursor(); } copyOverlaidContent(); for (int i = start; i < end && i < overlaidBrailleContent.length; ++i) { overlaidBrailleContent[i] |= (byte) SELECTION_DOTS; } if (selectionStart == -1) { selectionStart = start; } } return selectionStart; } /** * Makes sure that the overlaid content has its own copy. Call before * adding overlay dots. */ private void copyOverlaidContent() { if (overlaidBrailleContent == brailleContent) { overlaidBrailleContent = brailleContent.clone(); } } private void extendContentForCursor() { brailleContent = Arrays.copyOf(brailleContent, brailleContent.length + 1); // Always create a new copy of the overlaid content because there will // be a cursor, so we will need a copy anyway. overlaidBrailleContent = Arrays.copyOf(overlaidBrailleContent, overlaidBrailleContent.length + 1); } /** * Marks focus spans in the overlaid braille, and returns the position in * braille where the first focus begins. If there are no focus spans, * returns -1. */ private int markFocus(Spanned spanned) { DisplaySpans.FocusSpan[] spans = spanned.getSpans(0, spanned.length(), DisplaySpans.FocusSpan.class); int focusStart = -1; for (DisplaySpans.FocusSpan span : spans) { int start = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, spanned.getSpanStart(span)); if (start >= 0 && start < overlaidBrailleContent.length) { copyOverlaidContent(); overlaidBrailleContent[start] |= (byte) FOCUS_DOTS; if (focusStart == -1) { focusStart = start; } } } return focusStart; } @Override public void onConnectionStateChanged(int state) { if (state == Display.STATE_CONNECTED) { connected = true; displayHandler.retranslate(); } else { connected = false; } isSimulatedDisplay = display.isSimulated(); callbackHandler.onConnectionStateChanged(state); } @Override public void onInputEvent(BrailleInputEvent event) { keepAwake(); LogUtils.log(this, Log.VERBOSE, "InputEvent: %s", event); // We're called from within the handler thread, so we forward // the call only if we are going to invoke the user's callback. switch (event.getCommand()) { case BrailleInputEvent.CMD_NAV_PAN_LEFT: panLeft(); break; case BrailleInputEvent.CMD_NAV_PAN_RIGHT: panRight(); break; default: sendMappedEvent(event); break; } } @Override public void onTablesChanged() { displayHandler.retranslate(); } private void sendMappedEvent(BrailleInputEvent event) { if (BrailleInputEvent.argumentType(event.getCommand()) == BrailleInputEvent.ARGUMENT_POSITION) { int oldArgument = event.getArgument(); // Offset argument by pan position and make sure it is less than // the next split position. int offsetArgument = oldArgument + wrapStrategy.getDisplayStart(); if (offsetArgument >= wrapStrategy.getDisplayEnd()) { // The event is outisde the currently displayed // content, drop the event. return; } // The mapped event argument is the translated offset argument. int newArgument = displayToTextPosition( currentTranslationResult, cursorPositionToTranslate, offsetArgument); // Create a new event if the argument actually differs. if (newArgument != oldArgument) { event = new BrailleInputEvent(event.getCommand(), newArgument, event.getEventTime()); } } callbackHandler.onMappedInputEvent(event); } private void panLeft() { if (wrapStrategy.panLeft()) { updateDisplayedContent(); } else { callbackHandler.onPanLeftOverflow(); } } private void panRight() { if (wrapStrategy.panRight()) { updateDisplayedContent(); } else { callbackHandler.onPanRightOverflow(); } } private class DisplayHandler extends Handler { private static final int MSG_SET_CONTENT = 1; private static final int MSG_RETRANSLATE = 2; private static final int MSG_PULSE = 3; private static final int MSG_STOP = 4; public DisplayHandler(Looper looper) { super(looper); } public void setContent(Content content) { obtainMessage(MSG_SET_CONTENT, content).sendToTarget(); } public void retranslate() { sendEmptyMessage(MSG_RETRANSLATE); } public void schedulePulse() { if (hasMessages(MSG_PULSE)) { return; } sendEmptyMessageDelayed(MSG_PULSE, overlaysOn ? BLINK_ON_MILLIS : BLINK_OFF_MILLIS); } public void cancelPulse() { removeMessages(MSG_PULSE); overlaysOn = true; } public void stop() { sendEmptyMessage(MSG_STOP); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SET_CONTENT: handleSetContent((Content) msg.obj); break; case MSG_RETRANSLATE: handleRetranslate(); break; case MSG_PULSE: handlePulse(); break; case MSG_STOP: handleStop(); break; default: // Fall out. } } private void handleSetContent(Content content) { Content oldContent = currentContent; currentContent = content; updateWrapStrategy(); cursorPositionToTranslate = findCursorPosition(content); TranslationResult oldTranslationResult = currentTranslationResult; int oldDisplayStart = wrapStrategy.getDisplayStart(); translateCurrentContent(); cancelPulse(); // Adjust the pan position according to the panning strategy. // Setting the position to -1 below means that the cursor position // returned by markCursor() will be used instead; if the pan // position is >= 0, then the cursor position will be ignored. // If the pan position is -1 and the cursor position is also -1 // (no cursor), then the wrap strategy will reset the display to the // beginning of the line. int panPosition = -1; switch (content.panStrategy) { case Content.PAN_RESET: panPosition = 0; break; case Content.PAN_KEEP: if (oldContent != null) { // We don't align the display position to the size of // the display in this case so that content doesn't // jump around on the dipslay if content before the // current display position changes size. panPosition = findMatchingPanPosition( oldContent, content, oldTranslationResult, currentTranslationResult, oldDisplayStart); } break; case Content.PAN_CURSOR: break; default: LogUtils.log(this, Log.ERROR, "Unknown pan strategy: %d", content.panStrategy); } int cursorPosition = markCursor(); if (panPosition >= 0) { wrapStrategy.panTo(panPosition, false); } else { wrapStrategy.panTo(cursorPosition, true); } updateDisplayedContent(); if (oldContent != null) { // Have the callback handler recycle the old content so that // the thread in which the callbck handler is running is the // only thread modifying it. It is safe for the callback // thread to recycle the event when it receives this message // because the display handler thread will not send any more // input event containing this content and the events that // have already been sent will be processed by trhe callback // thread before the recycle message arrives because of the // guaranteed ordering of message handling. callbackHandler.recycleContent(oldContent); } } private void handleRetranslate() { if (currentContent == null) { return; } int oldTextPosition = displayToTextPosition( currentTranslationResult, cursorPositionToTranslate, wrapStrategy.getDisplayStart()); translateCurrentContent(); int panPosition = textToDisplayPosition( currentTranslationResult, cursorPositionToTranslate, oldTextPosition); int cursorPosition = markCursor(); if (panPosition >= 0) { wrapStrategy.panTo(panPosition, false); } else { wrapStrategy.panTo(cursorPosition, true); } cancelPulse(); updateDisplayedContent(); } private void handlePulse() { overlaysOn = !overlaysOn; refresh(); } private void handleStop() { display.shutdown(); handlerThread.quit(); } } private static class OnMappedInputEventArgs { public BrailleInputEvent event; public Content content; public OnMappedInputEventArgs(BrailleInputEvent eventArg, Content contentArg) { event = eventArg; content = contentArg; } } private class CallbackHandler extends Handler { private static final int MSG_ON_CONNECTION_STATE_CHANGED = 1; private static final int MSG_ON_MAPPED_INPUT_EVENT = 2; private static final int MSG_ON_PAN_LEFT_OVERFLOW = 3; private static final int MSG_ON_PAN_RIGHT_OVERFLOW = 4; private static final int MSG_RECYCLE_CONTENT = 5; public void onConnectionStateChanged(int state) { obtainMessage(MSG_ON_CONNECTION_STATE_CHANGED, state, 0) .sendToTarget(); } public void onMappedInputEvent(BrailleInputEvent event) { OnMappedInputEventArgs args = new OnMappedInputEventArgs(event, currentContent); obtainMessage(MSG_ON_MAPPED_INPUT_EVENT, args).sendToTarget(); } public void onPanLeftOverflow() { obtainMessage(MSG_ON_PAN_LEFT_OVERFLOW, currentContent).sendToTarget(); } public void onPanRightOverflow() { obtainMessage(MSG_ON_PAN_RIGHT_OVERFLOW, currentContent).sendToTarget(); } public void recycleContent(Content content) { obtainMessage(MSG_RECYCLE_CONTENT, content).sendToTarget(); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_ON_CONNECTION_STATE_CHANGED: handleOnConnectionStateChanged(msg.arg1); break; case MSG_ON_MAPPED_INPUT_EVENT: OnMappedInputEventArgs args = (OnMappedInputEventArgs) msg.obj; handleOnMappedInputEvent(args.event, args.content); break; case MSG_ON_PAN_LEFT_OVERFLOW: handleOnPanLeftOverflow((Content) msg.obj); break; case MSG_ON_PAN_RIGHT_OVERFLOW: handleOnPanRightOverflow((Content) msg.obj); break; case MSG_RECYCLE_CONTENT: handleRecycleContent((Content) msg.obj); break; default: // Fall out. } } private void handleOnConnectionStateChanged(int state) { connectionStateChangeListener.onConnectionStateChanged(state); } private void handleOnMappedInputEvent(BrailleInputEvent event, Content content) { mappedInputEventListener.onMappedInputEvent(event, content); } private void handleOnPanLeftOverflow(Content content) { panOverflowListener.onPanLeftOverflow(content); } private void handleOnPanRightOverflow(Content content) { panOverflowListener.onPanRightOverflow(content); } private void handleRecycleContent(Content content) { content.recycle(); } } private void translateCurrentContent() { // Use the current translator, whether contracted or uncontracted, for // editing text, but instruct contracted translaters to uncontract // the braille for the word under the cursor. BrailleTranslator translator = translatorManager.getTranslator(); currentTranslationResult = currentContent.translateWithVerbatimBraille( translator, cursorPositionToTranslate, uncontractBrailleAtCursor(currentContent)); // Make very sure we do not call getCells() on a null translation. // translateWithVerbatimBraille() currently should never return null. if (currentTranslationResult == null) { LogUtils.log(this, Log.ERROR, "currentTranslationResult is null"); currentTranslationResult = createEmptyTranslation(currentContent.getText()); } wrapStrategy.setContent(currentContent, currentTranslationResult, getNumTextCells()); brailleContent = currentTranslationResult.getCells(); overlaidBrailleContent = brailleContent; } private static TranslationResult createEmptyTranslation(CharSequence text) { int textLength = (text == null) ? 0 : text.length(); return new TranslationResult(new byte[0], new int[textLength], new int[0], 0); } /** * Marks the selection or focus cursor (in that priority), and returns the * position in braille of the selection or focus cursor if one exists. If no * selection or focus cursor exists, then returns -1. */ private int markCursor() { Spanned spanned = currentContent.getSpanned(); if (spanned != null) { int selectionPosition = markSelection(spanned); if (selectionPosition != -1) { return selectionPosition; } int focusPosition = markFocus(spanned); if (focusPosition != -1) { return focusPosition; } } return -1; } private void updateDisplayedContent() { if (!connected || currentContent == null) { return; } int displayStart = wrapStrategy.getDisplayStart(); int displayEnd = wrapStrategy.getDisplayEnd(); if (displayEnd < displayStart) { return; } // Compute equivalent text and mapping. int[] brailleToTextPositions = currentTranslationResult.getBrailleToTextPositions(); int textLeft = displayStart >= brailleToTextPositions.length ? 0 : brailleToTextPositions[displayStart]; int textRight = displayEnd >= brailleToTextPositions.length ? currentContent.text.length() : brailleToTextPositions[displayEnd]; // TODO: Prevent out of order brailleToTextPositions. if (textRight < textLeft) { textRight = textLeft; } StringBuilder newText = new StringBuilder(currentContent.text.subSequence(textLeft, textRight)); int[] trimmedBrailleToTextPositions = new int[displayEnd - displayStart]; for (int i = 0; i < trimmedBrailleToTextPositions.length; i++) { if (displayStart + i < brailleToTextPositions.length) { trimmedBrailleToTextPositions[i] = brailleToTextPositions[displayStart + i] - textLeft; } else { trimmedBrailleToTextPositions[i] = newText.length(); newText.append(' '); } } // Store all data needed by refresh(). displayedBraille = Arrays.copyOfRange(brailleContent, displayStart, displayEnd); if (brailleContent != overlaidBrailleContent) { displayedOverlaidBraille = Arrays.copyOfRange(overlaidBrailleContent, displayStart, displayEnd); } else { displayedOverlaidBraille = displayedBraille; } displayedText = newText.toString(); displayedBrailleToTextPositions = trimmedBrailleToTextPositions; blinkNeeded = blinkNeeded(); refresh(); } private void refresh() { if (!connected) { return; } byte[] toDisplay = overlaysOn ? displayedOverlaidBraille : displayedBraille; display.displayDots(toDisplay, displayedText, displayedBrailleToTextPositions); if (blinkNeeded) { displayHandler.schedulePulse(); } else { displayHandler.cancelPulse(); } } /** * Returns {@code true} if the current display content is such that it * requires blinking. */ private boolean blinkNeeded() { if (brailleContent == overlaidBrailleContent) { return false; } int start = wrapStrategy.getDisplayStart(); int end = wrapStrategy.getDisplayEnd(); for (int i = start; i < end; ++i) { if (brailleContent[i] != overlaidBrailleContent[i]) { return true; } } return false; } /** * Keeps the phone awake as if there was a 'user activity' registered * by the system. */ private void keepAwake() { // Acquiring the lock and immediately releasing it keesp the phone // awake. We don't use aqcuire() with a timeout because it just // adds an unnecessary context switch. wakeLock.acquire(); wakeLock.release(); } /** * Returns the size of the connected display, or {@code 1} if * no display is connected. */ private int getNumTextCells() { if (!connected) { return 1; } return display.getDisplayProperties().getNumTextCells(); } private int findMatchingPanPosition( Content oldContent, Content newContent, TranslationResult oldTranslationResult, TranslationResult newTranslationResult, int oldDisplayPosition) { Spanned oldSpanned = oldContent.getSpanned(); Spanned newSpanned = newContent.getSpanned(); if (oldSpanned == null || newSpanned == null) { return -1; } // Map the current display start and past-the-end positions // to the corresponding input positions. int oldTextStart = displayToTextPosition(oldTranslationResult, -1 /*cursorPosition*/, oldDisplayPosition); int oldTextEnd = displayToTextPosition(oldTranslationResult, -1 /*cursorPosition*/, oldDisplayPosition + getNumTextCells()); // Find the nodes that overlap with the display. AccessibilityNodeInfoCompat[] displayedNodes = oldSpanned.getSpans(oldTextStart, oldTextEnd, AccessibilityNodeInfoCompat.class); Arrays.sort(displayedNodes, new ByDistanceComparator(oldSpanned, oldTextStart)); // Find corresponding node in new content. for (AccessibilityNodeInfoCompat oldNode : displayedNodes) { AccessibilityNodeInfoCompat newNode = (AccessibilityNodeInfoCompat) DisplaySpans.getEqualSpan(newSpanned, oldNode); if (newNode == null) { continue; } int oldDisplayStart = textToDisplayPosition(oldTranslationResult, -1 /*cursorPosition*/, oldSpanned.getSpanStart(oldNode)); int newDisplayStart = textToDisplayPosition(newTranslationResult, -1 /*cursorPosition*/, newSpanned.getSpanStart(newNode)); // TODO: If crashes happen here, return -1 when *DisplayStart == -1. // Offset position according to diff in node position. int newDisplayPosition = oldDisplayPosition + (newDisplayStart - oldDisplayStart); return newDisplayPosition; } return -1; } private static class ByDistanceComparator implements Comparator<AccessibilityNodeInfoCompat> { private final Spanned spanned; private final int start; public ByDistanceComparator(Spanned spannedArg, int startArg) { spanned = spannedArg; start = startArg; } @Override public int compare( AccessibilityNodeInfoCompat a, AccessibilityNodeInfoCompat b) { int aStart = spanned.getSpanStart(a); int bStart = spanned.getSpanStart(b); int aDist = Math.abs(start - aStart); int bDist = Math.abs(start - bStart); if (aDist != bDist) { return aDist - bDist; } // They are on the same distance, compare by length. int aLength = aStart + spanned.getSpanEnd(a); int bLength = bStart + spanned.getSpanEnd(b); return aLength - bLength; } } /** Returns braille character index of a text character index. May return -1. */ private static int textToDisplayPosition( TranslationResult translationResult, int cursorPosition, int textPosition) { if (textPosition == cursorPosition) { return translationResult.getCursorPosition(); // May return -1? } int[] posMap = translationResult.getTextToBraillePositions(); // May include -1? // Any position past-the-end of the position map maps to the // corresponding past-the-end position in the braille. if (textPosition >= posMap.length) { return translationResult.getBrailleToTextPositions().length; } return posMap[textPosition]; } private static int displayToTextPosition( TranslationResult translationResult, int cursorPosition, int displayPosition) { if (displayPosition == translationResult.getCursorPosition()) { return cursorPosition; } int[] posMap = translationResult.getBrailleToTextPositions(); // Any position past-the-end of the position map maps to the // corresponding past-the-end position in the braille. if (displayPosition >= posMap.length) { return translationResult.getTextToBraillePositions().length; } return posMap[displayPosition]; } private static int findCursorPosition(Content content) { Spanned spanned = content.getSpanned(); if (spanned == null) { return -1; } DisplaySpans.SelectionSpan[] selectionSpans = spanned.getSpans(0, spanned.length(), DisplaySpans.SelectionSpan.class); if (selectionSpans.length > 0) { return spanned.getSpanStart(selectionSpans[0]); } DisplaySpans.FocusSpan[] focusSpans = spanned.getSpans(0, spanned.length(), DisplaySpans.FocusSpan.class); if (focusSpans.length > 0) { return spanned.getSpanStart(focusSpans[0]); } return -1; } private boolean uncontractBrailleAtCursor(Content content) { if (content.getContractionMode() == Content.CONTRACT_ALWAYS_ALLOW) { return false; } Spanned spanned = content.getSpanned(); if (spanned == null) { return false; } DisplaySpans.SelectionSpan[] selectionSpans = spanned.getSpans(0, spanned.length(), DisplaySpans.SelectionSpan.class); return selectionSpans.length != 0; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferencesArg, String s) { String wordWrapPrefKey = context.getString(R.string.pref_braille_word_wrap_key); if (s != null && s.equals(wordWrapPrefKey)) { updateWrapStrategyFromPreferences(); } } private void updateWrapStrategyFromPreferences() { boolean wrap = SharedPreferencesUtils.getBooleanPref( sharedPreferences, context.getResources(), R.string.pref_braille_word_wrap_key, R.bool.pref_braille_word_wrap_default); preferredWrapStrategy = wrap ? new WordWrapStrategy() : new SimpleWrapStrategy(); updateWrapStrategy(); displayHandler.retranslate(); } private void updateWrapStrategy() { boolean contentEditable = currentContent != null && currentContent.isEditable(); boolean imeOpen = context != null && context.imeNavigationMode != null && context.imeNavigationMode.isImeOpen(); boolean editing = contentEditable && imeOpen; wrapStrategy = editing ? editingWrapStrategy : preferredWrapStrategy; } }
apache-2.0
heriram/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-tests/hyracks-storage-am-lsm-invertedindex-test/src/test/java/org/apache/hyracks/storage/am/lsm/invertedindex/util/LSMInvertedIndexTestUtils.java
31192
/* * 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.hyracks.storage.am.lsm.invertedindex.util; import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.exceptions.ErrorCode; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.data.std.primitive.IntegerPointable; import org.apache.hyracks.data.std.util.GrowableArray; import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleBuilder; import org.apache.hyracks.dataflow.common.comm.io.ArrayTupleReference; import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference; import org.apache.hyracks.dataflow.common.data.marshalling.IntegerSerializerDeserializer; import org.apache.hyracks.dataflow.common.data.marshalling.ShortSerializerDeserializer; import org.apache.hyracks.dataflow.common.data.marshalling.UTF8StringSerializerDeserializer; import org.apache.hyracks.storage.am.btree.OrderedIndexTestUtils; import org.apache.hyracks.storage.am.btree.impls.RangePredicate; import org.apache.hyracks.storage.am.common.CheckTuple; import org.apache.hyracks.storage.am.common.datagen.DocumentStringFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.IFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.PersonNameFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.SortedIntegerFieldValueGenerator; import org.apache.hyracks.storage.am.common.datagen.TupleGenerator; import org.apache.hyracks.storage.am.common.impls.NoOpOperationCallback; import org.apache.hyracks.storage.am.common.tuples.PermutingTupleReference; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndex; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexAccessor; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedIndexSearchModifier; import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListCursor; import org.apache.hyracks.storage.am.lsm.invertedindex.common.LSMInvertedIndexTestHarness; import org.apache.hyracks.storage.am.lsm.invertedindex.search.InvertedIndexSearchPredicate; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.DelimitedUTF8StringBinaryTokenizerFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.HashedUTF8NGramTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.HashedUTF8WordTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizer; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IToken; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.ITokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.NGramUTF8StringBinaryTokenizerFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.UTF8NGramTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.UTF8WordTokenFactory; import org.apache.hyracks.storage.am.lsm.invertedindex.util.LSMInvertedIndexTestContext.InvertedIndexType; import org.apache.hyracks.storage.common.IIndexBulkLoader; import org.apache.hyracks.storage.common.IIndexCursor; import org.apache.hyracks.storage.common.MultiComparator; @SuppressWarnings("rawtypes") public class LSMInvertedIndexTestUtils { public static final int TEST_GRAM_LENGTH = 3; public static TupleGenerator createStringDocumentTupleGen(Random rnd) throws IOException { IFieldValueGenerator[] fieldGens = new IFieldValueGenerator[2]; fieldGens[0] = new DocumentStringFieldValueGenerator(2, 10, 10000, rnd); fieldGens[1] = new SortedIntegerFieldValueGenerator(0); ISerializerDeserializer[] fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), IntegerSerializerDeserializer.INSTANCE }; TupleGenerator tupleGen = new TupleGenerator(fieldGens, fieldSerdes, 0); return tupleGen; } public static TupleGenerator createPersonNamesTupleGen(Random rnd) throws IOException { IFieldValueGenerator[] fieldGens = new IFieldValueGenerator[2]; fieldGens[0] = new PersonNameFieldValueGenerator(rnd, 0.5f); fieldGens[1] = new SortedIntegerFieldValueGenerator(0); ISerializerDeserializer[] fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), IntegerSerializerDeserializer.INSTANCE }; TupleGenerator tupleGen = new TupleGenerator(fieldGens, fieldSerdes, 0); return tupleGen; } private static ISerializerDeserializer[] getNonHashedIndexFieldSerdes(InvertedIndexType invIndexType) throws HyracksDataException { ISerializerDeserializer[] fieldSerdes = null; switch (invIndexType) { case INMEMORY: case ONDISK: case LSM: { fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), IntegerSerializerDeserializer.INSTANCE }; break; } case PARTITIONED_INMEMORY: case PARTITIONED_ONDISK: case PARTITIONED_LSM: { // Such indexes also include the set-size for partitioning. fieldSerdes = new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(), ShortSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; break; } default: { throw new HyracksDataException("Unhandled inverted index type '" + invIndexType + "'."); } } return fieldSerdes; } private static ISerializerDeserializer[] getHashedIndexFieldSerdes(InvertedIndexType invIndexType) throws HyracksDataException { ISerializerDeserializer[] fieldSerdes = null; switch (invIndexType) { case INMEMORY: case ONDISK: case LSM: { fieldSerdes = new ISerializerDeserializer[] { IntegerSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; break; } case PARTITIONED_INMEMORY: case PARTITIONED_ONDISK: case PARTITIONED_LSM: { // Such indexes also include the set-size for partitioning. fieldSerdes = new ISerializerDeserializer[] { IntegerSerializerDeserializer.INSTANCE, ShortSerializerDeserializer.INSTANCE, IntegerSerializerDeserializer.INSTANCE }; break; } default: { throw new HyracksDataException("Unhandled inverted index type '" + invIndexType + "'."); } } return fieldSerdes; } public static LSMInvertedIndexTestContext createWordInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getNonHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new UTF8WordTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new DelimitedUTF8StringBinaryTokenizerFactory(true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static LSMInvertedIndexTestContext createHashedWordInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new HashedUTF8WordTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new DelimitedUTF8StringBinaryTokenizerFactory(true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static LSMInvertedIndexTestContext createNGramInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getNonHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new UTF8NGramTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new NGramUTF8StringBinaryTokenizerFactory(TEST_GRAM_LENGTH, true, true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static LSMInvertedIndexTestContext createHashedNGramInvIndexTestContext(LSMInvertedIndexTestHarness harness, InvertedIndexType invIndexType) throws IOException, HyracksDataException { ISerializerDeserializer[] fieldSerdes = getHashedIndexFieldSerdes(invIndexType); ITokenFactory tokenFactory = new HashedUTF8NGramTokenFactory(); IBinaryTokenizerFactory tokenizerFactory = new NGramUTF8StringBinaryTokenizerFactory(TEST_GRAM_LENGTH, true, true, false, tokenFactory); LSMInvertedIndexTestContext testCtx = LSMInvertedIndexTestContext.create(harness, fieldSerdes, fieldSerdes.length - 1, tokenizerFactory, invIndexType, null, null, null, null, null, null); return testCtx; } public static void bulkLoadInvIndex(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, int numDocs, boolean appendOnly) throws HyracksDataException, IOException { SortedSet<CheckTuple> tmpMemIndex = new TreeSet<>(); // First generate the expected index by inserting the documents one-by-one. for (int i = 0; i < numDocs; i++) { ITupleReference tuple = tupleGen.next(); testCtx.insertCheckTuples(tuple, tmpMemIndex); } ISerializerDeserializer[] fieldSerdes = testCtx.getFieldSerdes(); // Use the expected index to bulk-load the actual index. IIndexBulkLoader bulkLoader = testCtx.getIndex().createBulkLoader(1.0f, false, numDocs, true); ArrayTupleBuilder tupleBuilder = new ArrayTupleBuilder(testCtx.getFieldSerdes().length); ArrayTupleReference tuple = new ArrayTupleReference(); Iterator<CheckTuple> checkTupleIter = tmpMemIndex.iterator(); while (checkTupleIter.hasNext()) { CheckTuple checkTuple = checkTupleIter.next(); OrderedIndexTestUtils.createTupleFromCheckTuple(checkTuple, tupleBuilder, tuple, fieldSerdes); bulkLoader.add(tuple); } bulkLoader.end(); // Add all check tuples from the temp index to the text context. testCtx.getCheckTuples().addAll(tmpMemIndex); } public static void insertIntoInvIndex(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, int numDocs) throws IOException { // InMemoryInvertedIndex only supports insert. for (int i = 0; i < numDocs; i++) { ITupleReference tuple = tupleGen.next(); testCtx.getIndexAccessor().insert(tuple); testCtx.insertCheckTuples(tuple, testCtx.getCheckTuples()); } } public static void deleteFromInvIndex(LSMInvertedIndexTestContext testCtx, Random rnd, int numDocsToDelete) throws HyracksDataException { List<ITupleReference> documentCorpus = testCtx.getDocumentCorpus(); for (int i = 0; i < numDocsToDelete && !documentCorpus.isEmpty(); i++) { int size = documentCorpus.size(); int tupleIndex = Math.abs(rnd.nextInt()) % size; ITupleReference deleteTuple = documentCorpus.get(tupleIndex); testCtx.getIndexAccessor().delete(deleteTuple); testCtx.deleteCheckTuples(deleteTuple, testCtx.getCheckTuples()); // Swap tupleIndex with last element. documentCorpus.set(tupleIndex, documentCorpus.get(size - 1)); documentCorpus.remove(size - 1); } } /** * Compares actual and expected indexes using the rangeSearch() method of the inverted-index accessor. */ public static void compareActualAndExpectedIndexesRangeSearch(LSMInvertedIndexTestContext testCtx) throws HyracksDataException { IInvertedIndex invIndex = (IInvertedIndex) testCtx.getIndex(); int tokenFieldCount = invIndex.getTokenTypeTraits().length; int invListFieldCount = invIndex.getInvListTypeTraits().length; IInvertedIndexAccessor invIndexAccessor = (IInvertedIndexAccessor) invIndex .createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE); IIndexCursor invIndexCursor = invIndexAccessor.createRangeSearchCursor(); MultiComparator tokenCmp = MultiComparator.create(invIndex.getTokenCmpFactories()); IBinaryComparatorFactory[] tupleCmpFactories = new IBinaryComparatorFactory[tokenFieldCount + invListFieldCount]; for (int i = 0; i < tokenFieldCount; i++) { tupleCmpFactories[i] = invIndex.getTokenCmpFactories()[i]; } for (int i = 0; i < invListFieldCount; i++) { tupleCmpFactories[tokenFieldCount + i] = invIndex.getInvListCmpFactories()[i]; } MultiComparator tupleCmp = MultiComparator.create(tupleCmpFactories); RangePredicate nullPred = new RangePredicate(null, null, true, true, tokenCmp, tokenCmp); invIndexAccessor.rangeSearch(invIndexCursor, nullPred); // Helpers for generating a serialized inverted-list element from a CheckTuple from the expected index. ISerializerDeserializer[] fieldSerdes = testCtx.getFieldSerdes(); ArrayTupleBuilder expectedBuilder = new ArrayTupleBuilder(fieldSerdes.length); ArrayTupleReference expectedTuple = new ArrayTupleReference(); Iterator<CheckTuple> expectedIter = testCtx.getCheckTuples().iterator(); // Compare index elements. try { while (invIndexCursor.hasNext() && expectedIter.hasNext()) { invIndexCursor.next(); ITupleReference actualTuple = invIndexCursor.getTuple(); CheckTuple expected = expectedIter.next(); OrderedIndexTestUtils.createTupleFromCheckTuple(expected, expectedBuilder, expectedTuple, fieldSerdes); if (tupleCmp.compare(actualTuple, expectedTuple) != 0) { fail("Index entries differ for token '" + expected.getField(0) + "'."); } } if (expectedIter.hasNext()) { fail("Indexes do not match. Actual index is missing entries."); } if (invIndexCursor.hasNext()) { fail("Indexes do not match. Actual index contains too many entries."); } } finally { invIndexCursor.close(); } } /** * Compares actual and expected indexes by comparing their inverted-lists one by one. Exercises the openInvertedListCursor() method of the inverted-index accessor. */ @SuppressWarnings("unchecked") public static void compareActualAndExpectedIndexes(LSMInvertedIndexTestContext testCtx) throws HyracksDataException { IInvertedIndex invIndex = (IInvertedIndex) testCtx.getIndex(); ISerializerDeserializer[] fieldSerdes = testCtx.getFieldSerdes(); MultiComparator invListCmp = MultiComparator.create(invIndex.getInvListCmpFactories()); IInvertedIndexAccessor invIndexAccessor = (IInvertedIndexAccessor) testCtx.getIndexAccessor(); int tokenFieldCount = invIndex.getTokenTypeTraits().length; int invListFieldCount = invIndex.getInvListTypeTraits().length; // All tokens that were inserted into the indexes. Iterator<Comparable> tokensIter = testCtx.getAllTokens().iterator(); // Search key for finding an inverted-list in the actual index. ArrayTupleBuilder searchKeyBuilder = new ArrayTupleBuilder(tokenFieldCount); ArrayTupleReference searchKey = new ArrayTupleReference(); // Cursor over inverted list from actual index. IInvertedListCursor actualInvListCursor = invIndexAccessor.createInvertedListCursor(); // Helpers for generating a serialized inverted-list element from a CheckTuple from the expected index. ArrayTupleBuilder expectedBuilder = new ArrayTupleBuilder(fieldSerdes.length); // Includes the token fields. ArrayTupleReference completeExpectedTuple = new ArrayTupleReference(); // Field permutation and permuting tuple reference to strip away token fields from completeExpectedTuple. int[] fieldPermutation = new int[invListFieldCount]; for (int i = 0; i < fieldPermutation.length; i++) { fieldPermutation[i] = tokenFieldCount + i; } PermutingTupleReference expectedTuple = new PermutingTupleReference(fieldPermutation); // Iterate over all tokens. Find the inverted-lists in actual and expected indexes. Compare the inverted lists, while (tokensIter.hasNext()) { Comparable token = tokensIter.next(); // Position inverted-list iterator on expected index. CheckTuple checkLowKey = new CheckTuple(tokenFieldCount, tokenFieldCount); checkLowKey.appendField(token); CheckTuple checkHighKey = new CheckTuple(tokenFieldCount, tokenFieldCount); checkHighKey.appendField(token); SortedSet<CheckTuple> expectedInvList = OrderedIndexTestUtils.getPrefixExpectedSubset(testCtx.getCheckTuples(), checkLowKey, checkHighKey); Iterator<CheckTuple> expectedInvListIter = expectedInvList.iterator(); // Position inverted-list cursor in actual index. OrderedIndexTestUtils.createTupleFromCheckTuple(checkLowKey, searchKeyBuilder, searchKey, fieldSerdes); invIndexAccessor.openInvertedListCursor(actualInvListCursor, searchKey); if (actualInvListCursor.size() != expectedInvList.size()) { fail("Actual and expected inverted lists for token '" + token.toString() + "' have different sizes. Actual size: " + actualInvListCursor.size() + ". Expected size: " + expectedInvList.size() + "."); } // Compare inverted-list elements. int count = 0; actualInvListCursor.pinPages(); try { while (actualInvListCursor.hasNext() && expectedInvListIter.hasNext()) { actualInvListCursor.next(); ITupleReference actual = actualInvListCursor.getTuple(); CheckTuple expected = expectedInvListIter.next(); OrderedIndexTestUtils.createTupleFromCheckTuple(expected, expectedBuilder, completeExpectedTuple, fieldSerdes); expectedTuple.reset(completeExpectedTuple); if (invListCmp.compare(actual, expectedTuple) != 0) { fail("Inverted lists of token '" + token + "' differ at position " + count + "."); } count++; } } finally { actualInvListCursor.unpinPages(); } } } /** * Determine the expected results with the simple ScanCount algorithm. */ public static void getExpectedResults(int[] scanCountArray, TreeSet<CheckTuple> checkTuples, ITupleReference searchDocument, IBinaryTokenizer tokenizer, ISerializerDeserializer tokenSerde, IInvertedIndexSearchModifier searchModifier, List<Integer> expectedResults, InvertedIndexType invIndexType) throws IOException { boolean isPartitioned = false; switch (invIndexType) { case INMEMORY: case ONDISK: case LSM: { isPartitioned = false; break; } case PARTITIONED_INMEMORY: case PARTITIONED_ONDISK: case PARTITIONED_LSM: { isPartitioned = true; break; } } getExpectedResults(scanCountArray, checkTuples, searchDocument, tokenizer, tokenSerde, searchModifier, expectedResults, isPartitioned); } @SuppressWarnings("unchecked") public static void getExpectedResults(int[] scanCountArray, TreeSet<CheckTuple> checkTuples, ITupleReference searchDocument, IBinaryTokenizer tokenizer, ISerializerDeserializer tokenSerde, IInvertedIndexSearchModifier searchModifier, List<Integer> expectedResults, boolean isPartitioned) throws IOException { // Reset scan count array. Arrays.fill(scanCountArray, 0); expectedResults.clear(); GrowableArray tokenData = new GrowableArray(); tokenizer.reset(searchDocument.getFieldData(0), searchDocument.getFieldStart(0), searchDocument.getFieldLength(0)); // Run though tokenizer to get number of tokens. int numQueryTokens = 0; while (tokenizer.hasNext()) { tokenizer.next(); numQueryTokens++; } short numTokensLowerBound = -1; short numTokensUpperBound = -1; int invListElementField = 1; if (isPartitioned) { numTokensLowerBound = searchModifier.getNumTokensLowerBound((short) numQueryTokens); numTokensUpperBound = searchModifier.getNumTokensUpperBound((short) numQueryTokens); invListElementField = 2; } int occurrenceThreshold = searchModifier.getOccurrenceThreshold(numQueryTokens); tokenizer.reset(searchDocument.getFieldData(0), searchDocument.getFieldStart(0), searchDocument.getFieldLength(0)); while (tokenizer.hasNext()) { tokenizer.next(); IToken token = tokenizer.getToken(); tokenData.reset(); token.serializeToken(tokenData); ByteArrayInputStream inStream = new ByteArrayInputStream(tokenData.getByteArray(), 0, tokenData.getLength()); DataInput dataIn = new DataInputStream(inStream); Comparable tokenObj = (Comparable) tokenSerde.deserialize(dataIn); CheckTuple lowKey; if (numTokensLowerBound < 0) { // Index is not partitioned, or no length filtering is possible for this search modifier. lowKey = new CheckTuple(1, 1); lowKey.appendField(tokenObj); } else { // Index is length partitioned, and search modifier supports length filtering. lowKey = new CheckTuple(2, 2); lowKey.appendField(tokenObj); lowKey.appendField(Short.valueOf(numTokensLowerBound)); } CheckTuple highKey; if (numTokensUpperBound < 0) { // Index is not partitioned, or no length filtering is possible for this search modifier. highKey = new CheckTuple(1, 1); highKey.appendField(tokenObj); } else { // Index is length partitioned, and search modifier supports length filtering. highKey = new CheckTuple(2, 2); highKey.appendField(tokenObj); highKey.appendField(Short.valueOf(numTokensUpperBound)); } // Get view over check tuples containing inverted-list corresponding to token. SortedSet<CheckTuple> invList = OrderedIndexTestUtils.getPrefixExpectedSubset(checkTuples, lowKey, highKey); Iterator<CheckTuple> invListIter = invList.iterator(); // Iterate over inverted list and update scan count array. while (invListIter.hasNext()) { CheckTuple checkTuple = invListIter.next(); Integer element = (Integer) checkTuple.getField(invListElementField); scanCountArray[element]++; } } // Run through scan count array, and see whether elements satisfy the given occurrence threshold. expectedResults.clear(); for (int i = 0; i < scanCountArray.length; i++) { if (scanCountArray[i] >= occurrenceThreshold) { expectedResults.add(i); } } } public static void testIndexSearch(LSMInvertedIndexTestContext testCtx, TupleGenerator tupleGen, Random rnd, int numDocQueries, int numRandomQueries, IInvertedIndexSearchModifier searchModifier, int[] scanCountArray) throws IOException, HyracksDataException { IInvertedIndex invIndex = testCtx.invIndex; IInvertedIndexAccessor accessor = (IInvertedIndexAccessor) invIndex .createAccessor(NoOpOperationCallback.INSTANCE, NoOpOperationCallback.INSTANCE); IBinaryTokenizer tokenizer = testCtx.getTokenizerFactory().createTokenizer(); InvertedIndexSearchPredicate searchPred = new InvertedIndexSearchPredicate(tokenizer, searchModifier); List<ITupleReference> documentCorpus = testCtx.getDocumentCorpus(); // Project away the primary-key field. int[] fieldPermutation = new int[] { 0 }; PermutingTupleReference searchDocument = new PermutingTupleReference(fieldPermutation); int numQueries = numDocQueries + numRandomQueries; for (int i = 0; i < numQueries; i++) { // If number of documents in the corpus is less than numDocQueries, then replace the remaining ones with random queries. if (i >= numDocQueries || i >= documentCorpus.size()) { // Generate a random query. ITupleReference randomQuery = tupleGen.next(); searchDocument.reset(randomQuery); } else { // Pick a random document from the corpus to use as the search query. int queryIndex = Math.abs(rnd.nextInt() % documentCorpus.size()); searchDocument.reset(documentCorpus.get(queryIndex)); } // Set query tuple in search predicate. searchPred.setQueryTuple(searchDocument); searchPred.setQueryFieldIndex(0); IIndexCursor resultCursor = accessor.createSearchCursor(false); boolean panic = false; try { accessor.search(resultCursor, searchPred); } catch (HyracksDataException e) { // ignore panic queries. if (e.getErrorCode() == ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION) { panic = true; } else { throw e; } } try { if (!panic) { // Consume cursor and deserialize results so we can sort them. Some search cursors may not deliver the result sorted (e.g., LSM search cursor). ArrayList<Integer> actualResults = new ArrayList<>(); try { while (resultCursor.hasNext()) { resultCursor.next(); ITupleReference resultTuple = resultCursor.getTuple(); int actual = IntegerPointable.getInteger(resultTuple.getFieldData(0), resultTuple.getFieldStart(0)); actualResults.add(Integer.valueOf(actual)); } } catch (HyracksDataException e) { if (e.getErrorCode() == ErrorCode.OCCURRENCE_THRESHOLD_PANIC_EXCEPTION) { // Ignore panic queries. continue; } else { throw e; } } Collections.sort(actualResults); // Get expected results. List<Integer> expectedResults = new ArrayList<>(); LSMInvertedIndexTestUtils.getExpectedResults(scanCountArray, testCtx.getCheckTuples(), searchDocument, tokenizer, testCtx.getFieldSerdes()[0], searchModifier, expectedResults, testCtx.getInvertedIndexType()); Iterator<Integer> expectedIter = expectedResults.iterator(); Iterator<Integer> actualIter = actualResults.iterator(); while (expectedIter.hasNext() && actualIter.hasNext()) { int expected = expectedIter.next(); int actual = actualIter.next(); if (actual != expected) { fail("Query results do not match. Encountered: " + actual + ". Expected: " + expected + ""); } } if (expectedIter.hasNext()) { fail("Query results do not match. Actual results missing."); } if (actualIter.hasNext()) { fail("Query results do not match. Actual contains too many results."); } } } finally { resultCursor.close(); } } } }
apache-2.0
acrosoft-be/shared
Dispatch/src/main/java/be/acrosoft/gaia/shared/dispatch/WeakListener.java
1283
/** * Copyright Acropolis Software SPRL (https://www.acrosoft.be) * * 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 be.acrosoft.gaia.shared.dispatch; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is used on {@link Listener} implementations to indicate that instances of these * listeners should be stored as {@link java.lang.ref.WeakReference} as much as possible, allowing for * their collection even though they are registered as listeners in listener groups. * @see Listener * @see java.lang.ref.WeakReference */ @Target({ElementType.TYPE}) @Retention(value=RetentionPolicy.RUNTIME) public @interface WeakListener { }
apache-2.0
shigengyu/Hyperion
src/main/java/com/shigengyu/hyperion/core/TransitionCompensator.java
1103
/******************************************************************************* * Copyright 2013-2014 Gengyu (Univer) Shi * * 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.shigengyu.hyperion.core; /** * The common interface for all compensators. Compensators need to be designed as stateless. * * @author Gengyu (Univer) Shi * */ public interface TransitionCompensator { boolean canHandle(Exception exception); TransitionCompensationResult compensate(WorkflowInstance workflowInstance); }
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rosa/Rosa oederiana/README.md
171
# Rosa oederiana Tratt. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
smartliby/smartliby.github.io
source/_posts/2014-05-26-设计模式13之-门面-Facade-模式-结构模式.md
9331
--- title: 设计模式13之 门面(Facade)模式(结构模式) date: 2014-05-26 11:09:23 categories: - 设计模式 tags: - java - 门面模式 --- # 门面模式简介 门面模式是对象的结构模式,外部与一个子系统的通信必须通过一个统一的门面对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。 举个例子, 病人去医院看病,如果把医院作为一个子系统,按照部门职能,这个系统可以划分为挂号、门诊、划价、化验、收费、取药等。看病的病人要与这些部门打交道,就如同一个子系统的客户端与一个子系统的各个类打交道一样,不是一件容易的事情:首先病人必须先挂号,然后门诊;如果医生要求化验,病人必须首先划价,然后缴费,才可以到化验部门做化验;化验后再回到门诊室。如下图所示: <!-- more --> ![pattern13_01](/images/media/pattern13_01.jpg) 而如果引"进门面模式",在医院中增加一个接待员。由接待员负责代为挂号、划价、缴费、取药等,病人只接触接待员,由接待员与各个部门打交道。这样,对病人来说,就会简单很多。如下图所示: ![pattern13_02](/images/media/pattern13_02.jpg) 下面看看门面模式的UML类图: ![pattern13_03](/images/media/pattern13_03.jpg) 门面模式包括2个角色:**门面(Facade),子系统(SubSystem)**。 | 角色 | 说明 | | ---------- | --------------- | | 门 面 | 客户端可以调用这个角色的方法。此角色知晓相关的(一个或者多个)子系统的功能和责任。在正常情况下,本角色会将所有从客户端发来的请求委派到相应的子系统去。 | | 子系统 | 可以同时有一个或者多个子系统。每个子系统都不是一个单独的类,而是一个类的集合。每个子系统都可以被客户端直接调用,或者被门面角色调用。子系统并不知道门面的存在,对于子系统而言,门面仅仅是另外一个客户端而已。 | # 门面模式示例 一个保安系统由两个录像机、三个电灯、一个遥控器和一个警报器组成。保安系统的操作人员在早上上班的时候,将这些仪器打开;晚上下班之后,会将这些仪器关闭。 我们先演示在不使用"门面模式"的情况下,实现该系统。然后,通过"门面模式"实现该系统。 ## 未使用"门面模式" UML类图如下: ![pattern13_04](/images/media/pattern13_04.jpg) 从图中可以看出,客户端Client对象需要引用到录像机(Camera)、电灯(Light)、感应器(Sensor)和报警器(Alarm)所有的对象。 客户端(Client)源码 public class Client { private static Camera camera1, camera2; private static Light light1, light2, light3; private static Sensor sensor; private static Alarm alarm; public static void main(String[] args) { camera1 = new Camera(); camera2 = new Camera(); light1 = new Light(); light2 = new Light(); light3 = new Light(); sensor = new Sensor(); alarm = new Alarm(); camera1.turnOn(); camera2.turnOn(); light1.turnOn(); light2.turnOn(); light3.turnOn(); sensor.activate(); alarm.activate(); } } 录像机(Camera)源码 public class Camera { // 打开录像机 public void turnOn() { System.out.println("Turning on the camera."); } // 关闭录像机 public void turnOff() { System.out.println("Turning off the camera."); } // 转动录像机 public void rotate(int degrees) { System.out.println("Rotating the camera by "+degrees+" degrees."); } } 电灯(Light)源码 public class Light { // 打开灯 public void turnOn() { System.out.println("Turning on the light."); } // 关闭灯 public void turnOff() { System.out.println("Turning off the light."); } // 换灯泡 public void changeBulb() { System.out.println("Cotating the light-bulb."); } } 感应器(Sensor)源码 public class Sensor { // 启动感应器 public void activate() { System.out.println("Activating on the sensor."); } // 关闭感应器 public void deactivate() { System.out.println("Deactivating the sensor."); } // 触发感应器 public void trigger() { System.out.println("The sensor has been triggered."); } } 报警器(Alarm)源码 public class Alarm { // 启动警报器 public void activate() { System.out.println("Activating on the alarm."); } // 关闭警报器 public void deactivate() { System.out.println("Deactivating the alarm."); } // 拉响警报器 public void ring() { System.out.println("Ringing the alarm"); } // 停掉警报器 public void stopRing() { System.out.println("Stop the alarm"); } } 运行结果: Turning on the camera. Turning on the camera. Turning on the light. Turning on the light. Turning on the light. Activating on the sensor. Activating on the alarm. ## 使用"门面模式" UML类图如下: ![pattern13_05](/images/media/pattern13_05.jpg) 可以看出:门面SecurityFade承担了与保安系统内部各个对象打交道的任务,而客户对象只需要与门面对象打交道即可。SecurityFade是客户端与保安系统之间的一个门户,它使得客户端与子系统之间的关系变得简单和易于管理。 客户端(Client)源码 public class Client { private static SecurityFacade security; public static void main(String[] args) { security = new SecurityFacade(); security.activate(); } } 门面(SecurityFade)源码 public class SecurityFacade { private Camera camera1, camera2; private Light light1, light2, light3; private Sensor sensor; private Alarm alarm; public SecurityFacade() { camera1 = new Camera(); camera2 = new Camera(); light1 = new Light(); light2 = new Light(); light3 = new Light(); sensor = new Sensor(); alarm = new Alarm(); } public void activate() { camera1.turnOn(); camera2.turnOn(); light1.turnOn(); light2.turnOn(); light3.turnOn(); sensor.activate(); alarm.activate(); } public void deactivate() { camera1.turnOff(); camera2.turnOff(); light1.turnOff(); light2.turnOff(); light3.turnOff(); sensor.deactivate(); alarm.deactivate(); } } 录像机(Camera)源码 public class Camera { // 打开录像机 public void turnOn() { System.out.println("Turning on the camera."); } // 关闭录像机 public void turnOff() { System.out.println("Turning off the camera."); } // 转动录像机 public void rotate(int degrees) { System.out.println("Rotating the camera by "+degrees+" degrees."); } } 电灯(Light)源码 public class Light { // 打开灯 public void turnOn() { System.out.println("Turning on the light."); } // 关闭灯 public void turnOff() { System.out.println("Turning off the light."); } // 换灯泡 public void changeBulb() { System.out.println("Cotating the light-bulb."); } } 感应器(Sensor)源码 public class Sensor { // 启动感应器 public void activate() { System.out.println("Activating on the sensor."); } // 关闭感应器 public void deactivate() { System.out.println("Deactivating the sensor."); } // 触发感应器 public void trigger() { System.out.println("The sensor has been triggered."); } } 报警器(Alarm)源码 public class Alarm { // 启动警报器 public void activate() { System.out.println("Activating on the alarm."); } // 关闭警报器 public void deactivate() { System.out.println("Deactivating the alarm."); } // 拉响警报器 public void ring() { System.out.println("Ringing the alarm"); } // 停掉警报器 public void stopRing() { System.out.println("Stop the alarm"); } } 运行结果: Turning on the camera. Turning on the camera. Turning on the light. Turning on the light. Turning on the light. Activating on the sensor. Activating on the alarm.
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Coelococcus/README.md
168
# Coelococcus H.Wendl. GENUS #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
tanglei528/nova
nova/db/api.py
65070
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """Defines interface for DB access. Functions in this module are imported into the nova.db namespace. Call these functions from nova.db namespace, not the nova.db.api namespace. All functions in this module return objects that implement a dictionary-like interface. Currently, many of these objects are sqlalchemy objects that implement a dictionary interface. However, a future goal is to have all of these objects be simple dictionaries. """ from eventlet import tpool from oslo.config import cfg from nova.cells import rpcapi as cells_rpcapi from nova.openstack.common.db import api as db_api from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging db_opts = [ cfg.BoolOpt('enable_new_services', default=True, help='Services to be added to the available pool on create'), cfg.StrOpt('instance_name_template', default='instance-%08x', help='Template string to be used to generate instance names'), cfg.StrOpt('snapshot_name_template', default='snapshot-%s', help='Template string to be used to generate snapshot names'), ] tpool_opts = [ cfg.BoolOpt('use_tpool', default=False, deprecated_name='dbapi_use_tpool', deprecated_group='DEFAULT', help='Enable the experimental use of thread pooling for ' 'all DB API calls'), ] CONF = cfg.CONF CONF.register_opts(db_opts) CONF.register_opts(tpool_opts, 'database') CONF.import_opt('backend', 'nova.openstack.common.db.options', group='database') _BACKEND_MAPPING = {'sqlalchemy': 'nova.db.sqlalchemy.api'} class NovaDBAPI(object): """Nova's DB API wrapper class. This wraps the oslo DB API with an option to be able to use eventlet's thread pooling. Since the CONF variable may not be loaded at the time this class is instantiated, we must look at it on the first DB API call. """ def __init__(self): self.__db_api = None @property def _db_api(self): if not self.__db_api: nova_db_api = db_api.DBAPI(CONF.database.backend, backend_mapping=_BACKEND_MAPPING) if CONF.database.use_tpool: self.__db_api = tpool.Proxy(nova_db_api) else: self.__db_api = nova_db_api return self.__db_api def __getattr__(self, key): return getattr(self._db_api, key) IMPL = NovaDBAPI() LOG = logging.getLogger(__name__) # The maximum value a signed INT type may have MAX_INT = 0x7FFFFFFF ################### def constraint(**conditions): """Return a constraint object suitable for use with some updates.""" return IMPL.constraint(**conditions) def equal_any(*values): """Return an equality condition object suitable for use in a constraint. Equal_any conditions require that a model object's attribute equal any one of the given values. """ return IMPL.equal_any(*values) def not_equal(*values): """Return an inequality condition object suitable for use in a constraint. Not_equal conditions require that a model object's attribute differs from all of the given values. """ return IMPL.not_equal(*values) ################### def service_destroy(context, service_id): """Destroy the service or raise if it does not exist.""" return IMPL.service_destroy(context, service_id) def service_get(context, service_id, with_compute_node=False): """Get a service or raise if it does not exist.""" return IMPL.service_get(context, service_id, with_compute_node=with_compute_node) def service_get_by_host_and_topic(context, host, topic): """Get a service by host it's on and topic it listens to.""" return IMPL.service_get_by_host_and_topic(context, host, topic) def service_get_all(context, disabled=None): """Get all services.""" return IMPL.service_get_all(context, disabled) def service_get_all_by_topic(context, topic): """Get all services for a given topic.""" return IMPL.service_get_all_by_topic(context, topic) def service_get_all_by_host(context, host): """Get all services for a given host.""" return IMPL.service_get_all_by_host(context, host) def service_get_by_compute_host(context, host): """Get the service entry for a given compute host. Returns the service entry joined with the compute_node entry. """ return IMPL.service_get_by_compute_host(context, host) def service_get_by_args(context, host, binary): """Get the state of a service by node name and binary.""" return IMPL.service_get_by_args(context, host, binary) def service_create(context, values): """Create a service from the values dictionary.""" return IMPL.service_create(context, values) def service_update(context, service_id, values): """Set the given properties on a service and update it. Raises NotFound if service does not exist. """ return IMPL.service_update(context, service_id, values) ################### def compute_node_get(context, compute_id): """Get a compute node by its id. :param context: The security context :param compute_id: ID of the compute node :returns: Dictionary-like object containing properties of the compute node, including its corresponding service Raises ComputeHostNotFound if compute node with the given ID doesn't exist. """ return IMPL.compute_node_get(context, compute_id) def compute_node_get_by_service_id(context, service_id): """Get a compute node by its associated service id. :param context: The security context :param service_id: ID of the associated service :returns: Dictionary-like object containing properties of the compute node, including its corresponding service and statistics Raises ServiceNotFound if service with the given ID doesn't exist. """ return IMPL.compute_node_get_by_service_id(context, service_id) def compute_node_get_all(context, no_date_fields=False): """Get all computeNodes. :param context: The security context :param no_date_fields: If set to True, excludes 'created_at', 'updated_at', 'deleted_at' and 'deleted' fields from the output, thus significantly reducing its size. Set to False by default :returns: List of dictionaries each containing compute node properties, including corresponding service """ return IMPL.compute_node_get_all(context, no_date_fields) def compute_node_search_by_hypervisor(context, hypervisor_match): """Get compute nodes by hypervisor hostname. :param context: The security context :param hypervisor_match: The hypervisor hostname :returns: List of dictionary-like objects each containing compute node properties, including corresponding service """ return IMPL.compute_node_search_by_hypervisor(context, hypervisor_match) def compute_node_create(context, values): """Create a compute node from the values dictionary. :param context: The security context :param values: Dictionary containing compute node properties :returns: Dictionary-like object containing the properties of the created node, including its corresponding service and statistics """ return IMPL.compute_node_create(context, values) def compute_node_update(context, compute_id, values): """Set the given properties on a compute node and update it. :param context: The security context :param compute_id: ID of the compute node :param values: Dictionary containing compute node properties to be updated :returns: Dictionary-like object containing the properties of the updated compute node, including its corresponding service and statistics Raises ComputeHostNotFound if compute node with the given ID doesn't exist. """ return IMPL.compute_node_update(context, compute_id, values) def compute_node_delete(context, compute_id): """Delete a compute node from the database. :param context: The security context :param compute_id: ID of the compute node Raises ComputeHostNotFound if compute node with the given ID doesn't exist. """ return IMPL.compute_node_delete(context, compute_id) def compute_node_statistics(context): """Get aggregate statistics over all compute nodes. :param context: The security context :returns: Dictionary containing compute node characteristics summed up over all the compute nodes, e.g. 'vcpus', 'free_ram_mb' etc. """ return IMPL.compute_node_statistics(context) ################### def certificate_create(context, values): """Create a certificate from the values dictionary.""" return IMPL.certificate_create(context, values) def certificate_get_all_by_project(context, project_id): """Get all certificates for a project.""" return IMPL.certificate_get_all_by_project(context, project_id) def certificate_get_all_by_user(context, user_id): """Get all certificates for a user.""" return IMPL.certificate_get_all_by_user(context, user_id) def certificate_get_all_by_user_and_project(context, user_id, project_id): """Get all certificates for a user and project.""" return IMPL.certificate_get_all_by_user_and_project(context, user_id, project_id) ################### def floating_ip_get(context, id): return IMPL.floating_ip_get(context, id) def floating_ip_get_pools(context): """Returns a list of floating ip pools.""" return IMPL.floating_ip_get_pools(context) def floating_ip_allocate_address(context, project_id, pool, auto_assigned=False): """Allocate free floating ip from specified pool and return the address. Raises if one is not available. """ return IMPL.floating_ip_allocate_address(context, project_id, pool, auto_assigned) def floating_ip_bulk_create(context, ips): """Create a lot of floating ips from the values dictionary.""" return IMPL.floating_ip_bulk_create(context, ips) def floating_ip_bulk_destroy(context, ips): """Destroy a lot of floating ips from the values dictionary.""" return IMPL.floating_ip_bulk_destroy(context, ips) def floating_ip_create(context, values): """Create a floating ip from the values dictionary.""" return IMPL.floating_ip_create(context, values) def floating_ip_deallocate(context, address): """Deallocate a floating ip by address.""" return IMPL.floating_ip_deallocate(context, address) def floating_ip_destroy(context, address): """Destroy the floating_ip or raise if it does not exist.""" return IMPL.floating_ip_destroy(context, address) def floating_ip_disassociate(context, address): """Disassociate a floating ip from a fixed ip by address. :returns: the fixed ip record joined to network record or None if the ip was not associated to an ip. """ return IMPL.floating_ip_disassociate(context, address) def floating_ip_fixed_ip_associate(context, floating_address, fixed_address, host): """Associate a floating ip to a fixed_ip by address. :returns: the fixed ip record joined to network record or None if the ip was already associated to the fixed ip. """ return IMPL.floating_ip_fixed_ip_associate(context, floating_address, fixed_address, host) def floating_ip_get_all(context): """Get all floating ips.""" return IMPL.floating_ip_get_all(context) def floating_ip_get_all_by_host(context, host): """Get all floating ips by host.""" return IMPL.floating_ip_get_all_by_host(context, host) def floating_ip_get_all_by_project(context, project_id): """Get all floating ips by project.""" return IMPL.floating_ip_get_all_by_project(context, project_id) def floating_ip_get_by_address(context, address): """Get a floating ip by address or raise if it doesn't exist.""" return IMPL.floating_ip_get_by_address(context, address) def floating_ip_get_by_fixed_address(context, fixed_address): """Get a floating ips by fixed address.""" return IMPL.floating_ip_get_by_fixed_address(context, fixed_address) def floating_ip_get_by_fixed_ip_id(context, fixed_ip_id): """Get a floating ips by fixed address.""" return IMPL.floating_ip_get_by_fixed_ip_id(context, fixed_ip_id) def floating_ip_update(context, address, values): """Update a floating ip by address or raise if it doesn't exist.""" return IMPL.floating_ip_update(context, address, values) def floating_ip_set_auto_assigned(context, address): """Set auto_assigned flag to floating ip.""" return IMPL.floating_ip_set_auto_assigned(context, address) def dnsdomain_list(context): """Get a list of all zones in our database, public and private.""" return IMPL.dnsdomain_list(context) def dnsdomain_get_all(context): """Get a list of all dnsdomains in our database.""" return IMPL.dnsdomain_get_all(context) def dnsdomain_register_for_zone(context, fqdomain, zone): """Associated a DNS domain with an availability zone.""" return IMPL.dnsdomain_register_for_zone(context, fqdomain, zone) def dnsdomain_register_for_project(context, fqdomain, project): """Associated a DNS domain with a project id.""" return IMPL.dnsdomain_register_for_project(context, fqdomain, project) def dnsdomain_unregister(context, fqdomain): """Purge associations for the specified DNS zone.""" return IMPL.dnsdomain_unregister(context, fqdomain) def dnsdomain_get(context, fqdomain): """Get the db record for the specified domain.""" return IMPL.dnsdomain_get(context, fqdomain) #################### def migration_update(context, id, values): """Update a migration instance.""" return IMPL.migration_update(context, id, values) def migration_create(context, values): """Create a migration record.""" return IMPL.migration_create(context, values) def migration_get(context, migration_id): """Finds a migration by the id.""" return IMPL.migration_get(context, migration_id) def migration_get_by_instance_and_status(context, instance_uuid, status): """Finds a migration by the instance uuid its migrating.""" return IMPL.migration_get_by_instance_and_status(context, instance_uuid, status) def migration_get_unconfirmed_by_dest_compute(context, confirm_window, dest_compute, use_slave=False): """Finds all unconfirmed migrations within the confirmation window for a specific destination compute host. """ return IMPL.migration_get_unconfirmed_by_dest_compute(context, confirm_window, dest_compute, use_slave=use_slave) def migration_get_in_progress_by_host_and_node(context, host, node): """Finds all migrations for the given host + node that are not yet confirmed or reverted. """ return IMPL.migration_get_in_progress_by_host_and_node(context, host, node) def migration_get_all_by_filters(context, filters): """Finds all migrations in progress.""" return IMPL.migration_get_all_by_filters(context, filters) #################### def fixed_ip_associate(context, address, instance_uuid, network_id=None, reserved=False): """Associate fixed ip to instance. Raises if fixed ip is not available. """ return IMPL.fixed_ip_associate(context, address, instance_uuid, network_id, reserved) def fixed_ip_associate_pool(context, network_id, instance_uuid=None, host=None): """Find free ip in network and associate it to instance or host. Raises if one is not available. """ return IMPL.fixed_ip_associate_pool(context, network_id, instance_uuid, host) def fixed_ip_create(context, values): """Create a fixed ip from the values dictionary.""" return IMPL.fixed_ip_create(context, values) def fixed_ip_bulk_create(context, ips): """Create a lot of fixed ips from the values dictionary.""" return IMPL.fixed_ip_bulk_create(context, ips) def fixed_ip_disassociate(context, address): """Disassociate a fixed ip from an instance by address.""" return IMPL.fixed_ip_disassociate(context, address) def fixed_ip_disassociate_all_by_timeout(context, host, time): """Disassociate old fixed ips from host.""" return IMPL.fixed_ip_disassociate_all_by_timeout(context, host, time) def fixed_ip_get(context, id, get_network=False): """Get fixed ip by id or raise if it does not exist. If get_network is true, also return the associated network. """ return IMPL.fixed_ip_get(context, id, get_network) def fixed_ip_get_all(context): """Get all defined fixed ips.""" return IMPL.fixed_ip_get_all(context) def fixed_ip_get_by_address(context, address, columns_to_join=None): """Get a fixed ip by address or raise if it does not exist.""" return IMPL.fixed_ip_get_by_address(context, address, columns_to_join=columns_to_join) def fixed_ip_get_by_address_detailed(context, address): """Get detailed fixed ip info by address or raise if it does not exist.""" return IMPL.fixed_ip_get_by_address_detailed(context, address) def fixed_ip_get_by_floating_address(context, floating_address): """Get a fixed ip by a floating address.""" return IMPL.fixed_ip_get_by_floating_address(context, floating_address) def fixed_ip_get_by_instance(context, instance_uuid): """Get fixed ips by instance or raise if none exist.""" return IMPL.fixed_ip_get_by_instance(context, instance_uuid) def fixed_ip_get_by_host(context, host): """Get fixed ips by compute host.""" return IMPL.fixed_ip_get_by_host(context, host) def fixed_ip_get_by_network_host(context, network_uuid, host): """Get fixed ip for a host in a network.""" return IMPL.fixed_ip_get_by_network_host(context, network_uuid, host) def fixed_ips_by_virtual_interface(context, vif_id): """Get fixed ips by virtual interface or raise if none exist.""" return IMPL.fixed_ips_by_virtual_interface(context, vif_id) def fixed_ip_update(context, address, values): """Create a fixed ip from the values dictionary.""" return IMPL.fixed_ip_update(context, address, values) #################### def virtual_interface_create(context, values): """Create a virtual interface record in the database.""" return IMPL.virtual_interface_create(context, values) def virtual_interface_get(context, vif_id): """Gets a virtual interface from the table.""" return IMPL.virtual_interface_get(context, vif_id) def virtual_interface_get_by_address(context, address): """Gets a virtual interface from the table filtering on address.""" return IMPL.virtual_interface_get_by_address(context, address) def virtual_interface_get_by_uuid(context, vif_uuid): """Gets a virtual interface from the table filtering on vif uuid.""" return IMPL.virtual_interface_get_by_uuid(context, vif_uuid) def virtual_interface_get_by_instance(context, instance_id, use_slave=False): """Gets all virtual_interfaces for instance.""" return IMPL.virtual_interface_get_by_instance(context, instance_id, use_slave=use_slave) def virtual_interface_get_by_instance_and_network(context, instance_id, network_id): """Gets all virtual interfaces for instance.""" return IMPL.virtual_interface_get_by_instance_and_network(context, instance_id, network_id) def virtual_interface_delete_by_instance(context, instance_id): """Delete virtual interface records associated with instance.""" return IMPL.virtual_interface_delete_by_instance(context, instance_id) def virtual_interface_get_all(context): """Gets all virtual interfaces from the table.""" return IMPL.virtual_interface_get_all(context) #################### def instance_create(context, values): """Create an instance from the values dictionary.""" return IMPL.instance_create(context, values) def instance_destroy(context, instance_uuid, constraint=None, update_cells=True): """Destroy the instance or raise if it does not exist.""" rv = IMPL.instance_destroy(context, instance_uuid, constraint) if update_cells: try: cells_rpcapi.CellsAPI().instance_destroy_at_top(context, rv) except Exception: LOG.exception(_("Failed to notify cells of instance destroy")) return rv def instance_get_by_uuid(context, uuid, columns_to_join=None, use_slave=False): """Get an instance or raise if it does not exist.""" return IMPL.instance_get_by_uuid(context, uuid, columns_to_join, use_slave=use_slave) def instance_get(context, instance_id, columns_to_join=None): """Get an instance or raise if it does not exist.""" return IMPL.instance_get(context, instance_id, columns_to_join=columns_to_join) def instance_get_all(context, columns_to_join=None): """Get all instances.""" return IMPL.instance_get_all(context, columns_to_join=columns_to_join) def instance_get_all_by_filters(context, filters, sort_key='created_at', sort_dir='desc', limit=None, marker=None, columns_to_join=None, use_slave=False): """Get all instances that match all filters.""" return IMPL.instance_get_all_by_filters(context, filters, sort_key, sort_dir, limit=limit, marker=marker, columns_to_join=columns_to_join, use_slave=use_slave) def instance_get_active_by_window_joined(context, begin, end=None, project_id=None, host=None): """Get instances and joins active during a certain time window. Specifying a project_id will filter for a certain project. Specifying a host will filter for instances on a given compute host. """ return IMPL.instance_get_active_by_window_joined(context, begin, end, project_id, host) def instance_get_all_by_host(context, host, columns_to_join=None, use_slave=False): """Get all instances belonging to a host.""" return IMPL.instance_get_all_by_host(context, host, columns_to_join, use_slave=use_slave) def instance_get_all_by_host_and_node(context, host, node): """Get all instances belonging to a node.""" return IMPL.instance_get_all_by_host_and_node(context, host, node) def instance_get_all_by_host_and_not_type(context, host, type_id=None): """Get all instances belonging to a host with a different type_id.""" return IMPL.instance_get_all_by_host_and_not_type(context, host, type_id) def instance_get_floating_address(context, instance_id): """Get the first floating ip address of an instance.""" return IMPL.instance_get_floating_address(context, instance_id) def instance_floating_address_get_all(context, instance_uuid): """Get all floating ip addresses of an instance.""" return IMPL.instance_floating_address_get_all(context, instance_uuid) # NOTE(hanlind): This method can be removed as conductor RPC API moves to v2.0. def instance_get_all_hung_in_rebooting(context, reboot_window): """Get all instances stuck in a rebooting state.""" return IMPL.instance_get_all_hung_in_rebooting(context, reboot_window) def instance_update(context, instance_uuid, values, update_cells=True): """Set the given properties on an instance and update it. Raises NotFound if instance does not exist. """ rv = IMPL.instance_update(context, instance_uuid, values) if update_cells: try: cells_rpcapi.CellsAPI().instance_update_at_top(context, rv) except Exception: LOG.exception(_("Failed to notify cells of instance update")) return rv # FIXME(comstud): 'update_cells' is temporary as we transition to using # objects. When everything is using Instance.save(), we can remove the # argument and the RPC to nova-cells. def instance_update_and_get_original(context, instance_uuid, values, update_cells=True, columns_to_join=None): """Set the given properties on an instance and update it. Return a shallow copy of the original instance reference, as well as the updated one. :param context: = request context object :param instance_uuid: = instance id or uuid :param values: = dict containing column values :returns: a tuple of the form (old_instance_ref, new_instance_ref) Raises NotFound if instance does not exist. """ rv = IMPL.instance_update_and_get_original(context, instance_uuid, values, columns_to_join=columns_to_join) if update_cells: try: cells_rpcapi.CellsAPI().instance_update_at_top(context, rv[1]) except Exception: LOG.exception(_("Failed to notify cells of instance update")) return rv def instance_add_security_group(context, instance_id, security_group_id): """Associate the given security group with the given instance.""" return IMPL.instance_add_security_group(context, instance_id, security_group_id) def instance_remove_security_group(context, instance_id, security_group_id): """Disassociate the given security group from the given instance.""" return IMPL.instance_remove_security_group(context, instance_id, security_group_id) #################### def instance_group_create(context, values, policies=None, metadata=None, members=None): """Create a new group with metadata. Each group will receive a unique uuid. This will be used for access to the group. """ return IMPL.instance_group_create(context, values, policies, metadata, members) def instance_group_get(context, group_uuid): """Get a specific group by id.""" return IMPL.instance_group_get(context, group_uuid) def instance_group_update(context, group_uuid, values): """Update the attributes of an group.""" return IMPL.instance_group_update(context, group_uuid, values) def instance_group_delete(context, group_uuid): """Delete an group.""" return IMPL.instance_group_delete(context, group_uuid) def instance_group_get_all(context): """Get all groups.""" return IMPL.instance_group_get_all(context) def instance_group_get_all_by_project_id(context, project_id): """Get all groups for a specific project_id.""" return IMPL.instance_group_get_all_by_project_id(context, project_id) def instance_group_metadata_add(context, group_uuid, metadata, set_delete=False): """Add metadata to the group.""" return IMPL.instance_group_metadata_add(context, group_uuid, metadata, set_delete) def instance_group_metadata_delete(context, group_uuid, key): """Delete metadata from the group.""" return IMPL.instance_group_metadata_delete(context, group_uuid, key) def instance_group_metadata_get(context, group_uuid): """Get the metadata from the group.""" return IMPL.instance_group_metadata_get(context, group_uuid) def instance_group_members_add(context, group_uuid, members, set_delete=False): """Add members to the group.""" return IMPL.instance_group_members_add(context, group_uuid, members, set_delete=set_delete) def instance_group_member_delete(context, group_uuid, instance_id): """Delete a specific member from the group.""" return IMPL.instance_group_member_delete(context, group_uuid, instance_id) def instance_group_members_get(context, group_uuid): """Get the members from the group.""" return IMPL.instance_group_members_get(context, group_uuid) def instance_group_policies_add(context, group_uuid, policies, set_delete=False): """Add policies to the group.""" return IMPL.instance_group_policies_add(context, group_uuid, policies, set_delete=set_delete) def instance_group_policy_delete(context, group_uuid, policy): """Delete a specific policy from the group.""" return IMPL.instance_group_policy_delete(context, group_uuid, policy) def instance_group_policies_get(context, group_uuid): """Get the policies from the group.""" return IMPL.instance_group_policies_get(context, group_uuid) ################### def instance_info_cache_get(context, instance_uuid): """Gets an instance info cache from the table. :param instance_uuid: = uuid of the info cache's instance """ return IMPL.instance_info_cache_get(context, instance_uuid) def instance_info_cache_update(context, instance_uuid, values): """Update an instance info cache record in the table. :param instance_uuid: = uuid of info cache's instance :param values: = dict containing column values to update """ return IMPL.instance_info_cache_update(context, instance_uuid, values) def instance_info_cache_delete(context, instance_uuid): """Deletes an existing instance_info_cache record :param instance_uuid: = uuid of the instance tied to the cache record """ return IMPL.instance_info_cache_delete(context, instance_uuid) ################### def key_pair_create(context, values): """Create a key_pair from the values dictionary.""" return IMPL.key_pair_create(context, values) def key_pair_destroy(context, user_id, name): """Destroy the key_pair or raise if it does not exist.""" return IMPL.key_pair_destroy(context, user_id, name) def key_pair_get(context, user_id, name): """Get a key_pair or raise if it does not exist.""" return IMPL.key_pair_get(context, user_id, name) def key_pair_get_all_by_user(context, user_id): """Get all key_pairs by user.""" return IMPL.key_pair_get_all_by_user(context, user_id) def key_pair_count_by_user(context, user_id): """Count number of key pairs for the given user ID.""" return IMPL.key_pair_count_by_user(context, user_id) #################### def network_associate(context, project_id, network_id=None, force=False): """Associate a free network to a project.""" return IMPL.network_associate(context, project_id, network_id, force) def network_count_reserved_ips(context, network_id): """Return the number of reserved ips in the network.""" return IMPL.network_count_reserved_ips(context, network_id) def network_create_safe(context, values): """Create a network from the values dict. The network is only returned if the create succeeds. If the create violates constraints because the network already exists, no exception is raised. """ return IMPL.network_create_safe(context, values) def network_delete_safe(context, network_id): """Delete network with key network_id. This method assumes that the network is not associated with any project """ return IMPL.network_delete_safe(context, network_id) def network_disassociate(context, network_id, disassociate_host=True, disassociate_project=True): """Disassociate the network from project or host Raises if it does not exist. """ return IMPL.network_disassociate(context, network_id, disassociate_host, disassociate_project) def network_get(context, network_id, project_only="allow_none"): """Get a network or raise if it does not exist.""" return IMPL.network_get(context, network_id, project_only=project_only) def network_get_all(context, project_only="allow_none"): """Return all defined networks.""" return IMPL.network_get_all(context, project_only) def network_get_all_by_uuids(context, network_uuids, project_only="allow_none"): """Return networks by ids.""" return IMPL.network_get_all_by_uuids(context, network_uuids, project_only=project_only) # pylint: disable=C0103 def network_in_use_on_host(context, network_id, host=None): """Indicates if a network is currently in use on host.""" return IMPL.network_in_use_on_host(context, network_id, host) def network_get_associated_fixed_ips(context, network_id, host=None): """Get all network's ips that have been associated.""" return IMPL.network_get_associated_fixed_ips(context, network_id, host) def network_get_by_uuid(context, uuid): """Get a network by uuid or raise if it does not exist.""" return IMPL.network_get_by_uuid(context, uuid) def network_get_by_cidr(context, cidr): """Get a network by cidr or raise if it does not exist.""" return IMPL.network_get_by_cidr(context, cidr) def network_get_all_by_host(context, host): """All networks for which the given host is the network host.""" return IMPL.network_get_all_by_host(context, host) def network_set_host(context, network_id, host_id): """Safely set the host for network.""" return IMPL.network_set_host(context, network_id, host_id) def network_update(context, network_id, values): """Set the given properties on a network and update it. Raises NotFound if network does not exist. """ return IMPL.network_update(context, network_id, values) ############### def quota_create(context, project_id, resource, limit, user_id=None): """Create a quota for the given project and resource.""" return IMPL.quota_create(context, project_id, resource, limit, user_id=user_id) def quota_get(context, project_id, resource, user_id=None): """Retrieve a quota or raise if it does not exist.""" return IMPL.quota_get(context, project_id, resource, user_id=user_id) def quota_get_all_by_project_and_user(context, project_id, user_id): """Retrieve all quotas associated with a given project and user.""" return IMPL.quota_get_all_by_project_and_user(context, project_id, user_id) def quota_get_all_by_project(context, project_id): """Retrieve all quotas associated with a given project.""" return IMPL.quota_get_all_by_project(context, project_id) def quota_get_all(context, project_id): """Retrieve all user quotas associated with a given project.""" return IMPL.quota_get_all(context, project_id) def quota_update(context, project_id, resource, limit, user_id=None): """Update a quota or raise if it does not exist.""" return IMPL.quota_update(context, project_id, resource, limit, user_id=user_id) ################### def quota_usage_get(context, project_id, resource, user_id=None): """Retrieve a quota usage or raise if it does not exist.""" return IMPL.quota_usage_get(context, project_id, resource, user_id=user_id) def quota_usage_get_all_by_project_and_user(context, project_id, user_id): """Retrieve all usage associated with a given resource.""" return IMPL.quota_usage_get_all_by_project_and_user(context, project_id, user_id) def quota_usage_get_all_by_project(context, project_id): """Retrieve all usage associated with a given resource.""" return IMPL.quota_usage_get_all_by_project(context, project_id) def quota_usage_update(context, project_id, user_id, resource, **kwargs): """Update a quota usage or raise if it does not exist.""" return IMPL.quota_usage_update(context, project_id, user_id, resource, **kwargs) ################### def quota_reserve(context, resources, quotas, user_quotas, deltas, expire, until_refresh, max_age, project_id=None, user_id=None): """Check quotas and create appropriate reservations.""" return IMPL.quota_reserve(context, resources, quotas, user_quotas, deltas, expire, until_refresh, max_age, project_id=project_id, user_id=user_id) def reservation_commit(context, reservations, project_id=None, user_id=None): """Commit quota reservations.""" return IMPL.reservation_commit(context, reservations, project_id=project_id, user_id=user_id) def reservation_rollback(context, reservations, project_id=None, user_id=None): """Roll back quota reservations.""" return IMPL.reservation_rollback(context, reservations, project_id=project_id, user_id=user_id) def quota_destroy_all_by_project_and_user(context, project_id, user_id): """Destroy all quotas associated with a given project and user.""" return IMPL.quota_destroy_all_by_project_and_user(context, project_id, user_id) def quota_destroy_all_by_project(context, project_id): """Destroy all quotas associated with a given project.""" return IMPL.quota_destroy_all_by_project(context, project_id) def reservation_expire(context): """Roll back any expired reservations.""" return IMPL.reservation_expire(context) ################### def ec2_volume_create(context, volume_id, forced_id=None): return IMPL.ec2_volume_create(context, volume_id, forced_id) def ec2_volume_get_by_id(context, volume_id): return IMPL.ec2_volume_get_by_id(context, volume_id) def ec2_volume_get_by_uuid(context, volume_uuid): return IMPL.ec2_volume_get_by_uuid(context, volume_uuid) def get_snapshot_uuid_by_ec2_id(context, ec2_id): return IMPL.get_snapshot_uuid_by_ec2_id(context, ec2_id) def get_ec2_snapshot_id_by_uuid(context, snapshot_id): return IMPL.get_ec2_snapshot_id_by_uuid(context, snapshot_id) def ec2_snapshot_create(context, snapshot_id, forced_id=None): return IMPL.ec2_snapshot_create(context, snapshot_id, forced_id) #################### def block_device_mapping_create(context, values, legacy=True): """Create an entry of block device mapping.""" return IMPL.block_device_mapping_create(context, values, legacy) def block_device_mapping_update(context, bdm_id, values, legacy=True): """Update an entry of block device mapping.""" return IMPL.block_device_mapping_update(context, bdm_id, values, legacy) def block_device_mapping_update_or_create(context, values, legacy=True): """Update an entry of block device mapping. If not existed, create a new entry """ return IMPL.block_device_mapping_update_or_create(context, values, legacy) def block_device_mapping_get_all_by_instance(context, instance_uuid, use_slave=False): """Get all block device mapping belonging to an instance.""" return IMPL.block_device_mapping_get_all_by_instance(context, instance_uuid, use_slave) def block_device_mapping_get_by_volume_id(context, volume_id, columns_to_join=None): """Get block device mapping for a given volume.""" return IMPL.block_device_mapping_get_by_volume_id(context, volume_id, columns_to_join) def block_device_mapping_destroy(context, bdm_id): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy(context, bdm_id) def block_device_mapping_destroy_by_instance_and_device(context, instance_uuid, device_name): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy_by_instance_and_device( context, instance_uuid, device_name) def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy_by_instance_and_volume( context, instance_uuid, volume_id) #################### def security_group_get_all(context): """Get all security groups.""" return IMPL.security_group_get_all(context) def security_group_get(context, security_group_id, columns_to_join=None): """Get security group by its id.""" return IMPL.security_group_get(context, security_group_id, columns_to_join) def security_group_get_by_name(context, project_id, group_name, columns_to_join=None): """Returns a security group with the specified name from a project.""" return IMPL.security_group_get_by_name(context, project_id, group_name, columns_to_join=None) def security_group_get_by_project(context, project_id): """Get all security groups belonging to a project.""" return IMPL.security_group_get_by_project(context, project_id) def security_group_get_by_instance(context, instance_uuid): """Get security groups to which the instance is assigned.""" return IMPL.security_group_get_by_instance(context, instance_uuid) def security_group_in_use(context, group_id): """Indicates if a security group is currently in use.""" return IMPL.security_group_in_use(context, group_id) def security_group_create(context, values): """Create a new security group.""" return IMPL.security_group_create(context, values) def security_group_update(context, security_group_id, values, columns_to_join=None): """Update a security group.""" return IMPL.security_group_update(context, security_group_id, values, columns_to_join=columns_to_join) def security_group_ensure_default(context): """Ensure default security group exists for a project_id. Returns a tuple with the first element being a bool indicating if the default security group previously existed. Second element is the dict used to create the default security group. """ return IMPL.security_group_ensure_default(context) def security_group_destroy(context, security_group_id): """Deletes a security group.""" return IMPL.security_group_destroy(context, security_group_id) #################### def security_group_rule_create(context, values): """Create a new security group.""" return IMPL.security_group_rule_create(context, values) def security_group_rule_get_by_security_group(context, security_group_id, columns_to_join=None): """Get all rules for a given security group.""" return IMPL.security_group_rule_get_by_security_group( context, security_group_id, columns_to_join=columns_to_join) def security_group_rule_get_by_security_group_grantee(context, security_group_id): """Get all rules that grant access to the given security group.""" return IMPL.security_group_rule_get_by_security_group_grantee(context, security_group_id) def security_group_rule_destroy(context, security_group_rule_id): """Deletes a security group rule.""" return IMPL.security_group_rule_destroy(context, security_group_rule_id) def security_group_rule_get(context, security_group_rule_id): """Gets a security group rule.""" return IMPL.security_group_rule_get(context, security_group_rule_id) def security_group_rule_count_by_group(context, security_group_id): """Count rules in a given security group.""" return IMPL.security_group_rule_count_by_group(context, security_group_id) ################### def security_group_default_rule_get(context, security_group_rule_default_id): return IMPL.security_group_default_rule_get(context, security_group_rule_default_id) def security_group_default_rule_destroy(context, security_group_rule_default_id): return IMPL.security_group_default_rule_destroy( context, security_group_rule_default_id) def security_group_default_rule_create(context, values): return IMPL.security_group_default_rule_create(context, values) def security_group_default_rule_list(context): return IMPL.security_group_default_rule_list(context) ################### def provider_fw_rule_create(context, rule): """Add a firewall rule at the provider level (all hosts & instances).""" return IMPL.provider_fw_rule_create(context, rule) def provider_fw_rule_get_all(context): """Get all provider-level firewall rules.""" return IMPL.provider_fw_rule_get_all(context) def provider_fw_rule_destroy(context, rule_id): """Delete a provider firewall rule from the database.""" return IMPL.provider_fw_rule_destroy(context, rule_id) ################### def project_get_networks(context, project_id, associate=True): """Return the network associated with the project. If associate is true, it will attempt to associate a new network if one is not found, otherwise it returns None. """ return IMPL.project_get_networks(context, project_id, associate) ################### def console_pool_create(context, values): """Create console pool.""" return IMPL.console_pool_create(context, values) def console_pool_get_by_host_type(context, compute_host, proxy_host, console_type): """Fetch a console pool for a given proxy host, compute host, and type.""" return IMPL.console_pool_get_by_host_type(context, compute_host, proxy_host, console_type) def console_pool_get_all_by_host_type(context, host, console_type): """Fetch all pools for given proxy host and type.""" return IMPL.console_pool_get_all_by_host_type(context, host, console_type) def console_create(context, values): """Create a console.""" return IMPL.console_create(context, values) def console_delete(context, console_id): """Delete a console.""" return IMPL.console_delete(context, console_id) def console_get_by_pool_instance(context, pool_id, instance_uuid): """Get console entry for a given instance and pool.""" return IMPL.console_get_by_pool_instance(context, pool_id, instance_uuid) def console_get_all_by_instance(context, instance_uuid, columns_to_join=None): """Get consoles for a given instance.""" return IMPL.console_get_all_by_instance(context, instance_uuid, columns_to_join) def console_get(context, console_id, instance_uuid=None): """Get a specific console (possibly on a given instance).""" return IMPL.console_get(context, console_id, instance_uuid) ################## def flavor_create(context, values, projects=None): """Create a new instance type.""" return IMPL.flavor_create(context, values, projects=projects) def flavor_get_all(context, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): """Get all instance flavors.""" return IMPL.flavor_get_all( context, inactive=inactive, filters=filters, sort_key=sort_key, sort_dir=sort_dir, limit=limit, marker=marker) def flavor_get(context, id): """Get instance type by id.""" return IMPL.flavor_get(context, id) def flavor_get_by_name(context, name): """Get instance type by name.""" return IMPL.flavor_get_by_name(context, name) def flavor_get_by_flavor_id(context, id, read_deleted=None): """Get instance type by flavor id.""" return IMPL.flavor_get_by_flavor_id(context, id, read_deleted) def flavor_destroy(context, name): """Delete an instance type.""" return IMPL.flavor_destroy(context, name) def flavor_access_get_by_flavor_id(context, flavor_id): """Get flavor access by flavor id.""" return IMPL.flavor_access_get_by_flavor_id(context, flavor_id) def flavor_access_add(context, flavor_id, project_id): """Add flavor access for project.""" return IMPL.flavor_access_add(context, flavor_id, project_id) def flavor_access_remove(context, flavor_id, project_id): """Remove flavor access for project.""" return IMPL.flavor_access_remove(context, flavor_id, project_id) def flavor_extra_specs_get(context, flavor_id): """Get all extra specs for an instance type.""" return IMPL.flavor_extra_specs_get(context, flavor_id) def flavor_extra_specs_get_item(context, flavor_id, key): """Get extra specs by key and flavor_id.""" return IMPL.flavor_extra_specs_get_item(context, flavor_id, key) def flavor_extra_specs_delete(context, flavor_id, key): """Delete the given extra specs item.""" IMPL.flavor_extra_specs_delete(context, flavor_id, key) def flavor_extra_specs_update_or_create(context, flavor_id, extra_specs): """Create or update instance type extra specs. This adds or modifies the key/value pairs specified in the extra specs dict argument """ IMPL.flavor_extra_specs_update_or_create(context, flavor_id, extra_specs) #################### def pci_device_get_by_addr(context, node_id, dev_addr): """Get PCI device by address.""" return IMPL.pci_device_get_by_addr(context, node_id, dev_addr) def pci_device_get_by_id(context, id): """Get PCI device by id.""" return IMPL.pci_device_get_by_id(context, id) def pci_device_get_all_by_node(context, node_id): """Get all PCI devices for one host.""" return IMPL.pci_device_get_all_by_node(context, node_id) def pci_device_get_all_by_instance_uuid(context, instance_uuid): """Get PCI devices allocated to instance.""" return IMPL.pci_device_get_all_by_instance_uuid(context, instance_uuid) def pci_device_destroy(context, node_id, address): """Delete a PCI device record.""" return IMPL.pci_device_destroy(context, node_id, address) def pci_device_update(context, node_id, address, value): """Update a pci device.""" return IMPL.pci_device_update(context, node_id, address, value) ################### def cell_create(context, values): """Create a new child Cell entry.""" return IMPL.cell_create(context, values) def cell_update(context, cell_name, values): """Update a child Cell entry.""" return IMPL.cell_update(context, cell_name, values) def cell_delete(context, cell_name): """Delete a child Cell.""" return IMPL.cell_delete(context, cell_name) def cell_get(context, cell_name): """Get a specific child Cell.""" return IMPL.cell_get(context, cell_name) def cell_get_all(context): """Get all child Cells.""" return IMPL.cell_get_all(context) #################### def instance_metadata_get(context, instance_uuid): """Get all metadata for an instance.""" return IMPL.instance_metadata_get(context, instance_uuid) def instance_metadata_delete(context, instance_uuid, key): """Delete the given metadata item.""" IMPL.instance_metadata_delete(context, instance_uuid, key) def instance_metadata_update(context, instance_uuid, metadata, delete): """Update metadata if it exists, otherwise create it.""" return IMPL.instance_metadata_update(context, instance_uuid, metadata, delete) #################### def instance_system_metadata_get(context, instance_uuid): """Get all system metadata for an instance.""" return IMPL.instance_system_metadata_get(context, instance_uuid) def instance_system_metadata_update(context, instance_uuid, metadata, delete): """Update metadata if it exists, otherwise create it.""" IMPL.instance_system_metadata_update( context, instance_uuid, metadata, delete) #################### def agent_build_create(context, values): """Create a new agent build entry.""" return IMPL.agent_build_create(context, values) def agent_build_get_by_triple(context, hypervisor, os, architecture): """Get agent build by hypervisor/OS/architecture triple.""" return IMPL.agent_build_get_by_triple(context, hypervisor, os, architecture) def agent_build_get_all(context, hypervisor=None): """Get all agent builds.""" return IMPL.agent_build_get_all(context, hypervisor) def agent_build_destroy(context, agent_update_id): """Destroy agent build entry.""" IMPL.agent_build_destroy(context, agent_update_id) def agent_build_update(context, agent_build_id, values): """Update agent build entry.""" IMPL.agent_build_update(context, agent_build_id, values) #################### def bw_usage_get(context, uuid, start_period, mac, use_slave=False): """Return bw usage for instance and mac in a given audit period.""" return IMPL.bw_usage_get(context, uuid, start_period, mac) def bw_usage_get_by_uuids(context, uuids, start_period): """Return bw usages for instance(s) in a given audit period.""" return IMPL.bw_usage_get_by_uuids(context, uuids, start_period) def bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=None, update_cells=True): """Update cached bandwidth usage for an instance's network based on mac address. Creates new record if needed. """ rv = IMPL.bw_usage_update(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed=last_refreshed) if update_cells: try: cells_rpcapi.CellsAPI().bw_usage_update_at_top(context, uuid, mac, start_period, bw_in, bw_out, last_ctr_in, last_ctr_out, last_refreshed) except Exception: LOG.exception(_("Failed to notify cells of bw_usage update")) return rv ################### def vol_get_usage_by_time(context, begin): """Return volumes usage that have been updated after a specified time.""" return IMPL.vol_get_usage_by_time(context, begin) def vol_usage_update(context, id, rd_req, rd_bytes, wr_req, wr_bytes, instance_id, project_id, user_id, availability_zone, update_totals=False): """Update cached volume usage for a volume Creates new record if needed. """ return IMPL.vol_usage_update(context, id, rd_req, rd_bytes, wr_req, wr_bytes, instance_id, project_id, user_id, availability_zone, update_totals=update_totals) ################### def s3_image_get(context, image_id): """Find local s3 image represented by the provided id.""" return IMPL.s3_image_get(context, image_id) def s3_image_get_by_uuid(context, image_uuid): """Find local s3 image represented by the provided uuid.""" return IMPL.s3_image_get_by_uuid(context, image_uuid) def s3_image_create(context, image_uuid): """Create local s3 image represented by provided uuid.""" return IMPL.s3_image_create(context, image_uuid) #################### def aggregate_create(context, values, metadata=None): """Create a new aggregate with metadata.""" return IMPL.aggregate_create(context, values, metadata) def aggregate_get(context, aggregate_id): """Get a specific aggregate by id.""" return IMPL.aggregate_get(context, aggregate_id) def aggregate_get_by_host(context, host, key=None): """Get a list of aggregates that host belongs to.""" return IMPL.aggregate_get_by_host(context, host, key) def aggregate_metadata_get_by_host(context, host, key=None): """Get metadata for all aggregates that host belongs to. Returns a dictionary where each value is a set, this is to cover the case where there two aggregates have different values for the same key. Optional key filter """ return IMPL.aggregate_metadata_get_by_host(context, host, key) def aggregate_metadata_get_by_metadata_key(context, aggregate_id, key): """Get metadata for an aggregate by metadata key.""" return IMPL.aggregate_metadata_get_by_metadata_key(context, aggregate_id, key) def aggregate_host_get_by_metadata_key(context, key): """Get hosts with a specific metadata key metadata for all aggregates. Returns a dictionary where each key is a hostname and each value is a set of the key values return value: {machine: set( az1, az2 )} """ return IMPL.aggregate_host_get_by_metadata_key(context, key) def aggregate_update(context, aggregate_id, values): """Update the attributes of an aggregates. If values contains a metadata key, it updates the aggregate metadata too. """ return IMPL.aggregate_update(context, aggregate_id, values) def aggregate_delete(context, aggregate_id): """Delete an aggregate.""" return IMPL.aggregate_delete(context, aggregate_id) def aggregate_get_all(context): """Get all aggregates.""" return IMPL.aggregate_get_all(context) def aggregate_metadata_add(context, aggregate_id, metadata, set_delete=False): """Add/update metadata. If set_delete=True, it adds only.""" IMPL.aggregate_metadata_add(context, aggregate_id, metadata, set_delete) def aggregate_metadata_get(context, aggregate_id): """Get metadata for the specified aggregate.""" return IMPL.aggregate_metadata_get(context, aggregate_id) def aggregate_metadata_delete(context, aggregate_id, key): """Delete the given metadata key.""" IMPL.aggregate_metadata_delete(context, aggregate_id, key) def aggregate_host_add(context, aggregate_id, host): """Add host to the aggregate.""" IMPL.aggregate_host_add(context, aggregate_id, host) def aggregate_host_get_all(context, aggregate_id): """Get hosts for the specified aggregate.""" return IMPL.aggregate_host_get_all(context, aggregate_id) def aggregate_host_delete(context, aggregate_id, host): """Delete the given host from the aggregate.""" IMPL.aggregate_host_delete(context, aggregate_id, host) #################### def instance_fault_create(context, values): """Create a new Instance Fault.""" return IMPL.instance_fault_create(context, values) def instance_fault_get_by_instance_uuids(context, instance_uuids): """Get all instance faults for the provided instance_uuids.""" return IMPL.instance_fault_get_by_instance_uuids(context, instance_uuids) #################### def action_start(context, values): """Start an action for an instance.""" return IMPL.action_start(context, values) def action_finish(context, values): """Finish an action for an instance.""" return IMPL.action_finish(context, values) def actions_get(context, uuid): """Get all instance actions for the provided instance.""" return IMPL.actions_get(context, uuid) def action_get_by_request_id(context, uuid, request_id): """Get the action by request_id and given instance.""" return IMPL.action_get_by_request_id(context, uuid, request_id) def action_event_start(context, values): """Start an event on an instance action.""" return IMPL.action_event_start(context, values) def action_event_finish(context, values): """Finish an event on an instance action.""" return IMPL.action_event_finish(context, values) def action_events_get(context, action_id): """Get the events by action id.""" return IMPL.action_events_get(context, action_id) def action_event_get_by_id(context, action_id, event_id): return IMPL.action_event_get_by_id(context, action_id, event_id) #################### def get_ec2_instance_id_by_uuid(context, instance_id): """Get ec2 id through uuid from instance_id_mappings table.""" return IMPL.get_ec2_instance_id_by_uuid(context, instance_id) def get_instance_uuid_by_ec2_id(context, ec2_id): """Get uuid through ec2 id from instance_id_mappings table.""" return IMPL.get_instance_uuid_by_ec2_id(context, ec2_id) def ec2_instance_create(context, instance_uuid, id=None): """Create the ec2 id to instance uuid mapping on demand.""" return IMPL.ec2_instance_create(context, instance_uuid, id) def ec2_instance_get_by_uuid(context, instance_uuid): return IMPL.ec2_instance_get_by_uuid(context, instance_uuid) def ec2_instance_get_by_id(context, instance_id): return IMPL.ec2_instance_get_by_id(context, instance_id) #################### def task_log_end_task(context, task_name, period_beginning, period_ending, host, errors, message=None): """Mark a task as complete for a given host/time period.""" return IMPL.task_log_end_task(context, task_name, period_beginning, period_ending, host, errors, message) def task_log_begin_task(context, task_name, period_beginning, period_ending, host, task_items=None, message=None): """Mark a task as started for a given host/time period.""" return IMPL.task_log_begin_task(context, task_name, period_beginning, period_ending, host, task_items, message) def task_log_get_all(context, task_name, period_beginning, period_ending, host=None, state=None): return IMPL.task_log_get_all(context, task_name, period_beginning, period_ending, host, state) def task_log_get(context, task_name, period_beginning, period_ending, host, state=None): return IMPL.task_log_get(context, task_name, period_beginning, period_ending, host, state) #################### def archive_deleted_rows(context, max_rows=None): """Move up to max_rows rows from production tables to corresponding shadow tables. :returns: number of rows archived. """ return IMPL.archive_deleted_rows(context, max_rows=max_rows) def archive_deleted_rows_for_table(context, tablename, max_rows=None): """Move up to max_rows rows from tablename to corresponding shadow table. :returns: number of rows archived. """ return IMPL.archive_deleted_rows_for_table(context, tablename, max_rows=max_rows)
apache-2.0
KiviMao/kivi
Script/Show-Comments-story/Get-All-User.py
1268
#!/usr/bin/python3 import MySQLdb import os import re db = MySQLdb.connect("etos39.cn.ao.ericsson.se","automation","automation","gerrit_data_new") # db = MySQLdb.connect("localhost","root","root","work" ) cursor = db.cursor() cursor.execute('SELECT reviewer_username FROM comments GROUP BY reviewer_username') usersList = cursor.fetchall() UM = {} for users in usersList: for user in users: if user != None: outPut = os.popen('/usr/bin/ldapsearch -x -LLL -D "uid=COVESEOS,ou=Users,ou=Internal,o=ericsson" -w 1qaz\@WSX -b "uid='+user+',ou=Users,ou=Internal,o=ericsson" -h ecd.ericsson.se -p 389|grep eriOperationalManager:|awk \'{print $2}\'','r') if outPut != None: try: param = [] param=(str(user),str(outPut.read())) rule=re.compile(r'[^a-zA-z]') username = rule.sub('',str(user)) managername = rule.sub('',param[1]) print(username) cursor.execute("""INSERT INTO person(username,manager)VALUES(%s,%s)""",(username,managername)) db.commit() except Exception as e: print e db.rollback()
apache-2.0
WarlockD/arm-cortex-v7-unix
f9_os/src/xx6/main.c
4156
// BSP support routine #define __KERNEL__ #include "types.h" #include "defs.h" #include "param.h" #include "arm.h" #include "proc.h" #include "mpu.h" #include "buf.h" #include "fs.h" #include "file.h" #include <assert.h> #include <string.h> #include <stm32746g_discovery.h> #include "sysfile.h" void trace_printf(const char*,...); struct cpu cpus[NCPU]; struct cpu *cpu; #define MB (1024*1024) uint8_t temp_kernel[1024*64]; static void mkfs_balloc(struct superblock* sb, uint32_t used) { trace_printf("balloc: first %d blocks have been allocated\n", used); assert(used < BSIZE); uint32_t bn = sb->ninodes / IPB + 3; struct buf * bp = bread(0,bn); uint8_t* buf = (uint8_t*)bp->data; for(int i = 0; i < used; i++) { buf[i/8] = buf[i/8] | (0x1 << (i%8)); } trace_printf("balloc: write bitmap block at sector %lu\n", sb->ninodes/IPB + 3); bwrite(bp); brelse(bp); } static uint32_t i2b(uint32_t inum){ return (inum / IPB) + 2; } struct inode* iget (uint32_t dev, uint32_t inum); void ideinit(); void write_root_sb(int dev) { //ideinit(); struct buf *bp; struct superblock sb; struct inode *ip; sb.size = 1024; sb.nblocks = 995; // so whole disk is size sectors sb.ninodes = 200; sb.nlog = LOGSIZE; uint32_t bitblocks = sb.size/(BSIZE*8) + 1; uint32_t usedblocks = sb.ninodes / IPB + 3 + bitblocks; uint32_t freeblock = usedblocks; // format and make file system trace_printf("used %d (bit %d ninode %lu) free %u total %d\n", usedblocks, bitblocks, sb.ninodes/IPB + 1, freeblock, sb.nblocks+usedblocks); bp = bread(dev, 1); memmove(bp->data, &sb, sizeof(sb)); bwrite(bp); brelse(bp); mkfs_balloc(&sb,usedblocks); initlog(); // init the log here so the standard os stuff works begin_trans(); trace_printf("Staring root dir creationg\r\n"); ip= ialloc (ROOTDEV, _IFDIR); assert(ip->inum == ROOTINO); ilock(ip); ip->dev = ROOTDEV; ip->nlink = 2; iupdate(ip); trace_printf("root inode updated creationg\r\n"); // No ip->nlink++ for ".": avoid cyclic ref count. assert(dirlink(ip, ".", ip->inum)==0); // panic("create dots"); trace_printf("dirlink .\r\n"); //iupdate(ip); // force an update? assert(dirlink(ip, "..", ip->inum)==0); // panic("create dots"); trace_printf("dirlink ..\r\n"); iunlockput(ip); trace_printf("iunlockput ..\r\n"); commit_trans(); struct proc _p; proc = &_p; proc->cwd = namei("/"); SYSFILE_FUNC(mkdir)("/dev"); SYSFILE_FUNC(mknod)("/dev/console", 0,0); SYSFILE_FUNC(mknod)("/dev/mem0", 0,0); iput(proc->cwd); proc = NULL; } void kmain (void) { // uint32_t vectbl; cpu = &cpus[0]; // uart_init (P2V(UART0)); // interrrupt vector table is in the middle of first 1MB. We use the left // over for page tables // vectbl = P2V_WO (VEC_TBL & PDE_MASK); // init_vmm (); // kpt_freerange (align_up(&end, PT_SZ), vectbl); // kpt_freerange (vectbl + PT_SZ, P2V_WO(INIT_KERNMAP)); // paging_init (INIT_KERNMAP, PHYSTOP); kmem_init (); kmem_init2(temp_kernel, temp_kernel + sizeof(temp_kernel)); //extern char end __asm("end"); //char *prev_heap_end; //assert(cpu); temp_kernel if (cpu->user_heap == 0) { // userstack starts 4096 after the kernel stack cpu->user_heap = temp_kernel; cpu->user_stack = (char*)ALIGN(__get_MSP(),4096)-4096; #if 0 __set_PSP(ALIGN(__get_MSP(),4096)-4096); cpu->user_stack = (char*)__get_PSP(); cpu->user_heap = ALIGNP(&end,sizeof(uint32_t)); #endif } // trap_init (); // vector table and stacks for models // pic_init (P2V(VIC_BASE)); // interrupt controller // uart_enable_rx (); // interrupt for uart consoleinit (); // console pinit (); // process (locks) binit (); // buffer cache fileinit (); // file table iinit (); // inode cache timer_init (HZ); // the timer (ticker) // create the root dirrectory write_root_sb(0); // creates an empty root directory sti (); trace_printf("Ok, starting user init!\r\n"); // hard set it so we can test the file system ugh proc=userinit(); // first user process scheduler(); // start running processes }
apache-2.0
studiodev/archives
2005 - PortiX-Team (CMS)/pages/matchs.php
5562
<?php switch (@$_GET['action']) { default: $query = "SELECT * FROM ix_matchs ORDER BY id DESC"; $sql = mysql_query($query); $texte='<br><table class="liste_table" cellpadding=0 cellspacing=2 align="center"> <tr> <td class="liste_titre" width=20%>Date</td> <td class="liste_titre" width=25%>Adversaire</td> <td class="liste_titre" width=15%>Type</td> <td class="liste_titre" width=20%>Score</td> <td class="liste_titre" width=10%>Détail</td> <td class="liste_titre" width=10%>Démos</td> </tr> '; while($data = mysql_fetch_array($sql)) { if ($data['score1']<$data['score2']) { $color="#FFC8C8"; $colortxt="#E71B1B"; @$perdu++; } if ($data['score1']>$data['score2']) { $color="#D0F8C8"; $colortxt="#52C174"; @$gagne++; } if ($data['score1']==$data['score2']) { $color="#C8D8FF"; $colortxt="#3A37CE"; @$egalite++; } if (!empty($data['site_adv'])) { $adversaire="<a href=\"".$data['site_adv']."\" target=\"_blank\">".$data['adversaire']."</a>"; } else { $adversaire=$data['adversaire']; } if (!empty($data['hltv'])) { $demo='<a href="'.$data['hltv'].'" target="_blank"><img src="images/video.png" border=0 style="border:1px solid #FFFFFF;" OnMouseOver="this.style.border=\'1px outset #F7A118\'" OnMouseOut="this.style.border=\'1px solid #FFFFFF\'"></a>'; } else if (!empty($data['screen'])) { $demo='<a href="'.$data['screen'].'" target="_blank"><img src="images/screen.png" border=0 style="border:1px solid #FFFFFF;" OnMouseOver="this.style.border=\'1px outset #F7A118\'" OnMouseOut="this.style.border=\'1px solid #FFFFFF\'"></a>'; } else $demo="-"; $texte.=" <tr> <td class='liste_txt'>".inverser_date($data['date'])."</td> <td class='liste_txt'>$adversaire</td> <td class='liste_txt'>".$data['type']."</td> <td class='liste_txt' bgcolor='$color'><font color='$colortxt'><b>".$data['score1']."/".$data['score2']."</b></font></td> <td class='liste_txt'><a href=\"?page=matchs&action=detail&id=".$data['id']."\"><img src='images/rapport.png' border=0 style=\"border:1px solid #FFFFFF;\" OnMouseOver=\"this.style.border='1px outset #108AFB'\" OnMouseOut=\"this.style.border='1px solid #FFFFFF'\"></a></td> <td class='liste_txt'>$demo</td> </tr>"; } $texte.="</table><p align=\"center\"><img src=\"images/carre_vert.jpg\" alt=\"\" name=\"carre_rouge\" width=\"10\" height=\"10\" id=\"carre_rouge\" /> Gagné - <img src=\"images/carre_rouge.jpg\" alt=\"\" name=\"carre_rouge\" width=\"10\" height=\"10\" id=\"carre_rouge\" /> Perdu - <img src=\"images/carre_bleu.jpg\" alt=\"\" name=\"carre_rouge\" width=\"10\" height=\"10\" id=\"carre_rouge\" /> Egalité"; $texte.="<br><br><br><b>$gagne</b> matchs gagnés, <b>$perdu</b> matchs perdus et <b>$egalite</b> égalités.<br></p>"; $afficher->AddSession($handle, "contenu"); $afficher->setVar($handle, "contenu.module_titre", "Liste des matchs"); $afficher->setVar($handle, "contenu.module_texte", $texte ); $afficher->CloseSession($handle, "contenu"); break; case "detail": $query = "SELECT * FROM ix_matchs WHERE id=".$_GET['id']; $sql = mysql_query($query); $data=mysql_fetch_object($sql); (file_exists("images/maps/" . $data->map1 . ".jpg")) ? $urlimg1="images/maps/" . $data->map1 . ".jpg" : $urlimg1="images/maps/none.jpg"; (file_exists("images/maps/" . $data->map2 . ".jpg")) ? $urlimg2="images/maps/" . $data->map2 . ".jpg" : $urlimg2="images/maps/none.jpg"; if (isset($data->map1)) { $imgmap1='<img src="'.$urlimg1.'" style="border:1px solid #000000">'; } if (isset($data->map2)) { $imgmap2='<img src="'.$urlimg2.'" style="border:1px solid #000000">'; } $maps='<table width="322" align="center" cellpadding="0" cellspacing="0" > <tr bgcolor="#000000"> <td><div align="center"><font color="#FFFFFF">Map 1 : <b>'.$data->map1.'</b></font></div></td> <td><div align="center"><font color="#FFFFFF">Map 2 : <b>'.$data->map2.'</b></font></div></td> </tr> <tr> <td>'.@$imgmap1.'</td> <td>'.@$imgmap2.'</td> </tr> </table>'; $texte='<p align="center"><br /><span class="txt2" style="font-size:13px; font-weight:bold"> D&eacute;tail du Match contre les '.$data->adversaire.'</SPAN></p> <p>'.$maps.'<br><br> <span class="txt2">Date</span> : '.inverser_date($data->date).@$case.'<br /> <span class="txt2">Type</span> : '.$data->type.'<br /> <span class="txt2">Line Up</span> : '.$data->lineup.'<br /> <span class="txt2">Score</span> : <b>'.$data->score1.'</b> / '.$data->score2.'</p> <p><span class="txt2">Rapport : </span><br /> '.$data->rapport.'<br /> <br /> <span class="txt2"> Lien D&eacute;mo </span>: <a href="'.$data->hltv.'" target="_blank">'.$data->hltv.'</a><br /> <span class="txt2">Lien Screen </span>: <a href="'.$data->screen.'" target="_blank">'.$data->screen.'</a> </p> <p align="center"><br>- Post&eacute; un commentaire - ( a venir ! )<br> </p>'; $afficher->AddSession($handle, "contenu"); $afficher->setVar($handle, "contenu.module_titre", "Détail d'un match"); $afficher->setVar($handle, "contenu.module_texte", $texte ); $afficher->CloseSession($handle, "contenu"); } ?>
apache-2.0
nagyistoce/TinCan.NET
TinCan/RemoteLRS.cs
24709
/* Copyright 2014 Rustici Software 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. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Web; using Newtonsoft.Json.Linq; using TinCan.Documents; using TinCan.LRSResponses; namespace TinCan { public class RemoteLRS : ILRS { public Uri endpoint { get; set; } public TCAPIVersion version { get; set; } public String auth { get; set; } public Dictionary<String, String> extended { get; set; } public void SetAuth(String username, String password) { auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password)); } public RemoteLRS() { } public RemoteLRS(Uri endpoint, TCAPIVersion version, String username, String password) { this.endpoint = endpoint; this.version = version; this.SetAuth(username, password); } public RemoteLRS(String endpoint, TCAPIVersion version, String username, String password) : this(new Uri(endpoint), version, username, password) { } public RemoteLRS(String endpoint, String username, String password) : this(endpoint, TCAPIVersion.latest(), username, password) { } private class MyHTTPRequest { public String method { get; set; } public String resource { get; set; } public Dictionary<String, String> queryParams { get; set; } public Dictionary<String, String> headers { get; set; } public String contentType { get; set; } public byte[] content { get; set; } } private class MyHTTPResponse { public HttpStatusCode status { get; set; } public String contentType { get; set; } public byte[] content { get; set; } public DateTime lastModified { get; set; } public String etag { get; set; } public Exception ex { get; set; } public MyHTTPResponse() { } public MyHTTPResponse(HttpWebResponse webResp) { status = webResp.StatusCode; contentType = webResp.ContentType; etag = webResp.Headers.Get("Etag"); lastModified = webResp.LastModified; using (var stream = webResp.GetResponseStream()) { content = ReadFully(stream, (int)webResp.ContentLength); } } } private MyHTTPResponse MakeSyncRequest(MyHTTPRequest req) { String url; if (req.resource.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)) { url = req.resource; } else { url = endpoint.ToString(); if (! url.EndsWith("/") && ! req.resource.StartsWith("/")) { url += "/"; } url += req.resource; } if (req.queryParams != null) { String qs = ""; foreach (KeyValuePair<String, String> entry in req.queryParams) { if (qs != "") { qs += "&"; } qs += HttpUtility.UrlEncode(entry.Key) + "=" + HttpUtility.UrlEncode(entry.Value); } if (qs != "") { url += "?" + qs; } } // TODO: handle special properties we recognize, such as content type, modified since, etc. var webReq = (HttpWebRequest)WebRequest.Create(url); webReq.Method = req.method; webReq.Headers.Add("X-Experience-API-Version", version.ToString()); if (auth != null) { webReq.Headers.Add("Authorization", auth); } if (req.headers != null) { foreach (KeyValuePair<String, String> entry in req.headers) { webReq.Headers.Add(entry.Key, entry.Value); } } if (req.contentType != null) { webReq.ContentType = req.contentType; } else { webReq.ContentType = "application/octet-stream"; } if (req.content != null) { webReq.ContentLength = req.content.Length; using (var stream = webReq.GetRequestStream()) { stream.Write(req.content, 0, req.content.Length); } } MyHTTPResponse resp; try { using (var webResp = (HttpWebResponse)webReq.GetResponse()) { resp = new MyHTTPResponse(webResp); } } catch (WebException ex) { if (ex.Response != null) { using (var webResp = (HttpWebResponse)ex.Response) { resp = new MyHTTPResponse(webResp); } } else { resp = new MyHTTPResponse(); resp.content = Encoding.UTF8.GetBytes("Web exception without '.Response'"); } resp.ex = ex; } return resp; } /// <summary> /// See http://www.yoda.arachsys.com/csharp/readbinary.html no license found /// /// Reads data from a stream until the end is reached. The /// data is returned as a byte array. An IOException is /// thrown if any of the underlying IO calls fail. /// </summary> /// <param name="stream">The stream to read data from</param> /// <param name="initialLength">The initial buffer length</param> private static byte[] ReadFully(Stream stream, int initialLength) { // If we've been passed an unhelpful initial length, just // use 32K. if (initialLength < 1) { initialLength = 32768; } byte[] buffer = new byte[initialLength]; int read = 0; int chunk; while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) { read += chunk; // If we've reached the end of our buffer, check to see if there's // any more information if (read == buffer.Length) { int nextByte = stream.ReadByte(); // End of stream? If so, we're done if (nextByte == -1) { return buffer; } // Nope. Resize the buffer, put in the byte we've just // read, and continue byte[] newBuffer = new byte[buffer.Length * 2]; Array.Copy(buffer, newBuffer, buffer.Length); newBuffer[read] = (byte)nextByte; buffer = newBuffer; read++; } } // Buffer is now too big. Shrink it. byte[] ret = new byte[read]; Array.Copy(buffer, ret, read); return ret; } private MyHTTPResponse GetDocument(String resource, Dictionary<String, String> queryParams, Document document) { var req = new MyHTTPRequest(); req.method = "GET"; req.resource = resource; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status == HttpStatusCode.OK) { document.content = res.content; document.contentType = res.contentType; document.timestamp = res.lastModified; document.etag = res.etag; } return res; } private ProfileKeysLRSResponse GetProfileKeys(String resource, Dictionary<String, String> queryParams) { var r = new ProfileKeysLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = resource; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; var keys = JArray.Parse(Encoding.UTF8.GetString(res.content)); if (keys.Count > 0) { r.content = new List<String>(); foreach (JToken key in keys) { r.content.Add((String)key); } } return r; } private LRSResponse SaveDocument(String resource, Dictionary<String, String> queryParams, Document document) { var r = new LRSResponse(); var req = new MyHTTPRequest(); req.method = "PUT"; req.resource = resource; req.queryParams = queryParams; req.contentType = document.contentType; req.content = document.content; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.NoContent) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; return r; } private LRSResponse DeleteDocument(String resource, Dictionary<String, String> queryParams) { var r = new LRSResponse(); var req = new MyHTTPRequest(); req.method = "DELETE"; req.resource = resource; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.NoContent) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; return r; } private StatementLRSResponse GetStatement(Dictionary<String, String> queryParams) { var r = new StatementLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = "statements"; req.queryParams = queryParams; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new Statement(new Json.StringOfJSON(Encoding.UTF8.GetString(res.content))); return r; } public AboutLRSResponse About() { var r = new AboutLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = "about"; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new About(Encoding.UTF8.GetString(res.content)); return r; } public StatementLRSResponse SaveStatement(Statement statement) { var r = new StatementLRSResponse(); var req = new MyHTTPRequest(); req.queryParams = new Dictionary<String, String>(); req.resource = "statements"; if (statement.id == null) { req.method = "POST"; } else { req.method = "PUT"; req.queryParams.Add("statementId", statement.id.ToString()); } req.contentType = "application/json"; req.content = Encoding.UTF8.GetBytes(statement.ToJSON(version)); var res = MakeSyncRequest(req); if (statement.id == null) { if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } var ids = JArray.Parse(Encoding.UTF8.GetString(res.content)); statement.id = new Guid((String)ids[0]); } else { if (res.status != HttpStatusCode.NoContent) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } } r.success = true; r.content = statement; return r; } public StatementsResultLRSResponse SaveStatements(List<Statement> statements) { var r = new StatementsResultLRSResponse(); var req = new MyHTTPRequest(); req.resource = "statements"; req.method = "POST"; req.contentType = "application/json"; var jarray = new JArray(); foreach (Statement st in statements) { jarray.Add(st.ToJObject(version)); } req.content = Encoding.UTF8.GetBytes(jarray.ToString()); var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } var ids = JArray.Parse(Encoding.UTF8.GetString(res.content)); for (int i = 0; i < ids.Count; i++) { statements[i].id = new Guid((String)ids[i]); } r.success = true; r.content = new StatementsResult(statements); return r; } public StatementLRSResponse RetrieveStatement(Guid id) { var queryParams = new Dictionary<String, String>(); queryParams.Add("statementId", id.ToString()); return GetStatement(queryParams); } public StatementLRSResponse RetrieveVoidedStatement(Guid id) { var queryParams = new Dictionary<String, String>(); queryParams.Add("voidedStatementId", id.ToString()); return GetStatement(queryParams); } public StatementsResultLRSResponse QueryStatements(StatementsQuery query) { var r = new StatementsResultLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = "statements"; req.queryParams = query.ToParameterMap(version); var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new StatementsResult(new Json.StringOfJSON(Encoding.UTF8.GetString(res.content))); return r; } public StatementsResultLRSResponse MoreStatements(StatementsResult result) { var r = new StatementsResultLRSResponse(); var req = new MyHTTPRequest(); req.method = "GET"; req.resource = endpoint.GetLeftPart(UriPartial.Authority); if (! req.resource.EndsWith("/")) { req.resource += "/"; } req.resource += result.more; var res = MakeSyncRequest(req); if (res.status != HttpStatusCode.OK) { r.success = false; r.httpException = res.ex; r.SetErrMsgFromBytes(res.content); return r; } r.success = true; r.content = new StatementsResult(new Json.StringOfJSON(Encoding.UTF8.GetString(res.content))); return r; } // TODO: since param public ProfileKeysLRSResponse RetrieveStateIds(Activity activity, Agent agent, Nullable<Guid> registration = null) { var queryParams = new Dictionary<String, String>(); queryParams.Add("activityId", activity.id.ToString()); queryParams.Add("agent", agent.ToJSON(version)); if (registration != null) { queryParams.Add("registration", registration.ToString()); } return GetProfileKeys("activities/state", queryParams); } public StateLRSResponse RetrieveState(String id, Activity activity, Agent agent, Nullable<Guid> registration = null) { var r = new StateLRSResponse(); var queryParams = new Dictionary<String, String>(); queryParams.Add("stateId", id); queryParams.Add("activityId", activity.id.ToString()); queryParams.Add("agent", agent.ToJSON(version)); var state = new StateDocument(); state.id = id; state.activity = activity; state.agent = agent; if (registration != null) { queryParams.Add("registration", registration.ToString()); state.registration = registration; } var resp = GetDocument("activities/state", queryParams, state); if (resp.status != HttpStatusCode.OK && resp.status != HttpStatusCode.NotFound) { r.success = false; r.httpException = resp.ex; r.SetErrMsgFromBytes(resp.content); return r; } r.success = true; return r; } public LRSResponse SaveState(StateDocument state) { var queryParams = new Dictionary<String, String>(); queryParams.Add("stateId", state.id); queryParams.Add("activityId", state.activity.id.ToString()); queryParams.Add("agent", state.agent.ToJSON(version)); if (state.registration != null) { queryParams.Add("registration", state.registration.ToString()); } return SaveDocument("activities/state", queryParams, state); } public LRSResponse DeleteState(StateDocument state) { var queryParams = new Dictionary<String, String>(); queryParams.Add("stateId", state.id); queryParams.Add("activityId", state.activity.id.ToString()); queryParams.Add("agent", state.agent.ToJSON(version)); if (state.registration != null) { queryParams.Add("registration", state.registration.ToString()); } return DeleteDocument("activities/state", queryParams); } public LRSResponse ClearState(Activity activity, Agent agent, Nullable<Guid> registration = null) { var queryParams = new Dictionary<String, String>(); queryParams.Add("activityId", activity.id.ToString()); queryParams.Add("agent", agent.ToJSON(version)); if (registration != null) { queryParams.Add("registration", registration.ToString()); } return DeleteDocument("activities/state", queryParams); } // TODO: since param public ProfileKeysLRSResponse RetrieveActivityProfileIds(Activity activity) { var queryParams = new Dictionary<String, String>(); queryParams.Add("activityId", activity.id.ToString()); return GetProfileKeys("activities/profile", queryParams); } public ActivityProfileLRSResponse RetrieveActivityProfile(String id, Activity activity) { var r = new ActivityProfileLRSResponse(); var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", id); queryParams.Add("activityId", activity.id.ToString()); var profile = new ActivityProfileDocument(); profile.id = id; profile.activity = activity; var resp = GetDocument("activities/profile", queryParams, profile); if (resp.status != HttpStatusCode.OK && resp.status != HttpStatusCode.NotFound) { r.success = false; r.httpException = resp.ex; r.SetErrMsgFromBytes(resp.content); return r; } r.success = true; return r; } public LRSResponse SaveActivityProfile(ActivityProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("activityId", profile.activity.id.ToString()); return SaveDocument("activities/profile", queryParams, profile); } public LRSResponse DeleteActivityProfile(ActivityProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("activityId", profile.activity.id.ToString()); // TODO: need to pass Etag? return DeleteDocument("activities/profile", queryParams); } // TODO: since param public ProfileKeysLRSResponse RetrieveAgentProfileIds(Agent agent) { var queryParams = new Dictionary<String, String>(); queryParams.Add("agent", agent.ToJSON(version)); return GetProfileKeys("agents/profile", queryParams); } public AgentProfileLRSResponse RetrieveAgentProfile(String id, Agent agent) { var r = new AgentProfileLRSResponse(); var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", id); queryParams.Add("agent", agent.ToJSON(version)); var profile = new AgentProfileDocument(); profile.id = id; profile.agent = agent; var resp = GetDocument("agents/profile", queryParams, profile); if (resp.status != HttpStatusCode.OK && resp.status != HttpStatusCode.NotFound) { r.success = false; r.httpException = resp.ex; r.SetErrMsgFromBytes(resp.content); return r; } r.success = true; return r; } public LRSResponse SaveAgentProfile(AgentProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("agent", profile.agent.ToJSON(version)); return SaveDocument("agents/profile", queryParams, profile); } public LRSResponse DeleteAgentProfile(AgentProfileDocument profile) { var queryParams = new Dictionary<String, String>(); queryParams.Add("profileId", profile.id); queryParams.Add("agent", profile.agent.ToJSON(version)); // TODO: need to pass Etag? return DeleteDocument("agents/profile", queryParams); } } }
apache-2.0
Zebbeni/alien-empire
client/game_board.js
3574
var stage, board, tiles, fleets, scale, sWid, is_dragging; var lastMouse = { x:0, y:0 }; var is_dragging = false; $(document).ready(function() { init_stage(); document.addEventListener('keyup', handleKeyUp, false); document.addEventListener('keydown', handleKeyDown, false); loadLobby(); }); /** * Called from createAll in game.js after all assets are loaded. * Clears old game globals, re-sets defaults. */ var setGlobals = function() { stage.removeChild(board); board = new createjs.Container(); tiles = []; fleetshapes = {}; scale = 0.60; }; var handleKeyUp = function( e ) { switch (e.keyCode) { case 189: // dash zoomBoard(-0.05); break; case 187: // equals (plus sign) zoomBoard(0.05); break; default: break; } }; var handleKeyDown = function( e ) { switch (e.keyCode) { case 37: // left arrow moveBoard(-1, 0); break; case 38: // up arrow moveBoard(0, -1); break; case 39: moveBoard(1, 0); break; case 40: moveBoard(0, 1); break; default: break; } }; /** * Calls init and draw functions for each tile in game board */ var createBoard = function() { if (stage) { initSelection(); updateCanvasSize(); drawAsteroids(); drawTiles(); drawNoFlyZones(); drawBases(); drawAgents(); drawFleets(); drawSprites(); stage.addChild( board ); scale = 0.75; var boardWidth = 7 * sWid * scale; var boardHeight = 7 * sWid * scale; board.x = (window.innerWidth - boardWidth) / 2.0; board.y = (window.innerHeight - boardHeight) / 2.0; board.scaleX = scale; board.scaleY = scale; fadeIn(board, 1000, false, false); } }; var drawAsteroids = function() { var asteroids = clientGame.game.board.asteroids; for ( var a = 0; a < asteroids.length; a++ ) { drawAsteroid( asteroids[a] ); } }; var drawTiles = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { initTile(p); drawTile(p); } }; var drawFleets = function() { initFleets(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateFleets(p); } }; var drawNoFlyZones = function() { var planets = clientGame.game.board.planets; initNoFlyZones(); updateNoFlyZones(); }; var drawBases = function() { var planets = clientGame.game.board.planets; initBases(); for ( var p = 0; p < planets.length; p++ ) { updateBases(p); } }; var drawAgents = function() { initAgents(); var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateAgents(p); } }; /** * Calls function to turn mouse enablement on/off on different * createJS containers based on what action the user is in. */ var updateBoardInteractivity = function() { var planets = clientGame.game.board.planets; for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); } updateFleetsInteractivity(); updateBasesInteractivity(); updateAgentsInteractivity(); }; /** * Calls update functions on each tile to update appearance, interactivity * based on current pending action or game event */ var updateBoard = function() { var planets = clientGame.game.board.planets; // this sets all bases to invisible. Update function will reveal // and draw any that are on planets. updateRemovedBases(); for ( var p = 0; p < planets.length; p++ ) { updateTileInteractivity(p); updateTileImage(p); updateFleets(p); updateBases(p); updateAgents(p); } updateNoFlyZones(); updateRemovedFleets(); updateDeadAgents(); stage.update(); };
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Vigna/Vigna frutescens/ Syn. Vigna keniensis/README.md
178
# Vigna keniensis Harms SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
ptinsley/fling
vendor/google.golang.org/genproto/googleapis/ads/googleads/v1/errors/conversion_action_error.pb.go
8831
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v1/errors/conversion_action_error.proto package errors // import "google.golang.org/genproto/googleapis/ads/googleads/v1/errors" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genproto/googleapis/api/annotations" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Enum describing possible conversion action errors. type ConversionActionErrorEnum_ConversionActionError int32 const ( // Enum unspecified. ConversionActionErrorEnum_UNSPECIFIED ConversionActionErrorEnum_ConversionActionError = 0 // The received error code is not known in this version. ConversionActionErrorEnum_UNKNOWN ConversionActionErrorEnum_ConversionActionError = 1 // The specified conversion action name already exists. ConversionActionErrorEnum_DUPLICATE_NAME ConversionActionErrorEnum_ConversionActionError = 2 // Another conversion action with the specified app id already exists. ConversionActionErrorEnum_DUPLICATE_APP_ID ConversionActionErrorEnum_ConversionActionError = 3 // Android first open action conflicts with Google play codeless download // action tracking the same app. ConversionActionErrorEnum_TWO_CONVERSION_ACTIONS_BIDDING_ON_SAME_APP_DOWNLOAD ConversionActionErrorEnum_ConversionActionError = 4 // Android first open action conflicts with Google play codeless download // action tracking the same app. ConversionActionErrorEnum_BIDDING_ON_SAME_APP_DOWNLOAD_AS_GLOBAL_ACTION ConversionActionErrorEnum_ConversionActionError = 5 // The attribution model cannot be set to DATA_DRIVEN because a data-driven // model has never been generated. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_WAS_NEVER_GENERATED ConversionActionErrorEnum_ConversionActionError = 6 // The attribution model cannot be set to DATA_DRIVEN because the // data-driven model is expired. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_EXPIRED ConversionActionErrorEnum_ConversionActionError = 7 // The attribution model cannot be set to DATA_DRIVEN because the // data-driven model is stale. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_STALE ConversionActionErrorEnum_ConversionActionError = 8 // The attribution model cannot be set to DATA_DRIVEN because the // data-driven model is unavailable or the conversion action was newly // added. ConversionActionErrorEnum_DATA_DRIVEN_MODEL_UNKNOWN ConversionActionErrorEnum_ConversionActionError = 9 ) var ConversionActionErrorEnum_ConversionActionError_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "DUPLICATE_NAME", 3: "DUPLICATE_APP_ID", 4: "TWO_CONVERSION_ACTIONS_BIDDING_ON_SAME_APP_DOWNLOAD", 5: "BIDDING_ON_SAME_APP_DOWNLOAD_AS_GLOBAL_ACTION", 6: "DATA_DRIVEN_MODEL_WAS_NEVER_GENERATED", 7: "DATA_DRIVEN_MODEL_EXPIRED", 8: "DATA_DRIVEN_MODEL_STALE", 9: "DATA_DRIVEN_MODEL_UNKNOWN", } var ConversionActionErrorEnum_ConversionActionError_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "DUPLICATE_NAME": 2, "DUPLICATE_APP_ID": 3, "TWO_CONVERSION_ACTIONS_BIDDING_ON_SAME_APP_DOWNLOAD": 4, "BIDDING_ON_SAME_APP_DOWNLOAD_AS_GLOBAL_ACTION": 5, "DATA_DRIVEN_MODEL_WAS_NEVER_GENERATED": 6, "DATA_DRIVEN_MODEL_EXPIRED": 7, "DATA_DRIVEN_MODEL_STALE": 8, "DATA_DRIVEN_MODEL_UNKNOWN": 9, } func (x ConversionActionErrorEnum_ConversionActionError) String() string { return proto.EnumName(ConversionActionErrorEnum_ConversionActionError_name, int32(x)) } func (ConversionActionErrorEnum_ConversionActionError) EnumDescriptor() ([]byte, []int) { return fileDescriptor_conversion_action_error_6bc78838b2a5587b, []int{0, 0} } // Container for enum describing possible conversion action errors. type ConversionActionErrorEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *ConversionActionErrorEnum) Reset() { *m = ConversionActionErrorEnum{} } func (m *ConversionActionErrorEnum) String() string { return proto.CompactTextString(m) } func (*ConversionActionErrorEnum) ProtoMessage() {} func (*ConversionActionErrorEnum) Descriptor() ([]byte, []int) { return fileDescriptor_conversion_action_error_6bc78838b2a5587b, []int{0} } func (m *ConversionActionErrorEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ConversionActionErrorEnum.Unmarshal(m, b) } func (m *ConversionActionErrorEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ConversionActionErrorEnum.Marshal(b, m, deterministic) } func (dst *ConversionActionErrorEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_ConversionActionErrorEnum.Merge(dst, src) } func (m *ConversionActionErrorEnum) XXX_Size() int { return xxx_messageInfo_ConversionActionErrorEnum.Size(m) } func (m *ConversionActionErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_ConversionActionErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_ConversionActionErrorEnum proto.InternalMessageInfo func init() { proto.RegisterType((*ConversionActionErrorEnum)(nil), "google.ads.googleads.v1.errors.ConversionActionErrorEnum") proto.RegisterEnum("google.ads.googleads.v1.errors.ConversionActionErrorEnum_ConversionActionError", ConversionActionErrorEnum_ConversionActionError_name, ConversionActionErrorEnum_ConversionActionError_value) } func init() { proto.RegisterFile("google/ads/googleads/v1/errors/conversion_action_error.proto", fileDescriptor_conversion_action_error_6bc78838b2a5587b) } var fileDescriptor_conversion_action_error_6bc78838b2a5587b = []byte{ // 443 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x41, 0x8b, 0xd3, 0x40, 0x14, 0xc7, 0x6d, 0x56, 0x77, 0x75, 0x16, 0x74, 0x18, 0x14, 0xd9, 0x55, 0xf7, 0x50, 0xf0, 0xe0, 0xc1, 0x84, 0xb0, 0x07, 0x21, 0x7a, 0x79, 0xcd, 0x8c, 0x61, 0x30, 0x9d, 0x09, 0x49, 0x9a, 0x8a, 0x14, 0x86, 0xd8, 0x94, 0x50, 0xd8, 0xcd, 0x94, 0x4c, 0xed, 0x07, 0xf2, 0xe8, 0x47, 0xf1, 0xe6, 0xd7, 0xf0, 0xe2, 0xc9, 0xbb, 0x24, 0xb3, 0xad, 0x87, 0xed, 0xf6, 0x34, 0x7f, 0xde, 0xfb, 0xff, 0xfe, 0x09, 0xef, 0x3d, 0xf4, 0xa1, 0xd6, 0xba, 0xbe, 0x5a, 0x78, 0x65, 0x65, 0x3c, 0x2b, 0x3b, 0xb5, 0xf1, 0xbd, 0x45, 0xdb, 0xea, 0xd6, 0x78, 0x73, 0xdd, 0x6c, 0x16, 0xad, 0x59, 0xea, 0x46, 0x95, 0xf3, 0x75, 0xf7, 0xf4, 0x0d, 0x77, 0xd5, 0xea, 0xb5, 0x26, 0x17, 0x16, 0x71, 0xcb, 0xca, 0xb8, 0x3b, 0xda, 0xdd, 0xf8, 0xae, 0xa5, 0xcf, 0x5f, 0x6e, 0xd3, 0x57, 0x4b, 0xaf, 0x6c, 0x1a, 0xbd, 0x2e, 0xbb, 0x08, 0x63, 0xe9, 0xe1, 0x1f, 0x07, 0x9d, 0x85, 0xbb, 0x7c, 0xe8, 0xe3, 0x59, 0x07, 0xb2, 0xe6, 0xdb, 0xf5, 0xf0, 0x97, 0x83, 0x9e, 0xed, 0xed, 0x92, 0x27, 0xe8, 0x74, 0x22, 0xb2, 0x84, 0x85, 0xfc, 0x23, 0x67, 0x14, 0xdf, 0x23, 0xa7, 0xe8, 0x64, 0x22, 0x3e, 0x09, 0x39, 0x15, 0x78, 0x40, 0x08, 0x7a, 0x4c, 0x27, 0x49, 0xcc, 0x43, 0xc8, 0x99, 0x12, 0x30, 0x66, 0xd8, 0x21, 0x4f, 0x11, 0xfe, 0x5f, 0x83, 0x24, 0x51, 0x9c, 0xe2, 0x23, 0xf2, 0x0e, 0x5d, 0xe6, 0x53, 0xa9, 0x42, 0x29, 0x0a, 0x96, 0x66, 0x5c, 0x0a, 0x05, 0x61, 0xce, 0xa5, 0xc8, 0xd4, 0x88, 0x53, 0xca, 0x45, 0xa4, 0xa4, 0x50, 0x19, 0x8c, 0x2d, 0x42, 0xe5, 0x54, 0xc4, 0x12, 0x28, 0xbe, 0x4f, 0x7c, 0xf4, 0xf6, 0x90, 0x43, 0x41, 0xa6, 0xa2, 0x58, 0x8e, 0x20, 0xbe, 0x09, 0xc4, 0x0f, 0xc8, 0x1b, 0xf4, 0x9a, 0x42, 0x0e, 0x8a, 0xa6, 0xbc, 0x60, 0x42, 0x8d, 0x25, 0x65, 0xb1, 0x9a, 0x42, 0xa6, 0x04, 0x2b, 0x58, 0xaa, 0x22, 0x26, 0x58, 0x0a, 0x39, 0xa3, 0xf8, 0x98, 0xbc, 0x42, 0x67, 0xb7, 0xad, 0xec, 0x73, 0xc2, 0x53, 0x46, 0xf1, 0x09, 0x79, 0x81, 0x9e, 0xdf, 0x6e, 0x67, 0x39, 0xc4, 0x0c, 0x3f, 0xdc, 0xcf, 0x6e, 0x67, 0xf3, 0x68, 0xf4, 0x77, 0x80, 0x86, 0x73, 0x7d, 0xed, 0x1e, 0x5e, 0xdb, 0xe8, 0x7c, 0xef, 0xdc, 0x93, 0x6e, 0x69, 0xc9, 0xe0, 0x0b, 0xbd, 0xa1, 0x6b, 0x7d, 0x55, 0x36, 0xb5, 0xab, 0xdb, 0xda, 0xab, 0x17, 0x4d, 0xbf, 0xd2, 0xed, 0x09, 0xad, 0x96, 0xe6, 0xae, 0x8b, 0x7a, 0x6f, 0x9f, 0xef, 0xce, 0x51, 0x04, 0xf0, 0xc3, 0xb9, 0x88, 0x6c, 0x18, 0x54, 0xc6, 0xb5, 0xb2, 0x53, 0x85, 0xef, 0xf6, 0x9f, 0x34, 0x3f, 0xb7, 0x86, 0x19, 0x54, 0x66, 0xb6, 0x33, 0xcc, 0x0a, 0x7f, 0x66, 0x0d, 0xbf, 0x9d, 0xa1, 0xad, 0x06, 0x01, 0x54, 0x26, 0x08, 0x76, 0x96, 0x20, 0x28, 0xfc, 0x20, 0xb0, 0xa6, 0xaf, 0xc7, 0xfd, 0xdf, 0x5d, 0xfe, 0x0b, 0x00, 0x00, 0xff, 0xff, 0x0c, 0xe0, 0x92, 0x88, 0xee, 0x02, 0x00, 0x00, }
apache-2.0
mirkosertic/Bytecoder
integrationtest/src/main/java/de/mirkosertic/bytecoder/integrationtest/JBox2DSimulation.java
10500
/* * Copyright 2017 Mirko Sertic * * 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.mirkosertic.bytecoder.integrationtest; import de.mirkosertic.bytecoder.api.Import; import de.mirkosertic.bytecoder.api.web.AnimationFrameCallback; import de.mirkosertic.bytecoder.api.web.CanvasRenderingContext2D; import de.mirkosertic.bytecoder.api.web.MouseEvent; import de.mirkosertic.bytecoder.api.web.Document; import de.mirkosertic.bytecoder.api.web.EventListener; import de.mirkosertic.bytecoder.api.web.HTMLButton; import de.mirkosertic.bytecoder.api.web.HTMLCanvasElement; import de.mirkosertic.bytecoder.api.web.Window; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.collision.shapes.Shape; import org.jbox2d.collision.shapes.ShapeType; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.BodyType; import org.jbox2d.dynamics.Fixture; import org.jbox2d.dynamics.FixtureDef; import org.jbox2d.dynamics.World; import org.jbox2d.dynamics.joints.RevoluteJointDef; public class JBox2DSimulation { public static class Scene { private final World world; private Body axis; private Body reel; private long lastCalculated; private final long startTime; public Scene() { world = new World(new Vec2(0, -9.8f)); initAxis(); initReel(); joinReelToAxis(); initBalls(); lastCalculated = System.currentTimeMillis(); startTime = lastCalculated; } private void initAxis() { final BodyDef axisDef = new BodyDef(); axisDef.type = BodyType.STATIC; axisDef.position = new Vec2(3, 3); axis = world.createBody(axisDef); final CircleShape axisShape = new CircleShape(); axisShape.setRadius(0.02f); axisShape.m_p.set(0, 0); final FixtureDef axisFixture = new FixtureDef(); axisFixture.shape = axisShape; axis.createFixture(axisFixture); } private void initReel() { final BodyDef reelDef = new BodyDef(); reelDef.type = BodyType.DYNAMIC; reelDef.position = new Vec2(3, 3); reel = world.createBody(reelDef); final FixtureDef fixture = new FixtureDef(); fixture.friction = 0.5f; fixture.restitution = 0.4f; fixture.density = 1; final int parts = 30; for (int i = 0; i < parts; ++i) { final PolygonShape shape = new PolygonShape(); final double angle1 = i / (double) parts * 2 * Math.PI; final double x1 = 2.7 * Math.cos(angle1); final double y1 = 2.7 * Math.sin(angle1); final double angle2 = (i + 1) / (double) parts * 2 * Math.PI; final double x2 = 2.7 * Math.cos(angle2); final double y2 = 2.7 * Math.sin(angle2); final double angle = (angle1 + angle2) / 2; final double x = 0.01 * Math.cos(angle); final double y = 0.01 * Math.sin(angle); shape.set(new Vec2[] { new Vec2((float) x1, (float) y1), new Vec2((float) x2, (float) y2), new Vec2((float) (x2 - x), (float) (y2 - y)), new Vec2((float) (x1 - x), (float) (y1 - y)) }, 4); fixture.shape = shape; reel.createFixture(fixture); } } private void initBalls() { final float ballRadius = 0.15f; final BodyDef ballDef = new BodyDef(); ballDef.type = BodyType.DYNAMIC; final FixtureDef fixtureDef = new FixtureDef(); fixtureDef.friction = 0.3f; fixtureDef.restitution = 0.3f; fixtureDef.density = 0.2f; final CircleShape shape = new CircleShape(); shape.m_radius = ballRadius; fixtureDef.shape = shape; for (int i = 0; i < 6; ++i) { for (int j = 0; j < 6; ++j) { final float x = (j + 0.5f) * (ballRadius * 2 + 0.01f); final float y = (i + 0.5f) * (ballRadius * 2 + 0.01f); ballDef.position.x = 3 + x; ballDef.position.y = 3 + y; Body body = world.createBody(ballDef); body.createFixture(fixtureDef); ballDef.position.x = 3 - x; ballDef.position.y = 3 + y; body = world.createBody(ballDef); body.createFixture(fixtureDef); ballDef.position.x = 3 + x; ballDef.position.y = 3 - y; body = world.createBody(ballDef); body.createFixture(fixtureDef); ballDef.position.x = 3 - x; ballDef.position.y = 3 - y; body = world.createBody(ballDef); body.createFixture(fixtureDef); } } } private void joinReelToAxis() { final RevoluteJointDef jointDef = new RevoluteJointDef(); jointDef.bodyA = axis; jointDef.bodyB = reel; world.createJoint(jointDef); } public void calculate() { final long currentTime = System.currentTimeMillis(); int timeToCalculate = (int) (currentTime - lastCalculated); final long relativeTime = currentTime - startTime; while (timeToCalculate > 10) { final int period = (int) ((relativeTime + 5000) / 10000); reel.applyTorque(period % 2 == 0 ? 8f : -8f); world.step(0.01f, 20, 40); lastCalculated += 10; timeToCalculate -= 10; } lastCalculated = System.currentTimeMillis(); } public World getWorld() { return world; } } private static Scene scene; private static CanvasRenderingContext2D renderingContext2D; private static AnimationFrameCallback animationCallback; private static Window window; public static void main(final String[] args) { scene = new Scene(); window = Window.window(); final Document document = window.document(); final HTMLCanvasElement theCanvas = document.getElementById("benchmark-canvas"); renderingContext2D = theCanvas.getContext("2d"); animationCallback = new AnimationFrameCallback() { @Override public void run(final int aElapsedTime) { final long theStart = System.currentTimeMillis(); statsBegin(); scene.calculate(); render(); statsEnd(); final int theDuration = (int) (System.currentTimeMillis() - theStart); logRuntime(theDuration); window.requestAnimationFrame(animationCallback); } }; final HTMLButton button = document.getElementById("button"); button.addEventListener("click", new EventListener<MouseEvent>() { @Override public void run(final MouseEvent aValue) { button.disabled(true); window.requestAnimationFrame(animationCallback); } }); window.fetch("versioninfo.txt").then(response -> { response.text().then(text -> { document.getElementById("versioninfo").innerHTML(text); }); }); } @Import(module = "debug", name = "logRuntime") public static native void logRuntime(int aValue); @Import(module = "stats", name = "begin") public static native void statsBegin(); @Import(module = "stats", name = "end") public static native void statsEnd(); private static void render() { renderingContext2D.setFillStyle("white"); renderingContext2D.setStrokeStyle("black"); renderingContext2D.fillRect(0, 0, 600, 600); renderingContext2D.save(); renderingContext2D.translate(0, 600); renderingContext2D.scale(1, -1); renderingContext2D.scale(100, 100); renderingContext2D.setLineWidth(0.01f); for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) { final Vec2 center = body.getPosition(); renderingContext2D.save(); renderingContext2D.translate(center.x, center.y); renderingContext2D.rotate(body.getAngle()); for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) { final Shape shape = fixture.getShape(); if (shape.getType() == ShapeType.CIRCLE) { final CircleShape circle = (CircleShape) shape; renderingContext2D.beginPath(); renderingContext2D.arc(circle.m_p.x, circle.m_p.y, circle.getRadius(), 0, Math.PI * 2, true); renderingContext2D.closePath(); renderingContext2D.stroke(); } else if (shape.getType() == ShapeType.POLYGON) { final PolygonShape poly = (PolygonShape) shape; final Vec2[] vertices = poly.getVertices(); renderingContext2D.beginPath(); renderingContext2D.moveTo(vertices[0].x, vertices[0].y); for (int i = 1; i < poly.getVertexCount(); ++i) { renderingContext2D.lineTo(vertices[i].x, vertices[i].y); } renderingContext2D.closePath(); renderingContext2D.stroke(); } } renderingContext2D.restore(); } renderingContext2D.restore(); } }
apache-2.0
legionus/origin
pkg/network/node/egressip.go
6103
// +build linux package node import ( "fmt" "net" "sync" "syscall" "github.com/golang/glog" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "github.com/openshift/origin/pkg/network/common" networkinformers "github.com/openshift/origin/pkg/network/generated/informers/internalversion" "github.com/vishvananda/netlink" ) type egressIPWatcher struct { sync.Mutex tracker *common.EgressIPTracker oc *ovsController localIP string masqueradeBit uint32 iptables *NodeIPTables iptablesMark map[string]string vxlanMonitor *egressVXLANMonitor localEgressLink netlink.Link localEgressNet *net.IPNet testModeChan chan string } func newEgressIPWatcher(oc *ovsController, localIP string, masqueradeBit *int32) *egressIPWatcher { eip := &egressIPWatcher{ oc: oc, localIP: localIP, iptablesMark: make(map[string]string), } if masqueradeBit != nil { eip.masqueradeBit = 1 << uint32(*masqueradeBit) } eip.tracker = common.NewEgressIPTracker(eip) return eip } func (eip *egressIPWatcher) Start(networkInformers networkinformers.SharedInformerFactory, iptables *NodeIPTables) error { var err error if eip.localEgressLink, eip.localEgressNet, err = GetLinkDetails(eip.localIP); err != nil { // Not expected, should already be caught by node.New() return nil } eip.iptables = iptables updates := make(chan *egressVXLANNode) eip.vxlanMonitor = newEgressVXLANMonitor(eip.oc.ovs, eip.tracker, updates) go eip.watchVXLAN(updates) eip.tracker.Start(networkInformers.Network().InternalVersion().HostSubnets(), networkInformers.Network().InternalVersion().NetNamespaces()) return nil } // Convert vnid to a hex value that is not 0, does not have masqueradeBit set, and isn't // the same value as would be returned for any other valid vnid. func getMarkForVNID(vnid, masqueradeBit uint32) string { if vnid == 0 { vnid = 0xff000000 } if (vnid & masqueradeBit) != 0 { vnid = (vnid | 0x01000000) ^ masqueradeBit } return fmt.Sprintf("0x%08x", vnid) } func (eip *egressIPWatcher) ClaimEgressIP(vnid uint32, egressIP, nodeIP string) { if nodeIP == eip.localIP { mark := getMarkForVNID(vnid, eip.masqueradeBit) eip.iptablesMark[egressIP] = mark if err := eip.assignEgressIP(egressIP, mark); err != nil { utilruntime.HandleError(fmt.Errorf("Error assigning Egress IP %q: %v", egressIP, err)) } } else if eip.vxlanMonitor != nil { eip.vxlanMonitor.AddNode(nodeIP) } } func (eip *egressIPWatcher) ReleaseEgressIP(egressIP, nodeIP string) { if nodeIP == eip.localIP { mark := eip.iptablesMark[egressIP] delete(eip.iptablesMark, egressIP) if err := eip.releaseEgressIP(egressIP, mark); err != nil { utilruntime.HandleError(fmt.Errorf("Error releasing Egress IP %q: %v", egressIP, err)) } } else if eip.vxlanMonitor != nil { eip.vxlanMonitor.RemoveNode(nodeIP) } } func (eip *egressIPWatcher) SetNamespaceEgressNormal(vnid uint32) { if err := eip.oc.SetNamespaceEgressNormal(vnid); err != nil { utilruntime.HandleError(fmt.Errorf("Error updating Namespace egress rules for VNID %d: %v", vnid, err)) } } func (eip *egressIPWatcher) SetNamespaceEgressDropped(vnid uint32) { if err := eip.oc.SetNamespaceEgressDropped(vnid); err != nil { utilruntime.HandleError(fmt.Errorf("Error updating Namespace egress rules for VNID %d: %v", vnid, err)) } } func (eip *egressIPWatcher) SetNamespaceEgressViaEgressIP(vnid uint32, egressIP, nodeIP string) { mark := eip.iptablesMark[egressIP] if err := eip.oc.SetNamespaceEgressViaEgressIP(vnid, nodeIP, mark); err != nil { utilruntime.HandleError(fmt.Errorf("Error updating Namespace egress rules for VNID %d: %v", vnid, err)) } } func (eip *egressIPWatcher) assignEgressIP(egressIP, mark string) error { if egressIP == eip.localIP { return fmt.Errorf("desired egress IP %q is the node IP", egressIP) } if eip.testModeChan != nil { eip.testModeChan <- fmt.Sprintf("claim %s", egressIP) return nil } localEgressIPMaskLen, _ := eip.localEgressNet.Mask.Size() egressIPNet := fmt.Sprintf("%s/%d", egressIP, localEgressIPMaskLen) addr, err := netlink.ParseAddr(egressIPNet) if err != nil { return fmt.Errorf("could not parse egress IP %q: %v", egressIPNet, err) } if !eip.localEgressNet.Contains(addr.IP) { return fmt.Errorf("egress IP %q is not in local network %s of interface %s", egressIP, eip.localEgressNet.String(), eip.localEgressLink.Attrs().Name) } err = netlink.AddrAdd(eip.localEgressLink, addr) if err != nil { if err == syscall.EEXIST { glog.V(2).Infof("Egress IP %q already exists on %s", egressIPNet, eip.localEgressLink.Attrs().Name) } else { return fmt.Errorf("could not add egress IP %q to %s: %v", egressIPNet, eip.localEgressLink.Attrs().Name, err) } } if err := eip.iptables.AddEgressIPRules(egressIP, mark); err != nil { return fmt.Errorf("could not add egress IP iptables rule: %v", err) } return nil } func (eip *egressIPWatcher) releaseEgressIP(egressIP, mark string) error { if egressIP == eip.localIP { return nil } if eip.testModeChan != nil { eip.testModeChan <- fmt.Sprintf("release %s", egressIP) return nil } localEgressIPMaskLen, _ := eip.localEgressNet.Mask.Size() egressIPNet := fmt.Sprintf("%s/%d", egressIP, localEgressIPMaskLen) addr, err := netlink.ParseAddr(egressIPNet) if err != nil { return fmt.Errorf("could not parse egress IP %q: %v", egressIPNet, err) } err = netlink.AddrDel(eip.localEgressLink, addr) if err != nil { if err == syscall.EADDRNOTAVAIL { glog.V(2).Infof("Could not delete egress IP %q from %s: no such address", egressIPNet, eip.localEgressLink.Attrs().Name) } else { return fmt.Errorf("could not delete egress IP %q from %s: %v", egressIPNet, eip.localEgressLink.Attrs().Name, err) } } if err := eip.iptables.DeleteEgressIPRules(egressIP, mark); err != nil { return fmt.Errorf("could not delete egress IP iptables rule: %v", err) } return nil } func (eip *egressIPWatcher) watchVXLAN(updates chan *egressVXLANNode) { for node := range updates { eip.tracker.SetNodeOffline(node.nodeIP, node.offline) } }
apache-2.0
googleinterns/calcite
core/src/main/java/org/apache/calcite/sql/SqlSelectOperator.java
8563
/* * 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.calcite.sql; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.ReturnTypes; import org.apache.calcite.sql.util.SqlBasicVisitor; import org.apache.calcite.sql.util.SqlVisitor; import java.util.ArrayList; import java.util.List; /** * An operator describing a query. (Not a query itself.) * * <p>Operands are:</p> * * <ul> * <li>0: distinct ({@link SqlLiteral})</li> * <li>1: selectClause ({@link SqlNodeList})</li> * <li>2: fromClause ({@link SqlCall} to "join" operator)</li> * <li>3: whereClause ({@link SqlNode})</li> * <li>4: havingClause ({@link SqlNode})</li> * <li>5: qualifyClause ({@link SqlNode})</li> * <li>6: groupClause ({@link SqlNode})</li> * <li>7: windowClause ({@link SqlNodeList})</li> * <li>8: orderClause ({@link SqlNode})</li> * </ul> */ public class SqlSelectOperator extends SqlOperator { public static final SqlSelectOperator INSTANCE = new SqlSelectOperator(); //~ Constructors ----------------------------------------------------------- private SqlSelectOperator() { super("SELECT", SqlKind.SELECT, 2, true, ReturnTypes.SCOPE, null, null); } //~ Methods ---------------------------------------------------------------- public SqlSyntax getSyntax() { return SqlSyntax.SPECIAL; } public SqlCall createCall( SqlLiteral functionQualifier, SqlParserPos pos, SqlNode... operands) { assert functionQualifier == null; return new SqlSelect(pos, /*keywordList=*/ (SqlNodeList) operands[0], /*selectList=*/ (SqlNodeList) operands[1], /* from= */ operands[2], /* where= */ operands[3], /*groupBy=*/ (SqlNodeList) operands[4], /*having=*/ operands[5], /*qualify=*/ operands[6], /*windowDecls=*/ (SqlNodeList) operands[7], /*orderBy=*/ (SqlNodeList) operands[8], /*offset=*/ operands[9], /*fetch=*/ operands[10], /*hints=*/ (SqlNodeList) operands[11]); } /** * Creates a call to the <code>SELECT</code> operator. * * @param keywordList List of keywords such DISTINCT and ALL, or null * @param selectList The SELECT clause, or null if empty * @param fromClause The FROM clause * @param whereClause The WHERE clause, or null if not present * @param groupBy The GROUP BY clause, or null if not present * @param having The HAVING clause, or null if not present * @param qualify The QUALIFY clause, or null if not present * @param windowDecls The WINDOW clause, or null if not present * @param orderBy The ORDER BY clause, or null if not present * @param offset Expression for number of rows to discard before * returning first row * @param fetch Expression for number of rows to fetch * @param pos The parser position, or * {@link org.apache.calcite.sql.parser.SqlParserPos#ZERO} * if not specified; must not be null. * @return A {@link SqlSelect}, never null */ public SqlSelect createCall( SqlNodeList keywordList, SqlNodeList selectList, SqlNode fromClause, SqlNode whereClause, SqlNodeList groupBy, SqlNode having, SqlNode qualify, SqlNodeList windowDecls, SqlNodeList orderBy, SqlNode offset, SqlNode fetch, SqlNodeList hints, SqlParserPos pos) { return new SqlSelect( pos, keywordList, selectList, fromClause, whereClause, groupBy, having, qualify, windowDecls, orderBy, offset, fetch, hints); } public <R> void acceptCall( SqlVisitor<R> visitor, SqlCall call, boolean onlyExpressions, SqlBasicVisitor.ArgHandler<R> argHandler) { if (!onlyExpressions) { // None of the arguments to the SELECT operator are expressions. super.acceptCall(visitor, call, onlyExpressions, argHandler); } } @SuppressWarnings("deprecation") public void unparse( SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) { SqlSelect select = (SqlSelect) call; final SqlWriter.Frame selectFrame = writer.startList(SqlWriter.FrameTypeEnum.SELECT); writer.sep("SELECT"); if (select.hasHints()) { writer.sep("/*+"); select.hints.unparse(writer, 0, 0); writer.print("*/"); writer.newlineAndIndent(); } for (int i = 0; i < select.keywordList.size(); i++) { final SqlNode keyword = select.keywordList.get(i); keyword.unparse(writer, 0, 0); } if (select.topN != null) { writer.topN(select.topN); } else { writer.fetchAsTopN(select.fetch, select.offset); } final SqlNodeList selectClause = select.selectList != null ? select.selectList : SqlNodeList.of(SqlIdentifier.star(SqlParserPos.ZERO)); writer.list(SqlWriter.FrameTypeEnum.SELECT_LIST, SqlWriter.COMMA, selectClause); if (select.from != null) { // Calcite SQL requires FROM but MySQL does not. writer.sep("FROM"); // for FROM clause, use precedence just below join operator to make // sure that an un-joined nested select will be properly // parenthesized final SqlWriter.Frame fromFrame = writer.startList(SqlWriter.FrameTypeEnum.FROM_LIST); select.from.unparse( writer, SqlJoin.OPERATOR.getLeftPrec() - 1, SqlJoin.OPERATOR.getRightPrec() - 1); writer.endList(fromFrame); } if (select.where != null) { writer.sep("WHERE"); if (!writer.isAlwaysUseParentheses()) { SqlNode node = select.where; // decide whether to split on ORs or ANDs SqlBinaryOperator whereSep = SqlStdOperatorTable.AND; if ((node instanceof SqlCall) && node.getKind() == SqlKind.OR) { whereSep = SqlStdOperatorTable.OR; } // unroll whereClause final List<SqlNode> list = new ArrayList<>(0); while (node.getKind() == whereSep.kind) { assert node instanceof SqlCall; final SqlCall call1 = (SqlCall) node; list.add(0, call1.operand(1)); node = call1.operand(0); } list.add(0, node); // unparse in a WHERE_LIST frame writer.list(SqlWriter.FrameTypeEnum.WHERE_LIST, whereSep, new SqlNodeList(list, select.where.getParserPosition())); } else { select.where.unparse(writer, 0, 0); } } if (select.groupBy != null) { writer.sep("GROUP BY"); final SqlNodeList groupBy = select.groupBy.size() == 0 ? SqlNodeList.SINGLETON_EMPTY : select.groupBy; writer.list(SqlWriter.FrameTypeEnum.GROUP_BY_LIST, SqlWriter.COMMA, groupBy); } if (select.having != null) { writer.sep("HAVING"); select.having.unparse(writer, 0, 0); } if (select.getQualify() != null) { writer.sep("QUALIFY"); select.getQualify().unparse(writer, 0, 0); } if (select.windowDecls.size() > 0) { writer.sep("WINDOW"); writer.list(SqlWriter.FrameTypeEnum.WINDOW_DECL_LIST, SqlWriter.COMMA, select.windowDecls); } if (select.orderBy != null && select.orderBy.size() > 0) { writer.sep("ORDER BY"); writer.list(SqlWriter.FrameTypeEnum.ORDER_BY_LIST, SqlWriter.COMMA, select.orderBy); } writer.fetchOffset(select.fetch, select.offset); writer.endList(selectFrame); } public boolean argumentMustBeScalar(int ordinal) { return ordinal == SqlSelect.WHERE_OPERAND; } }
apache-2.0
dbflute-test/dbflute-test-active-hangar
src/main/java/org/docksidestage/hangar/dbflute/dtomapper/MemberServiceDtoMapper.java
776
package org.docksidestage.hangar.dbflute.dtomapper; import java.util.Map; import org.dbflute.Entity; import org.docksidestage.hangar.dbflute.dtomapper.bs.BsMemberServiceDtoMapper; /** * The DTO mapper of MEMBER_SERVICE. * <p> * You can implement your original methods here. * This class remains when re-generating. * </p> * @author DBFlute(AutoGenerator) */ public class MemberServiceDtoMapper extends BsMemberServiceDtoMapper { /** Serial version UID. (Default) */ private static final long serialVersionUID = 1L; public MemberServiceDtoMapper() { } public MemberServiceDtoMapper(Map<Entity, Object> relationDtoMap, Map<Object, Entity> relationEntityMap) { super(relationDtoMap, relationEntityMap); } }
apache-2.0
aaronpmishkin/CUCSC-ValueCharts
client/modules/ValueChart/interactions/ReorderObjectives.interaction.ts
17688
/* * @Author: aaronpmishkin * @Date: 2016-06-17 09:05:15 * @Last Modified by: aaronpmishkin * @Last Modified time: 2017-06-02 17:48:12 */ // Import Angular Classes: import { Injectable } from '@angular/core'; import { NgZone } from '@angular/core'; // Import Libraries: import * as d3 from 'd3'; import { Subject } from 'rxjs/Subject'; import '../../utilities/rxjs-operators'; // Import Application Classes import { RendererService } from '../services/Renderer.service'; import { ChartUndoRedoService } from '../services/ChartUndoRedo.service'; import { LabelDefinitions } from '../definitions/Label.definitions'; // Import Model Classes: import { Objective } from '../../../model/Objective'; import { PrimitiveObjective } from '../../../model/PrimitiveObjective'; import { AbstractObjective } from '../../../model/AbstractObjective'; import { RowData, CellData, LabelData, RendererConfig } from '../../../types/RendererData.types'; import { RendererUpdate } from '../../../types/RendererData.types'; import { ObjectivesRecord } from '../../../types/Record.types'; /* This class contains all the logic for dragging objective labels change the order of objectives in the objective and summary charts. Any objective label can be dragged within the confines of its parent label's Dimension Two so that it may be reordered with respect to its siblings (ie. the other children of the parent). The rows of the objective and summary charts are reordered to reflect the change in the label ordering when a label is released. */ @Injectable() export class ReorderObjectivesInteraction { // ======================================================================================== // Fields // ======================================================================================== public lastRendererUpdate: RendererUpdate; private labelRootContainer: d3.Selection<any,any,any,any>; private reorderSubject: Subject<boolean>; private ignoreReorder: boolean; // Whether the drag events should be ignored. If true, all dragging of the current label is ignored. // Fields used to store information about the active dragging event chain. private reorderObjectiveMouseOffset: number; // Offset of the mouse from the Coordinate Two position of the label that is to be dragged. This is set when dragging first begins. private totalCoordTwoChange: number = 0; // The Coordinate Two distance that the label has been moved so far. private containerToReorder: d3.Selection<any, any, any, any>; // The the d3 selection of the 'g' element that holds the label being reordered. private parentObjectiveName: string; // The name of the parent objective for the label being reordered. private parentContainer: d3.Selection<any, any, any, any>; // The selection of the container that holds the container for the label being reordered. private siblingContainers: d3.Selection<any, any, any, any>; // The selection of label containers s.t. every label container is at the same level in the label hierarchy as containerToReorder and also has the same parent label. private objectiveDimensionTwo: number; // The Dimension Two (height if vertical, width of horizontal) of the label being dragged. private objectiveCoordTwoOffset: number; // The initial Coordinate Two position (y if vertical, x if horizontal) of the label being reordered. private maxCoordinateTwo: number; // The maximum Coordinate Two that label being reordered can have before it exits the label area. private currentObjectiveIndex: number; // The index of the label being reordered in the list of siblings. private newObjectiveIndex: number; // The new index of the label as a result of the dragging. private jumpPoints: number[]; // The list of points that define what position the label being reordered has been moved to. // ======================================================================================== // Constructor // ======================================================================================== /* @returns {void} @description Used for Angular's dependency injection ONLY. It should not be used to do any initialization of the class. This constructor will be called automatically when Angular constructs an instance of this class prior to dependency injection. */ constructor( private rendererService: RendererService, private chartUndoRedoService: ChartUndoRedoService) { this.chartUndoRedoService.undoRedoDispatcher.on(this.chartUndoRedoService.OBJECTIVES_CHANGE, this.changeRowOrder); } // ======================================================================================== // Methods // ======================================================================================== /* @param enableReordering - Whether or not to enable dragging to reorder objectives. @returns {void} @description Toggles clicking and dragging labels in the label area to reorder objectives. Both abstract and primitive objectives can be reordered via label dragging when the user interaction is enabled. Dragging is implemented using d3's dragging system and makes use of all three drag events. 'start' is used to perform setup that is required to for dragging to work properly and is called before the 'drag' events fire. 'drag' is used to implement the visual dragging mechanism. Note that the handler for these events, reorderObjectives, only updates the visual display of the objective area. 'end' is used to actually reorder the objectives within the objective hierarchy, and then re-render the ValueChart via the ValueChartDirective. */ public toggleObjectiveReordering(enableReordering: boolean, labelRootContainer: d3.Selection<any, any, any, any>, rendererUpdate: RendererUpdate): Subject<boolean> { this.lastRendererUpdate = rendererUpdate; this.labelRootContainer = labelRootContainer; var labelOutlines: d3.Selection<any, any, any, any> = labelRootContainer.selectAll('.' + LabelDefinitions.SUBCONTAINER_OUTLINE); var labelTexts: d3.Selection<any, any, any, any> = labelRootContainer.selectAll('.' + LabelDefinitions.SUBCONTAINER_TEXT); var dragToReorder: d3.DragBehavior<any, any, any> = d3.drag(); if (enableReordering) { dragToReorder .on('start', this.startReorderObjectives) .on('drag', this.reorderObjectives) .on('end', this.endReorderObjectives); } labelOutlines.call(dragToReorder); labelTexts.call(dragToReorder); this.reorderSubject = new Subject(); return this.reorderSubject; } // This function is called when a user first begins to drag a label to rearrange the ordering of objectives. It contains all the logic required to initialize the drag, // including determining the bounds that the label can be dragged in, the points where the label is considered to have switched positions, etc. private startReorderObjectives = (d: LabelData, i: number) => { // Reset variables. this.ignoreReorder = false; // Whether the drag events should be ignored. If true, all further dragging of the current label will be ignored. this.reorderObjectiveMouseOffset = undefined; // Offset of the mouse from the Coordinate Two position of the label that is to be dragged. this.totalCoordTwoChange = 0; // The Coordinate Two distance that the label has been moved so far. this.containerToReorder = d3.select('#label-' + d.objective.getId() + '-container'); // The container that holds the label being reordered. this.parentObjectiveName = (<Element>this.containerToReorder.node()).getAttribute('parent'); // The name of the parent objective for the label being reordered. // If the selected label is the root label, then it is not possible to reorder, and all further drag events for this selection should be ignored. if (this.parentObjectiveName === LabelDefinitions.ROOT_CONTAINER_NAME) { this.ignoreReorder = true; return; } this.chartUndoRedoService.saveObjectivesRecord(this.lastRendererUpdate.valueChart.getRootObjectives()); this.parentContainer = d3.select('#label-' + this.parentObjectiveName + '-container'); // The container that holds the container for the label being reordered. this.siblingContainers = this.parentContainer.selectAll('g[parent="' + this.parentObjectiveName + '"]'); // The selection of label containers s.t. every label container is at the same level as containerToReorder, with the same parent. // Note: siblingsConatiners includes containerToReorder. // Set all the siblings that are NOT being moved to be partially transparent. this.siblingContainers.style('opacity', 0.5); this.containerToReorder.style('opacity', 1); var parentOutline: d3.Selection<any, any, any, any> = this.parentContainer.select('rect'); // Select the rect that outlines the parent label of the label being reordered. var currentOutline: d3.Selection<any, any, any, any> = this.containerToReorder.select('rect'); // Select the rect that outlines the label being reordered. this.objectiveDimensionTwo = +currentOutline.attr(this.lastRendererUpdate.rendererConfig.dimensionTwo); // Determine the Dimension Two (height if vertical, width of horizontal) of the label being dragged. this.maxCoordinateTwo = +parentOutline.attr(this.lastRendererUpdate.rendererConfig.dimensionTwo) - this.objectiveDimensionTwo; // Determine the maximum Coordinate Two of the label being reordered. this.objectiveCoordTwoOffset = +currentOutline.attr(this.lastRendererUpdate.rendererConfig.coordinateTwo); // Determine the initial Coordinate Two position (y if vertical, x if horizontal) of the label being reordered. this.currentObjectiveIndex = this.siblingContainers.nodes().indexOf(this.containerToReorder.node()); // Determine the index of the label being reordered in the list of siblings. this.newObjectiveIndex = this.currentObjectiveIndex; this.jumpPoints = [0]; // Initialize the list of points which define what position the label being reordered has been moved to. this.siblingContainers.select('rect').nodes().forEach((el: Element) => { if (el !== undefined) { // For each of the labels that the label being reordered can be switched with, determine its Coordinate Two midpoint. This is used to determine what position the label being reordered has been moved to. let selection: d3.Selection<any, any, any, any> = d3.select(el); let jumpPoint: number = (+selection.attr(this.lastRendererUpdate.rendererConfig.dimensionTwo) / 2) + +selection.attr(this.lastRendererUpdate.rendererConfig.coordinateTwo); this.jumpPoints.push(jumpPoint); } }); this.jumpPoints.push(this.lastRendererUpdate.rendererConfig.dimensionTwoSize); } // This function is called whenever a label that is being reordered is dragged by the user. It contains the logic which updates the // position of the label so the user knows where they have dragged it to as well as the code that determines what position the label will be in when dragging ends. private reorderObjectives = (d: LabelData, i: number) => { // Do nothing if we are ignoring the current dragging of the label. if (this.ignoreReorder) { return; } // Get the change in Coordinate Two from the d3 event. Note that although we are getting coordinateTwo, not dCoordinateTwo, this is the still the change. // The reason for this is because when a label is dragged, the transform of label container is changed, which can changes cooordinateTwo of the outline rectangle inside the container. // THis change is equal to deltaCoordinateTwo, meaning d3.event.cooordinateTwo is reset to 0 at the end of cooordinateTwo drag event, making cooordinateTwo really dCoordinateTwo var deltaCoordinateTwo: number = (<any>d3.event)[this.lastRendererUpdate.rendererConfig.coordinateTwo]; // If we have not yet determined the mouse offset, then this is the first drag event that has been fired, and the mouse offset from 0 should the current mouse position. if (this.reorderObjectiveMouseOffset === undefined) { this.reorderObjectiveMouseOffset = deltaCoordinateTwo; } deltaCoordinateTwo = deltaCoordinateTwo - this.reorderObjectiveMouseOffset; // Subtract the mouse offset to get the change in Coordinate Two from the 0 point. // Calculate the current Coordinate Two position of the label that is being reordered. // This is the recent change (deltaCoordinateTwo) + the totalChange so far (this.totalCoordTwoChange) + the offset of the label before dragging began (this.objectiveCoordTwoOffset) var currentCoordTwoPosition: number = deltaCoordinateTwo + this.totalCoordTwoChange + this.objectiveCoordTwoOffset; // Make sure that the label does not exit the bounds of the label area. if (currentCoordTwoPosition < 0) { deltaCoordinateTwo = 0 - this.totalCoordTwoChange - this.objectiveCoordTwoOffset; } else if (currentCoordTwoPosition > this.maxCoordinateTwo) { deltaCoordinateTwo = this.maxCoordinateTwo - this.totalCoordTwoChange - this.objectiveCoordTwoOffset; } // Add the most recent change in Coordinate Two to the total change so far. this.totalCoordTwoChange += deltaCoordinateTwo; // If we are dragging the label up, then we want to check the current position of the label from its top. // If we are dragging the label down, then we want to check the current position of the label form its bottom. var labelDimensionTwoOffset: number = (this.totalCoordTwoChange > 0) ? this.objectiveDimensionTwo : 0; // Determine which of the two jump points the label is current between, and assigned its new position accordingly. for (var i = 0; i < this.jumpPoints.length; i++) { if (this.totalCoordTwoChange + labelDimensionTwoOffset > (this.jumpPoints[i] - this.objectiveCoordTwoOffset) && this.totalCoordTwoChange + labelDimensionTwoOffset < (this.jumpPoints[i + 1] - this.objectiveCoordTwoOffset)) { this.newObjectiveIndex = i; break; } } // If we were dragging down, then the index is one off and must be decremented. if (this.totalCoordTwoChange > 0) this.newObjectiveIndex--; // Retrieved the previous transform of the label we are dragging so that it can be incremented properly. var previousTransform: string = this.containerToReorder.attr('transform'); // Generate the new transform. var labelTransform: string = this.rendererService.incrementTransform(this.lastRendererUpdate.viewConfig, previousTransform, 0, deltaCoordinateTwo); // Apply the new transformation to the label. this.containerToReorder.attr('transform', labelTransform); } // This function is called when the label that is being reordered is released by the user, and dragging ends. It contains the logic for re-rendering the ValueChart according // to the labels new position. private endReorderObjectives = (d: LabelData, i: number) => { // Do nothing if we are ignoring the current dragging of the label. if (this.ignoreReorder) { return; } // Get the label data for the siblings of the label we arranged. Note that this contains the label data for the label we rearranged. var parentData: LabelData = this.parentContainer.datum(); // Move the label data for the label we rearranged to its new position in the array of labels. if (this.newObjectiveIndex !== this.currentObjectiveIndex) { // Reorder the label data. let temp: LabelData = parentData.subLabelData.splice(this.currentObjectiveIndex, 1)[0]; parentData.subLabelData.splice(this.newObjectiveIndex, 0, temp); // Reorder the Objectives let siblingObjectives: Objective[] = (<AbstractObjective>parentData.objective).getDirectSubObjectives() let tempObjective: Objective = siblingObjectives.splice(this.currentObjectiveIndex, 1)[0]; siblingObjectives.splice(this.newObjectiveIndex, 0, tempObjective); } else { // No changes were made, so delete the change record that was created in startReorderObjectives. this.chartUndoRedoService.deleteNewestRecord(); this.lastRendererUpdate.renderRequired.value = true; } // Select all the label data, not just the siblings of the label we moved. var labelData: LabelData[] = <any> d3.select('g[parent=' + LabelDefinitions.ROOT_CONTAINER_NAME + ']').data(); // Re-arrange the rows of the objective and summary charts according to the new objective ordering. Note this triggers change detection in ValueChartDirective that // updates the object and summary charts. This is to avoid making the labelRenderer dependent on the other renderers. this.lastRendererUpdate.valueChart.setRootObjectives(this.getOrderedRootObjectives(labelData)); this.siblingContainers.style('opacity', 1); this.containerToReorder.style('opacity', 1); this.reorderSubject.next(true); } // This function extracts the ordering of objectives from the ordering of labels. private getOrderedRootObjectives(labelData: LabelData[]): Objective[] { var rootObjectives: Objective[] = []; labelData.forEach((labelDatum: LabelData) => { var objective: Objective = labelDatum.objective; if (labelDatum.depthOfChildren !== 0) { (<AbstractObjective>objective).setDirectSubObjectives(this.getOrderedRootObjectives(labelDatum.subLabelData)); } rootObjectives.push(objective); }); return rootObjectives; } changeRowOrder = (objectivesRecord: ObjectivesRecord) => { this.lastRendererUpdate.valueChart.setRootObjectives(objectivesRecord.rootObjectives); this.lastRendererUpdate.labelData[0] = undefined; this.reorderSubject.next(true); } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202105/CdnConfigurationService.java
1308
// Copyright 2021 Google LLC // // 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. /** * CdnConfigurationService.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.admanager.axis.v202105; public interface CdnConfigurationService extends javax.xml.rpc.Service { public java.lang.String getCdnConfigurationServiceInterfacePortAddress(); public com.google.api.ads.admanager.axis.v202105.CdnConfigurationServiceInterface getCdnConfigurationServiceInterfacePort() throws javax.xml.rpc.ServiceException; public com.google.api.ads.admanager.axis.v202105.CdnConfigurationServiceInterface getCdnConfigurationServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException; }
apache-2.0
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/creole/command/CommandCreoleSprite.java
2672
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.creole.command; import net.sourceforge.plantuml.ISkinSimple; import net.sourceforge.plantuml.command.regex.Matcher2; import net.sourceforge.plantuml.command.regex.MyPattern; import net.sourceforge.plantuml.command.regex.Pattern2; import net.sourceforge.plantuml.creole.Parser; import net.sourceforge.plantuml.creole.legacy.StripeSimple; import net.sourceforge.plantuml.graphic.Splitter; import net.sourceforge.plantuml.ugraphic.color.HColor; public class CommandCreoleSprite implements Command { @Override public String startingChars() { return "<"; } private static final Pattern2 pattern = MyPattern.cmpile("^(" + Splitter.spritePattern2 + ")"); private CommandCreoleSprite() { } public static Command create() { return new CommandCreoleSprite(); } public int matchingSize(String line) { final Matcher2 m = pattern.matcher(line); if (m.find() == false) return 0; return m.group(1).length(); } public String executeAndGetRemaining(String line, StripeSimple stripe) { final Matcher2 m = pattern.matcher(line); if (m.find() == false) throw new IllegalStateException(); final String src = m.group(2); final double scale = Parser.getScale(m.group(3), 1); final String colorName = Parser.getColor(m.group(3)); HColor color = null; if (colorName != null) { final ISkinSimple skinParam = stripe.getSkinParam(); color = skinParam.getIHtmlColorSet().getColorOrWhite(skinParam.getThemeStyle(), colorName); } stripe.addSprite(src, scale, color); return line.substring(m.group(1).length()); } }
apache-2.0
sh1n1xs/TrashyWindowControl
TrashyWindowControlExamples/SetCoordinatesExample/Program.cs
2416
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; using TrashyWindowControl; namespace SetCoordinatesExample { class Program { static void Main(string[] args) { //make sure a process called "notepad" is already running befor starting this programm! WindowControl twc = new WindowControl(); twc.process = Process.GetProcessesByName("notepad").FirstOrDefault(); char input; Console.WriteLine("Move the window with WASD!"); Console.WriteLine("You can change the height with R/F and the width with T/G"); do { input = Console.ReadKey().KeyChar; input = Char.ToLower(input); switch (input) { case 'w': { twc.y = twc.y - 5; break; } case 's': { twc.y = twc.y + 5; break; } case 'd': { twc.x = twc.x + 5; break; } case 'a': { twc.x = twc.x - 5; break; } case 'r': { twc.height = twc.height + 5; break; } case 'f': { twc.height = twc.height - 5; break; } case 't': { twc.width = twc.width + 5; break; } case 'g': { twc.width = twc.width - 5; break; } } } while (true); } } }
apache-2.0
SES-fortiss/SmartGridCoSimulation
core/cim15/src/CIM15/IEC61968/Metering/EndDeviceControl.java
33206
/** */ package CIM15.IEC61968.Metering; import CIM15.IEC61968.Customers.CustomerAgreement; import CIM15.IEC61968.Customers.CustomersPackage; import CIM15.IEC61970.Core.IdentifiedObject; import CIM15.IEC61970.Domain.DateTimeInterval; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>End Device Control</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getDemandResponseProgram <em>Demand Response Program</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getCustomerAgreement <em>Customer Agreement</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getScheduledInterval <em>Scheduled Interval</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDeviceGroup <em>End Device Group</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDevice <em>End Device</em>}</li> * <li>{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}</li> * </ul> * </p> * * @generated */ public class EndDeviceControl extends IdentifiedObject { /** * The cached value of the '{@link #getDemandResponseProgram() <em>Demand Response Program</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDemandResponseProgram() * @generated * @ordered */ protected DemandResponseProgram demandResponseProgram; /** * The default value of the '{@link #getDrProgramLevel() <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDrProgramLevel() * @generated * @ordered */ protected static final int DR_PROGRAM_LEVEL_EDEFAULT = 0; /** * The cached value of the '{@link #getDrProgramLevel() <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDrProgramLevel() * @generated * @ordered */ protected int drProgramLevel = DR_PROGRAM_LEVEL_EDEFAULT; /** * This is true if the Dr Program Level attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean drProgramLevelESet; /** * The default value of the '{@link #isDrProgramMandatory() <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDrProgramMandatory() * @generated * @ordered */ protected static final boolean DR_PROGRAM_MANDATORY_EDEFAULT = false; /** * The cached value of the '{@link #isDrProgramMandatory() <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDrProgramMandatory() * @generated * @ordered */ protected boolean drProgramMandatory = DR_PROGRAM_MANDATORY_EDEFAULT; /** * This is true if the Dr Program Mandatory attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean drProgramMandatoryESet; /** * The cached value of the '{@link #getCustomerAgreement() <em>Customer Agreement</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCustomerAgreement() * @generated * @ordered */ protected CustomerAgreement customerAgreement; /** * The default value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected static final String TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected String type = TYPE_EDEFAULT; /** * This is true if the Type attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean typeESet; /** * The cached value of the '{@link #getScheduledInterval() <em>Scheduled Interval</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getScheduledInterval() * @generated * @ordered */ protected DateTimeInterval scheduledInterval; /** * The cached value of the '{@link #getEndDeviceGroup() <em>End Device Group</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDeviceGroup() * @generated * @ordered */ protected EndDeviceGroup endDeviceGroup; /** * The cached value of the '{@link #getEndDevice() <em>End Device</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDevice() * @generated * @ordered */ protected EndDevice endDevice; /** * The default value of the '{@link #getPriceSignal() <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPriceSignal() * @generated * @ordered */ protected static final float PRICE_SIGNAL_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getPriceSignal() <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPriceSignal() * @generated * @ordered */ protected float priceSignal = PRICE_SIGNAL_EDEFAULT; /** * This is true if the Price Signal attribute has been set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ protected boolean priceSignalESet; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EndDeviceControl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MeteringPackage.Literals.END_DEVICE_CONTROL; } /** * Returns the value of the '<em><b>Demand Response Program</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Metering.DemandResponseProgram#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Demand Response Program</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Demand Response Program</em>' reference. * @see #setDemandResponseProgram(DemandResponseProgram) * @see CIM15.IEC61968.Metering.DemandResponseProgram#getEndDeviceControls * @generated */ public DemandResponseProgram getDemandResponseProgram() { if (demandResponseProgram != null && demandResponseProgram.eIsProxy()) { InternalEObject oldDemandResponseProgram = (InternalEObject)demandResponseProgram; demandResponseProgram = (DemandResponseProgram)eResolveProxy(oldDemandResponseProgram); if (demandResponseProgram != oldDemandResponseProgram) { } } return demandResponseProgram; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DemandResponseProgram basicGetDemandResponseProgram() { return demandResponseProgram; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetDemandResponseProgram(DemandResponseProgram newDemandResponseProgram, NotificationChain msgs) { DemandResponseProgram oldDemandResponseProgram = demandResponseProgram; demandResponseProgram = newDemandResponseProgram; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDemandResponseProgram <em>Demand Response Program</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Demand Response Program</em>' reference. * @see #getDemandResponseProgram() * @generated */ public void setDemandResponseProgram(DemandResponseProgram newDemandResponseProgram) { if (newDemandResponseProgram != demandResponseProgram) { NotificationChain msgs = null; if (demandResponseProgram != null) msgs = ((InternalEObject)demandResponseProgram).eInverseRemove(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs); if (newDemandResponseProgram != null) msgs = ((InternalEObject)newDemandResponseProgram).eInverseAdd(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs); msgs = basicSetDemandResponseProgram(newDemandResponseProgram, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Dr Program Level</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Dr Program Level</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Dr Program Level</em>' attribute. * @see #isSetDrProgramLevel() * @see #unsetDrProgramLevel() * @see #setDrProgramLevel(int) * @generated */ public int getDrProgramLevel() { return drProgramLevel; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Dr Program Level</em>' attribute. * @see #isSetDrProgramLevel() * @see #unsetDrProgramLevel() * @see #getDrProgramLevel() * @generated */ public void setDrProgramLevel(int newDrProgramLevel) { drProgramLevel = newDrProgramLevel; drProgramLevelESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetDrProgramLevel() * @see #getDrProgramLevel() * @see #setDrProgramLevel(int) * @generated */ public void unsetDrProgramLevel() { drProgramLevel = DR_PROGRAM_LEVEL_EDEFAULT; drProgramLevelESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getDrProgramLevel <em>Dr Program Level</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Dr Program Level</em>' attribute is set. * @see #unsetDrProgramLevel() * @see #getDrProgramLevel() * @see #setDrProgramLevel(int) * @generated */ public boolean isSetDrProgramLevel() { return drProgramLevelESet; } /** * Returns the value of the '<em><b>Dr Program Mandatory</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Dr Program Mandatory</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Dr Program Mandatory</em>' attribute. * @see #isSetDrProgramMandatory() * @see #unsetDrProgramMandatory() * @see #setDrProgramMandatory(boolean) * @generated */ public boolean isDrProgramMandatory() { return drProgramMandatory; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Dr Program Mandatory</em>' attribute. * @see #isSetDrProgramMandatory() * @see #unsetDrProgramMandatory() * @see #isDrProgramMandatory() * @generated */ public void setDrProgramMandatory(boolean newDrProgramMandatory) { drProgramMandatory = newDrProgramMandatory; drProgramMandatoryESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetDrProgramMandatory() * @see #isDrProgramMandatory() * @see #setDrProgramMandatory(boolean) * @generated */ public void unsetDrProgramMandatory() { drProgramMandatory = DR_PROGRAM_MANDATORY_EDEFAULT; drProgramMandatoryESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#isDrProgramMandatory <em>Dr Program Mandatory</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Dr Program Mandatory</em>' attribute is set. * @see #unsetDrProgramMandatory() * @see #isDrProgramMandatory() * @see #setDrProgramMandatory(boolean) * @generated */ public boolean isSetDrProgramMandatory() { return drProgramMandatoryESet; } /** * Returns the value of the '<em><b>Customer Agreement</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Customers.CustomerAgreement#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Customer Agreement</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Customer Agreement</em>' reference. * @see #setCustomerAgreement(CustomerAgreement) * @see CIM15.IEC61968.Customers.CustomerAgreement#getEndDeviceControls * @generated */ public CustomerAgreement getCustomerAgreement() { if (customerAgreement != null && customerAgreement.eIsProxy()) { InternalEObject oldCustomerAgreement = (InternalEObject)customerAgreement; customerAgreement = (CustomerAgreement)eResolveProxy(oldCustomerAgreement); if (customerAgreement != oldCustomerAgreement) { } } return customerAgreement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CustomerAgreement basicGetCustomerAgreement() { return customerAgreement; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCustomerAgreement(CustomerAgreement newCustomerAgreement, NotificationChain msgs) { CustomerAgreement oldCustomerAgreement = customerAgreement; customerAgreement = newCustomerAgreement; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getCustomerAgreement <em>Customer Agreement</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Customer Agreement</em>' reference. * @see #getCustomerAgreement() * @generated */ public void setCustomerAgreement(CustomerAgreement newCustomerAgreement) { if (newCustomerAgreement != customerAgreement) { NotificationChain msgs = null; if (customerAgreement != null) msgs = ((InternalEObject)customerAgreement).eInverseRemove(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs); if (newCustomerAgreement != null) msgs = ((InternalEObject)newCustomerAgreement).eInverseAdd(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs); msgs = basicSetCustomerAgreement(newCustomerAgreement, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Type</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Type</em>' attribute. * @see #isSetType() * @see #unsetType() * @see #setType(String) * @generated */ public String getType() { return type; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Type</em>' attribute. * @see #isSetType() * @see #unsetType() * @see #getType() * @generated */ public void setType(String newType) { type = newType; typeESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetType() * @see #getType() * @see #setType(String) * @generated */ public void unsetType() { type = TYPE_EDEFAULT; typeESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getType <em>Type</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Type</em>' attribute is set. * @see #unsetType() * @see #getType() * @see #setType(String) * @generated */ public boolean isSetType() { return typeESet; } /** * Returns the value of the '<em><b>Scheduled Interval</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Scheduled Interval</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Scheduled Interval</em>' containment reference. * @see #setScheduledInterval(DateTimeInterval) * @generated */ public DateTimeInterval getScheduledInterval() { return scheduledInterval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetScheduledInterval(DateTimeInterval newScheduledInterval, NotificationChain msgs) { DateTimeInterval oldScheduledInterval = scheduledInterval; scheduledInterval = newScheduledInterval; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getScheduledInterval <em>Scheduled Interval</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Scheduled Interval</em>' containment reference. * @see #getScheduledInterval() * @generated */ public void setScheduledInterval(DateTimeInterval newScheduledInterval) { if (newScheduledInterval != scheduledInterval) { NotificationChain msgs = null; if (scheduledInterval != null) msgs = ((InternalEObject)scheduledInterval).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL, null, msgs); if (newScheduledInterval != null) msgs = ((InternalEObject)newScheduledInterval).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL, null, msgs); msgs = basicSetScheduledInterval(newScheduledInterval, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>End Device Group</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Metering.EndDeviceGroup#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>End Device Group</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>End Device Group</em>' reference. * @see #setEndDeviceGroup(EndDeviceGroup) * @see CIM15.IEC61968.Metering.EndDeviceGroup#getEndDeviceControls * @generated */ public EndDeviceGroup getEndDeviceGroup() { if (endDeviceGroup != null && endDeviceGroup.eIsProxy()) { InternalEObject oldEndDeviceGroup = (InternalEObject)endDeviceGroup; endDeviceGroup = (EndDeviceGroup)eResolveProxy(oldEndDeviceGroup); if (endDeviceGroup != oldEndDeviceGroup) { } } return endDeviceGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndDeviceGroup basicGetEndDeviceGroup() { return endDeviceGroup; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEndDeviceGroup(EndDeviceGroup newEndDeviceGroup, NotificationChain msgs) { EndDeviceGroup oldEndDeviceGroup = endDeviceGroup; endDeviceGroup = newEndDeviceGroup; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDeviceGroup <em>End Device Group</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>End Device Group</em>' reference. * @see #getEndDeviceGroup() * @generated */ public void setEndDeviceGroup(EndDeviceGroup newEndDeviceGroup) { if (newEndDeviceGroup != endDeviceGroup) { NotificationChain msgs = null; if (endDeviceGroup != null) msgs = ((InternalEObject)endDeviceGroup).eInverseRemove(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs); if (newEndDeviceGroup != null) msgs = ((InternalEObject)newEndDeviceGroup).eInverseAdd(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs); msgs = basicSetEndDeviceGroup(newEndDeviceGroup, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>End Device</b></em>' reference. * It is bidirectional and its opposite is '{@link CIM15.IEC61968.Metering.EndDevice#getEndDeviceControls <em>End Device Controls</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>End Device</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>End Device</em>' reference. * @see #setEndDevice(EndDevice) * @see CIM15.IEC61968.Metering.EndDevice#getEndDeviceControls * @generated */ public EndDevice getEndDevice() { if (endDevice != null && endDevice.eIsProxy()) { InternalEObject oldEndDevice = (InternalEObject)endDevice; endDevice = (EndDevice)eResolveProxy(oldEndDevice); if (endDevice != oldEndDevice) { } } return endDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndDevice basicGetEndDevice() { return endDevice; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEndDevice(EndDevice newEndDevice, NotificationChain msgs) { EndDevice oldEndDevice = endDevice; endDevice = newEndDevice; return msgs; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getEndDevice <em>End Device</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>End Device</em>' reference. * @see #getEndDevice() * @generated */ public void setEndDevice(EndDevice newEndDevice) { if (newEndDevice != endDevice) { NotificationChain msgs = null; if (endDevice != null) msgs = ((InternalEObject)endDevice).eInverseRemove(this, MeteringPackage.END_DEVICE__END_DEVICE_CONTROLS, EndDevice.class, msgs); if (newEndDevice != null) msgs = ((InternalEObject)newEndDevice).eInverseAdd(this, MeteringPackage.END_DEVICE__END_DEVICE_CONTROLS, EndDevice.class, msgs); msgs = basicSetEndDevice(newEndDevice, msgs); if (msgs != null) msgs.dispatch(); } } /** * Returns the value of the '<em><b>Price Signal</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Price Signal</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Price Signal</em>' attribute. * @see #isSetPriceSignal() * @see #unsetPriceSignal() * @see #setPriceSignal(float) * @generated */ public float getPriceSignal() { return priceSignal; } /** * Sets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Price Signal</em>' attribute. * @see #isSetPriceSignal() * @see #unsetPriceSignal() * @see #getPriceSignal() * @generated */ public void setPriceSignal(float newPriceSignal) { priceSignal = newPriceSignal; priceSignalESet = true; } /** * Unsets the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetPriceSignal() * @see #getPriceSignal() * @see #setPriceSignal(float) * @generated */ public void unsetPriceSignal() { priceSignal = PRICE_SIGNAL_EDEFAULT; priceSignalESet = false; } /** * Returns whether the value of the '{@link CIM15.IEC61968.Metering.EndDeviceControl#getPriceSignal <em>Price Signal</em>}' attribute is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Price Signal</em>' attribute is set. * @see #unsetPriceSignal() * @see #getPriceSignal() * @see #setPriceSignal(float) * @generated */ public boolean isSetPriceSignal() { return priceSignalESet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: if (demandResponseProgram != null) msgs = ((InternalEObject)demandResponseProgram).eInverseRemove(this, MeteringPackage.DEMAND_RESPONSE_PROGRAM__END_DEVICE_CONTROLS, DemandResponseProgram.class, msgs); return basicSetDemandResponseProgram((DemandResponseProgram)otherEnd, msgs); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: if (customerAgreement != null) msgs = ((InternalEObject)customerAgreement).eInverseRemove(this, CustomersPackage.CUSTOMER_AGREEMENT__END_DEVICE_CONTROLS, CustomerAgreement.class, msgs); return basicSetCustomerAgreement((CustomerAgreement)otherEnd, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: if (endDeviceGroup != null) msgs = ((InternalEObject)endDeviceGroup).eInverseRemove(this, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_CONTROLS, EndDeviceGroup.class, msgs); return basicSetEndDeviceGroup((EndDeviceGroup)otherEnd, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: if (endDevice != null) msgs = ((InternalEObject)endDevice).eInverseRemove(this, MeteringPackage.END_DEVICE__END_DEVICE_CONTROLS, EndDevice.class, msgs); return basicSetEndDevice((EndDevice)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: return basicSetDemandResponseProgram(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: return basicSetCustomerAgreement(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: return basicSetScheduledInterval(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: return basicSetEndDeviceGroup(null, msgs); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: return basicSetEndDevice(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: if (resolve) return getDemandResponseProgram(); return basicGetDemandResponseProgram(); case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: return getDrProgramLevel(); case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: return isDrProgramMandatory(); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: if (resolve) return getCustomerAgreement(); return basicGetCustomerAgreement(); case MeteringPackage.END_DEVICE_CONTROL__TYPE: return getType(); case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: return getScheduledInterval(); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: if (resolve) return getEndDeviceGroup(); return basicGetEndDeviceGroup(); case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: if (resolve) return getEndDevice(); return basicGetEndDevice(); case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: return getPriceSignal(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: setDemandResponseProgram((DemandResponseProgram)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: setDrProgramLevel((Integer)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: setDrProgramMandatory((Boolean)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: setCustomerAgreement((CustomerAgreement)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__TYPE: setType((String)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: setScheduledInterval((DateTimeInterval)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: setEndDeviceGroup((EndDeviceGroup)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: setEndDevice((EndDevice)newValue); return; case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: setPriceSignal((Float)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: setDemandResponseProgram((DemandResponseProgram)null); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: unsetDrProgramLevel(); return; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: unsetDrProgramMandatory(); return; case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: setCustomerAgreement((CustomerAgreement)null); return; case MeteringPackage.END_DEVICE_CONTROL__TYPE: unsetType(); return; case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: setScheduledInterval((DateTimeInterval)null); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: setEndDeviceGroup((EndDeviceGroup)null); return; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: setEndDevice((EndDevice)null); return; case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: unsetPriceSignal(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MeteringPackage.END_DEVICE_CONTROL__DEMAND_RESPONSE_PROGRAM: return demandResponseProgram != null; case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_LEVEL: return isSetDrProgramLevel(); case MeteringPackage.END_DEVICE_CONTROL__DR_PROGRAM_MANDATORY: return isSetDrProgramMandatory(); case MeteringPackage.END_DEVICE_CONTROL__CUSTOMER_AGREEMENT: return customerAgreement != null; case MeteringPackage.END_DEVICE_CONTROL__TYPE: return isSetType(); case MeteringPackage.END_DEVICE_CONTROL__SCHEDULED_INTERVAL: return scheduledInterval != null; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_GROUP: return endDeviceGroup != null; case MeteringPackage.END_DEVICE_CONTROL__END_DEVICE: return endDevice != null; case MeteringPackage.END_DEVICE_CONTROL__PRICE_SIGNAL: return isSetPriceSignal(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (drProgramLevel: "); if (drProgramLevelESet) result.append(drProgramLevel); else result.append("<unset>"); result.append(", drProgramMandatory: "); if (drProgramMandatoryESet) result.append(drProgramMandatory); else result.append("<unset>"); result.append(", type: "); if (typeESet) result.append(type); else result.append("<unset>"); result.append(", priceSignal: "); if (priceSignalESet) result.append(priceSignal); else result.append("<unset>"); result.append(')'); return result.toString(); } } // EndDeviceControl
apache-2.0
morelinq/MoreLINQ
MoreLinq/FullJoin.cs
12941
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copysecond (c) 2017 Atif Aziz. All seconds 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; using System.Linq; static partial class MoreEnumerable { /// <summary> /// Performs a full outer join on two homogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> firstSelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.FullJoin(second, keySelector, firstSelector, secondSelector, bothSelector, null); } /// <summary> /// Performs a full outer join on two homogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> firstSelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector, IEqualityComparer<TKey>? comparer) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.FullJoin(second, keySelector, keySelector, firstSelector, secondSelector, bothSelector, comparer); } /// <summary> /// Performs a full outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TResult> firstSelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector) => first.FullJoin(second, firstKeySelector, secondKeySelector, firstSelector, secondSelector, bothSelector, null); /// <summary> /// Performs a full outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence to join fully.</param> /// <param name="second"> /// The second sequence to join fully.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="firstSelector"> /// Function that projects the result given just an element from /// <paramref name="first"/> where there is no corresponding element /// in <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a full /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> FullJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TFirst, TResult> firstSelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector, IEqualityComparer<TKey>? comparer) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector)); if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector)); if (firstSelector == null) throw new ArgumentNullException(nameof(firstSelector)); if (secondSelector == null) throw new ArgumentNullException(nameof(secondSelector)); if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector)); return _(); IEnumerable<TResult> _() { var seconds = second.Select(e => new KeyValuePair<TKey, TSecond>(secondKeySelector(e), e)).ToArray(); var secondLookup = seconds.ToLookup(e => e.Key, e => e.Value, comparer); var firstKeys = new HashSet<TKey>(comparer); foreach (var fe in first) { var key = firstKeySelector(fe); firstKeys.Add(key); using var se = secondLookup[key].GetEnumerator(); if (se.MoveNext()) { do { yield return bothSelector(fe, se.Current); } while (se.MoveNext()); } else { se.Dispose(); yield return firstSelector(fe); } } foreach (var se in seconds) { if (!firstKeys.Contains(se.Key)) yield return secondSelector(se.Value); } } } } }
apache-2.0
cilium/cilium
pkg/hubble/filters/filters_test.go
3264
// SPDX-License-Identifier: Apache-2.0 // Copyright Authors of Hubble //go:build !privileged_tests // +build !privileged_tests package filters import ( "context" "testing" "github.com/stretchr/testify/assert" flowpb "github.com/cilium/cilium/api/v1/flow" v1 "github.com/cilium/cilium/pkg/hubble/api/v1" ) func TestApply(t *testing.T) { ffyes := FilterFuncs{func(_ *v1.Event) bool { return true }} ffno := FilterFuncs{func(_ *v1.Event) bool { return false }} type args struct { whitelist FilterFuncs blacklist FilterFuncs ev *v1.Event } tests := []struct { name string args args want bool }{ {args: args{whitelist: ffyes}, want: true}, {args: args{whitelist: ffno}, want: false}, {args: args{blacklist: ffno}, want: true}, {args: args{blacklist: ffyes}, want: false}, {args: args{whitelist: ffyes, blacklist: ffyes}, want: false}, {args: args{whitelist: ffyes, blacklist: ffno}, want: true}, {args: args{whitelist: ffno, blacklist: ffyes}, want: false}, {args: args{whitelist: ffno, blacklist: ffno}, want: false}, {args: args{}, want: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Apply(tt.args.whitelist, tt.args.blacklist, tt.args.ev); got != tt.want { t.Errorf("Apply() = %v, want %v", got, tt.want) } }) } } func TestMatch(t *testing.T) { fyes := func(_ *v1.Event) bool { return true } fno := func(_ *v1.Event) bool { return false } fs := FilterFuncs{fyes, fno} assert.False(t, fs.MatchAll(nil)) assert.True(t, fs.MatchOne(nil)) assert.False(t, fs.MatchNone(nil)) // When no filter is specified, MatchAll(), MatchOne() and MatchNone() must // all return true fs = FilterFuncs{} assert.True(t, fs.MatchAll(nil)) assert.True(t, fs.MatchOne(nil)) assert.True(t, fs.MatchNone(nil)) } type testFilterTrue struct{} func (t *testFilterTrue) OnBuildFilter(_ context.Context, ff *flowpb.FlowFilter) ([]FilterFunc, error) { return []FilterFunc{func(ev *v1.Event) bool { return true }}, nil } type testFilterFalse struct{} func (t *testFilterFalse) OnBuildFilter(_ context.Context, ff *flowpb.FlowFilter) ([]FilterFunc, error) { return []FilterFunc{func(ev *v1.Event) bool { return false }}, nil } func TestOnBuildFilter(t *testing.T) { fl, err := BuildFilterList(context.Background(), []*flowpb.FlowFilter{{SourceIdentity: []uint32{1, 2, 3}}}, // true []OnBuildFilter{&testFilterTrue{}}) // true assert.NoError(t, err) assert.Equal(t, true, fl.MatchAll(&v1.Event{Event: &flowpb.Flow{ Source: &flowpb.Endpoint{Identity: 3}, }})) fl, err = BuildFilterList(context.Background(), []*flowpb.FlowFilter{{SourceIdentity: []uint32{1, 2, 3}}}, // true []OnBuildFilter{&testFilterFalse{}}) // false assert.NoError(t, err) assert.Equal(t, false, fl.MatchAll(&v1.Event{Event: &flowpb.Flow{ Source: &flowpb.Endpoint{Identity: 3}, }})) fl, err = BuildFilterList(context.Background(), []*flowpb.FlowFilter{{SourceIdentity: []uint32{1, 2, 3}}}, // true []OnBuildFilter{ &testFilterFalse{}, // false &testFilterTrue{}}) // true assert.NoError(t, err) assert.Equal(t, false, fl.MatchAll(&v1.Event{Event: &flowpb.Flow{ Source: &flowpb.Endpoint{Identity: 3}, }})) }
apache-2.0
Dataman-Cloud/drone
vendor/github.com/go-swagger/go-swagger/examples/generated/restapi/operations/pet/delete_pet_responses.go
655
package pet // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "github.com/go-swagger/go-swagger/httpkit" ) /*DeletePetBadRequest Invalid pet value swagger:response deletePetBadRequest */ type DeletePetBadRequest struct { } // NewDeletePetBadRequest creates DeletePetBadRequest with default headers values func NewDeletePetBadRequest() *DeletePetBadRequest { return &DeletePetBadRequest{} } // WriteResponse to the client func (o *DeletePetBadRequest) WriteResponse(rw http.ResponseWriter, producer httpkit.Producer) { rw.WriteHeader(400) }
apache-2.0
geftimov/MapReduce
src/main/java/com/eftimoff/mapreduce/filtering/distinct/DistinctUser.java
2821
package com.eftimoff.mapreduce.filtering.distinct; import static com.eftimoff.mapreduce.utils.MRDPUtils.transformXmlToMap; import java.io.IOException; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class DistinctUser extends Configured implements Tool { public static class DistinctUserMapper extends Mapper<Object, Text, Text, NullWritable> { private Text outUserId = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { Map<String, String> parsed = transformXmlToMap(value.toString()); // Get the value for the UserId attribute String userId = parsed.get("UserId"); if (userId == null) { return; } // Set our output key to the user's id outUserId.set(userId); // Write the user's id with a null value context.write(outUserId, NullWritable.get()); } } public static class DistinctUserReducer extends Reducer<Text, NullWritable, Text, NullWritable> { public void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException { // Write the user's id with a null value context.write(key, NullWritable.get()); } } public static void main(String[] args) throws Exception { int res = ToolRunner.run(new Configuration(), new DistinctUser(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { Configuration conf = new Configuration(); GenericOptionsParser parser = new GenericOptionsParser(conf, args); String[] otherArgs = parser.getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: DistinctUser <in> <out>"); ToolRunner.printGenericCommandUsage(System.err); System.exit(2); } Job job = new Job(conf, "Distinct User"); job.setJarByClass(DistinctUser.class); job.setMapperClass(DistinctUserMapper.class); job.setReducerClass(DistinctUserReducer.class); job.setCombinerClass(DistinctUserReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); boolean success = job.waitForCompletion(true); return success ? 0 : 1; } }
apache-2.0
brettfo/roslyn
src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedEmbeddedNativeIntegerAttributeSymbol.cs
4340
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedEmbeddedNativeIntegerAttributeSymbol : SynthesizedEmbeddedAttributeSymbolBase { private readonly ImmutableArray<FieldSymbol> _fields; private readonly ImmutableArray<MethodSymbol> _constructors; private readonly TypeSymbol _boolType; private const string FieldName = "TransformFlags"; public SynthesizedEmbeddedNativeIntegerAttributeSymbol( string name, NamespaceSymbol containingNamespace, ModuleSymbol containingModule, NamedTypeSymbol systemAttributeType, TypeSymbol boolType) : base(name, containingNamespace, containingModule, baseType: systemAttributeType) { _boolType = boolType; var boolArrayType = TypeWithAnnotations.Create( ArrayTypeSymbol.CreateSZArray( boolType.ContainingAssembly, TypeWithAnnotations.Create(boolType))); _fields = ImmutableArray.Create<FieldSymbol>( new SynthesizedFieldSymbol( this, boolArrayType.Type, FieldName, isPublic: true, isReadOnly: true, isStatic: false)); _constructors = ImmutableArray.Create<MethodSymbol>( new SynthesizedEmbeddedAttributeConstructorWithBodySymbol( this, m => ImmutableArray<ParameterSymbol>.Empty, (f, s, p) => GenerateParameterlessConstructorBody(f, s)), new SynthesizedEmbeddedAttributeConstructorWithBodySymbol( this, m => ImmutableArray.Create(SynthesizedParameterSymbol.Create(m, boolArrayType, 0, RefKind.None)), (f, s, p) => GenerateBoolArrayConstructorBody(f, s, p))); // Ensure we never get out of sync with the description Debug.Assert(_constructors.Length == AttributeDescription.NativeIntegerAttribute.Signatures.Length); } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() => _fields; public override ImmutableArray<MethodSymbol> Constructors => _constructors; internal override AttributeUsageInfo GetAttributeUsageInfo() { return new AttributeUsageInfo( AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, allowMultiple: false, inherited: false); } private void GenerateParameterlessConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder<BoundStatement> statements) { statements.Add( factory.ExpressionStatement( factory.AssignmentExpression( factory.Field( factory.This(), _fields.Single()), factory.Array( _boolType, ImmutableArray.Create<BoundExpression>(factory.Literal(true)) ) ) ) ); } private void GenerateBoolArrayConstructorBody(SyntheticBoundNodeFactory factory, ArrayBuilder<BoundStatement> statements, ImmutableArray<ParameterSymbol> parameters) { statements.Add( factory.ExpressionStatement( factory.AssignmentExpression( factory.Field( factory.This(), _fields.Single()), factory.Parameter(parameters.Single()) ) ) ); } } }
apache-2.0
bytedance/fedlearner
web_console_v2/client/src/views/Datasets/CreateDataset/index.tsx
2390
import React, { FC, useState } from 'react'; import styled from 'styled-components'; import { Modal } from 'antd'; import { Z_INDEX_GREATER_THAN_HEADER } from 'components/Header'; import { useHistory } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useToggle } from 'react-use'; import { Steps, Row } from 'antd'; import StepOneBasic from './StepOneBasic'; import StepTwoAddBatch from './StepTwoAddBatch'; import { useResetCreateForm } from 'hooks/dataset'; import { forceToRefreshQuery } from 'shared/queryClient'; import { DATASET_LIST_QUERY_KEY } from '../DatasetList'; const ContainerModal = styled(Modal)` .ant-modal-body { padding-bottom: 14px; } .ant-modal-footer { display: none; } `; const StepRow = styled(Row)` width: 340px; margin: 10px auto 35px; `; const CreateDataset: FC = () => { const history = useHistory(); const { t } = useTranslation(); const [step, setStep] = useState(0); const [visible, toggleVisible] = useToggle(true); const resetForm = useResetCreateForm(); return ( <ContainerModal title={t('dataset.title_create')} visible={visible} style={{ top: '20%' }} width="fit-content" closable={false} maskClosable={false} maskStyle={{ backdropFilter: 'blur(4px)' }} keyboard={false} afterClose={afterClose} getContainer="body" zIndex={Z_INDEX_GREATER_THAN_HEADER} onCancel={() => toggleVisible(false)} > <StepRow justify="center"> <Steps current={step} size="small"> <Steps.Step title={t('dataset.step_basic')} /> <Steps.Step title={t('dataset.step_add_batch')} /> </Steps> </StepRow> {step === 0 && <StepOneBasic onSuccess={goAddBatch} onCancel={closeModal} />} {step === 1 && ( <StepTwoAddBatch onSuccess={onCreateNStartImportSuccess} onPrevious={backToStepBasic} onCancel={closeModal} /> )} </ContainerModal> ); function afterClose() { history.push('/datasets'); } function goAddBatch() { setStep(1); } function backToStepBasic() { setStep(0); } function closeModal() { resetForm(); toggleVisible(false); } function onCreateNStartImportSuccess() { forceToRefreshQuery([DATASET_LIST_QUERY_KEY]); closeModal(); } }; export default CreateDataset;
apache-2.0
ChenJonathan/Argon
docs/classes/messageeventlike.html
11467
<!doctype html> <html class="default no-js"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>MessageEventLike | argon.js</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../assets/css/main.css"> </head> <body> <header> <div class="tsd-page-toolbar"> <div class="container"> <div class="table-wrap"> <div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base=".."> <div class="field"> <label for="tsd-search-field" class="tsd-widget search no-caption">Search</label> <input id="tsd-search-field" type="text" /> </div> <ul class="results"> <li class="state loading">Preparing search index...</li> <li class="state failure">The search index is not available</li> </ul> <a href="../index.html" class="title">argon.js</a> </div> <div class="table-cell" id="tsd-widgets"> <div id="tsd-filter"> <a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a> <div class="tsd-filter-group"> <div class="tsd-select" id="tsd-filter-visibility"> <span class="tsd-select-label">All</span> <ul class="tsd-select-list"> <li data-value="public">Public</li> <li data-value="protected">Public/Protected</li> <li data-value="private" class="selected">All</li> </ul> </div> <input type="checkbox" id="tsd-filter-inherited" checked /> <label class="tsd-widget" for="tsd-filter-inherited">Inherited</label> </div> </div> <a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a> </div> </div> </div> </div> <div class="tsd-page-title"> <div class="container"> <ul class="tsd-breadcrumb"> <li> <a href="../globals.html">Globals</a> </li> <li> <a href="messageeventlike.html">MessageEventLike</a> </li> </ul> <h1>Class MessageEventLike</h1> </div> </div> </header> <div class="container container-main"> <div class="row"> <div class="col-8 col-content"> <section class="tsd-panel tsd-comment"> <div class="tsd-comment tsd-typography"> <div class="lead"> <p>A minimal MessageEvent interface.</p> </div> </div> </section> <section class="tsd-panel tsd-hierarchy"> <h3>Hierarchy</h3> <ul class="tsd-hierarchy"> <li> <span class="target">MessageEventLike</span> </li> </ul> </section> <section class="tsd-panel-group tsd-index-group"> <h2>Index</h2> <section class="tsd-panel tsd-index-panel"> <div class="tsd-index-content"> <section class="tsd-index-section "> <h3>Constructors</h3> <ul class="tsd-index-list"> <li class="tsd-kind-constructor tsd-parent-kind-class"><a href="messageeventlike.html#constructor" class="tsd-kind-icon">constructor</a></li> </ul> </section> <section class="tsd-index-section "> <h3>Properties</h3> <ul class="tsd-index-list"> <li class="tsd-kind-property tsd-parent-kind-class"><a href="messageeventlike.html#data" class="tsd-kind-icon">data</a></li> </ul> </section> </div> </section> </section> <section class="tsd-panel-group tsd-member-group "> <h2>Constructors</h2> <section class="tsd-panel tsd-member tsd-kind-constructor tsd-parent-kind-class"> <a name="constructor" class="tsd-anchor"></a> <h3>constructor</h3> <ul class="tsd-signatures tsd-kind-constructor tsd-parent-kind-class"> <li class="tsd-signature tsd-kind-icon">new <wbr>Message<wbr>Event<wbr>Like<span class="tsd-signature-symbol">(</span>data<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">any</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="messageeventlike.html" class="tsd-signature-type">MessageEventLike</a></li> </ul> <ul class="tsd-descriptions"> <li class="tsd-description"> <aside class="tsd-sources"> <ul> <li>Defined in <a href="https://github.com/argonjs/argon/blob/2ce0501/src/utils/message-channel.ts#L5">src/utils/message-channel.ts:5</a></li> </ul> </aside> <h4 class="tsd-parameters-title">Parameters</h4> <ul class="tsd-parameters"> <li> <h5>data: <span class="tsd-signature-type">any</span></h5> </li> </ul> <h4 class="tsd-returns-title">Returns <a href="messageeventlike.html" class="tsd-signature-type">MessageEventLike</a></h4> </li> </ul> </section> </section> <section class="tsd-panel-group tsd-member-group "> <h2>Properties</h2> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class"> <a name="data" class="tsd-anchor"></a> <h3>data</h3> <div class="tsd-signature tsd-kind-icon">data<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">any</span></div> <aside class="tsd-sources"> <ul> <li>Defined in <a href="https://github.com/argonjs/argon/blob/2ce0501/src/utils/message-channel.ts#L7">src/utils/message-channel.ts:7</a></li> </ul> </aside> </section> </section> </div> <div class="col-4 col-menu menu-sticky-wrap menu-highlight"> <nav class="tsd-navigation primary"> <ul> <li class="globals "> <a href="../globals.html"><em>Globals</em></a> </li> </ul> </nav> <nav class="tsd-navigation secondary menu-sticky"> <ul class="before-current"> </ul> <ul class="current"> <li class="current tsd-kind-class"> <a href="messageeventlike.html" class="tsd-kind-icon">Message<wbr>Event<wbr>Like</a> <ul> <li class=" tsd-kind-constructor tsd-parent-kind-class"> <a href="messageeventlike.html#constructor" class="tsd-kind-icon">constructor</a> </li> <li class=" tsd-kind-property tsd-parent-kind-class"> <a href="messageeventlike.html#data" class="tsd-kind-icon">data</a> </li> </ul> </li> </ul> <ul class="after-current"> </ul> </nav> </div> </div> </div> <footer class="with-border-bottom"> <div class="container"> <h2>Legend</h2> <div class="tsd-legend-group"> <ul class="tsd-legend"> <li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li> <li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li> <li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li> <li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li> <li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li> <li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li> <li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li> <li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li> <li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li> <li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li> <li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li> </ul> </div> </div> </footer> <div class="container tsd-generator"> <p>Generated using <a href="http://typedoc.org/" target="_blank">TypeDoc</a></p> </div> <div class="overlay"></div> <script src="../assets/js/main.js"></script> <script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-63191442-2', ''); ga('send', 'pageview'); </script> </body> </html>
apache-2.0
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/hierarchy/TypeHierarchyBrowserBase.java
6301
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.hierarchy; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.ide.DeleteProvider; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.DeleteHandler; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.ui.PopupHandler; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; public abstract class TypeHierarchyBrowserBase extends HierarchyBrowserBaseEx { public static final String TYPE_HIERARCHY_TYPE = "Class {0}"; public static final String SUBTYPES_HIERARCHY_TYPE = "Subtypes of {0}"; public static final String SUPERTYPES_HIERARCHY_TYPE = "Supertypes of {0}"; private boolean myIsInterface; private final MyDeleteProvider myDeleteElementProvider = new MyDeleteProvider(); public TypeHierarchyBrowserBase(Project project, PsiElement element) { super(project, element); } protected abstract boolean isInterface(@NotNull PsiElement psiElement); protected void createTreeAndSetupCommonActions(@NotNull Map<? super @Nls String, ? super JTree> trees, @NotNull String groupId) { BaseOnThisTypeAction baseOnThisTypeAction = createBaseOnThisAction(); JTree tree1 = createTree(true); PopupHandler.installPopupMenu(tree1, groupId, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP); baseOnThisTypeAction .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree1); trees.put(getTypeHierarchyType(), tree1); JTree tree2 = createTree(true); PopupHandler.installPopupMenu(tree2, groupId, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP); baseOnThisTypeAction .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree2); trees.put(getSupertypesHierarchyType(), tree2); JTree tree3 = createTree(true); PopupHandler.installPopupMenu(tree3, groupId, ActionPlaces.TYPE_HIERARCHY_VIEW_POPUP); baseOnThisTypeAction .registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_TYPE_HIERARCHY).getShortcutSet(), tree3); trees.put(getSubtypesHierarchyType(), tree3); } @NotNull protected BaseOnThisTypeAction createBaseOnThisAction() { return new BaseOnThisTypeAction(); } protected abstract boolean canBeDeleted(PsiElement psiElement); protected abstract String getQualifiedName(PsiElement psiElement); @Override protected @NotNull Map<String, Supplier<String>> getPresentableNameMap() { HashMap<String, Supplier<String>> map = new HashMap<>(); map.put(TYPE_HIERARCHY_TYPE, TypeHierarchyBrowserBase::getTypeHierarchyType); map.put(SUBTYPES_HIERARCHY_TYPE, TypeHierarchyBrowserBase::getSubtypesHierarchyType); map.put(SUPERTYPES_HIERARCHY_TYPE, TypeHierarchyBrowserBase::getSupertypesHierarchyType); return map; } public boolean isInterface() { return myIsInterface; } @Override protected void setHierarchyBase(@NotNull PsiElement element) { super.setHierarchyBase(element); myIsInterface = isInterface(element); } @Override protected void prependActions(@NotNull DefaultActionGroup actionGroup) { actionGroup.add(new ViewClassHierarchyAction()); actionGroup.add(new ViewSupertypesHierarchyAction()); actionGroup.add(new ViewSubtypesHierarchyAction()); actionGroup.add(new AlphaSortAction()); } @Override @NotNull protected String getActionPlace() { return ActionPlaces.TYPE_HIERARCHY_VIEW_TOOLBAR; } @Override public final Object getData(@NotNull String dataId) { if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { return myDeleteElementProvider; } return super.getData(dataId); } @Override @NotNull protected String getPrevOccurenceActionNameImpl() { return IdeBundle.message("hierarchy.type.prev.occurence.name"); } @Override @NotNull protected String getNextOccurenceActionNameImpl() { return IdeBundle.message("hierarchy.type.next.occurence.name"); } private final class MyDeleteProvider implements DeleteProvider { @Override public void deleteElement(@NotNull DataContext dataContext) { PsiElement aClass = getSelectedElement(); if (!canBeDeleted(aClass)) return; LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting.class", getQualifiedName(aClass))); try { PsiElement[] elements = {aClass}; DeleteHandler.deletePsiElement(elements, myProject); } finally { a.finish(); } } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { PsiElement aClass = getSelectedElement(); if (!canBeDeleted(aClass)) { return false; } PsiElement[] elements = {aClass}; return DeleteHandler.shouldEnableDeleteAction(elements); } } protected static class BaseOnThisTypeAction extends BaseOnThisElementAction { public BaseOnThisTypeAction() { super(IdeBundle.messagePointer("action.base.on.this.class"), LanguageTypeHierarchy.INSTANCE); } @Override @Nls protected String correctViewType(@NotNull HierarchyBrowserBaseEx browser, @Nls String viewType) { if (((TypeHierarchyBrowserBase)browser).myIsInterface && getTypeHierarchyType().equals(viewType)) { return getSubtypesHierarchyType(); } return viewType; } } public static @Nls String getTypeHierarchyType() { //noinspection UnresolvedPropertyKey return IdeBundle.message("title.hierarchy.class"); } @Nls public static String getSubtypesHierarchyType() { //noinspection UnresolvedPropertyKey return IdeBundle.message("title.hierarchy.subtypes"); } public static @Nls String getSupertypesHierarchyType() { //noinspection UnresolvedPropertyKey return IdeBundle.message("title.hierarchy.supertypes"); } }
apache-2.0
patrickfav/tuwien
master/SB_task2/src/exceptions/IDaoSaveException.java
325
package exceptions; public class IDaoSaveException extends Exception{ private static final long serialVersionUID = 8041577551538125989L; public IDaoSaveException() { super(); } public IDaoSaveException(String msg) { super(msg); } public IDaoSaveException(String msg,Throwable cause) { super(msg,cause); } }
apache-2.0
bytescout/ByteScout-SDK-SourceCode
Barcode Suite/Delphi/Generate barcode from console with barcode sdk/README.md
18618
## How to generate barcode from console with barcode sdk in Delphi with ByteScout Barcode Suite ### Step-by-step tutorial on how to generate barcode from console with barcode sdk in Delphi The sample source code below will teach you how to generate barcode from console with barcode sdk in Delphi. ByteScout Barcode Suite can generate barcode from console with barcode sdk. It can be applied from Delphi. ByteScout Barcode Suite is the set that includes three different SDK products to generate barcodes, read barcodes and read and write spreadsheets: Barcode SDK, Barcode Reader SDK and Spreadsheet SDK. Want to save time? You will save a lot of time on writing and testing code as you may just take the Delphi code from ByteScout Barcode Suite for generate barcode from console with barcode sdk below and use it in your application. This Delphi sample code is all you need for your app. Just copy and paste the code, add references (if needs to) and you are all set! Enjoy writing a code with ready-to-use sample Delphi codes. The trial version of ByteScout Barcode Suite can be downloaded for free from our website. It also includes source code samples for Delphi and other programming languages. ## REQUEST FREE TECH SUPPORT [Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Barcode%20Suite%20Question) or just send email to [[email protected]](mailto:[email protected]?subject=ByteScout%20Barcode%20Suite%20Question) ## ON-PREMISE OFFLINE SDK [Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme) [Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme) [Sign Up For Online Training](https://academy.bytescout.com/) ## ON-DEMAND REST WEB API [Get your API key](https://pdf.co/documentation/api?utm_source=github-readme) [Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme) [Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API) ## VIDEO REVIEW [https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8) <!-- code block begin --> ##### ****Project1.bdsproj:** ``` <?xml version="1.0" encoding="utf-8"?> <BorlandProject> <PersonalityInfo> <Option> <Option Name="Personality">Delphi.Personality</Option> <Option Name="ProjectType"></Option> <Option Name="Version">1.0</Option> <Option Name="GUID">{2168453D-CDA3-43AE-A177-0DDAEFD0CDF0}</Option> </Option> </PersonalityInfo> <Delphi.Personality> <Source> <Source Name="MainSource">Project1.dpr</Source> </Source> <FileVersion> <FileVersion Name="Version">7.0</FileVersion> </FileVersion> <Compiler> <Compiler Name="A">8</Compiler> <Compiler Name="B">0</Compiler> <Compiler Name="C">1</Compiler> <Compiler Name="D">1</Compiler> <Compiler Name="E">0</Compiler> <Compiler Name="F">0</Compiler> <Compiler Name="G">1</Compiler> <Compiler Name="H">1</Compiler> <Compiler Name="I">1</Compiler> <Compiler Name="J">0</Compiler> <Compiler Name="K">0</Compiler> <Compiler Name="L">1</Compiler> <Compiler Name="M">0</Compiler> <Compiler Name="N">1</Compiler> <Compiler Name="O">1</Compiler> <Compiler Name="P">1</Compiler> <Compiler Name="Q">0</Compiler> <Compiler Name="R">0</Compiler> <Compiler Name="S">0</Compiler> <Compiler Name="T">0</Compiler> <Compiler Name="U">0</Compiler> <Compiler Name="V">1</Compiler> <Compiler Name="W">0</Compiler> <Compiler Name="X">1</Compiler> <Compiler Name="Y">1</Compiler> <Compiler Name="Z">1</Compiler> <Compiler Name="ShowHints">True</Compiler> <Compiler Name="ShowWarnings">True</Compiler> <Compiler Name="UnitAliases">WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE;</Compiler> <Compiler Name="NamespacePrefix"></Compiler> <Compiler Name="GenerateDocumentation">False</Compiler> <Compiler Name="DefaultNamespace"></Compiler> <Compiler Name="SymbolDeprecated">True</Compiler> <Compiler Name="SymbolLibrary">True</Compiler> <Compiler Name="SymbolPlatform">True</Compiler> <Compiler Name="SymbolExperimental">True</Compiler> <Compiler Name="UnitLibrary">True</Compiler> <Compiler Name="UnitPlatform">True</Compiler> <Compiler Name="UnitDeprecated">True</Compiler> <Compiler Name="UnitExperimental">True</Compiler> <Compiler Name="HResultCompat">True</Compiler> <Compiler Name="HidingMember">True</Compiler> <Compiler Name="HiddenVirtual">True</Compiler> <Compiler Name="Garbage">True</Compiler> <Compiler Name="BoundsError">True</Compiler> <Compiler Name="ZeroNilCompat">True</Compiler> <Compiler Name="StringConstTruncated">True</Compiler> <Compiler Name="ForLoopVarVarPar">True</Compiler> <Compiler Name="TypedConstVarPar">True</Compiler> <Compiler Name="AsgToTypedConst">True</Compiler> <Compiler Name="CaseLabelRange">True</Compiler> <Compiler Name="ForVariable">True</Compiler> <Compiler Name="ConstructingAbstract">True</Compiler> <Compiler Name="ComparisonFalse">True</Compiler> <Compiler Name="ComparisonTrue">True</Compiler> <Compiler Name="ComparingSignedUnsigned">True</Compiler> <Compiler Name="CombiningSignedUnsigned">True</Compiler> <Compiler Name="UnsupportedConstruct">True</Compiler> <Compiler Name="FileOpen">True</Compiler> <Compiler Name="FileOpenUnitSrc">True</Compiler> <Compiler Name="BadGlobalSymbol">True</Compiler> <Compiler Name="DuplicateConstructorDestructor">True</Compiler> <Compiler Name="InvalidDirective">True</Compiler> <Compiler Name="PackageNoLink">True</Compiler> <Compiler Name="PackageThreadVar">True</Compiler> <Compiler Name="ImplicitImport">True</Compiler> <Compiler Name="HPPEMITIgnored">True</Compiler> <Compiler Name="NoRetVal">True</Compiler> <Compiler Name="UseBeforeDef">True</Compiler> <Compiler Name="ForLoopVarUndef">True</Compiler> <Compiler Name="UnitNameMismatch">True</Compiler> <Compiler Name="NoCFGFileFound">True</Compiler> <Compiler Name="ImplicitVariants">True</Compiler> <Compiler Name="UnicodeToLocale">True</Compiler> <Compiler Name="LocaleToUnicode">True</Compiler> <Compiler Name="ImagebaseMultiple">True</Compiler> <Compiler Name="SuspiciousTypecast">True</Compiler> <Compiler Name="PrivatePropAccessor">True</Compiler> <Compiler Name="UnsafeType">False</Compiler> <Compiler Name="UnsafeCode">False</Compiler> <Compiler Name="UnsafeCast">False</Compiler> <Compiler Name="OptionTruncated">True</Compiler> <Compiler Name="WideCharReduced">True</Compiler> <Compiler Name="DuplicatesIgnored">True</Compiler> <Compiler Name="UnitInitSeq">True</Compiler> <Compiler Name="LocalPInvoke">True</Compiler> <Compiler Name="MessageDirective">True</Compiler> <Compiler Name="CodePage"></Compiler> </Compiler> <Linker> <Linker Name="MapFile">0</Linker> <Linker Name="OutputObjs">0</Linker> <Linker Name="GenerateHpps">False</Linker> <Linker Name="ConsoleApp">1</Linker> <Linker Name="DebugInfo">False</Linker> <Linker Name="RemoteSymbols">False</Linker> <Linker Name="GenerateDRC">False</Linker> <Linker Name="MinStackSize">16384</Linker> <Linker Name="MaxStackSize">1048576</Linker> <Linker Name="ImageBase">4194304</Linker> <Linker Name="ExeDescription"></Linker> </Linker> <Directories> <Directories Name="OutputDir"></Directories> <Directories Name="UnitOutputDir"></Directories> <Directories Name="PackageDLLOutputDir"></Directories> <Directories Name="PackageDCPOutputDir"></Directories> <Directories Name="SearchPath"></Directories> <Directories Name="Packages"></Directories> <Directories Name="Conditionals"></Directories> <Directories Name="DebugSourceDirs"></Directories> <Directories Name="UsePackages">False</Directories> </Directories> <Parameters> <Parameters Name="RunParams"></Parameters> <Parameters Name="HostApplication"></Parameters> <Parameters Name="Launcher"></Parameters> <Parameters Name="UseLauncher">False</Parameters> <Parameters Name="DebugCWD"></Parameters> <Parameters Name="Debug Symbols Search Path"></Parameters> <Parameters Name="LoadAllSymbols">True</Parameters> <Parameters Name="LoadUnspecifiedSymbols">False</Parameters> </Parameters> <Language> <Language Name="ActiveLang"></Language> <Language Name="ProjectLang">$00000000</Language> <Language Name="RootDir"></Language> </Language> <VersionInfo> <VersionInfo Name="IncludeVerInfo">False</VersionInfo> <VersionInfo Name="AutoIncBuild">False</VersionInfo> <VersionInfo Name="MajorVer">1</VersionInfo> <VersionInfo Name="MinorVer">0</VersionInfo> <VersionInfo Name="Release">0</VersionInfo> <VersionInfo Name="Build">0</VersionInfo> <VersionInfo Name="Debug">False</VersionInfo> <VersionInfo Name="PreRelease">False</VersionInfo> <VersionInfo Name="Special">False</VersionInfo> <VersionInfo Name="Private">False</VersionInfo> <VersionInfo Name="DLL">False</VersionInfo> <VersionInfo Name="Locale">1049</VersionInfo> <VersionInfo Name="CodePage">1251</VersionInfo> </VersionInfo> <VersionInfoKeys> <VersionInfoKeys Name="CompanyName"></VersionInfoKeys> <VersionInfoKeys Name="FileDescription"></VersionInfoKeys> <VersionInfoKeys Name="FileVersion">1.0.0.0</VersionInfoKeys> <VersionInfoKeys Name="InternalName"></VersionInfoKeys> <VersionInfoKeys Name="LegalCopyright"></VersionInfoKeys> <VersionInfoKeys Name="LegalTrademarks"></VersionInfoKeys> <VersionInfoKeys Name="OriginalFilename"></VersionInfoKeys> <VersionInfoKeys Name="ProductName"></VersionInfoKeys> <VersionInfoKeys Name="ProductVersion">1.0.0.0</VersionInfoKeys> <VersionInfoKeys Name="Comments"></VersionInfoKeys> </VersionInfoKeys> <Excluded_Packages> <Excluded_Packages Name="c:\program files\borland\bds\4.0\Bin\bcbie100.bpl">Borland C++Builder Internet Explorer 5 Components Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\DSPack_D2006.bpl">DSPack 2.3: Multimedia Package for Delphi</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\DirectX9_D2006.bpl">DirectX 9 Headers</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\SynEdit_R2005.bpl">SynEdit component suite runtime</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\tntExtendedEditors.bpl">TNT Extended Editors by lummie.co.uk</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\VirtualTreesD10.bpl">Virtual Treeview runtime package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\TntUnicodeVcl100.bpl">TntWare Unicode Controls - Runtime</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\Jcl100.bpl">JEDI Code Library RTL package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JclVcl100.bpl">JEDI Code Library VCL package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvCoreD10R.bpl">JVCL Core Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvSystemD10R.bpl">JVCL System Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvStdCtrlsD10R.bpl">JVCL Standard Controls Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvAppFrmD10R.bpl">JVCL Application and Form Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvCtrlsD10R.bpl">JVCL Visual Controls Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvBandsD10R.bpl">JVCL Band Objects Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvDBD10R.bpl">JVCL Database Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvDlgsD10R.bpl">JVCL Dialog Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvCustomD10R.bpl">JVCL Custom Controls Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvBDED10R.bpl">JVCL BDE Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvCmpD10R.bpl">JVCL Non-Visual Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvCryptD10R.bpl">JVCL Encryption and Compression Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvDockingD10R.bpl">JVCL Docking Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvDotNetCtrlsD10R.bpl">JVCL DotNet Controls Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvEDID10R.bpl">JVCL EDI Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvGlobusD10R.bpl">JVCL Globus Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvHMID10R.bpl">JVCL HMI Controls Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvInterpreterD10R.bpl">JVCL Interpreter Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvJansD10R.bpl">JVCL Jans Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvManagedThreadsD10R.bpl">JVCL Managed Threads Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvMMD10R.bpl">JVCL Multimedia and Image Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvNetD10R.bpl">JVCL Network Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvPageCompsD10R.bpl">JVCL Page Style Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvPluginD10R.bpl">JVCL Plugin Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvPrintPreviewD10R.bpl">JVCL Print Preview Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvRuntimeDesignD10R.bpl">JVCL Runtime Design Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvTimeFrameworkD10R.bpl">JVCL Time Framework Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvValidatorsD10R.bpl">JVCL Validators and Error Provider Components Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvWizardD10R.bpl">JVCL Wizard Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\JvXPCtrlsD10R.bpl">JVCL XP Controls Runtime Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\dklang10.bpl">DKLang Localization Package</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\tbx_d10.bpl">Toolbar2000 -- TBX Extensions (Alex Denisov)</Excluded_Packages> <Excluded_Packages Name="X:\My_projects\CODE\delphi-compo\bpl\tb2k_d10.bpl">Toolbar2000 Components (Jordan Russell)</Excluded_Packages> <Excluded_Packages Name="c:\program files\borland\bds\4.0\Bin\dclie100.bpl">Internet Explorer Components</Excluded_Packages> </Excluded_Packages> </Delphi.Personality> <StarTeamAssociation></StarTeamAssociation> <StarTeamNonRelativeFiles></StarTeamNonRelativeFiles> </BorlandProject> ``` <!-- code block end --> <!-- code block begin --> ##### ****Project1.dpr:** ``` //******************************************************************* // ByteScout BarCode SDK // // Copyright © 2016 ByteScout - http://www.bytescout.com // ALL RIGHTS RESERVED // //******************************************************************* { IMPORTANT: To work with Bytescout BarCode SDK you need to import this as a component into Delphi To import Bytescout BarCode SDK into Delphi 5 or higher to the following: 1) Click Component | Import ActiveX control 2) Find and select Bytescout BarCode SDK in the list of available type libraries and 4) Click Next 5) Select "Add Bytescout_BarCode_TLB.pas" into Project" and click Finish To import Bytescout BarCode SDK into Delphi 2006 or higher do the following: 1) Click Component | Import Component.. 2) Select Type Library and click Next 3) Find and select Bytescout BarCode SDK in the list of available type libraries and 4) Click Next 5) Click Next on next screen 6) Select "Add Bytescout_BarCode_TLB.pas" into Project" and click Finish This will add Bytescout_BarCode_TLB.pas into your project and now you can use BarCode object interface (_BarCode class) } program Project1; {$APPTYPE CONSOLE} uses SysUtils, ActiveX, // required for ActiveX support Bytescout_BarCode_TLB in 'C:\Program Files\Borland\BDS\4.0\Imports\Bytescout_BarCode_TLB.pas'; var bc: _Barcode; begin CoInitialize(nil); // required for console applications, initializes ActiveX support // create barcode object using CoBarCode class bc:= CoBarCode.Create(); // set symbology to Code39 bc.Symbology := SymbologyType_Code39; // set barcode value bc.Value:= '12345'; // save into PNG image bc.SaveImage('Code39.png'); // free barcode object by setting to nil bc:= nil; CoUninitialize(); // required for console applications, initializes ActiveX support end. ``` <!-- code block end -->
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Loranthaceae/Aetanthus/Aetanthus engelsii/README.md
174
# Aetanthus engelsii Engl. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Rhodophyta/Florideophyceae/Palmariales/Palmariaceae/Palmaria/Palmaria palmata/ Syn. Rhodymenia palmata sarniensis/README.md
207
# Rhodymenia palmata var. sarniensis (Roth) Greville VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Dendrobium/Dendrobium sinuosum/ Syn. Aporum sinuosum/README.md
189
# Aporum sinuosum (Ames) M.A.Clem. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Camaridium/Camaridium vestitum/ Syn. Ornithidium parviflorum/README.md
205
# Ornithidium parviflorum (Poepp. & Endl.) Rchb.f. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Spermacoce/Spermacoce stachydea/ Syn. Borreria stachydea phyllocephala/README.md
194
# Borreria stachydea var. phyllocephala VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Mespilus/Mespilus quitensis/README.md
175
# Mespilus quitensis K.Koch SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Septoria/Septoriopsis citri/README.md
248
# Septoriopsis citri Gonz. Frag. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Boln de la Real Soc. Españ. Hist. Nat. , Madrid 15: 127 (1915) #### Original name Septoriopsis citri Gonz. Frag. ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Crassulaceae/Sedum/Sedum wuianum/README.md
171
# Sedum wuianum K.S.Hao SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0