code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/** * FeedMappingStatus.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.v201402.cm; public class FeedMappingStatus implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected FeedMappingStatus(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _ACTIVE = "ACTIVE"; public static final java.lang.String _DELETED = "DELETED"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final FeedMappingStatus ACTIVE = new FeedMappingStatus(_ACTIVE); public static final FeedMappingStatus DELETED = new FeedMappingStatus(_DELETED); public static final FeedMappingStatus UNKNOWN = new FeedMappingStatus(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static FeedMappingStatus fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { FeedMappingStatus enumeration = (FeedMappingStatus) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static FeedMappingStatus fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} 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.EnumSerializer( _javaType, _xmlType); } 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.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(FeedMappingStatus.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201402", "FeedMapping.Status")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
nafae/developer
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201402/cm/FeedMappingStatus.java
Java
apache-2.0
2,919
package strd.tcp import org.jboss.netty.channel._ import org.slf4j.LoggerFactory import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory import java.util.concurrent.Executors import org.jboss.netty.bootstrap.ServerBootstrap import scala.Some import java.net.InetSocketAddress import com.twitter.ostrich.admin.Service import strd.util.IntegerParam /** * $Id$ * $URL$ * User: bulay * Date: 4/11/13 * Time: 5:31 PM */ class TcpServer(val port : Int, val pipelineFactory : ChannelPipelineFactory) extends Service { val log = LoggerFactory.getLogger(getClass) var channel : Option[Channel] = None val MAX_PACKET_SIZE = 512 * 1024 * 1024; //512 Kb val threads = Runtime.getRuntime.availableProcessors / 2 + 1 val factory: NioServerSocketChannelFactory = new NioServerSocketChannelFactory( Executors.newFixedThreadPool(2), Executors.newFixedThreadPool(threads), threads ) val bootstrap = new ServerBootstrap( factory) bootstrap.setPipelineFactory( pipelineFactory ) // bootstrap.setOption( "child.tcpNoDelay", true ) // bootstrap.setOption( "child.keepAlive", true ) bootstrap.setOption( "child.connectTimeoutMillis", 6000 ) // bootstrap.setOption( "reuseAddress", true ) bootstrap.setOption( "backlog", 64000 ) def stop() { channel.foreach(ch =>{ log.debug("Server stopping...") ch.close() ch.unbind() factory.releaseExternalResources() log.info("Server stopped") }) } def start() { channel = Some( bootstrap.bind( new InetSocketAddress(port) ) ) log.info("Server Started: " + port) } override def quiesce() { log.debug(s"\t--\tquiesce TcpServer on port $port") } def shutdown() { log.debug(s"\t--\tstop TcpServer on port $port") stop() } }
onerinvestments/strd
strd-commons/src/main/scala/strd/tcp/TcpServer.scala
Scala
apache-2.0
1,797
package com.google.api.ads.adwords.jaxws.v201402.cm; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PagingError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="PagingError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="START_INDEX_CANNOT_BE_NEGATIVE"/> * &lt;enumeration value="NUMBER_OF_RESULTS_CANNOT_BE_NEGATIVE"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "PagingError.Reason") @XmlEnum public enum PagingErrorReason { START_INDEX_CANNOT_BE_NEGATIVE, NUMBER_OF_RESULTS_CANNOT_BE_NEGATIVE, /** * * <span class="constraint Rejected">Used for return value only. An enumeration could not be processed, typically due to incompatibility with your WSDL version.</span> * * */ UNKNOWN; public String value() { return name(); } public static PagingErrorReason fromValue(String v) { return valueOf(v); } }
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/cm/PagingErrorReason.java
Java
apache-2.0
1,220
/* * * Copyright (c) Lightstreamer Srl * * 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.lightstreamer.examples.rss_demo.adapters; import java.io.File; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.lightstreamer.adapters.metadata.LiteralBasedProvider; import com.lightstreamer.interfaces.metadata.CreditsException; import com.lightstreamer.interfaces.metadata.ItemsException; import com.lightstreamer.interfaces.metadata.MetadataProviderException; import com.lightstreamer.interfaces.metadata.NotificationException; public class RSSMetadataAdapter extends LiteralBasedProvider{ private static String RSS_NEWS_ITEM = "rss_items_"; private static String RSS_CONTROL_ITEM = "rss_info_"; /** * The associated feed to which messages will be forwarded; * it is the Data Adapter itself. */ private volatile RSSDataAdapter rssFeed; /** * Unique identification of the related RSS Data Adapter instance; * see feedMap on the RSSDataAdapter. */ private String adapterSetId; /** * Private logger; a specific "LS_demos_Logger.NewsAggregator.adapter" category * should be supplied by log4j configuration. */ private Logger logger; public RSSMetadataAdapter() { } public void init(Map params, File configDir) throws MetadataProviderException { //Call super's init method to handle basic Metadata Adapter features super.init(params,configDir); logger = LogManager.getLogger("LS_demos_Logger.NewsAggregator.adapter"); // Read the Adapter Set name, which is supplied by the Server as a parameter this.adapterSetId = (String) params.get("adapters_conf.id"); /* * Note: the RSSDataAdapter instance cannot be looked for * here to initialize the "rssFeed" variable, because the RSS * Data Adapter may not be loaded and initialized at this moment. * We need to wait until the first "sendMessage" occurrence; * then we can store the reference for later use. */ logger.info("RSSMetadataAdapter ready"); } public String[] getItems(String user, String session, String id) throws ItemsException { String[] broken = super.getItems(user, session, id); for (int i = 0; i < broken.length; i++) { broken[i] = convertRSSUserName(broken[i],session); } return broken; } private String convertRSSUserName(String item, String session) throws ItemsException { if (item.indexOf(RSS_NEWS_ITEM) == 0 || item.indexOf(RSS_CONTROL_ITEM) == 0) { if (item.indexOf("|") > -1) { throw new ItemsException("RSS user name must not contain the | character"); } return item + "_" + session; } return item; } /** * Triggered by a client "sendMessage" call. * The message encodes a chat message from the client. */ public void notifyUserMessage(String user, String session, String message) throws NotificationException, CreditsException { if (message == null) { logger.warn("Null message received"); throw new NotificationException("Null message received"); } //Split the string on the | character //The message must be of the form "RT|n|message" //(where n is the number that identifies the item //and message is the message to be published) String[] pieces = message.split("\\|"); this.loadRSSFeed(); this.handleRSSMessage(pieces,message,session); } private void loadRSSFeed() throws CreditsException { if (this.rssFeed == null) { try { // Get the RSSDataAdapter instance to bind it with this // Metadata Adapter and send chat messages through it this.rssFeed = RSSDataAdapter.feedMap.get(this.adapterSetId); } catch(Throwable t) { // It can happen if the RSS Data Adapter jar was not even // included in the Adapter Set lib directory (the RSS // Data Adapter could not be included in the Adapter Set as well) logger.error("RSSDataAdapter class was not loaded: " + t); throw new CreditsException(0, "No rss feed available", "No rss feed available"); } if (this.rssFeed == null) { // The feed is not yet available on the static map, maybe the // RSS Data Adapter was not included in the Adapter Set logger.error("RSSDataAdapter not found"); throw new CreditsException(0, "No rss feed available", "No rss feed available"); } } } private void handleRSSMessage(String[] pieces, String message, String session) throws NotificationException { if (pieces.length < 4) { logger.warn("Wrong message received: " + message); throw new NotificationException("Wrong message received"); } //Check the message, it must be of the form "RSS|ADD|user|url" //or "RSS|REM|user|url" if (pieces[0].equals("RSS")) { String user = pieces[2] + "_" + session; //is there a better way to do this? int otherLength = pieces[0].length() + pieces[1].length() + pieces[2].length() + 3; String feed = message.substring(otherLength); if (pieces[1].equals("ADD")) { try { if (!this.rssFeed.subscribeRSS(feed, user)) { logger.warn("Not valid user (" + session + "): " + message); throw new NotificationException("Not valid user: " + message); } } catch (ItemsException e) { logger.warn("Problems with message " + message + ": " + e.getMessage()); NotificationException ne = new NotificationException("Wrong message received"); ne.initCause(e); throw ne; } } else if(pieces[1].equals("REM")) { this.rssFeed.unsubscribeRSS(feed, user); } else { logger.warn("Wrong message received: " + message); throw new NotificationException("Wrong message received"); } } else { logger.warn("Wrong message received: " + message); throw new NotificationException("Wrong message received"); } } }
Lightstreamer/Lightstreamer-example-RSS-adapter-java
src/main/java/com/lightstreamer/examples/rss_demo/adapters/RSSMetadataAdapter.java
Java
apache-2.0
7,237
# Copyright 2018 Red Hat, Inc. # 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. from tempest.api.image import base from tempest.lib.common.utils import data_utils from tempest.lib import decorators class BasicOperationsImagesAdminTest(base.BaseV2ImageAdminTest): @decorators.related_bug('1420008') @decorators.idempotent_id('646a6eaa-135f-4493-a0af-12583021224e') def test_create_image_owner_param(self): # NOTE: Create image with owner different from tenant owner by # using "owner" parameter requires an admin privileges. random_id = data_utils.rand_uuid_hex() image = self.admin_client.create_image( container_format='bare', disk_format='raw', owner=random_id) self.addCleanup(self.admin_client.delete_image, image['id']) image_info = self.admin_client.show_image(image['id']) self.assertEqual(random_id, image_info['owner']) @decorators.related_bug('1420008') @decorators.idempotent_id('525ba546-10ef-4aad-bba1-1858095ce553') def test_update_image_owner_param(self): random_id_1 = data_utils.rand_uuid_hex() image = self.admin_client.create_image( container_format='bare', disk_format='raw', owner=random_id_1) self.addCleanup(self.admin_client.delete_image, image['id']) created_image_info = self.admin_client.show_image(image['id']) random_id_2 = data_utils.rand_uuid_hex() self.admin_client.update_image( image['id'], [dict(replace="/owner", value=random_id_2)]) updated_image_info = self.admin_client.show_image(image['id']) self.assertEqual(random_id_2, updated_image_info['owner']) self.assertNotEqual(created_image_info['owner'], updated_image_info['owner'])
masayukig/tempest
tempest/api/image/v2/admin/test_images.py
Python
apache-2.0
2,341
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2018 Fabian Prasser and contributors * * 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.deidentifier.arx.metric.v2; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.certificate.elements.ElementData; import org.deidentifier.arx.framework.lattice.Transformation; import org.deidentifier.arx.metric.MetricConfiguration; /** * This class provides an implementation of normalized non-uniform entropy. See:<br> * A. De Waal and L. Willenborg: * "Information loss through global recoding and local suppression" * Netherlands Off Stat, vol. 14, pp. 17–20, 1999. * * @author Fabian Prasser * @author Florian Kohlmayer */ public class MetricMDNUNMNormalizedEntropy extends MetricMDNUNMNormalizedEntropyPrecomputed { /** SVUID. */ private static final long serialVersionUID = 8815423510640657624L; /** * Creates a new instance. */ protected MetricMDNUNMNormalizedEntropy() { super(); } /** * Creates a new instance. * * @param function */ protected MetricMDNUNMNormalizedEntropy(AggregateFunction function){ super(function); } /** * Returns the configuration of this metric. * * @return */ public MetricConfiguration getConfiguration() { return new MetricConfiguration(false, // monotonic 0.5d, // gs-factor false, // precomputed 0.0d, // precomputation threshold this.getAggregateFunction() // aggregate function ); } @Override public String getName() { return "Normalized non-uniform entropy"; } @Override public ElementData render(ARXConfiguration config) { ElementData result = new ElementData("Normalized non-uniform entropy"); result.addProperty("Aggregate function", super.getAggregateFunction().toString()); result.addProperty("Monotonic", this.isMonotonic(config.getSuppressionLimit())); return result; } @Override public String toString() { return "Normalized non-uniform entropy"; } @Override protected AbstractILMultiDimensional getLowerBoundInternal(Transformation<?> node) { return null; } }
RaffaelBild/arx
src/main/org/deidentifier/arx/metric/v2/MetricMDNUNMNormalizedEntropy.java
Java
apache-2.0
3,033
package com.sarality.app.loader; import com.sarality.app.datastore.db.Table; import com.sarality.app.datastore.db.TableRegistry; import com.sarality.app.datastore.query.Query; import com.sarality.app.datastore.query.QueryBuilder; import java.util.List; /** * Utility class to load data from a Table. * * @param <T> Type of data returned by the Table. * @author abhideep@ (Abhidep Singh) */ public class TableDataLoader<T> { private final Table<T> table; private Query query; public TableDataLoader(String tableName, TableRegistry registry) { this.table = (Table<T>) registry.getTable(tableName); } public TableDataLoader(String tableName) { this(tableName, TableRegistry.getGlobalInstance()); } public TableDataLoader<T> setQuery(QueryBuilder builder) { if (builder == null) { query = null; } else { this.query = builder.build(); } return this; } public QueryBuilder newQuery() { return new QueryBuilder(table); } public List<T> loadAll() { try { table.open(); return table.query(query); } finally { table.close(); } } public T load() { List<T> dataList = loadAll(); if (dataList != null && dataList.size() == 1) { return dataList.get(0); } if (dataList != null && dataList.size() > 1) { throw new IllegalArgumentException("Query returned more than one result. Use loadAll instead"); } // If no data is returned then simply return null; return null; } }
sarality/appblocks
src/main/java/com/sarality/app/loader/TableDataLoader.java
Java
apache-2.0
1,507
/* Copyright 2019 The Skaffold 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 v1alpha4 import ( "testing" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v1alpha5" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" "github.com/GoogleContainerTools/skaffold/testutil" ) func TestUpgrade(t *testing.T) { yaml := `apiVersion: skaffold/v1alpha4 kind: Config build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* profiles: - name: test profile build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* ` expected := `apiVersion: skaffold/v1alpha5 kind: Config build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* profiles: - name: test profile build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* ` verifyUpgrade(t, yaml, expected) } func verifyUpgrade(t *testing.T, input, output string) { config := NewSkaffoldConfig() err := yaml.UnmarshalStrict([]byte(input), config) testutil.CheckErrorAndDeepEqual(t, false, err, Version, config.GetVersion()) upgraded, err := config.Upgrade() testutil.CheckError(t, false, err) expected := v1alpha5.NewSkaffoldConfig() err = yaml.UnmarshalStrict([]byte(output), expected) testutil.CheckErrorAndDeepEqual(t, false, err, expected, upgraded) }
GoogleContainerTools/skaffold
pkg/skaffold/schema/v1alpha4/upgrade_test.go
GO
apache-2.0
2,406
/* * Copyright (c) 2018 Nordic Semiconductor ASA * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef ZEPHYR_DRIVERS_ADC_ADC_CONTEXT_H_ #define ZEPHYR_DRIVERS_ADC_ADC_CONTEXT_H_ #include <adc.h> #include <atomic.h> #ifdef __cplusplus extern "C" { #endif struct adc_context; /* * Each driver should provide implementations of the following two functions: * - adc_context_start_sampling() that will be called when a sampling (of one * or more channels, depending on the realized sequence) is to be started * - adc_context_update_buffer_pointer() that will be called when the sample * buffer pointer should be prepared for writing of next sampling results, * the "repeat_sampling" parameter indicates if the results should be written * in the same place as before (when true) or as consecutive ones (otherwise). */ static void adc_context_start_sampling(struct adc_context *ctx); static void adc_context_update_buffer_pointer(struct adc_context *ctx, bool repeat_sampling); /* * If a given driver uses some dedicated hardware timer to trigger consecutive * samplings, it should implement also the following two functions. Otherwise, * it should define the ADC_CONTEXT_USES_KERNEL_TIMER macro to enable parts of * this module that utilize a standard kernel timer. */ static void adc_context_enable_timer(struct adc_context *ctx); static void adc_context_disable_timer(struct adc_context *ctx); struct adc_context { atomic_t sampling_requested; #ifdef ADC_CONTEXT_USES_KERNEL_TIMER struct k_timer timer; #endif /* ADC_CONTEXT_USES_KERNEL_TIMER */ struct k_sem lock; struct k_sem sync; int status; #ifdef CONFIG_ADC_ASYNC struct k_poll_signal *signal; bool asynchronous; #endif /* CONFIG_ADC_ASYNC */ const struct adc_sequence *sequence; u16_t sampling_index; }; #ifdef ADC_CONTEXT_USES_KERNEL_TIMER #define ADC_CONTEXT_INIT_TIMER(_data, _ctx_name) \ ._ctx_name.timer = _K_TIMER_INITIALIZER(_data._ctx_name.timer, \ adc_context_on_timer_expired, \ NULL) #endif /* ADC_CONTEXT_USES_KERNEL_TIMER */ #define ADC_CONTEXT_INIT_LOCK(_data, _ctx_name) \ ._ctx_name.lock = _K_SEM_INITIALIZER(_data._ctx_name.lock, 0, 1) #define ADC_CONTEXT_INIT_SYNC(_data, _ctx_name) \ ._ctx_name.sync = _K_SEM_INITIALIZER(_data._ctx_name.sync, 0, 1) static inline void adc_context_request_next_sampling(struct adc_context *ctx) { if (atomic_inc(&ctx->sampling_requested) == 0) { adc_context_start_sampling(ctx); } else { /* * If a sampling was already requested and was not finished yet, * do not start another one from here, this will be done from * adc_context_on_sampling_done() after the current sampling is * complete. Instead, note this fact, and inform the user about * it after the sequence is done. */ ctx->status = -EIO; } } #ifdef ADC_CONTEXT_USES_KERNEL_TIMER static inline void adc_context_enable_timer(struct adc_context *ctx) { u32_t interval_us = ctx->sequence->options->interval_us; u32_t interval_ms = ceiling_fraction(interval_us, 1000UL); k_timer_start(&ctx->timer, 0, interval_ms); } static inline void adc_context_disable_timer(struct adc_context *ctx) { k_timer_stop(&ctx->timer); } static void adc_context_on_timer_expired(struct k_timer *timer_id) { struct adc_context *ctx = CONTAINER_OF(timer_id, struct adc_context, timer); adc_context_request_next_sampling(ctx); } #endif /* ADC_CONTEXT_USES_KERNEL_TIMER */ static inline void adc_context_lock(struct adc_context *ctx, bool asynchronous, struct k_poll_signal *signal) { k_sem_take(&ctx->lock, K_FOREVER); #ifdef CONFIG_ADC_ASYNC ctx->asynchronous = asynchronous; ctx->signal = signal; #endif /* CONFIG_ADC_ASYNC */ } static inline void adc_context_release(struct adc_context *ctx, int status) { #ifdef CONFIG_ADC_ASYNC if (ctx->asynchronous && (status == 0)) { return; } #endif /* CONFIG_ADC_ASYNC */ k_sem_give(&ctx->lock); } static inline void adc_context_unlock_unconditionally(struct adc_context *ctx) { if (!k_sem_count_get(&ctx->lock)) { k_sem_give(&ctx->lock); } } static inline int adc_context_wait_for_completion(struct adc_context *ctx) { #ifdef CONFIG_ADC_ASYNC if (ctx->asynchronous) { return 0; } #endif /* CONFIG_ADC_ASYNC */ k_sem_take(&ctx->sync, K_FOREVER); return ctx->status; } static inline void adc_context_complete(struct adc_context *ctx, int status) { #ifdef CONFIG_ADC_ASYNC if (ctx->asynchronous) { if (ctx->signal) { k_poll_signal(ctx->signal, status); } k_sem_give(&ctx->lock); return; } #endif /* CONFIG_ADC_ASYNC */ /* * Override the status only when an error is signaled to this function. * Please note that adc_context_request_next_sampling() might have set * this field. */ if (status != 0) { ctx->status = status; } k_sem_give(&ctx->sync); } static inline void adc_context_start_read(struct adc_context *ctx, const struct adc_sequence *sequence) { ctx->sequence = sequence; ctx->status = 0; if (ctx->sequence->options) { ctx->sampling_index = 0; if (ctx->sequence->options->interval_us != 0) { atomic_set(&ctx->sampling_requested, 0); adc_context_enable_timer(ctx); return; } } adc_context_start_sampling(ctx); } /* * This function should be called after a sampling (of one or more channels, * depending on the realized sequence) is done. It calls the defined callback * function if required and takes further actions accordingly. */ static inline void adc_context_on_sampling_done(struct adc_context *ctx, struct device *dev) { if (ctx->sequence->options) { adc_sequence_callback callback = ctx->sequence->options->callback; enum adc_action action; bool finish = false; bool repeat = false; if (callback) { action = callback(dev, ctx->sequence, ctx->sampling_index); } else { action = ADC_ACTION_CONTINUE; } switch (action) { case ADC_ACTION_REPEAT: repeat = true; break; case ADC_ACTION_FINISH: finish = true; break; default: /* ADC_ACTION_CONTINUE */ if (ctx->sampling_index < ctx->sequence->options->extra_samplings) { ++ctx->sampling_index; } else { finish = true; } } if (!finish) { adc_context_update_buffer_pointer(ctx, repeat); /* * Immediately start the next sampling if working with * a zero interval or if the timer expired again while * the current sampling was in progress. */ if (ctx->sequence->options->interval_us == 0) { adc_context_start_sampling(ctx); } else if (atomic_dec(&ctx->sampling_requested) > 1) { adc_context_start_sampling(ctx); } return; } if (ctx->sequence->options->interval_us != 0) { adc_context_disable_timer(ctx); } } adc_context_complete(ctx, 0); } #ifdef __cplusplus } #endif #endif /* ZEPHYR_DRIVERS_ADC_ADC_CONTEXT_H_ */
kraj/zephyr
drivers/adc/adc_context.h
C
apache-2.0
6,862
DROP TABLE IF EXISTS system_user_schema.system_user_last_active; CREATE TABLE system_user_schema.system_user_last_active ( sysuser_id uuid NOT NULL PRIMARY KEY, login text NOT NULL, datetime_last_active timestamp without time zone NOT NULL, CONSTRAINT system_user_last_active_sysuser_id_fkey FOREIGN KEY (sysuser_id) REFERENCES system_user_schema.system_users (sysuser_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE CASCADE );
james-cantrill/funda_components
system_user/system_user_database/table_definitions/system_user_last_active.sql
SQL
apache-2.0
437
import tensorflow as tf from tensorflow.contrib import layers from tensorflow.contrib.framework import arg_scope from tensormate.graph import TfGgraphBuilder class ImageGraphBuilder(TfGgraphBuilder): def __init__(self, scope=None, device=None, plain=False, data_format="NHWC", data_format_ops=(layers.conv2d, layers.convolution2d, layers.convolution2d_transpose, layers.convolution2d_in_plane, layers.convolution2d_transpose, layers.conv2d_in_plane, layers.conv2d_transpose, layers.separable_conv2d, layers.separable_convolution2d, layers.avg_pool2d, layers.max_pool2d, layers.batch_norm)): super(ImageGraphBuilder, self).__init__(scope=scope, device=device, plain=plain) self.data_format = data_format self.data_format_ops = data_format_ops if data_format_ops is not None else [] def _call_body(self, *args, **kwargs): # is_training = kwargs.get("is_training", True) # reuse = self.ref_count > 0 with tf.variable_scope(self._scope, reuse=tf.AUTO_REUSE): with arg_scope(self.data_format_ops, data_format=self.data_format): if self._device is None: output = self._build(*args, **kwargs) else: with tf.device(self._device): output = self._build(*args, **kwargs) return output
songgc/tensormate
tensormate/graph/image_graph.py
Python
apache-2.0
1,742
#include "envoy/upstream/resource_manager.h" #include "envoy/upstream/upstream.h" #include "common/ssl/context_manager_impl.h" #include "common/stats/stats_impl.h" #include "server/config_validation/cluster_manager.h" #include "test/mocks/access_log/mocks.h" #include "test/mocks/event/mocks.h" #include "test/mocks/http/mocks.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/network/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/utility.h" namespace Envoy { namespace Upstream { TEST(ValidationClusterManagerTest, MockedMethods) { NiceMock<Runtime::MockLoader> runtime; Stats::IsolatedStoreImpl stats; NiceMock<ThreadLocal::MockInstance> tls; NiceMock<Runtime::MockRandomGenerator> random; auto dns_resolver = std::make_shared<NiceMock<Network::MockDnsResolver>>(); Ssl::ContextManagerImpl ssl_context_manager{runtime}; NiceMock<Event::MockDispatcher> dispatcher; LocalInfo::MockLocalInfo local_info; ValidationClusterManagerFactory factory(runtime, stats, tls, random, dns_resolver, ssl_context_manager, dispatcher, local_info); AccessLog::MockAccessLogManager log_manager; const envoy::api::v2::Bootstrap bootstrap; ClusterManagerPtr cluster_manager = factory.clusterManagerFromProto( bootstrap, stats, tls, runtime, random, local_info, log_manager); EXPECT_EQ(nullptr, cluster_manager->httpConnPoolForCluster("cluster", ResourcePriority::Default, nullptr)); Host::CreateConnectionData data = cluster_manager->tcpConnForCluster("cluster", nullptr); EXPECT_EQ(nullptr, data.connection_); EXPECT_EQ(nullptr, data.host_description_); Http::AsyncClient& client = cluster_manager->httpAsyncClientForCluster("cluster"); Http::MockAsyncClientStreamCallbacks stream_callbacks; EXPECT_EQ(nullptr, client.start(stream_callbacks, Optional<std::chrono::milliseconds>())); } } // namespace Upstream } // namespace Envoy
tdmackey/envoy
test/server/config_validation/cluster_manager_test.cc
C++
apache-2.0
2,043
/* * Copyright 2015 the original author or 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 org.springframework.cloud.stream.config; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.cloud.stream.annotation.Bindings; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.binder.BinderFactory; import org.springframework.cloud.stream.messaging.Source; import org.springframework.cloud.stream.test.binder.TestSupportBinder; import org.springframework.context.annotation.PropertySource; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Ilayaperumal Gopinathan */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration({ContentTypeOutboundSourceTests.TestSource.class}) public class ContentTypeOutboundSourceTests { @Autowired @Bindings(TestSource.class) private Source testSource; @Autowired private BinderFactory binderFactory; @Test public void testMessageHeaderWhenNoExplicitContentTypeOnMessage() throws Exception { testSource.output().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build()); Message<String> received = (Message<String>) ((TestSupportBinder) binderFactory.getBinder(null)).messageCollector().forChannel(testSource.output()).poll(); assertThat(received.getHeaders().get(MessageHeaders.CONTENT_TYPE).toString(), equalTo("application/json")); assertThat(received.getPayload(), equalTo("{\"message\":\"Hi\"}")); } @EnableBinding(Source.class) @EnableAutoConfiguration @PropertySource("classpath:/org/springframework/cloud/stream/config/channel/source-channel-configurers.properties") public static class TestSource { } }
pperalta/spring-cloud-stream
spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ContentTypeOutboundSourceTests.java
Java
apache-2.0
2,704
package com.james.status.fragments; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.james.status.R; import com.james.status.adapters.ArrayAdapter; public class HelpFragment extends SimpleFragment { private static final String COMMUNITY_URL = "https://plus.google.com/communities/100021389226995148571"; private ArrayAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_help, container, false); RecyclerView recycler = v.findViewById(R.id.recycler); recycler.setLayoutManager(new GridLayoutManager(getContext(), 1)); recycler.setNestedScrollingEnabled(false); adapter = new ArrayAdapter(getContext(), R.array.faq); recycler.setAdapter(adapter); v.findViewById(R.id.community).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(COMMUNITY_URL))); } }); return v; } @Override public void filter(@Nullable String filter) { if (adapter != null) adapter.filter(filter); } @Override public String getTitle(Context context) { return context.getString(R.string.tab_help); } }
TheAndroidMaster/Status
app/src/main/java/com/james/status/fragments/HelpFragment.java
Java
apache-2.0
1,719
/* * Copyright 2010 JBoss 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 org.drools.guvnor.server.selector; import org.drools.repository.AssetItem; import org.drools.repository.CategoryItem; import java.util.ArrayList; import java.util.List; public class BuiltInSelector implements AssetSelector { private String status; private String statusOperator; private String category; private String categoryOperator; private boolean enableStatusSelector; private boolean enableCategorySelector; private List<String> searchStatus; public BuiltInSelector() { } public boolean isEnableStatusSelector() { return enableStatusSelector; } public void setEnableStatusSelector(boolean enableStatusSelector) { this.enableStatusSelector = enableStatusSelector; } public boolean isEnableCategorySelector() { return enableCategorySelector; } public void setEnableCategorySelector(boolean enableCategorySelector) { this.enableCategorySelector = enableCategorySelector; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getCategoryOperator() { return categoryOperator; } public void setCategoryOperator(String categoryOperator) { this.categoryOperator = categoryOperator; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; this.searchStatus = extractListFromComaSeparated(this.status); } public String getStatusOperator() { return statusOperator; } public void setStatusOperator(String statusOperator) { this.statusOperator = statusOperator; } public boolean isAssetAllowed(AssetItem item) { if ( enableStatusSelector && enableCategorySelector ) { return (isStatusAllowed( item ) && isCategoryAllowed( item )); } else if ( enableStatusSelector ) { return isStatusAllowed( item ); } else if ( enableCategorySelector ) { return isCategoryAllowed( item ); } //allow everything if none enabled. return true; } private boolean isStatusAllowed(AssetItem item) { if ( "=".equals( statusOperator ) ) { if (searchStatus.contains(item.getStateDescription())){ return true; } } else if ( "!=".equals( statusOperator ) ) { if (!searchStatus.contains(item.getStateDescription())){ return true; } } return false; } public List<String> extractListFromComaSeparated(String status){ List<String> extractedList = new ArrayList<String>(); if (status!= null && status.length()> 0 ){ int firstIndex=0; int lastIndex= status.indexOf(",", firstIndex); while (lastIndex != -1){ String newStatus = status.substring(firstIndex, lastIndex); extractedList.add(newStatus); firstIndex = lastIndex+1; lastIndex = status.indexOf(",", firstIndex); } if (firstIndex > 0){ String newStatus = status.substring(firstIndex,status.length()); extractedList.add(newStatus); }else { extractedList.add(status); } } return extractedList; } private boolean isCategoryAllowed(AssetItem item) { if ( "=".equals( categoryOperator ) ) { for ( CategoryItem cat : item.getCategories() ) { if ( cat.getFullPath().equals( category ) ) { return true; } } } else if ( "!=".equals( categoryOperator ) ) { boolean categoryFound = false; for ( CategoryItem cat : item.getCategories() ) { if ( cat.getFullPath().equals( category ) ) { categoryFound = true; } } return !categoryFound; } return false; } }
cyberdrcarr/guvnor
guvnor-webapp-core/src/main/java/org/drools/guvnor/server/selector/BuiltInSelector.java
Java
apache-2.0
4,761
package weibo4j.examples.place; import weibo4j.Place; import weibo4j.examples.oauth2.Log; import weibo4j.model.Places; import weibo4j.model.WeiboException; import java.util.List; public class GetUserCheckins { public static void main(String[] args) { String access_token = args[0]; String uid = args[1]; Place p = new Place(access_token); try { List<Places> list = p.checkinsList(uid); for (Places pl : list) { Log.logInfo(pl.toString()); } } catch (WeiboException e) { e.printStackTrace(); } } }
jpbirdy/WordsDetection
weibo/src/main/java/weibo4j/examples/place/GetUserCheckins.java
Java
apache-2.0
657
package com.lerx.web.vo; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.lerx.article.dao.IArticleGroupDao; import com.lerx.article.dao.IArticleThreadDao; import com.lerx.attachment.dao.IAttachmentDao; import com.lerx.bbs.dao.IBbsBMDao; import com.lerx.bbs.dao.IBbsForumDao; import com.lerx.bbs.dao.IBbsInfoDao; import com.lerx.bbs.dao.IBbsThemeDao; import com.lerx.bbs.dao.IScoreGroupDao; import com.lerx.bbs.dao.IScoreSchemeDao; import com.lerx.bbs.vo.BbsInfo; import com.lerx.comment.dao.ICommentDao; import com.lerx.draw.dao.IDrawDao; import com.lerx.qa.dao.IQaItemDao; import com.lerx.qa.dao.IQaNavDao; import com.lerx.site.dao.ISiteInfoDao; import com.lerx.site.vo.SiteInfo; import com.lerx.style.bbs.dao.IBbsStyleDao; import com.lerx.style.bbs.vo.BbsStyle; import com.lerx.style.bbs.vo.BbsStyleSubElementInCommon; import com.lerx.style.draw.dao.IDrawStyleDao; import com.lerx.style.draw.vo.DrawStyle; import com.lerx.style.qa.dao.IQaStyleDao; import com.lerx.style.qa.vo.QaStyle; import com.lerx.style.qa.vo.QaStyleSubElementInCommon; import com.lerx.style.site.dao.ISiteStyleDao; import com.lerx.style.site.vo.SiteStyle; import com.lerx.style.site.vo.SiteStyleSubElementInCommon; import com.lerx.style.vote.dao.IVoteStyleDao; import com.lerx.style.vote.vo.VoteStyle; import com.lerx.style.vote.vo.VoteStyleSubElementInCommon; import com.lerx.sys.dao.IExternalHostCharsetDao; import com.lerx.sys.util.vo.CookieDoModel; import com.lerx.sys.util.vo.FormatElements; import com.lerx.sys.util.vo.UserCookie; import com.lerx.user.dao.IInterconnectionDao; import com.lerx.user.dao.IPasserDao; import com.lerx.user.dao.IUserArtsCountDao; import com.lerx.user.dao.IUserDao; import com.lerx.vote.dao.IVoteItemDao; import com.lerx.vote.dao.IVoteRecDao; import com.lerx.vote.dao.IVoteSubjectDao; import com.opensymphony.xwork2.ActionSupport; public class WebElements { private HttpServletRequest request; private HttpServletResponse response; private ActionSupport as; private ISiteInfoDao siteInfDaoImp; private ISiteStyleDao siteStyleDaoImp; private IBbsStyleDao bbsStyleDaoImp; private IArticleGroupDao articleGroupDaoImp; private IArticleThreadDao articleThreadDaoImp; private IBbsInfoDao bbsInfoDaoImp; private IBbsForumDao bbsForumDaoImp; private IBbsThemeDao bbsThemeDaoImp; private IBbsBMDao bbsBMDaoImp; private IUserDao userDaoImp; private IPasserDao passerDaoImp; private IInterconnectionDao interconnectionDaoImp; private IScoreSchemeDao scoreSchemeDaoImp; private IScoreGroupDao scoreGroupDaoImp; private IAttachmentDao attachmentDaoImp; private IQaStyleDao qaStyleDaoImp; private IQaItemDao qaItemDaoImp; private IQaNavDao qaNavDaoImp; private IVoteSubjectDao voteSubjectDaoImp; private IVoteItemDao voteItemDaoImp; private IVoteStyleDao voteStyleDaoImp; private IVoteRecDao voteRecDaoImp; private IDrawDao drawDaoImp; private IDrawStyleDao drawStyleDaoImp; private ICommentDao commentDaoImp; private IUserArtsCountDao userArtsCountDaoImp; private IExternalHostCharsetDao externalHostCharsetDaoImp; private SiteInfo site; private BbsInfo bi; private SiteStyle curSiteStyle; private BbsStyle curBbsStyle; private QaStyle curQaStyle; private VoteStyle curVoteStyle; private DrawStyle curDrawStyle; private SiteStyleSubElementInCommon sel; private BbsStyleSubElementInCommon bel; private QaStyleSubElementInCommon qel; private VoteStyleSubElementInCommon vel; private FormatElements fel; private String htmlTemplate; private String css; private String html; private String topCode; private String footerCode; private String titleFormat; private String hrefLineFormat; private String dateFormatOnLine; private String editAreaCode; private String searchAreaCode; private String functionAreaCode; private boolean refererRec; private String locationSplitStr; private UserCookie uc; private String shortSiteName; private String siteName; private String bbsName; private CookieDoModel cdm; private long pageStart; private long pageEnd; private long id; private int gid; private long tid; private long uid; private String pwd; private int mod; private int umode; private int smode; private int fid; private int stateMode; private boolean notice; private int soul; private int page; private int pageSize; private String key; private String keyCon; private int offset; private int station; private boolean toEnd; private int scrollPos; private boolean userLogined; private ResultEl re; private String msg; private int de; private FileReadArgs fra; public int getDe() { return de; } public void setDe(int de) { this.de = de; } public ActionSupport getAs() { return as; } public void setAs(ActionSupport as) { this.as = as; } public ISiteInfoDao getSiteInfDaoImp() { return siteInfDaoImp; } public void setSiteInfDaoImp(ISiteInfoDao siteInfDaoImp) { this.siteInfDaoImp = siteInfDaoImp; } public ISiteStyleDao getSiteStyleDaoImp() { return siteStyleDaoImp; } public void setSiteStyleDaoImp(ISiteStyleDao siteStyleDaoImp) { this.siteStyleDaoImp = siteStyleDaoImp; } public IBbsStyleDao getBbsStyleDaoImp() { return bbsStyleDaoImp; } public void setBbsStyleDaoImp(IBbsStyleDao bbsStyleDaoImp) { this.bbsStyleDaoImp = bbsStyleDaoImp; } public IArticleGroupDao getArticleGroupDaoImp() { return articleGroupDaoImp; } public void setArticleGroupDaoImp(IArticleGroupDao articleGroupDaoImp) { this.articleGroupDaoImp = articleGroupDaoImp; } public IArticleThreadDao getArticleThreadDaoImp() { return articleThreadDaoImp; } public void setArticleThreadDaoImp(IArticleThreadDao articleThreadDaoImp) { this.articleThreadDaoImp = articleThreadDaoImp; } public IBbsInfoDao getBbsInfoDaoImp() { return bbsInfoDaoImp; } public void setBbsInfoDaoImp(IBbsInfoDao bbsInfoDaoImp) { this.bbsInfoDaoImp = bbsInfoDaoImp; } public IBbsForumDao getBbsForumDaoImp() { return bbsForumDaoImp; } public void setBbsForumDaoImp(IBbsForumDao bbsForumDaoImp) { this.bbsForumDaoImp = bbsForumDaoImp; } public IBbsThemeDao getBbsThemeDaoImp() { return bbsThemeDaoImp; } public void setBbsThemeDaoImp(IBbsThemeDao bbsThemeDaoImp) { this.bbsThemeDaoImp = bbsThemeDaoImp; } public IBbsBMDao getBbsBMDaoImp() { return bbsBMDaoImp; } public void setBbsBMDaoImp(IBbsBMDao bbsBMDaoImp) { this.bbsBMDaoImp = bbsBMDaoImp; } public IUserDao getUserDaoImp() { return userDaoImp; } public void setUserDaoImp(IUserDao userDaoImp) { this.userDaoImp = userDaoImp; } public IPasserDao getPasserDaoImp() { return passerDaoImp; } public void setPasserDaoImp(IPasserDao passerDaoImp) { this.passerDaoImp = passerDaoImp; } public IInterconnectionDao getInterconnectionDaoImp() { return interconnectionDaoImp; } public void setInterconnectionDaoImp(IInterconnectionDao interconnectionDaoImp) { this.interconnectionDaoImp = interconnectionDaoImp; } public IScoreSchemeDao getScoreSchemeDaoImp() { return scoreSchemeDaoImp; } public void setScoreSchemeDaoImp(IScoreSchemeDao scoreSchemeDaoImp) { this.scoreSchemeDaoImp = scoreSchemeDaoImp; } public IScoreGroupDao getScoreGroupDaoImp() { return scoreGroupDaoImp; } public void setScoreGroupDaoImp(IScoreGroupDao scoreGroupDaoImp) { this.scoreGroupDaoImp = scoreGroupDaoImp; } public IAttachmentDao getAttachmentDaoImp() { return attachmentDaoImp; } public void setAttachmentDaoImp(IAttachmentDao attachmentDaoImp) { this.attachmentDaoImp = attachmentDaoImp; } public IQaStyleDao getQaStyleDaoImp() { return qaStyleDaoImp; } public void setQaStyleDaoImp(IQaStyleDao qaStyleDaoImp) { this.qaStyleDaoImp = qaStyleDaoImp; } public IVoteStyleDao getVoteStyleDaoImp() { return voteStyleDaoImp; } public void setVoteStyleDaoImp(IVoteStyleDao voteStyleDaoImp) { this.voteStyleDaoImp = voteStyleDaoImp; } public IQaItemDao getQaItemDaoImp() { return qaItemDaoImp; } public void setQaItemDaoImp(IQaItemDao qaItemDaoImp) { this.qaItemDaoImp = qaItemDaoImp; } public IQaNavDao getQaNavDaoImp() { return qaNavDaoImp; } public void setQaNavDaoImp(IQaNavDao qaNavDaoImp) { this.qaNavDaoImp = qaNavDaoImp; } public IVoteSubjectDao getVoteSubjectDaoImp() { return voteSubjectDaoImp; } public void setVoteSubjectDaoImp(IVoteSubjectDao voteSubjectDaoImp) { this.voteSubjectDaoImp = voteSubjectDaoImp; } public IVoteItemDao getVoteItemDaoImp() { return voteItemDaoImp; } public void setVoteItemDaoImp(IVoteItemDao voteItemDaoImp) { this.voteItemDaoImp = voteItemDaoImp; } public IVoteRecDao getVoteRecDaoImp() { return voteRecDaoImp; } public void setVoteRecDaoImp(IVoteRecDao voteRecDaoImp) { this.voteRecDaoImp = voteRecDaoImp; } public IDrawDao getDrawDaoImp() { return drawDaoImp; } public void setDrawDaoImp(IDrawDao drawDaoImp) { this.drawDaoImp = drawDaoImp; } public IDrawStyleDao getDrawStyleDaoImp() { return drawStyleDaoImp; } public void setDrawStyleDaoImp(IDrawStyleDao drawStyleDaoImp) { this.drawStyleDaoImp = drawStyleDaoImp; } public ICommentDao getCommentDaoImp() { return commentDaoImp; } public void setCommentDaoImp(ICommentDao commentDaoImp) { this.commentDaoImp = commentDaoImp; } public void setUserArtsCountDaoImp(IUserArtsCountDao userArtsCountDaoImp) { this.userArtsCountDaoImp = userArtsCountDaoImp; } public IUserArtsCountDao getUserArtsCountDaoImp() { return userArtsCountDaoImp; } public IExternalHostCharsetDao getExternalHostCharsetDaoImp() { return externalHostCharsetDaoImp; } public void setExternalHostCharsetDaoImp( IExternalHostCharsetDao externalHostCharsetDaoImp) { this.externalHostCharsetDaoImp = externalHostCharsetDaoImp; } public SiteInfo getSite() { return site; } public void setSite(SiteInfo site) { this.site = site; } public SiteStyle getCurSiteStyle() { return curSiteStyle; } public void setCurSiteStyle(SiteStyle curSiteStyle) { this.curSiteStyle = curSiteStyle; } public BbsStyle getCurBbsStyle() { return curBbsStyle; } public void setCurBbsStyle(BbsStyle curBbsStyle) { this.curBbsStyle = curBbsStyle; } public QaStyle getCurQaStyle() { return curQaStyle; } public void setCurQaStyle(QaStyle curQaStyle) { this.curQaStyle = curQaStyle; } public VoteStyle getCurVoteStyle() { return curVoteStyle; } public void setCurVoteStyle(VoteStyle curVoteStyle) { this.curVoteStyle = curVoteStyle; } public DrawStyle getCurDrawStyle() { return curDrawStyle; } public void setCurDrawStyle(DrawStyle curDrawStyle) { this.curDrawStyle = curDrawStyle; } public SiteStyleSubElementInCommon getSel() { return sel; } public void setSel(SiteStyleSubElementInCommon sel) { this.sel = sel; } public BbsStyleSubElementInCommon getBel() { return bel; } public void setBel(BbsStyleSubElementInCommon bel) { this.bel = bel; } public QaStyleSubElementInCommon getQel() { return qel; } public void setQel(QaStyleSubElementInCommon qel) { this.qel = qel; } public VoteStyleSubElementInCommon getVel() { return vel; } public void setVel(VoteStyleSubElementInCommon vel) { this.vel = vel; } public FormatElements getFel() { return fel; } public void setFel(FormatElements fel) { this.fel = fel; } public String getHtmlTemplate() { return htmlTemplate; } public void setHtmlTemplate(String htmlTemplate) { this.htmlTemplate = htmlTemplate; } public String getCss() { return css; } public void setCss(String css) { this.css = css; } public String getHtml() { return html; } public void setHtml(String html) { this.html = html; } public String getTopCode() { return topCode; } public void setTopCode(String topCode) { this.topCode = topCode; } public String getFooterCode() { return footerCode; } public void setFooterCode(String footerCode) { this.footerCode = footerCode; } public String getTitleFormat() { return titleFormat; } public void setTitleFormat(String titleFormat) { this.titleFormat = titleFormat; } public String getHrefLineFormat() { return hrefLineFormat; } public void setHrefLineFormat(String hrefLineFormat) { this.hrefLineFormat = hrefLineFormat; } public String getSearchAreaCode() { return searchAreaCode; } public void setSearchAreaCode(String searchAreaCode) { this.searchAreaCode = searchAreaCode; } public boolean isRefererRec() { return refererRec; } public void setRefererRec(boolean refererRec) { this.refererRec = refererRec; } public String getLocationSplitStr() { return locationSplitStr; } public void setLocationSplitStr(String locationSplitStr) { this.locationSplitStr = locationSplitStr; } public UserCookie getUc() { return uc; } public void setUc(UserCookie uc) { this.uc = uc; } public String getShortSiteName() { return shortSiteName; } public void setShortSiteName(String shortSiteName) { this.shortSiteName = shortSiteName; } public String getSiteName() { return siteName; } public void setSiteName(String siteName) { this.siteName = siteName; } public CookieDoModel getCdm() { return cdm; } public void setCdm(CookieDoModel cdm) { this.cdm = cdm; } public long getPageStart() { return pageStart; } public void setPageStart(long pageStart) { this.pageStart = pageStart; } public long getPageEnd() { return pageEnd; } public void setPageEnd(long pageEnd) { this.pageEnd = pageEnd; } public long getId() { return id; } public void setId(long id) { this.id = id; } public int getGid() { return gid; } public void setGid(int gid) { this.gid = gid; } public long getTid() { return tid; } public void setTid(long tid) { this.tid = tid; } public long getUid() { return uid; } public void setUid(long uid) { this.uid = uid; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getMod() { return mod; } public void setMod(int mod) { this.mod = mod; } public int getUmode() { return umode; } public void setUmode(int umode) { this.umode = umode; } public int getSmode() { return smode; } public void setSmode(int smode) { this.smode = smode; } public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public int getStateMode() { return stateMode; } public void setStateMode(int stateMode) { this.stateMode = stateMode; } public boolean isNotice() { return notice; } public void setNotice(boolean notice) { this.notice = notice; } public int getSoul() { return soul; } public void setSoul(int soul) { this.soul = soul; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getKeyCon() { return keyCon; } public void setKeyCon(String keyCon) { this.keyCon = keyCon; } public int getStation() { return station; } public void setStation(int station) { this.station = station; } public String getDateFormatOnLine() { return dateFormatOnLine; } public void setDateFormatOnLine(String dateFormatOnLine) { this.dateFormatOnLine = dateFormatOnLine; } public String getEditAreaCode() { return editAreaCode; } public void setEditAreaCode(String editAreaCode) { this.editAreaCode = editAreaCode; } public HttpServletRequest getRequest() { return request; } public void setRequest(HttpServletRequest request) { this.request = request; } public HttpServletResponse getResponse() { return response; } public void setResponse(HttpServletResponse response) { this.response = response; } public boolean isUserLogined() { return userLogined; } public void setUserLogined(boolean userLogined) { this.userLogined = userLogined; } public ResultEl getRe() { return re; } public void setRe(ResultEl re) { this.re = re; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public String getBbsName() { return bbsName; } public void setBbsName(String bbsName) { this.bbsName = bbsName; } public BbsInfo getBi() { return bi; } public void setBi(BbsInfo bi) { this.bi = bi; } public String getFunctionAreaCode() { return functionAreaCode; } public void setFunctionAreaCode(String functionAreaCode) { this.functionAreaCode = functionAreaCode; } public boolean isToEnd() { return toEnd; } public void setToEnd(boolean toEnd) { this.toEnd = toEnd; } public int getScrollPos() { return scrollPos; } public void setScrollPos(int scrollPos) { this.scrollPos = scrollPos; } public FileReadArgs getFra() { return fra; } public void setFra(FileReadArgs fra) { this.fra = fra; } }
chenxyzy/cms
src/com/lerx/web/vo/WebElements.java
Java
apache-2.0
16,997
--- copyright: years: 2016, 2017 lastupdated: "2017-03-17" --- {:new_window: target="\_blank"} {:shortdesc: .shortdesc} {:screen:.screen} {:codeblock:.codeblock} {:pre: .pre} # Gestión de riesgos y de seguridad {: #RM_security} Puede mejorar la seguridad para habilitar la creación, imposición y notificación de la seguridad de la conexión de dispositivos. Con esta seguridad avanzada, se utilizan certificados y autenticación TLS (seguridad de capa de transporte), además de los ID de usuario y las señales que utiliza {{site.data.keyword.iot_short_notm}} para determinar cómo y cuándo se conectan los dispositivos a la plataforma. Si los certificados están habilitados, durante la comunicación entre los dispositivos y el servidor, a cualquier dispositivo que no tenga certificados válidos, según la configuración de los valores de seguridad, se le deniega el acceso, aunque utilice ID de usuario y contraseñas válidos. ## Certificados de cliente {: #certificates} Para configurar certificados los certificados del cliente y el acceso al servidor de los dispositivos, el operador del sistema importa los certificados de la entidad emisora de certificados (CA) asociada y los certificados del servidor de mensajería en {{site.data.keyword.iot_short_notm}}. Luego el analista de seguridad configura las políticas de seguridad de conexión de modo que las conexiones predeterminadas entre los dispositivos y la plataforma utilicen los niveles de seguridad Solo certificados o Certificados con señal de autenticación. El analista puede añadir distintas políticas para los distintos tipos de dispositivos. Para obtener información sobre cómo configurar certificados, consulte [Configuración de certificados](set_up_certificates.html). ## Planes de organización y políticas de seguridad Las políticas de seguridad reforzadas permiten a las organizaciones determinar cómo quieren conectar los dispositivos y la autenticación en la plataforma, utilizando políticas de conexión y políticas de listas negras y listas blancas. Las opciones de las políticas de seguridad disponibles para una organización dependen del tipo de plan de la organización, del siguiente modo: **Plan estándar:** - Los operadores del sistema pueden configurar las políticas de conexión con las siguientes opciones: - TLS opcional - TLS con autenticación de señal - TLS con autenticación de señal y de certificado de cliente **Plan de seguridad avanzada (ASP) o plan Lite:** - Los operadores del sistema pueden configurar las políticas de conexión con las siguientes opciones: - TLS opcional - TLS con autenticación de señal - TLS con autenticación de certificado de cliente - TLS con autenticación de señal y de certificado de cliente - TLS con señal o certificado de cliente - Los operadores del sistema pueden configura las listas negras o las listas blancas ## Políticas de conexión {: #connect_policy} Las políticas de conexión imponen cómo se conectan los dispositivos a la plataforma. Puede configurar políticas de conexión predeterminadas para todos los tipos de dispositivo y crear valores personalizados para tipos de dispositivo específicos. La política se puede definir de modo que permita conexiones sin cifrar, que imponga solo conexiones de seguridad de la capa de transporte (sólo TLS) y que habilite los dispositivos para que se autentiquen con certificados del lado del cliente. Para obtener información sobre cómo configurar las políticas de seguridad de conexión, consulte [Configuración de políticas de seguridad](set_up_policies.html). La seguridad de conexión también se puede configurar de modo que los operadores del sistema puedan utilizar su propio certificado de servidor de mensajería en lugar del certificado predeterminado que se proporciona. El uso de un certificado de servidor de mensajería personalizado puede resultar útil si los dispositivos del usuario se autenticarán ante el servidor durante el reconocimiento de TLS. Solo se admiten los certificados de servidor de mensajería personalizados que utilizan el mismo dominio que el servidor de mensajería de IoTP original (<orgId>.messaging.internetofthings.ibmcloud.com). ## Políticas de lista negra y lista blanca {: #wl_bl} Las políticas de lista negra y lista blanca proporcionan la posibilidad de controlar las ubicaciones desde las que los dispositivos pueden conectar con la cuenta de la organización. Una lista negra identifica todas las direcciones IP, CIDR o países a los que se denegará el acceso al servidor, mientras una lista blanca proporciona acceso explícito a determinadas direcciones IP. Para obtener información sobre cómo configurar políticas de lista negra y lista blanca, consulte [Configuración de listas negras y listas blancas](set_up_policies.html#config_black_white). ## Panel de control de Risk and Security Management {: #dashboard} Finalmente, el operador del sistema y el analista de seguridad pueden utilizar el panel de control de Risk and Security Management para ver el estado general de la seguridad. Las tarjetas del panel de control ofrecen una completa visión general, así como el estado de conexión de los dispositivos.
nickgaski/docs
services/IoT/nl/es/reference/security/RM_security.md
Markdown
apache-2.0
5,260
__author__ = 'sianwahl' from string import Template class NedGenerator: def __init__(self, number_of_channels): self.number_of_channels = number_of_channels def generate(self): return self._generate_tuplefeeder_ned(), self._generate_m2etis_ned() def _generate_tuplefeeder_ned(self): template = """ // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // package m2etis.applications.TupleFeeder; import oversim.common.BaseApp; import oversim.common.ITier; simple TupleFeeder extends BaseApp { parameters: @class(TupleFeeder); int largestKey; // largest key we can pick int numSubs; int numPubs; int numPubSubs; int numRend; int channelCount; double stopAvg; int waitForSubscribe @unit(s); int waitForPublish @unit(s); $channel_specific_parameters } module TupleFeederModules like ITier { parameters: @display("i=block/segm"); gates: input from_lowerTier; // gate from the lower tier input from_upperTier; // gate from the upper tier output to_lowerTier; // gate to the lower tier output to_upperTier; // gate to the upper tier input trace_in; // gate for trace file commands input udpIn; output udpOut; input tcpIn; output tcpOut; submodules: tupleFeeder: TupleFeeder; connections allowunconnected: from_lowerTier --> tupleFeeder.from_lowerTier; to_lowerTier <-- tupleFeeder.to_lowerTier; trace_in --> tupleFeeder.trace_in; udpIn --> tupleFeeder.udpIn; udpOut <-- tupleFeeder.udpOut; } """ channel_specific_parameters = "" for i in range(0, self.number_of_channels): channel_specific_parameters += "int numToSend_" + str(i) + ";\n\t" channel_specific_parameters += "int burstAmount_" + str(i) + ";\n\t" channel_specific_parameters += "int burstFrequency_" + str(i) + " @unit(s);\n\t" channel_specific_parameters += "int burstDuration_" + str(i) + " @unit(s);\n\t" channel_specific_parameters += "int chanceToUnsubscribe_" + str(i) + ";\n\t" channel_specific_parameters += "int timeToUnsubscribe_" + str(i) + " @unit(s);\n\t" channel_specific_parameters += "int timeToSubscribe_" + str(i) + " @unit(s);\n\t" channel_specific_parameters += "int dropChance_" + str(i) + ";\n\t" channel_specific_parameters += "bool compensateDrop_" + str(i) + ";\n\t" channel_specific_parameters += "double fluctuation_" + str(i) + ";\n\t" template_prepared = Template(template) result = template_prepared.substitute( channel_specific_parameters=channel_specific_parameters ) return result def _generate_m2etis_ned(self): template = """ // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // package m2etis.middleware; import oversim.common.BaseApp; import oversim.common.ITier; // // TODO auto-generated type // simple M2etisAdapter extends BaseApp { parameters: @class(M2etisAdapter); $disable_overlays int packetSize @unit(B); int queueSize @unit(B); int channelCount; int downstream @unit(bps); int upstream @unit(bps); int headerSize @unit(B); int startRoot; int endRoot; int rendezvousNode; double stopAvg; double simulationResolution @unit(s); bool queueDisabled; } module M2etisPubSub like ITier { gates: input udpIn; // gate from the UDP layer output udpOut; // gate to the UDP layer input from_lowerTier; // gate from the lower tier input from_upperTier; // gate from the upper tier output to_lowerTier; // gate to the lower tier output to_upperTier; // gate to the upper tier input trace_in; // gate for trace file commands input tcpIn; // gate from the TCP layer output tcpOut; // gate to the TCP layer submodules: m2etis: M2etisAdapter; connections allowunconnected: from_lowerTier --> m2etis.from_lowerTier; to_lowerTier <-- m2etis.to_lowerTier; from_upperTier --> m2etis.from_upperTier; to_upperTier <-- m2etis.to_upperTier; udpIn --> m2etis.udpIn; udpOut <-- m2etis.udpOut; } """ disable_overlays = "" for i in range(0, self.number_of_channels): disable_overlays += "bool disableOverlay_" + str(i) + ";\n\t" template_prepared = Template(template) result = template_prepared.substitute( disable_overlays=disable_overlays ) return result
ClockworkOrigins/m2etis
configurator/configurator/NedGenerator.py
Python
apache-2.0
6,119
package ru.stqa.pft.addressbook.model; import com.google.common.collect.ForwardingSet; import java.util.HashSet; import java.util.Set; /** * Created by o.kaluzhin on 22.09.2016. */ public class Contacts extends ForwardingSet<ContactData> { private Set<ContactData> delegate; public Contacts(Contacts contacts) { this.delegate = new HashSet<ContactData>(contacts.delegate); } public Contacts() { this.delegate = new HashSet<ContactData>(); } @Override protected Set<ContactData> delegate() { return delegate; } public Contacts withAdded(ContactData contact) { Contacts contacts = new Contacts(this); contacts.add(contact); return contacts; } public Contacts without(ContactData contact) { Contacts contacts = new Contacts(this); contacts.remove(contact); return contacts; } }
OKaluzhyn/java_test
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Contacts.java
Java
apache-2.0
846
#!/bin/bash START=$(date +%s) # fail on first error set -e source /data/src/docker/joynr-base/scripts/ci/global.sh cd /data/src mvn clean install -P no-license-and-notice,no-java-formatter,no-checkstyle -DskipTests END=$(date +%s) DIFF=$(( $END - $START )) log "c++ generate sources took $DIFF seconds"
bmwcarit/joynr
docker/joynr-cpp-base/scripts/build/cpp-generate.sh
Shell
apache-2.0
308
package org.wikipedia.feed.news; import android.support.annotation.NonNull; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.feed.model.CardType; import org.wikipedia.feed.model.ListCard; import org.wikipedia.feed.model.UtcDate; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class NewsListCard extends ListCard<NewsItemCard> { @NonNull private UtcDate age; public NewsListCard(@NonNull List<NewsItem> news, @NonNull UtcDate age, @NonNull WikiSite wiki) { super(toItemCards(news, wiki)); this.age = age; } @NonNull @Override public String title() { return ""; } @NonNull @Override public CardType type() { return CardType.NEWS_LIST; } @NonNull public UtcDate age() { return age; } @NonNull private static List<NewsItemCard> toItemCards(@NonNull List<NewsItem> items, @NonNull WikiSite wiki) { List<NewsItemCard> itemCards = new ArrayList<>(); for (NewsItem item : items) { itemCards.add(new NewsItemCard(item, wiki)); } return itemCards; } @Override protected int dismissHashCode() { return (int) TimeUnit.MILLISECONDS.toDays(age.baseCalendar().getTime().getTime()); } }
anirudh24seven/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/news/NewsListCard.java
Java
apache-2.0
1,308
:- use_package(persdb). :- use_module(library('pillow/http_server')). :- use_module(library(sockets)). :- use_module(library('sockets/sockets_io'),[serve_socket/3]). :- use_module(library(strings),[write_string/2]). :- use_module(library(soap),[soap_message/2]). :- use_module(library(write)). % Predicados Persistentes % En estos predicados se asertan los mensajes recibidos y los errores % detectados. Cada hecho que se aserta va a un fichero: % ./user/cached_1.pl y ./user/received_message_2.pl % Muy util para "espiar" que es lo que esta pasando... persistent_dir(db,'./ser'). :- persistent(received_message/2,db). :- persistent(cached/1,db). % Punto de entrada principal % Invocando el ejecutable como server NUMERO, arranca el proceso servidor % escuchando en el port NUMERO. Por cada nueva peticion de un cliente se llama % al predicado serve/1, por cada error que ocurra se llama a catcher/1. main(N):- %atom_codes(S,Codes), %number_codes(N,Codes), set_prolog_flag(write_strings,on), bind_socket(N,5,Socket), serve_socket(Socket,server,catcher). % Manejador de Peticiones % Lee una peticion, la procesa, devuelve la respuesta y cierra la conexion. % Para http esto es suficiente. Para otros protocolos podria escribirse y % volver a leer, volver a escribir, etc. sobre el mismo Stream. server(Stream):- http_serve_fetch(Stream,serve(Stream)). serve(Message,Stream,Answer):- !, display(Message),nl, display(Stream),nl, http_answer(good,Answer). serve(Message,Stream,Answer):- writeq(received_message(Stream,Message)), nl, assertz_fact(received_message(Stream,Message)), process(Message,Answer). % Manejador de Errores catcher(Error):- !, display('Error: '), display(Error),nl. catcher(Error):- assertz_fact(cached(Error)), writeq(Error), nl. % Proceso de la Aplicacion % Parsea el mensaje HTTP extrayendo el mensaje SOAP, luego parsea este % obteniendo el contenido: un termino XML. process(Message,[Answer]):- http_message(Message,SoapStr), soap_message(SoapStr,XmlTerm), !, http_answer(good,Answer), writeq(xmlterm(XmlTerm)), nl. process(_Message,[Answer]):- http_answer(bad,Answer). http_answer(bad,status(request_error,400,"ERROR")). http_answer(good,status(success,200,"OK")). http_message(Message,SoapStr):- member(post,Message), !, member(content(SoapStr),Message). http_message(Message,SoapStr):- member(document(SoapStr),Message). % Si el protocolo de la aplicacion es sincrono, el mensaje SOAP de respuesta % deberia ir en Answer. Aqui se usa Answer como confirmacion de recepcion % correcta; la respuesta SOAP se enviaria usando la parte cliente: % ver client.pl
leuschel/ecce
www/CiaoDE/ciao/library/connections/soap/server2.pl
Perl
apache-2.0
2,624
/* * 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.spark.sql.sources.v2.writer; import org.apache.spark.annotation.Evolving; import org.apache.spark.sql.sources.v2.SupportsBatchWrite; import org.apache.spark.sql.sources.v2.Table; import org.apache.spark.sql.sources.v2.writer.streaming.StreamingWrite; import org.apache.spark.sql.types.StructType; /** * An interface for building the {@link BatchWrite}. Implementations can mix in some interfaces to * support different ways to write data to data sources. * * Unless modified by a mixin interface, the {@link BatchWrite} configured by this builder is to * append data without affecting existing data. */ @Evolving public interface WriteBuilder { /** * Passes the `queryId` from Spark to data source. `queryId` is a unique string of the query. It's * possible that there are many queries running at the same time, or a query is restarted and * resumed. {@link BatchWrite} can use this id to identify the query. * * @return a new builder with the `queryId`. By default it returns `this`, which means the given * `queryId` is ignored. Please override this method to take the `queryId`. */ default WriteBuilder withQueryId(String queryId) { return this; } /** * Passes the schema of the input data from Spark to data source. * * @return a new builder with the `schema`. By default it returns `this`, which means the given * `schema` is ignored. Please override this method to take the `schema`. */ default WriteBuilder withInputDataSchema(StructType schema) { return this; } /** * Returns a {@link BatchWrite} to write data to batch source. By default this method throws * exception, data sources must overwrite this method to provide an implementation, if the * {@link Table} that creates this scan implements {@link SupportsBatchWrite}. * * Note that, the returned {@link BatchWrite} can be null if the implementation supports SaveMode, * to indicate that no writing is needed. We can clean it up after removing * {@link SupportsSaveMode}. */ default BatchWrite buildForBatch() { throw new UnsupportedOperationException(getClass().getName() + " does not support batch write"); } default StreamingWrite buildForStreaming() { throw new UnsupportedOperationException(getClass().getName() + " does not support streaming write"); } }
yanboliang/spark
sql/core/src/main/java/org/apache/spark/sql/sources/v2/writer/WriteBuilder.java
Java
apache-2.0
3,185
/* * Copyright (C) 2016 R&D Solutions Ltd. * * 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 io.hawkcd.services.filters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.hawkcd.utilities.deserializers.MaterialDefinitionAdapter; import io.hawkcd.utilities.deserializers.TaskDefinitionAdapter; import io.hawkcd.utilities.deserializers.WsContractDeserializer; import io.hawkcd.model.MaterialDefinition; import io.hawkcd.model.PipelineDefinition; import io.hawkcd.model.StageDefinition; import io.hawkcd.model.TaskDefinition; import io.hawkcd.model.dto.WsContractDto; import io.hawkcd.services.PipelineDefinitionService; import io.hawkcd.services.StageDefinitionService; import io.hawkcd.services.filters.interfaces.IAuthorizationService; import io.hawkcd.services.interfaces.IPipelineDefinitionService; import io.hawkcd.services.interfaces.IStageDefinitionService; import java.util.ArrayList; import java.util.List; public class StageDefinitionAuthorizationService implements IAuthorizationService { private IPipelineDefinitionService pipelineDefinitionService; private IStageDefinitionService stageDefinitionService; private IAuthorizationService pipelineDefintionAuthorizationService; private Gson jsonConverter; public StageDefinitionAuthorizationService() { this.pipelineDefinitionService = new PipelineDefinitionService(); this.stageDefinitionService = new StageDefinitionService(); this.pipelineDefintionAuthorizationService = new PipelineDefinitionAuthorizationService(); this.jsonConverter = new GsonBuilder() .registerTypeAdapter(WsContractDto.class, new WsContractDeserializer()) .registerTypeAdapter(TaskDefinition.class, new TaskDefinitionAdapter()) .registerTypeAdapter(MaterialDefinition.class, new MaterialDefinitionAdapter()) .create(); } public StageDefinitionAuthorizationService(IPipelineDefinitionService pipelineDefinitionService, IStageDefinitionService stageDefinitionService, IAuthorizationService pipelineDefintionAuthorizationService) { this.pipelineDefinitionService = pipelineDefinitionService; this.stageDefinitionService = stageDefinitionService; this.pipelineDefintionAuthorizationService = pipelineDefintionAuthorizationService; this.jsonConverter = new GsonBuilder() .registerTypeAdapter(WsContractDto.class, new WsContractDeserializer()) .registerTypeAdapter(TaskDefinition.class, new TaskDefinitionAdapter()) .registerTypeAdapter(MaterialDefinition.class, new MaterialDefinitionAdapter()) .create(); } @Override public List getAll(List permissions, List entriesToFilter) { List<StageDefinition> filteredStageDefinitions = new ArrayList<>(); List<PipelineDefinition> pipelineDefinitions = (List<PipelineDefinition>) this.pipelineDefinitionService.getAll().getEntity(); List<PipelineDefinition> filteredPipelineDefinitions = this.pipelineDefintionAuthorizationService.getAll(permissions, pipelineDefinitions); for (PipelineDefinition filteredPipelineDefinition : filteredPipelineDefinitions) { filteredStageDefinitions.addAll(filteredPipelineDefinition.getStageDefinitions()); } return filteredStageDefinitions; } @Override public boolean getById(String entityId, List permissions) { StageDefinition stageDefinition = (StageDefinition) this.stageDefinitionService.getById(entityId).getEntity(); return this.pipelineDefintionAuthorizationService.getById(stageDefinition.getPipelineDefinitionId(), permissions); } @Override public boolean add(String entity, List permissions) { StageDefinition stageDefinition = this.jsonConverter.fromJson(entity, StageDefinition.class); PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(stageDefinition.getPipelineDefinitionId()).getEntity(); String pipelineDefinitionsAsString = this.jsonConverter.toJson(pipelineDefinition); return this.pipelineDefintionAuthorizationService.update(pipelineDefinitionsAsString, permissions); } @Override public boolean update(String entity, List permissions) { StageDefinition stageDefinition = this.jsonConverter.fromJson(entity, StageDefinition.class); PipelineDefinition pipelineDefinition = (PipelineDefinition) this.pipelineDefinitionService.getById(stageDefinition.getPipelineDefinitionId()).getEntity(); String pipelineDefinitionsAsString = this.jsonConverter.toJson(pipelineDefinition); return this.pipelineDefintionAuthorizationService.update(pipelineDefinitionsAsString, permissions); } @Override public boolean delete(String entityId, List permissions) { StageDefinition stageDefinition = (StageDefinition) this.stageDefinitionService.getById(entityId).getEntity(); return this.pipelineDefintionAuthorizationService.delete(stageDefinition.getPipelineDefinitionId(), permissions); } }
rndsolutions/hawkcd
Server/src/main/java/io/hawkcd/services/filters/StageDefinitionAuthorizationService.java
Java
apache-2.0
5,644
/* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 Untied States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ package gov.nist.javax.sip.parser; import gov.nist.core.InternalErrorHandler; import gov.nist.javax.sip.stack.SIPStackTimerTask; import gov.nist.javax.sip.stack.timers.SipTimer; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.NoSuchElementException; /** * Input class for the pipelined parser. Buffer all bytes read from the socket * and make them available to the message parser. * * @author M. Ranganathan (Contains a bug fix contributed by Rob Daugherty ( * Lucent Technologies) ) * */ public class Pipeline extends InputStream { private LinkedList buffList; private Buffer currentBuffer; private boolean isClosed; private SipTimer timer; private InputStream pipe; private int readTimeout; private SIPStackTimerTask myTimerTask; class MyTimer extends SIPStackTimerTask { Pipeline pipeline; private boolean isCancelled; protected MyTimer(Pipeline pipeline) { this.pipeline = pipeline; } public void runTask() { if (this.isCancelled) { this.pipeline = null; return; } try { pipeline.close(); } catch (IOException ex) { InternalErrorHandler.handleException(ex); } } @Override public void cleanUpBeforeCancel() { this.isCancelled = true; this.pipeline = null; super.cleanUpBeforeCancel(); } } class Buffer { byte[] bytes; int length; int ptr; public Buffer(byte[] bytes, int length) { ptr = 0; this.length = length; this.bytes = bytes; } public int getNextByte() { return (int) bytes[ptr++] & 0xFF; } } public void startTimer() { if (this.readTimeout == -1) return; // TODO make this a tunable number. For now 4 seconds // between reads seems reasonable upper limit. this.myTimerTask = new MyTimer(this); this.timer.schedule(this.myTimerTask, this.readTimeout); } public void stopTimer() { if (this.readTimeout == -1) return; if (this.myTimerTask != null) this.timer.cancel(myTimerTask); } public Pipeline(InputStream pipe, int readTimeout, SipTimer timer) { // pipe is the Socket stream // this is recorded here to implement a timeout. this.timer = timer; this.pipe = pipe; buffList = new LinkedList(); this.readTimeout = readTimeout; } public void write(byte[] bytes, int start, int length) throws IOException { if (this.isClosed) throw new IOException("Closed!!"); Buffer buff = new Buffer(bytes, length); buff.ptr = start; synchronized (this.buffList) { buffList.add(buff); buffList.notifyAll(); } } public void write(byte[] bytes) throws IOException { if (this.isClosed) throw new IOException("Closed!!"); Buffer buff = new Buffer(bytes, bytes.length); synchronized (this.buffList) { buffList.add(buff); buffList.notifyAll(); } } public void close() throws IOException { this.isClosed = true; synchronized (this.buffList) { this.buffList.notifyAll(); } // JvB: added this.pipe.close(); } public int read() throws IOException { // if (this.isClosed) return -1; synchronized (this.buffList) { if (currentBuffer != null && currentBuffer.ptr < currentBuffer.length) { int retval = currentBuffer.getNextByte(); if (currentBuffer.ptr == currentBuffer.length) this.currentBuffer = null; return retval; } // Bug fix contributed by Rob Daugherty. if (this.isClosed && this.buffList.isEmpty()) return -1; try { // wait till something is posted. while (this.buffList.isEmpty()) { this.buffList.wait(); // jeand : Issue 314 : return -1 only is the buffer is empty if (this.buffList.isEmpty() && this.isClosed) return -1; } currentBuffer = (Buffer) this.buffList.removeFirst(); int retval = currentBuffer.getNextByte(); if (currentBuffer.ptr == currentBuffer.length) this.currentBuffer = null; return retval; } catch (InterruptedException ex) { throw new IOException(ex.getMessage()); } catch (NoSuchElementException ex) { ex.printStackTrace(); throw new IOException(ex.getMessage()); } } } /** * @return the isClosed */ public boolean isClosed() { return isClosed; } }
fhg-fokus-nubomedia/signaling-plane
modules/lib-sip/src/main/java/gov/nist/javax/sip/parser/Pipeline.java
Java
apache-2.0
6,237
pkg-config libxml-2.0 --modversion
bayvictor/distributed-polling-system
bin/pkg_config_lib_ver.sh
Shell
apache-2.0
36
namespace Fuel_consumption.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; [Table("MyTable")] public partial class MyTable { public int Id { get; set; } public DateTime RefuelingDate { get; set; } public double Liter { get; set; } public double Kilometer { get; set; } } }
wutsunglun/CHU
BuildSchool/01_Csharp/Hackathons/Hackathon01/Fuel consumption/Models/MyTable.cs
C#
apache-2.0
485
.modal-header { padding: 12px; color: #fff; border-radius: 4px; background-image: linear-gradient(to bottom,#337ab7 0,#265a88 100%); } .proxy-mappings-import-endpoint-modal { width: 30% !important; } input[type="file"] { display: none; } .upload-button { width: 100%; } .upload-select-file-button { border: 1px solid #ccc; display: inline-block; padding: 6px 12px; width: 100%; cursor: pointer; }
mgtechsoftware/smockin
src/main/resources/public/css/server_proxy_mappings_import.css
CSS
apache-2.0
450
package pl.com.mmotak.sample.models; import android.content.Intent; /** * Created by Maciej on 2017-03-11. */ public class ItemExample { public final String message; public final Intent intent; public final String title; public ItemExample(String title, String message, Intent intent) { this.title = title; this.message = message; this.intent = intent; } }
mmotak/DroidMVVMValidator
sampleapp/src/main/java/pl/com/mmotak/sample/models/ItemExample.java
Java
apache-2.0
407
@charset "UTF-8"; html, body { margin: 0; padding: 0; overflow: hidden; background-color: #7F7F7F; }
clojurecup2014/astrocats
resources/public/css/default.css
CSS
apache-2.0
114
# Copyright 2017 Google Inc. 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. """Resources for mapping between user emails and host usernames/owners.""" from upvote.gae import settings def UsernameToEmail(username): if '@' in username: return username return '@'.join((username, settings.USER_EMAIL_DOMAIN)) def EmailToUsername(email): return email.partition('@')[0]
google/upvote_py2
upvote/gae/utils/user_utils.py
Python
apache-2.0
901
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>FotonCMS</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <!-- Navbar ================================================== --> <div class="navbar"> <div class="navbar-inner"> <div class="container"> <a class="brand" href="./index.html">FotonCMS</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class=""> <a href="./index.html">Overview</a> </li> <li class="active"> <a href="./admin.html">Administration</a> </li> </ul> </div> </div> </div> </div> <div class="container"> <div class="row"> <h1>FotonCMS administration</h1> </div> <div class="row"> It's a stub for now. </div> </div> </body> </html>
Spawnfest2012/Inverted-Link
server/priv/www/admin.html
HTML
apache-2.0
1,394
package ru.job4j.iterator; import org.junit.Before; import org.junit.Test; import java.util.NoSuchElementException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * Test Class MatrixTest. * @author shustovakv * @since 10.06.2018 */ public class MatrixIteratorTest { private MatrixIterator it; @Before public void setUp() { it = new MatrixIterator(new int[][]{{1, 2, 3}, {4, 5, 6}}); } @Test public void hasNextNextSequentialInvocation() { assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(1)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(2)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(3)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(4)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(5)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(6)); assertThat(it.hasNext(), is(false)); } @Test public void testsThatNextMethodDoesNotDependsOnPriorHasNextInvocation() { assertThat(it.next(), is(1)); assertThat(it.next(), is(2)); assertThat(it.next(), is(3)); assertThat(it.next(), is(4)); assertThat(it.next(), is(5)); assertThat(it.next(), is(6)); } @Test public void sequentialHasNextInvocationDoesNotAffectRetrievalOrder() { assertThat(it.hasNext(), is(true)); assertThat(it.hasNext(), is(true)); assertThat(it.next(), is(1)); assertThat(it.next(), is(2)); assertThat(it.next(), is(3)); assertThat(it.next(), is(4)); assertThat(it.next(), is(5)); assertThat(it.next(), is(6)); } @Test(expected = NoSuchElementException.class) public void shouldThrowNoSuchElementException() { it = new MatrixIterator(new int[][]{}); it.next(); } }
Spirka/shustovakv
chapter_004/src/test/java/ru/job4j/iterator/MatrixIteratorTest.java
Java
apache-2.0
1,987
/* * AbstractActivatedNodeHandler.java * * Created on 19. Mai 2007, 22:55 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.huberb.i18nvalidator; import org.netbeans.modules.properties.BundleStructure; import org.netbeans.modules.properties.PropertiesDataObject; import org.netbeans.modules.properties.PropertiesFileEntry; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.nodes.Node; /** * * @author HuberB1 */ public abstract class AbstractPropertiesActivatedNodeHandler extends AbstractActivatedNodeHandler { /** * Creates a new instance of AbstractPropertiesActivatedNodeHandler */ public AbstractPropertiesActivatedNodeHandler () { this(false); } /** * Creates a new instance of AbstractPropertiesActivatedNodeHandler */ public AbstractPropertiesActivatedNodeHandler (boolean recursivly) { super(recursivly); } public void handleActivatedNode( Node node ) { final DataObject c = (DataObject)node.getCookie(DataObject.class); if (c instanceof PropertiesDataObject) { PropertiesDataObject pdo = (PropertiesDataObject)c; BundleStructure bs = pdo.getBundleStructure(); int iMax = bs.getEntryCount(); for (int i = 0; i < iMax; i++ ) { PropertiesFileEntry pfe = bs.getNthEntry(i); FileObject fo = pfe.getFile(); handleSingleFileObjectWrapper(fo); } } else { super.handleActivatedNode(node); } } protected abstract void handleSingleFileObject(FileObject fo); }
bernhardhuber/netbeansplugins
nb-i18n-validator/src/org/huberb/i18nvalidator/AbstractPropertiesActivatedNodeHandler.java
Java
apache-2.0
1,788
// // ArticleListView.h // Vienna // // Created by Steve on 8/27/05. // Copyright (c) 2004-2014 Steve Palmer and Vienna contributors. 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. // #import <Cocoa/Cocoa.h> #import "Database.h" #import "ArticleBaseView.h" #import "BrowserView.h" #import "PopupButton.h" #import "StdEnclosureView.h" #import <WebKit/WebKit.h> @class AppController; @class ArticleController; @class MessageListView; @class ArticleView; @class FoldersTree; @interface ArticleListView : NSView<BaseView, ArticleBaseView, NSSplitViewDelegate, NSTableViewDelegate, NSTableViewDataSource, WebUIDelegate, WebFrameLoadDelegate> { IBOutlet AppController * controller; IBOutlet ArticleController * articleController; IBOutlet MessageListView * articleList; IBOutlet ArticleView * articleText; IBOutlet NSSplitView * splitView2; IBOutlet FoldersTree * foldersTree; IBOutlet StdEnclosureView * stdEnclosureView; int currentSelectedRow; int tableLayout; BOOL isAppInitialising; BOOL isChangingOrientation; BOOL isInTableInit; BOOL blockSelectionHandler; BOOL blockMarkRead; NSTimer * markReadTimer; NSString * guidOfArticleToSelect; NSFont * articleListFont; NSFont * articleListUnreadFont; NSMutableDictionary * reportCellDict; NSMutableDictionary * unreadReportCellDict; NSMutableDictionary * selectionDict; NSMutableDictionary * topLineDict; NSMutableDictionary * linkLineDict; NSMutableDictionary * middleLineDict; NSMutableDictionary * bottomLineDict; NSMutableDictionary * unreadTopLineDict; NSMutableDictionary * unreadTopLineSelectionDict; NSURL * currentURL; BOOL isCurrentPageFullHTML; BOOL isLoadingHTMLArticle; NSError * lastError; } // Public functions -(void)updateAlternateMenuTitle; -(void)updateVisibleColumns; -(void)saveTableSettings; -(int)tableLayout; -(NSArray *)markedArticleRange; -(BOOL)canDeleteMessageAtRow:(int)row; -(void)loadArticleLink:(NSString *) articleLink; -(NSURL *)url; -(void)webViewLoadFinished:(NSNotification *)notification; @end
iamjasonchoi/vienna-rss
src/ArticleListView.h
C
apache-2.0
2,555
package org.aplikator.client.shared.descriptor; import java.util.List; import org.aplikator.client.shared.data.ItemSuggestion; import org.jboss.errai.common.client.api.annotations.Portable; @Portable public class SuggestionsDTO { private List<ItemSuggestion> suggestions; public List<ItemSuggestion> getSuggestions() { return suggestions; } public void setSuggestions(List<ItemSuggestion> suggestions) { this.suggestions = suggestions; } }
incad/aplikator
src/main/java/org/aplikator/client/shared/descriptor/SuggestionsDTO.java
Java
apache-2.0
482
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.repositories.azure; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import java.util.Locale; import java.util.function.Function; import com.microsoft.azure.storage.LocationMode; import com.microsoft.azure.storage.StorageException; import org.elasticsearch.cloud.azure.blobstore.AzureBlobStore; import org.elasticsearch.cloud.azure.storage.AzureStorageService; import org.elasticsearch.cloud.azure.storage.AzureStorageService.Storage; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.metadata.RepositoryMetaData; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.repositories.IndexId; import org.elasticsearch.snapshots.SnapshotId; import org.elasticsearch.common.Strings; import org.elasticsearch.common.blobstore.BlobPath; import org.elasticsearch.common.blobstore.BlobStore; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.env.Environment; import org.elasticsearch.repositories.RepositoryVerificationException; import org.elasticsearch.repositories.blobstore.BlobStoreRepository; import org.elasticsearch.snapshots.SnapshotCreationException; import static org.elasticsearch.cloud.azure.storage.AzureStorageService.MAX_CHUNK_SIZE; import static org.elasticsearch.cloud.azure.storage.AzureStorageService.MIN_CHUNK_SIZE; import static org.elasticsearch.cloud.azure.storage.AzureStorageSettings.getValue; /** * Azure file system implementation of the BlobStoreRepository * <p> * Azure file system repository supports the following settings: * <dl> * <dt>{@code container}</dt><dd>Azure container name. Defaults to elasticsearch-snapshots</dd> * <dt>{@code base_path}</dt><dd>Specifies the path within bucket to repository data. Defaults to root directory.</dd> * <dt>{@code chunk_size}</dt><dd>Large file can be divided into chunks. This parameter specifies the chunk size. Defaults to 64mb.</dd> * <dt>{@code compress}</dt><dd>If set to true metadata files will be stored compressed. Defaults to false.</dd> * </dl> */ public class AzureRepository extends BlobStoreRepository { public static final String TYPE = "azure"; public static final class Repository { public static final Setting<String> ACCOUNT_SETTING = Setting.simpleString("account", Property.NodeScope); public static final Setting<String> CONTAINER_SETTING = new Setting<>("container", "elasticsearch-snapshots", Function.identity(), Property.NodeScope); public static final Setting<String> BASE_PATH_SETTING = Setting.simpleString("base_path", Property.NodeScope); public static final Setting<String> LOCATION_MODE_SETTING = Setting.simpleString("location_mode", Property.NodeScope); public static final Setting<ByteSizeValue> CHUNK_SIZE_SETTING = Setting.byteSizeSetting("chunk_size", MAX_CHUNK_SIZE, MIN_CHUNK_SIZE, MAX_CHUNK_SIZE, Property.NodeScope); public static final Setting<Boolean> COMPRESS_SETTING = Setting.boolSetting("compress", false, Property.NodeScope); } private final AzureBlobStore blobStore; private final BlobPath basePath; private final ByteSizeValue chunkSize; private final boolean compress; private final boolean readonly; public AzureRepository(RepositoryMetaData metadata, Environment environment, NamedXContentRegistry namedXContentRegistry, AzureStorageService storageService) throws IOException, URISyntaxException, StorageException { super(metadata, environment.settings(), namedXContentRegistry); blobStore = new AzureBlobStore(metadata, environment.settings(), storageService); String container = getValue(metadata.settings(), settings, Repository.CONTAINER_SETTING, Storage.CONTAINER_SETTING); this.chunkSize = getValue(metadata.settings(), settings, Repository.CHUNK_SIZE_SETTING, Storage.CHUNK_SIZE_SETTING); this.compress = getValue(metadata.settings(), settings, Repository.COMPRESS_SETTING, Storage.COMPRESS_SETTING); String modeStr = getValue(metadata.settings(), settings, Repository.LOCATION_MODE_SETTING, Storage.LOCATION_MODE_SETTING); Boolean forcedReadonly = metadata.settings().getAsBoolean("readonly", null); // If the user explicitly did not define a readonly value, we set it by ourselves depending on the location mode setting. // For secondary_only setting, the repository should be read only if (forcedReadonly == null) { if (Strings.hasLength(modeStr)) { LocationMode locationMode = LocationMode.valueOf(modeStr.toUpperCase(Locale.ROOT)); this.readonly = locationMode == LocationMode.SECONDARY_ONLY; } else { this.readonly = false; } } else { readonly = forcedReadonly; } String basePath = getValue(metadata.settings(), settings, Repository.BASE_PATH_SETTING, Storage.BASE_PATH_SETTING); if (Strings.hasLength(basePath)) { // Remove starting / if any basePath = Strings.trimLeadingCharacter(basePath, '/'); BlobPath path = new BlobPath(); for(String elem : basePath.split("/")) { path = path.add(elem); } this.basePath = path; } else { this.basePath = BlobPath.cleanPath(); } logger.debug("using container [{}], chunk_size [{}], compress [{}], base_path [{}]", container, chunkSize, compress, basePath); } /** * {@inheritDoc} */ @Override protected BlobStore blobStore() { return blobStore; } @Override protected BlobPath basePath() { return basePath; } /** * {@inheritDoc} */ @Override protected boolean isCompress() { return compress; } /** * {@inheritDoc} */ @Override protected ByteSizeValue chunkSize() { return chunkSize; } @Override public void initializeSnapshot(SnapshotId snapshotId, List<IndexId> indices, MetaData clusterMetadata) { try { if (!blobStore.doesContainerExist(blobStore.container())) { logger.debug("container [{}] does not exist. Creating...", blobStore.container()); deprecationLogger.deprecated("Auto creation of the container for an azure backed repository is deprecated" + " and will be removed in 6.0."); blobStore.createContainer(blobStore.container()); } super.initializeSnapshot(snapshotId, indices, clusterMetadata); } catch (StorageException | URISyntaxException e) { logger.warn("can not initialize container [{}]: [{}]", blobStore.container(), e.getMessage()); throw new SnapshotCreationException(getMetadata().name(), snapshotId, e); } } @Override public String startVerification() { if (readonly == false) { try { if (!blobStore.doesContainerExist(blobStore.container())) { logger.debug("container [{}] does not exist. Creating...", blobStore.container()); deprecationLogger.deprecated("Auto creation of the container for an azure backed repository is deprecated" + " and will be removed in 6.0."); blobStore.createContainer(blobStore.container()); } } catch (StorageException | URISyntaxException e) { logger.warn("can not initialize container [{}]: [{}]", blobStore.container(), e.getMessage()); throw new RepositoryVerificationException(getMetadata().name(), "can not initialize container " + blobStore.container(), e); } } return super.startVerification(); } @Override public boolean isReadOnly() { return readonly; } }
strapdata/elassandra5-rc
plugins/repository-azure/src/main/java/org/elasticsearch/repositories/azure/AzureRepository.java
Java
apache-2.0
8,900
ENT.Type = "anim" ENT.Base = "base_gmodentity" ENT.PrintName = "Ship Controller Weapon" ENT.Author = "Paradukes" ENT.Category = "SBEP - Other" ENT.Spawnable = true ENT.AdminSpawnable = true ENT.Owner = nil
X-Coder/SBEP-Weapons
lua/entities/weaponmonitor/shared.lua
Lua
apache-2.0
219
An Infinite Runner Game This is an infinite runner written in P5 and EMCA6.
ntroutman/infinite-runner-p5
README.md
Markdown
apache-2.0
76
"""Class to hold all camera accessories.""" import asyncio from datetime import timedelta import logging from haffmpeg.core import HAFFmpeg from pyhap.camera import ( VIDEO_CODEC_PARAM_LEVEL_TYPES, VIDEO_CODEC_PARAM_PROFILE_ID_TYPES, Camera as PyhapCamera, ) from pyhap.const import CATEGORY_CAMERA from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import STATE_ON from homeassistant.core import callback from homeassistant.helpers.event import ( async_track_state_change_event, async_track_time_interval, ) from homeassistant.util import get_local_ip from .accessories import TYPES, HomeAccessory from .const import ( CHAR_MOTION_DETECTED, CHAR_MUTE, CHAR_PROGRAMMABLE_SWITCH_EVENT, CONF_AUDIO_CODEC, CONF_AUDIO_MAP, CONF_AUDIO_PACKET_SIZE, CONF_LINKED_DOORBELL_SENSOR, CONF_LINKED_MOTION_SENSOR, CONF_MAX_FPS, CONF_MAX_HEIGHT, CONF_MAX_WIDTH, CONF_STREAM_ADDRESS, CONF_STREAM_COUNT, CONF_STREAM_SOURCE, CONF_SUPPORT_AUDIO, CONF_VIDEO_CODEC, CONF_VIDEO_MAP, CONF_VIDEO_PACKET_SIZE, DEFAULT_AUDIO_CODEC, DEFAULT_AUDIO_MAP, DEFAULT_AUDIO_PACKET_SIZE, DEFAULT_MAX_FPS, DEFAULT_MAX_HEIGHT, DEFAULT_MAX_WIDTH, DEFAULT_STREAM_COUNT, DEFAULT_SUPPORT_AUDIO, DEFAULT_VIDEO_CODEC, DEFAULT_VIDEO_MAP, DEFAULT_VIDEO_PACKET_SIZE, SERV_DOORBELL, SERV_MOTION_SENSOR, SERV_SPEAKER, SERV_STATELESS_PROGRAMMABLE_SWITCH, ) from .img_util import scale_jpeg_camera_image from .util import pid_is_alive _LOGGER = logging.getLogger(__name__) DOORBELL_SINGLE_PRESS = 0 DOORBELL_DOUBLE_PRESS = 1 DOORBELL_LONG_PRESS = 2 VIDEO_OUTPUT = ( "-map {v_map} -an " "-c:v {v_codec} " "{v_profile}" "-tune zerolatency -pix_fmt yuv420p " "-r {fps} " "-b:v {v_max_bitrate}k -bufsize {v_bufsize}k -maxrate {v_max_bitrate}k " "-payload_type 99 " "-ssrc {v_ssrc} -f rtp " "-srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params {v_srtp_key} " "srtp://{address}:{v_port}?rtcpport={v_port}&" "localrtcpport={v_port}&pkt_size={v_pkt_size}" ) AUDIO_OUTPUT = ( "-map {a_map} -vn " "-c:a {a_encoder} " "{a_application}" "-ac 1 -ar {a_sample_rate}k " "-b:a {a_max_bitrate}k -bufsize {a_bufsize}k " "-payload_type 110 " "-ssrc {a_ssrc} -f rtp " "-srtp_out_suite AES_CM_128_HMAC_SHA1_80 -srtp_out_params {a_srtp_key} " "srtp://{address}:{a_port}?rtcpport={a_port}&" "localrtcpport={a_port}&pkt_size={a_pkt_size}" ) SLOW_RESOLUTIONS = [ (320, 180, 15), (320, 240, 15), ] RESOLUTIONS = [ (320, 180), (320, 240), (480, 270), (480, 360), (640, 360), (640, 480), (1024, 576), (1024, 768), (1280, 720), (1280, 960), (1920, 1080), ] VIDEO_PROFILE_NAMES = ["baseline", "main", "high"] FFMPEG_WATCH_INTERVAL = timedelta(seconds=5) FFMPEG_WATCHER = "ffmpeg_watcher" FFMPEG_PID = "ffmpeg_pid" SESSION_ID = "session_id" CONFIG_DEFAULTS = { CONF_SUPPORT_AUDIO: DEFAULT_SUPPORT_AUDIO, CONF_MAX_WIDTH: DEFAULT_MAX_WIDTH, CONF_MAX_HEIGHT: DEFAULT_MAX_HEIGHT, CONF_MAX_FPS: DEFAULT_MAX_FPS, CONF_AUDIO_CODEC: DEFAULT_AUDIO_CODEC, CONF_AUDIO_MAP: DEFAULT_AUDIO_MAP, CONF_VIDEO_MAP: DEFAULT_VIDEO_MAP, CONF_VIDEO_CODEC: DEFAULT_VIDEO_CODEC, CONF_AUDIO_PACKET_SIZE: DEFAULT_AUDIO_PACKET_SIZE, CONF_VIDEO_PACKET_SIZE: DEFAULT_VIDEO_PACKET_SIZE, CONF_STREAM_COUNT: DEFAULT_STREAM_COUNT, } @TYPES.register("Camera") class Camera(HomeAccessory, PyhapCamera): """Generate a Camera accessory.""" def __init__(self, hass, driver, name, entity_id, aid, config): """Initialize a Camera accessory object.""" self._ffmpeg = hass.data[DATA_FFMPEG] for config_key in CONFIG_DEFAULTS: if config_key not in config: config[config_key] = CONFIG_DEFAULTS[config_key] max_fps = config[CONF_MAX_FPS] max_width = config[CONF_MAX_WIDTH] max_height = config[CONF_MAX_HEIGHT] resolutions = [ (w, h, fps) for w, h, fps in SLOW_RESOLUTIONS if w <= max_width and h <= max_height and fps < max_fps ] + [ (w, h, max_fps) for w, h in RESOLUTIONS if w <= max_width and h <= max_height ] video_options = { "codec": { "profiles": [ VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["BASELINE"], VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["MAIN"], VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["HIGH"], ], "levels": [ VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_1"], VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_2"], VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE4_0"], ], }, "resolutions": resolutions, } audio_options = { "codecs": [ {"type": "OPUS", "samplerate": 24}, {"type": "OPUS", "samplerate": 16}, ] } stream_address = config.get(CONF_STREAM_ADDRESS, get_local_ip()) options = { "video": video_options, "audio": audio_options, "address": stream_address, "srtp": True, "stream_count": config[CONF_STREAM_COUNT], } super().__init__( hass, driver, name, entity_id, aid, config, category=CATEGORY_CAMERA, options=options, ) self._char_motion_detected = None self.linked_motion_sensor = self.config.get(CONF_LINKED_MOTION_SENSOR) if self.linked_motion_sensor: state = self.hass.states.get(self.linked_motion_sensor) if state: serv_motion = self.add_preload_service(SERV_MOTION_SENSOR) self._char_motion_detected = serv_motion.configure_char( CHAR_MOTION_DETECTED, value=False ) self._async_update_motion_state(state) self._char_doorbell_detected = None self._char_doorbell_detected_switch = None self.linked_doorbell_sensor = self.config.get(CONF_LINKED_DOORBELL_SENSOR) if self.linked_doorbell_sensor: state = self.hass.states.get(self.linked_doorbell_sensor) if state: serv_doorbell = self.add_preload_service(SERV_DOORBELL) self.set_primary_service(serv_doorbell) self._char_doorbell_detected = serv_doorbell.configure_char( CHAR_PROGRAMMABLE_SWITCH_EVENT, value=0, ) serv_stateless_switch = self.add_preload_service( SERV_STATELESS_PROGRAMMABLE_SWITCH ) self._char_doorbell_detected_switch = serv_stateless_switch.configure_char( CHAR_PROGRAMMABLE_SWITCH_EVENT, value=0, valid_values={"SinglePress": DOORBELL_SINGLE_PRESS}, ) serv_speaker = self.add_preload_service(SERV_SPEAKER) serv_speaker.configure_char(CHAR_MUTE, value=0) self._async_update_doorbell_state(state) async def run_handler(self): """Handle accessory driver started event. Run inside the Home Assistant event loop. """ if self._char_motion_detected: async_track_state_change_event( self.hass, [self.linked_motion_sensor], self._async_update_motion_state_event, ) if self._char_doorbell_detected: async_track_state_change_event( self.hass, [self.linked_doorbell_sensor], self._async_update_doorbell_state_event, ) await super().run_handler() @callback def _async_update_motion_state_event(self, event): """Handle state change event listener callback.""" self._async_update_motion_state(event.data.get("new_state")) @callback def _async_update_motion_state(self, new_state): """Handle link motion sensor state change to update HomeKit value.""" if not new_state: return detected = new_state.state == STATE_ON if self._char_motion_detected.value == detected: return self._char_motion_detected.set_value(detected) _LOGGER.debug( "%s: Set linked motion %s sensor to %d", self.entity_id, self.linked_motion_sensor, detected, ) @callback def _async_update_doorbell_state_event(self, event): """Handle state change event listener callback.""" self._async_update_doorbell_state(event.data.get("new_state")) @callback def _async_update_doorbell_state(self, new_state): """Handle link doorbell sensor state change to update HomeKit value.""" if not new_state: return if new_state.state == STATE_ON: self._char_doorbell_detected.set_value(DOORBELL_SINGLE_PRESS) self._char_doorbell_detected_switch.set_value(DOORBELL_SINGLE_PRESS) _LOGGER.debug( "%s: Set linked doorbell %s sensor to %d", self.entity_id, self.linked_doorbell_sensor, DOORBELL_SINGLE_PRESS, ) @callback def async_update_state(self, new_state): """Handle state change to update HomeKit value.""" pass # pylint: disable=unnecessary-pass async def _async_get_stream_source(self): """Find the camera stream source url.""" stream_source = self.config.get(CONF_STREAM_SOURCE) if stream_source: return stream_source try: stream_source = await self.hass.components.camera.async_get_stream_source( self.entity_id ) except Exception: # pylint: disable=broad-except _LOGGER.exception( "Failed to get stream source - this could be a transient error or your camera might not be compatible with HomeKit yet" ) if stream_source: self.config[CONF_STREAM_SOURCE] = stream_source return stream_source async def start_stream(self, session_info, stream_config): """Start a new stream with the given configuration.""" _LOGGER.debug( "[%s] Starting stream with the following parameters: %s", session_info["id"], stream_config, ) input_source = await self._async_get_stream_source() if not input_source: _LOGGER.error("Camera has no stream source") return False if "-i " not in input_source: input_source = "-i " + input_source video_profile = "" if self.config[CONF_VIDEO_CODEC] != "copy": video_profile = ( "-profile:v " + VIDEO_PROFILE_NAMES[ int.from_bytes(stream_config["v_profile_id"], byteorder="big") ] + " " ) audio_application = "" if self.config[CONF_AUDIO_CODEC] == "libopus": audio_application = "-application lowdelay " output_vars = stream_config.copy() output_vars.update( { "v_profile": video_profile, "v_bufsize": stream_config["v_max_bitrate"] * 4, "v_map": self.config[CONF_VIDEO_MAP], "v_pkt_size": self.config[CONF_VIDEO_PACKET_SIZE], "v_codec": self.config[CONF_VIDEO_CODEC], "a_bufsize": stream_config["a_max_bitrate"] * 4, "a_map": self.config[CONF_AUDIO_MAP], "a_pkt_size": self.config[CONF_AUDIO_PACKET_SIZE], "a_encoder": self.config[CONF_AUDIO_CODEC], "a_application": audio_application, } ) output = VIDEO_OUTPUT.format(**output_vars) if self.config[CONF_SUPPORT_AUDIO]: output = output + " " + AUDIO_OUTPUT.format(**output_vars) _LOGGER.debug("FFmpeg output settings: %s", output) stream = HAFFmpeg(self._ffmpeg.binary, loop=self.driver.loop) opened = await stream.open( cmd=[], input_source=input_source, output=output, stdout_pipe=False ) if not opened: _LOGGER.error("Failed to open ffmpeg stream") return False _LOGGER.info( "[%s] Started stream process - PID %d", session_info["id"], stream.process.pid, ) session_info["stream"] = stream session_info[FFMPEG_PID] = stream.process.pid async def watch_session(_): await self._async_ffmpeg_watch(session_info["id"]) session_info[FFMPEG_WATCHER] = async_track_time_interval( self.hass, watch_session, FFMPEG_WATCH_INTERVAL, ) return await self._async_ffmpeg_watch(session_info["id"]) async def _async_ffmpeg_watch(self, session_id): """Check to make sure ffmpeg is still running and cleanup if not.""" ffmpeg_pid = self.sessions[session_id][FFMPEG_PID] if pid_is_alive(ffmpeg_pid): return True _LOGGER.warning("Streaming process ended unexpectedly - PID %d", ffmpeg_pid) self._async_stop_ffmpeg_watch(session_id) self.set_streaming_available(self.sessions[session_id]["stream_idx"]) return False @callback def _async_stop_ffmpeg_watch(self, session_id): """Cleanup a streaming session after stopping.""" if FFMPEG_WATCHER not in self.sessions[session_id]: return self.sessions[session_id].pop(FFMPEG_WATCHER)() async def stop_stream(self, session_info): """Stop the stream for the given ``session_id``.""" session_id = session_info["id"] stream = session_info.get("stream") if not stream: _LOGGER.debug("No stream for session ID %s", session_id) return self._async_stop_ffmpeg_watch(session_id) if not pid_is_alive(stream.process.pid): _LOGGER.info("[%s] Stream already stopped", session_id) return True for shutdown_method in ["close", "kill"]: _LOGGER.info("[%s] %s stream", session_id, shutdown_method) try: await getattr(stream, shutdown_method)() return except Exception: # pylint: disable=broad-except _LOGGER.exception( "[%s] Failed to %s stream", session_id, shutdown_method ) async def reconfigure_stream(self, session_info, stream_config): """Reconfigure the stream so that it uses the given ``stream_config``.""" return True def get_snapshot(self, image_size): """Return a jpeg of a snapshot from the camera.""" return scale_jpeg_camera_image( asyncio.run_coroutine_threadsafe( self.hass.components.camera.async_get_image(self.entity_id), self.hass.loop, ).result(), image_size["image-width"], image_size["image-height"], )
titilambert/home-assistant
homeassistant/components/homekit/type_cameras.py
Python
apache-2.0
15,437
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.Basic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void NavigationBetweenKeywords() { VisualStudio.Editor.SetText(@" Class C Sub Main() For a = 0 To 1 Step 1 For b = 0 To 2 Next b, a End Sub End Class"); Verify("To", 3); VisualStudio.ExecuteCommand("Edit.NextHighlightedReference"); VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true); } private void Verify(string marker, int expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); // Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTagCount()); } } }
VSadov/roslyn
src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicKeywordHighlighting.cs
C#
apache-2.0
1,976
var config, _ = require('underscore'), https = require('https'), futils = require('./fhutils'), fhutils; module.exports = function(cfg) { config = cfg; fhutils = new futils(config); return call; }; // // $fh.call() : Call back to millicore from our Node.js code. // NOT a public function but may be one day. // TODO - note that it uses hardcoded https here. var call = function call(path, params, callback) { var headers = { "accept": "application/json" }; var props = fhutils.getMillicoreProps(); headers["content-type"] = "application/json; charset=utf-8"; fhutils.addAppApiKeyHeader(headers); var options = { host: props.millicore, port: props.port, path: '/box/srv/1.1/' + path, method: 'POST', headers: headers }; var addParams = (params === undefined || params === null) ? {} : _.clone(params); addParams["instance"] = props.instId; addParams["widget"] = props.widgId; var fhResp = {}; var req = https.request(options, function(res) { fhResp.status = res.statusCode; // TODO - *both* of these are recommended ways of setting timeout on http requests.. // needs further investigation (and proper test case!!) // bob build didnt like below..above suggests it was never verified?? ... changed to this to add timeout //req.socket && req.socket.setTimeout(config.socketTimeout); //req.connection.setTimeout && req.connection.setTimeout(config.socketTimeout); req.on('socket', function(socket) { socket.setTimeout(config.socketTimeout); }); req.on('connect', function(res, socket) { socket.setTimeout(config.socketTimeout); }); var data = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { data += chunk; }); res.on('end', function() { fhResp.body = data; callback(undefined, fhResp); }); }); req.on('error', function(e) { console.error('Problem invoking: %s', e.message); callback(e); }); req.write(JSON.stringify(addParams) + "\n"); req.end(); };
feedhenry/fh-mbaas-api
lib/call.js
JavaScript
apache-2.0
2,043
package com.google.api.ads.adwords.jaxws.v201402.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Data used for authorization using OAuth. * For more information about OAuth, see: * {@link "https://developers.google.com/accounts/docs/OAuth2"} * * * <p>Java class for OAuthInfo complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OAuthInfo"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="httpMethod" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="httpRequestUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="httpAuthorizationHeader" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OAuthInfo", propOrder = { "httpMethod", "httpRequestUrl", "httpAuthorizationHeader" }) public class OAuthInfo { protected String httpMethod; protected String httpRequestUrl; protected String httpAuthorizationHeader; /** * Gets the value of the httpMethod property. * * @return * possible object is * {@link String } * */ public String getHttpMethod() { return httpMethod; } /** * Sets the value of the httpMethod property. * * @param value * allowed object is * {@link String } * */ public void setHttpMethod(String value) { this.httpMethod = value; } /** * Gets the value of the httpRequestUrl property. * * @return * possible object is * {@link String } * */ public String getHttpRequestUrl() { return httpRequestUrl; } /** * Sets the value of the httpRequestUrl property. * * @param value * allowed object is * {@link String } * */ public void setHttpRequestUrl(String value) { this.httpRequestUrl = value; } /** * Gets the value of the httpAuthorizationHeader property. * * @return * possible object is * {@link String } * */ public String getHttpAuthorizationHeader() { return httpAuthorizationHeader; } /** * Sets the value of the httpAuthorizationHeader property. * * @param value * allowed object is * {@link String } * */ public void setHttpAuthorizationHeader(String value) { this.httpAuthorizationHeader = value; } }
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/cm/OAuthInfo.java
Java
apache-2.0
3,004
package com.twitter.finagle.tracing import org.specs.SpecificationWithJUnit class SpanIdSpec extends SpecificationWithJUnit { "SpanId" should { "parse positive long" in { SpanId.fromString("7fffffffffffffff").get.toLong mustEqual Long.MaxValue } "parse negative long" in { SpanId.fromString("8000000000000000").get.toLong mustEqual Long.MinValue } "create a span with the ID 123 from hex '7b'" in { SpanId.fromString("7b").get.toLong mustEqual 123L } "return None if string is not valid hex" in { SpanId.fromString("rofl") must beNone } "represent a span with the ID 123 as the hex '000000000000007b'" in { SpanId(123L).toString mustEqual "000000000000007b" // padded for lexical ordering } "be equal if the underlying value is equal" in { val a = SpanId(1234L) val b = SpanId(1234L) a mustEqual b } } }
foursquare/finagle
finagle-core/src/test/scala/com/twitter/finagle/tracing/SpanIdSpec.scala
Scala
apache-2.0
912
import {async} from '../scheduler/async'; import {Operator} from '../Operator'; import {Scheduler} from '../Scheduler'; import {Subscriber} from '../Subscriber'; import {Observable} from '../Observable'; import {Subscription} from '../Subscription'; /** * Ignores source values for `duration` milliseconds, then emits the most recent * value from the source Observable, then repeats this process. * * <span class="informal">When it sees a source values, it ignores that plus * the next ones for `duration` milliseconds, and then it emits the most recent * value from the source.</span> * * <img src="./img/auditTime.png" width="100%"> * * `auditTime` is similar to `throttleTime`, but emits the last value from the * silenced time window, instead of the first value. `auditTime` emits the most * recent value from the source Observable on the output Observable as soon as * its internal timer becomes disabled, and ignores source values while the * timer is enabled. Initially, the timer is disabled. As soon as the first * source value arrives, the timer is enabled. After `duration` milliseconds (or * the time unit determined internally by the optional `scheduler`) has passed, * the timer is disabled, then the most recent source value is emitted on the * output Observable, and this process repeats for the next source value. * Optionally takes a {@link Scheduler} for managing timers. * * @example <caption>Emit clicks at a rate of at most one click per second</caption> * var clicks = Rx.Observable.fromEvent(document, 'click'); * var result = clicks.auditTime(1000); * result.subscribe(x => console.log(x)); * * @see {@link audit} * @see {@link debounceTime} * @see {@link delay} * @see {@link sampleTime} * @see {@link throttleTime} * * @param {number} duration Time to wait before emitting the most recent source * value, measured in milliseconds or the time unit determined internally * by the optional `scheduler`. * @param {Scheduler} [scheduler=async] The {@link Scheduler} to use for * managing the timers that handle the rate-limiting behavior. * @return {Observable<T>} An Observable that performs rate-limiting of * emissions from the source Observable. * @method auditTime * @owner Observable */ export function auditTime<T>(duration: number, scheduler: Scheduler = async): Observable<T> { return this.lift(new AuditTimeOperator(duration, scheduler)); } export interface AuditTimeSignature<T> { (duration: number, scheduler?: Scheduler): Observable<T>; } class AuditTimeOperator<T> implements Operator<T, T> { constructor(private duration: number, private scheduler: Scheduler) { } call(subscriber: Subscriber<T>, source: any): any { return source._subscribe(new AuditTimeSubscriber(subscriber, this.duration, this.scheduler)); } } /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ class AuditTimeSubscriber<T> extends Subscriber<T> { private value: T; private hasValue: boolean = false; private throttled: Subscription; constructor(destination: Subscriber<T>, private duration: number, private scheduler: Scheduler) { super(destination); } protected _next(value: T): void { this.value = value; this.hasValue = true; if (!this.throttled) { this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, this)); } } clearThrottle(): void { const { value, hasValue, throttled } = this; if (throttled) { this.remove(throttled); this.throttled = null; throttled.unsubscribe(); } if (hasValue) { this.value = null; this.hasValue = false; this.destination.next(value); } } } function dispatchNext<T>(subscriber: AuditTimeSubscriber<T>): void { subscriber.clearThrottle(); }
tzerb/Learning
WebApplication3/src/WebApplication3/jspm_packages/npm/rxjs@5.0.0-beta.9/src/operator/auditTime.ts
TypeScript
apache-2.0
3,856
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/hlo_computation.h" #include <algorithm> #include <cstddef> #include <functional> #include <list> #include <queue> #include <set> #include <sstream> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/memory/memory.h" #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/logging.h" namespace xla { using absl::StrCat; std::unique_ptr<HloComputation> HloComputation::Builder::Build( HloInstruction* root_instruction) { int parameter_count = 0; for (auto& instruction : instructions_) { if (instruction->opcode() == HloOpcode::kParameter) { parameter_count++; } } // If root_instruction is not specified use the last added instruction. HloInstruction* root = root_instruction ? root_instruction : last_added_instruction_; CHECK_NE(nullptr, root); return absl::WrapUnique(new HloComputation( name_, parameter_count, &instructions_, root, fusion_instruction_)); } HloComputation::HloComputation( const string& name, int parameter_count, std::vector<std::unique_ptr<HloInstruction>>* instructions, HloInstruction* root_instruction, HloInstruction* fusion_instruction) : name_(NameUniquer::GetSanitizedName(name)), unique_id_(-1), root_instruction_(root_instruction), fusion_instruction_(fusion_instruction) { param_instructions_.resize(parameter_count, nullptr); bool root_found = false; for (auto& instruction : *instructions) { if (instruction->opcode() == HloOpcode::kParameter) { int64 param_no = instruction->parameter_number(); CHECK(param_no >= 0 && param_no < parameter_count) << "\nERROR: invalid parameter number. Expected [0, " << parameter_count << "), got " << param_no; CHECK(param_instructions_[param_no] == nullptr) << "\nERROR: parameter number " << param_no << " already allocated in this computation"; param_instructions_[param_no] = instruction.get(); } root_found |= instruction.get() == root_instruction_; AddInstructionInternal(std::move(instruction)); } CHECK(root_found) << "\nERROR: root instruction is not present in computation."; } HloInstruction* HloComputation::AddInstruction( std::unique_ptr<HloInstruction> instruction) { CHECK(instruction->opcode() != HloOpcode::kParameter) << "Parameter instructions cannot be added to a computation after " << "it has been built"; return AddInstructionInternal(std::move(instruction)); } HloInstruction* HloComputation::AddInstructionInternal( std::unique_ptr<HloInstruction> instruction) { if (parent() != nullptr) { instruction->UniquifyName(&parent()->instruction_name_uniquer()); instruction->SetUniqueId(parent()->NewUniqueInstructionId()); } instruction->set_parent(this); HloInstruction* pinst = instruction.get(); instruction_iterators_[pinst] = instructions_.insert(instructions_.end(), std::move(instruction)); return pinst; } HloInstruction* HloComputation::AddParameter( std::unique_ptr<HloInstruction> instruction) { CHECK(instruction->opcode() == HloOpcode::kParameter); CHECK(IsFusionComputation()); CHECK(fusion_instruction_->operand_count() == param_instructions_.size()); instruction->set_parent(this); param_instructions_.push_back(instruction.get()); AddInstructionInternal(std::move(instruction)); return instructions_.back().get(); } Status HloComputation::RemoveParameter(int64 param_no) { CHECK_GE(param_no, 0); CHECK_LT(param_no, param_instructions_.size()); CHECK(IsFusionComputation()); HloInstruction* param_instruction = param_instructions_[param_no]; auto param_instruction_iterator = param_instructions_.begin() + param_no; param_instructions_.erase(param_instruction_iterator); // Throw removed fused parameter instruction away. TF_RETURN_IF_ERROR(RemoveInstruction(param_instruction)); while (param_no < param_instructions_.size()) { param_instruction = param_instructions_[param_no]; HloInstruction* new_instr = AddInstructionInternal(HloInstruction::CreateParameter( param_no, param_instruction->shape(), StrCat("param_", param_no))); TF_RETURN_IF_ERROR(param_instruction->ReplaceAllUsesWith(new_instr)); param_instructions_[param_no] = new_instr; TF_RETURN_IF_ERROR(RemoveInstruction(param_instruction)); param_no++; } return Status::OK(); } Status HloComputation::RemoveUnusedParameters() { CHECK(IsFusionComputation()); int64 removed = 0; for (int64 i = 0; i < param_instructions_.size(); ++i) { HloInstruction* param_instruction = param_instructions_[i]; if (param_instruction->user_count() == 0 && param_instruction != root_instruction()) { TF_RETURN_IF_ERROR(RemoveInstruction(param_instruction)); ++removed; continue; } if (removed > 0) { const int64 param_no = i - removed; HloInstruction* new_instr = AddInstructionInternal( HloInstruction::CreateParameter(param_no, param_instruction->shape(), StrCat("param_", param_no))); TF_RETURN_IF_ERROR(param_instruction->ReplaceAllUsesWith(new_instr)); param_instructions_[param_no] = new_instr; TF_RETURN_IF_ERROR(RemoveInstruction(param_instruction)); } } param_instructions_.resize(param_instructions_.size() - removed); return Status::OK(); } bool HloComputation::IsRemovable(const HloInstruction* instruction) { // If the instruction has control predecessors or successors then we cannot // remove the instruction without violating ordering constraints (added, for // example, to avert interference due to buffer aliasing). if (!instruction->control_predecessors().empty() || !instruction->control_successors().empty()) { return false; } if (instruction->opcode() == HloOpcode::kParameter && !IsFusionComputation()) { return false; } return true; } bool HloComputation::HasSideEffect() const { for (auto* instruction : instructions()) { if (instruction->HasSideEffect()) { return true; } } return false; } Status HloComputation::RemoveInstructionAndUnusedOperands( HloInstruction* instruction) { TF_RET_CHECK(root_instruction() != instruction); TF_RET_CHECK(instruction->user_count() == 0); TF_RET_CHECK(IsRemovable(instruction)) << "Cannot remove instruction: " << instruction->ToString(); std::unordered_set<HloInstruction*> removed; std::queue<HloInstruction*> worklist; worklist.push(instruction); while (!worklist.empty()) { HloInstruction* item = worklist.front(); worklist.pop(); if (removed.count(item) != 0 || item->user_count() != 0 || item == root_instruction() || !IsRemovable(item) || (item->HasSideEffect() && item != instruction)) { continue; } for (int i = 0; i < item->operand_count(); ++i) { worklist.push(item->mutable_operand(i)); } TF_RETURN_IF_ERROR(RemoveInstruction(item)); removed.insert(item); } return Status::OK(); } Status HloComputation::RemoveInstruction(HloInstruction* instruction) { VLOG(2) << "Removing instruction " << instruction->name() << " from computation " << name(); TF_RET_CHECK(IsRemovable(instruction)) << "cannot remove instruction: " << instruction->ToString(); TF_RET_CHECK(root_instruction() != instruction) << "cannot remove root instruction " << instruction->name(); TF_RET_CHECK(instruction->user_count() == 0) << "instruction " << instruction->name() << " has users and cannot be removed"; TF_RET_CHECK(instruction->control_predecessors().empty()) << "instruction " << instruction->name() << " has control predecessors and cannot be removed"; TF_RET_CHECK(instruction->control_successors().empty()) << "instruction " << instruction->name() << " has control successors and cannot be removed"; auto inst_it = instruction_iterators_.find(instruction); TF_RET_CHECK(inst_it != instruction_iterators_.end()); (*inst_it->second)->set_parent(nullptr); instructions_.erase(inst_it->second); instruction_iterators_.erase(inst_it); return Status::OK(); } void HloComputation::set_root_instruction(HloInstruction* new_root_instruction, bool accept_different_shape) { // The shape of the root (ignoring layout) is an invariant of the computation // for non-fusion cases. if (!IsFusionComputation() && !accept_different_shape) { CHECK(ShapeUtil::Compatible(new_root_instruction->shape(), root_instruction_->shape())) << new_root_instruction->shape() << " is incompatible with " << root_instruction_->shape(); } bool root_found = false; for (auto& instruction : instructions_) { if (new_root_instruction == instruction.get()) { root_found = true; break; } } DCHECK(root_found); root_instruction_ = new_root_instruction; } namespace { // Helper which builds a post order of the HLO call graph. void ComputeComputationPostOrder(HloComputation* computation, absl::flat_hash_set<HloComputation*>* visited, std::vector<HloComputation*>* post_order) { if (visited->insert(computation).second) { for (auto* instruction : computation->instructions()) { for (HloComputation* called_computation : instruction->called_computations()) { ComputeComputationPostOrder(called_computation, visited, post_order); } } post_order->push_back(computation); } } } // namespace void HloComputation::ComputeInstructionPostOrder( const HloComputation::ChannelDependencyMap& channel_dependency_map, std::vector<HloInstruction*>* post_order, HloInstruction* root, absl::flat_hash_map<HloInstruction*, VisitState>* visited) const { std::vector<HloInstruction*> dfs_stack; dfs_stack.push_back(root); while (!dfs_stack.empty()) { const auto current = dfs_stack.back(); auto it = visited->find(current); if (it != visited->end()) { if (it->second == kVisited) { // Already visited. dfs_stack.pop_back(); continue; } // Visit this node. CHECK_EQ(kVisiting, it->second); dfs_stack.pop_back(); post_order->push_back(current); it->second = kVisited; continue; } visited->insert({current, kVisiting}); // Add the operands to the stack in reverse order so the first operand is // processed first. This will produce a more natural ordering and a nicer // result for things like HLO stringification. const auto& operands = current->operands(); for (int64 i = operands.size() - 1; i >= 0; --i) { dfs_stack.emplace_back(operands[i]); } for (HloInstruction* op : current->control_predecessors()) { dfs_stack.emplace_back(op); } // Add inputs for send->recv_done dependencies and all-reduce // dependencies. switch (current->opcode()) { case HloOpcode::kRecvDone: { auto it = channel_dependency_map.find(current->channel_id()); if (it != channel_dependency_map.end()) { for (HloInstruction* op : it->second) { dfs_stack.emplace_back(op); } } break; } case HloOpcode::kAllReduce: { auto all_reduce_id = current->all_reduce_id(); if (all_reduce_id) { auto it = channel_dependency_map.find(all_reduce_id.value()); if (it != channel_dependency_map.end()) { for (HloInstruction* op : it->second) { dfs_stack.emplace_back(op); } } } break; } default: break; } } } HloComputation::ChannelDependencyMap HloComputation::ComputeChannelDependencies() const { ChannelDependencyMap channel_dependency_map; for (const auto& instruction : instructions_) { switch (instruction->opcode()) { case HloOpcode::kSend: { channel_dependency_map[instruction->channel_id()].push_back( instruction.get()); break; } case HloOpcode::kAllReduce: { auto all_reduce_id = instruction->all_reduce_id(); if (all_reduce_id) { auto& dependencies = channel_dependency_map[all_reduce_id.value()]; absl::c_copy(instruction->operands(), std::back_inserter(dependencies)); absl::c_copy(instruction->control_predecessors(), std::back_inserter(dependencies)); } break; } default: break; } } return channel_dependency_map; } std::vector<HloInstruction*> HloComputation::MakeInstructionPostOrder() const { auto channel_dependency_map = ComputeChannelDependencies(); std::vector<HloInstruction*> post_order; post_order.reserve(instruction_count()); std::vector<HloInstruction*> trace_instructions; absl::flat_hash_map<HloInstruction*, VisitState> visited; visited.reserve(instruction_count()); for (auto& instruction : instructions_) { if (instruction->opcode() == HloOpcode::kTrace) { // Trace instructions aren't handled by the DFS visitor. Add trace // instructions to the post order at the end (necessarily they have no // users). trace_instructions.push_back(instruction.get()); } else if (instruction->users().empty()) { ComputeInstructionPostOrder(channel_dependency_map, &post_order, instruction.get(), &visited); } } post_order.insert(post_order.end(), trace_instructions.begin(), trace_instructions.end()); CHECK_EQ(instructions_.size(), post_order.size()) << "number of instructions does not match post order size"; return post_order; } std::vector<HloComputation*> HloComputation::MakeEmbeddedComputationsList() const { absl::flat_hash_set<HloComputation*> visited; std::vector<HloComputation*> post_order; // To avoid special handling of this computation, cast away const of // 'this'. 'this' is immediately removed from the post order after // construction. // // TODO(b/78350259): This violates const-correctness, since while the original // computation is not returned, we still retrieve non-const computations from // a const one. Consider also avoiding const for HloComputation, or review XLA // for const-correctness of non-HloInstruction* types like this. ComputeComputationPostOrder(const_cast<HloComputation*>(this), &visited, &post_order); // We don't want to include this computation in the post order. CHECK_EQ(this, post_order.back()); post_order.pop_back(); return post_order; } string HloComputation::ToString(const HloPrintOptions& options) const { return ToString(options, MakeInstructionPostOrder()); } string HloComputation::ToString( const HloPrintOptions& options, absl::Span<const HloInstruction* const> instruction_order) const { CHECK_EQ(instruction_order.size(), instruction_count()); std::ostringstream s; for (int i = 0; i < options.indent_amount(); i++) { s << " "; } if (!options.is_in_nested_computation()) { if (options.print_percent()) { s << "%"; } s << name() << " "; } if (options.print_program_shape()) { s << ShapeUtil::HumanString(ComputeProgramShape()) << " "; } s << "{\n"; { // Print the instructions in this computation. HloPrintOptions new_options = options; new_options.set_indent_amount(options.indent_amount() + 1) .set_is_in_nested_computation(true); CanonicalNameMap name_map; for (const HloInstruction* instruction : instruction_order) { CHECK_EQ(this, instruction->parent()); for (int i = 0; i < new_options.indent_amount(); i++) { s << " "; } s << (instruction == root_instruction_ ? "ROOT " : "") << instruction->ToStringWithCanonicalNameMap(new_options, &name_map) << "\n"; } } for (int i = 0; i < options.indent_amount(); i++) { s << " "; } s << "}"; return s.str(); } HloComputationProto HloComputation::ToProto() const { HloComputationProto proto; CHECK(unique_id_ != -1) << "This computation does not have a valid id. Please make sure the " "computation is inside a module before dumping it."; proto.set_id(unique_id_); proto.set_name(name_); for (const HloInstruction* instruction : MakeInstructionPostOrder()) { HloInstructionProto instruction_proto = instruction->ToProto(); proto.add_instructions()->Swap(&instruction_proto); } proto.set_root_id(root_instruction()->unique_id()); *proto.mutable_program_shape() = ComputeProgramShape().ToProto(); return proto; } /* static */ StatusOr<std::unique_ptr<HloComputation>> HloComputation::CreateFromProto( const HloComputationProto& proto, const absl::flat_hash_map<int64, HloComputation*>& computation_map) { absl::flat_hash_map<int64, HloInstruction*> instruction_map; absl::flat_hash_map<HloInstruction*, int64> to_proto_id; std::vector<std::unique_ptr<HloInstruction>> instructions; int64 parameter_count = 0; for (const HloInstructionProto& instruction_proto : proto.instructions()) { TF_ASSIGN_OR_RETURN( std::unique_ptr<HloInstruction> instruction, HloInstruction::CreateFromProto(instruction_proto, instruction_map, computation_map)); if (instruction->opcode() == HloOpcode::kParameter) { parameter_count++; } TF_RET_CHECK(!ContainsKey(instruction_map, instruction_proto.id())); instruction_map[instruction_proto.id()] = instruction.get(); to_proto_id[instruction.get()] = instruction_proto.id(); instructions.push_back(std::move(instruction)); } TF_RET_CHECK(proto.root_id() != -1); TF_RET_CHECK(ContainsKey(instruction_map, proto.root_id())); HloInstruction* root = instruction_map.at(proto.root_id()); // Sort the instructions in the proto id's order. std::sort(instructions.begin(), instructions.end(), [&](const std::unique_ptr<HloInstruction>& a, const std::unique_ptr<HloInstruction>& b) { return to_proto_id[a.get()] < to_proto_id[b.get()]; }); TF_RETURN_IF_ERROR([&]() -> Status { std::vector<bool> parameters_seen(parameter_count); int parameters_seen_count = 0; for (auto& instruction : instructions) { if (instruction->opcode() == HloOpcode::kParameter) { int64 param_no = instruction->parameter_number(); TF_RET_CHECK(param_no >= 0 && param_no < parameter_count) << "Invalid parameter number. Expected [0, " << parameter_count << "), got " << param_no; TF_RET_CHECK(!parameters_seen[param_no]) << "Parameter number " << param_no << " already allocated in this computation"; parameters_seen[param_no] = true; parameters_seen_count++; } } TF_RET_CHECK(parameters_seen_count == parameter_count) << "Not all parameters in range [0, " << parameter_count << ") were referenced"; return Status::OK(); }()); auto computation = absl::WrapUnique( new HloComputation(proto.name(), parameter_count, &instructions, root, /*fusion_instruction=*/nullptr)); computation->unique_id_ = proto.id(); return std::move(computation); } void HloComputation::FuseInstructionsInto( absl::Span<HloInstruction* const> instructions_to_fuse, HloInstruction* fusion_instruction) { CHECK_EQ(HloOpcode::kFusion, fusion_instruction->opcode()); HloInstruction* root = instructions_to_fuse.front(); TF_CHECK_OK(root->ReplaceAllUsesWith(fusion_instruction)); if (root == root_instruction()) { set_root_instruction(fusion_instruction); } TF_CHECK_OK(RemoveInstruction(root)); for (size_t i = 1; i < instructions_to_fuse.size(); ++i) { HloInstruction* instruction = instructions_to_fuse[i]; fusion_instruction->FuseInstruction(instruction); if (instruction->user_count() == 0) { TF_CHECK_OK(RemoveInstruction(instruction)); } } } HloInstruction* HloComputation::CreateFusionInstruction( absl::Span<HloInstruction* const> instructions_to_fuse, HloInstruction::FusionKind fusion_kind) { HloInstruction* root = instructions_to_fuse.front(); HloInstruction* fusion_instruction = AddInstruction( HloInstruction::CreateFusion(root->shape(), fusion_kind, root)); FuseInstructionsInto(instructions_to_fuse, fusion_instruction); return fusion_instruction; } StatusOr<HloInstruction*> HloComputation::DeepCopyHelper( HloInstruction* instruction, ShapeIndex* index, const std::function< HloInstruction*(HloInstruction* leaf, const ShapeIndex& leaf_index, HloComputation* computation)>& copy_leaf) { if (instruction->shape().IsTuple()) { std::vector<HloInstruction*> elements; for (int64 i = 0; i < ShapeUtil::TupleElementCount(instruction->shape()); i++) { HloInstruction* gte = AddInstruction(HloInstruction::CreateGetTupleElement( ShapeUtil::GetTupleElementShape(instruction->shape(), i), instruction, i)); index->push_back(i); TF_ASSIGN_OR_RETURN(HloInstruction * element, DeepCopyHelper(gte, index, copy_leaf)); elements.push_back(element); index->pop_back(); } return AddInstruction(HloInstruction::CreateTuple(elements)); } if (instruction->shape().IsToken()) { // Tokens have no on-device representation and cannot be copied. Pass // through transparently. return instruction; } // Array shape. TF_RET_CHECK(instruction->shape().IsArray()); return copy_leaf(instruction, *index, this); } StatusOr<HloInstruction*> HloComputation::DeepCopyInstruction( HloInstruction* instruction, const ShapeTree<bool>* indices_to_copy, ShapeTree<HloInstruction*>* copies_added) { if (instruction->parent() != this) { return FailedPrecondition( "Can't deep copy instruction %s: instruction is not in computation %s", instruction->name(), name()); } if (indices_to_copy != nullptr && !ShapeUtil::Compatible(instruction->shape(), indices_to_copy->shape())) { return FailedPrecondition( "Can't deep copy instruction %s: given shape tree of indices to copy " "has incompatible shapes: %s vs. %s", instruction->name(), ShapeUtil::HumanString(instruction->shape()), ShapeUtil::HumanString(indices_to_copy->shape())); } ShapeIndex index; auto copy_leaf = [indices_to_copy, copies_added]( HloInstruction* leaf, const ShapeIndex& leaf_index, HloComputation* computation) { if (indices_to_copy == nullptr || indices_to_copy->element(leaf_index)) { HloInstruction* copy = computation->AddInstruction( HloInstruction::CreateUnary(leaf->shape(), HloOpcode::kCopy, leaf)); if (copies_added != nullptr) { *copies_added->mutable_element(leaf_index) = copy; } return copy; } // Elements which are not to be copied are passed through // transparently. return leaf; }; return DeepCopyHelper(instruction, &index, copy_leaf); } StatusOr<HloInstruction*> HloComputation::DeepCopyInstructionWithCustomCopier( HloInstruction* instruction, const std::function< HloInstruction*(HloInstruction* leaf, const ShapeIndex& leaf_index, HloComputation* computation)>& copy_leaf) { if (instruction->parent() != this) { return FailedPrecondition( "Can't deep copy instruction %s: instruction is not in computation %s", instruction->name(), name()); } ShapeIndex index; return DeepCopyHelper(instruction, &index, copy_leaf); } ProgramShape HloComputation::ComputeProgramShape() const { ProgramShape program_shape; for (auto* param_instruction : param_instructions_) { *program_shape.add_parameters() = param_instruction->shape(); *program_shape.add_parameter_names() = param_instruction->name(); } *program_shape.mutable_result() = root_instruction_->shape(); return program_shape; } bool HloComputation::operator==(const HloComputation& other) const { if (this == &other) { return true; } std::set<std::pair<const HloInstruction*, const HloInstruction*>> visited; std::function<bool(const HloInstruction*, const HloInstruction*)> eq = [&visited, &eq](const HloInstruction* a, const HloInstruction* b) { // If <a,b> are visited but not identical, the recursion should have // been aborted. So, if <a,b> are visited at this point, they must be // identical. if (visited.count(std::make_pair(a, b)) > 0) { return true; } visited.emplace(a, b); return a->Identical( *b, eq, [](const HloComputation* a, const HloComputation* b) { return *a == *b; }); }; return eq(root_instruction(), other.root_instruction()); } Status HloComputation::ReplaceWithNewInstruction( HloInstruction* old_instruction, std::unique_ptr<HloInstruction> new_instruction) { return ReplaceInstruction(old_instruction, AddInstruction(std::move(new_instruction))); } Status HloComputation::ReplaceInstruction(HloInstruction* old_instruction, HloInstruction* new_instruction) { TF_RET_CHECK( ShapeUtil::Compatible(old_instruction->shape(), new_instruction->shape())) << ShapeUtil::HumanString(old_instruction->shape()) << " vs " << ShapeUtil::HumanString(new_instruction->shape()); VLOG(10) << "transformed " << old_instruction->ToString() << " to " << new_instruction->ToString(); // Try to add metadata for HLO instructions that are created to replace // existing HLO instructions (e.g. during optimizations). The assumption is // that the old instruction and the new instruction would perform the same // function, and that they would be correlated to the same TF op. This might // not always be correct since HLO optimizations can cross TF op boundaries. // But still this seems to be better than nothing. if (new_instruction->metadata().op_name().empty()) { new_instruction->set_metadata(old_instruction->metadata()); } TF_RETURN_IF_ERROR(old_instruction->ReplaceAllUsesWith(new_instruction)); return RemoveInstructionAndUnusedOperands(old_instruction); } std::vector<HloInstruction*> HloComputation::CollectUnreachableRoots() const { std::vector<HloInstruction*> unreachable_roots; for (auto* instruction : instructions()) { if (instruction->user_count() == 0 && instruction->control_successors().empty() && instruction != root_instruction()) { unreachable_roots.push_back(instruction); } } VLOG(3) << "Unreachable roots:" << absl::StrJoin(unreachable_roots, "\n\t", [](string* out, const HloInstruction* hlo) { absl::StrAppend(out, hlo->ToString()); }); return unreachable_roots; } template <typename HloInstructionPtr> Status HloComputation::Accept( DfsHloVisitorBase<HloInstructionPtr>* visitor) const { // Visit unreachable roots. Beware that the visitor might delete the currently // visited root, which would invalidate iterators if the unreachable roots // weren't computed ahead of time. for (HloInstruction* root : CollectUnreachableRoots()) { VLOG(3) << "Traversing unreachable root: " << root->ToString(); // Call FinishVisit only at the end. TF_RETURN_IF_ERROR(root->Accept(visitor, /*call_finish_visit=*/false)); } // Visit the computation root instruction last. return root_instruction()->Accept(visitor, /*call_finish_visit=*/true); } // Explicit instantiations. template Status HloComputation::Accept(DfsHloVisitor* visitor) const; template Status HloComputation::Accept(ConstDfsHloVisitor* visitor) const; Status HloComputation::AcceptWithOperandOrder( DfsHloVisitor* visitor, const HloInstruction::CompareFunction& operand_order) const { // Visit unreachable roots. Beware that the visitor might delete the currently // visited root, which would invalidate iterators if the unreachable roots // weren't computed ahead of time. for (HloInstruction* root : CollectUnreachableRoots()) { TF_RETURN_IF_ERROR( root->AcceptWithOperandOrder(visitor, operand_order, /*call_finish_visit=*/false)); } // Visit the computation root instruction last. return root_instruction()->AcceptWithOperandOrder(visitor, operand_order, /*call_finish_visit=*/true); } template <typename HloInstructionPtr> Status HloComputation::AcceptOrdered( DfsHloVisitorBase<HloInstructionPtr>* visitor, absl::Span<HloInstruction* const> order) const { VLOG(3) << "Accepting visitor with order."; for (HloInstruction* root : CollectUnreachableRoots()) { TF_RET_CHECK(std::find(order.begin(), order.end(), root) != order.end()) << root->ToString(); } TF_RET_CHECK(order.size() == instruction_count()); std::unordered_set<const HloInstruction*> visited; for (const HloInstruction* instruction : order) { VLOG(3) << "Visiting ordered: " << instruction->ToString(); TF_RET_CHECK(instruction_iterators_.count(instruction) == 1) << "Instruction " << instruction->name() << " is not in computation " << name(); TF_RET_CHECK(visited.count(instruction) == 0) << "Instruction " << instruction->name() << " appears more than once in order"; HloInstruction* mutable_instruction = const_cast<HloInstruction*>(instruction); TF_RETURN_IF_ERROR(visitor->Preprocess(mutable_instruction)); TF_RETURN_IF_ERROR(mutable_instruction->Visit(visitor)); visitor->SetVisited(*mutable_instruction); TF_RETURN_IF_ERROR(visitor->Postprocess(mutable_instruction)); visited.insert(instruction); } TF_RETURN_IF_ERROR(visitor->FinishVisit(root_instruction())); return Status::OK(); } // Explicit instantiations. template Status HloComputation::AcceptOrdered( DfsHloVisitor*, absl::Span<HloInstruction* const>) const; template Status HloComputation::AcceptOrdered( ConstDfsHloVisitor*, absl::Span<HloInstruction* const>) const; Status HloComputation::Accept( const std::function<Status(HloInstruction*)>& visitor_func) { FunctionVisitor visitor(visitor_func); return this->Accept(&visitor); } Status HloComputation::Accept( const std::function<Status(const HloInstruction*)>& visitor_func) const { ConstFunctionVisitor visitor(visitor_func); return this->Accept(&visitor); } std::unique_ptr<HloComputation> HloComputation::Clone( const string& suffix, HloCloneContext* context) { return CloneWithReplacements( /*replacements=*/std::unordered_map<const HloInstruction*, std::unique_ptr<HloInstruction>>(), context, suffix); } std::unique_ptr<HloComputation> HloComputation::CloneWithReplacementPairs( std::pair<const HloInstruction*, std::unique_ptr<HloInstruction>> r1, HloCloneContext* context, const string& suffix) { std::unordered_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; replacements.emplace(std::move(r1)); return CloneWithReplacements(std::move(replacements), context, suffix); } std::unique_ptr<HloComputation> HloComputation::CloneWithReplacementPairs( std::pair<const HloInstruction*, std::unique_ptr<HloInstruction>> r1, std::pair<const HloInstruction*, std::unique_ptr<HloInstruction>> r2, HloCloneContext* context, const string& suffix) { std::unordered_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; replacements.emplace(std::move(r1)); replacements.emplace(std::move(r2)); return CloneWithReplacements(std::move(replacements), context, suffix); } std::unique_ptr<HloComputation> HloComputation::CloneWithReplacementPairs( std::pair<const HloInstruction*, std::unique_ptr<HloInstruction>> r1, std::pair<const HloInstruction*, std::unique_ptr<HloInstruction>> r2, std::pair<const HloInstruction*, std::unique_ptr<HloInstruction>> r3, HloCloneContext* context, const string& suffix) { std::unordered_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements; replacements.emplace(std::move(r1)); replacements.emplace(std::move(r2)); replacements.emplace(std::move(r3)); return CloneWithReplacements(std::move(replacements), context, suffix); } std::unique_ptr<HloComputation> HloComputation::CloneWithReplacements( std::unordered_map<const HloInstruction*, std::unique_ptr<HloInstruction>> replacements, HloCloneContext* context, const string& suffix) { std::unique_ptr<HloCloneContext> context_ptr; if (context == nullptr) { context_ptr = absl::make_unique<HloCloneContext>(parent(), suffix); context = context_ptr.get(); } // Look up instr in the replacements map, and return either the replacement, // or instr, if the replacement isn't present. // // Note: This can return null, indicating that instr should not be present in // the new computation. auto replace = [&](HloInstruction* instr) { auto it = replacements.find(instr); if (it == replacements.end()) { return instr; } return it->second.get(); }; VLOG(1) << "Cloning " << name() << " --> " << suffix << "\n"; // We want to do a postorder walk over [replace(i) for i in instructions_]. // We can't reuse MakeInstructionPostOrder() for this, because that will // generate a postorder of plain instructions_, and our replacements may // change the postorder! // // The postorder we want here is simpler than what MakeInstructionPostOrder() // does -- we only care about operand dependencies -- so let's just do it // ourselves. std::vector<HloInstruction*> postorder; absl::flat_hash_map<HloInstruction*, VisitState> visited; for (const auto& instr : instructions_) { std::vector<HloInstruction*> dfs_stack; HloInstruction* new_instr = replace(instr.get()); if (!new_instr) { continue; } dfs_stack.push_back(new_instr); while (!dfs_stack.empty()) { auto* cur = dfs_stack.back(); auto it = visited.find(cur); if (it != visited.end()) { dfs_stack.pop_back(); if (it->second == kVisited) { continue; } CHECK_EQ(it->second, kVisiting); postorder.push_back(cur); it->second = kVisited; continue; } visited.insert({cur, kVisiting}); for (HloInstruction* operand : cur->operands()) { HloInstruction* new_operand = replace(operand); if (new_operand) { dfs_stack.emplace_back(new_operand); } } } } std::vector<std::unique_ptr<HloInstruction>> instructions; for (auto instr : postorder) { std::vector<HloInstruction*> new_operands; for (auto operand : instr->operands()) { auto replaced_operand = replace(operand); CHECK_NE(replaced_operand, nullptr) << "replacements map tried to eliminate a used instruction " << operand->ToString() << ", used by " << instr->ToString(); new_operands.push_back(context->GetInstruction(replaced_operand)); } instructions.push_back( instr->CloneWithNewOperands(instr->shape(), new_operands, context)); } Builder builder(name() + "." + suffix); for (auto& instr : instructions) { builder.AddInstruction(std::move(instr)); } auto result = builder.Build( /*root_instruction=*/context->GetInstruction( replace(root_instruction()))); // Clone control dependencies. for (auto instr : postorder) { HloInstruction* new_instr = context->GetInstruction(instr); for (auto successor : instr->control_successors()) { auto replaced_successor = replace(successor); // successor may not have been remapped, because it might have been // removed by the replacements map. if (replaced_successor != nullptr) { TF_CHECK_OK(new_instr->AddControlDependencyTo( context->GetInstruction(replaced_successor))); } } } context->MapComputation(this, result.get()); return result; } void HloComputation::UniquifyName(NameUniquer* name_uniquer) { name_ = name_uniquer->GetUniqueName(name_); } HloInstruction* HloComputation::GetInstructionWithName(absl::string_view name) { auto instructions_in_computation = instructions(); auto it = absl::c_find_if( instructions_in_computation, [&](HloInstruction* instr) { return instr->name() == name; }); return it == instructions_in_computation.end() ? nullptr : *it; } } // namespace xla
hfp/tensorflow-xsmm
tensorflow/compiler/xla/service/hlo_computation.cc
C++
apache-2.0
38,469
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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 herddb.index.brin; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; import herddb.codec.RecordSerializer; import herddb.core.AbstractIndexManager; import herddb.core.AbstractTableManager; import herddb.core.HerdDBInternalException; import herddb.core.MemoryManager; import herddb.core.PageReplacementPolicy; import herddb.core.PostCheckpointAction; import herddb.core.TableSpaceManager; import herddb.index.IndexOperation; import herddb.index.SecondaryIndexPrefixScan; import herddb.index.SecondaryIndexRangeScan; import herddb.index.SecondaryIndexSeek; import herddb.index.brin.BlockRangeIndexMetadata.BlockMetadata; import herddb.log.CommitLog; import herddb.log.LogSequenceNumber; import herddb.model.Index; import herddb.model.StatementEvaluationContext; import herddb.model.StatementExecutionException; import herddb.model.Table; import herddb.model.TableContext; import herddb.sql.SQLRecordKeyFunction; import herddb.storage.DataStorageManager; import herddb.storage.DataStorageManagerException; import herddb.storage.IndexStatus; import herddb.utils.Bytes; import herddb.utils.DataAccessor; import herddb.utils.ExtendedDataInputStream; import herddb.utils.ExtendedDataOutputStream; import herddb.utils.SimpleByteArrayInputStream; /** * Block-range like index with pagination managed by a {@link PageReplacementPolicy} * * @author enrico.olivelli * @author diego.salvi */ public class BRINIndexManager extends AbstractIndexManager { private static final Logger LOGGER = Logger.getLogger(BRINIndexManager.class.getName()); LogSequenceNumber bootSequenceNumber; private final AtomicLong newPageId = new AtomicLong(1); private final BlockRangeIndex<Bytes, Bytes> data; private final IndexDataStorage<Bytes, Bytes> storageLayer = new IndexDataStorageImpl(); public BRINIndexManager(Index index, MemoryManager memoryManager, AbstractTableManager tableManager, CommitLog log, DataStorageManager dataStorageManager, TableSpaceManager tableSpaceManager, String tableSpaceUUID, long transaction) { super(index, tableManager, dataStorageManager, tableSpaceManager.getTableSpaceUUID(), log, transaction); this.data = new BlockRangeIndex<>( memoryManager.getMaxLogicalPageSize(), memoryManager.getDataPageReplacementPolicy(), storageLayer); } private static final class PageContents { public static final int TYPE_METADATA = 9; public static final int TYPE_BLOCKDATA = 10; private int type; private List<Map.Entry<Bytes, Bytes>> pageData; private List<BlockRangeIndexMetadata.BlockMetadata<Bytes>> metadata; byte[] serialize() throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(1024); ExtendedDataOutputStream eout = new ExtendedDataOutputStream(out)) { serialize(eout); eout.flush(); return out.toByteArray(); } } void serialize(ExtendedDataOutputStream out) throws IOException { out.writeVLong(2); // version out.writeVLong(0); // flags for future implementations out.writeVInt(this.type); switch (type) { case TYPE_METADATA: out.writeVInt(metadata.size()); for (BlockRangeIndexMetadata.BlockMetadata<Bytes> md : metadata) { /* First key is null if is the head block */ boolean head = md.firstKey == null; /* Next block is null if is the tail block */ boolean tail = md.nextBlockId == null; /* Prepares hasd/tail flags */ byte blockFlags = 0; if (head) { blockFlags |= BlockMetadata.HEAD; } if (tail) { blockFlags |= BlockMetadata.TAIL; } out.writeByte(blockFlags); if (!head) { out.writeArray(md.firstKey.data); } out.writeVLong(md.blockId); out.writeVLong(md.size); out.writeVLong(md.pageId); if (!tail) { out.writeVLong(md.nextBlockId); } } break; case TYPE_BLOCKDATA: out.writeVInt(pageData.size()); for (Map.Entry<Bytes, Bytes> entry : pageData) { out.writeArray(entry.getKey().data); out.writeArray(entry.getValue().data); } break; default: throw new IllegalStateException("bad index page type " + type); } } static PageContents deserialize(ExtendedDataInputStream in) throws IOException { long version = in.readVLong(); // version long flags = in.readVLong(); // flags for future implementations /* Only version 2 actually supported, older versions will need a full rebuild */ if (version < 2) { throw new UnsupportedMetadataVersionException(version); } if (version > 2 || flags != 0) { throw new DataStorageManagerException("corrupted index page"); } PageContents result = new PageContents(); result.type = in.readVInt(); switch (result.type) { case TYPE_METADATA: int blocks = in.readVInt(); result.metadata = new ArrayList<>(); for (int i = 0; i < blocks; i++) { byte blockFlags = in.readByte(); Bytes firstKey; if ((blockFlags & BlockMetadata.HEAD) > 0) { /* Is HEAD */ /* First key is null if is the head block */ firstKey = null; } else { firstKey = Bytes.from_array(in.readArray()); } long blockId = in.readVLong(); long size = in.readVLong(); long pageId = in.readVLong(); Long nextBlockId; if ((blockFlags & BlockMetadata.TAIL) > 0) { /* Is TAIL */ /* Next block is null if is the tail block */ nextBlockId = null; } else { nextBlockId = in.readVLong(); } BlockRangeIndexMetadata.BlockMetadata<Bytes> md = new BlockRangeIndexMetadata.BlockMetadata<>(firstKey, blockId, size, pageId, nextBlockId); result.metadata.add(md); } break; case TYPE_BLOCKDATA: int values = in.readVInt(); result.pageData = new ArrayList<>(values); for (int i = 0; i < values; i++) { Bytes key = Bytes.from_array(in.readArray()); Bytes value = Bytes.from_array(in.readArray()); result.pageData.add(new AbstractMap.SimpleImmutableEntry<>(key, value)); } break; default: throw new IOException("bad index page type " + result.type); } return result; } static PageContents deserialize(byte[] pagedata) throws IOException { try (SimpleByteArrayInputStream in = new SimpleByteArrayInputStream(pagedata); ExtendedDataInputStream ein = new ExtendedDataInputStream(in)) { return deserialize(ein); } } } /** * Signal that an old unsupported version of page metadata has been read. In * such cases the index will need a full rebuild. */ private static final class UnsupportedMetadataVersionException extends HerdDBInternalException { /** Default Serial Version UID */ private static final long serialVersionUID = 1L; private final long version; public UnsupportedMetadataVersionException(long version) { super(); this.version = version; } } @Override protected boolean doStart(LogSequenceNumber sequenceNumber) throws DataStorageManagerException { LOGGER.log(Level.SEVERE, " start index {0} uuid {1}", new Object[]{index.name, index.uuid}); bootSequenceNumber = sequenceNumber; if (LogSequenceNumber.START_OF_TIME.equals(sequenceNumber)) { /* Empty index (booting from the start) */ this.data.boot(BlockRangeIndexMetadata.empty()); LOGGER.log(Level.SEVERE, "loaded empty index {0}", new Object[]{index.name}); return true; } else { IndexStatus status; try { status = dataStorageManager.getIndexStatus(tableSpaceUUID, index.uuid, sequenceNumber); } catch (DataStorageManagerException e) { LOGGER.log(Level.SEVERE, "cannot load index {0} due to {1}, it will be rebuilt", new Object[] {index.name, e}); return false; } try { PageContents metadataBlock = PageContents.deserialize(status.indexData); this.data.boot(new BlockRangeIndexMetadata<>(metadataBlock.metadata)); } catch (IOException e) { throw new DataStorageManagerException(e); } catch (UnsupportedMetadataVersionException e) { LOGGER.log(Level.SEVERE, "cannot load index {0} due to an old metadata version ({1}) found, it will be rebuilt", new Object[] {index.name, e.version}); return false; } newPageId.set(status.newPageId); LOGGER.log(Level.SEVERE, "loaded index {0} {1} blocks", new Object[]{index.name, this.data.getNumBlocks()}); return true; } } @Override public void rebuild() throws DataStorageManagerException { long _start = System.currentTimeMillis(); LOGGER.log(Level.SEVERE, "rebuilding index {0}", index.name); data.reset(); Table table = tableManager.getTable(); tableManager.scanForIndexRebuild(r -> { DataAccessor values = r.getDataAccessor(table); Bytes key = RecordSerializer.serializePrimaryKey(values, table, table.primaryKey); Bytes indexKey = RecordSerializer.serializePrimaryKey(values, index, index.columnNames); // LOGGER.log(Level.SEVERE, "adding " + key + " -> " + values); recordInserted(key, indexKey); }); long _stop = System.currentTimeMillis(); LOGGER.log(Level.SEVERE, "rebuilding index {0} took {1}", new Object[]{index.name, (_stop - _start) + " ms"}); } @Override public List<PostCheckpointAction> checkpoint(LogSequenceNumber sequenceNumber, boolean pin) throws DataStorageManagerException { try { BlockRangeIndexMetadata<Bytes> metadata = data.checkpoint(); PageContents page = new PageContents(); page.type = PageContents.TYPE_METADATA; page.metadata = metadata.getBlocksMetadata(); byte[] contents = page.serialize(); Set<Long> activePages = new HashSet<>(); page.metadata.forEach(b -> { activePages.add(b.pageId); }); IndexStatus indexStatus = new IndexStatus(index.name, sequenceNumber, newPageId.get(), activePages, contents); List<PostCheckpointAction> result = new ArrayList<>(); result.addAll(dataStorageManager.indexCheckpoint(tableSpaceUUID, index.uuid, indexStatus, pin)); LOGGER.log(Level.INFO, "checkpoint index {0} finished: logpos {1}, {2} blocks", new Object[] {index.name, sequenceNumber, Integer.toString(page.metadata.size())}); LOGGER.log(Level.FINE, "checkpoint index {0} finished: logpos {1}, pages {2}", new Object[] {index.name, sequenceNumber, activePages}); return result; } catch (IOException err) { throw new DataStorageManagerException(err); } } @Override public void unpinCheckpoint(LogSequenceNumber sequenceNumber) throws DataStorageManagerException { dataStorageManager.unPinIndexCheckpoint(tableSpaceUUID, index.uuid, sequenceNumber); } @Override protected Stream<Bytes> scanner(IndexOperation operation, StatementEvaluationContext context, TableContext tableContext) throws StatementExecutionException { if (operation instanceof SecondaryIndexSeek) { SecondaryIndexSeek sis = (SecondaryIndexSeek) operation; SQLRecordKeyFunction value = sis.value; byte[] refvalue = value.computeNewValue(null, context, tableContext); return data.query(Bytes.from_array(refvalue)); } else if (operation instanceof SecondaryIndexPrefixScan) { SecondaryIndexPrefixScan sis = (SecondaryIndexPrefixScan) operation; SQLRecordKeyFunction value = sis.value; byte[] refvalue = value.computeNewValue(null, context, tableContext); Bytes firstKey = Bytes.from_array(refvalue); Bytes lastKey = firstKey.next(); return data.query(firstKey, lastKey); } else if (operation instanceof SecondaryIndexRangeScan) { Bytes firstKey = null; Bytes lastKey = null; SecondaryIndexRangeScan sis = (SecondaryIndexRangeScan) operation; SQLRecordKeyFunction minKey = sis.minValue; if (minKey != null) { byte[] refminvalue = minKey.computeNewValue(null, context, tableContext); firstKey = Bytes.from_array(refminvalue); } SQLRecordKeyFunction maxKey = sis.maxValue; if (maxKey != null) { byte[] refmaxvalue = maxKey.computeNewValue(null, context, tableContext); lastKey = Bytes.from_array(refmaxvalue); } LOGGER.log(Level.FINE, "range scan on {0}.{1}, from {2} to {1}", new Object[]{index.table, index.name, firstKey, lastKey}); return data.query(firstKey, lastKey); } else { throw new UnsupportedOperationException("unsuppported index access type " + operation); } } @Override public void recordDeleted(Bytes key, Bytes indexKey) { data.delete(indexKey, key); } @Override public void recordInserted(Bytes key, Bytes indexKey) { data.put(indexKey, key); } @Override public void recordUpdated(Bytes key, Bytes indexKeyRemoved, Bytes indexKeyAdded) { if (Objects.equals(indexKeyRemoved, indexKeyAdded)) { return; } // BEWARE that this operation is not atomic if (indexKeyAdded != null) { data.put(indexKeyAdded, key); } if (indexKeyRemoved != null) { data.delete(indexKeyRemoved, key); } } private class IndexDataStorageImpl implements IndexDataStorage<Bytes, Bytes> { @Override public List<Map.Entry<Bytes, Bytes>> loadDataPage(long pageId) throws IOException { try { PageContents contents = dataStorageManager.readIndexPage(tableSpaceUUID, index.uuid, pageId, in -> { return PageContents.deserialize(in); }); if (contents.type != PageContents.TYPE_BLOCKDATA) { throw new IOException("page " + pageId + " does not contain blocks data"); } return contents.pageData; } catch (DataStorageManagerException err) { throw new IOException(err); } } @Override public long createDataPage(List<Map.Entry<Bytes, Bytes>> values) throws IOException { try { PageContents contents = new PageContents(); contents.type = PageContents.TYPE_BLOCKDATA; contents.pageData = values; long pageId = newPageId.getAndIncrement(); dataStorageManager.writeIndexPage(tableSpaceUUID, index.uuid, pageId, (out) -> contents.serialize(out)); return pageId; } catch (DataStorageManagerException err) { throw new IOException(err); } } } @Override public void truncate() throws DataStorageManagerException { this.data.reset(); dropIndexData(); } @Override public void close() { data.clear(); } public int getNumBlocks() { return data.getNumBlocks(); } }
eolivelli/herddb
herddb-core/src/main/java/herddb/index/brin/BRINIndexManager.java
Java
apache-2.0
18,354
/* * Copyright 2016-2018 Sean C Foley * * 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 * or at * https://github.com/seancfoley/IPAddress/blob/master/LICENSE * * 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 inet.ipaddr; import java.io.Serializable; import java.util.Map; import inet.ipaddr.Address.AddressValueProvider; import inet.ipaddr.format.standard.AddressCreator; /** * An object representing a collection of addresses. * <p> * It also encapsulates settings for handling all addresses in the network like the prefix configuration that determines certain properties of the addresses in the network. * <p> * If your use of the IPAddress library has non-default configuration settings in this AddressNetwork class, and within the same JVM the IPAddress library * is being used elsewhere with different configuration settings, then you have two options available to you: * <p> * 1. Use classloaders to load the two uses of IPAddress in different classloaders, a common Java architecture that is part of the language itself to address just this issue * <p> * 2. Use your own network classes, and within them overide the configuration methods to return the values you desire. * <p> * All access to the network classes is through public virtual accessor methods getNetwork or getXNetwork in the classes XAddress, XAddressSection, XAddressSegment * where X is one of MAC, IPv6, or IPv4. So you need to subclass those classes, and then override those getNetwork and getXNetwork methods to return your own network instances. * There are a couple of other places to consider to ensure only your own network instances are used. * XAddressString objects obtain their network object from the validation parameters supplied to the constructor, so you would customize those validation parameters as well. * The same is true for the HostName class, which uses an embedded address validation instance inside the host name parameters instance. * Finally, the address generator/cache classes (that are nested classes that in the network) use validation parameters as well that would be customized to your own network instances. * <p> * Generally you would use the same network object for any given address type (ie one for IPv6, one for IPv4, one for MAC), although this is not necessary. * However, it is necessary that the configuration is the same for any given address type. * <p> * Now suppose you wish to ensure any and all methods in this library create instances of your own subclasses of the XAddress, XAddressSection, XAddressSegment classes. * * All internally created address components are created by the address creator instance owned by the network object. * So you override the getAddressCreator() in your new network classes to provide your own address creator object. * * * @author sfoley * */ public abstract class AddressNetwork<S extends AddressSegment> implements Serializable { private static final long serialVersionUID = 4L; public interface AddressSegmentCreator<S extends AddressSegment> { S[] createSegmentArray(int length); S createSegment(int value); S createSegment(int value, Integer segmentPrefixLength); S createSegment(int lower, int upper, Integer segmentPrefixLength); } public abstract AddressCreator<?, ?, ?, S> getAddressCreator(); public void clearCaches() { getAddressCreator().clearCaches(); } public void setSegmentCaching(boolean enable) { getAddressCreator().setSegmentCaching(enable); } //// Configuration /* * a few sources about the network address - * https://superuser.com/questions/379451/why-can-a-network-address-not-be-a-valid-host-address * https://serverfault.com/questions/451238/why-cant-all-zeros-in-the-host-portion-of-ip-address-be-used-for-a-host * //// Configuration * Maybe use a bit from https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing, see the phrase "In common usage" * https://github.com/ipaddress-gem/ipaddress */ /** * Prefix Handling Configuration * * The library is designed to treat prefixes three different ways: * <p>1. All prefixes are subnets. This was the legacy behaviour for version earlier than version 4. * All prefixed addresses are converted to the block of addresses that share the same prefix. * For addresses in which prefixes are derived from the address ranges, such as MAC, prefix lengths are implicitly calculated from the range, * so 1:2:3:*:*:* implicitly has the prefix length of 24. This is also the case for any address derived from the original. * <p> * 2. Addresses with zero-values hosts are treated as subnets. More precisely, addresses whose hosts are entirely zero, * or addresses whose hosts start with zeros and end with the full range of values are treated as subnets. * So, for example, 1.2.0.0/16 is converted to 1.2.*.* which is the block of addresses with with prefix 1.2. * Also, 1.2.0.* /16 or 1.2.*.* /16 are also equivalent to the block of 65535 addresses 1.2.*.* associated with prefix length 16. * Addresses with non-zero hosts, such as 1.2.0.1/16 are treated differently. 1.2.0.1/16 is equivalent to the single address 1.2.0.1 and is not a treated as a subnet block of multiple addresses. * The new behaviour is akin to the typical convention used by network administrators in which the address with a host of zero is known as the network address. * The all-zero address 0.0.0.0 is conventionally known as INADDR_ANY (any address on the local machine), and when paired with prefix zero it is known as the default route (the route for all addresses). * <p> * The same is true on the IPv6 side, where 1:2:3:4::/64 is treated as the subnet of all addresses with prefix 1:2:3:4. * With IPv6 it is a common convention to depict a prefixed network as a:b:c:d::/64, with the host shown as all zeros. * This is also known as the subnet router anycast address in IPv6. The all-zero address '::' is the value of IN6ADDR_ANY_INIT, the analog to the IPv4 INADDR_ANY. * <p> * In summary:<br> * <ul><li>A prefixed address whose host bits are all 0 is not a single host address, instead it represents a subnet, the block of all addresses with that prefix. * </li><li>A prefixed address whose host is non-zero is treated as a single address with the given prefix length. * </li></ul> * <p> * So for example, 1.2.0.0/16 will give you the subnet block 1.2.*.* /16, and once you have it, if you want just the single address 1.2.0.0/16, you can get it using {@link IPAddress#getLower()}. * <p> * This option has less meaning for other address types in which ranges are explicit, such as MAC addresses. However, this option does allow you, using the appropriate constructor, to assign a prefix length to any address. * So there is no automatic fixed mapping between the range of the address values and the associated prefix length. * <p> * Additionally, when starting with an address whose prefix was calculated from its range, you can derive additionally addresses from the original, and those addresses will have the same prefix. * For instance, 1:2:3:*:*:* implicitly has the prefix length of 24 regardless of the prefix configuration. But with this prefix configuration, * you can then construct a derived address with the same prefix, for example with new MACAddressString("1:2:3:*:*:*").getAddress().replace(MACAddressString("1:2:3:4:5:6").getSection(2)); * <p> * 3. The third option is the setting for which prefixes are never automatically converted to subnets. Any subnet must be explicitly defined, * such as 1.2.*.* /16 * <p> * For addresses in which ranges are explicit, such as MAC addresses, this option is no different than the second option. * * <p> * In summary:<ul> * <li>When PrefixConfiguration == ALL_PREFIXES_ARE_SUBNETS all prefixed addresses have hosts that span all possible host values.</li> * <li>When PrefixConfiguration == PREFIXED_ZERO_HOSTS_ARE_SUBNETS addresses constructed with zero host will have hosts that span all possible values, such as 1.2.0.0/16 which is equivalent to 1.2.*.* /16</li> * <li>When PrefixConfiguration == EXPLICIT_SUBNETS hosts that span all values are explicit, such as 1.2.*.* /16, while 1.2.0.0/16 is just a single address with a single host value of zero.</li> * </ul> * <p> * Note that when setting a non-default prefix configuration, indeterminate behaviour can result from the same addresses using different prefix configuration settings at different times, so this method must be used carefully. * <p> * Should you wish to use two different prefix configurations in the same app, it can be done safely using classloaders, * and it can also be done using different network instances. To used different networks, you can override the virtual methods * for getting network instances in your address component classes. */ public enum PrefixConfiguration { ALL_PREFIXED_ADDRESSES_ARE_SUBNETS,//legacy behaviour PREFIXED_ZERO_HOSTS_ARE_SUBNETS,//default EXPLICIT_SUBNETS; /** * @return whether this is ALL_PREFIXED_ADDRESSES_ARE_SUBNETS */ public boolean allPrefixedAddressesAreSubnets() { return this == ALL_PREFIXED_ADDRESSES_ARE_SUBNETS; } /** * @return whether this is PREFIXED_ZERO_HOSTS_ARE_SUBNETS */ public boolean zeroHostsAreSubnets() { return this == PREFIXED_ZERO_HOSTS_ARE_SUBNETS; } /** * @return whether this is EXPLICIT_SUBNETS */ public boolean prefixedSubnetsAreExplicit() { return this == EXPLICIT_SUBNETS; } } private static PrefixConfiguration defaultPrefixConfiguration = PrefixConfiguration.PREFIXED_ZERO_HOSTS_ARE_SUBNETS; //public static PrefixConfiguration prefixConfiguration = PrefixConfiguration.ALL_PREFIXES_ARE_SUBNETS; //old behaviour (version 3 and under) /** * This method determines the prefix configuration in use by this network. * <p> * The prefix configuration determines whether a prefixed address like 1.2.0.0/16 results in a subnet block (ie 1.2.*.*) or just a single address (1.2.0.0) with a prefix length. * <p> * If you wish to change the default behaviour, you can either call {@link inet.ipaddr.ipv4.IPv4AddressNetwork#setDefaultPrefixConfiguration(PrefixConfiguration)}, * or {@link inet.ipaddr.ipv6.IPv6AddressNetwork#setDefaultPrefixConfiguration(PrefixConfiguration)} or you can override this method in your own network and use your own network for your addresses. * * @see PrefixConfiguration */ public abstract PrefixConfiguration getPrefixConfiguration(); public static PrefixConfiguration getDefaultPrefixConfiguration() { return defaultPrefixConfiguration; } protected boolean isCompatible(AddressNetwork<?> other) { return IPAddressSection.isCompatibleNetworks(this, other); } /** * Generates and caches HostIdentifierString instances. Choose a map of your choice to implement a cache of address string identifiers. * <p> * You choose the map of your choice to be the backing map for the cache. * For example, for thread-safe access to the cache, ConcurrentHashMap is a good choice. * For maps of bounded size, LinkedHashMap provides the removeEldestEntry method to override to implement LRU or other eviction mechanisms. * <p> * @author sfoley * * @param <T> the type to be cached, typically either IPAddressString or HostName */ public static abstract class HostIdentifierStringGenerator<T extends HostIdentifierString> implements Serializable { private static final long serialVersionUID = 4L; protected final Map<String, T> backingMap; public HostIdentifierStringGenerator() { this(null); } public HostIdentifierStringGenerator(Map<String, T> backingMap) { this.backingMap = backingMap; } public Map<String, T> getBackingMap() { return backingMap; } /* * If you wish to maintain a count of added addresses, or a log, then override this method */ protected void added(T added) {} /** * Returns whether the given instance is in the cache. * @param value * @return whether the given instance of T is in the cache */ public boolean contains(T value) { return backingMap.containsValue(value); } /** * Gets the object for the given key. If the object does not exist yet then it is created and added to the cache. * @param key * @return the object for the given key */ public T get(String key) { if(backingMap == null) { return create(key); } T result = backingMap.get(key); if(result == null) { result = create(key); String normalizedKey = result.toNormalizedString(); //we want to use only the IPAddressString or HostName that was created from the normalized string. //This helps things like getHostAddress to have predictable behaviour result = create(normalizedKey); T existing = backingMap.putIfAbsent(normalizedKey, result); if(existing == null) { added(result); } else { result = existing; } if(!normalizedKey.equals(key)) { backingMap.put(key, result); } } return result; } public abstract T get(byte bytes[]); public abstract T get(AddressValueProvider addressProvider); protected abstract T create(String key); } }
seancfoley/IPAddress
IPAddress/src/inet.ipaddr/inet/ipaddr/AddressNetwork.java
Java
apache-2.0
14,046
IJCAI 2018 Tutorial: Ontology-based Data Access: Theory and Practice ======================================================= In this hands-on session, we are considering fragments of the information systems of two universities describing students, academic staff and courses. Requirements ------------ * [Java 8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) * Protégé bundle with Ontop from [SourceForge](https://sourceforge.net/projects/ontop4obda/files/ontop-3.0.0-beta-2/) * Tomact bundle for Ontop SPARQL endpoint from [SourceForge](https://sourceforge.net/projects/ontop4obda/files/ontop-3.0.0-beta-2/) * [H2 with preloaded datasets](./h2.zip) Programme --------- 1. [Mapping the first data source](university-1.md) 2. [Mapping the second data source](university-2.md) 3. [Deploying a SPARQL endpoint](sparql-endpoint.md)
ontop/ontop-examples
ijcai-18-tutorial/README.md
Markdown
apache-2.0
861
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace RealApplication.Models.AccountViewModels { public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
tzerb/Learning
WebApplication2/src/RealApplication/Models/AccountViewModels/RegisterViewModel.cs
C#
apache-2.0
869
/** * ConversionCategoryKey.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.v201406.video; /** * Segment key for conversion category. */ public class ConversionCategoryKey implements java.io.Serializable { private com.google.api.ads.adwords.axis.v201406.video.ConversionCategoryKeyConversionCategory conversionCategory; public ConversionCategoryKey() { } public ConversionCategoryKey( com.google.api.ads.adwords.axis.v201406.video.ConversionCategoryKeyConversionCategory conversionCategory) { this.conversionCategory = conversionCategory; } /** * Gets the conversionCategory value for this ConversionCategoryKey. * * @return conversionCategory */ public com.google.api.ads.adwords.axis.v201406.video.ConversionCategoryKeyConversionCategory getConversionCategory() { return conversionCategory; } /** * Sets the conversionCategory value for this ConversionCategoryKey. * * @param conversionCategory */ public void setConversionCategory(com.google.api.ads.adwords.axis.v201406.video.ConversionCategoryKeyConversionCategory conversionCategory) { this.conversionCategory = conversionCategory; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ConversionCategoryKey)) return false; ConversionCategoryKey other = (ConversionCategoryKey) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.conversionCategory==null && other.getConversionCategory()==null) || (this.conversionCategory!=null && this.conversionCategory.equals(other.getConversionCategory()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getConversionCategory() != null) { _hashCode += getConversionCategory().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ConversionCategoryKey.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "ConversionCategoryKey")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("conversionCategory"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "conversionCategory")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201406", "ConversionCategoryKey.ConversionCategory")); elemField.setMinOccurs(0); elemField.setNillable(false); 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); } }
nafae/developer
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201406/video/ConversionCategoryKey.java
Java
apache-2.0
4,314
/** * AdSenseAccountErrorReason.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.dfp.axis.v201403; public class AdSenseAccountErrorReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected AdSenseAccountErrorReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _ASSOCIATE_ACCOUNT_API_ERROR = "ASSOCIATE_ACCOUNT_API_ERROR"; public static final java.lang.String _GET_AD_SLOT_API_ERROR = "GET_AD_SLOT_API_ERROR"; public static final java.lang.String _GET_CHANNEL_API_ERROR = "GET_CHANNEL_API_ERROR"; public static final java.lang.String _GET_BULK_ACCOUNT_STATUSES_API_ERROR = "GET_BULK_ACCOUNT_STATUSES_API_ERROR"; public static final java.lang.String _RESEND_VERIFICATION_EMAIL_ERROR = "RESEND_VERIFICATION_EMAIL_ERROR"; public static final java.lang.String _UNEXPECTED_API_RESPONSE_ERROR = "UNEXPECTED_API_RESPONSE_ERROR"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final AdSenseAccountErrorReason ASSOCIATE_ACCOUNT_API_ERROR = new AdSenseAccountErrorReason(_ASSOCIATE_ACCOUNT_API_ERROR); public static final AdSenseAccountErrorReason GET_AD_SLOT_API_ERROR = new AdSenseAccountErrorReason(_GET_AD_SLOT_API_ERROR); public static final AdSenseAccountErrorReason GET_CHANNEL_API_ERROR = new AdSenseAccountErrorReason(_GET_CHANNEL_API_ERROR); public static final AdSenseAccountErrorReason GET_BULK_ACCOUNT_STATUSES_API_ERROR = new AdSenseAccountErrorReason(_GET_BULK_ACCOUNT_STATUSES_API_ERROR); public static final AdSenseAccountErrorReason RESEND_VERIFICATION_EMAIL_ERROR = new AdSenseAccountErrorReason(_RESEND_VERIFICATION_EMAIL_ERROR); public static final AdSenseAccountErrorReason UNEXPECTED_API_RESPONSE_ERROR = new AdSenseAccountErrorReason(_UNEXPECTED_API_RESPONSE_ERROR); public static final AdSenseAccountErrorReason UNKNOWN = new AdSenseAccountErrorReason(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static AdSenseAccountErrorReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { AdSenseAccountErrorReason enumeration = (AdSenseAccountErrorReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static AdSenseAccountErrorReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} 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.EnumSerializer( _javaType, _xmlType); } 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.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(AdSenseAccountErrorReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201403", "AdSenseAccountError.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
nafae/developer
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201403/AdSenseAccountErrorReason.java
Java
apache-2.0
4,180
<?php /** * This file is part of the bee4/transport package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @copyright Bee4 2015 * @author Stephane HULARD <s.hulard@chstudio.fr> * @package Bee4\Transport\Message\Request\Ftp */ namespace Bee4\Transport\Message\Request\Ftp; /** * FTP HEAD Request object used to check if resources are really here * @package Bee4\Transport\Message\Request\Ftp */ class Head extends FtpRequest { protected function prepare() { parent::prepare(); $this->addOption('body', false); //apply MDTM action on the file, if not valid status is 550 the simplest way for HEAD $this->addOption('commands.request', ['MDTM '.$this->getUrl()->path()]); } }
bee4/transport
src/Message/Request/Ftp/Head.php
PHP
apache-2.0
814
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (16) on Sat Dec 18 21:56:37 UTC 2021 --> <title>DynamicallyTypedMapWithFloats (Glowstone 2021.7.1-SNAPSHOT API)</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2021-12-18"> <meta name="description" content="declaration: package: net.glowstone.util, interface: DynamicallyTypedMapWithFloats"> <meta name="generator" content="javadoc/ClassWriterImpl"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> <script type="text/javascript" src="../../../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../../../script-dir/jquery-ui.min.js"></script> </head> <body class="class-declaration-page"> <script type="text/javascript">var evenRowColor = "even-row-color"; var oddRowColor = "odd-row-color"; var tableTab = "table-tab"; var activeTableTab = "active-table-tab"; var pathtoroot = "../../../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../../../index.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="nav-bar-cell1-rev">Class</li> <li><a href="class-use/DynamicallyTypedMapWithFloats.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div> <ul class="sub-nav-list"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="sub-nav-list"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="sub-title"><span class="package-label-in-type">Package</span>&nbsp;<a href="package-summary.html">net.glowstone.util</a></div> <h1 title="Interface DynamicallyTypedMapWithFloats" class="title">Interface DynamicallyTypedMapWithFloats&lt;K&gt;</h1> </div> <section class="description"> <dl class="notes"> <dt>All Superinterfaces:</dt> <dd><code><a href="DynamicallyTypedMap.html" title="interface in net.glowstone.util">DynamicallyTypedMap</a>&lt;K&gt;</code></dd> </dl> <dl class="notes"> <dt>All Known Subinterfaces:</dt> <dd><code><a href="DynamicallyTypedMapWithDoubles.html" title="interface in net.glowstone.util">DynamicallyTypedMapWithDoubles</a>&lt;K&gt;</code></dd> </dl> <dl class="notes"> <dt>All Known Implementing Classes:</dt> <dd><code><a href="nbt/CompoundTag.html" title="class in net.glowstone.util.nbt">CompoundTag</a></code>, <code><a href="../entity/meta/MetadataMap.html" title="class in net.glowstone.entity.meta">MetadataMap</a></code>, <code><a href="config/WorldConfig.html" title="class in net.glowstone.util.config">WorldConfig</a></code></dd> </dl> <hr> <div class="type-signature"><span class="modifiers">public interface </span><span class="element-name type-name-label">DynamicallyTypedMapWithFloats&lt;K&gt;</span><span class="extends-implements"> extends <a href="DynamicallyTypedMap.html" title="interface in net.glowstone.util">DynamicallyTypedMap</a>&lt;K&gt;</span></div> </section> <section class="summary"> <ul class="summary-list"> <!-- ========== METHOD SUMMARY =========== --> <li> <section class="method-summary" id="method.summary"> <h2>Method Summary</h2> <div id="method-summary-table"> <div class="table-tabs" role="tablist" aria-orientation="horizontal"><button id="method-summary-table-tab0" role="tab" aria-selected="true" aria-controls="method-summary-table.tabpanel" tabindex="0" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table', 3)" class="active-table-tab">All Methods</button><button id="method-summary-table-tab2" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab2', 3)" class="table-tab">Instance Methods</button><button id="method-summary-table-tab3" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab3', 3)" class="table-tab">Abstract Methods</button></div> <div id="method-summary-table.tabpanel" role="tabpanel"> <div class="summary-table three-column-summary" aria-labelledby="method-summary-table-tab0"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color method-summary-table-tab2 method-summary-table method-summary-table-tab3"><code>float</code></div> <div class="col-second even-row-color method-summary-table-tab2 method-summary-table method-summary-table-tab3"><code><span class="member-name-link"><a href="#getFloat(K)">getFloat</a></span>&#8203;(<a href="DynamicallyTypedMapWithFloats.html" title="type parameter in DynamicallyTypedMapWithFloats">K</a>&nbsp;key)</code></div> <div class="col-last even-row-color method-summary-table-tab2 method-summary-table method-summary-table-tab3"> <div class="block">Retrieves an entry as a <code>float</code>.</div> </div> </div> </div> </div> <div class="inherited-list"> <h3 id="methods.inherited.from.class.net.glowstone.util.DynamicallyTypedMap">Methods inherited from interface&nbsp;net.glowstone.util.<a href="DynamicallyTypedMap.html" title="interface in net.glowstone.util">DynamicallyTypedMap</a></h3> <code><a href="DynamicallyTypedMap.html#getBoolean(K)">getBoolean</a>, <a href="DynamicallyTypedMap.html#getInt(K)">getInt</a>, <a href="DynamicallyTypedMap.html#getString(K)">getString</a></code></div> </section> </li> </ul> </section> <section class="details"> <ul class="details-list"> <!-- ============ METHOD DETAIL ========== --> <li> <section class="method-details" id="method.detail"> <h2>Method Details</h2> <ul class="member-list"> <li> <section class="detail" id="getFloat(K)"> <h3 id="getFloat(java.lang.Object)">getFloat</h3> <div class="member-signature"><span class="return-type">float</span>&nbsp;<span class="element-name">getFloat</span>&#8203;<span class="parameters">(<a href="DynamicallyTypedMapWithFloats.html" title="type parameter in DynamicallyTypedMapWithFloats">K</a>&nbsp;key)</span></div> <div class="block">Retrieves an entry as a <code>float</code>.</div> <dl class="notes"> <dt>Parameters:</dt> <dd><code>key</code> - the key to look up</dd> <dt>Returns:</dt> <dd>the value as a <code>float</code></dd> </dl> </section> </li> </ul> </section> </li> </ul> </section> <!-- ========= END OF CLASS DATA ========= --> </main> <footer role="contentinfo"> <hr> <p class="legal-copy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </footer> </div> </div> </body> </html>
GlowstoneMC/glowstonemc.github.io
content/jd/glowstone/1.16/net/glowstone/util/DynamicallyTypedMapWithFloats.html
HTML
artistic-2.0
8,176
using System; using AGS.API; namespace AGS.Engine.Android { public class AndroidFontLoader : IFontLoader { public AndroidFontLoader() { } #region IFontLoader implementation public void InstallFonts(params string[] paths) { } public IFont LoadFont(string fontFamily, float sizeInPoints, FontStyle style) { return AndroidFont.FromFamilyName(fontFamily, style, sizeInPoints, this); } public IFont LoadFontFromPath(string path, float sizeInPoints, FontStyle style) { return AndroidFont.FromPath(path, style, sizeInPoints, this); } #endregion } }
tzachshabtay/MonoAGS
Source/Engine/AGS.Engine.Android/Drawing/AndroidFontLoader.cs
C#
artistic-2.0
593
var obj_a = { a: "hi", b: "no", c: { h: { j:0, k:1 }, i: { j:0, k:1 }, }, d: [0, 1, 2], e: [0, 1, 2], f: ["a","b","c"], g: ["a","b","c"], x: 1, }; var obj_b = { a: "hi", b: "no", c: { h: { j:0, k:1 }, i: { j:0, k:1 }, }, d: [0, 1, 2], e: [1, 1, 2], f: ["a","b","c"], g: ["a","b","d"], z: 1, }; var a = {a:1, b:2}; var b = {a:2, c: {a:1, b:2}} var c = {a:2, b:2, c: {a:1, b:2}} var combined = Aux.combine(a,b); Test.expect(c.a, combined.a); Test.expect(c.b, combined.b); Test.expect(c.c.a, combined.c.a); function f(a,b,c) { return a+b-c; } f_parse = Aux.parse_function(f); expect(f_parse.args, ["a","b","c"]); expect(f_parse.body, "return a+b-c;"); //var a_b_template = Aux.make_template(obj_a, obj_b); // //var expected_template = { // base: { // a: "hi", // b: null, // c: { // h: {j: null, k: 1}, // i: {j: 0, k: 1}, // }, // d: [0, 1, 2], // e: null, // f: ["a","b","c"], // g: null, // x: undefined, // z: undefined, // }, // vars: [ // {field:"b", type:"string"}, // {field:"c.h.j", type:"void"}, // {field:"e", type:["number"]}, // {field:"g", type:["string"]}, // ], //} // //// doing these individually because they are implemented //this.// separately in the make_template() function //var fields_to_check = ["a","b","d","f","g","c.h.j","c.i.j","c.h.k","c.i.k"]; //for(var i in fields_to_check) { // var expected_v = eval("expected_template.base."+fields_to_check[i]); // var resulted_v = eval("resulted_template.base."+fields_to_check[i]); // Test.expect(expected_v, resulted_v); //} // //for(var i in expected_template.vars) { // var expected_v = expected_template.vars[i]; // var resulted_v = a_b_template.vars[i]; // Test.note_result("make_template()", {field:resulted_v.field, type:resulted_v.type}); // Test.expect(resulted_v.field, expected_v.field); // Test.expect(resulted_v.field, expected_v.field); //} // //var well_formed_obj = Aux.fill_template(expected_template, // ["good",{u:0,v:1},[3,45],["so","well","formed"]]); // //Test.expect(well_formed_obj.a, "hi"); //Test.expect(well_formed_obj.b, "good"); //Test.expect(well_formed_obj.c.h.j, {u:0,v:1}); //Test.expect(well_formed_obj.e, [3,45]); //Test.expect(well_formed_obj.f, ["a","b","c"]); //Test.expect(well_formed_obj.g, ["so","well","formed"]); // //try { // var malformed_obj = Aux.fill_template(expected_template, // [0,{u:0,v:1},[3,45],["so","well","formed"]]); //} catch(err) { // Test.note_result("Found error while trying to fill template badly."); //} // //var object_list_a = { // a: [{b:1,c:"3",d:5}] //}; //var object_list_b = { // a: [{b:2,c:"4",d:5}] //}; // //var list_template = { // base: { // a: null // }, // vars: [ // { // field:a, // type:[{ // base: {b:1,c:null,d:5}, // vars: [{field:"c", type:"string"} ] // }] // }, // ], //};
aaronstarov/kindred.web
source/_/core/objects.test.js
JavaScript
artistic-2.0
3,138
#!/bin/bash xbindkeys -mk exit while true do echo 'Press Ctrl-C to exit ...' xbindkeys -k sleep 1 done
LaKing/xoclock
keypress-identifyer.sh
Shell
artistic-2.0
117
package PillowFort::Modules::RTorrent; use parent 'PillowFort::Module'; use strict; use warnings; use utf8; use Mojo::IOLoop; use RPC::RTorrent; my $paused_actions = ['start', 'remove']; my $running_actions = ['stop', 'remove']; my $entry_update = sub { my ($entry, $item) = @_; my $progress = "$item->{down_total} / $item->{size_bytes}"; $entry->{title} = "[$item->{state}]$item->{name}"; $entry->{subtext} = join("\n", $progress, $item->{message}); $entry->{actions} = $item->{state} ? $running_actions : $paused_actions; $entry->{hash} = $item->{hash}; return $entry; }; my $transform = sub { $entry_update->(new PillowFort::Module::Entry (), $_[0]); }; sub _init { my $self = shift; my $index = {}; my $rtc = RPC::RTorrent->new($self->{url}); $rtc->on(add => sub { for(@{$_[0]}){ my $entry = $transform->($_); $index->{$_->{hash}} = $entry; $self->add_entry($entry); } }); $rtc->on(remove => sub { for(@{$_[0]}){ my $entry = $index->{$_}; $self->remove_entry($entry); delete $index->{$_}; } }); my $update = sub { $rtc->update; $rtc->for_each(sub { $entry_update->($index->{$_[0]->{hash}}, $_[0]); }); $self->send_entries; }; $self->{watcher} = Mojo::IOLoop->recurring( $self->{timer}->{interval}, $update ); Mojo::IOLoop->next_tick($update) if $self->{timer}->{autostart}; $self->{actions} = { 'stop' => sub { $rtc->stop($_[1]->{hash}) }, 'start' => sub { $rtc->start($_[1]->{hash}) }, 'remove' => sub { $rtc->erase($_[1]->{hash}) }, }; return $self; } 1;
ZetsubouClown/pillow-fort
lib/PillowFort/Modules/RTorrent.pm
Perl
artistic-2.0
1,759
# !/usr/bin/env python # -*-coding:utf-8-*- # by huangjiangbo # 部署服务 # deploy.py from ConfigParser import ConfigParser ConfigFile = r'config.ini' # 读取配置文件 config = ConfigParser() config.read(ConfigFile) de_infos = config.items(r'deploy_server') # 远程部署服务器信息 redeploy_server_info = {} appinfo = {} print de_infos for (key, value) in de_infos: redeploy_server_info[key] = value print redeploy_server_info
cherry-hyx/hjb-test
脚本/deploy/t.py
Python
artistic-2.0
449
# Rakudo Perl 6 This is Rakudo Perl, a Perl 6 compiler for the Parrot virtual machine, the JVM and MoarVM. Rakudo Perl is Copyright (C) 2008-2014, The Perl Foundation. Rakudo Perl is distributed under the terms of the Artistic License 2.0. For more details, see the full text of the license in the file LICENSE. This directory contains only the Rakudo Perl 6 compiler itself; it does not contain any of the modules, documentation, or other items that would normally come with a full Perl 6 distribution. If you're after more than just the bare compiler, please download [the latest Rakudo Star package](http://rakudo.org/downloads/star). Note that different backends implement slightly different sets of featurs. For a high-level overview of implemented and missing features, please visit [the features page on perl6.org](http://perl6.org/compilers/features). Recent changes and feature additions are documented in the `doc/ChangeLog` text file. ## Building and Installing Rakudo See the INSTALL.txt file for detailed prerequisites and build and installation instructions. The general process for building is running `perl Configure.pl` with the desired configuration options (common options listed below), and then running `make` or `make install`. Optionally, you may run `make spectest` to test your build on [Roast](http://github.com/perl6/roast), the Official Perl 6 test suite. Installation of Rakudo simply requires building and running `make install`. Note that this step is necessary for running Rakudo from outside the build directory. But don't worry, it installs locally by default, so you don't need any administrator privileges for carrying out this step. ### Configuring Rakudo to run on MoarVM To automatically download and build a fresh MoarMV and NQP, run: perl Configure.pl --gen-moar --gen-nqp --backends=moar ### Configuring Rakudo to run on Parrot To automatically download and build a fresh Parrot and NQP, run: perl Configure.pl --gen-parrot --backends=parrot It is recommended to first install the libicu-dev and libreadline-dev packages. ### Configuring Rakudo to run on the JVM Note that to run Rakudo on JVM, JDK 1.7 must be installed. To automatically download an build a fresh NQP, run: perl Configure.pl --gen-nqp --backends=jvm If you get an out of memory error building rakudo on the JVM, you may need to modify your NQP runner to limit memory use. e.g. edit the nqp-j / nqp-j.bat executable (found wherever you installed to, or in the `install/bin` directory) to include `-Xms500m -Xmx2g` as options passed to java. ### Multiple backends at the same time By supplying combinations of backends to the `--backends` flag, you can get two or three backends built in the same prefix. The first backend you supply in the list is the one that gets the `perl6` name as a symlink, and all backends are installed seperately as `perl6-m`, `perl6-p`, or `perl6-j` for Rakudo on MoarVM, Parrot, or JVM respectively. The format for the `--backends` flag is: $ perl Configure.pl --backends=moar,parrot $ perl Configure.pl --backends=parrot,moar,jvm $ perl Configure.pl --backends=ALL ## Where to get help or answers to questions There are several mailing lists, IRC channels, and wikis available with help for Perl 6 and Rakudo on Parrot. Figuring out the right one to use is often the biggest battle. Here are some rough guidelines: The central hub for Perl 6 information is [perl6.org](http://perl6.org/). This is always a good starting point. If you have a question about Perl 6 syntax or the right way to approach a problem using Perl 6, you probably want the "perl6-users@perl.org" mailing list or the "irc.freenode.net/#perl6" channel. The perl6-users list is primarily for the people who want to use Perl 6 to write programs, so newbie questions are welcomed there. Newbie questions are also welcome on the #perl6 channel; the Rakudo and Perl 6 development teams tend to hang out there and are generally glad to help. You can follow "@rakudoperl" on Twitter, and there's a Perl 6 news aggregator at [Planet Perl 6](http://planeteria.org/perl6/). Questions about NQP can also be posted to the #perl6 IRC channel. For questions about Parrot, see <http://parrot.org/> for links and resources, or join the #parrot IRC channel on irc.perl.org . For questions about MoarVM, you can join #moarvm on freenode. ## Reporting bugs Bug reports should be sent to "rakudobug@perl.org" with the moniker [BUG]\(including the brackets) at the start of the subject so that it gets appropriately tagged in [the RT system](https://rt.perl.org/rt3/). Please include or attach any sample source code that exhibits the bug, and include either the release name/date or the git commit identifier. You find that information in the output from `perl6 --version` (or in the first line of `git log`, if Rakudo fails to build). There's no need to cc: the perl6-compiler mailing list, as the RT system will handle this on its own. If you find a bug in MoarVM or NQP, you can either discuss it on the IRC and have it reported for you, or you can submit an issue to the issue trackers on github for perl6/nqp or moarvm/moarvm. ## Submitting patches If you have a patch that fixes a bug or adds a new feature, please submit it to "rakudobug@perl.org" with the moniker [PATCH]\(including the brackets) at the start of the subject line. We'll generally accept patches in any form if we can get them to work, but unified diff from the `git` command is greatly preferred. In general this means that in the "rakudo" directory you make your changes, and then type git commit -m 'Your commit message' changed/filename.pm git format-patch HEAD^ This will generate a file called "001-your-commit-message.patch", or more of them if you made multiple commits; please attach these to your email. Please note that if you made more than one commit, you have to specify a proper commit range for format-patch, for example `origin/nom..HEAD`. (Note to the maintainers: you can apply these patches with the `git-am -s` command; it preserves meta information like author). ## How the compiler works See `docs/compiler_overview.pod`. ## AUTHOR Patrick Michaud "pmichaud@pobox.com" is the current pumpking for Rakudo Perl 6. See CREDITS for the many people that have contributed to the development of the Rakudo compiler.
dwarring/rakudo
README.md
Markdown
artistic-2.0
6,374
package vn.edu.fpt.hsts.bizlogic.model; import java.io.Serializable; /** * Created by Aking on 10/11/2015. */ public class PracticePrescriptionModel implements Serializable{ /** * Practice */ private String p; /** * Practice Time */ private int pTime; /** * Practice Intensity */ private String pIntensity; /** * Practice Note */ private String pNote; public PracticePrescriptionModel() { } public PracticePrescriptionModel(String p, int pTime, String pIntensity, String pNote) { this.p = p; this.pTime = pTime; this.pIntensity = pIntensity; this.pNote = pNote; } public String getP() { return p; } public void setP(String p) { this.p = p; } public int getpTime() { return pTime; } public void setpTime(int pTime) { this.pTime = pTime; } public String getpIntensity() { return pIntensity; } public void setpIntensity(String pIntensity) { this.pIntensity = pIntensity; } public String getpNote() { return pNote; } public void setpNote(String pNote) { this.pNote = pNote; } public boolean isValid(){ if (null == p || p.isEmpty()){ return false; } else if (pTime <= 0){ return false; } else if (null == pIntensity || pIntensity.isEmpty()){ return false; } return true; } @Override public String toString() { return "PracticePrescriptionModel{" + "p='" + p + '\'' + ", pTime=" + pTime + ", pIntensity='" + pIntensity + '\'' + ", pNote='" + pNote + '\'' + '}'; } }
quantdse60878/HSTS
sources/hsts-demo/src/main/java/vn/edu/fpt/hsts/bizlogic/model/PracticePrescriptionModel.java
Java
artistic-2.0
1,808
# A reentrant lock mechanism with condition variable support. my class X::Lock::ConditionVariable::New is Exception { method message() { "Cannot directly create a ConditionVariable; use the 'condition' method on a lock" } } my class Lock is repr('ReentrantMutex') { class ConditionVariable is repr('ConditionVariable') { method new() { X::Lock::ConditionVariable::New.new.throw } method wait() { nqp::condwait(self) } method signal() { nqp::condsignalone(self) } method signal_all() { nqp::condsignalall(self) } } method lock() { nqp::lock(self) } method unlock() { nqp::unlock(self) } method protect(&code) { nqp::lock(self); my \res := code(); nqp::unlock(self); CATCH { nqp::unlock(self); } res } method condition() { nqp::getlockcondvar(self, ConditionVariable) } }
dwarring/rakudo
src/core/Lock.pm
Perl
artistic-2.0
922
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_292) on Fri Jul 02 16:35:40 UTC 2021 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package org.bukkit.event.inventory (Glowkit 1.16.5-R0.1-SNAPSHOT API)</title> <meta name="date" content="2021-07-02"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.bukkit.event.inventory (Glowkit 1.16.5-R0.1-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/bukkit/event/inventory/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package org.bukkit.event.inventory" class="title">Uses of Package<br>org.bukkit.event.inventory</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.destroystokyo.paper.event.block">com.destroystokyo.paper.event.block</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.destroystokyo.paper.event.inventory">com.destroystokyo.paper.event.inventory</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.bukkit">org.bukkit</a></td> <td class="colLast"> <div class="block">The root package of the Bukkit API, contains generalized API classes.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.bukkit.entity">org.bukkit.entity</a></td> <td class="colLast"> <div class="block">Interfaces for non-voxel objects that can exist in a <a href="../../../../org/bukkit/World.html" title="interface in org.bukkit"><code>world</code></a>, including all players, monsters, projectiles, etc.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.bukkit.event.enchantment">org.bukkit.event.enchantment</a></td> <td class="colLast"> <div class="block"><a href="../../../../org/bukkit/event/Event.html" title="class in org.bukkit.event"><code>Events</code></a> triggered from an <a href="../../../../org/bukkit/inventory/EnchantingInventory.html" title="interface in org.bukkit.inventory"><code>enchantment table</code></a>.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.bukkit.event.inventory">org.bukkit.event.inventory</a></td> <td class="colLast"> <div class="block"><a href="../../../../org/bukkit/event/Event.html" title="class in org.bukkit.event"><code>Events</code></a> relating to <a href="../../../../org/bukkit/inventory/Inventory.html" title="interface in org.bukkit.inventory"><code>inventory</code></a> manipulation.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#org.bukkit.inventory">org.bukkit.inventory</a></td> <td class="colLast"> <div class="block">Classes involved in manipulating player inventories and item interactions.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.destroystokyo.paper.event.block"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../com/destroystokyo/paper/event/block/package-summary.html">com.destroystokyo.paper.event.block</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryEvent.html#com.destroystokyo.paper.event.block">InventoryEvent</a> <div class="block">Represents a player related inventory event</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.destroystokyo.paper.event.inventory"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../com/destroystokyo/paper/event/inventory/package-summary.html">com.destroystokyo.paper.event.inventory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryEvent.html#com.destroystokyo.paper.event.inventory">InventoryEvent</a> <div class="block">Represents a player related inventory event</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.bukkit"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../org/bukkit/package-summary.html">org.bukkit</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryType.html#org.bukkit">InventoryType</a> <div class="block">Represents the different kinds of inventories available in Bukkit.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.bukkit.entity"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../org/bukkit/entity/package-summary.html">org.bukkit.entity</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryCloseEvent.Reason.html#org.bukkit.entity">InventoryCloseEvent.Reason</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.bukkit.event.enchantment"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../org/bukkit/event/enchantment/package-summary.html">org.bukkit.event.enchantment</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryEvent.html#org.bukkit.event.enchantment">InventoryEvent</a> <div class="block">Represents a player related inventory event</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.bukkit.event.inventory"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/ClickType.html#org.bukkit.event.inventory">ClickType</a> <div class="block">What the client did to trigger this action (not the result).</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/DragType.html#org.bukkit.event.inventory">DragType</a> <div class="block">Represents the effect of a drag that will be applied to an Inventory in an InventoryDragEvent.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryAction.html#org.bukkit.event.inventory">InventoryAction</a> <div class="block">An estimation of what the result will be.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryClickEvent.html#org.bukkit.event.inventory">InventoryClickEvent</a> <div class="block">This event is called when a player clicks in an inventory.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryCloseEvent.Reason.html#org.bukkit.event.inventory">InventoryCloseEvent.Reason</a>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryEvent.html#org.bukkit.event.inventory">InventoryEvent</a> <div class="block">Represents a player related inventory event</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryInteractEvent.html#org.bukkit.event.inventory">InventoryInteractEvent</a> <div class="block">An abstract base class for events that describe an interaction between a HumanEntity and the contents of an Inventory.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryType.html#org.bukkit.event.inventory">InventoryType</a> <div class="block">Represents the different kinds of inventories available in Bukkit.</div> </td> </tr> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryType.SlotType.html#org.bukkit.event.inventory">InventoryType.SlotType</a>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.bukkit.inventory"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../org/bukkit/event/inventory/package-summary.html">org.bukkit.event.inventory</a> used by <a href="../../../../org/bukkit/inventory/package-summary.html">org.bukkit.inventory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryType.html#org.bukkit.inventory">InventoryType</a> <div class="block">Represents the different kinds of inventories available in Bukkit.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><a href="../../../../org/bukkit/event/inventory/class-use/InventoryType.SlotType.html#org.bukkit.inventory">InventoryType.SlotType</a>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/bukkit/event/inventory/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </body> </html>
GlowstoneMC/glowstonemc.github.io
content/jd/glowkit/1.16/org/bukkit/event/inventory/package-use.html
HTML
artistic-2.0
14,865
<?php final class InterpellerGraphView extends AphrontView { private $header = ''; private $tasks = array(); private $viewer = NULL; private $handles = array(); private $queries = NULL; private $uri = NULL; public function setURI ( $uri ) { $this->uri = '//' . $uri . '/ours-js/d3.v3.min.js'; } public function setHeader ( $header ) { $this->header = $header; } public function setTasks ( $tasks ) { $this->tasks = $tasks; } public function setViewer ( $user ) { $this->viewer = $user; } public function setHandles ( array $handles ) { assert_instances_of( $handles, 'PhabricatorObjectHandle' ); $this->handles = $handles; return $this; } public function setQueries ( PhabricatorSavedQuery $queries ) { $this->queries = $queries; } final public function render () { $filters = $this->queries->getParameter( 'filters', array() ); $script_code = <<<EOT <script type="text/javascript" charset="utf-8"> var wnd = window, el = document.documentElement, body = document.getElementsByTagName( 'body' )[ 0 ], width = wnd.innerWidth || el.clientWidth || body.clientWidth, height = wnd.innerHeight|| el.clientHeight || body.clientHeight; height -= 400; width -= 80; if ( width < 800 ) width = 800; if ( height < 600 ) height = 600; var labelDistance = 0; var vis = d3.select( "div.is4u_graph" ).append( "svg:svg" ).attr( "width", width ).attr( "height", height ); var nodes = []; var labelAnchors = []; var labelAnchorLinks = []; var links = []; EOT; $counter = 0; $tasks = array(); Javelin::initBehavior('phui-hovercards'); foreach ( $this->tasks as $task ) { $phid = $task->getPHID(); $tasks[ $phid ][ "id" ] = $counter++; $tasks[ $phid ][ "is_source" ] = 0; $tasks[ $phid ][ "is_target" ] = 0; } foreach ( $this->tasks as $task ) { $phid = $task->getPHID(); $target = $tasks[ $phid ][ "id" ]; foreach ( $task->loadDependsOnTaskPHIDs() as $depend ) { if ( array_key_exists( $depend, $tasks ) ) { $source = $tasks[ $depend ][ "id" ]; $tasks[ $phid ][ "is_target" ] = 1; $tasks[ $depend ][ "is_source" ] = 1; $script_code .= <<<EOT links.push( { source: $source, target: $target } ); EOT; } } } $response = CelerityAPI::getStaticResourceResponse(); $maxHours = 0; foreach ( $this->tasks as $task ) { $phid = $task->getPHID(); $title = trim( $task->getTitle() ); $title = str_replace( "\n", ' ', $title ); $owner = $this->handles[ $task->getOwnerPHID() ]; # add progress and estimated hours to hovered title $field_list = PhabricatorCustomField::getObjectFields( $task, PhabricatorCustomField::ROLE_VIEW ); $field_list->setViewer( $this->viewer )->readFieldsFromStorage( $task ); $myFields = []; foreach ( $field_list->getFields() as $key => $field ) { $field->setViewer( $this->viewer ); $fname = $field->getFieldKey(); $fproxy = $field->getProxy(); if ($fproxy != null) { $myFields[ $fname ] = $fproxy->getFieldValue(); } } if ( ! array_key_exists( 'std:maniphest:is4u:estimated-hours', $myFields ) || !isset( $myFields[ 'std:maniphest:is4u:estimated-hours' ]) ) $myFields[ 'std:maniphest:is4u:estimated-hours' ] = 1; if ( ! array_key_exists( 'std:maniphest:is4u:progress', $myFields ) || !isset( $myFields[ 'std:maniphest:is4u:progress' ]) ) $myFields[ 'std:maniphest:is4u:progress' ] = 0; if ( array_key_exists( 'std:maniphest:is4u:estimated-hours', $myFields ) && array_key_exists( 'std:maniphest:is4u:progress', $myFields ) ) $title .= sprintf( " (%s, %d hours, %d %% progress)", $owner->getName(), $myFields[ 'std:maniphest:is4u:estimated-hours' ], $myFields[ 'std:maniphest:is4u:progress' ] ); else $title .= sprintf( " (%s)", $owner->getName() ); $title = phutil_escape_html( $title ); $progress = 0; if ( array_key_exists( 'std:maniphest:is4u:progress', $myFields ) ) { $progress = $myFields[ 'std:maniphest:is4u:progress' ]; if ( $progress < 0 ) $progress = 0; if ( $progress > 100 ) $progress = 100; } $estimatedHours = 0; if ( array_key_exists( 'std:maniphest:is4u:estimated-hours', $myFields ) ) { $estimatedHours = $myFields[ 'std:maniphest:is4u:estimated-hours' ]; if ( $estimatedHours < 1 ) $estimatedHours = 1; if ( $estimatedHours > $maxHours ) $maxHours = $estimatedHours; } $myTask = $task->getOwnerPHID() == $this->viewer->getPHID(); $blocker = $tasks[ $phid ][ "is_source" ] && ! $tasks[ $phid ][ "is_target" ]; $myBlocker = $myTask && $blocker; $color = $myBlocker ? '#F00' : ( $blocker ? '#F3F' : ( $myTask ? '#00F' : '#777' ) ); $id = $task->getId(); $label = "T$id"; $label = phutil_escape_html( $label ); $meta_id = $response->addMetadata( array( 'hoverPHID' => $phid ) ); $show = 1; $standalone = ! $tasks[ $phid ][ "is_source" ] && ! $tasks[ $phid ][ "is_target" ]; if ( $standalone && $myTask && in_array( 'my_standalone', $filters ) ) $show = 0; if ( $standalone && ! $myTask && in_array( 'others_standalone', $filters ) ) $show = 0; $script_code .= <<<EOT var node = { label: "$label", title: "$title", color: "$color", meta: "$meta_id", show: "$show", my: "$myTask", adjacentNodes: [], adjacentLinks: [], progress: $progress, estimatedHours: $estimatedHours }; nodes.push( node ); EOT; } $script_code .= <<<EOT for ( var i = 0; i < links.length; i++ ) { links[ i ].source = nodes[ links[ i ].source ]; links[ i ].target = nodes[ links[ i ].target ]; links[ i ].source.adjacentNodes.push( links[ i ].target ); links[ i ].source.adjacentLinks.push( links[ i ] ); links[ i ].target.adjacentNodes.push( links[ i ].source ); links[ i ].target.adjacentLinks.push( links[ i ] ); } if ( ! Array.prototype.indexOf ) Array.prototype.indexOf = function( elt /*, from*/ ) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) if (from in this && this[from] === elt) return from; return -1; }; function bfs ( v ) { var queue = []; var result = []; queue.push( v ); v.bfsMark = true; while ( queue.length > 0 ) { var t = queue.shift(); if ( t != v ) result.push( t ); for ( var i = 0; i < t.adjacentNodes.length; i++ ) if ( ! t.adjacentNodes[ i ].bfsMark ) { t.adjacentNodes[ i ].bfsMark = true; queue.push( t.adjacentNodes[ i ] ); } } for ( var i = 0; i < nodes.length; i++ ) nodes[ i ].bfsMark = false; return result; } EOT; if ( in_array( 'others_clusters', $filters ) ) { $script_code .= <<<EOT for (var i = 0; i < nodes.length; i++ ) if ( nodes[ i ].my == "1" ) { nodes[ i ].keep = true; var connected = bfs( nodes[ i ] ); for ( var j = 0; j < connected.length; j++ ) connected[ j ].keep = true; } for ( var i = 0; i < nodes.length; i++ ) if ( ! nodes[ i ].keep ) nodes[ i ].show = "0"; EOT; } if ( in_array( 'redundant_links', $filters ) ) { $script_code .= <<<EOT for ( var i = 0; i < links.length; i++ ) links[ i ].redundant = false; for ( var i = 0; i < nodes.length; i++ ) for ( var j = 0; j < nodes[ i ].adjacentNodes.length; j++ ) { var connected = bfs( nodes[ i ].adjacentNodes[ j ] ); if ( connected.length > 0 ) for ( var k = 0; k < nodes[ i ].adjacentLinks.length; k++ ) if ( connected.indexOf( nodes[ i ].adjacentLinks[ k ].target ) >= 0 ) nodes[ i ].adjacentLinks[ k ].redundant = true; } for ( var i = links.length-1; i >= 0; i-- ) if ( links[ i ].redundant ) links.splice( i, 1 ); EOT; } $script_code .= <<<EOT links = links.filter( function ( d ) { return d.source.show == "1" && d.target.show == "1"; } ) for ( var i = 0; i < nodes.length; i++ ) { labelAnchors.push( { node: nodes[ i ] } ); labelAnchors.push( { node: nodes[ i ] } ); } for ( var i = 0; i < nodes.length; i++ ) { labelAnchorLinks.push( { source: i * 2, target: i * 2 + 1 } ); } var force = d3.layout.force() .size( [ width, height ] ) .nodes( nodes ) .links( links ) .gravity( 1 ) .linkDistance( 20 ) .charge( -3000 ) .linkStrength( 2 ) force.start(); var force2 = d3.layout.force() .nodes( labelAnchors ) .links( labelAnchorLinks ) .gravity( 0 ) .linkDistance( 0 ) .linkStrength( 8 ) .charge( -100 ) .size( [ width, height ] ); force2.start(); vis.append( "svg:defs" ) .append( "marker" ) .attr( "id", "triangle" ) .attr( "viewbox", "0 0 10 10" ) .attr( "markerWidth", 10 ) .attr( "markerHeight", 10 ) .attr( "refX", 15 ) .attr( "refY", 5 ) .attr( "orient", "auto" ) .attr( "markerUnits", "strokeWidth" ) .append( "polyline" ) .attr( "points", "0,0 10,5 0,10 1,5" ) .style( "fill", "#999" ); var link = vis.selectAll("line.link") .data(links) .enter().append("svg:line") .attr("class", "link") .style("stroke", "#999") .attr( "marker-end", "url(#triangle)" ); if ( links.length == 0 ) { d3.selectAll("line.link").remove(); } force.nodes( force.nodes().filter( function ( d ) { return d.show == "1"; } ) ); force2.nodes( force2.nodes().filter( function ( d ) { return d.node.show == "1"; } ) ); var node = vis.selectAll("g.node") .data(force.nodes()) .enter().append("svg:g") .attr("class", "node"); node.append("svg:circle") .attr("r", 5) .style("fill", function (d) { return d.color; } ) .style("stroke", "#FFF") .style("stroke-width", 3) .append( "title" ) .text( function (d, i) { return d.label + " " + d.title; }); node.call(force.drag); var anchorLink = vis.selectAll("line.anchorLink").data(labelAnchorLinks); var anchorNode = vis.selectAll("g.anchorNode") .data(force2.nodes()) .enter().append("svg:g") .attr("class", "anchorNode"); anchorNode.append("svg:circle") .attr("r", 0) .style("fill", "#FFF"); anchorNode.append("svg:text") .attr( 'data-sigil', 'hovercard' ) .attr( 'data-meta', function ( d ) { if ( d ) return d.node.meta; } ) .text( function(d, i) { return i % 2 == 0 ? "" : d.node.label }) .style( "fill", function ( d ) { return d.node.color; } ) .style( "font-family", "Arial" ) .style( "font-size", 12 ) .style( "cursor", "pointer" ) .on( 'click', function( d,i ) { if ( d ) { window.open( "/" + d.node.label, "_blank" ); d3.event.stopPropagation(); } } ) .append( 'svg:title' ) .text( function (d, i) { return i % 2 == 0 ? "" : d.node.label + " " + d.node.title }); var updateLink = function() { this .attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); } var updateNode = function() { this.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); } force.on("tick", function() { force2.start(); node.call(updateNode); anchorNode.each(function(d, i) { if(i % 2 == 0) { d.x = d.node.x; d.y = d.node.y; } else { var b = this.childNodes[1].getBBox(); var diffX = d.x - d.node.x; var diffY = d.y - d.node.y; var dist = Math.sqrt(diffX * diffX + diffY * diffY); var shiftX = b.width * (diffX - dist) / (dist * 2); shiftX = Math.max(-b.width, Math.min(0, shiftX)); var shiftY = 5; this.childNodes[1].setAttribute("transform", "translate(" + shiftX + "," + shiftY + ")"); } }); anchorNode.call(updateNode); link.call(updateLink); anchorLink.call(updateLink); }); </script> EOT; $box_content = new PhutilSafeHTML( $script_code ); $box = id( new PHUIBoxView() ) ->appendChild( phutil_tag( 'div', array( "class" => "is4u_graph" ), '' ) ) ->appendChild( phutil_tag( 'script', array( 'src' => $this->uri ) ) ) ->appendChild( $box_content ) ->appendChild( phutil_tag( 'div', array(), pht( 'Links indicate dependency "this task has to be done before that". Blue one tasks are yours. Red ones represent your true blockers while magenta other blocking tasks.' ) ) ) ->addPadding( PHUI::PADDING_LARGE ); $header = id( new PHUIHeaderView() ) ->setHeader( $this->header ); $filter_header = id( new PHUIHeaderView() ) ->setHeader( pht( 'Filters' ) ); $filter_defs = array( 'my_standalone' => pht( 'my standalone tasks' ), 'others_standalone' => pht( 'others standalone tasks' ), 'others_clusters' => pht( 'clusters without my tasks' ), 'redundant_links' => pht( 'redundant dependencies' ), /* 'stack_stucked' => 'tasks from Stucked stack', 'stack_wishlist' => 'tasks from Wishlist stack', 'stack_backlog' => 'tasks from Backlog stack', 'stack_discussion' => 'tasks from Needs discussion stack', 'stack_revision' => 'tasks from Needs revision stack', 'wishlist_priority' => 'tasks with Wishlist priority' */ ); $cb = id( new AphrontFormCheckboxControl() )->setLabel( 'Hide' ); foreach ( $filter_defs as $k => $v ) { $cb->addCheckbox( 'filters[]', $k, pht( $v ), in_array( $k, $filters ) ); } $filter = id ( new AphrontFormView() ) ->setUser( $this->viewer ) ->appendChild( $cb ) ->appendChild( id( new AphrontFormSubmitControl() )->setValue( pht( 'Filter' ) ) ); $filter_box = id( new PHUIBoxView() ) ->appendChild( $filter_header ) ->appendChild( $filter ) ->setBorder( true ) ->addMargin(PHUI::MARGIN_LARGE_TOP) ->addMargin(PHUI::MARGIN_LARGE_LEFT) ->addMargin(PHUI::MARGIN_LARGE_RIGHT) ->addClass( 'phui-object-box' ); $fullbox = id( new PHUIBoxView() ) ->appendChild( $header ) ->appendChild( $box ) ->setBorder( true ) ->addMargin(PHUI::MARGIN_LARGE_TOP) ->addMargin(PHUI::MARGIN_LARGE_LEFT) ->addMargin(PHUI::MARGIN_LARGE_RIGHT) ->addClass( 'phui-object-box' ); $rendered = id ( new PHUIBoxView() ) ->appendChild( $filter_box ) ->appendChild( $fullbox ); return $rendered; } }
milsorm/phabricator-interpeller
src/interpeller/views/InterpellerGraphView.php
PHP
artistic-2.0
13,934
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (16) on Fri Jul 02 03:26:51 UTC 2021 --> <title>Uses of Class net.glowstone.net.message.play.entity.EntityEffectMessage (Glowstone 2021.7.1-SNAPSHOT API)</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2021-07-02"> <meta name="description" content="use: package: net.glowstone.net.message.play.entity, class: EntityEffectMessage"> <meta name="generator" content="javadoc/ClassUseWriter"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../../../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../../../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> <script type="text/javascript" src="../../../../../../../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../../../../../../../script-dir/jquery-ui.min.js"></script> </head> <body class="class-use-page"> <script type="text/javascript">var pathtoroot = "../../../../../../../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../../../../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">Class</a></li> <li class="nav-bar-cell1-rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <div class="header"> <h1 title="Uses of Class net.glowstone.net.message.play.entity.EntityEffectMessage" class="title">Uses of Class<br>net.glowstone.net.message.play.entity.EntityEffectMessage</h1> </div> <div class="caption"><span>Packages that use <a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">EntityEffectMessage</a></span></div> <div class="summary-table two-column-summary"> <div class="table-header col-first">Package</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><a href="#net.glowstone.net.codec.play.entity">net.glowstone.net.codec.play.entity</a></div> <div class="col-last even-row-color">&nbsp;</div> </div> <section class="class-uses"> <ul class="block-list"> <li> <section class="detail" id="net.glowstone.net.codec.play.entity"> <h2>Uses of <a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">EntityEffectMessage</a> in <a href="../../../../codec/play/entity/package-summary.html">net.glowstone.net.codec.play.entity</a></h2> <div class="caption"><span>Methods in <a href="../../../../codec/play/entity/package-summary.html">net.glowstone.net.codec.play.entity</a> that return <a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">EntityEffectMessage</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code><a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">EntityEffectMessage</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">EntityEffectCodec.</span><code><span class="member-name-link"><a href="../../../../codec/play/entity/EntityEffectCodec.html#decode(io.netty.buffer.ByteBuf)">decode</a></span>&#8203;(io.netty.buffer.ByteBuf&nbsp;buf)</code></div> <div class="col-last even-row-color">&nbsp;</div> </div> <div class="caption"><span>Methods in <a href="../../../../codec/play/entity/package-summary.html">net.glowstone.net.codec.play.entity</a> with parameters of type <a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">EntityEffectMessage</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code>io.netty.buffer.ByteBuf</code></div> <div class="col-second even-row-color"><span class="type-name-label">EntityEffectCodec.</span><code><span class="member-name-link"><a href="../../../../codec/play/entity/EntityEffectCodec.html#encode(io.netty.buffer.ByteBuf,net.glowstone.net.message.play.entity.EntityEffectMessage)">encode</a></span>&#8203;(io.netty.buffer.ByteBuf&nbsp;buf, <a href="../EntityEffectMessage.html" title="class in net.glowstone.net.message.play.entity">EntityEffectMessage</a>&nbsp;message)</code></div> <div class="col-last even-row-color">&nbsp;</div> </div> </section> </li> </ul> </section> </main> <footer role="contentinfo"> <hr> <p class="legal-copy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </footer> </div> </div> </body> </html>
GlowstoneMC/glowstonemc.github.io
content/jd/glowstone/1.17/net/glowstone/net/message/play/entity/class-use/EntityEffectMessage.html
HTML
artistic-2.0
6,144
<?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <?xml-stylesheet href="logtalk.css" type="text/css"?><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>fibonacci</title> <link rel="stylesheet" href="logtalk.css" type="text/css"/> </head> <body> <div class="header"> <p class="type">object</p> <h1 class="code">fibonacci</h1> <blockquote> <p class="comment">Computation of Fibonacci numbers using a fold left meta-predicate.</p> </blockquote> </div> <div class="entity"> <div class="section"> <dl class="properties"> <dt class="key">author:</dt> <dd class="value"> <code>Paulo Moura</code> </dd> <dt class="key">version:</dt> <dd class="value"> <code>1.0</code> </dd> <dt class="key">date:</dt> <dd class="value"> <code>2010/12/19</code> </dd> </dl> <dl class="properties"> <dt class="key">compilation:</dt> <dd class="value"> <code>static, context_switching_calls</code> </dd> </dl> <p class="comment">(no dependencies on other files)</p> </div> </div> <div class="predicates"> <div class="public"> <h2>Public interface</h2> <div class="section"> <h3 class="code">nth/2</h3> <blockquote> <p class="comment">Calculates the Nth Fibonacci number.</p> </blockquote> <dl class="properties"> <dt class="key">compilation:</dt> <dd class="value"> <code>static</code> </dd> <dt class="key">template:</dt> <dd class="value"> <code>nth(Nth,Number)</code> </dd> <dt class="key">mode &ndash; number of solutions:</dt> <dd class="value"> <code>nth(+integer,-integer) &ndash; one</code> </dd> </dl> </div> </div> <div class="protected"> <h2>Protected interface</h2> <div class="section"> <p class="comment">(none)</p> </div> </div> <div class="private"> <h2>Private predicates</h2> <div class="section"> <p class="comment">(none)</p> </div> </div> </div> <div class="operators"> <h2>Operators</h2> <div class="section"> <h3 class="comment">(none)</h3> </div> </div> <div class="remarks"> <h2>Remarks</h2> <div class="section"> <h3 class="comment">(none)</h3> </div> </div> </body> </html>
igler/ESProNa
doc/fibonacci_0.html
HTML
artistic-2.0
2,873
#!/bin/bash containerID=$(docker run -d metaverseorg/buildnginx) docker cp $containerID:/root/build/nginx-1.10.0/nginx_1.10.0-1_amd64.deb . sleep 1 docker rm $containerID
aelsharawi/nginx-ps-hdrs-cach
extractdeb.sh
Shell
artistic-2.0
172
# demo for a bug in bud-tls ## Usage ```bash node index.js & bud -c bud.json & curl -k https://localhost:1443/demo.js ``` You'll see an SSL error.
joeybaker/bud-bug-demo
README.md
Markdown
artistic-2.0
150
# PattisQuiltPatterns
pattiuman/PattisQuiltPatterns
README.md
Markdown
artistic-2.0
22
/* * optional_io.hpp * * Created on: 29 апр. 2016 г. * Author: sergey.fedorov */ #ifndef WIRE_ENCODING_DETAIL_OPTIONAL_IO_HPP_ #define WIRE_ENCODING_DETAIL_OPTIONAL_IO_HPP_ #include <boost/optional.hpp> #include <wire/encoding/detail/helpers.hpp> #include <wire/encoding/detail/fixed_io.hpp> #include <wire/encoding/detail/wire_io_detail.hpp> namespace wire { namespace encoding { namespace detail { template < typename T > struct writer < ::boost::optional< T > > { using optional_type = ::boost::optional< T >; using in_type = typename arg_type_helper< optional_type >::in_type; using flag_writer = writer< bool >; using type_writer = writer< T >; template < typename OutputIterator > static void output(OutputIterator o, in_type v) { using output_iterator_check = octet_output_iterator_concept< OutputIterator >; flag_writer::output(o, v.is_initialized()); if (v.is_initialized()) { type_writer::output(o, *v); } } }; template < typename T > struct reader < ::boost::optional< T > > { using optional_type = ::boost::optional< T >; using out_type = typename arg_type_helper< optional_type >::out_type; using flag_reader = reader< bool >; using type_reader = reader< T >; template < typename InputIterator > static void input(InputIterator& begin, InputIterator end, out_type v) { using input_iterator_check = octet_input_iterator_concept< InputIterator >; bool has_value = false; flag_reader::input(begin, end, has_value); if (has_value) { T val; type_reader::input(begin, end, val); v = val; } } }; } /* namespace detail */ } /* namespace encoding */ } /* namespace wire */ #endif /* WIRE_ENCODING_DETAIL_OPTIONAL_IO_HPP_ */
zmij/wire
include/wire/encoding/detail/optional_io.hpp
C++
artistic-2.0
1,900
#include<stdio.h> // Andrew was here int main() { int save1=5,save2=2; //Set the integers and name the save float average; // Average variable int total; // set total for integer total=save1+save2; // Set total given the variables average=total/2.0; // Divide printf("Total of %d and %d = %d",save1,save2,total); // Print numerical as total printf("\nAverage of %d and %d = %.1f",save1,save2,average); // Show the average return 0; // Otherwise return 0 "undefined" }
Mentors4EDU/C-Programming-Portfolio
Problems/2A.c
C
artistic-2.0
492
<!DOCTYPE HTML> <html lang="en-US" > <head> <meta charset="UTF-8"> <title>Create a basic map | Become a humanitarian data scientist with R</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="description" content=""> <meta name="generator" content="GitBook 1.0.3"> <meta name="HandheldFriendly" content="true"/> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png"> <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon"> <link rel="next" href="../create_a_thematic_map/README.html" /> <link rel="prev" href="../multivariate_analysis_-_mca/README.html" /> </head> <body> <link rel="stylesheet" href="../gitbook/style.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-exercises/exercises.css"> <div class="book" data-level="10" data-basepath=".." data-revision="1420992706168"> <div class="book-summary"> <div class="book-search"> <input type="text" placeholder="Type to search" class="form-control" /> </div> <ul class="summary"> <li class="chapter " data-level="0" data-path="index.html"> <a href="../index.html"> <i class="fa fa-check"></i> Introduction </a> </li> <li class="chapter " data-level="1" data-path="why_moving_to_r/README.html"> <a href="../why_moving_to_r/README.html"> <i class="fa fa-check"></i> <b>1.</b> Why moving to R </a> </li> <li class="chapter " data-level="2" data-path="set_up_your_environment/README"> <a href="../set_up_your_environment/README"> <i class="fa fa-check"></i> <b>2.</b> Set Up your environment </a> </li> <li class="chapter " data-level="3" data-path="data_management_-_basic_r_concept/README"> <a href="../data_management_-_basic_r_concept/README"> <i class="fa fa-check"></i> <b>3.</b> Data management - basic R Concept </a> </li> <li class="chapter " data-level="4" data-path="organise_your_project/README.html"> <a href="../organise_your_project/README.html"> <i class="fa fa-check"></i> <b>4.</b> Organise your project </a> </li> <li class="chapter " data-level="5" data-path="retrieve_data/README.html"> <a href="../retrieve_data/README.html"> <i class="fa fa-check"></i> <b>5.</b> Retrieve data </a> </li> <li class="chapter " data-level="6" data-path="re-encode_&amp;_classify_a_variable/README.html"> <a href="../re-encode_&amp;_classify_a_variable/README.html"> <i class="fa fa-check"></i> <b>6.</b> Re-encode &amp; classify a variable </a> </li> <li class="chapter " data-level="7" data-path="create_graph_with_gplot2/README.html"> <a href="../create_graph_with_gplot2/README.html"> <i class="fa fa-check"></i> <b>7.</b> Create graphs with Gplot2 </a> </li> <li class="chapter " data-level="8" data-path="produce_histogram/README"> <a href="../produce_histogram/README"> <i class="fa fa-check"></i> <b>8.</b> Produce histogram </a> </li> <li class="chapter " data-level="9" data-path="multivariate_analysis_-_mca/README.html"> <a href="../multivariate_analysis_-_mca/README.html"> <i class="fa fa-check"></i> <b>9.</b> Multivariate Analysis - MCA </a> </li> <li class="chapter active" data-level="10" data-path="create_a_basic_map/README.html"> <a href="../create_a_basic_map/README.html"> <i class="fa fa-check"></i> <b>10.</b> Create a basic map </a> </li> <li class="chapter " data-level="11" data-path="create_a_thematic_map/README.html"> <a href="../create_a_thematic_map/README.html"> <i class="fa fa-check"></i> <b>11.</b> Create a thematic map - Choropleth </a> </li> <li class="chapter " data-level="12" data-path="extract_value_from_a_raster_image_-_bioclimatic_data/README.html"> <a href="../extract_value_from_a_raster_image_-_bioclimatic_data/README.html"> <i class="fa fa-check"></i> <b>12.</b> Extract value from a raster image - bioclimatic data </a> </li> <li class="chapter " data-level="13" data-path="gnerate_reports_and_slides/README"> <a href="../gnerate_reports_and_slides/README"> <i class="fa fa-check"></i> <b>13.</b> Generate reports and slides </a> </li> <li class="chapter " data-level="14" data-path="create_datavisualisation/README"> <a href="../create_datavisualisation/README"> <i class="fa fa-check"></i> <b>14.</b> Create datavisualisation </a> </li> <li class="divider"></li> <li> <a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Published using GitBook</a> </li> </ul> </div> <div class="book-body"> <div class="body-inner"> <div class="book-header"> <!-- Actions Left --> <a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a> <a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a> <div id="font-settings-wrapper" class="dropdown pull-left"> <a href="#" class="btn toggle-dropdown" aria-label="Toggle font settings"><i class="fa fa-font"></i> </a> <div class="dropdown-menu font-settings"> <div class="dropdown-caret"> <span class="caret-outer"></span> <span class="caret-inner"></span> </div> <div class="buttons"> <button type="button" id="reduce-font-size" class="button size-2">A</button> <button type="button" id="enlarge-font-size" class="button size-2">A</button> </div> <div class="buttons font-family-list"> <button type="button" data-font="0" class="button">Serif</button> <button type="button" data-font="1" class="button">Sans</button> </div> <div class="buttons color-theme-list"> <button type="button" id="color-theme-preview-0" class="button size-3" data-theme="0">White</button> <button type="button" id="color-theme-preview-1" class="button size-3" data-theme="1">Sepia</button> <button type="button" id="color-theme-preview-2" class="button size-3" data-theme="2">Night</button> </div> </div> </div> <!-- Actions Right --> <div class="dropdown pull-right"> <a href="#" class="btn toggle-dropdown" aria-label="Toggle share dropdown"><i class="fa fa-share-alt"></i> </a> <div class="dropdown-menu font-settings dropdown-left"> <div class="dropdown-caret"> <span class="caret-outer"></span> <span class="caret-inner"></span> </div> <div class="buttons"> <button type="button" data-sharing="twitter" class="button">Twitter</button> <button type="button" data-sharing="google-plus" class="button">Google</button> <button type="button" data-sharing="facebook" class="button">Facebook</button> <button type="button" data-sharing="weibo" class="button">Weibo</button> <button type="button" data-sharing="instapaper" class="button">Instapaper</button> </div> </div> </div> <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a> <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a> <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a> <!-- Title --> <h1> <i class="fa fa-circle-o-notch fa-spin"></i> <a href="../" >Become a humanitarian data scientist with R</a> </h1> </div> <div class="page-wrapper" tabindex="-1"> <div class="page-inner"> <section class="normal" id="section-gitbook_4698"> <h1 id="create-a-basic-map">Create a basic map</h1> <p>Load a map</p> <p>R offers a large <a href="http://cran.r-project.org/web/views/Spatial.html" target="_blank">number of packages to deal with spatial data</a></p> </section> </div> </div> </div> <a href="../multivariate_analysis_-_mca/README.html" class="navigation navigation-prev " aria-label="Previous page: Multivariate Analysis - MCA"><i class="fa fa-angle-left"></i></a> <a href="../create_a_thematic_map/README.html" class="navigation navigation-next " aria-label="Next page: Create a thematic map - Choropleth"><i class="fa fa-angle-right"></i></a> </div> </div> <script src="../gitbook/app.js"></script> <script src="../gitbook/plugins/gitbook-plugin-exercises/ace/ace.js"></script> <script src="../gitbook/plugins/gitbook-plugin-exercises/ace/theme-tomorrow.js"></script> <script src="../gitbook/plugins/gitbook-plugin-exercises/ace/mode-javascript.js"></script> <script src="../gitbook/plugins/gitbook-plugin-exercises/exercises.js"></script> <script src="https://cdn.mathjax.org/mathjax/2.4-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script> <script> require(["gitbook"], function(gitbook) { var config = {"fontSettings":{"theme":null,"family":"sans","size":2}}; gitbook.start(config); }); </script> <script src="../gitbook/plugins/gitbook-plugin-exercises/jsrepl/jsrepl.js" id="jsrepl-script"></script> </body> </html>
Edouard-Legoupil/humanitaRian-data-science
book/_book/create_a_basic_map/README.html
HTML
artistic-2.0
14,187
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (16) on Sat Dec 18 21:56:37 UTC 2021 --> <title>net.glowstone.net.config (Glowstone 2021.7.1-SNAPSHOT API)</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2021-12-18"> <meta name="description" content="declaration: package: net.glowstone.net.config"> <meta name="generator" content="javadoc/PackageWriterImpl"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> <script type="text/javascript" src="../../../../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../../../../script-dir/jquery-ui.min.js"></script> </head> <body class="package-declaration-page"> <script type="text/javascript">var pathtoroot = "../../../../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li class="nav-bar-cell1-rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <div class="header"> <h1 title="Package" class="title">Package&nbsp;net.glowstone.net.config</h1> </div> <hr> <div class="package-signature">package <span class="element-name">net.glowstone.net.config</span></div> <section class="summary"> <ul class="summary-list"> <li> <div class="caption"><span>Class Summary</span></div> <div class="summary-table two-column-summary"> <div class="table-header col-first">Class</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><a href="DnsEndpoint.html" title="class in net.glowstone.net.config">DnsEndpoint</a></div> <div class="col-last even-row-color">&nbsp;</div> </div> </li> </ul> </section> </main> <footer role="contentinfo"> <hr> <p class="legal-copy"><small>Copyright &#169; 2021. All rights reserved.</small></p> </footer> </div> </div> </body> </html>
GlowstoneMC/glowstonemc.github.io
content/jd/glowstone/1.16/net/glowstone/net/config/package-summary.html
HTML
artistic-2.0
3,285
<!DOCTYPE html> <!-- This is a starter template page. Use this page to start your new project from scratch. This page gets rid of all links and provides the needed markup only. --> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Health Support Tracking System</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.5 --> <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <!-- jQueryUI --> <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <!-- Multi select --> <link rel="stylesheet" href="plugins/bootstrap-multiselect/css/bootstrap-multiselect.css" type="text/css"> <link rel="stylesheet" href="plugins/bootstrap-multiselect/css/prettify.css" type="text/css"> <!-- Theme style --> <link rel="stylesheet" href="dist/css/AdminLTE.min.css"> <!-- AdminLTE Skins. Choose a skin from the css/skins folder instead of downloading all of them to reduce the load. --> <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css"> <style type="text/css"> /*STYLES FOR CSS POPUP*/ #blanket { background-color:#111; opacity: 0.65; *background:none; position:absolute; z-index: 9001; top:0px; left:0px; width:100%; } #popUpAppointment { position:absolute; width:400px; height:300px; z-index: 9002; } #popupConfirm { position:absolute; width:400px; height:300px; z-index: 9002; } </style> </head> <body class="hold-transition skin-green-light sidebar-mini"> <div class="wrapper"> <!-- Main Header --> <header class="main-header"> <!-- Logo --> <a href="#" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><img src="image/FPT_Logo.png" style="width :50px;height: 50px;"></span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><img src="image/FPT_Logo.png" style="height: 50px;"></span> </a> <!-- Header Navbar --> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> </a> <!-- Logo --> <a href="#" style="font-size: 20px;line-height: 50px;text-align: center;color: white;"> <!-- logo for regular state and mobile devices --> <span>Health Support Tracking System</span> </a> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Notifications Menu --> <li class="dropdown notifications-menu"> <!-- Menu toggle button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">2</span> </a> <ul class="dropdown-menu"> <li class="header">You have 2 notifications</li> <li> <!-- Inner Menu: contains the notifications --> <ul class="menu"> <li><!-- start notification --> <a href="#"> <i class="fa fa-users text-aqua"></i> Appointment with Patient 1 </a> </li><!-- end notification --> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <!-- User Account Menu --> <li class="dropdown user user-menu"> <!-- Menu Toggle Button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <!-- The user image in the navbar--> <img src="dist/img/user2-160x160.jpg" class="user-image" alt="User Image"> <!-- hidden-xs hides the username on small devices so only the image appears. --> <span class="hidden-xs">Dr Nhat Anh</span> </a> <ul class="dropdown-menu"> <!-- The user image in the menu --> <li class="user-header"> <img src="dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> <p> Dr Nhat Anh <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel (optional) --> <div class="user-panel"> <div class="pull-left image"> <img src="dist/img/user2-160x160.jpg" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Dr Nhat Anh</p> <!-- Status --> <a href="#"><i class="fa fa-circle text-success"></i> Doctor</a> </div> </div> <!-- Sidebar Menu --> <ul class="sidebar-menu"> <li class="header">MAIN NAVIGATION</li> <li class="treeview"> <a href="#"> <i class="fa fa-user-md"></i> <span>Nurse</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="register.html"><i class="fa fa-circle-o"></i> Register Patient</a></li> <li><a href="listpatients.html"><i class="fa fa-circle-o"></i> Patients</a></li> </ul> </li> <li class="active treeview"> <a href="#"> <i class="fa fa-stethoscope"></i> <span>Doctor</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li class="active"><a href="listpatients.html"><i class="fa fa-circle-o"></i> Patients</a></li> <li><a href="Appointment.html"><i class="fa fa-circle-o"></i> Appointments</a></li> </ul> </li> <li class="treeview"> <a href="#"> <i class="fa fa-user-plus"></i> <span>Admin</span> <i class="fa fa-angle-left pull-right"></i> </a> <ul class="treeview-menu"> <li><a href="#"><i class="fa fa-circle-o"></i> Staffs</a></li> </ul> </li> </ul><!-- /.sidebar-menu --> </section> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Nutrition <small>Patient 2</small> </h1> <ol class="breadcrumb"> <li><a href="home"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Nutrition</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-md-12"> <div class="box box-default"> <!-- form start --> <form class="form-horizontal"> <table id="rateEnergyMeals" class="table table-bordered table-striped"> <thead> <tr> <th>Rate Energy Meals</th> <th>Energy</th> </tr> </thead> <tbody> <tr> <td> <label class="control-label">Breakfast</label> </td> <td> <input type="text" name="Breakfast" class="form-control" /> </td> </tr> <tr> <td> <label class="control-label">Light Snacks</label> </td> <td> <input type="text" name="lightSnacks" class="form-control" /> </td> </tr> <tr> <td> <label class="control-label">Lunch</label> </td> <td> <input type="text" name="lunch" class="form-control" /> </td> </tr> <tr> <td><label class="control-label">Afternoon Snacks</label></td> <td> <input type="text" name="afternoonSnacks" class="form-control" /> </td> </tr> <tr> <td><label class="control-label">Dinner</label></td> <td> <input type="text" name="dinner" class="form-control" /> </td> </tr> <tr> <td><label class="control-label">Evening Snacks</label></td> <td> <input type="text" name="eveningSnacks" class="form-control" /> </td> </tr> </tbody> </table> </form><!-- /.form --> </div><!-- /.box --> </div><!-- /.col --> </div><!-- /.row --> </section><!-- /.content --> </div><!-- /.content-wrapper --> <!-- Main Footer --> <footer class="main-footer"> <!-- To the right --> <div class="pull-right hidden-xs"> Version 1.0.0.1 </div> <!-- Default to the left --> <strong>Copyright &copy; 2015 <a href="#">Group 3</a>.</strong> All rights reserved. </footer> </div><!-- ./wrapper --> <!-- REQUIRED JS SCRIPTS --> <!-- jQuery 2.1.4 --> <script src="plugins/jQuery/jQuery-2.1.4.min.js"></script> <!-- Multi select --> <script type="text/javascript" src="plugins/bootstrap-multiselect/js/bootstrap-multiselect.js"></script> <script type="text/javascript" src="plugins/bootstrap-multiselect/js/prettify.js"></script> <!-- Bootstrap 3.3.5 --> <script src="bootstrap/js/bootstrap.min.js"></script> <!-- AdminLTE App --> <script src="dist/js/app.min.js"></script> <!-- jQueryUI --> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> </script> </body> </html>
quantdse60878/HSTS
prototype/starter - Copy.html
HTML
artistic-2.0
12,245
#define PARROT_IN_EXTENSION #include "parrot/parrot.h" #include "parrot/extend.h" #include "../sixmodelobject.h" #include "VMIter.h" /* This representation's function pointer table. */ static REPROps *this_repr; /* Creates a new type object of this representation, and associates it with * the given HOW. */ static PMC * type_object_for(PARROT_INTERP, PMC *HOW) { /* Create new object instance. */ VMIterInstance *obj = mem_allocate_zeroed_typed(VMIterInstance); /* Build an STable. */ PMC *st_pmc = create_stable(interp, this_repr, HOW); STable *st = STABLE_STRUCT(st_pmc); /* Create type object and point it back at the STable. */ obj->common.stable = st_pmc; st->WHAT = wrap_object(interp, obj); PARROT_GC_WRITE_BARRIER(interp, st_pmc); /* Flag it as a type object. */ MARK_AS_TYPE_OBJECT(st->WHAT); return st->WHAT; } /* Composes the representation. */ static void compose(PARROT_INTERP, STable *st, PMC *repr_info) { /* Nothing to do yet, but should handle type in the future. */ } /* Creates a new instance based on the type object. */ static PMC * allocate(PARROT_INTERP, STable *st) { VMIterInstance *obj = mem_allocate_zeroed_typed(VMIterInstance); obj->common.stable = st->stable_pmc; return wrap_object(interp, obj); } /* Initialize a new instance. */ static void initialize(PARROT_INTERP, STable *st, void *data) { /* Nothing to do here. */ } /* Copies to the body of one object to another. */ static void copy_to(PARROT_INTERP, STable *st, void *src, void *dest) { VMIterBody *src_body = (VMIterBody *)src; VMIterBody *dest_body = (VMIterBody *)dest; /* Nothing to do yet. */ } /* This Parrot-specific addition to the API is used to free an object. */ static void gc_free(PARROT_INTERP, PMC *obj) { mem_sys_free(PMC_data(obj)); PMC_data(obj) = NULL; } /* Gets the storage specification for this representation. */ static storage_spec get_storage_spec(PARROT_INTERP, STable *st) { storage_spec spec; spec.inlineable = STORAGE_SPEC_REFERENCE; spec.boxed_primitive = STORAGE_SPEC_BP_NONE; spec.can_box = 0; spec.bits = sizeof(void *) * 8; spec.align = ALIGNOF1(void *); return spec; } /* Initializes the VMIter representation. */ REPROps * VMIter_initialize(PARROT_INTERP) { /* Allocate and populate the representation function table. */ this_repr = mem_allocate_zeroed_typed(REPROps); this_repr->type_object_for = type_object_for; this_repr->compose = compose; this_repr->allocate = allocate; this_repr->initialize = initialize; this_repr->copy_to = copy_to; this_repr->gc_free = gc_free; this_repr->get_storage_spec = get_storage_spec; return this_repr; }
tokuhirom/nqp
src/vm/parrot/6model/reprs/VMIter.c
C
artistic-2.0
2,739
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>VisibleRemoteObject.Show</title> <link href="css/style.css" rel="stylesheet" type="text/css"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > </head> <body bgcolor="#ffffff"> <table border="0" width="100%" bgcolor="#F0F0FF"> <tr> <td>Concept Framework 2.2 documentation</td> <td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td> </tr> </table> <h2><a href="VisibleRemoteObject.html">VisibleRemoteObject</a>.Show</h2> <table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"> <tr bgcolor="#f0f0f0"> <td><i>Name</i></td> <td><i>Type</i></td> <td><i>Access</i></td> <td><i>Version</i></td> <td><i>Deprecated</i></td> </tr> <tr bgcolor="#fafafa"> <td><b>Show</b></td> <td>function</td> <td>public</td> <td>version 1.0</td> <td>no</td> </tr> </table> <br /> <b>Prototype:</b><br /> <table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>public function Show ()</b></td></tr></table> <br /> <br /> <b>Description:</b><br /> <table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"> <tr><td> This function shows this control by setting the <a href="VisibleRemoteObject.Visible.html">Visible</a> property to true. When instantiating a controls using the 'new' operator the <a href="VisibleRemoteObject.Visible.html">Visible</a> property is set to false by default. You must call Show for the control to appear on the client machine. </td></tr> </table> <br /> <b>Returns:</b><br /> This function returns null. <br /> <br /> <!-- <p> <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-html40" alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a> <a href="http://jigsaw.w3.org/css-validator/"> <img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!" border="0"/> </a> </p> --> <table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Eduard Suica, generation time: Sun Jan 27 18:15:03 2013 GMT</td><td align="right">(c)2013 <a href="http://www.devronium.com">Devronium Applications</a></td></tr></table> </body> </html>
Devronium/ConceptApplicationServer
core/server/Samples/CIDE/Help/VisibleRemoteObject.Show.html
HTML
bsd-2-clause
2,538
# C++ skeleton for Bison # Copyright (C) 2002-2015, 2018-2019 Free Software Foundation, Inc. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. m4_pushdef([b4_copyright_years], [2002-2015, 2018-2019]) # b4_position_file # ---------------- # Name of the file containing the position class, if we want this file. b4_defines_if([b4_required_version_if([302], [], [m4_define([b4_position_file], [position.hh])])])]) # b4_location_file # ---------------- # Name of the file containing the position/location class, # if we want this file. b4_percent_define_check_file([b4_location_file], [[api.location.file]], b4_defines_if([[location.hh]])) # b4_location_include # ------------------- # If location.hh is to be generated, the name under which should it be # included. # # b4_location_path # ---------------- # The path to use for the CPP guard. m4_ifdef([b4_location_file], [m4_define([b4_location_include], [b4_percent_define_get([[api.location.include]], ["b4_location_file"])]) m4_define([b4_location_path], b4_percent_define_get([[api.location.include]], ["b4_dir_prefix[]b4_location_file"])) m4_define([b4_location_path], m4_substr(m4_defn([b4_location_path]), 1, m4_eval(m4_len(m4_defn([b4_location_path])) - 2))) ]) # b4_location_define # ------------------ # Define the position and location classes. m4_define([b4_location_define], [[ /// A point in a source file. class position { public:]m4_ifdef([b4_location_constructors], [[ /// Construct a position. explicit position (]b4_percent_define_get([[filename_type]])[* f = YY_NULLPTR, unsigned l = ]b4_location_initial_line[u, unsigned c = ]b4_location_initial_column[u) : filename (f) , line (l) , column (c) {} ]])[ /// Initialization. void initialize (]b4_percent_define_get([[filename_type]])[* fn = YY_NULLPTR, unsigned l = ]b4_location_initial_line[u, unsigned c = ]b4_location_initial_column[u) { filename = fn; line = l; column = c; } /** \name Line and Column related manipulators ** \{ */ /// (line related) Advance to the COUNT next lines. void lines (int count = 1) { if (count) { column = ]b4_location_initial_column[u; line = add_ (line, count, ]b4_location_initial_line[); } } /// (column related) Advance to the COUNT next columns. void columns (int count = 1) { column = add_ (column, count, ]b4_location_initial_column[); } /** \} */ /// File name to which this position refers. ]b4_percent_define_get([[filename_type]])[* filename; /// Current line number. unsigned line; /// Current column number. unsigned column; private: /// Compute max (min, lhs+rhs). static unsigned add_ (unsigned lhs, int rhs, int min) { return static_cast<unsigned> (std::max (min, static_cast<int> (lhs) + rhs)); } }; /// Add \a width columns, in place. inline position& operator+= (position& res, int width) { res.columns (width); return res; } /// Add \a width columns. inline position operator+ (position res, int width) { return res += width; } /// Subtract \a width columns, in place. inline position& operator-= (position& res, int width) { return res += -width; } /// Subtract \a width columns. inline position operator- (position res, int width) { return res -= width; } ]b4_percent_define_flag_if([[define_location_comparison]], [[ /// Compare two position objects. inline bool operator== (const position& pos1, const position& pos2) { return (pos1.line == pos2.line && pos1.column == pos2.column && (pos1.filename == pos2.filename || (pos1.filename && pos2.filename && *pos1.filename == *pos2.filename))); } /// Compare two position objects. inline bool operator!= (const position& pos1, const position& pos2) { return !(pos1 == pos2); } ]])[ /** \brief Intercept output stream redirection. ** \param ostr the destination output stream ** \param pos a reference to the position to redirect */ template <typename YYChar> std::basic_ostream<YYChar>& operator<< (std::basic_ostream<YYChar>& ostr, const position& pos) { if (pos.filename) ostr << *pos.filename << ':'; return ostr << pos.line << '.' << pos.column; } /// Two points in a source file. class location { public: ]m4_ifdef([b4_location_constructors], [ /// Construct a location from \a b to \a e. location (const position& b, const position& e) : begin (b) , end (e) {} /// Construct a 0-width location in \a p. explicit location (const position& p = position ()) : begin (p) , end (p) {} /// Construct a 0-width location in \a f, \a l, \a c. explicit location (]b4_percent_define_get([[filename_type]])[* f, unsigned l = ]b4_location_initial_line[u, unsigned c = ]b4_location_initial_column[u) : begin (f, l, c) , end (f, l, c) {} ])[ /// Initialization. void initialize (]b4_percent_define_get([[filename_type]])[* f = YY_NULLPTR, unsigned l = ]b4_location_initial_line[u, unsigned c = ]b4_location_initial_column[u) { begin.initialize (f, l, c); end = begin; } /** \name Line and Column related manipulators ** \{ */ public: /// Reset initial location to final location. void step () { begin = end; } /// Extend the current location to the COUNT next columns. void columns (int count = 1) { end += count; } /// Extend the current location to the COUNT next lines. void lines (int count = 1) { end.lines (count); } /** \} */ public: /// Beginning of the located region. position begin; /// End of the located region. position end; }; /// Join two locations, in place. inline location& operator+= (location& res, const location& end) { res.end = end.end; return res; } /// Join two locations. inline location operator+ (location res, const location& end) { return res += end; } /// Add \a width columns to the end position, in place. inline location& operator+= (location& res, int width) { res.columns (width); return res; } /// Add \a width columns to the end position. inline location operator+ (location res, int width) { return res += width; } /// Subtract \a width columns to the end position, in place. inline location& operator-= (location& res, int width) { return res += -width; } /// Subtract \a width columns to the end position. inline location operator- (location res, int width) { return res -= width; } ]b4_percent_define_flag_if([[define_location_comparison]], [[ /// Compare two location objects. inline bool operator== (const location& loc1, const location& loc2) { return loc1.begin == loc2.begin && loc1.end == loc2.end; } /// Compare two location objects. inline bool operator!= (const location& loc1, const location& loc2) { return !(loc1 == loc2); } ]])[ /** \brief Intercept output stream redirection. ** \param ostr the destination output stream ** \param loc a reference to the location to redirect ** ** Avoid duplicate information. */ template <typename YYChar> std::basic_ostream<YYChar>& operator<< (std::basic_ostream<YYChar>& ostr, const location& loc) { unsigned end_col = 0 < loc.end.column ? loc.end.column - 1 : 0; ostr << loc.begin; if (loc.end.filename && (!loc.begin.filename || *loc.begin.filename != *loc.end.filename)) ostr << '-' << loc.end.filename << ':' << loc.end.line << '.' << end_col; else if (loc.begin.line < loc.end.line) ostr << '-' << loc.end.line << '.' << end_col; else if (loc.begin.column < end_col) ostr << '-' << end_col; return ostr; } ]]) m4_ifdef([b4_position_file], [[ ]b4_output_begin([b4_dir_prefix], [b4_position_file])[ ]b4_generated_by[ // Starting with Bison 3.2, this file is useless: the structure it // used to define is now defined in "]b4_location_file[". // // To get rid of this file: // 1. add 'require "3.2"' (or newer) to your grammar file // 2. remove references to this file from your build system // 3. if you used to include it, include "]b4_location_file[" instead. #include ]b4_location_include[ ]b4_output_end[ ]]) m4_ifdef([b4_location_file], [[ ]b4_output_begin([b4_dir_prefix], [b4_location_file])[ ]b4_copyright([Locations for Bison parsers in C++])[ /** ** \file ]b4_location_path[ ** Define the ]b4_namespace_ref[::location class. */ ]b4_cpp_guard_open([b4_location_path])[ # include <algorithm> // std::max # include <iostream> # include <string> ]b4_null_define[ ]b4_namespace_open[ ]b4_location_define[ ]b4_namespace_close[ ]b4_cpp_guard_close([b4_location_path])[ ]b4_output_end[ ]]) m4_popdef([b4_copyright_years])
OSTC/php-sdk-binary-tools
msys2/usr/share/bison/skeletons/location.cc
C++
bsd-2-clause
10,004
int xmodem_recv(int usecrc); int xmodem_send(int send1k);
mjgardner/cgterm
xmodem.h
C
bsd-2-clause
58
# DateTime class Quick and small C++ date and time class Known C++ &lt;ctime&gt; date and time structures have disappointing limitations which have driven me to make my own class. For instance, time_t is not crossplatform-consistant and can't keep dates before 1970. Struct tm keeps dates from 1900 only. Modern C++ versions suggest more appropriate ways to track date and time. But what to do with, say, Visual Studio 2010? There are known libraries dealing with the subject but linking huge dependencies just for dates is not a stright-forward way. DateTime class is quick and small: it contains only one long long field which keeps number of milliseconds from the start of January the first of the first year (by Gregorian calendar). Instances may be initialized from a standard string, time_t or struct tm. Likewise it may be explicitly converted back to those data types. You can apply some arythmetics to DateTime: increase or decrease dates by a certain amount of days, months, years, compare DateTime values etc. DateTime class is very helpful when you are working with relational databases: SQLite, PostgreSQL, MS SQL... Just a simple example: DateTime now; now.setNow(); now.incMonth(20); cout << now.formatDateTime() << endl; now.fromUTC(); cout << now.formatDateTime() << endl; now.set("2017-01-28 22:12:50"); ## Some disclaimer Timezone is a tricky business and I can't say how fromUTC() and toUTC() will behave on different platforms. In detecting timezone gmtime_s() is used which is platform specific (I use Visual Studio 2010 Express as mentioned above). But you can easily fix that. Enjoy! Alexander Belkov
sundersb/datetime
README.md
Markdown
bsd-2-clause
1,667
/* * vsnprintf() * * Poor substitute for a real vsnprintf() function for systems * that don't have them... */ #include "compiler.h" #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include "nasmlib.h" #define BUFFER_SIZE 65536 /* Bigger than any string we might print... */ static char snprintf_buffer[BUFFER_SIZE]; int vsnprintf(char *str, size_t size, const char *format, va_list ap) { int rv, bytes; if (size > BUFFER_SIZE) { nasm_error(ERR_PANIC|ERR_NOFILE, "vsnprintf: size (%d) > BUFFER_SIZE (%d)", size, BUFFER_SIZE); size = BUFFER_SIZE; } rv = vsprintf(snprintf_buffer, format, ap); if (rv >= BUFFER_SIZE) nasm_error(ERR_PANIC|ERR_NOFILE, "vsnprintf buffer overflow"); if (size > 0) { if ((size_t)rv < size-1) bytes = rv; else bytes = size-1; memcpy(str, snprintf_buffer, bytes); str[bytes] = '\0'; } return rv; }
coapp-packages/nasm
lib/vsnprintf.c
C
bsd-2-clause
1,070
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__="Scott Hendrickson" __license__="Simplified BSD" import sys import datetime import fileinput from io import StringIO # Experimental: Use numba to speed up some fo the basic function # that are run many times per record # from numba import jit # use fastest option available try: import ujson as json except ImportError: try: import json except ImportError: import simplejson as json gnipError = "GNIPERROR" gnipRemove = "GNIPREMOVE" gnipDateTime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z") INTERNAL_EMPTY_FIELD = "GNIPEMPTYFIELD" class _Field(object): """ Base class for extracting the desired value at the end of a series of keys in a JSON Activity Streams payload. Set the application-wide default value (for e.g. missing values) here, but also use child classes to override when necessary. Subclasses also need to define the key-path (path) to the desired location by overwriting the path attr. """ # set some default values; these can be overwritten in custom classes # twitter format default_t_fmt = "%Y-%m-%dT%H:%M:%S.000Z" default_value = INTERNAL_EMPTY_FIELD path = [] # dict key-path to follow for desired value label = 'DummyKeyPathLabel' # this must match if-statement in constructor def __init__(self, json_record): if self.label == 'DummyKeyPathLabel': self.label = ':'.join(self.path) self.value = None # str representation of the field, often = str( self.value_list ) if json_record is not None: self.value = self.walk_path(json_record) else: self.value = self.default_value def __repr__(self): return unicode(self.value) def walk_path(self, json_record, path=None): res = json_record if path is None: path = self.path for k in path: if res is None: break if k not in res or ( type(res[k]) is list and len(res[k]) == 0 ): # parenthetical clause for values with empty lists e.g. twitter_entities return self.default_value res = res[k] # handle the special case where the walk_path found null (JSON) which converts to # a Python None. Only use "None" (str version) if it's assigned to self.default_value res = res if res is not None else self.default_value return res def walk_path_slower(self, json_record, path=None): """Slower version fo walk path. Depricated.""" if path is None: path = self.path try: execstr = "res=json_record" + '["{}"]'*len(path) exec(execstr.format(*path)) except (KeyError, TypeError): res = None if res is None: res = self.default_value return res def fix_length(self, iterable, limit=None): """ Take an iterable (typically a list) and an optional maximum length (limit). If limit is not given, and the input iterable is not equal to self.default_value (typically "None"), the input iterable is returned. If limit is given, the return value is a list that is either truncated to the first limit items, or padded with self.default_value until it is of size limit. Note: strings are iterables, so if you pass this function a string, it will (optionally) truncate the number of characters in the string according to limit. """ res = [] if limit is None: # no limits on the length of the result, so just return the original iterable res = iterable else: #if len(iterable) == 0: if iterable == self.default_value or len(iterable) == 0: # if walk_path() finds the final key, but the value is an empty list # (common for e.g. the contents of twitter_entities) # overwrite self.value with a list of self.default_value and of length limit res = [ self.default_value ]*limit else: # found something useful in the iterable, either pad the list or truncate # to end up with something of the proper length current_length = len( iterable ) if current_length < limit: res = iterable + [ self.default_value for _ in range(limit - current_length) ] else: res = iterable[:limit] return res class _LimitedField(_Field): """ Takes JSON record (in python dict form) and optionally a maximum length (limit, with default length=5). Uses parent class _Field() to assign the appropriate value to self.value. When self.value is a list of dictionaries, inheriting from _LimitedField() class allows for the extraction and combination of an arbitrary number of fields within self.value into self.value_list. Ex: if your class would lead to having self.value = [ {'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6} ], and what you'd like is a list that looks like [ 1, 2, 4, 5 ], inheriting from _LimitedField() allows you to overwrite the fields list ( fields=["a", "b"] ) to obtain this result. Finally, self.value is set to a string representation of the final self.value_list. """ #TODO: is there a better way that this class and the fix_length() method in _Field class # could be combined? #TODO: set limit=None by default and just return as many as there are, otherwise (by specifying # limit), return a maximum of limit. # TODO: # - consolidate _LimitedField() & fix_length() if possible def __init__(self, json_record, limit=1): self.fields = None super( _LimitedField , self).__init__(json_record) # self.value is possibly a list of dicts for each activity media object if self.fields: # start with default list full of the default_values self.value_list = [ self.default_value ]*( len(self.fields)*limit ) if self.value != self.default_value: for i,x in enumerate(self.value): # iterate over the dicts in the list if i < limit: # ... up until you reach limit for j,y in enumerate(self.fields): # iterate over the dict keys self.value_list[ len( self.fields )*i + j ] = x[ self.fields[j] ] # finally, str-ify the list self.value = str( self.value_list ) class AcsCSV(object): """Base class for all delimited list objects. Basic delimited list utility functions""" def __init__(self, delim, options_keypath): self.delim = delim if delim == "": print >>sys.stderr, "Warning - Output has Null delimiter" self.rmchars = "\n\r {}".format(self.delim) self.options_keypath = options_keypath def string_hook(self, record_string, mode_dummy): """ Returns a file-like StringIO object built from the activity record in record_string. This is ultimately passed down to the FileInput.readline() method. The mode_dummy parameter is only included so the signature matches other hooks. """ return StringIO( record_string ) def file_reader(self, options_filename=None, json_string=None): """ Read arbitrary input file(s) or standard Python str. When passing file_reader() a JSON string, assign it to the json_string arg. Yields a tuple of (line number, record). """ line_number = 0 if json_string is not None: hook = self.string_hook options_filename = json_string else: hook = fileinput.hook_compressed for r in fileinput.FileInput(options_filename, openhook=hook): line_number += 1 try: recs = [json.loads(r.strip())] except ValueError: try: # maybe a missing line feed? recs = [json.loads(x) for x in r.strip().replace("}{", "}GNIP_SPLIT{") .split("GNIP_SPLIT")] except ValueError: sys.stderr.write("Invalid JSON record (%d) %s, skipping\n" %(line_number, r.strip())) continue for record in recs: if len(record) == 0: continue # hack: let the old source modules still have a self.cnt for error msgs self.cnt = line_number yield line_number, record def cleanField(self,f): """Clean fields of new lines and delmiter.""" res = INTERNAL_EMPTY_FIELD try: res = f.strip( ).replace("\n"," " ).replace("\r"," " ).replace(self.delim, " " ) except AttributeError: try: # odd edge case that f is a number # then can't call string functions float(f) res = str(f) except TypeError: pass return res def buildListString(self,l): """Generic list builder returns a string representation of list""" # unicode output of list (without u's) res = '[' for r in l: # handle the various types of lists we might see try: if isinstance(r, list): res += "'" + self.buildListString(r) + "'," elif isinstance(r, str) or isinstance(r, unicode): res += "'" + r + "'," else: res += "'" + str(r) + "'," except NameError: if isinstance(r, list): res += "'" + self.buildListString(r) + "'," elif isinstance(r, str): res += "'" + r + "'," else: res += "'" + str(r) + "'," if res.endswith(','): res = res[:-1] res += ']' return res def splitId(self, x, index=1): """Generic functions for splitting id parts""" tmp = x.split("/") if len(tmp) > index: return tmp[index] else: return x def asString(self, l, emptyField): """Returns a delimited list object as a properly delimited string.""" if l is None: return None for i, x in enumerate(l): if x == INTERNAL_EMPTY_FIELD: l[i] = emptyField return self.delim.join(l) def get_source_list(self, x): """Wrapper for the core activity parsing function.""" source_list = self.procRecordToList(x) if self.options_keypath: source_list.append(self.keyPath(x)) # ensure no pipes, newlines, etc return [ self.cleanField(x) for x in source_list ] def procRecord(self, x, emptyField="None"): return self.asString(self.get_source_list(x), emptyField) def asGeoJSON(self, x): """Get results as GeoJSON representation.""" record_list = self.procRecordToList(x) if self.__class__.__name__ == "TwacsCSV" and self.options_geo: if self.geoCoordsList is None: return lon_lat = self.geoCoordsList[::-1] elif self.__class__.__name__ == "FsqacsCSV" and self.options_geo: lon_lat = self.geo_coords_list else: return {"Error":"This publisher doesn't have geo"} return { "type": "Feature" , "geometry": { "type": "Point", "coordinates": lon_lat } , "properties": { "id": record_list[0] } } def keyPath(self,d): """Get a generic key path specified at run time. Consider using jq instead?""" #key_list = self.options_keypath.split(":") delim = ":" #print >> sys.stderr, "self.__class__ " + str(self.__class__) if self.__class__.__name__ == "NGacsCSV": delim = "," key_stack = self.options_keypath.split(delim) #print >> sys.stderr, "key_stack " + str(key_stack) x = d while len(key_stack) > 0: try: k = key_stack.pop(0) try: idx = int(k) except ValueError: # keys are ascii strings idx = str(k) x = x[idx] except (IndexError, TypeError, KeyError) as e: #sys.stderr.write("Keypath error at %s\n"%k) return "PATH_EMPTY" return unicode(x)
DrSkippy/Gnacs
acscsv/acscsv.py
Python
bsd-2-clause
13,140
#ifndef SD_SNAPSHOTITER_H_ #define SD_SNAPSHOTITER_H_ /* * sophia database * sphia.org * * Copyright (c) Dmitry Simonenko * BSD License */ typedef struct sdsnapshotiter sdsnapshotiter; struct sdsnapshotiter { sdsnapshot *s; sdsnapshotnode *n; uint32_t npos; } sspacked; static inline int sd_snapshotiter_open(ssiter *i, sr *r, sdsnapshot *s) { sdsnapshotiter *si = (sdsnapshotiter*)i->priv; si->s = s; si->n = NULL; si->npos = 0; if (ssunlikely(ss_bufused(&s->buf) < (int)sizeof(sdsnapshotheader))) goto error; sdsnapshotheader *h = (sdsnapshotheader*)s->buf.s; uint32_t crc = ss_crcs(r->crc, h, sizeof(*h), 0); if (h->crc != crc) goto error; if (ssunlikely((int)h->size != ss_bufused(&s->buf))) goto error; si->n = (sdsnapshotnode*)(s->buf.s + sizeof(sdsnapshotheader)); return 0; error: sr_malfunction(r->e, "%s", "snapshot file corrupted"); return -1; } static inline void sd_snapshotiter_close(ssiter *i ssunused) { } static inline int sd_snapshotiter_has(ssiter *i) { sdsnapshotiter *si = (sdsnapshotiter*)i->priv; return si->n != NULL; } static inline void* sd_snapshotiter_of(ssiter *i) { sdsnapshotiter *si = (sdsnapshotiter*)i->priv; if (ssunlikely(si->n == NULL)) return NULL; return si->n; } static inline void sd_snapshotiter_next(ssiter *i) { sdsnapshotiter *si = (sdsnapshotiter*)i->priv; if (ssunlikely(si->n == NULL)) return; si->npos++; sdsnapshotheader *h = (sdsnapshotheader*)si->s->buf.s; if (si->npos < h->nodes) { si->n = (sdsnapshotnode*)((char*)si->n + sizeof(sdsnapshotnode) + si->n->size); return; } si->n = NULL; } extern ssiterif sd_snapshotiter; #endif
mknight-tag/sophia
sophia/database/sd_snapshotiter.h
C
bsd-2-clause
1,639
module Propellor.Property.Tor where import Propellor import qualified Propellor.Property.File as File import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.Service as Service import Utility.FileMode import Utility.DataUnits import System.Posix.Files import Data.Char import Data.List type HiddenServiceName = String type NodeName = String -- | Sets up a tor bridge. (Not a relay or exit node.) -- -- Uses port 443 isBridge :: Property NoInfo isBridge = configured [ ("BridgeRelay", "1") , ("Exitpolicy", "reject *:*") , ("ORPort", "443") ] `describe` "tor bridge" `requires` server -- | Sets up a tor relay. -- -- Uses port 443 isRelay :: Property NoInfo isRelay = configured [ ("BridgeRelay", "0") , ("Exitpolicy", "reject *:*") , ("ORPort", "443") ] `describe` "tor relay" `requires` server -- | Makes the tor node be named, with a known private key. -- -- This can be moved to a different IP without needing to wait to -- accumulate trust. named :: NodeName -> Property HasInfo named n = configured [("Nickname", n')] `describe` ("tor node named " ++ n') `requires` torPrivKey (Context ("tor " ++ n)) where n' = saneNickname n torPrivKey :: Context -> Property HasInfo torPrivKey context = f `File.hasPrivContent` context `onChange` File.ownerGroup f user (userGroup user) -- install tor first, so the directory exists with right perms `requires` Apt.installed ["tor"] where f = "/var/lib/tor/keys/secret_id_key" -- | A tor server (bridge, relay, or exit) -- Don't use if you just want to run tor for personal use. server :: Property NoInfo server = configured [("SocksPort", "0")] `requires` Apt.installed ["tor", "ntp"] `describe` "tor server" -- | Specifies configuration settings. Any lines in the config file -- that set other values for the specified settings will be removed, -- while other settings are left as-is. Tor is restarted when -- configuration is changed. configured :: [(String, String)] -> Property NoInfo configured settings = File.fileProperty "tor configured" go mainConfig `onChange` restarted where ks = map fst settings go ls = sort $ map toconfig $ filter (\(k, _) -> k `notElem` ks) (map fromconfig ls) ++ settings toconfig (k, v) = k ++ " " ++ v fromconfig = separate (== ' ') data BwLimit = PerSecond String | PerDay String | PerMonth String -- | Limit incoming and outgoing traffic to the specified -- amount each. -- -- For example, PerSecond "30 kibibytes" is the minimum limit -- for a useful relay. bandwidthRate :: BwLimit -> Property NoInfo bandwidthRate (PerSecond s) = bandwidthRate' s 1 bandwidthRate (PerDay s) = bandwidthRate' s (24*60*60) bandwidthRate (PerMonth s) = bandwidthRate' s (31*24*60*60) bandwidthRate' :: String -> Integer -> Property NoInfo bandwidthRate' s divby = case readSize dataUnits s of Just sz -> let v = show (sz `div` divby) ++ " bytes" in configured [("BandwidthRate", v)] `describe` ("tor BandwidthRate " ++ v) Nothing -> property ("unable to parse " ++ s) noChange hiddenServiceAvailable :: HiddenServiceName -> Int -> Property NoInfo hiddenServiceAvailable hn port = hiddenServiceHostName prop where prop = configured [ ("HiddenServiceDir", varLib </> hn) , ("HiddenServicePort", unwords [show port, "127.0.0.1:" ++ show port]) ] `describe` "hidden service available" hiddenServiceHostName p = adjustPropertySatisfy p $ \satisfy -> do r <- satisfy h <- liftIO $ readFile (varLib </> hn </> "hostname") warningMessage $ unwords ["hidden service hostname:", h] return r hiddenService :: HiddenServiceName -> Int -> Property NoInfo hiddenService hn port = configured [ ("HiddenServiceDir", varLib </> hn) , ("HiddenServicePort", unwords [show port, "127.0.0.1:" ++ show port]) ] `describe` unwords ["hidden service available:", hn, show port] hiddenServiceData :: IsContext c => HiddenServiceName -> c -> Property HasInfo hiddenServiceData hn context = combineProperties desc [ installonion "hostname" , installonion "private_key" ] where desc = unwords ["hidden service data available in", varLib </> hn] installonion f = withPrivData (PrivFile $ varLib </> hn </> f) context $ \getcontent -> property desc $ getcontent $ install $ varLib </> hn </> f install f content = ifM (liftIO $ doesFileExist f) ( noChange , ensureProperties [ property desc $ makeChange $ do createDirectoryIfMissing True (takeDirectory f) writeFileProtected f content , File.mode (takeDirectory f) $ combineModes [ownerReadMode, ownerWriteMode, ownerExecuteMode] , File.ownerGroup (takeDirectory f) user (userGroup user) , File.ownerGroup f user (userGroup user) ] ) restarted :: Property NoInfo restarted = Service.restarted "tor" mainConfig :: FilePath mainConfig = "/etc/tor/torrc" varLib :: FilePath varLib = "/var/lib/tor" varRun :: FilePath varRun = "/var/run/tor" user :: User user = User "debian-tor" type NickName = String -- | Convert String to a valid tor NickName. saneNickname :: String -> NickName saneNickname s | null n = "unnamed" | otherwise = n where legal c = isNumber c || isAsciiUpper c || isAsciiLower c n = take 19 $ filter legal s
sjfloat/propellor
src/Propellor/Property/Tor.hs
Haskell
bsd-2-clause
5,177
# Weird Canada Player An HTML5/JavaScript audio player for [Weird Canada](http://weirdcanada.com/). Unlike most audio players it also has to parse Wordpress API data and pull out song metadata from the raw HTML, so it's kinda special. This may make it weird to use on other sites, but the parse module is easy to replace with something for your purpose. ## License The code is under BSD License. Do what you want, but it's not my fault if it breaks. **Except:** The Weird Canada logo is property of Weird Canada. Ask them.
sixohsix/weird-player
README.md
Markdown
bsd-2-clause
528
# **二叉树** # *** * 二叉树基本知识 * 二叉树链式实现 * 二叉搜索树 ## **1. 二叉树基本知识** ## 请参见./btree.md ## **2. 二叉树链式实现** ## > ### **2.1 思路** ### 1) 内部使用链表结构来存储二叉树 2) 内部的各种函数使用递归 3) 优点是实现简单 4) 缺点是大量使用了递归 5) 可以将递归转化为循环 > ### **2.2 实现** ### 请参见./btree-list/ ## **3. 二叉搜索树** ## > ### **3.1 思路** ### 1) 内部使用链表结构来存储二叉树 2) 每一个节点一个KEY值 3) 插入删除节点直接使用循环 4) 具体的请[参见](btree.md) > ### **3.2 实现** ### 请参见./btree-search/
ASMlover/study
data-structure/btree/README.md
Markdown
bsd-2-clause
738
void jpeg_zigzag_scalar(const uint16_t* in, uint16_t* out) { for (int i=0; i < 64; i++) { unsigned index = zigzag_shuffle[i]; out[i] = in[index]; } } void jpeg_zigzag_scalar_unrolled4(const uint16_t* in, uint16_t* out) { for (int i=0; i < 64; i += 4) { unsigned index0 = zigzag_shuffle[i + 0]; unsigned index1 = zigzag_shuffle[i + 1]; unsigned index2 = zigzag_shuffle[i + 2]; unsigned index3 = zigzag_shuffle[i + 3]; out[i + 0] = in[index0]; out[i + 1] = in[index1]; out[i + 2] = in[index2]; out[i + 3] = in[index3]; } }
WojciechMula/toys
avx512-jpeg-zizag/16bit-array/scalar.cpp
C++
bsd-2-clause
618
/* * Copyright (c) 2014, Linaro Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef IO_H #define IO_H static inline void write8(uint8_t val, vaddr_t addr) { *(volatile uint8_t *)addr = val; } static inline void write16(uint16_t val, vaddr_t addr) { *(volatile uint16_t *)addr = val; } static inline void write32(uint32_t val, vaddr_t addr) { *(volatile uint32_t *)addr = val; } static inline uint8_t read8(vaddr_t addr) { return *(volatile uint8_t *)addr; } static inline uint16_t read16(vaddr_t addr) { return *(volatile uint16_t *)addr; } static inline uint32_t read32(vaddr_t addr) { return *(volatile uint32_t *)addr; } #endif /*IO_H*/
jenswi-linaro/trusted_os
include/io.h
C
bsd-2-clause
1,954
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Wish.Commands { public class CommandLine { public string Text { get; set; } public CommandLine(string line) { Text = line; } public string Function { get { var m = Regex.Match(Text.Trim() + " ", @"^(.+?)(?:\s+|$)(.*)"); return m.Success ? m.Groups[1].Value.Trim() : String.Empty; } } public List<string> Arguments { get { var args = new List<string>(); var match = Regex.Match(Text.Trim() + " ", @"^(.+?)(?:\s+|$)(.*)"); var argsLine = match.Groups[2].Value.Trim(); string pattern; if(argsLine.Contains("'")) { pattern = @"[^\s']+|'[^']*'[^\s]+|'[^']*'"; } else { pattern = argsLine.Contains("\"") ? @"[^\s""]+|""[^""]*""[^\s]+|""[^""]*""" : @"(?<!\\)"".*?(?<!\\)""|[\S]+"; } var argMatches = Regex.Match(argsLine + " ", pattern); while (argMatches.Success) { var arg = Regex.Replace(argMatches.Value.Trim(), @"^""(.*?)""$", "$1"); args.Add(arg); argMatches = argMatches.NextMatch(); } return args; } } } }
tltjr/Wish
Wish.Commands/CommandLine.cs
C#
bsd-2-clause
1,559
from django.conf.urls import include, url from django.views.generic.base import RedirectView from cms.models import * from cms.views import show # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = [ url(r'^$', show,{'slug':"/%s"%settings.HOME_SLUG}, name='cms.home'), # contenido definido en home slug url(r'^%s/$'%settings.HOME_SLUG, RedirectView.as_view(url='/', permanent=False)), # redirect url(r'(?P<slug>.*)/$', show,name='cms.show'), ]
eliasfernandez/django-simplecms
cms/urls.py
Python
bsd-2-clause
537
import platform import pytest import math import numpy as np import dartpy as dart def test_solve_for_free_joint(): ''' Very simple test of InverseKinematics module, applied to a FreeJoint to ensure that the target is reachable ''' skel = dart.dynamics.Skeleton() [joint0, body0] = skel.createFreeJointAndBodyNodePair() ik = body0.getOrCreateIK() assert ik.isActive() tf = dart.math.Isometry3() tf.set_translation([0, 0, 0.8]) tf.set_rotation(dart.math.AngleAxis(math.pi / 8.0, [0, 1, 0]).to_rotation_matrix()) ik.getTarget().setTransform(tf) error_method = ik.getErrorMethod() assert error_method.getMethodName() == 'TaskSpaceRegion' [lb, ub] = error_method.getBounds() assert len(lb) is 6 assert len(ub) is 6 error_method.setBounds(np.ones(6) * -1e-8, np.ones(6) * 1e-8) [lb, ub] = error_method.getBounds() assert lb == pytest.approx(-1e-8) assert ub == pytest.approx(1e-8) solver = ik.getSolver() solver.setNumMaxIterations(100) prob = ik.getProblem() tf_actual = ik.getTarget().getTransform().matrix() tf_expected = body0.getTransform().matrix() assert not np.isclose(tf_actual, tf_expected).all() success = solver.solve() assert success tf_actual = ik.getTarget().getTransform().matrix() tf_expected = body0.getTransform().matrix() assert np.isclose(tf_actual, tf_expected).all() class FailingSolver(dart.optimizer.Solver): def __init__(self, constant): super(FailingSolver, self).__init__() self.constant = constant def solve(self): problem = self.getProblem() if problem is None: print('[FailingSolver::solve] Attempting to solve a nullptr problem! We will return false.') return False dim = problem.getDimension() wrong_solution = np.ones(dim) * self.constant problem.setOptimalSolution(wrong_solution) return False def getType(self): return 'FailingSolver' def clone(self): return FailingSolver(self.constant) def test_do_not_apply_solution_on_failure(): skel = dart.dynamics.Skeleton() [joint, body] = skel.createFreeJointAndBodyNodePair() ik = body.getIK(True) solver = FailingSolver(10) ik.setSolver(solver) dofs = skel.getNumDofs() skel.resetPositions() assert not ik.solveAndApply(allowIncompleteResult=False) assert np.isclose(skel.getPositions(), np.zeros(dofs)).all() assert not ik.solveAndApply(allowIncompleteResult=True) assert not np.isclose(skel.getPositions(), np.zeros(dofs)).all() if __name__ == "__main__": pytest.main()
dartsim/dart
python/tests/unit/dynamics/test_inverse_kinematics.py
Python
bsd-2-clause
2,669
class Orientdb < Formula desc "Graph database" homepage "https://orientdb.com/" url "https://orientdb.com/download.php?file=orientdb-community-importers-2.2.29.tar.gz" sha256 "ed6e65b18fed70ace3afa780a125100a19899e9b18f4d6e9bc1111e7ee88d752" bottle :unneeded depends_on :java => "1.6+" def install rm_rf Dir["{bin,benchmarks}/*.{bat,exe}"] chmod 0755, Dir["bin/*"] libexec.install Dir["*"] inreplace "#{libexec}/config/orientdb-server-config.xml", "</properties>", <<-EOS.undent <entry name="server.database.path" value="#{var}/db/orientdb" /> </properties> EOS inreplace "#{libexec}/config/orientdb-server-log.properties", "../log", "#{var}/log/orientdb" inreplace "#{libexec}/bin/orientdb.sh", "../log", "#{var}/log/orientdb" inreplace "#{libexec}/bin/server.sh", "ORIENTDB_PID=$ORIENTDB_HOME/bin", "ORIENTDB_PID=#{var}/run/orientdb" inreplace "#{libexec}/bin/shutdown.sh", "ORIENTDB_PID=$ORIENTDB_HOME/bin", "ORIENTDB_PID=#{var}/run/orientdb" inreplace "#{libexec}/bin/orientdb.sh", '"YOUR_ORIENTDB_INSTALLATION_PATH"', libexec inreplace "#{libexec}/bin/orientdb.sh", 'su $ORIENTDB_USER -c "cd \"$ORIENTDB_DIR/bin\";', "" inreplace "#{libexec}/bin/orientdb.sh", '&"', "&" bin.install_symlink "#{libexec}/bin/orientdb.sh" => "orientdb" bin.install_symlink "#{libexec}/bin/console.sh" => "orientdb-console" bin.install_symlink "#{libexec}/bin/gremlin.sh" => "orientdb-gremlin" end def post_install (var/"db/orientdb").mkpath (var/"run/orientdb").mkpath (var/"log/orientdb").mkpath touch "#{var}/log/orientdb/orientdb.err" touch "#{var}/log/orientdb/orientdb.log" ENV["ORIENTDB_ROOT_PASSWORD"] = "orientdb" system "#{bin}/orientdb", "stop" sleep 3 system "#{bin}/orientdb", "start" sleep 3 ensure system "#{bin}/orientdb", "stop" end def caveats; <<-EOS.undent The OrientDB root password was set to 'orientdb'. To reset it: https://orientdb.com/docs/2.2/Server-Security.html#restoring-the-servers-user-root EOS end plist_options :manual => "orientdb start" def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>Label</key> <string>homebrew.mxcl.orientdb</string> <key>ProgramArguments</key> <array> <string>/usr/local/opt/orientdb/libexec/bin/server.sh</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>/usr/local/var</string> <key>StandardErrorPath</key> <string>/usr/local/var/log/orientdb/serror.log</string> <key>StandardOutPath</key> <string>/usr/local/var/log/orientdb/sout.log</string> </dict> </plist> EOS end test do ENV["CONFIG_FILE"] = "#{testpath}/orientdb-server-config.xml" ENV["ORIENTDB_ROOT_PASSWORD"] = "orientdb" cp "#{libexec}/config/orientdb-server-config.xml", testpath inreplace "#{testpath}/orientdb-server-config.xml", "</properties>", " <entry name=\"server.database.path\" value=\"#{testpath}\" />\n </properties>" begin assert_match "OrientDB console v.#{version}", pipe_output("#{bin}/orientdb-console \"exit;\"") end end end
bfontaine/homebrew-core
Formula/orientdb.rb
Ruby
bsd-2-clause
3,539
#include "../include/L1Distance.h" using namespace std; using namespace cv; double L1Distance::calc(const ImageData &dat1, const ImageData &dat2){ return cv::norm(dat1.norm_hist, dat2.norm_hist, NORM_L1); } string L1Distance::get_class_name(){ return "L1Distance"; }
foobar999/Medienretrieval
src/L1Distance.cpp
C++
bsd-2-clause
278
import React from "react" import { makeStyles } from "@material-ui/core/styles" import Alert from "@material-ui/lab/Alert" import AvailableDisplay from "./AvailableDisplay" import { CartItem } from "common/types" const useStyles = makeStyles((theme) => ({ message: { padding: "0px", }, })) type Props = { cartData: CartItem inStock: boolean } /** * Availability handles the display to indicate a stock's current * inventory status. */ const Availability = ({ cartData, inStock }: Props) => { const classes = useStyles() return ( <React.Fragment> {inStock ? ( <AvailableDisplay cartData={cartData} /> ) : ( <Alert classes={{ message: classes.message }} icon={false} severity="error"> Currently unavailable at the DSC </Alert> )} </React.Fragment> ) } export default Availability
dictyBase/Dicty-Stock-Center
src/features/Stocks/Details/common/Availability.tsx
TypeScript
bsd-2-clause
894
''' Project: Farnsworth Author: Karandeep Singh Nagra ''' from django.contrib.auth.models import User, Group, Permission from django.core.urlresolvers import reverse from django.db import models from base.models import UserProfile class Thread(models.Model): ''' The Thread model. Used to group messages. ''' owner = models.ForeignKey( UserProfile, help_text="The user who started this thread.", ) subject = models.CharField( blank=False, null=False, max_length=254, help_text="Subject of this thread.", ) start_date = models.DateTimeField( auto_now_add=True, help_text="The date this thread was started.", ) change_date = models.DateTimeField( auto_now_add=True, help_text="The last time this thread was modified.", ) number_of_messages = models.PositiveSmallIntegerField( default=1, help_text="The number of messages in this thread.", ) active = models.BooleanField( default=True, help_text="Whether this thread is still active.", ) views = models.PositiveIntegerField( default=0, help_text="The number times this thread has been viewed.", ) followers = models.ManyToManyField( User, blank=True, null=True, related_name="following", help_text="Users following this thread", ) def __unicode__(self): return self.subject class Meta: ordering = ['-change_date'] def is_thread(self): return True def get_view_url(self): return reverse("threads:view_thread", kwargs={"pk": self.pk}) class Message(models.Model): ''' The Message model. Contains a body, owner, and post_date, referenced by thread. ''' body = models.TextField( blank=False, null=False, help_text="Body of this message.", ) owner = models.ForeignKey( UserProfile, help_text="The user who posted this message.", ) post_date = models.DateTimeField( auto_now_add=True, help_text="The date this message was posted.", ) thread = models.ForeignKey( Thread, help_text="The thread to which this message belongs.", ) edited = models.BooleanField( default=False, ) def __str__(self): return self.__unicode__() def __unicode__(self): return self.body class Meta: ordering = ['post_date'] def is_message(self): return True def pre_save_thread(sender, instance, **kwargs): thread = instance thread.number_of_messages = thread.message_set.count() def post_save_thread(sender, instance, created, **kwargs): thread = instance if not created and thread.number_of_messages == 0: thread.delete() def post_save_message(sender, instance, created, **kwargs): message = instance thread = message.thread if created: thread.change_date = message.post_date thread.save() def post_delete_message(sender, instance, **kwargs): message = instance message.thread.save() # Connect signals with their respective functions from above. # When a message is created, update that message's thread's change_date to the post_date of that message. models.signals.post_save.connect(post_save_message, sender=Message) models.signals.post_delete.connect(post_delete_message, sender=Message) models.signals.pre_save.connect(pre_save_thread, sender=Thread) models.signals.post_save.connect(post_save_thread, sender=Thread)
knagra/farnsworth
threads/models.py
Python
bsd-2-clause
3,639
/* * #%L * none: runtime code modification by annotation idioms. * %% * Copyright (C) 2014 Tobias Pietzsch. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package examples; import java.util.Random; import none.annotation.ByTypeOf; import none.annotation.Instantiate; /** * Example illustrating @Instantiate @ByTypeOf. * Try running it with {@code -javaagent:/path/to/none-1.0.0-SNAPSHOT.jar} and without. * * @author Tobias Pietzsch <tobias.pietzsch@gmail.com> */ public class Example1 { final int[] values; public Example1( final int size ) { values = new int[ size ]; final Random random = new Random(); for ( int i = 0; i < size; ++i ) values[ i ] = random.nextInt( Integer.MAX_VALUE ); } static interface F { void apply( int i ); } @Instantiate public void foreach( @ByTypeOf final F f ) { for ( final int i : values ) f.apply( i ); } static class Sum implements F { private long sum = 0; @Override public void apply( final int i ) { sum += i; } public long get() { return sum; } } static class Max implements F { private int max = 0; @Override public void apply( final int i ) { if ( i > max ) max = i; } public long get() { return max; } } static class Average implements F { private long sum = 0; private int n = 0; @Override public void apply( final int i ) { sum += i; ++n; } public long get() { return sum / n; } } public static void main( final String[] args ) { final Example1 example1 = new Example1( 10000000 ); long t0, t; for ( int i = 0; i < 3; ++i ) { t0 = System.currentTimeMillis(); final Sum sum = new Sum(); example1.foreach( sum ); t = System.currentTimeMillis() - t0; System.out.println( "Sum: " + t + "ms" ); t0 = System.currentTimeMillis(); final Max sum2 = new Max(); example1.foreach( sum2 ); t = System.currentTimeMillis() - t0; System.out.println( "Max: " + t + "ms" ); t0 = System.currentTimeMillis(); final Average sum3 = new Average(); example1.foreach( sum3 ); t = System.currentTimeMillis() - t0; System.out.println( "Average: " + t + "ms" ); } } }
tpietzsch/none
src/main/java/examples/Example1.java
Java
bsd-2-clause
3,460
/* Copyright (c) 2015, Florian Sittel (www.lettis.net) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tools.hpp" #include <cmath> #include <stdarg.h> namespace Clustering { namespace Tools { unsigned int min_multiplicator(unsigned int orig , unsigned int mult) { return (unsigned int) std::ceil(orig / ((float) mult)); }; void write_fes(std::string fname, std::vector<float> fes) { std::ofstream ofs(fname); if (ofs.fail()) { std::cerr << "error: cannot open file '" << fname << "'" << std::endl; exit(EXIT_FAILURE); } else { ofs << std::scientific; for (float f: fes) { ofs << f << "\n"; } } } void write_pops(std::string fname, std::vector<std::size_t> pops) { // technically the same ... write_clustered_trajectory(fname, pops); } std::vector<std::size_t> read_clustered_trajectory(std::string filename) { std::vector<std::size_t> traj; std::ifstream ifs(filename); if (ifs.fail()) { std::cerr << "error: cannot open file '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } else { while (ifs.good()) { std::size_t buf; ifs >> buf; if ( ! ifs.fail()) { traj.push_back(buf); } } } return traj; } void write_clustered_trajectory(std::string filename, std::vector<std::size_t> traj) { std::ofstream ofs(filename); if (ofs.fail()) { std::cerr << "error: cannot open file '" << filename << "'" << std::endl; exit(EXIT_FAILURE); } else { for (std::size_t c: traj) { ofs << c << "\n"; } } } //// from: https://github.com/lettis/Kubix /** behaves like sprintf(char*, ...), but with c++ strings and returns the result \param str pattern to be printed to \return resulting string The function internally calls sprintf, but converts the result to a c++ string and returns that one. Problems of memory allocation are taken care of automatically. */ std::string stringprintf(const std::string& str, ...) { unsigned int size = 256; va_list args; char* buf = (char*) malloc(size * sizeof(char)); va_start(args, str); while (size <= (unsigned int) vsnprintf(buf, size, str.c_str(), args)) { size *= 2; buf = (char*) realloc(buf, size * sizeof(char)); } va_end(args); std::string result(buf); free(buf); return result; } std::vector<float> read_free_energies(std::string filename) { return read_single_column<float>(filename); } std::pair<Neighborhood, Neighborhood> read_neighborhood(const std::string fname) { Neighborhood nh; Neighborhood nh_high_dens; std::ifstream ifs(fname); if (ifs.fail()) { std::cerr << "error: cannot open file '" << fname << "' for reading." << std::endl; exit(EXIT_FAILURE); } else { std::size_t i=0; while (ifs.good()) { std::size_t buf1; float buf2; std::size_t buf3; float buf4; ifs >> buf1; ifs >> buf2; ifs >> buf3; ifs >> buf4; if ( ! ifs.fail()) { nh[i] = std::pair<std::size_t, float>(buf1, buf2); nh_high_dens[i] = std::pair<std::size_t, float>(buf3, buf4); ++i; } } } return {nh, nh_high_dens}; } void write_neighborhood(const std::string fname, const Neighborhood& nh, const Neighborhood& nh_high_dens) { std::ofstream ofs(fname); auto p = nh.begin(); auto p_hd = nh_high_dens.begin(); while (p != nh.end() && p_hd != nh_high_dens.end()) { // first: key (not used) // second: neighbor // second.first: id; second.second: squared dist ofs << p->second.first << " " << p->second.second << " " << p_hd->second.first << " " << p_hd->second.second << "\n"; ++p; ++p_hd; } } std::map<std::size_t, std::size_t> microstate_populations(std::vector<std::size_t> traj) { std::map<std::size_t, std::size_t> populations; for (std::size_t state: traj) { if (populations.count(state) == 0) { populations[state] = 1; } else { ++populations[state]; } } return populations; } } // end namespace Tools } // end namespace Clustering
lettis/Clustering
tools.cpp
C++
bsd-2-clause
5,305
cask v1: 'easytether' do version :latest sha256 :no_check url 'http://www.mobile-stream.com/beta/easytether.dmg' name 'EasyTether' homepage 'http://www.mobile-stream.com/easytether/' license :commercial pkg 'EasyTetherUSBEthernet.pkg' uninstall pkgutil: 'com.mobile-stream.pkg.EasyTether' end
askl56/homebrew-cask
Casks/easytether.rb
Ruby
bsd-2-clause
312
require 'thor' module Rubex # Cli for rubex using Thor(http://whatisthor.com/) class Cli < Thor desc 'generate FILE', 'generates directory with name specified in the argument and creates an extconf.rb file which is required for C extensions' option :force, aliases: '-f', desc: 'replace existing files and directories' option :dir, aliases: '-d', desc: 'specify a directory for generating files', type: :string option :install, aliases: '-i', desc: 'automatically run install command after generating Makefile' option :debug, aliases: '-g', desc: 'enable debugging symbols when compiling with GCC' def generate(file) if (force = options[:force]) directory = (options[:dir] ? options[:dir].to_s : Dir.pwd) + "/#{Rubex::Compiler.extract_target_name(file)}" STDOUT.puts "Warning! you are about to replace contents in the directory '#{directory}', Are you sure? [Yn] " confirmation = STDIN.gets.chomp force = (confirmation == 'Y') end Rubex::Compiler.compile file, target_dir: options[:dir], force: force, make: options[:install], debug: options[:debug] end desc 'install PATH', 'run "make" utility to generate a shared object file required for C extensions' def install(path) Rubex::Compiler.run_make path end end end
v0dro/rubex
lib/rubex/cli.rb
Ruby
bsd-2-clause
1,402
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.io.findfile; import jodd.io.FileNameUtil; import jodd.util.ClassLoaderUtil; import jodd.util.InExRules; import jodd.util.StringUtil; import jodd.util.Wildcard; import jodd.util.ArraysUtil; import jodd.io.FileUtil; import jodd.io.StreamUtil; import jodd.io.ZipUtil; import java.net.URL; import java.util.zip.ZipFile; import java.util.zip.ZipEntry; import java.util.Enumeration; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.FileNotFoundException; import static jodd.util.InExRuleMatcher.WILDCARD_PATH_RULE_MATCHER; import static jodd.util.InExRuleMatcher.WILDCARD_RULE_MATCHER; /** * Simple utility that scans <code>URL</code>s for classes. * Its purpose is to help scanning class paths for some classes. * Content of Jar files is also examined. * <p> * Scanning starts in included all mode (blacklist mode) for both jars and lists. * User can set explicit excludes. Of course, mode can be changed. * <p> * All paths are matched using {@link Wildcard#matchPath(String, String) path-style} * wildcard matcher. All entries are matched using {@link Wildcard#match(CharSequence, CharSequence)} common-style} * wildcard matcher. * * @see ClassScanner */ public abstract class ClassFinder { private static final String CLASS_FILE_EXT = ".class"; private static final String JAR_FILE_EXT = ".jar"; // ---------------------------------------------------------------- excluded jars /** * Array of system jars that are excluded from the search. * By default, these paths are common for linux, windows and mac. */ protected static String[] systemJars = new String[] { "**/jre/lib/*.jar", "**/jre/lib/ext/*.jar", "**/Java/Extensions/*.jar", "**/Classes/*.jar" }; protected final InExRules<String, String> rulesJars = createJarRules(); /** * Creates JAR rules. By default, excludes all system jars. */ protected InExRules<String, String> createJarRules() { InExRules<String, String> rulesJars = new InExRules<>(WILDCARD_PATH_RULE_MATCHER); for (String systemJar : systemJars) { rulesJars.exclude(systemJar); } return rulesJars; } /** * Returns system jars. */ public static String[] getSystemJars() { return systemJars; } /** * Specify excluded jars. */ public void setExcludedJars(String... excludedJars) { for (String excludedJar : excludedJars) { rulesJars.exclude(excludedJar); } } /** * Specify included jars. */ public void setIncludedJars(String... includedJars) { for (String includedJar : includedJars) { rulesJars.include(includedJar); } } /** * Sets white/black list mode for jars. */ public void setIncludeAllJars(boolean blacklist) { if (blacklist) { rulesJars.blacklist(); } else { rulesJars.whitelist(); } } /** * Sets white/black list mode for jars. */ public void setExcludeAllJars(boolean whitelist) { if (whitelist) { rulesJars.whitelist(); } else { rulesJars.blacklist(); } } // ---------------------------------------------------------------- included entries protected final InExRules<String, String> rulesEntries = createEntriesRules(); protected InExRules<String, String> createEntriesRules() { return new InExRules<>(WILDCARD_RULE_MATCHER); } /** * Sets included set of names that will be considered during configuration. * @see jodd.util.InExRules */ public void setIncludedEntries(String... includedEntries) { for (String includedEntry : includedEntries) { rulesEntries.include(includedEntry); } } /** * Sets white/black list mode for entries. */ public void setIncludeAllEntries(boolean blacklist) { if (blacklist) { rulesEntries.blacklist(); } else { rulesEntries.whitelist(); } } /** * Sets white/black list mode for entries. */ public void setExcludeAllEntries(boolean whitelist) { if (whitelist) { rulesEntries.whitelist(); } else { rulesEntries.blacklist(); } } /** * Sets excluded names that narrows included set of packages. * @see jodd.util.InExRules */ public void setExcludedEntries(String... excludedEntries) { for (String excludedEntry : excludedEntries) { rulesEntries.exclude(excludedEntry); } } // ---------------------------------------------------------------- implementation /** * If set to <code>true</code> all files will be scanned and not only classes. */ protected boolean includeResources; /** * If set to <code>true</code> exceptions for entry scans are ignored. */ protected boolean ignoreException; public boolean isIncludeResources() { return includeResources; } public void setIncludeResources(boolean includeResources) { this.includeResources = includeResources; } public boolean isIgnoreException() { return ignoreException; } /** * Sets if exceptions during scanning process should be ignored or not. */ public void setIgnoreException(boolean ignoreException) { this.ignoreException = ignoreException; } // ---------------------------------------------------------------- scan /** * Scans several URLs. If (#ignoreExceptions} is set, exceptions * per one URL will be ignored and loops continues. */ protected void scanUrls(URL... urls) { for (URL path : urls) { scanUrl(path); } } /** * Scans single URL for classes and jar files. * Callback {@link #onEntry(EntryData)} is called on * each class name. */ protected void scanUrl(URL url) { File file = FileUtil.toFile(url); if (file == null) { if (!ignoreException) { throw new FindFileException("URL is not a valid file: " + url); } } scanPath(file); } protected void scanPaths(File... paths) { for (File path : paths) { scanPath(path); } } protected void scanPaths(String... paths) { for (String path : paths) { scanPath(path); } } protected void scanPath(String path) { scanPath(new File(path)); } /** * Returns <code>true</code> if some JAR file has to be accepted. */ protected boolean acceptJar(File jarFile) { String path = jarFile.getAbsolutePath(); path = FileNameUtil.separatorsToUnix(path); return rulesJars.match(path); } /** * Scans single path. */ protected void scanPath(File file) { String path = file.getAbsolutePath(); if (StringUtil.endsWithIgnoreCase(path, JAR_FILE_EXT)) { if (!acceptJar(file)) { return; } scanJarFile(file); } else if (file.isDirectory()) { scanClassPath(file); } } // ---------------------------------------------------------------- internal /** * Scans classes inside single JAR archive. Archive is scanned as a zip file. * @see #onEntry(EntryData) */ protected void scanJarFile(File file) { ZipFile zipFile; try { zipFile = new ZipFile(file); } catch (IOException ioex) { if (!ignoreException) { throw new FindFileException("Invalid zip: " + file.getName(), ioex); } return; } Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); String zipEntryName = zipEntry.getName(); try { if (StringUtil.endsWithIgnoreCase(zipEntryName, CLASS_FILE_EXT)) { String entryName = prepareEntryName(zipEntryName, true); EntryData entryData = new EntryData(entryName, zipFile, zipEntry); try { scanEntry(entryData); } finally { entryData.closeInputStreamIfOpen(); } } else if (includeResources) { String entryName = prepareEntryName(zipEntryName, false); EntryData entryData = new EntryData(entryName, zipFile, zipEntry); try { scanEntry(entryData); } finally { entryData.closeInputStreamIfOpen(); } } } catch (RuntimeException rex) { if (!ignoreException) { ZipUtil.close(zipFile); throw rex; } } } ZipUtil.close(zipFile); } /** * Scans single classpath directory. * @see #onEntry(EntryData) */ protected void scanClassPath(File root) { String rootPath = root.getAbsolutePath(); if (!rootPath.endsWith(File.separator)) { rootPath += File.separatorChar; } FindFile ff = new FindFile().includeDirs(false).recursive(true).searchPath(rootPath); File file; while ((file = ff.nextFile()) != null) { String filePath = file.getAbsolutePath(); try { if (StringUtil.endsWithIgnoreCase(filePath, CLASS_FILE_EXT)) { scanClassFile(filePath, rootPath, file, true); } else if (includeResources) { scanClassFile(filePath, rootPath, file, false); } } catch (RuntimeException rex) { if (!ignoreException) { throw rex; } } } } protected void scanClassFile(String filePath, String rootPath, File file, boolean isClass) { if (StringUtil.startsWithIgnoreCase(filePath, rootPath)) { String entryName = prepareEntryName(filePath.substring(rootPath.length()), isClass); EntryData entryData = new EntryData(entryName, file); try { scanEntry(entryData); } finally { entryData.closeInputStreamIfOpen(); } } } /** * Prepares resource and class names. For classes, it strips '.class' from the end and converts * all (back)slashes to dots. For resources, it replaces all backslashes to slashes. */ protected String prepareEntryName(String name, boolean isClass) { String entryName = name; if (isClass) { entryName = name.substring(0, name.length() - 6); // 6 == ".class".length() entryName = StringUtil.replaceChar(entryName, '/', '.'); entryName = StringUtil.replaceChar(entryName, '\\', '.'); } else { entryName = '/' + StringUtil.replaceChar(entryName, '\\', '/'); } return entryName; } /** * Returns <code>true</code> if some entry name has to be accepted. * @see #prepareEntryName(String, boolean) * @see #scanEntry(EntryData) */ protected boolean acceptEntry(String entryName) { return rulesEntries.match(entryName); } /** * If entry name is {@link #acceptEntry(String) accepted} invokes {@link #onEntry(EntryData)} a callback}. */ protected void scanEntry(EntryData entryData) { if (!acceptEntry(entryData.getName())) { return; } try { onEntry(entryData); } catch (Exception ex) { throw new FindFileException("Scan entry error: " + entryData, ex); } } // ---------------------------------------------------------------- callback /** * Called during classpath scanning when class or resource is found. * <ul> * <li>Class name is java-alike class name (pk1.pk2.class) that may be immediately used * for dynamic loading.</li> * <li>Resource name starts with '\' and represents either jar path (\pk1/pk2/res) or relative file path (\pk1\pk2\res).</li> * </ul> * * <code>InputStream</code> is provided by InputStreamProvider and opened lazy. * Once opened, input stream doesn't have to be closed - this is done by this class anyway. */ protected abstract void onEntry(EntryData entryData) throws Exception; // ---------------------------------------------------------------- utilities /** * Returns type signature bytes used for searching in class file. */ protected byte[] getTypeSignatureBytes(Class type) { String name = 'L' + type.getName().replace('.', '/') + ';'; return name.getBytes(); } /** * Returns <code>true</code> if class contains {@link #getTypeSignatureBytes(Class) type signature}. * It searches the class content for bytecode signature. This is the fastest way of finding if come * class uses some type. Please note that if signature exists it still doesn't means that class uses * it in expected way, therefore, class should be loaded to complete the scan. */ protected boolean isTypeSignatureInUse(InputStream inputStream, byte[] bytes) { try { byte[] data = StreamUtil.readBytes(inputStream); int index = ArraysUtil.indexOf(data, bytes); return index != -1; } catch (IOException ioex) { throw new FindFileException("Read error", ioex); } } // ---------------------------------------------------------------- class loading /** * Loads class by its name. If {@link #ignoreException} is set, * no exception is thrown, but <code>null</code> is returned. */ protected Class loadClass(String className) throws ClassNotFoundException { try { return ClassLoaderUtil.loadClass(className); } catch (ClassNotFoundException cnfex) { if (ignoreException) { return null; } throw cnfex; } catch (Error error) { if (ignoreException) { return null; } throw error; } } // ---------------------------------------------------------------- provider /** * Provides input stream on demand. Input stream is not open until get(). */ protected static class EntryData { private final File file; private final ZipFile zipFile; private final ZipEntry zipEntry; private final String name; EntryData(String name, ZipFile zipFile, ZipEntry zipEntry) { this.name = name; this.zipFile = zipFile; this.zipEntry = zipEntry; this.file = null; inputStream = null; } EntryData(String name, File file) { this.name = name; this.file = file; this.zipEntry = null; this.zipFile = null; inputStream = null; } private InputStream inputStream; /** * Returns entry name. */ public String getName() { return name; } /** * Returns <code>true</code> if archive. */ public boolean isArchive() { return zipFile != null; } /** * Returns archive name or <code>null</code> if entry is not inside archived file. */ public String getArchiveName() { if (zipFile != null) { return zipFile.getName(); } return null; } /** * Opens zip entry or plain file and returns its input stream. */ public InputStream openInputStream() { if (zipFile != null) { try { inputStream = zipFile.getInputStream(zipEntry); return inputStream; } catch (IOException ioex) { throw new FindFileException("Input stream error: '" + zipFile.getName() + "', entry: '" + zipEntry.getName() + "'." , ioex); } } try { inputStream = new FileInputStream(file); return inputStream; } catch (FileNotFoundException fnfex) { throw new FindFileException("Unable to open: " + file.getAbsolutePath(), fnfex); } } /** * Closes input stream if opened. */ void closeInputStreamIfOpen() { if (inputStream == null) { return; } StreamUtil.close(inputStream); inputStream = null; } @Override public String toString() { return "EntryData{" + name + '\'' +'}'; } } }
vilmospapp/jodd
jodd-core/src/main/java/jodd/io/findfile/ClassFinder.java
Java
bsd-2-clause
15,922