text
stringlengths
2
99k
meta
dict
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <div xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields" xmlns:form="urn:jsptagdir:/WEB-INF/tags/form" xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"> <jsp:directive.page contentType="text/html;charset=UTF-8"/> <jsp:output omit-xml-declaration="yes"/> <form:update id="fu_nl_bzk_brp_model_data_kern_Persnation" modelAttribute="persnation" path="/persnations" versionField="none" z="5liNQkcBRBpy8paMn/gEr+PcZwo="> <field:simple field="hisPersnations" id="c_nl_bzk_brp_model_data_kern_Persnation_hisPersnations" messageCode="entity_reference_not_managed" messageCodeAttribute="His Persnation" z="Xw3n2x9wAF52zf1Sgt+NUpYWzRA="/> <field:select field="nation" id="c_nl_bzk_brp_model_data_kern_Persnation_nation" itemValue="id" items="${nations}" path="/nations" z="id/2jU+WcoF9Z1Ip7yhRxcjxPOE="/> <field:select field="pers" id="c_nl_bzk_brp_model_data_kern_Persnation_pers" itemValue="id" items="${perses}" path="/perses" z="+e5x89MSwTWaPlaDKKGEEpyPMaA="/> <field:select field="rdnverk" id="c_nl_bzk_brp_model_data_kern_Persnation_rdnverk" itemValue="id" items="${rdnverknlnations}" path="/rdnverknlnations" z="qOnXouRuJi1NeBdMTg+/WnjljTE="/> <field:select field="rdnverlies" id="c_nl_bzk_brp_model_data_kern_Persnation_rdnverlies" itemValue="id" items="${rdnverliesnlnations}" path="/rdnverliesnlnations" z="taN8bsqLNr0uSw83Hn8nxp7bMTg="/> <field:input field="persnationstatushis" id="c_nl_bzk_brp_model_data_kern_Persnation_persnationstatushis" required="true" z="VDOhR0WfPDeVH0S0I/5VNMg/K0U="/> </form:update> </div>
{ "pile_set_name": "Github" }
<?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"> <!-- # # 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. # --> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>org.apache.cordova.$(PRODUCT_NAME:rfc1034identifier)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>BNDL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> </dict> </plist>
{ "pile_set_name": "Github" }
#!/bin/sh # Copyright (C) The Arvados Authors. All rights reserved. # # SPDX-License-Identifier: AGPL-3.0 # This code runs after package variable definitions and step2.sh. set -e DATABASE_READY=1 APPLICATION_READY=1 if [ -s "$HOME/.rvm/scripts/rvm" ] || [ -s "/usr/local/rvm/scripts/rvm" ]; then COMMAND_PREFIX="/usr/local/rvm/bin/rvm-exec default" else COMMAND_PREFIX= fi report_not_ready() { local ready_flag="$1"; shift local config_file="$1"; shift if [ "1" != "$ready_flag" ]; then cat >&2 <<EOF PLEASE NOTE: The $PACKAGE_NAME package was not configured completely because $config_file needs some tweaking. Please refer to the documentation at <$DOC_URL> for more details. When $(basename "$config_file") has been modified, reconfigure or reinstall this package. EOF fi } report_web_service_warning() { local warning="$1"; shift cat >&2 <<EOF WARNING: $warning. To override, set the WEB_SERVICE environment variable to the name of the service hosting the Rails server. For Debian-based systems, then reconfigure this package with dpkg-reconfigure. For RPM-based systems, then reinstall this package. EOF } run_and_report() { # Usage: run_and_report ACTION_MSG CMD # This is the usual wrapper that prints ACTION_MSG, runs CMD, then writes # a message about whether CMD succeeded or failed. Returns the exit code # of CMD. local action_message="$1"; shift local retcode=0 echo -n "$action_message..." if "$@"; then echo " done." else retcode=$? echo " failed." fi return $retcode } setup_confdirs() { for confdir in "$@"; do if [ ! -d "$confdir" ]; then install -d -g "$WWW_OWNER" -m 0750 "$confdir" fi done } setup_conffile() { # Usage: setup_conffile CONFFILE_PATH [SOURCE_PATH] # Both paths are relative to RELEASE_CONFIG_PATH. # This function will try to safely ensure that a symbolic link for # the configuration file points from RELEASE_CONFIG_PATH to CONFIG_PATH. # If SOURCE_PATH is given, this function will try to install that file as # the configuration file in CONFIG_PATH, and return 1 if the file in # CONFIG_PATH is unmodified from the source. local conffile_relpath="$1"; shift local conffile_source="$1" local release_conffile="$RELEASE_CONFIG_PATH/$conffile_relpath" local etc_conffile="$CONFIG_PATH/$(basename "$conffile_relpath")" # Note that -h can return true and -e will return false simultaneously # when the target is a dangling symlink. We're okay with that outcome, # so check -h first. if [ ! -h "$release_conffile" ]; then if [ ! -e "$release_conffile" ]; then ln -s "$etc_conffile" "$release_conffile" # If there's a config file in /var/www identical to the one in /etc, # overwrite it with a symlink after porting its permissions. elif cmp --quiet "$release_conffile" "$etc_conffile"; then local ownership="$(stat -c "%u:%g" "$release_conffile")" local owning_group="${ownership#*:}" if [ 0 != "$owning_group" ]; then chgrp "$owning_group" "$CONFIG_PATH" /etc/arvados fi chown "$ownership" "$etc_conffile" chmod --reference="$release_conffile" "$etc_conffile" ln --force -s "$etc_conffile" "$release_conffile" fi fi if [ -n "$conffile_source" ]; then if [ ! -e "$etc_conffile" ]; then install -g "$WWW_OWNER" -m 0640 \ "$RELEASE_CONFIG_PATH/$conffile_source" "$etc_conffile" return 1 # Even if $etc_conffile already existed, it might be unmodified from # the source. This is especially likely when a user installs, updates # database.yml, then reconfigures before they update application.yml. # Use cmp to be sure whether $etc_conffile is modified. elif cmp --quiet "$RELEASE_CONFIG_PATH/$conffile_source" "$etc_conffile"; then return 1 fi fi } prepare_database() { DB_MIGRATE_STATUS=`$COMMAND_PREFIX bundle exec rake db:migrate:status 2>&1 || true` if echo "$DB_MIGRATE_STATUS" | grep -qF 'Schema migrations table does not exist yet.'; then # The database exists, but the migrations table doesn't. run_and_report "Setting up database" $COMMAND_PREFIX bundle exec \ rake "$RAILSPKG_DATABASE_LOAD_TASK" db:seed elif echo "$DB_MIGRATE_STATUS" | grep -q '^database: '; then run_and_report "Running db:migrate" \ $COMMAND_PREFIX bundle exec rake db:migrate elif echo "$DB_MIGRATE_STATUS" | grep -q 'database .* does not exist'; then if ! run_and_report "Running db:setup" \ $COMMAND_PREFIX bundle exec rake db:setup 2>/dev/null; then echo "Warning: unable to set up database." >&2 DATABASE_READY=0 fi else echo "Warning: Database is not ready to set up. Skipping database setup." >&2 DATABASE_READY=0 fi } configure_version() { if [ -n "$WEB_SERVICE" ]; then SERVICE_MANAGER=$(guess_service_manager) elif WEB_SERVICE=$(list_services_systemd | grep -E '^(nginx|httpd)'); then SERVICE_MANAGER=systemd elif WEB_SERVICE=$(list_services_service \ | grep -Eo '\b(nginx|httpd)[^[:space:]]*'); then SERVICE_MANAGER=service fi if [ -z "$WEB_SERVICE" ]; then report_web_service_warning "Web service (Nginx or Apache) not found" elif [ "$WEB_SERVICE" != "$(echo "$WEB_SERVICE" | head -n 1)" ]; then WEB_SERVICE=$(echo "$WEB_SERVICE" | head -n 1) report_web_service_warning \ "Multiple web services found. Choosing the first one ($WEB_SERVICE)" fi if [ -e /etc/redhat-release ]; then # Recognize any service that starts with "nginx"; e.g., nginx16. if [ "$WEB_SERVICE" != "${WEB_SERVICE#nginx}" ]; then WWW_OWNER=nginx else WWW_OWNER=apache fi else # Assume we're on a Debian-based system for now. # Both Apache and Nginx run as www-data by default. WWW_OWNER=www-data fi echo echo "Assumption: $WEB_SERVICE is configured to serve Rails from" echo " $RELEASE_PATH" echo "Assumption: $WEB_SERVICE and passenger run as $WWW_OWNER" echo echo -n "Creating symlinks to configuration in $CONFIG_PATH ..." setup_confdirs /etc/arvados "$CONFIG_PATH" setup_conffile environments/production.rb environments/production.rb.example \ || true setup_extra_conffiles echo "... done." # Before we do anything else, make sure some directories and files are in place if [ ! -e $SHARED_PATH/log ]; then mkdir -p $SHARED_PATH/log; fi if [ ! -e $RELEASE_PATH/tmp ]; then mkdir -p $RELEASE_PATH/tmp; fi if [ ! -e $RELEASE_PATH/log ]; then ln -s $SHARED_PATH/log $RELEASE_PATH/log; fi if [ ! -e $SHARED_PATH/log/production.log ]; then touch $SHARED_PATH/log/production.log; fi cd "$RELEASE_PATH" export RAILS_ENV=production if ! $COMMAND_PREFIX bundle --version >/dev/null; then run_and_report "Installing bundler" $COMMAND_PREFIX gem install bundler --version 1.17.3 fi run_and_report "Running bundle install" \ $COMMAND_PREFIX bundle install --path $SHARED_PATH/vendor_bundle --local --quiet echo -n "Ensuring directory and file permissions ..." # Ensure correct ownership of a few files chown "$WWW_OWNER:" $RELEASE_PATH/config/environment.rb chown "$WWW_OWNER:" $RELEASE_PATH/config.ru chown "$WWW_OWNER:" $RELEASE_PATH/Gemfile.lock chown -R "$WWW_OWNER:" $RELEASE_PATH/tmp || true chown -R "$WWW_OWNER:" $SHARED_PATH/log case "$RAILSPKG_DATABASE_LOAD_TASK" in db:schema:load) chown "$WWW_OWNER:" $RELEASE_PATH/db/schema.rb ;; db:structure:load) chown "$WWW_OWNER:" $RELEASE_PATH/db/structure.sql ;; esac chmod 644 $SHARED_PATH/log/* chmod -R 2775 $RELEASE_PATH/tmp || true echo "... done." if [ -n "$RAILSPKG_DATABASE_LOAD_TASK" ]; then prepare_database fi if [ 11 = "$RAILSPKG_SUPPORTS_CONFIG_CHECK$APPLICATION_READY" ]; then run_and_report "Checking configuration for completeness" \ $COMMAND_PREFIX bundle exec rake config:check || APPLICATION_READY=0 fi # precompile assets; thankfully this does not take long if [ "$APPLICATION_READY" = "1" ]; then run_and_report "Precompiling assets" \ $COMMAND_PREFIX bundle exec rake assets:precompile -q -s 2>/dev/null \ || APPLICATION_READY=0 else echo "Precompiling assets... skipped." fi chown -R "$WWW_OWNER:" $RELEASE_PATH/tmp setup_before_nginx_restart if [ -n "$SERVICE_MANAGER" ]; then service_command "$SERVICE_MANAGER" restart "$WEB_SERVICE" fi } if [ "$1" = configure ]; then # This is a debian-based system configure_version elif [ "$1" = "0" ] || [ "$1" = "1" ] || [ "$1" = "2" ]; then # This is an rpm-based system configure_version fi if printf '%s\n' "$CONFIG_PATH" | grep -Fqe "sso"; then report_not_ready "$APPLICATION_READY" "$CONFIG_PATH/application.yml" report_not_ready "$DATABASE_READY" "$CONFIG_PATH/database.yml" else report_not_ready "$APPLICATION_READY" "/etc/arvados/config.yml" fi
{ "pile_set_name": "Github" }
/* * Copyright 2014 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.gradle.api.reporting.dependencies.internal; import com.googlecode.jatl.Html; import org.gradle.api.Project; import org.gradle.api.Transformer; import org.gradle.reporting.HtmlPageBuilder; import org.gradle.reporting.ReportRenderer; import org.gradle.util.GradleVersion; import java.io.IOException; import java.io.Writer; import java.util.Date; public class ProjectPageRenderer extends ReportRenderer<Project, HtmlPageBuilder<Writer>> { private final Transformer<String, Project> namingScheme; public ProjectPageRenderer(Transformer<String, Project> namingScheme) { this.namingScheme = namingScheme; } @Override public void render(final Project project, final HtmlPageBuilder<Writer> builder) throws IOException { final String baseCssLink = builder.requireResource(getClass().getResource("/org/gradle/reporting/base-style.css")); final String cssLink = builder.requireResource(getClass().getResource(getReportResourcePath("style.css"))); final String jqueryLink = builder.requireResource(getClass().getResource("/org/gradle/reporting/jquery.min-1.11.0.js")); final String jtreeLink = builder.requireResource(getClass().getResource(getReportResourcePath("jquery.jstree.js"))); final String scriptLink = builder.requireResource(getClass().getResource(getReportResourcePath("script.js"))); builder.requireResource(getClass().getResource(getReportResourcePath("tree.css"))); builder.requireResource(getClass().getResource(getReportResourcePath("d.gif"))); builder.requireResource(getClass().getResource(getReportResourcePath("d.png"))); builder.requireResource(getClass().getResource(getReportResourcePath("throbber.gif"))); new Html(builder.getOutput()) {{ html(); head(); meta().httpEquiv("Content-Type").content("text/html; charset=utf-8"); meta().httpEquiv("x-ua-compatible").content("IE=edge"); link().rel("stylesheet").type("text/css").href(baseCssLink).end(); link().rel("stylesheet").type("text/css").href(cssLink).end(); script().src(jqueryLink).charset("utf-8").end(); script().src(jtreeLink).charset("utf-8").end(); script().src(namingScheme.transform(project)).charset("utf-8").end(); script().src(scriptLink).charset("utf-8").end(); title().text("Dependency reports").end(); end(); body(); div().id("content"); h1().text("Dependency Report").end(); div().classAttr("breadcrumbs"); a().href("index.html").text("Projects").end(); text(" > "); span().id("projectBreacrumb").end(); end(); div().id("insight").end(); div().id("dependencies").end(); div().id("footer"); p(); text("Generated by "); a().href("http://www.gradle.org").text(GradleVersion.current().toString()).end(); text(String.format(" at %s", builder.formatDate(new Date()))); end(); end(); end(); end(); endAll(); }}; } private String getReportResourcePath(String fileName) { return "/org/gradle/api/tasks/diagnostics/htmldependencyreport/" + fileName; } }
{ "pile_set_name": "Github" }
package com.geekq.miaosha.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import java.util.Map; @Configuration public class MQConfig { /** * /usr/sbin/rabbitmq-plugins enable rabbitmq_management * mq页面 */ public static final String MIAOSHA_QUEUE = "miaosha.queue"; public static final String EXCHANGE_TOPIC = "exchange_topic"; public static final String MIAOSHA_MESSAGE = "miaosha_mess"; public static final String MIAOSHATEST = "miaoshatest"; public static final String QUEUE = "queue"; public static final String TOPIC_QUEUE1 = "topic.queue1"; public static final String TOPIC_QUEUE2 = "topic.queue2"; public static final String HEADER_QUEUE = "header.queue"; public static final String TOPIC_EXCHANGE = "topicExchage"; public static final String FANOUT_EXCHANGE = "fanoutxchage"; public static final String HEADERS_EXCHANGE = "headersExchage"; /** * Direct模式 交换机Exchange * */ @Bean public Queue queue() { return new Queue(QUEUE, true); } /** * Topic模式 交换机Exchange * */ @Bean public Queue topicQueue1() { return new Queue(TOPIC_QUEUE1, true); } @Bean public Queue topicQueue2() { return new Queue(TOPIC_QUEUE2, true); } @Bean public TopicExchange topicExchage(){ return new TopicExchange(TOPIC_EXCHANGE); } @Bean public Binding topicBinding1() { return BindingBuilder.bind(topicQueue1()).to(topicExchage()).with("topic.key1"); } @Bean public Binding topicBinding2() { return BindingBuilder.bind(topicQueue2()).to(topicExchage()).with("topic.#"); } /** * Fanout模式 交换机Exchange * */ @Bean public FanoutExchange fanoutExchage(){ return new FanoutExchange(FANOUT_EXCHANGE); } @Bean public Binding FanoutBinding1() { return BindingBuilder.bind(topicQueue1()).to(fanoutExchage()); } @Bean public Binding FanoutBinding2() { return BindingBuilder.bind(topicQueue2()).to(fanoutExchage()); } /** * Header模式 交换机Exchange * */ @Bean public HeadersExchange headersExchage(){ return new HeadersExchange(HEADERS_EXCHANGE); } @Bean public Queue headerQueue1() { return new Queue(HEADER_QUEUE, true); } @Bean public Binding headerBinding() { Map<String, Object> map = new HashMap<String, Object>(); map.put("header1", "value1"); map.put("header2", "value2"); return BindingBuilder.bind(headerQueue1()).to(headersExchage()).whereAll(map).match(); } }
{ "pile_set_name": "Github" }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="QueueView.xaml.cs" company="HandBrake Project (http://handbrake.fr)"> // This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace HandBrakeWPF.Views { using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using HandBrakeWPF.Services.Queue.Model; using HandBrakeWPF.ViewModels; public partial class QueueView : Window { private QueueTask mouseActiveQueueTask; public QueueView() { this.InitializeComponent(); this.SizeChanged += this.QueueView_SizeChanged; } private void QueueView_SizeChanged(object sender, SizeChangedEventArgs e) { // Make the view adaptive. if (e.WidthChanged) { int queueSizeLimit = 745; this.summaryTabControl.Visibility = this.ActualWidth < queueSizeLimit ? Visibility.Collapsed : Visibility.Visible; this.leftTabPanel.Width = this.ActualWidth < queueSizeLimit ? new GridLength(this.ActualWidth - 10, GridUnitType.Star) : new GridLength(3, GridUnitType.Star); this.leftTabPanel.MaxWidth = this.ActualWidth < queueSizeLimit ? 750 : 650; } } private void ContextMenu_OnOpened(object sender, RoutedEventArgs e) { ContextMenu menu = sender as ContextMenu; this.mouseActiveQueueTask = null; if (menu != null) { Point p = Mouse.GetPosition(this); HitTestResult result = VisualTreeHelper.HitTest(this, p); if (result != null) { ListBoxItem listBoxItem = FindParent<ListBoxItem>(result.VisualHit); if (listBoxItem != null) { this.mouseActiveQueueTask = listBoxItem.DataContext as QueueTask; } } } // Handle menu state this.ResetMenuItem.Header = this.queueJobs.SelectedItems.Count > 1 ? Properties.Resources.QueueView_ResetSelectedJobs : Properties.Resources.QueueView_Reset; if (this.queueJobs.SelectedItems.Count > 1) { this.ResetMenuItem.IsEnabled = false; foreach (QueueTask task in this.queueJobs.SelectedItems) { if (task.Status == QueueItemStatus.Error || task.Status == QueueItemStatus.Completed) { this.ResetMenuItem.IsEnabled = true; break; } } } else { var activeQueueTask = this.mouseActiveQueueTask; if (activeQueueTask != null && (activeQueueTask.Status == QueueItemStatus.Error || activeQueueTask.Status == QueueItemStatus.Completed)) { this.ResetMenuItem.IsEnabled = true; } else { this.ResetMenuItem.IsEnabled = false; } } this.DeleteMenuItem.Header = this.queueJobs.SelectedItems.Count > 1 ? Properties.Resources.QueueView_DeleteSelected : Properties.Resources.QueueView_Delete; this.DeleteMenuItem.IsEnabled = this.mouseActiveQueueTask != null || this.queueJobs.SelectedItems.Count >= 1; this.EditMenuItem.IsEnabled = this.mouseActiveQueueTask != null && this.queueJobs.SelectedItems.Count == 1; this.openSourceDir.IsEnabled = this.mouseActiveQueueTask != null && this.queueJobs.SelectedItems.Count == 1; this.openDestDir.IsEnabled = this.mouseActiveQueueTask != null && this.queueJobs.SelectedItems.Count == 1; } private static T FindParent<T>(DependencyObject from) where T : class { DependencyObject parent = VisualTreeHelper.GetParent(from); T result = null; if (parent is T) { result = parent as T; } else if (parent != null) { result = FindParent<T>(parent); } return result; } private void OpenSourceDir_OnClick(object sender, RoutedEventArgs e) { ((QueueViewModel)this.DataContext).OpenSourceDirectory(this.mouseActiveQueueTask); } private void OpenDestDir_OnClick(object sender, RoutedEventArgs e) { ((QueueViewModel)this.DataContext).OpenDestinationDirectory(this.mouseActiveQueueTask); } private void QueueOptionsDropButton_OnClick(object sender, RoutedEventArgs e) { var button = sender as FrameworkElement; if (button != null && button.ContextMenu != null) { button.ContextMenu.PlacementTarget = button; button.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom; button.ContextMenu.IsOpen = true; } } private void QueueItem_Delete(object sender, RoutedEventArgs e) { if (this.queueJobs.SelectedItems.Count > 1) { ((QueueViewModel)this.DataContext).RemoveSelectedJobs(); } else { ((QueueViewModel)this.DataContext).RemoveJob(this.mouseActiveQueueTask); } } private void QueueItem_Retry(object sender, RoutedEventArgs e) { if (this.queueJobs.SelectedItems.Count > 1) { ((QueueViewModel)this.DataContext).ResetSelectedJobs(); } else { ((QueueViewModel)this.DataContext).RetryJob(this.mouseActiveQueueTask); } } private void QueueItem_Edit(object sender, RoutedEventArgs e) { ((QueueViewModel)this.DataContext).EditJob(this.mouseActiveQueueTask); } private void QueueDeleteJob_OnClick(object sender, RoutedEventArgs e) { Button button = sender as Button; QueueTask task = button?.DataContext as QueueTask; if (task != null) { ((QueueViewModel)this.DataContext).RemoveJob(task); } } } }
{ "pile_set_name": "Github" }
/* This code is derived from jgit (http://eclipse.org/jgit). Copyright owners are documented in jgit's IP log. This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0 which accompanies this distribution, is reproduced below, and is available at http://www.eclipse.org/org/documents/edl-v10.php All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - 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. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ using NGit; using NGit.Junit; using NGit.Merge; using NGit.Notes; using NGit.Revwalk; using Sharpen; namespace NGit.Notes { [NUnit.Framework.TestFixture] public class NoteMapMergerTest : RepositoryTestCase { private TestRepository<Repository> tr; private ObjectReader reader; private ObjectInserter inserter; private NoteMap noRoot; private NoteMap empty; private NoteMap map_a; private NoteMap map_a_b; private RevBlob noteAId; private string noteAContent; private RevBlob noteABlob; private RevBlob noteBId; private string noteBContent; private RevBlob noteBBlob; private RevCommit sampleTree_a; private RevCommit sampleTree_a_b; /// <exception cref="System.Exception"></exception> [NUnit.Framework.SetUp] public override void SetUp() { base.SetUp(); tr = new TestRepository<Repository>(db); reader = db.NewObjectReader(); inserter = db.NewObjectInserter(); noRoot = NoteMap.NewMap(null, reader); empty = NoteMap.NewEmptyMap(); noteAId = tr.Blob("a"); noteAContent = "noteAContent"; noteABlob = tr.Blob(noteAContent); sampleTree_a = tr.Commit().Add(noteAId.Name, noteABlob).Create(); tr.ParseBody(sampleTree_a); map_a = NoteMap.Read(reader, sampleTree_a); noteBId = tr.Blob("b"); noteBContent = "noteBContent"; noteBBlob = tr.Blob(noteBContent); sampleTree_a_b = tr.Commit().Add(noteAId.Name, noteABlob).Add(noteBId.Name, noteBBlob ).Create(); tr.ParseBody(sampleTree_a_b); map_a_b = NoteMap.Read(reader, sampleTree_a_b); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.TearDown] public override void TearDown() { reader.Release(); inserter.Release(); base.TearDown(); } /// <exception cref="System.IO.IOException"></exception> [NUnit.Framework.Test] public virtual void TestNoChange() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap result; NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(noRoot, noRoot, noRoot ))); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(empty, empty, empty))); result = merger.Merge(map_a, map_a, map_a); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestOursEqualsTheirs() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap result; NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(empty, noRoot, noRoot) )); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a, noRoot, noRoot) )); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(noRoot, empty, empty)) ); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a, empty, empty))); result = merger.Merge(noRoot, map_a, map_a); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); result = merger.Merge(empty, map_a, map_a); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); result = merger.Merge(map_a_b, map_a, map_a); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); result = merger.Merge(map_a, map_a_b, map_a_b); NUnit.Framework.Assert.AreEqual(2, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(noteBBlob, result.Get(noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestBaseEqualsOurs() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap result; NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(noRoot, noRoot, empty) )); result = merger.Merge(noRoot, noRoot, map_a); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(empty, empty, noRoot)) ); result = merger.Merge(empty, empty, map_a); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a, map_a, noRoot)) ); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a, map_a, empty))); result = merger.Merge(map_a, map_a, map_a_b); NUnit.Framework.Assert.AreEqual(2, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(noteBBlob, result.Get(noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestBaseEqualsTheirs() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap result; NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(noRoot, empty, noRoot) )); result = merger.Merge(noRoot, map_a, noRoot); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(empty, noRoot, empty)) ); result = merger.Merge(empty, map_a, empty); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a, noRoot, map_a)) ); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a, empty, map_a))); result = merger.Merge(map_a, map_a_b, map_a); NUnit.Framework.Assert.AreEqual(2, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(noteBBlob, result.Get(noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestAddDifferentNotes() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap result; NoteMap map_a_c = NoteMap.Read(reader, sampleTree_a); RevBlob noteCId = tr.Blob("c"); RevBlob noteCBlob = tr.Blob("noteCContent"); map_a_c.Set(noteCId, noteCBlob); map_a_c.WriteTree(inserter); result = merger.Merge(map_a, map_a_b, map_a_c); NUnit.Framework.Assert.AreEqual(3, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(noteBBlob, result.Get(noteBId)); NUnit.Framework.Assert.AreEqual(noteCBlob, result.Get(noteCId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestAddSameNoteDifferentContent() { NoteMapMerger merger = new NoteMapMerger(db, new DefaultNoteMerger(), null); NoteMap result; NoteMap map_a_b1 = NoteMap.Read(reader, sampleTree_a); string noteBContent1 = noteBContent + "change"; RevBlob noteBBlob1 = tr.Blob(noteBContent1); map_a_b1.Set(noteBId, noteBBlob1); map_a_b1.WriteTree(inserter); result = merger.Merge(map_a, map_a_b, map_a_b1); NUnit.Framework.Assert.AreEqual(2, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(tr.Blob(noteBContent + noteBContent1), result.Get (noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestEditSameNoteDifferentContent() { NoteMapMerger merger = new NoteMapMerger(db, new DefaultNoteMerger(), null); NoteMap result; NoteMap map_a1 = NoteMap.Read(reader, sampleTree_a); string noteAContent1 = noteAContent + "change1"; RevBlob noteABlob1 = tr.Blob(noteAContent1); map_a1.Set(noteAId, noteABlob1); map_a1.WriteTree(inserter); NoteMap map_a2 = NoteMap.Read(reader, sampleTree_a); string noteAContent2 = noteAContent + "change2"; RevBlob noteABlob2 = tr.Blob(noteAContent2); map_a2.Set(noteAId, noteABlob2); map_a2.WriteTree(inserter); result = merger.Merge(map_a, map_a1, map_a2); NUnit.Framework.Assert.AreEqual(1, CountNotes(result)); NUnit.Framework.Assert.AreEqual(tr.Blob(noteAContent1 + noteAContent2), result.Get (noteAId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestEditDifferentNotes() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap result; NoteMap map_a1_b = NoteMap.Read(reader, sampleTree_a_b); string noteAContent1 = noteAContent + "change"; RevBlob noteABlob1 = tr.Blob(noteAContent1); map_a1_b.Set(noteAId, noteABlob1); map_a1_b.WriteTree(inserter); NoteMap map_a_b1 = NoteMap.Read(reader, sampleTree_a_b); string noteBContent1 = noteBContent + "change"; RevBlob noteBBlob1 = tr.Blob(noteBContent1); map_a_b1.Set(noteBId, noteBBlob1); map_a_b1.WriteTree(inserter); result = merger.Merge(map_a_b, map_a1_b, map_a_b1); NUnit.Framework.Assert.AreEqual(2, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob1, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(noteBBlob1, result.Get(noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestDeleteDifferentNotes() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap map_b = NoteMap.Read(reader, sampleTree_a_b); map_b.Set(noteAId, null); // delete note a map_b.WriteTree(inserter); NUnit.Framework.Assert.AreEqual(0, CountNotes(merger.Merge(map_a_b, map_a, map_b) )); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestEditDeleteConflict() { NoteMapMerger merger = new NoteMapMerger(db, new DefaultNoteMerger(), null); NoteMap result; NoteMap map_a_b1 = NoteMap.Read(reader, sampleTree_a_b); string noteBContent1 = noteBContent + "change"; RevBlob noteBBlob1 = tr.Blob(noteBContent1); map_a_b1.Set(noteBId, noteBBlob1); map_a_b1.WriteTree(inserter); result = merger.Merge(map_a_b, map_a_b1, map_a); NUnit.Framework.Assert.AreEqual(2, CountNotes(result)); NUnit.Framework.Assert.AreEqual(noteABlob, result.Get(noteAId)); NUnit.Framework.Assert.AreEqual(noteBBlob1, result.Get(noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestLargeTreesWithoutConflict() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap map1 = CreateLargeNoteMap("note_1_", "content_1_", 300, 0); NoteMap map2 = CreateLargeNoteMap("note_2_", "content_2_", 300, 0); NoteMap result = merger.Merge(empty, map1, map2); NUnit.Framework.Assert.AreEqual(600, CountNotes(result)); // check a few random notes NUnit.Framework.Assert.AreEqual(tr.Blob("content_1_59"), result.Get(tr.Blob("note_1_59" ))); NUnit.Framework.Assert.AreEqual(tr.Blob("content_2_10"), result.Get(tr.Blob("note_2_10" ))); NUnit.Framework.Assert.AreEqual(tr.Blob("content_2_99"), result.Get(tr.Blob("note_2_99" ))); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestLargeTreesWithConflict() { NoteMapMerger merger = new NoteMapMerger(db, new DefaultNoteMerger(), null); NoteMap largeTree1 = CreateLargeNoteMap("note_1_", "content_1_", 300, 0); NoteMap largeTree2 = CreateLargeNoteMap("note_1_", "content_2_", 300, 0); NoteMap result = merger.Merge(empty, largeTree1, largeTree2); NUnit.Framework.Assert.AreEqual(300, CountNotes(result)); // check a few random notes NUnit.Framework.Assert.AreEqual(tr.Blob("content_1_59content_2_59"), result.Get(tr .Blob("note_1_59"))); NUnit.Framework.Assert.AreEqual(tr.Blob("content_1_10content_2_10"), result.Get(tr .Blob("note_1_10"))); NUnit.Framework.Assert.AreEqual(tr.Blob("content_1_99content_2_99"), result.Get(tr .Blob("note_1_99"))); } /// <exception cref="System.Exception"></exception> private NoteMap CreateLargeNoteMap(string noteNamePrefix, string noteContentPrefix , int notesCount, int firstIndex) { NoteMap result = NoteMap.NewEmptyMap(); for (int i = 0; i < notesCount; i++) { result.Set(tr.Blob(noteNamePrefix + (firstIndex + i)), tr.Blob(noteContentPrefix + (firstIndex + i))); } result.WriteTree(inserter); return result; } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestFanoutAndLeafWithoutConflict() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap largeTree = CreateLargeNoteMap("note_1_", "content_1_", 300, 0); NoteMap result = merger.Merge(map_a, map_a_b, largeTree); NUnit.Framework.Assert.AreEqual(301, CountNotes(result)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestFanoutAndLeafWitConflict() { NoteMapMerger merger = new NoteMapMerger(db, new DefaultNoteMerger(), null); NoteMap largeTree_b1 = CreateLargeNoteMap("note_1_", "content_1_", 300, 0); string noteBContent1 = noteBContent + "change"; largeTree_b1.Set(noteBId, tr.Blob(noteBContent1)); largeTree_b1.WriteTree(inserter); NoteMap result = merger.Merge(map_a, map_a_b, largeTree_b1); NUnit.Framework.Assert.AreEqual(301, CountNotes(result)); NUnit.Framework.Assert.AreEqual(tr.Blob(noteBContent + noteBContent1), result.Get (noteBId)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestCollapseFanoutAfterMerge() { NoteMapMerger merger = new NoteMapMerger(db, null, null); NoteMap largeTree = CreateLargeNoteMap("note_", "content_", 257, 0); NUnit.Framework.Assert.IsTrue(largeTree.GetRoot() is FanoutBucket); NoteMap deleteFirstHundredNotes = CreateLargeNoteMap("note_", "content_", 157, 100 ); NoteMap deleteLastHundredNotes = CreateLargeNoteMap("note_", "content_", 157, 0); NoteMap result = merger.Merge(largeTree, deleteFirstHundredNotes, deleteLastHundredNotes ); NUnit.Framework.Assert.AreEqual(57, CountNotes(result)); NUnit.Framework.Assert.IsTrue(result.GetRoot() is LeafBucket); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestNonNotesWithoutNonNoteConflict() { NoteMapMerger merger = new NoteMapMerger(db, null, MergeStrategy.RESOLVE); RevCommit treeWithNonNotes = tr.Commit().Add(noteAId.Name, noteABlob).Add("a.txt" , tr.Blob("content of a.txt")).Create(); // this is a note // this is a non-note tr.ParseBody(treeWithNonNotes); NoteMap @base = NoteMap.Read(reader, treeWithNonNotes); treeWithNonNotes = tr.Commit().Add(noteAId.Name, noteABlob).Add("a.txt", tr.Blob( "content of a.txt")).Add("b.txt", tr.Blob("content of b.txt")).Create(); tr.ParseBody(treeWithNonNotes); NoteMap ours = NoteMap.Read(reader, treeWithNonNotes); treeWithNonNotes = tr.Commit().Add(noteAId.Name, noteABlob).Add("a.txt", tr.Blob( "content of a.txt")).Add("c.txt", tr.Blob("content of c.txt")).Create(); tr.ParseBody(treeWithNonNotes); NoteMap theirs = NoteMap.Read(reader, treeWithNonNotes); NoteMap result = merger.Merge(@base, ours, theirs); NUnit.Framework.Assert.AreEqual(3, CountNonNotes(result)); } /// <exception cref="System.Exception"></exception> [NUnit.Framework.Test] public virtual void TestNonNotesWithNonNoteConflict() { NoteMapMerger merger = new NoteMapMerger(db, null, MergeStrategy.RESOLVE); RevCommit treeWithNonNotes = tr.Commit().Add(noteAId.Name, noteABlob).Add("a.txt" , tr.Blob("content of a.txt")).Create(); // this is a note // this is a non-note tr.ParseBody(treeWithNonNotes); NoteMap @base = NoteMap.Read(reader, treeWithNonNotes); treeWithNonNotes = tr.Commit().Add(noteAId.Name, noteABlob).Add("a.txt", tr.Blob( "change 1")).Create(); tr.ParseBody(treeWithNonNotes); NoteMap ours = NoteMap.Read(reader, treeWithNonNotes); treeWithNonNotes = tr.Commit().Add(noteAId.Name, noteABlob).Add("a.txt", tr.Blob( "change 2")).Create(); tr.ParseBody(treeWithNonNotes); NoteMap theirs = NoteMap.Read(reader, treeWithNonNotes); try { merger.Merge(@base, ours, theirs); NUnit.Framework.Assert.Fail("NotesMergeConflictException was expected"); } catch (NotesMergeConflictException) { } } // expected private static int CountNotes(NoteMap map) { int c = 0; Iterator<Note> it = map.Iterator(); while (it.HasNext()) { it.Next(); c++; } return c; } private static int CountNonNotes(NoteMap map) { int c = 0; NonNoteEntry nonNotes = map.GetRoot().nonNotes; while (nonNotes != null) { c++; nonNotes = nonNotes.next; } return c; } } }
{ "pile_set_name": "Github" }
<queries language="cpp"/>
{ "pile_set_name": "Github" }
require_relative '../../spec_helper' require_relative 'shared/store' describe "ENV.store" do it_behaves_like :env_store, :store end
{ "pile_set_name": "Github" }
# Turkish stopwords from LUCENE-559 # merged with the list from "Information Retrieval on Turkish Texts" # (http://www.users.muohio.edu/canf/papers/JASIST2008offPrint.pdf) acaba altmış altı ama ancak arada aslında ayrıca bana bazı belki ben benden beni benim beri beş bile bin bir birçok biri birkaç birkez birşey birşeyi biz bize bizden bizi bizim böyle böylece bu buna bunda bundan bunlar bunları bunların bunu bunun burada çok çünkü da daha dahi de defa değil diğer diye doksan dokuz dolayı dolayısıyla dört edecek eden ederek edilecek ediliyor edilmesi ediyor eğer elli en etmesi etti ettiği ettiğini gibi göre halen hangi hatta hem henüz hep hepsi her herhangi herkesin hiç hiçbir için iki ile ilgili ise işte itibaren itibariyle kadar karşın katrilyon kendi kendilerine kendini kendisi kendisine kendisini kez ki kim kimden kime kimi kimse kırk milyar milyon mu mü mı nasıl ne neden nedenle nerde nerede nereye niye niçin o olan olarak oldu olduğu olduğunu olduklarını olmadı olmadığı olmak olması olmayan olmaz olsa olsun olup olur olursa oluyor on ona ondan onlar onlardan onları onların onu onun otuz oysa öyle pek rağmen sadece sanki sekiz seksen sen senden seni senin siz sizden sizi sizin şey şeyden şeyi şeyler şöyle şu şuna şunda şundan şunları şunu tarafından trilyon tüm üç üzere var vardı ve veya ya yani yapacak yapılan yapılması yapıyor yapmak yaptı yaptığı yaptığını yaptıkları yedi yerine yetmiş yine yirmi yoksa yüz zaten
{ "pile_set_name": "Github" }
/****************************************************************************** * * Copyright 2014 Paphus Solutions Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * 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.botlibre.thought; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import org.botlibre.api.knowledge.MemoryEventListener; import org.botlibre.api.knowledge.Network; import org.botlibre.api.knowledge.Vertex; import org.botlibre.knowledge.Primitive; import org.botlibre.thought.BasicThought; /** * A sub-conscious thought that processes active memory in the background. */ public abstract class SubconsciousThought extends BasicThought { public int threshold = 200; public int delay = 0; protected Queue<Vertex> activeMemoryBackLog = new ConcurrentLinkedQueue<Vertex>(); protected MemoryEventListener listener; public SubconsciousThought() { } /** * Determine if the thought should first wait for conscious thoughts to process the input. */ public boolean isConsciousProcessingRequired() { return false; } /** * Add a listener to the memory to be notified when new active memory. */ @Override public void awake() { super.awake(); this.listener = new MemoryEventListener() { public void addActiveMemory(Vertex vertex) { if (isStopped || !isEnabled || !bot.mind().isConscious()) { return; } if (getActiveMemoryBackLog().size() > SubconsciousThought.this.threshold) { bot.log(this, "Subconscious backlog threshold reached, clearing backlog", Level.WARNING); getActiveMemoryBackLog().clear(); } getActiveMemoryBackLog().add(vertex); } }; this.bot.memory().addListener(this.listener); } public void stop() { super.stop(); this.bot.memory().removeListener(this.listener); } /** * Analyze the active memory. * Output the active article to the senses. */ @Override public void think() { if (this.isStopped || !this.isEnabled || !this.bot.mind().isConscious()) { getActiveMemoryBackLog().clear(); return; } Vertex vertex = getActiveMemoryBackLog().poll(); if (vertex != null) { try { Thread.sleep(this.delay); if (this.isStopped || !this.isEnabled || !this.bot.mind().isConscious()) { getActiveMemoryBackLog().clear(); return; } Network memory = this.bot.memory().newMemory(); vertex = memory.createVertex(vertex); int abort = 0; if (isConsciousProcessingRequired()) { while ((abort < 20) && !vertex.hasRelationship(Primitive.CONTEXT)) { Thread.sleep(1000); if (this.isStopped || !this.isEnabled || !this.bot.mind().isConscious()) { getActiveMemoryBackLog().clear(); return; } memory = this.bot.memory().newMemory(); vertex = memory.createVertex(vertex); abort++; } } if (abort < 20) { boolean commit = processInput(vertex, memory); if (commit && isEnabled() && !isStopped() && this.bot.mind().isConscious()) { memory.save(); } } } catch (Exception failed) { log(failed); } } } /** * Process the active memory in the isolated memory in the background. * Return if memory should be saved, or discarded. */ public abstract boolean processInput(Vertex vertex, Network network); /** * Thoughts can be conscious or sub-conscious. * A conscious thought is run by the mind single threaded with exclusive access to the short term memory. * A sub-conscious thought is run concurrently, and must run in its own memory space. */ @Override public boolean isConscious() { return false; } public Queue<Vertex> getActiveMemoryBackLog() { return activeMemoryBackLog; } public void setActiveMemoryBackLog(Queue<Vertex> activeMemoryBackLog) { this.activeMemoryBackLog = activeMemoryBackLog; } }
{ "pile_set_name": "Github" }
{ "_from": "verror@1.10.0", "_id": "verror@1.10.0", "_inBundle": false, "_integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", "_location": "/verror", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "verror@1.10.0", "name": "verror", "escapedName": "verror", "rawSpec": "1.10.0", "saveSpec": null, "fetchSpec": "1.10.0" }, "_requiredBy": [ "/jsprim" ], "_resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", "_shasum": "3a105ca17053af55d6e270c1f8288682e18da400", "_spec": "verror@1.10.0", "_where": "/Users/rebecca/code/npm/node_modules/jsprim", "bugs": { "url": "https://github.com/davepacheco/node-verror/issues" }, "bundleDependencies": false, "dependencies": { "assert-plus": "^1.0.0", "core-util-is": "1.0.2", "extsprintf": "^1.2.0" }, "deprecated": false, "description": "richer JavaScript errors", "engines": [ "node >=0.6.0" ], "homepage": "https://github.com/davepacheco/node-verror#readme", "license": "MIT", "main": "./lib/verror.js", "name": "verror", "repository": { "type": "git", "url": "git://github.com/davepacheco/node-verror.git" }, "scripts": { "test": "make test" }, "version": "1.10.0" }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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. */ namespace TencentCloud.Ssl.V20191205.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class UploadCertificateRequest : AbstractModel { /// <summary> /// 证书公钥。 /// </summary> [JsonProperty("CertificatePublicKey")] public string CertificatePublicKey{ get; set; } /// <summary> /// 私钥内容,证书类型为 SVR 时必填,为 CA 时可不填。 /// </summary> [JsonProperty("CertificatePrivateKey")] public string CertificatePrivateKey{ get; set; } /// <summary> /// 证书类型,默认 SVR。CA = 客户端证书,SVR = 服务器证书。 /// </summary> [JsonProperty("CertificateType")] public string CertificateType{ get; set; } /// <summary> /// 备注名称。 /// </summary> [JsonProperty("Alias")] public string Alias{ get; set; } /// <summary> /// 项目 ID。 /// </summary> [JsonProperty("ProjectId")] public ulong? ProjectId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "CertificatePublicKey", this.CertificatePublicKey); this.SetParamSimple(map, prefix + "CertificatePrivateKey", this.CertificatePrivateKey); this.SetParamSimple(map, prefix + "CertificateType", this.CertificateType); this.SetParamSimple(map, prefix + "Alias", this.Alias); this.SetParamSimple(map, prefix + "ProjectId", this.ProjectId); } } }
{ "pile_set_name": "Github" }
Search = function(data, input, result) { this.data = data; this.$input = $(input); this.$result = $(result); this.$current = null; this.$view = this.$result.parent(); this.searcher = new Searcher(data.index); this.init(); } Search.prototype = $.extend({}, Navigation, new function() { var suid = 1; this.init = function() { var _this = this; var observer = function() { _this.search(_this.$input[0].value); }; this.$input.keyup(observer); this.$input.click(observer); // mac's clear field this.searcher.ready(function(results, isLast) { _this.addResults(results, isLast); }) this.initNavigation(); this.setNavigationActive(false); } this.search = function(value, selectFirstMatch) { value = jQuery.trim(value).toLowerCase(); if (value) { this.setNavigationActive(true); } else { this.setNavigationActive(false); } if (value == '') { this.lastQuery = value; this.$result.empty(); this.setNavigationActive(false); } else if (value != this.lastQuery) { this.lastQuery = value; this.firstRun = true; this.searcher.find(value); } } this.addResults = function(results, isLast) { var target = this.$result.get(0); if (this.firstRun && (results.length > 0 || isLast)) { this.$current = null; this.$result.empty(); } for (var i=0, l = results.length; i < l; i++) { target.appendChild(this.renderItem.call(this, results[i])); }; if (this.firstRun && results.length > 0) { this.firstRun = false; this.$current = $(target.firstChild); this.$current.addClass('current'); } if (jQuery.browser.msie) this.$element[0].className += ''; } this.move = function(isDown) { if (!this.$current) return; var $next = this.$current[isDown ? 'next' : 'prev'](); if ($next.length) { this.$current.removeClass('current'); $next.addClass('current'); this.scrollIntoView($next[0], this.$view[0]); this.$current = $next; } return true; } this.hlt = function(html) { return this.escapeHTML(html). replace(/\u0001/g, '<em>'). replace(/\u0002/g, '</em>'); } this.escapeHTML = function(html) { return html.replace(/[&<>]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); } });
{ "pile_set_name": "Github" }
<?php /* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_AdExchangeBuyer_Creative extends Google_Collection { protected $collection_key = 'vendorType'; protected $internal_gapi_mappings = array( "hTMLSnippet" => "HTMLSnippet", ); public $hTMLSnippet; public $accountId; public $adChoicesDestinationUrl; public $advertiserId; public $advertiserName; public $agencyId; public $apiUploadTimestamp; public $attribute; public $buyerCreativeId; public $clickThroughUrl; protected $correctionsType = 'Google_Service_AdExchangeBuyer_CreativeCorrections'; protected $correctionsDataType = 'array'; public $dealsStatus; protected $filteringReasonsType = 'Google_Service_AdExchangeBuyer_CreativeFilteringReasons'; protected $filteringReasonsDataType = ''; public $height; public $impressionTrackingUrl; public $kind; protected $nativeAdType = 'Google_Service_AdExchangeBuyer_CreativeNativeAd'; protected $nativeAdDataType = ''; public $openAuctionStatus; public $productCategories; public $restrictedCategories; public $sensitiveCategories; protected $servingRestrictionsType = 'Google_Service_AdExchangeBuyer_CreativeServingRestrictions'; protected $servingRestrictionsDataType = 'array'; public $vendorType; public $version; public $videoURL; public $width; public function setHTMLSnippet($hTMLSnippet) { $this->hTMLSnippet = $hTMLSnippet; } public function getHTMLSnippet() { return $this->hTMLSnippet; } public function setAccountId($accountId) { $this->accountId = $accountId; } public function getAccountId() { return $this->accountId; } public function setAdChoicesDestinationUrl($adChoicesDestinationUrl) { $this->adChoicesDestinationUrl = $adChoicesDestinationUrl; } public function getAdChoicesDestinationUrl() { return $this->adChoicesDestinationUrl; } public function setAdvertiserId($advertiserId) { $this->advertiserId = $advertiserId; } public function getAdvertiserId() { return $this->advertiserId; } public function setAdvertiserName($advertiserName) { $this->advertiserName = $advertiserName; } public function getAdvertiserName() { return $this->advertiserName; } public function setAgencyId($agencyId) { $this->agencyId = $agencyId; } public function getAgencyId() { return $this->agencyId; } public function setApiUploadTimestamp($apiUploadTimestamp) { $this->apiUploadTimestamp = $apiUploadTimestamp; } public function getApiUploadTimestamp() { return $this->apiUploadTimestamp; } public function setAttribute($attribute) { $this->attribute = $attribute; } public function getAttribute() { return $this->attribute; } public function setBuyerCreativeId($buyerCreativeId) { $this->buyerCreativeId = $buyerCreativeId; } public function getBuyerCreativeId() { return $this->buyerCreativeId; } public function setClickThroughUrl($clickThroughUrl) { $this->clickThroughUrl = $clickThroughUrl; } public function getClickThroughUrl() { return $this->clickThroughUrl; } public function setCorrections($corrections) { $this->corrections = $corrections; } public function getCorrections() { return $this->corrections; } public function setDealsStatus($dealsStatus) { $this->dealsStatus = $dealsStatus; } public function getDealsStatus() { return $this->dealsStatus; } public function setFilteringReasons(Google_Service_AdExchangeBuyer_CreativeFilteringReasons $filteringReasons) { $this->filteringReasons = $filteringReasons; } public function getFilteringReasons() { return $this->filteringReasons; } public function setHeight($height) { $this->height = $height; } public function getHeight() { return $this->height; } public function setImpressionTrackingUrl($impressionTrackingUrl) { $this->impressionTrackingUrl = $impressionTrackingUrl; } public function getImpressionTrackingUrl() { return $this->impressionTrackingUrl; } public function setKind($kind) { $this->kind = $kind; } public function getKind() { return $this->kind; } public function setNativeAd(Google_Service_AdExchangeBuyer_CreativeNativeAd $nativeAd) { $this->nativeAd = $nativeAd; } public function getNativeAd() { return $this->nativeAd; } public function setOpenAuctionStatus($openAuctionStatus) { $this->openAuctionStatus = $openAuctionStatus; } public function getOpenAuctionStatus() { return $this->openAuctionStatus; } public function setProductCategories($productCategories) { $this->productCategories = $productCategories; } public function getProductCategories() { return $this->productCategories; } public function setRestrictedCategories($restrictedCategories) { $this->restrictedCategories = $restrictedCategories; } public function getRestrictedCategories() { return $this->restrictedCategories; } public function setSensitiveCategories($sensitiveCategories) { $this->sensitiveCategories = $sensitiveCategories; } public function getSensitiveCategories() { return $this->sensitiveCategories; } public function setServingRestrictions($servingRestrictions) { $this->servingRestrictions = $servingRestrictions; } public function getServingRestrictions() { return $this->servingRestrictions; } public function setVendorType($vendorType) { $this->vendorType = $vendorType; } public function getVendorType() { return $this->vendorType; } public function setVersion($version) { $this->version = $version; } public function getVersion() { return $this->version; } public function setVideoURL($videoURL) { $this->videoURL = $videoURL; } public function getVideoURL() { return $this->videoURL; } public function setWidth($width) { $this->width = $width; } public function getWidth() { return $this->width; } }
{ "pile_set_name": "Github" }
/* * Copyright 2017 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.gradle.internal.buildoption; import javax.annotation.Nullable; /** * Configuration for a boolean command line option. * * @since 4.4 */ public class BooleanCommandLineOptionConfiguration extends CommandLineOptionConfiguration { private final String disabledDescription; BooleanCommandLineOptionConfiguration(String longOption, String enabledDescription, String disabledDescription) { this(longOption, null, enabledDescription, disabledDescription); } BooleanCommandLineOptionConfiguration(String longOption, @Nullable String shortOption, String enabledDescription, String disabledDescription) { super(longOption, shortOption, enabledDescription); assert disabledDescription != null : "disabled description cannot be null"; this.disabledDescription = disabledDescription; } public static BooleanCommandLineOptionConfiguration create(String longOption, String enabledDescription, String disabledDescription) { return new BooleanCommandLineOptionConfiguration(longOption, enabledDescription, disabledDescription); } public static BooleanCommandLineOptionConfiguration create(String longOption, String shortOption, String enabledDescription, String disabledDescription) { return new BooleanCommandLineOptionConfiguration(longOption, shortOption, enabledDescription, disabledDescription); } public String getDisabledDescription() { return disabledDescription; } @Override public BooleanCommandLineOptionConfiguration incubating() { super.incubating(); return this; } @Override public BooleanCommandLineOptionConfiguration deprecated() { super.deprecated(); return this; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven conversion-service="conversionService"/> <mvc:default-servlet-handler/> <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">--> <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>--> <!--<property name="prefix" value="/WEB-INF/jsp/"/>--> <!--<property name="suffix" value=".jsp"/>--> <!--</bean>--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <property name="maxUploadSize" value="10485760000"/> <property name="maxInMemorySize" value="40960"/> </bean> <context:component-scan base-package="org.seckill.web;org.seckill.web.swagger"/> <!--日期字符串转date类型--> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <bean class="org.seckill.util.common.util.String2DateUtil"/> </property> </bean> <!--静态资源访问--> <!--<mvc:resources mapping="/html/**" location="/html/"/>--> <!--线程池--> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="10"/> <property name="maxPoolSize" value="20"/> <property name="queueCapacity" value="100"/> <property name="keepAliveSeconds" value="60"/> <property name="rejectedExecutionHandler"> <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /> </property> </bean> </beans>
{ "pile_set_name": "Github" }
/* * Copyright 2017-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.api.async; import java.util.List; import java.util.Map; import io.lettuce.core.*; import io.lettuce.core.output.KeyValueStreamingChannel; /** * Asynchronous executed commands for Strings. * * @param <K> Key type. * @param <V> Value type. * @author Mark Paluch * @since 4.0 * @generated by io.lettuce.apigenerator.CreateAsyncApi */ public interface RedisStringAsyncCommands<K, V> { /** * Append a value to a key. * * @param key the key * @param value the value * @return Long integer-reply the length of the string after the append operation. */ RedisFuture<Long> append(K key, V value); /** * Count set bits in a string. * * @param key the key * * @return Long integer-reply The number of bits set to 1. */ RedisFuture<Long> bitcount(K key); /** * Count set bits in a string. * * @param key the key * @param start the start * @param end the end * * @return Long integer-reply The number of bits set to 1. */ RedisFuture<Long> bitcount(K key, long start, long end); /** * Execute {@code BITFIELD} with its subcommands. * * @param key the key * @param bitFieldArgs the args containing subcommands, must not be {@code null}. * * @return Long bulk-reply the results from the bitfield commands. */ RedisFuture<List<Long>> bitfield(K key, BitFieldArgs bitFieldArgs); /** * Find first bit set or clear in a string. * * @param key the key * @param state the state * * @return Long integer-reply The command returns the position of the first bit set to 1 or 0 according to the request. * * If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is * returned. * * If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns * the first bit not part of the string on the right. So if the string is tree bytes set to the value 0xff the * command {@code BITPOS key 0} will return 24, since up to bit 23 all the bits are 1. * * Basically the function consider the right of the string as padded with zeros if you look for clear bits and * specify no range or the <em>start</em> argument <strong>only</strong>. */ RedisFuture<Long> bitpos(K key, boolean state); /** * Find first bit set or clear in a string. * * @param key the key * @param state the bit type: long * @param start the start type: long * @return Long integer-reply The command returns the position of the first bit set to 1 or 0 according to the request. * * If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is * returned. * * If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns * the first bit not part of the string on the right. So if the string is tree bytes set to the value 0xff the * command {@code BITPOS key 0} will return 24, since up to bit 23 all the bits are 1. * * Basically the function consider the right of the string as padded with zeros if you look for clear bits and * specify no range or the <em>start</em> argument <strong>only</strong>. * @since 5.0.1 */ RedisFuture<Long> bitpos(K key, boolean state, long start); /** * Find first bit set or clear in a string. * * @param key the key * @param state the bit type: long * @param start the start type: long * @param end the end type: long * @return Long integer-reply The command returns the position of the first bit set to 1 or 0 according to the request. * * If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is * returned. * * If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns * the first bit not part of the string on the right. So if the string is tree bytes set to the value 0xff the * command {@code BITPOS key 0} will return 24, since up to bit 23 all the bits are 1. * * Basically the function consider the right of the string as padded with zeros if you look for clear bits and * specify no range or the <em>start</em> argument <strong>only</strong>. * * However this behavior changes if you are looking for clear bits and specify a range with both * <strong>start</strong> and <strong>end</strong>. If no clear bit is found in the specified range, the function * returns -1 as the user specified a clear range and there are no 0 bits in that range. */ RedisFuture<Long> bitpos(K key, boolean state, long start, long end); /** * Perform bitwise AND between strings. * * @param destination result key of the operation * @param keys operation input key names * @return Long integer-reply The size of the string stored in the destination key, that is equal to the size of the longest * input string. */ RedisFuture<Long> bitopAnd(K destination, K... keys); /** * Perform bitwise NOT between strings. * * @param destination result key of the operation * @param source operation input key names * @return Long integer-reply The size of the string stored in the destination key, that is equal to the size of the longest * input string. */ RedisFuture<Long> bitopNot(K destination, K source); /** * Perform bitwise OR between strings. * * @param destination result key of the operation * @param keys operation input key names * @return Long integer-reply The size of the string stored in the destination key, that is equal to the size of the longest * input string. */ RedisFuture<Long> bitopOr(K destination, K... keys); /** * Perform bitwise XOR between strings. * * @param destination result key of the operation * @param keys operation input key names * @return Long integer-reply The size of the string stored in the destination key, that is equal to the size of the longest * input string. */ RedisFuture<Long> bitopXor(K destination, K... keys); /** * Decrement the integer value of a key by one. * * @param key the key * @return Long integer-reply the value of {@code key} after the decrement */ RedisFuture<Long> decr(K key); /** * Decrement the integer value of a key by the given number. * * @param key the key * @param amount the decrement type: long * @return Long integer-reply the value of {@code key} after the decrement */ RedisFuture<Long> decrby(K key, long amount); /** * Get the value of a key. * * @param key the key * @return V bulk-string-reply the value of {@code key}, or {@code null} when {@code key} does not exist. */ RedisFuture<V> get(K key); /** * Returns the bit value at offset in the string value stored at key. * * @param key the key * @param offset the offset type: long * @return Long integer-reply the bit value stored at <em>offset</em>. */ RedisFuture<Long> getbit(K key, long offset); /** * Get a substring of the string stored at a key. * * @param key the key * @param start the start type: long * @param end the end type: long * @return V bulk-string-reply */ RedisFuture<V> getrange(K key, long start, long end); /** * Set the string value of a key and return its old value. * * @param key the key * @param value the value * @return V bulk-string-reply the old value stored at {@code key}, or {@code null} when {@code key} did not exist. */ RedisFuture<V> getset(K key, V value); /** * Increment the integer value of a key by one. * * @param key the key * @return Long integer-reply the value of {@code key} after the increment */ RedisFuture<Long> incr(K key); /** * Increment the integer value of a key by the given amount. * * @param key the key * @param amount the increment type: long * @return Long integer-reply the value of {@code key} after the increment */ RedisFuture<Long> incrby(K key, long amount); /** * Increment the float value of a key by the given amount. * * @param key the key * @param amount the increment type: double * @return Double bulk-string-reply the value of {@code key} after the increment. */ RedisFuture<Double> incrbyfloat(K key, double amount); /** * Get the values of all the given keys. * * @param keys the key * @return List&lt;V&gt; array-reply list of values at the specified keys. */ RedisFuture<List<KeyValue<K, V>>> mget(K... keys); /** * Stream over the values of all the given keys. * * @param channel the channel * @param keys the keys * * @return Long array-reply list of values at the specified keys. */ RedisFuture<Long> mget(KeyValueStreamingChannel<K, V> channel, K... keys); /** * Set multiple keys to multiple values. * * @param map the null * @return String simple-string-reply always {@code OK} since {@code MSET} can't fail. */ RedisFuture<String> mset(Map<K, V> map); /** * Set multiple keys to multiple values, only if none of the keys exist. * * @param map the null * @return Boolean integer-reply specifically: * * {@code 1} if the all the keys were set. {@code 0} if no key was set (at least one key already existed). */ RedisFuture<Boolean> msetnx(Map<K, V> map); /** * Set the string value of a key. * * @param key the key * @param value the value * * @return String simple-string-reply {@code OK} if {@code SET} was executed correctly. */ RedisFuture<String> set(K key, V value); /** * Set the string value of a key. * * @param key the key * @param value the value * @param setArgs the setArgs * * @return String simple-string-reply {@code OK} if {@code SET} was executed correctly. */ RedisFuture<String> set(K key, V value, SetArgs setArgs); /** * Sets or clears the bit at offset in the string value stored at key. * * @param key the key * @param offset the offset type: long * @param value the value type: string * @return Long integer-reply the original bit value stored at <em>offset</em>. */ RedisFuture<Long> setbit(K key, long offset, int value); /** * Set the value and expiration of a key. * * @param key the key * @param seconds the seconds type: long * @param value the value * @return String simple-string-reply */ RedisFuture<String> setex(K key, long seconds, V value); /** * Set the value and expiration in milliseconds of a key. * * @param key the key * @param milliseconds the milliseconds type: long * @param value the value * @return String simple-string-reply */ RedisFuture<String> psetex(K key, long milliseconds, V value); /** * Set the value of a key, only if the key does not exist. * * @param key the key * @param value the value * @return Boolean integer-reply specifically: * * {@code 1} if the key was set {@code 0} if the key was not set */ RedisFuture<Boolean> setnx(K key, V value); /** * Overwrite part of a string at key starting at the specified offset. * * @param key the key * @param offset the offset type: long * @param value the value * @return Long integer-reply the length of the string after it was modified by the command. */ RedisFuture<Long> setrange(K key, long offset, V value); /** * The STRALGO command implements complex algorithms that operate on strings. This method uses the LCS algorithm (longest * common substring). * * <ul> * <li>Without modifiers the string representing the longest common substring is returned.</li> * <li>When {@link StrAlgoArgs#justLen() LEN} is given the command returns the length of the longest common substring.</li> * <li>When {@link StrAlgoArgs#withIdx() IDX} is given the command returns an array with the LCS length and all the ranges * in both the strings, start and end offset for each string, where there are matches. When * {@link StrAlgoArgs#withMatchLen() WITHMATCHLEN} is given each array representing a match will also have the length of the * match.</li> * </ul> * * @param strAlgoArgs command arguments. * @return StringMatchResult * @since 6.0 */ RedisFuture<StringMatchResult> stralgoLcs(StrAlgoArgs strAlgoArgs); /** * Get the length of the value stored in a key. * * @param key the key * @return Long integer-reply the length of the string at {@code key}, or {@code 0} when {@code key} does not exist. */ RedisFuture<Long> strlen(K key); }
{ "pile_set_name": "Github" }
@echo off setlocal REM Copyright 2006-2010 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the REM Amazon Software License (the "License"). You may not use this file except in compliance with the License. A copy of the REM License is located at http://aws.amazon.com/asl or in the "license" file accompanying this file. This file is distributed on an "AS REM IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific REM language governing permissions and limitations under the License. REM Set intermediate env vars because the %VAR:x=y% notation below REM (which replaces the string x with the string y in VAR) REM doesn't handle undefined environment variables. This way REM we're always dealing with defined variables in those tests. set CHK_HOME=_%EC2_HOME% if "%CHK_HOME:"=%" == "_" goto HOME_MISSING "%EC2_HOME:"=%\bin\ec2-cmd" DescribeVolumes %* goto DONE :HOME_MISSING echo EC2_HOME is not set exit /b 1 :DONE
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Rabin-Karp method\n", "\n", "If you think hard enough, there's nothing that diferrentiates piecs of text from numbers. You can think of letters as digits and base of the numbers as sufficently big to accomodate for all the digits. For example take the following text\n", "\n", "$$\n", "babacb\n", "$$\n", "\n", "it can be though of as a number base 26 (for all the english letters):\n", "\n", "$$\n", "(1,0,1,0,2,1)_{26}\n", "$$\n", "\n", "We can transform this number to base 10 using the following equation.\n", "\n", "$$\n", "1*26^5 + 0 * 26^4 + 1*26^3 + 0*26^2 + 2*26^1 + 1*26^0 = 11899005\n", "$$\n", "\n", "From the formulation above the following property should be clear.\n", "\n", "$$\n", "abba = abb * 26 + b\n", "$$\n", "\n", "in general we can write $concat(word, letter) = base * word + letter$ (1).\n", "\n", "There's also a small technicality. When we compare numbers then $0001$ and $001$ and $1$ are equivalent. This means that we cannot map any letter to 0 if we want to be able to successfuly compare the numbers. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Observation (1) allows us to quickly compute hashes for all the prefixes of a given word. Just like in class we are going to use modular arithmetic for our computations." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "'A' 65\n", "'a' 97\n", "'b' 98\n", "'c' 99\n", "' ' 32\n", "'c' - 'a' + 1 = 3\n" ] } ], "source": [ "# we need to map letters to numbers. Python function ord does the job\n", "print(repr('A'), ord('A'))\n", "print(repr('a'), ord('a'))\n", "print(repr('b'), ord('b'))\n", "print(repr('c'), ord('c'))\n", "print(repr(' '), ord(' '))\n", "\n", "print('%s - %s + 1 = %d' % (repr('c'), repr('a'), ord('c') - ord('a') + 1))\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "BIG_FAT_PRIME = 2**32 - 1\n", "ENGLISH_BASE = 30 # in theory 27 is sufficient but better safe than sorry!\n", "\n", "def compute_hashes(text, base=ENGLISH_BASE, modulo = BIG_FAT_PRIME):\n", " # \n", " h = [None for _ in range(len(text) + 1)]\n", " h[0] = 0 # hash of empty word is 0\n", " for i in range(len(text)):\n", " # we only deal with english letters so we subtract 'a'\n", " # to normalize range. We add 0 to avoid creating zero digit.\n", " letter_as_number = (ord(text[i]) - ord('a') + 1)\n", " h[i + 1] = h[i] * base + letter_as_number\n", " h[i + 1] %= modulo\n", " # at the end of the iteration h[i+1] is the hash\n", " # of prefix of text of lenght (i+1) which in\n", " # Python is text[:(i+1)]\n", " return h" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "PROTIP: If you happen to ever implemented this is lower level programming language like C or C++, be ware of integer overflows." ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 2, 61, 1832, 54961, 1648833, 49464992]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "compute_hashes(\"babacb\")" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0, 2, 61, 1832, 54964, 1648924, 49467724]" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "compute_hashes(\"babddd\")" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0,\n", " 2,\n", " 61,\n", " 1832,\n", " 54964,\n", " 1648924,\n", " 49467721,\n", " 1484031649,\n", " 1571276524,\n", " 4188622771,\n", " 1104631594,\n", " 3074176759,\n", " 2030989594,\n", " 800145691,\n", " 2529534259]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# for longer strings modulo matters\n", "compute_hashes(\"babddasdasdsad\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## hashes of substrings\n", "\n", "Now here's a crutial observation. Let's take polynomial representation of string $babacb$ (where $X$ is the base)\n", "\n", "$$\n", "b*X^5 + a * X^4 + b*X^3 + a*X^2 + c*X^1 + b*X^0 \n", "$$\n", "\n", "Say we want to compute hash of $ac$ which is conveniently appears on 4-th index the string we originally hashed. Moreover we have hashes of all the prefixes - it seems like we are in good shape:\n", "\n", "\\begin{align}\n", "\\text{we have }\\ \\ \\ & hash(babac) &=\\ & b*X^4 + a * X^3 + b*X^2 &+& a*X^1 + c*X^0 \\\\\n", "\\text{we have }\\ \\ \\ & hash(bab) &=\\ & b*X^2 + a * X^1 + b*X^0&&\\\\\n", "\\text{we WANT }\\ \\ \\ & hash(ac) &=\\ & && a*X^1 + c*X^0\\\\\n", "\\end{align}\n", "\n", "\n", "From above we can clearly see that:\n", "\n", "$$\n", "hash(ac) = hash(babac) - X^2 * hash(bab)\n", "$$\n", "\n", "We can generalize this to arbitrary substring of our hashed string. Assume we hashed string $s_0, s_1, ..., s_{n-1}$ such that $h_0 = hash(\\emptyset)$, $h_1 = hash(s_0)$, $h_2 = hash(s_0, s_1)$ etc. \n", "Then we can compute $hash(s_i, ..., s_j)$ using the following formula:\n", "\n", "$$\n", "hash(s_i, ..., s_{j-1}) = h_j - h_i * X ^{j - i}\n", "$$\n", "\n", "This looks very close to $O(1)$ complexity hash computation if not for $X ^{j - i}$. But since there are at most $n$ different powers of $X$ that we are interested in, we can precompute them in $O(n)$ time." ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def compute_powers(n, base=ENGLISH_BASE, modulo=BIG_FAT_PRIME):\n", " powers = [None for _ in range(n + 1)]\n", " powers[0] = 1\n", " for i in range(n):\n", " powers[i+1] = (powers[i] * base) % modulo\n", " return powers" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1,\n", " 30,\n", " 900,\n", " 27000,\n", " 810000,\n", " 24300000,\n", " 729000000,\n", " 395163525,\n", " 3264971160,\n", " 3459854310,\n", " 716414220]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "compute_powers(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can put all those observations together into efficient detastructure that allows us to compute hashes of substrings in $O(1)$" ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Hasher(object):\n", " def __init__(self, word):\n", " self.h = compute_hashes(word)\n", " self.powers = compute_powers(len(word))\n", " \n", " def substring_hash(self, i, j):\n", " result = self.h[j] - self.h[i] * self.powers[j-i]\n", " return result % BIG_FAT_PRIME" ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "collapsed": false }, "outputs": [], "source": [ "TEXT = \"abcxabcx\"\n", "h = Hasher(TEXT)" ] }, { "cell_type": "code", "execution_count": 79, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ab]cxabcx 32\n", "abcx[ab]cx 32\n", "abc[xa]bcx 721\n" ] } ], "source": [ "def highlight(word, i, j):\n", " return word[:i] + \"[\" + word[i:j] + \"]\" + word[j:]\n", "\n", "print(highlight(TEXT, 0, 2), h.substring_hash(0, 2))\n", "print(highlight(TEXT, 4, 6), h.substring_hash(4, 6))\n", "print(highlight(TEXT, 3, 5), h.substring_hash(3, 5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Hasher complexity analysis.\n", "\n", "Preprocessing (`__init__`):\n", "- `compute_hashes` is $O(n)$\n", "- 'compute_powers` is $O(n)$\n", "Therefore precomputing is $O(n)$.\n", "\n", "Queries (`substring_hash`) is of complexity $O(1)$ - it is just a simple formula." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that this technique is very powerful. More powerful than we need for pattern matching. It should not be a surprise that we can easily use it to solve pattern matching" ] }, { "cell_type": "code", "execution_count": 100, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# hasher for text\n", "text_h = Hasher(\"to be or not to be\")" ] }, { "cell_type": "code", "execution_count": 101, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "65" ] }, "execution_count": 101, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# hash of the pattern\n", "compute_hashes(\"be\")[-1]" ] }, { "cell_type": "code", "execution_count": 102, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "65" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# hash of the occurence of \"be\" in original text. \n", "text_h.substring_hash(3, 5)" ] }, { "cell_type": "code", "execution_count": 105, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def compute_matches(text, pattern):\n", " # hash of patter\n", " pattern_hash = compute_hashes(pattern)[-1]\n", " # hasher for text\n", " text_h = Hasher(text)\n", " res = []\n", " for i in range(len(text) - len(pattern) + 1):\n", " # i is potential match start index\n", " # compare hash in text with hash of pattern\n", " if text_h.substring_hash(i, i + len(pattern)) == pattern_hash:\n", " # if matching append to result list.\n", " res.append(i)\n", " return res" ] }, { "cell_type": "code", "execution_count": 106, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[3, 16]" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "compute_matches(\"to be or not to be\", \"be\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rabin-Karp complexity analysis\n", "\n", "Assume that pattern is of length $n$ and text of length $m$\n", "\n", "- pattern hash: $O(n)$\n", "- text preprocessing $O(m)$.\n", "- $n - m$ iterations of main loop with $O(1)$ hash computation in each loop\n", "\n", "total: $O(n+m)$\n", "\n", "Catch? Relies on luck." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.1" } }, "nbformat": 4, "nbformat_minor": 0 }
{ "pile_set_name": "Github" }
require 'tzinfo/timezone_definition' module TZInfo module Definitions module Etc module GMT0 include TimezoneDefinition linked_timezone 'Etc/GMT0', 'Etc/GMT' end end end end
{ "pile_set_name": "Github" }
setClass("pubClass", representation("numeric", id = "integer")) setClass("privCl", representation(x = "numeric", id = "integer")) .showMe <- function(object) cat("show()ing object of class ", class(object), " and slots named\n\t", paste(slotNames(object), collapse=", "), "\n") setMethod("show", "pubClass", .showMe) setMethod("show", "privCl", .showMe) setMethod("plot", "pubClass", function(x, ...) plot(as(x, "numeric"), ...)) setMethod("plot", "privCl", function(x, ...) plot(x@x, ...)) ## this is exported: assertError <- function(expr) stopifnot(inherits(try(expr, silent = TRUE), "try-error")) ## this one is not: assertWarning <- function(expr) stopifnot(inherits(tryCatch(expr, warning = function(w)w), "warning")) if(isGeneric("colSums")) { stop("'colSums' is already generic -- need new example in test ...") } else { setGeneric("colSums") stopifnot(isGeneric("colSums")) } assertError(setGeneric("pubGenf"))# error: no skeleton setGeneric("pubGenf", function(x,y) standardGeneric("pubGenf")) ## a private generic {not often making sense}: setGeneric("myGenf", function(x,y){ standardGeneric("myGenf") }) setMethod("myGenf", "pubClass", function(x, y) 2*x) ## "(x, ...)" not ok, as generic has no '...': assertError(setMethod("pubGenf", "pubClass", function(x, ...) { 10*x } )) ## and this is ok setMethod("pubGenf", c(x="pubClass"), function(x, y) { 10*x } ) ## Long signature in generic; method not specifying all setGeneric("pubfn", function(filename, dimLengths, dimSteps, dimStarts, likeTemplate, likeFile) { function(x,y) standardGeneric("pubfn") }) setMethod("pubfn", signature= signature(filename="character", dimLengths="numeric", dimSteps="numeric", dimStarts="numeric"), function(filename=filename, dimLengths=NULL, dimSteps=NULL, dimStarts=NULL) { sys.call() }) ### "Same" class as in Matrix (but different 'Extends'!) {as in Rmpfr} ## "atomic vectors" (-> ?is.atomic ) -- exactly as in "Matrix": ## --------------- setClassUnion("atomicVector", ## "double" is not needed, and not liked by some members = c("logical", "integer", "numeric", "complex", "raw", "character")) setClassUnion("array_or_vector", members = c("array", "matrix", "atomicVector")) ## Non trivial class union (in the sense that subclasses are S4) ## derived from a Matrix pkg analogon: ## NB: exportClasses(..) all these *but* "mM" (!) setClass("M", contains = "VIRTUAL", slots = c(Dim = "integer", Dimnames = "list"), prototype = prototype(Dim = integer(2), Dimnames = list(NULL,NULL))) setClass("dM", contains = c("M", "VIRTUAL"), slots = c(x = "numeric")) setClass("diagM", contains = c("M", "VIRTUAL"), slots = c(diag = "character")) setClass("ddiM", contains = c("diagM", "dM")) ## now the class union .. that is *NOT* exported setClassUnion("mM", members = c("matrix", "M"))
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // REQUIRES: locale.en_US.UTF-8 // <iomanip> // template <class charT> T10 put_time(const struct tm* tmb, const charT* fmt); #include <iomanip> #include <ostream> #include <cassert> #include "test_macros.h" #include "platform_support.h" // locale name macros template <class CharT> class testbuf : public std::basic_streambuf<CharT> { typedef std::basic_streambuf<CharT> base; std::basic_string<CharT> str_; public: testbuf() { } std::basic_string<CharT> str() const {return std::basic_string<CharT>(base::pbase(), base::pptr());} protected: virtual typename base::int_type overflow(typename base::int_type ch = base::traits_type::eof()) { if (ch != base::traits_type::eof()) { int n = static_cast<int>(str_.size()); str_.push_back(static_cast<CharT>(ch)); str_.resize(str_.capacity()); base::setp(const_cast<CharT*>(str_.data()), const_cast<CharT*>(str_.data() + str_.size())); base::pbump(n+1); } return ch; } }; int main(int, char**) { { testbuf<char> sb; std::ostream os(&sb); os.imbue(std::locale(LOCALE_en_US_UTF_8)); std::tm t = {}; t.tm_sec = 59; t.tm_min = 55; t.tm_hour = 23; t.tm_mday = 31; t.tm_mon = 11; t.tm_year = 161; t.tm_wday = 6; t.tm_isdst = 0; os << std::put_time(&t, "%a %b %d %H:%M:%S %Y"); assert(sb.str() == "Sat Dec 31 23:55:59 2061"); } { testbuf<wchar_t> sb; std::wostream os(&sb); os.imbue(std::locale(LOCALE_en_US_UTF_8)); std::tm t = {}; t.tm_sec = 59; t.tm_min = 55; t.tm_hour = 23; t.tm_mday = 31; t.tm_mon = 11; t.tm_year = 161; t.tm_wday = 6; os << std::put_time(&t, L"%a %b %d %H:%M:%S %Y"); assert(sb.str() == L"Sat Dec 31 23:55:59 2061"); } return 0; }
{ "pile_set_name": "Github" }
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
{ "pile_set_name": "Github" }
*extension_loaded* -- Find out whether an extension is loaded bool extension_loaded(string name)~ Finds out whether the extension is loaded. {name} The extension name. You can see the names of various extensions by using |phpinfo| or if you're using the CGI or CLI version of PHP you can use the -m switch to list all available extensions: $ php -m [PHP Modules] xml tokenizer standard sockets session posix pcre overload mysql mbstring ctype [Zend Modules] Returns TRUE if the extension identified by {name} is loaded, FALSE otherwise. |extension_loaded| example <?php > if (!extension_loaded('gd')) { if (!dl('gd.so')) { exit; } } ?> Version Description 5.0.0 |extension_loaded| uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extensions available which also use uppercase letters. Prior to PHP 5, this function compared the names case sensitively. |get_loaded_extensions| |get_extension_funcs| |phpinfo| |dl| vim:ft=help:
{ "pile_set_name": "Github" }
/// @ref core /// @file glm/ext/matrix_double3x3.hpp #pragma once #include "../detail/type_mat3x3.hpp" namespace glm { /// @addtogroup core_matrix /// @{ /// 3 columns of 3 components matrix of double-precision floating-point numbers. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> typedef mat<3, 3, double, defaultp> dmat3x3; /// 3 columns of 3 components matrix of double-precision floating-point numbers. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> typedef mat<3, 3, double, defaultp> dmat3; /// @} }//namespace glm
{ "pile_set_name": "Github" }
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: A Class to create a window that you can type and edit text in. // Window can hold single line or multiline text. // If it is single it can scroll horizontally in response to // key input and mouse selection. // // $NoKeywords: $ //=============================================================================// #ifndef TEXTENTRY_H #define TEXTENTRY_H #ifdef _WIN32 #pragma once #endif #include <vgui/VGUI.h> #include <Color.h> #include <vgui_controls/Panel.h> #include <vgui_controls/Label.h> #include <vgui_controls/ListPanel.h> #include <utlvector.h> namespace vgui { //----------------------------------------------------------------------------- // Purpose: Text-input handler // Behaviour Specs: // This class handles input from mouse and keyboard. // TextEntry classes support several box styles, horizontal scrolling with no scrollbar // vertical scrolling with or without a scrollbar, single line, multiline, // editable and noneditable. // // Shared behaviour: // URL's are a different text color and are clickable. Clicking them brings up a web browser. // For vertical scroll bars, up and down arrows scroll one line at a time. // Clicking and dragging the nob scrolls through text lines. // Mouse wheel also moves the nob. // User can select and highlight text in the window. // Double clicking on a word selects it. // // Non editable: // No blinking cursor in non editable windows. // Right clicking mouse opens copy menu. Menu's top left corner is where mouse is. // Ctrl-c will also copy the text. // Editable: // Blinking cursor is positioned where text will be inserted. // Text keys type chars in the window. // ctrl-c copy highlighted text // ctrl-v paste highlighted text // ctrl-x cut highlighted text // ctrl-right arrow move cursor to the start of the next word // ctrl-left arrow move cursor to the start of the prev word // ctrl-enter delete the selected text (and inserts a newline if _catchEnterKey is true) // insert delete selected text and pastes text from the clipboard // delete delete the selected text // ctrl-home move cursor to the start of the text // ctrl-end move cursor to the end of the text. // left arrow move cursor before prev char // ctrl-shift left/right arrow selects text a word at a time // right arrow move cursor before next char // up arrow move cursor up one line. // down arrow move cursor down one line. // home move cursor to start of current line // end move cursor to end of current line // backspace delete prev char or selected text. // Trying to move to the prev/next char/line/word when there is none moves the cursor to the // start/end of the text. // Horizontal scrolling: // Trying to move to the prev/next char/line/word when there is none scrolls the text // horizontally in the window so the new text displays at the correct side. // When moving to prev chars scrolling is staggered. To next chars it is one char at a time. // Cut/Copy/Paste Menu: // Right clicking mouse brings up cut/copy/paste menu. // If no text is highlighted the cut/copy options are dimmed. Cut is dimmed in non editable panels // If there is no text in the clipboard or panel is not editable the paste option is dimmed. // If the mouse is right clicked over selected text, the text stays selected. // If the mouse is right clicked over unselected text, any selected text is deselected. // // //----------------------------------------------------------------------------- class TextEntry : public Panel { DECLARE_CLASS_SIMPLE( TextEntry, Panel ); public: TextEntry(Panel *parent, const char *panelName); virtual ~TextEntry(); virtual void SetText(const wchar_t *wszText); virtual void SetText(const char *text); virtual void GetText(OUT_Z_BYTECAP(bufLenInBytes) char *buf, int bufLenInBytes); virtual void GetText(OUT_Z_BYTECAP(bufLenInBytes) wchar_t *buf, int bufLenInBytes); virtual int GetTextLength() const; virtual bool IsTextFullySelected() const; virtual int GetWordLeft(); // Get the index of the start of the word to the left virtual int GetWordRight(); // Get the index of the start of the word to the right // editing virtual void GotoLeft(); // move cursor one char left virtual void GotoRight(); // move cursor one char right virtual void GotoUp(); // move cursor one line up virtual void GotoDown(); // move cursor one line down virtual void GotoWordRight(); // move cursor to Start of next word virtual void GotoWordLeft(); // move cursor to Start of prev word virtual void GotoFirstOfLine(); // go to Start of the current line virtual void GotoEndOfLine(); // go to end of the current line virtual void GotoTextStart(); // go to Start of text buffer virtual void GotoTextEnd(); // go to end of text buffer virtual void InsertChar(wchar_t ch); virtual void InsertString(const char *text); virtual void InsertString(const wchar_t *wszText); virtual void Backspace(); virtual void Delete(); virtual void SelectNone(); virtual void OpenEditMenu(); MESSAGE_FUNC( CutSelected, "DoCutSelected" ); MESSAGE_FUNC( CopySelected, "DoCopySelected" ); MESSAGE_FUNC( Paste, "DoPaste" ); MESSAGE_FUNC_INT( LanguageChanged, "DoLanguageChanged", handle ); MESSAGE_FUNC_INT( ConversionModeChanged, "DoConversionModeChanged", handle ); MESSAGE_FUNC_INT( SentenceModeChanged, "DoSentenceModeChanged", handle ); MESSAGE_FUNC_WCHARPTR( CompositionString, "DoCompositionString", string ); MESSAGE_FUNC( ShowIMECandidates, "DoShowIMECandidates" ); MESSAGE_FUNC( HideIMECandidates, "DoHideIMECandidates" ); MESSAGE_FUNC( UpdateIMECandidates, "DoUpdateIMECandidates" ); virtual void DeleteSelectedRange(int x0, int x1); virtual void DeleteSelected(); virtual void Undo(); virtual void SaveUndoState(); virtual void SetFont(HFont font); virtual HFont GetFont(); virtual void SetTextHidden(bool bHideText); virtual void SetEditable(bool state); virtual bool IsEditable(); virtual void SetEnabled(bool state); // move the cursor to line 'line', given how many pixels are in a line virtual void MoveCursor(int line, int pixelsAcross); // sets the color of the background when the control is disabled virtual void SetDisabledBgColor(Color col); // set whether the box handles more than one line of entry virtual void SetMultiline(bool state); virtual bool IsMultiline(); // sets visibility of scrollbar virtual void SetVerticalScrollbar(bool state); // sets whether or not the edit catches and stores ENTER key presses virtual void SetCatchEnterKey(bool state); // sets whether or not to send "TextNewLine" msgs when ENTER key is pressed virtual void SendNewLine(bool send); // sets limit of number of characters insertable into field; set to -1 to remove maximum // only works with if rich-edit is NOT enabled virtual void SetMaximumCharCount(int maxChars); virtual int GetMaximumCharCount(); virtual void SetAutoProgressOnHittingCharLimit(bool state); // sets whether to wrap text once maxChars is reached (on a line by line basis) virtual void SetWrap(bool wrap); virtual void RecalculateLineBreaks(); virtual void LayoutVerticalScrollBarSlider(); virtual bool RequestInfo(KeyValues *outputData); // sets the height of the window so all text is visible. // used by tooltips void SetToFullHeight(); // sets the width of the window so all text is visible. (will create one line) // used by tooltips void SetToFullWidth(); int GetNumLines(); /* INFO HANDLING "GetText" returns: "text" - text contained in the text box */ /* CUSTOM MESSAGE HANDLING "SetText" input: "text" - text is set to be this string */ /* MESSAGE SENDING (to action signal targets) "TextChanged" - sent when the text is edited by the user "TextNewLine" - sent when the end key is pressed in the text entry AND _sendNewLines is true "TextKillFocus" - sent when focus leaves textentry field */ // Selects all the text in the text entry. void SelectAllText(bool bResetCursorPos); void SelectNoText(); void SelectAllOnFirstFocus( bool status ); void SetDrawWidth(int width); // width from right side of window we have to draw in int GetDrawWidth(); void SetHorizontalScrolling(bool status); // turn horizontal scrolling on or off. // sets whether non-ascii characters (unicode chars > 127) are allowed in the control - defaults to OFF void SetAllowNonAsciiCharacters(bool state); // sets whether or not number input only is allowed void SetAllowNumericInputOnly(bool state); // gets whether or not number input only is allowed bool GetAllowNumericInputOnly() const; // By default, we draw the language shortname on the right hand side of the control void SetDrawLanguageIDAtLeft( bool state ); virtual bool GetDropContextMenu( Menu *menu, CUtlVector< KeyValues * >& data ); virtual bool IsDroppable( CUtlVector< KeyValues * >& data ); virtual void OnPanelDropped( CUtlVector< KeyValues * >& data ); virtual Panel *GetDragPanel(); virtual void OnCreateDragData( KeyValues *msg ); void SelectAllOnFocusAlways( bool status ); void SetSelectionTextColor( const Color& clr ); void SetSelectionBgColor( const Color& clr ); void SetSelectionUnfocusedBgColor( const Color& clr ); void SetUseFallbackFont( bool bState, HFont hFallback ); protected: virtual void ResetCursorBlink(); virtual void PerformLayout(); // layout the text in the window virtual void ApplySchemeSettings(IScheme *pScheme); virtual void PaintBackground(); virtual int DrawChar(wchar_t ch, HFont font, int index, int x, int y); virtual bool DrawCursor(int x, int y); virtual void SetCharAt(wchar_t ch, int index); // set the value of a char in the text buffer virtual void ApplySettings( KeyValues *inResourceData ); virtual void GetSettings( KeyValues *outResourceData ); void InitSettings() OVERRIDE; virtual void FireActionSignal(); virtual bool GetSelectedRange(int& cx0,int& cx1); virtual void CursorToPixelSpace(int cursorPos, int &cx, int &cy); virtual int PixelToCursorSpace(int cx, int cy); virtual void AddAnotherLine(int &cx, int &cy); virtual int GetYStart(); // works out ypixel position drawing started at virtual bool SelectCheck( bool fromMouse = false ); // check if we are in text selection mode MESSAGE_FUNC_WCHARPTR( OnSetText, "SetText", text ); MESSAGE_FUNC( OnSliderMoved, "ScrollBarSliderMoved" ); // respond to scroll bar events virtual void OnKillFocus(); virtual void OnMouseWheeled(int delta); // respond to mouse wheel events virtual void OnKeyCodePressed(KeyCode code); //respond to keyboard events virtual void OnKeyCodeTyped(KeyCode code); //respond to keyboard events virtual void OnKeyTyped(wchar_t unichar); //respond to keyboard events virtual void OnCursorMoved(int x, int y); // respond to moving the cursor with mouse button down virtual void OnMousePressed(MouseCode code); // respond to mouse down events virtual void OnMouseDoublePressed( MouseCode code ); virtual void OnMouseTriplePressed( MouseCode code ); virtual void OnMouseReleased( MouseCode code ); // respond to mouse up events virtual void OnKeyFocusTicked(); // do while window has keyboard focus virtual void OnMouseFocusTicked(); // do while window has mouse focus virtual void OnCursorEntered(); // handle cursor entering window virtual void OnCursorExited(); // handle cursor exiting window virtual void OnMouseCaptureLost(); virtual void OnSizeChanged(int newWide, int newTall); // Returns the character index the drawing should Start at virtual int GetStartDrawIndex(int &lineBreakIndexIndex); public: // helper accessors for common gets virtual float GetValueAsFloat(); virtual int GetValueAsInt(); protected: void ScrollRight(); // scroll to right until cursor is visible void ScrollLeft(); // scroll to left bool IsCursorOffRightSideOfWindow(int cursorPos); // check if cursor is off right side of window bool IsCursorOffLeftSideOfWindow(int cursorPos); // check if cursor is off left side of window void ScrollLeftForResize(); void OnSetFocus(); // Change keyboard layout type void OnChangeIME( bool forward ); bool NeedsEllipses( HFont font, int *pIndex ); private: MESSAGE_FUNC_INT( OnSetState, "SetState", state ); // get index in buffer of the Start of the current line we are on int GetCurrentLineStart(); // get index in buffer of the end of the current line we are on int GetCurrentLineEnd(); bool IsLineBreak(int index); int GetCursorLine(); void MoveScrollBar(int delta); void CalcBreakIndex(); // calculate _recalculateLineBreaksIndex void CreateEditMenu(); // create copy/cut/paste menu public: Menu *GetEditMenu(); // retrieve copy/cut/paste menu void SetDrawOffset(int x, int y); private: void FlipToLastIME(); public: virtual void GetTextRange( wchar_t *buf, int from, int numchars ); // copy a portion of the text to the buffer and add zero-termination virtual void GetTextRange( char *buf, int from, int numchars ); // copy a portion of the text to the buffer and add zero-termination private: CUtlVector<wchar_t> m_TextStream; // the text in the text window is stored in this buffer CUtlVector<wchar_t> m_UndoTextStream; // a copy of the text buffer to revert changes CUtlVector<int> m_LineBreaks; // an array that holds the index in the buffer to wrap lines at int _cursorPos; // the position in the text buffer of the blinking cursor bool _cursorIsAtEnd; bool _putCursorAtEnd; int _undoCursorPos; // a copy of the cursor position to revert changes bool _cursorBlink; // whether cursor is blinking or not bool _hideText; // whether text is visible on screen or not bool _editable; // whether text is editable or not bool _mouseSelection; // whether we are highlighting text or not (selecting text) bool _mouseDragSelection; // tells weather mouse is outside window and button is down so we select text int _mouseSelectCursorStart; // where mouse button was pressed down in text window long _cursorNextBlinkTime; // time of next cursor blink int _cursorBlinkRate; // speed of cursor blinking int _select[2]; // select[1] is the offset in the text to where the cursor is currently // select[0] is the offset to where the cursor was dragged to. or -1 if no drag. int _pixelsIndent; int _charCount; int _maxCharCount; // max number of chars that can be in the text buffer HFont _font; // font of chars in the text buffer CUtlString _fontName; CUtlString _smallFontName; HFont _smallfont; bool _dataChanged; // whether anything in the window has changed. bool _multiline; // whether buffer is multiline or just a single line bool _verticalScrollbar; // whether window has a vertical scroll bar ScrollBar *_vertScrollBar; // the scroll bar used in the window Color _cursorColor; // color of the text cursor Color _disabledFgColor; Color _disabledBgColor; Color _selectionColor; Color _selectionTextColor; // color of the highlighted text Color _defaultSelectionBG2Color; int _currentStartLine; // use for checking vertical text scrolling (multiline) int _currentStartIndex; // use for horizontal text scrolling (!multiline) bool _horizScrollingAllowed; // use to disable horizontal text scrolling period. Color _focusEdgeColor; bool _catchEnterKey; bool _wrap; bool _sendNewLines; int _drawWidth; int _drawOffsetX; int _drawOffsetY; // selection data Menu *m_pEditMenu; ///cut/copy/paste popup int _recalculateBreaksIndex; // tells next linebreakindex index to Start recalculating line breaks bool _selectAllOnFirstFocus : 1; // highlights all text in window when focus is gained. bool _selectAllOnFocusAlways : 1; bool _firstFocusStatus; // keep track if we've had that first focus or not bool m_bAllowNumericInputOnly; bool m_bAllowNonAsciiCharacters; bool m_bAutoProgressOnHittingCharLimit; enum { MAX_COMPOSITION_STRING = 256, }; wchar_t m_szComposition[ MAX_COMPOSITION_STRING ]; Menu *m_pIMECandidates; int m_hPreviousIME; bool m_bDrawLanguageIDAtLeft; int m_nLangInset; bool m_bUseFallbackFont : 1; HFont m_hFallbackFont; }; } #endif // TEXTENTRY_H
{ "pile_set_name": "Github" }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.event.tracking.phase.packet.player; import org.spongepowered.common.event.tracking.phase.packet.BasicPacketState; public final class UpdateSignState extends BasicPacketState { }
{ "pile_set_name": "Github" }
/* This file is part of the iText (R) project. Copyright (c) 1998-2020 iText Group NV Authors: Bruno Lowagie, Paulo Soares, et al. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product. For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ namespace iText.Layout.Margincollapse { public class MarginsCollapseInfo { private bool ignoreOwnMarginTop; private bool ignoreOwnMarginBottom; private MarginsCollapse collapseBefore; private MarginsCollapse collapseAfter; // MarginCollapse instance which contains margin-after of the element without next sibling or parent margins (only element's margin and element's kids) private MarginsCollapse ownCollapseAfter; private bool isSelfCollapsing; // when a parent has a fixed height these fields tells kid how much free space parent has for the margin collapsed with kid private float bufferSpaceOnTop; private float bufferSpaceOnBottom; private float usedBufferSpaceOnTop; private float usedBufferSpaceOnBottom; private bool clearanceApplied; internal MarginsCollapseInfo() { this.ignoreOwnMarginTop = false; this.ignoreOwnMarginBottom = false; this.collapseBefore = new MarginsCollapse(); this.collapseAfter = new MarginsCollapse(); this.isSelfCollapsing = true; this.bufferSpaceOnTop = 0; this.bufferSpaceOnBottom = 0; this.usedBufferSpaceOnTop = 0; this.usedBufferSpaceOnBottom = 0; this.clearanceApplied = false; } internal MarginsCollapseInfo(bool ignoreOwnMarginTop, bool ignoreOwnMarginBottom, MarginsCollapse collapseBefore , MarginsCollapse collapseAfter) { this.ignoreOwnMarginTop = ignoreOwnMarginTop; this.ignoreOwnMarginBottom = ignoreOwnMarginBottom; this.collapseBefore = collapseBefore; this.collapseAfter = collapseAfter; this.isSelfCollapsing = true; this.bufferSpaceOnTop = 0; this.bufferSpaceOnBottom = 0; this.usedBufferSpaceOnTop = 0; this.usedBufferSpaceOnBottom = 0; this.clearanceApplied = false; } public virtual void CopyTo(iText.Layout.Margincollapse.MarginsCollapseInfo destInfo) { destInfo.ignoreOwnMarginTop = this.ignoreOwnMarginTop; destInfo.ignoreOwnMarginBottom = this.ignoreOwnMarginBottom; destInfo.collapseBefore = this.collapseBefore; destInfo.collapseAfter = this.collapseAfter; destInfo.SetOwnCollapseAfter(ownCollapseAfter); destInfo.SetSelfCollapsing(isSelfCollapsing); destInfo.SetBufferSpaceOnTop(bufferSpaceOnTop); destInfo.SetBufferSpaceOnBottom(bufferSpaceOnBottom); destInfo.SetUsedBufferSpaceOnTop(usedBufferSpaceOnTop); destInfo.SetUsedBufferSpaceOnBottom(usedBufferSpaceOnBottom); destInfo.SetClearanceApplied(clearanceApplied); } public static iText.Layout.Margincollapse.MarginsCollapseInfo CreateDeepCopy(iText.Layout.Margincollapse.MarginsCollapseInfo instance) { iText.Layout.Margincollapse.MarginsCollapseInfo copy = new iText.Layout.Margincollapse.MarginsCollapseInfo (); instance.CopyTo(copy); copy.collapseBefore = instance.collapseBefore.Clone(); copy.collapseAfter = instance.collapseAfter.Clone(); if (instance.ownCollapseAfter != null) { copy.SetOwnCollapseAfter(instance.ownCollapseAfter.Clone()); } return copy; } public static void UpdateFromCopy(iText.Layout.Margincollapse.MarginsCollapseInfo originalInstance, iText.Layout.Margincollapse.MarginsCollapseInfo processedCopy) { originalInstance.ignoreOwnMarginTop = processedCopy.ignoreOwnMarginTop; originalInstance.ignoreOwnMarginBottom = processedCopy.ignoreOwnMarginBottom; originalInstance.collapseBefore.JoinMargin(processedCopy.collapseBefore); originalInstance.collapseAfter.JoinMargin(processedCopy.collapseAfter); if (processedCopy.GetOwnCollapseAfter() != null) { if (originalInstance.GetOwnCollapseAfter() == null) { originalInstance.SetOwnCollapseAfter(new MarginsCollapse()); } originalInstance.GetOwnCollapseAfter().JoinMargin(processedCopy.GetOwnCollapseAfter()); } originalInstance.SetSelfCollapsing(processedCopy.isSelfCollapsing); originalInstance.SetBufferSpaceOnTop(processedCopy.bufferSpaceOnTop); originalInstance.SetBufferSpaceOnBottom(processedCopy.bufferSpaceOnBottom); originalInstance.SetUsedBufferSpaceOnTop(processedCopy.usedBufferSpaceOnTop); originalInstance.SetUsedBufferSpaceOnBottom(processedCopy.usedBufferSpaceOnBottom); originalInstance.SetClearanceApplied(processedCopy.clearanceApplied); } internal virtual MarginsCollapse GetCollapseBefore() { return this.collapseBefore; } internal virtual MarginsCollapse GetCollapseAfter() { return collapseAfter; } internal virtual void SetCollapseAfter(MarginsCollapse collapseAfter) { this.collapseAfter = collapseAfter; } internal virtual MarginsCollapse GetOwnCollapseAfter() { return ownCollapseAfter; } internal virtual void SetOwnCollapseAfter(MarginsCollapse marginsCollapse) { this.ownCollapseAfter = marginsCollapse; } internal virtual void SetSelfCollapsing(bool selfCollapsing) { isSelfCollapsing = selfCollapsing; } internal virtual bool IsSelfCollapsing() { return isSelfCollapsing; } internal virtual bool IsIgnoreOwnMarginTop() { return ignoreOwnMarginTop; } internal virtual bool IsIgnoreOwnMarginBottom() { return ignoreOwnMarginBottom; } internal virtual float GetBufferSpaceOnTop() { return bufferSpaceOnTop; } internal virtual void SetBufferSpaceOnTop(float bufferSpaceOnTop) { this.bufferSpaceOnTop = bufferSpaceOnTop; } internal virtual float GetBufferSpaceOnBottom() { return bufferSpaceOnBottom; } internal virtual void SetBufferSpaceOnBottom(float bufferSpaceOnBottom) { this.bufferSpaceOnBottom = bufferSpaceOnBottom; } internal virtual float GetUsedBufferSpaceOnTop() { return usedBufferSpaceOnTop; } internal virtual void SetUsedBufferSpaceOnTop(float usedBufferSpaceOnTop) { this.usedBufferSpaceOnTop = usedBufferSpaceOnTop; } internal virtual float GetUsedBufferSpaceOnBottom() { return usedBufferSpaceOnBottom; } internal virtual void SetUsedBufferSpaceOnBottom(float usedBufferSpaceOnBottom) { this.usedBufferSpaceOnBottom = usedBufferSpaceOnBottom; } internal virtual bool IsClearanceApplied() { return clearanceApplied; } internal virtual void SetClearanceApplied(bool clearanceApplied) { this.clearanceApplied = clearanceApplied; } } }
{ "pile_set_name": "Github" }
name: test_env channels: - defaults - conda-forge dependencies: - python=3.6 - pip - pydap - xarray - numpy - scipy - gfortran_osx-64 - libgfortran - future - attrdict - requests - pytest - codecov - pytest-cov
{ "pile_set_name": "Github" }
# Tenko parser autogenerated test case - From: tests/testcases/import_dynamic/autogen.md - Path: tests/testcases/import_dynamic/gen/Cannot_use_spread/10.md > :: import dynamic : gen : Cannot use spread > > ::> 10 ## Input - `es = 10` `````js import(...a); ````` ## Output _Note: the whole output block is auto-generated. Manual changes will be overwritten!_ Below follow outputs in five parsing modes: sloppy, sloppy+annexb, strict script, module, module+annexb. Note that the output parts are auto-generated by the test runner to reflect actual result. ### Sloppy mode Parsed with script goal and as if the code did not start with strict mode header. ````` throws: Parser error! Dynamic import syntax not supported. Requires version ES2020+ / ES11+. start@1:0, error@1:0 ╔══╦════════════════ 1 ║ import(...a); ║ ^^^^^^------- error ╚══╩════════════════ ````` ### Strict mode Parsed with script goal but as if it was starting with `"use strict"` at the top. _Output same as sloppy mode._ ### Module goal Parsed with the module goal. _Output same as sloppy mode._ ### Sloppy mode with AnnexB Parsed with script goal with AnnexB rules enabled and as if the code did not start with strict mode header. _Output same as sloppy mode._ ### Module goal with AnnexB Parsed with the module goal with AnnexB rules enabled. _Output same as sloppy mode._
{ "pile_set_name": "Github" }
/* * linux/fs/nls/nls_cp863.c * * Charset cp863 translation tables. * Generated automatically from the Unicode and charset * tables from the Unicode Organization (www.unicode.org). * The Unicode to charset table has only exact mappings. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/nls.h> #include <linux/errno.h> static const wchar_t charset2uni[256] = { /* 0x00*/ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x000e, 0x000f, /* 0x10*/ 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c, 0x001d, 0x001e, 0x001f, /* 0x20*/ 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028, 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e, 0x002f, /* 0x30*/ 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a, 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, /* 0x40*/ 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c, 0x004d, 0x004e, 0x004f, /* 0x50*/ 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f, /* 0x60*/ 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, 0x0068, 0x0069, 0x006a, 0x006b, 0x006c, 0x006d, 0x006e, 0x006f, /* 0x70*/ 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, 0x0078, 0x0079, 0x007a, 0x007b, 0x007c, 0x007d, 0x007e, 0x007f, /* 0x80*/ 0x00c7, 0x00fc, 0x00e9, 0x00e2, 0x00c2, 0x00e0, 0x00b6, 0x00e7, 0x00ea, 0x00eb, 0x00e8, 0x00ef, 0x00ee, 0x2017, 0x00c0, 0x00a7, /* 0x90*/ 0x00c9, 0x00c8, 0x00ca, 0x00f4, 0x00cb, 0x00cf, 0x00fb, 0x00f9, 0x00a4, 0x00d4, 0x00dc, 0x00a2, 0x00a3, 0x00d9, 0x00db, 0x0192, /* 0xa0*/ 0x00a6, 0x00b4, 0x00f3, 0x00fa, 0x00a8, 0x00b8, 0x00b3, 0x00af, 0x00ce, 0x2310, 0x00ac, 0x00bd, 0x00bc, 0x00be, 0x00ab, 0x00bb, /* 0xb0*/ 0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556, 0x2555, 0x2563, 0x2551, 0x2557, 0x255d, 0x255c, 0x255b, 0x2510, /* 0xc0*/ 0x2514, 0x2534, 0x252c, 0x251c, 0x2500, 0x253c, 0x255e, 0x255f, 0x255a, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256c, 0x2567, /* 0xd0*/ 0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256b, 0x256a, 0x2518, 0x250c, 0x2588, 0x2584, 0x258c, 0x2590, 0x2580, /* 0xe0*/ 0x03b1, 0x00df, 0x0393, 0x03c0, 0x03a3, 0x03c3, 0x00b5, 0x03c4, 0x03a6, 0x0398, 0x03a9, 0x03b4, 0x221e, 0x03c6, 0x03b5, 0x2229, /* 0xf0*/ 0x2261, 0x00b1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00f7, 0x2248, 0x00b0, 0x2219, 0x00b7, 0x221a, 0x207f, 0x00b2, 0x25a0, 0x00a0, }; static const unsigned char page00[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xff, 0x00, 0x9b, 0x9c, 0x98, 0x00, 0xa0, 0x8f, /* 0xa0-0xa7 */ 0xa4, 0x00, 0x00, 0xae, 0xaa, 0x00, 0x00, 0xa7, /* 0xa8-0xaf */ 0xf8, 0xf1, 0xfd, 0xa6, 0xa1, 0xe6, 0x86, 0xfa, /* 0xb0-0xb7 */ 0xa5, 0x00, 0x00, 0xaf, 0xac, 0xab, 0xad, 0x00, /* 0xb8-0xbf */ 0x8e, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x80, /* 0xc0-0xc7 */ 0x91, 0x90, 0x92, 0x94, 0x00, 0x00, 0xa8, 0x95, /* 0xc8-0xcf */ 0x00, 0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00, /* 0xd0-0xd7 */ 0x00, 0x9d, 0x00, 0x9e, 0x9a, 0x00, 0x00, 0xe1, /* 0xd8-0xdf */ 0x85, 0x00, 0x83, 0x00, 0x00, 0x00, 0x00, 0x87, /* 0xe0-0xe7 */ 0x8a, 0x82, 0x88, 0x89, 0x00, 0x00, 0x8c, 0x8b, /* 0xe8-0xef */ 0x00, 0x00, 0x00, 0xa2, 0x93, 0x00, 0x00, 0xf6, /* 0xf0-0xf7 */ 0x00, 0x97, 0xa3, 0x96, 0x81, 0x00, 0x00, 0x00, /* 0xf8-0xff */ }; static const unsigned char page01[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ }; static const unsigned char page03[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0x00, 0x00, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0xe9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0x00, 0x00, 0x00, 0xe4, 0x00, 0x00, 0xe8, 0x00, /* 0xa0-0xa7 */ 0x00, 0xea, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa8-0xaf */ 0x00, 0xe0, 0x00, 0x00, 0xeb, 0xee, 0x00, 0x00, /* 0xb0-0xb7 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xb8-0xbf */ 0xe3, 0x00, 0x00, 0xe5, 0xe7, 0x00, 0xed, 0x00, /* 0xc0-0xc7 */ }; static const unsigned char page20[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8d, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x60-0x67 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, /* 0x78-0x7f */ }; static const unsigned char page22[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0xf9, 0xfb, 0x00, 0x00, 0x00, 0xec, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0xef, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0xf7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x50-0x57 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x58-0x5f */ 0x00, 0xf0, 0x00, 0x00, 0xf3, 0xf2, 0x00, 0x00, /* 0x60-0x67 */ }; static const unsigned char page23[256] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0xf4, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x20-0x27 */ }; static const unsigned char page25[256] = { 0xc4, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x00-0x07 */ 0x00, 0x00, 0x00, 0x00, 0xda, 0x00, 0x00, 0x00, /* 0x08-0x0f */ 0xbf, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, /* 0x10-0x17 */ 0xd9, 0x00, 0x00, 0x00, 0xc3, 0x00, 0x00, 0x00, /* 0x18-0x1f */ 0x00, 0x00, 0x00, 0x00, 0xb4, 0x00, 0x00, 0x00, /* 0x20-0x27 */ 0x00, 0x00, 0x00, 0x00, 0xc2, 0x00, 0x00, 0x00, /* 0x28-0x2f */ 0x00, 0x00, 0x00, 0x00, 0xc1, 0x00, 0x00, 0x00, /* 0x30-0x37 */ 0x00, 0x00, 0x00, 0x00, 0xc5, 0x00, 0x00, 0x00, /* 0x38-0x3f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x40-0x47 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x48-0x4f */ 0xcd, 0xba, 0xd5, 0xd6, 0xc9, 0xb8, 0xb7, 0xbb, /* 0x50-0x57 */ 0xd4, 0xd3, 0xc8, 0xbe, 0xbd, 0xbc, 0xc6, 0xc7, /* 0x58-0x5f */ 0xcc, 0xb5, 0xb6, 0xb9, 0xd1, 0xd2, 0xcb, 0xcf, /* 0x60-0x67 */ 0xd0, 0xca, 0xd8, 0xd7, 0xce, 0x00, 0x00, 0x00, /* 0x68-0x6f */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x70-0x77 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x78-0x7f */ 0xdf, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, /* 0x80-0x87 */ 0xdb, 0x00, 0x00, 0x00, 0xdd, 0x00, 0x00, 0x00, /* 0x88-0x8f */ 0xde, 0xb0, 0xb1, 0xb2, 0x00, 0x00, 0x00, 0x00, /* 0x90-0x97 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0x98-0x9f */ 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0xa0-0xa7 */ }; static const unsigned char *const page_uni2charset[256] = { page00, page01, NULL, page03, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, page20, NULL, page22, page23, NULL, page25, NULL, NULL, }; static const unsigned char charset2lower[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */ 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */ 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x87, 0x81, 0x82, 0x83, 0x83, 0x85, 0x86, 0x87, /* 0x80-0x87 */ 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x85, 0x8f, /* 0x88-0x8f */ 0x82, 0x8a, 0x88, 0x93, 0x89, 0x8b, 0x96, 0x97, /* 0x90-0x97 */ 0x98, 0x93, 0x81, 0x9b, 0x9c, 0x97, 0x96, 0x9f, /* 0x98-0x9f */ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0x8c, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0xe0, 0xe1, 0x00, 0xe3, 0xe5, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */ 0xed, 0x00, 0x00, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static const unsigned char charset2upper[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */ 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */ 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */ 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */ 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */ 0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */ 0x80, 0x9a, 0x90, 0x84, 0x84, 0x8e, 0x86, 0x80, /* 0x80-0x87 */ 0x92, 0x94, 0x91, 0x95, 0xa8, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */ 0x90, 0x91, 0x92, 0x99, 0x94, 0x95, 0x9e, 0x9d, /* 0x90-0x97 */ 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x00, /* 0x98-0x9f */ 0xa0, 0xa1, 0x00, 0x00, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */ 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */ 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */ 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */ 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */ 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */ 0x00, 0xe1, 0xe2, 0x00, 0xe4, 0xe4, 0x00, 0x00, /* 0xe0-0xe7 */ 0xe8, 0xe9, 0xea, 0x00, 0xec, 0xe8, 0x00, 0xef, /* 0xe8-0xef */ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */ 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */ }; static int uni2char(wchar_t uni, unsigned char *out, int boundlen) { const unsigned char *uni2charset; unsigned char cl = uni & 0x00ff; unsigned char ch = (uni & 0xff00) >> 8; if (boundlen <= 0) return -ENAMETOOLONG; uni2charset = page_uni2charset[ch]; if (uni2charset && uni2charset[cl]) out[0] = uni2charset[cl]; else return -EINVAL; return 1; } static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni) { *uni = charset2uni[*rawstring]; if (*uni == 0x0000) return -EINVAL; return 1; } static struct nls_table table = { .charset = "cp863", .uni2char = uni2char, .char2uni = char2uni, .charset2lower = charset2lower, .charset2upper = charset2upper, }; static int __init init_nls_cp863(void) { return register_nls(&table); } static void __exit exit_nls_cp863(void) { unregister_nls(&table); } module_init(init_nls_cp863) module_exit(exit_nls_cp863) MODULE_LICENSE("Dual BSD/GPL");
{ "pile_set_name": "Github" }
// Package api defines the data structure to be used in the request/response // messages between libnetwork and the remote ipam plugin package api import "github.com/docker/libnetwork/ipamapi" // Response is the basic response structure used in all responses type Response struct { Error string } // IsSuccess returns whether the plugin response is successful func (r *Response) IsSuccess() bool { return r.Error == "" } // GetError returns the error from the response, if any. func (r *Response) GetError() string { return r.Error } // GetCapabilityResponse is the response of GetCapability request type GetCapabilityResponse struct { Response RequiresMACAddress bool RequiresRequestReplay bool } // ToCapability converts the capability response into the internal ipam driver capability structure func (capRes GetCapabilityResponse) ToCapability() *ipamapi.Capability { return &ipamapi.Capability{ RequiresMACAddress: capRes.RequiresMACAddress, RequiresRequestReplay: capRes.RequiresRequestReplay, } } // GetAddressSpacesResponse is the response to the ``get default address spaces`` request message type GetAddressSpacesResponse struct { Response LocalDefaultAddressSpace string GlobalDefaultAddressSpace string } // RequestPoolRequest represents the expected data in a ``request address pool`` request message type RequestPoolRequest struct { AddressSpace string Pool string SubPool string Options map[string]string V6 bool } // RequestPoolResponse represents the response message to a ``request address pool`` request type RequestPoolResponse struct { Response PoolID string Pool string // CIDR format Data map[string]string } // ReleasePoolRequest represents the expected data in a ``release address pool`` request message type ReleasePoolRequest struct { PoolID string } // ReleasePoolResponse represents the response message to a ``release address pool`` request type ReleasePoolResponse struct { Response } // RequestAddressRequest represents the expected data in a ``request address`` request message type RequestAddressRequest struct { PoolID string Address string Options map[string]string } // RequestAddressResponse represents the expected data in the response message to a ``request address`` request type RequestAddressResponse struct { Response Address string // in CIDR format Data map[string]string } // ReleaseAddressRequest represents the expected data in a ``release address`` request message type ReleaseAddressRequest struct { PoolID string Address string } // ReleaseAddressResponse represents the response message to a ``release address`` request type ReleaseAddressResponse struct { Response }
{ "pile_set_name": "Github" }
{ "private": true, "name": "fixture-project", "bolt": { "workspaces": ["packages/*"] }, "dependencies": { "react": "^15.6.1" } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: c7ff1896f35a148d8a4c1850f1e8e13d folderAsset: yes timeCreated: 1459934446 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// @flow export const TYPES = { PRIMARY: "primary", SECONDARY: "secondary", CRITICAL: "critical", INLINE: "inline", }; export const TOKENS = { background: "background", backgroundHover: "backgroundHover", backgroundActive: "backgroundActive", foreground: "foreground", foregroundHover: "foregroundHover", foregroundActive: "foregroundActive", marginRightIcon: "marginRightIcon", };
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE article PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN" "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"> <article id="filename_test" last-revision="DEBUG MODE Date: 2000/12/20 12:00:00 $" xmlns:xi="http://www.w3.org/2001/XInclude"> <title>Filename Test</title> <para> filename-1_7.quickbook </para> <bridgehead renderas="sect2" id="filename_test.h0"> <phrase id="filename_test.test_1"/><link linkend="filename_test.test_1">Test 1</link> </bridgehead> <para> sub/filename_include1.quickbook </para> <para> sub/../filename_include2.quickbook </para> <bridgehead renderas="sect2" id="filename_test.h1"> <phrase id="filename_test.test_2"/><link linkend="filename_test.test_2">Test 2</link> </bridgehead> <para> filename_include2.quickbook </para> <bridgehead renderas="sect2" id="filename_test.h2"> <phrase id="filename_test.test_3"/><link linkend="filename_test.test_3">Test 3</link> </bridgehead> <para> sub/filename_include1.quickbook </para> <para> sub/../filename_include2.quickbook </para> <bridgehead renderas="sect2" id="filename_test.h3"> <phrase id="filename_test.test_4"/><link linkend="filename_test.test_4">Test 4</link> </bridgehead> <para> sub/filename_include1.quickbook </para> <para> sub/../filename_include2.quickbook </para> </article>
{ "pile_set_name": "Github" }
// compile // Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // PR61253: gccgo incorrectly parsed the // `RecvStmt = ExpressionList "=" RecvExpr` production. package main func main() { c := make(chan int) v := new(int) b := new(bool) select { case (*v), (*b) = <-c: } }
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.8"/> <title>GLFW: compat.dox File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="extra.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <div class="glfwheader"> <a href="http://www.glfw.org/" id="glfwhome">GLFW</a> <ul class="glfwnavbar"> <li><a href="http://www.glfw.org/documentation.html">Documentation</a></li> <li><a href="http://www.glfw.org/download.html">Download</a></li> <li><a href="http://www.glfw.org/media.html">Media</a></li> <li><a href="http://www.glfw.org/community.html">Community</a></li> </ul> </div> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.8 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>Globals</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Macros</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Modules</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">compat.dox File Reference</div> </div> </div><!--header--> <div class="contents"> </div><!-- contents --> <address class="footer"> <p> Last update on Mon Oct 12 2015 for GLFW 3.1.2 </p> </address> </body> </html>
{ "pile_set_name": "Github" }
from sklearn.ensemble import RandomForestClassifier as RF from xgboost_multi import XGBC from sklearn import cross_validation from sklearn.cross_validation import StratifiedKFold as KFold from sklearn.metrics import log_loss import numpy as np import pandas as pd import pickle # create model_list def get_model_list(): model_list = [] for num_round in [200]: for max_depth in [2]: for eta in [0.25]: for min_child_weight in [2]: for col_sample in [1]: model_list.append((XGBC(num_round = num_round, max_depth = max_depth, eta = eta, min_child_weight = min_child_weight, colsample_bytree = col_sample), 'xgb_tree_%i_depth_%i_lr_%f_child_%i_col_sample_%i'%(num_round, max_depth, eta, min_child_weight,col_sample))) return model_list def gen_data(): # the 4k features! the_train = pickle.load(open('X33_train_reproduce.p','rb')) the_test = pickle.load(open('X33_test_reproduce.p','rb')) # corresponding id and labels Id = pickle.load(open('xid.p','rb')) labels = pickle.load(open('y.p','rb')) Id_test = pickle.load(open('Xt_id.p','rb')) # merge them into pandas join_train = np.column_stack((Id, the_train, labels)) join_test = np.column_stack((Id_test, the_test)) train = pd.DataFrame(join_train, columns=['Id']+['the_fea%i'%i for i in xrange(the_train.shape[1])] + ['Class']) test = pd.DataFrame(join_test, columns=['Id']+['the_fea%i'%i for i in xrange(the_train.shape[1])]) del join_train, join_test # convert into numeric features train = train.convert_objects(convert_numeric=True) test = test.convert_objects(convert_numeric=True) # including more things train_count = pd.read_csv("train_frequency.csv") test_count = pd.read_csv("test_frequency.csv") train = pd.merge(train, train_count, on='Id') test = pd.merge(test, test_count, on='Id') # instr count train_instr_count = pd.read_csv("train_instr_frequency.csv") test_instr_count = pd.read_csv("test_instr_frequency.csv") for n in list(train_instr_count)[1:]: if np.sum(train_instr_count[n]) == 0: del train_instr_count[n] del test_instr_count[n] train_instr_freq = train_instr_count.copy() test_instr_freq = test_instr_count.copy() train_instr_freq.ix[:,1:] = train_instr_freq.ix[:,1:].apply(lambda x: x/np.sum(x), axis = 1) #train_instr_freq = train_instr_freq.replace(np.inf, 0) train_instr_freq = train_instr_freq.replace(np.nan, 0) test_instr_freq.ix[:,1:]=test_instr_freq.ix[:,1:].apply(lambda x: x/np.sum(x), axis = 1) #test_instr_freq = test_instr_freq.replace(np.inf, 0) test_instr_freq = test_instr_freq.replace(np.nan, 0) train = pd.merge(train, train_instr_freq, on='Id') test = pd.merge(test, test_instr_freq, on='Id') ## all right, include more! grams_train = pd.read_csv("train_data_750.csv") grams_test = pd.read_csv("test_data_750.csv") # daf features #train_daf = pd.read_csv("train_daf.csv") #test_daf = pd.read_csv("test_daf.csv") #daf_list = [0,165,91,60,108,84,42,93,152,100] #daf list for 500 grams. # dll features train_dll = pd.read_csv("train_dll.csv") test_dll = pd.read_csv("test_dll.csv") # merge all them #mine = pd.merge(grams_train, train_daf,on='Id') mine = grams_train mine = pd.merge(mine, train_dll, on='Id') mine_labels = pd.read_csv("trainLabels.csv") mine = pd.merge(mine, mine_labels, on='Id') mine_labels = mine.Class mine_Id = mine.Id del mine['Class'] del mine['Id'] mine = mine.as_matrix() #mine_test = pd.merge(grams_test, test_daf,on='Id') mine_test = grams_test mine_test = pd.merge(mine_test, test_dll,on='Id') mine_test_id = mine_test.Id del mine_test['Id'] clf_se = RF(n_estimators=500, n_jobs=-1,random_state = 0) clf_se.fit(mine,mine_labels) mine_train = np.array(clf_se.transform(mine, '1.25*mean')) mine_test = np.array(clf_se.transform(mine_test, '1.25*mean')) train_mine = pd.DataFrame(np.column_stack((mine_Id, mine_train)), columns=['Id']+['mine_'+str(x) for x in xrange(mine_train.shape[1])]).convert_objects(convert_numeric=True) test_mine = pd.DataFrame(np.column_stack((mine_test_id, mine_test)), columns=['Id']+['mine_'+str(x) for x in xrange(mine_test.shape[1])]).convert_objects(convert_numeric=True) train = pd.merge(train, train_mine, on='Id') test = pd.merge(test, test_mine, on='Id') train_image = pd.read_csv("train_asm_image.csv", usecols=['Id']+['asm_%i'%i for i in xrange(800)]) test_image = pd.read_csv("test_asm_image.csv", usecols=['Id']+['asm_%i'%i for i in xrange(800)]) train = pd.merge(train, train_image, on='Id') test = pd.merge(test, test_image, on='Id') return train, test def gen_semi_label(model): # read in data print "read data and prepare semi labels..." train, test = gen_data() X = train.copy() Id = X.Id labels = np.array(X.Class - 1) # for the purpose of using multilogloss fun. del X['Id'] del X['Class'] X = X.as_matrix() X_test = test.copy() id_test = X_test.Id del X_test['Id'] X_test = X_test.as_matrix() clf, clf_name = model print "generating model %s..."%clf_name clf.fit(X, labels) pred = clf.predict_proba(X_test) pred = pred.reshape(X_test.shape[0],9) pred = np.column_stack((id_test, pred)) submission = pd.DataFrame(pred, columns=['Id']+['Prediction%i'%i for i in xrange(1,10)]) submission = submission.convert_objects(convert_numeric=True) #submission.to_csv('model3.csv',index = False) semi_labels = np.array([int(x[-1]) for x in submission.ix[:,1:].idxmax(1)]) semi_labels = np.column_stack((id_test, semi_labels)) semi_labels = pd.DataFrame(semi_labels, columns = ['Id','Class']).convert_objects(convert_numeric=True) print "semi labels are found...." test = pd.merge(test, semi_labels, on='Id', how='inner') #print train.shape, test.shape return train, test def cross_validate(model_list): # read in data #print "read data and prepare modelling..." train, test = gen_semi_label(model_list[0]) X = train Id = X.Id labels = np.array(X.Class - 1) # for the purpose of using multilogloss fun. del X['Id'] del X['Class'] X = X.as_matrix() X_test = test id_test = X_test.Id labels_test = np.array(X_test.Class - 1) del X_test['Id'] del X_test['Class'] X_test = X_test.as_matrix() kf = KFold(labels, n_folds=4) # 4 folds best_score = 1.0 for j, (clf, clf_name) in enumerate(model_list): print "modelling %s"%clf_name stack_train = np.zeros((len(Id),9)) # 9 classes. for i, (train_fold, validate) in enumerate(kf): X_train, X_validate, labels_train, labels_validate = X[train_fold,:], X[validate,:], labels[train_fold], labels[validate] X_train = np.concatenate((X_train, X_test)) labels_train = np.concatenate((labels_train, labels_test)) clf.fit(X_train,labels_train) stack_train[validate] = clf.predict_proba(X_validate) #print "finish one fold..." print multiclass_log_loss(labels, stack_train) def semi_learning(model_list): # read in data #print "read data and prepare modelling..." train, test = gen_semi_label(model_list[0]) X = train Id = X.Id labels = np.array(X.Class - 1) # for the purpose of using multilogloss fun. del X['Id'] del X['Class'] X = X.as_matrix() X_test = test id_test = X_test.Id labels_test = np.array(X_test.Class - 1) del X_test['Id'] del X_test['Class'] X_test = X_test.as_matrix() kf = KFold(labels_test, n_folds=4) # 4 folds for j, (clf, clf_name) in enumerate(model_list): print "modelling %s"%clf_name stack_train = np.zeros((len(id_test),9)) # 9 classes. for i, (train_fold, validate) in enumerate(kf): X_train, X_validate, labels_train, labels_validate = X_test[train_fold,:], X_test[validate,:], labels_test[train_fold], labels_test[validate] X_train = np.concatenate((X, X_train)) labels_train = np.concatenate((labels, labels_train)) clf.fit(X_train,labels_train) stack_train[validate] = clf.predict_proba(X_validate).reshape(X_validate.shape[0],9) pred = np.column_stack((id_test, stack_train)) submission = pd.DataFrame(pred, columns=['Id']+['Prediction%i'%i for i in xrange(1,10)]) submission = submission.convert_objects(convert_numeric=True) submission.to_csv('submission.csv',index = False) def multiclass_log_loss(y_true, y_pred, eps=1e-15): """Multi class version of Logarithmic Loss metric. https://www.kaggle.com/wiki/MultiClassLogLoss Parameters ---------- y_true : array, shape = [n_samples] true class, intergers in [0, n_classes - 1) y_pred : array, shape = [n_samples, n_classes] Returns ------- loss : float """ predictions = np.clip(y_pred, eps, 1 - eps) # normalize row sums to 1 predictions /= predictions.sum(axis=1)[:, np.newaxis] actual = np.zeros(y_pred.shape) n_samples = actual.shape[0] actual[np.arange(n_samples), y_true.astype(int)] = 1 vectsum = np.sum(actual * np.log(predictions)) loss = -1.0 / n_samples * vectsum return loss if __name__ == '__main__': model_list = get_model_list() #cross_validate(model_list) semi_learning(model_list) print "ALL DONE!!!"
{ "pile_set_name": "Github" }
/*========================================================================= Program: ParaView Module: pqPropertyManager.cxx Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS 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. =========================================================================*/ // self include #include "pqPropertyManager.h" // Qt includes #include <QApplication> #include <QByteArray> #include <QMultiMap> // ParaView includes #include "pqPropertyLinks.h" //----------------------------------------------------------------------------- pqPropertyManager::pqPropertyManager(QObject* p) : QObject(p) { this->Links = new pqPropertyLinks(); this->Links->setUseUncheckedProperties(true); this->Links->setAutoUpdateVTKObjects(false); QObject::connect(this->Links, SIGNAL(qtWidgetChanged()), this, SLOT(propertyChanged())); this->Modified = false; } //----------------------------------------------------------------------------- pqPropertyManager::~pqPropertyManager() { delete this->Links; this->Links = NULL; } //----------------------------------------------------------------------------- void pqPropertyManager::registerLink(QObject* qObject, const char* qProperty, const char* signal, vtkSMProxy* Proxy, vtkSMProperty* Property, int Index) { this->Links->addPropertyLink(qObject, qProperty, signal, Proxy, Property, Index); } //----------------------------------------------------------------------------- void pqPropertyManager::unregisterLink(QObject* qObject, const char* qProperty, const char* signal, vtkSMProxy* Proxy, vtkSMProperty* Property, int Index) { this->Links->removePropertyLink(qObject, qProperty, signal, Proxy, Property, Index); } //----------------------------------------------------------------------------- void pqPropertyManager::removeAllLinks() { this->Links->removeAllPropertyLinks(); } //----------------------------------------------------------------------------- void pqPropertyManager::accept() { Q_EMIT this->aboutToAccept(); this->Links->accept(); Q_EMIT this->accepted(); this->Modified = false; } //----------------------------------------------------------------------------- void pqPropertyManager::reject() { this->Links->reset(); Q_EMIT this->rejected(); this->Modified = false; } //----------------------------------------------------------------------------- void pqPropertyManager::propertyChanged() { this->Modified = true; Q_EMIT this->modified(); } //----------------------------------------------------------------------------- bool pqPropertyManager::isModified() const { return this->Modified; }
{ "pile_set_name": "Github" }
// // CKDiscoverAllContactsOperation.h // CloudKit // // Copyright (c) 2014 Apple Inc. All rights reserved. // #import <Foundation/Foundation.h> #import <CloudKit/CKOperation.h> @class CKDiscoveredUserInfo; /* Finds all discoverable users in the device's address book. No Address Book access dialog will be displayed */ NS_ASSUME_NONNULL_BEGIN NS_CLASS_AVAILABLE(10_10, 8_0) __TVOS_UNAVAILABLE @interface CKDiscoverAllContactsOperation : CKOperation - (instancetype)init NS_DESIGNATED_INITIALIZER; @property (nonatomic, copy, nullable) void (^discoverAllContactsCompletionBlock)(NSArray <CKDiscoveredUserInfo *> * __nullable userInfos, NSError * __nullable operationError); @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
var convert = require('./convert'), func = convert('sortedLastIndexBy', require('../sortedLastIndexBy')); func.placeholder = require('./placeholder'); module.exports = func;
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="DDDSample.Domain" namespace="DDDSample.Domain.Cargo" auto-import="false" schema="domain"> <class name="Cargo" table="Cargo"> <id type="Guid"> <column name="Id" /> <generator class="guid"></generator> </id> <component name="TrackingId" update="false" class="TrackingId"> <property name="_idString" column="TrackingId" not-null="true" access="field"/> </component> <component name="RouteSpecification" class="RouteSpecification" access="field"> <many-to-one name="_origin" column="SpecOriginId" class="DDDSample.Domain.Location.Location" access="field" not-null="true"/> <many-to-one name="_destination" column="SpecDestinationId" class="DDDSample.Domain.Location.Location" access="field" not-null="true"/> <property name="_arrivalDeadline" column="SpecArrivalDeadline" not-null="true" access="field"/> </component> <component name="Itinerary" class="Itinerary" access="field"> <list name="Legs" lazy="true" cascade="all" access="field" table="Leg"> <key column="CargoId"/> <index column="LegIndex"/> <composite-element class="Leg"> <many-to-one name="_loadLocation" column="LoadLocation" class="DDDSample.Domain.Location.Location" access="field"/> <many-to-one name="_unloadLocation" column="UnloadLocation" class="DDDSample.Domain.Location.Location" access="field"/> <property name="_loadDate" column="LoadDate" access="field"/> <property name="_unloadDate" column="UnloadDate" access="field"/> </composite-element> </list> </component> <many-to-one name="_lastHandlingEvent" access="field" class="HandlingEvent" cascade="all-delete-orphan" column="LastHandlingEvent"/> <bag name="_handlingEvents" access="field" lazy="true" cascade="all-delete-orphan"> <key column="CargoId"/> <one-to-many class="HandlingEvent"/> </bag> </class> </hibernate-mapping>
{ "pile_set_name": "Github" }
# From https://sourceforge.net/projects/dc3dd/files/dc3dd/7.2/ sha1 1bfe81a921a8473a6ecb46f328ecaab761afb55d dc3dd-7.2.641.tar.xz # Locally computed sha256 7f50aadc38649845ab11014d11013928411c9d2128c941e9630939d4c28cae6d dc3dd-7.2.641.tar.xz sha256 8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903 COPYING
{ "pile_set_name": "Github" }
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ #include "freespace.h" #include "gamesnd/gamesnd.h" #include "globalincs/systemvars.h" #include "hud/hudets.h" #include "io/timer.h" #include "localization/localize.h" #include "object/object.h" #include "object/objectshield.h" #include "ship/ship.h" #include "ship/subsysdamage.h" #include "weapon/emp.h" #include "weapon/weapon.h" float Energy_levels[NUM_ENERGY_LEVELS] = {0.0f, 0.0833f, 0.167f, 0.25f, 0.333f, 0.417f, 0.5f, 0.583f, 0.667f, 0.75f, 0.833f, 0.9167f, 1.0f}; bool Weapon_energy_cheat = false; // ------------------------------------------------------------------------------------------------- // ets_init_ship() is called by a ship when it is created (effectively, for every ship at the start // of a mission). This will set the default charge rates for the different systems and initialize // the weapon energy reserve. // void ets_init_ship(object* obj) { ship* sp; // fred should bail here if(Fred_running){ return; } Assert(obj->type == OBJ_SHIP); sp = &Ships[obj->instance]; sp->weapon_energy = Ship_info[sp->ship_info_index].max_weapon_reserve; if ((sp->flags[Ship::Ship_Flags::No_ets]) == 0) { sp->next_manage_ets = timestamp(AI_MODIFY_ETS_INTERVAL); } else { sp->next_manage_ets = -1; } set_default_recharge_rates(obj); } // ------------------------------------------------------------------------------------------------- // update_ets() is called once per frame for every OBJ_SHIP in the game. The amount of energy // to send to the weapons and shields is calculated, and the top ship speed is calculated. The // amount of time elapsed from the previous call is passed in as the parameter fl_frametime. // // parameters: obj ==> object that is updating their energy system // fl_frametime ==> game frametime (in seconds) // void update_ets(object* objp, float fl_frametime) { float max_new_shield_energy, max_new_weapon_energy, _ss; if ( fl_frametime <= 0 ){ return; } ship* ship_p = &Ships[objp->instance]; ship_info* sinfo_p = &Ship_info[ship_p->ship_info_index]; float max_g=sinfo_p->max_weapon_reserve; if ( ship_p->flags[Ship::Ship_Flags::Dying] ){ return; } if ( sinfo_p->power_output == 0 ){ return; } // new_energy = fl_frametime * sinfo_p->power_output; // update weapon energy max_new_weapon_energy = fl_frametime * ship_p->max_weapon_regen_per_second * max_g; if ( objp->flags[Object::Object_Flags::Player_ship] ) { ship_p->weapon_energy += Energy_levels[ship_p->weapon_recharge_index] * max_new_weapon_energy * The_mission.ai_profile->weapon_energy_scale[Game_skill_level]; } else { ship_p->weapon_energy += Energy_levels[ship_p->weapon_recharge_index] * max_new_weapon_energy; } if ( ship_p->weapon_energy > sinfo_p->max_weapon_reserve ){ ship_p->weapon_energy = sinfo_p->max_weapon_reserve; } float shield_delta; max_new_shield_energy = fl_frametime * ship_p->max_shield_regen_per_second * shield_get_max_strength(objp, true); // recharge rate is unaffected by $Max Shield Recharge if ( objp->flags[Object::Object_Flags::Player_ship] ) { shield_delta = Energy_levels[ship_p->shield_recharge_index] * max_new_shield_energy * The_mission.ai_profile->shield_energy_scale[Game_skill_level]; } else { shield_delta = Energy_levels[ship_p->shield_recharge_index] * max_new_shield_energy; } shield_add_strength(objp, shield_delta); // if strength now exceeds max, scale back segments proportionally float max_shield = shield_get_max_strength(objp); if ( (_ss = shield_get_strength(objp)) > max_shield ){ for (int i=0; i<objp->n_quadrants; i++){ objp->shield_quadrant[i] *= max_shield / _ss; } } // calculate the top speed of the ship based on the energy flow to engines float y = Energy_levels[ship_p->engine_recharge_index]; ship_p->current_max_speed = ets_get_max_speed(objp, y); // AL 11-15-97: Rules for engine strength affecting max speed: // 1. if strength >= 0.5 no affect // 2. if strength < 0.5 then max_speed = sqrt(strength) // // This will translate to 71% max speed at 50% engines, and 31% max speed at 10% engines // float strength = ship_get_subsystem_strength(ship_p, SUBSYSTEM_ENGINE); // don't let engine strength affect max speed when playing on lowest skill level if ( (objp != Player_obj) || (Game_skill_level > 0) ) { if ( strength < SHIP_MIN_ENGINES_FOR_FULL_SPEED ) { ship_p->current_max_speed *= fl_sqrt(strength); } } if ( timestamp_elapsed(ship_p->next_manage_ets) ) { if ( !(objp->flags[Object::Object_Flags::Player_ship]) ) { ai_manage_ets(objp); ship_p->next_manage_ets = timestamp(AI_MODIFY_ETS_INTERVAL); } else { if ( Weapon_energy_cheat ){ ship_p->weapon_energy = sinfo_p->max_weapon_reserve; } } } } float ets_get_max_speed(object* objp, float engine_energy) { Assertion(objp != NULL, "Invalid object pointer passed!"); Assertion(objp->type == OBJ_SHIP, "Object needs to be a ship object!"); Assertion(engine_energy >= 0.0f && engine_energy <= 1.0f, "Invalid float passed, needs to be in [0, 1], was %f!", engine_energy); ship* shipp = &Ships[objp->instance]; ship_info* sip = &Ship_info[shipp->ship_info_index]; // check for a shortcuts first before doing linear interpolation if ( engine_energy == Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX] ){ return sip->max_speed; } else if ( engine_energy == 0.0f ){ return 0.5f * sip->max_speed; } else if ( engine_energy == 1.0f ){ return sip->max_overclocked_speed; } else { // do a linear interpolation to find the current max speed, using points (0,1/2 default_max_speed) (.333,default_max_speed) // x = x1 + (y-y1) * (x2-x1) / (y2-y1); if ( engine_energy < Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX] ){ return 0.5f*sip->max_speed + (engine_energy * (0.5f*sip->max_speed) ) / Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX]; } else { // do a linear interpolation to find the current max speed, using points (.333,default_max_speed) (1,max_overclock_speed) return sip->max_speed + (engine_energy - Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX]) * (sip->max_overclocked_speed - sip->max_speed) / (1.0f - Energy_levels[INTIAL_ENGINE_RECHARGE_INDEX]); } } } // ------------------------------------------------------------------------------------------------- // ai_manage_ets() will determine if a ship should modify it's energy transfer percentages, or // transfer energy from shields->weapons or from weapons->shields // // minimum level rule constants #define SHIELDS_MIN_LEVEL_PERCENT 0.3f #define WEAPONS_MIN_LEVEL_PERCENT 0.3f // maximum level rule constants #define SHIELDS_MAX_LEVEL_PERCENT 0.8f #define WEAPONS_MAX_LEVEL_PERCENT 0.8f // emergency rule constants #define SHIELDS_EMERG_LEVEL_PERCENT 0.10f #define WEAPONS_EMERG_LEVEL_PERCENT 0.05f // need this, or ai's tend to totally eliminate engine power! #define MIN_ENGINE_RECHARGE_INDEX 3 #define DEFAULT_CHARGE_INDEX 4 #define NORMAL_TOLERANCE_PERCENT .10f void ai_manage_ets(object* obj) { ship* ship_p = &Ships[obj->instance]; ship_info* ship_info_p = &Ship_info[ship_p->ship_info_index]; if ( ship_info_p->power_output == 0 ) return; if (ship_p->flags[Ship::Ship_Flags::Dying]) return; // check if any of the three systems are not being used. If so, don't allow energy management. if ( !ship_p->ship_max_shield_strength || !ship_info_p->max_speed || !ship_info_p->max_weapon_reserve) return; float shield_left_percent = get_shield_pct(obj); float weapon_left_percent = ship_p->weapon_energy/ship_info_p->max_weapon_reserve; // maximum level check // MK, changed these, might as well let them go up to 100% if nothing else needs the recharge ability. if ( weapon_left_percent == 1.0f) { decrease_recharge_rate(obj, WEAPONS); } if (!(obj->flags[Object::Object_Flags::No_shields]) && (shield_left_percent == 1.0f)) { decrease_recharge_rate(obj, SHIELDS); } // minimum check if (!(obj->flags[Object::Object_Flags::No_shields]) && (shield_left_percent < SHIELDS_MIN_LEVEL_PERCENT)) { if ( weapon_left_percent > WEAPONS_MIN_LEVEL_PERCENT ) increase_recharge_rate(obj, SHIELDS); } if ( weapon_left_percent < WEAPONS_MIN_LEVEL_PERCENT ) { increase_recharge_rate(obj, WEAPONS); } if ( ship_p->engine_recharge_index < MIN_ENGINE_RECHARGE_INDEX ) { increase_recharge_rate(obj, ENGINES); } // emergency check if (!(obj->flags[Object::Object_Flags::No_shields])) { if ( shield_left_percent < SHIELDS_EMERG_LEVEL_PERCENT ) { if (ship_p->target_shields_delta == 0.0f) transfer_energy_to_shields(obj); } else if ( weapon_left_percent < WEAPONS_EMERG_LEVEL_PERCENT ) { if ( shield_left_percent > SHIELDS_MIN_LEVEL_PERCENT || weapon_left_percent <= 0.01 ) // dampen ai enthusiasm for sucking energy to weapons transfer_energy_to_weapons(obj); } // check for return to normal values if ( fl_abs( shield_left_percent - 0.5f ) < NORMAL_TOLERANCE_PERCENT ) { if ( ship_p->shield_recharge_index > DEFAULT_CHARGE_INDEX ) decrease_recharge_rate(obj, SHIELDS); else if ( ship_p->shield_recharge_index < DEFAULT_CHARGE_INDEX ) increase_recharge_rate(obj, SHIELDS); } } if ( fl_abs( weapon_left_percent - 0.5f ) < NORMAL_TOLERANCE_PERCENT ) { if ( ship_p->weapon_recharge_index > DEFAULT_CHARGE_INDEX ) decrease_recharge_rate(obj, WEAPONS); else if ( ship_p->weapon_recharge_index < DEFAULT_CHARGE_INDEX ) increase_recharge_rate(obj, WEAPONS); } } // ------------------------------------------------------------------------------------------------- // set_default_recharge_rates() will set the charge levels for the weapons, shields and // engines to their default levels void set_default_recharge_rates(object* obj) { int ship_properties; ship* ship_p = &Ships[obj->instance]; ship_info* ship_info_p = &Ship_info[ship_p->ship_info_index]; if ( ship_info_p->power_output == 0 ) return; ship_properties = 0; if (ship_has_energy_weapons(ship_p)) ship_properties |= HAS_WEAPONS; if (!(obj->flags[Object::Object_Flags::No_shields])) ship_properties |= HAS_SHIELDS; if (ship_has_engine_power(ship_p)) ship_properties |= HAS_ENGINES; // the default charge rate depends on what systems are on each ship switch ( ship_properties ) { case HAS_ENGINES | HAS_WEAPONS | HAS_SHIELDS: ship_p->shield_recharge_index = INTIAL_SHIELD_RECHARGE_INDEX; ship_p->weapon_recharge_index = INTIAL_WEAPON_RECHARGE_INDEX; ship_p->engine_recharge_index = INTIAL_ENGINE_RECHARGE_INDEX; break; case HAS_ENGINES | HAS_SHIELDS: ship_p->shield_recharge_index = ONE_HALF_INDEX; ship_p->weapon_recharge_index = ZERO_INDEX; ship_p->engine_recharge_index = ONE_HALF_INDEX; break; case HAS_WEAPONS | HAS_SHIELDS: ship_p->shield_recharge_index = ONE_HALF_INDEX; ship_p->weapon_recharge_index = ONE_HALF_INDEX; ship_p->engine_recharge_index = ZERO_INDEX; break; case HAS_ENGINES | HAS_WEAPONS: ship_p->shield_recharge_index = ZERO_INDEX; ship_p->weapon_recharge_index = ONE_HALF_INDEX; ship_p->engine_recharge_index = ONE_HALF_INDEX; break; case HAS_SHIELDS: ship_p->shield_recharge_index = ALL_INDEX; ship_p->weapon_recharge_index = ZERO_INDEX; ship_p->engine_recharge_index = ZERO_INDEX; break; case HAS_ENGINES: ship_p->shield_recharge_index = ZERO_INDEX; ship_p->weapon_recharge_index = ZERO_INDEX; ship_p->engine_recharge_index = ALL_INDEX; break; case HAS_WEAPONS: ship_p->shield_recharge_index = ZERO_INDEX; ship_p->weapon_recharge_index = ALL_INDEX; ship_p->engine_recharge_index = ZERO_INDEX; break; default: Int3(); // if no systems, power output should be zero, and this funtion shouldn't be called break; } // end switch } // ------------------------------------------------------------------------------------------------- // increase_recharge_rate() will increase the energy flow to the specified system (one of // WEAPONS, SHIELDS or ENGINES). The increase in energy will result in a decrease to // the other two systems. void increase_recharge_rate(object* obj, SYSTEM_TYPE ship_system) { int *gain_index=NULL, *lose_index1=NULL, *lose_index2=NULL, *tmp=NULL; int count=0; ship *ship_p = &Ships[obj->instance]; if (ship_p->flags[Ship::Ship_Flags::No_ets]) return; switch ( ship_system ) { case WEAPONS: if ( !ship_has_energy_weapons(ship_p) ) return; gain_index = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) lose_index1 = NULL; else lose_index1 = &ship_p->shield_recharge_index; if ( !ship_has_engine_power(ship_p) ) lose_index2 = NULL; else lose_index2 = &ship_p->engine_recharge_index; break; case SHIELDS: if ( obj->flags[Object::Object_Flags::No_shields] ) return; gain_index = &ship_p->shield_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) lose_index1 = NULL; else lose_index1 = &ship_p->weapon_recharge_index; if ( !ship_has_engine_power(ship_p) ) lose_index2 = NULL; else lose_index2 = &ship_p->engine_recharge_index; break; case ENGINES: if ( !ship_has_engine_power(ship_p) ) return; gain_index = &ship_p->engine_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) lose_index1 = NULL; else lose_index1 = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) lose_index2 = NULL; else lose_index2 = &ship_p->shield_recharge_index; break; } // end switch // return if we can't transfer energy if (!lose_index1 && !lose_index2) return; // already full, nothing to do count = MAX_ENERGY_INDEX - *gain_index; if ( count > 2 ) count = 2; if ( count <= 0 ) { if ( obj == Player_obj ) { snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); } return; } *gain_index += count; // ensure that the highest lose index takes the first decrease if ( lose_index1 && lose_index2 ) { if ( *lose_index1 < *lose_index2 ) { tmp = lose_index1; lose_index1 = lose_index2; lose_index2 = tmp; } } int sanity = 0; while(count > 0) { if ( lose_index1 && *lose_index1 > 0 ) { *lose_index1 -= 1; count--; } if ( count <= 0 ) break; if ( lose_index2 && *lose_index2 > 0 ) { *lose_index2 -= 1; count--; } if ( sanity++ > 10 ) { Int3(); // get Alan break; } } if ( obj == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS), 0.0f ); } // ------------------------------------------------------------------------------------------------- // decrease_recharge_rate() will decrease the energy flow to the specified system (one of // WEAPONS, SHIELDS or ENGINES). The decrease in energy will result in an increase to // the other two systems. void decrease_recharge_rate(object* obj, SYSTEM_TYPE ship_system) { int *lose_index=NULL, *gain_index1=NULL, *gain_index2=NULL, *tmp=NULL; int count; ship *ship_p = &Ships[obj->instance]; if (ship_p->flags[Ship::Ship_Flags::No_ets]) return; switch ( ship_system ) { case WEAPONS: if ( !ship_has_energy_weapons(ship_p) ) return; lose_index = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) gain_index1 = NULL; else gain_index1 = &ship_p->shield_recharge_index; if ( !ship_has_engine_power(ship_p) ) gain_index2 = NULL; else gain_index2 = &ship_p->engine_recharge_index; break; case SHIELDS: if ( obj->flags[Object::Object_Flags::No_shields] ) return; lose_index = &ship_p->shield_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) gain_index1 = NULL; else gain_index1 = &ship_p->weapon_recharge_index; if ( !ship_has_engine_power(ship_p) ) gain_index2 = NULL; else gain_index2 = &ship_p->engine_recharge_index; break; case ENGINES: if ( !ship_has_engine_power(ship_p) ) return; lose_index = &ship_p->engine_recharge_index; if ( !ship_has_energy_weapons(ship_p) ) gain_index1 = NULL; else gain_index1 = &ship_p->weapon_recharge_index; if ( obj->flags[Object::Object_Flags::No_shields] ) gain_index2 = NULL; else gain_index2 = &ship_p->shield_recharge_index; break; } // end switch // return if we can't transfer energy if (!gain_index1 && !gain_index2) return; // check how much there is to lose count = MIN(2, *lose_index); if ( count <= 0 ) { if ( obj == Player_obj ) { snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); } return; } *lose_index -= count; // make sure that the gain starts with the system which needs it most if ( gain_index1 && gain_index2 ) { if ( *gain_index1 > *gain_index2 ) { tmp = gain_index1; gain_index1 = gain_index2; gain_index2 = tmp; } } int sanity=0; while(count > 0) { if ( gain_index1 && *gain_index1 < MAX_ENERGY_INDEX ) { *gain_index1 += 1; count--; } if ( count <= 0 ) break; if ( gain_index2 && *gain_index2 < MAX_ENERGY_INDEX ) { *gain_index2 += 1; count--; } if ( sanity++ > 10 ) { Int3(); // get Alan break; } } if ( obj == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS), 0.0f ); } void transfer_energy_weapon_common(object *objp, float from_field, float to_field, float *from_delta, float *to_delta, float max, float scale) { float delta; delta = from_field * ENERGY_DIVERT_DELTA * scale; if (to_field + *to_delta + delta > max) delta = max - to_field - *to_delta; if ( delta > 0 ) { if ( objp == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS), 0.0f ); if (delta > from_field) delta = from_field; *to_delta += delta; *from_delta -= delta; } else if ( objp == Player_obj ) snd_play( gamesnd_get_game_sound(GameSounds::ENERGY_TRANS_FAIL), 0.0f ); } // ------------------------------------------------------------------------------------------------- // transfer_energy_to_shields() will transfer ENERGY_DIVERT_DELTA percent of weapon energy // to shield energy. void transfer_energy_to_shields(object* obj) { ship* ship_p = &Ships[obj->instance]; if (ship_p->flags[Ship::Ship_Flags::Dying]) return; if ( !ship_has_energy_weapons(ship_p) || obj->flags[Object::Object_Flags::No_shields] ) { return; } transfer_energy_weapon_common(obj, ship_p->weapon_energy, shield_get_strength(obj), &ship_p->target_weapon_energy_delta, &ship_p->target_shields_delta, shield_get_max_strength(obj), 0.5f); } // ------------------------------------------------------------------------------------------------- // transfer_energy_to_weapons() will transfer ENERGY_DIVERT_DELTA percent of shield energy // to weapon energy. void transfer_energy_to_weapons(object* obj) { ship* ship_p = &Ships[obj->instance]; ship_info* sinfo_p = &Ship_info[ship_p->ship_info_index]; if (ship_p->flags[Ship::Ship_Flags::Dying]) return; if ( !ship_has_energy_weapons(ship_p) || obj->flags[Object::Object_Flags::No_shields] ) { return; } transfer_energy_weapon_common(obj, shield_get_strength(obj), ship_p->weapon_energy, &ship_p->target_shields_delta, &ship_p->target_weapon_energy_delta, sinfo_p->max_weapon_reserve, 1.0f); } /** * decrease one ets index to zero & adjust others up */ void zero_one_ets (int *reduce, int *add1, int *add2) { int *tmp; // add to the smallest index 1st if (*add1 > *add2) { tmp = add1; add1 = add2; add2 = tmp; } while (*reduce > ZERO_INDEX) { if (*add1 < ALL_INDEX) { ++*add1; --*reduce; } if (*reduce <= ZERO_INDEX) { break; } if (*add2 < ALL_INDEX) { ++*add2; --*reduce; } } } /** * ensure input ETS indexs are valid. * If not, "fix" them by moving outliers towards the middle index */ void sanity_check_ets_inputs(int (&ets_indexes)[num_retail_ets_gauges]) { int i; int ets_delta = MAX_ENERGY_INDEX - ets_indexes[ENGINES] - ets_indexes[SHIELDS] - ets_indexes[WEAPONS]; if ( ets_delta != 0 ) { if ( ets_delta > 0) { // add to lowest indexes while ( ets_delta != 0 ) { int lowest_val = MAX_ENERGY_INDEX; int lowest_idx = 0; for (i = 0; i < num_retail_ets_gauges; ++i) { if (ets_indexes[i] <= lowest_val ) { lowest_val = ets_indexes[i]; lowest_idx = i; } } ++ets_indexes[lowest_idx]; --ets_delta; } } else { // remove from highest indexes while ( ets_delta != 0 ) { int highest_val = 0; int highest_idx = 0; for (i = 0; i < num_retail_ets_gauges; ++i) { if (ets_indexes[i] >= highest_val ) { highest_val = ets_indexes[i]; highest_idx = i; } } --ets_indexes[highest_idx]; ++ets_delta; } } } } /** * adjust input ETS indexes to handle missing systems on the target ship * return true if indexes are valid to be set */ bool validate_ship_ets_indxes(const int &ship_idx, int (&ets_indexes)[num_retail_ets_gauges]) { if (ship_idx < 0) { return false; } if (Ships[ship_idx].objnum < 0) { return false; } ship *ship_p = &Ships[ship_idx]; if (ship_p->flags[Ship::Ship_Flags::No_ets]) return false; // handle ships that are missing parts of the ETS int ship_properties = 0; if (ship_has_energy_weapons(ship_p)) { ship_properties |= HAS_WEAPONS; } if (!(Objects[ship_p->objnum].flags[Object::Object_Flags::No_shields])) { ship_properties |= HAS_SHIELDS; } if (ship_has_engine_power(ship_p)) { ship_properties |= HAS_ENGINES; } switch ( ship_properties ) { case HAS_ENGINES | HAS_WEAPONS | HAS_SHIELDS: // all present, don't change ets indexes break; case HAS_ENGINES | HAS_SHIELDS: zero_one_ets(&ets_indexes[WEAPONS], &ets_indexes[ENGINES], &ets_indexes[SHIELDS]); break; case HAS_WEAPONS | HAS_SHIELDS: zero_one_ets(&ets_indexes[ENGINES], &ets_indexes[SHIELDS], &ets_indexes[WEAPONS]); break; case HAS_ENGINES | HAS_WEAPONS: zero_one_ets(&ets_indexes[SHIELDS], &ets_indexes[ENGINES], &ets_indexes[WEAPONS]); break; case HAS_ENGINES: case HAS_SHIELDS: case HAS_WEAPONS: // can't change anything if only one is active on this ship return false; break; default: Error(LOCATION, "Encountered a ship (%s) with a broken ETS", ship_p->ship_name); break; } return true; } HudGaugeEts::HudGaugeEts(): HudGauge(HUD_OBJECT_ETS_ENGINES, HUD_ETS_GAUGE, false, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255), System_type(0) { } HudGaugeEts::HudGaugeEts(int _gauge_object, int _system_type): HudGauge(_gauge_object, HUD_ETS_GAUGE, false, false, (VM_EXTERNAL | VM_DEAD_VIEW | VM_WARP_CHASE | VM_PADLOCK_ANY | VM_OTHER_SHIP), 255, 255, 255), System_type(_system_type) { } void HudGaugeEts::initBarHeight(int _ets_h) { ETS_bar_h = _ets_h; } void HudGaugeEts::initLetterOffsets(int _x, int _y) { Letter_offsets[0] = _x; Letter_offsets[1] = _y; } void HudGaugeEts::initTopOffsets(int _x, int _y) { Top_offsets[0] = _x; Top_offsets[1] = _y; } void HudGaugeEts::initBottomOffsets(int _x, int _y) { Bottom_offsets[0] = _x; Bottom_offsets[1] = _y; } void HudGaugeEts::initLetter(char _letter) { Letter = _letter; } void HudGaugeEts::initBitmaps(char *fname) { Ets_bar.first_frame = bm_load_animation(fname, &Ets_bar.num_frames); if ( Ets_bar.first_frame < 0 ) { Warning(LOCATION,"Cannot load hud ani: %s\n", fname); } } void HudGaugeEts::render(float /*frametime*/) { } void HudGaugeEts::pageIn() { bm_page_in_aabitmap( Ets_bar.first_frame, Ets_bar.num_frames ); } /** * Draw one ETS bar to screen */ void HudGaugeEts::blitGauge(int index) { int y_start, y_end, clip_h, w, h, x, y; clip_h = fl2i( (1 - Energy_levels[index]) * ETS_bar_h ); bm_get_info(Ets_bar.first_frame,&w,&h); if ( index < NUM_ENERGY_LEVELS-1 ) { // some portion of dark needs to be drawn setGaugeColor(); // draw the top portion x = position[0] + Top_offsets[0]; y = position[1] + Top_offsets[1]; renderBitmapEx(Ets_bar.first_frame,x,y,w,clip_h,0,0); // draw the bottom portion x = position[0] + Bottom_offsets[0]; y = position[1] + Bottom_offsets[1]; y_start = y + (ETS_bar_h - clip_h); y_end = y + ETS_bar_h; renderBitmapEx(Ets_bar.first_frame, x, y_start, w, y_end-y_start, 0, ETS_bar_h-clip_h); } if ( index > 0 ) { if ( maybeFlashSexp() == 1 ) { setGaugeColor(HUD_C_DIM); // hud_set_dim_color(); } else { setGaugeColor(HUD_C_BRIGHT); // hud_set_bright_color(); } // some portion of recharge needs to be drawn // draw the top portion x = position[0] + Top_offsets[0]; y = position[1] + Top_offsets[1]; y_start = y + clip_h; y_end = y + ETS_bar_h; renderBitmapEx(Ets_bar.first_frame+1, x, y_start, w, y_end-y_start, 0, clip_h); // draw the bottom portion x = position[0] + Bottom_offsets[0]; y = position[1] + Bottom_offsets[1]; renderBitmapEx(Ets_bar.first_frame+2, x,y,w,ETS_bar_h-clip_h,0,0); } } /** * Default ctor for retail ETS gauge * 2nd arg (0) is not used */ HudGaugeEtsRetail::HudGaugeEtsRetail(): HudGaugeEts(HUD_OBJECT_ETS_RETAIL, 0) { } /** * Render the ETS retail gauge to the screen (weapon+shield+engine) */ void HudGaugeEtsRetail::render(float /*frametime*/) { int i; int initial_position; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; setGaugeColor(); // draw the letters for the gauges first, before any clipping occurs // skip letter for any missing gauges (max one, see check above) initial_position = 0; if (ship_has_energy_weapons(ship_p)) { Letter = Letters[0]; position[0] = Gauge_positions[initial_position++]; renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); } if (!(Player_obj->flags[Object::Object_Flags::No_shields])) { Letter = Letters[1]; position[0] = Gauge_positions[initial_position++]; renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); } if (ship_has_engine_power(ship_p)) { Letter = Letters[2]; position[0] = Gauge_positions[initial_position++]; renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); } // draw gauges, skipping any gauge that is missing initial_position = 0; if (ship_has_energy_weapons(ship_p)) { Letter = Letters[0]; position[0] = Gauge_positions[initial_position++]; blitGauge(ship_p->weapon_recharge_index); } if (!(Player_obj->flags[Object::Object_Flags::No_shields])) { Letter = Letters[1]; position[0] = Gauge_positions[initial_position++]; blitGauge(ship_p->shield_recharge_index); } if (ship_has_engine_power(ship_p)) { Letter = Letters[2]; position[0] = Gauge_positions[initial_position++]; blitGauge(ship_p->engine_recharge_index); } } /** * Set ETS letters for retail ETS gauge * Allows for different languages to be used in the hud */ void HudGaugeEtsRetail::initLetters(char *_letters) { int i; for ( i = 0; i < num_retail_ets_gauges; ++i) Letters[i] = _letters[i]; } /** * Set the three possible positions for ETS bars */ void HudGaugeEtsRetail::initGaugePositions(int *_gauge_positions) { int i; for ( i = 0; i < num_retail_ets_gauges; ++i) Gauge_positions[i] = _gauge_positions[i]; } HudGaugeEtsWeapons::HudGaugeEtsWeapons(): HudGaugeEts(HUD_OBJECT_ETS_WEAPONS, (int)WEAPONS) { } void HudGaugeEtsWeapons::render(float /*frametime*/) { int i; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; // no weapon energy, no weapon gauge if (!ship_has_energy_weapons(ship_p)) { return; } setGaugeColor(); // draw the letters for the gauge first, before any clipping occurs renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); // draw the gauges for the weapon system blitGauge(ship_p->weapon_recharge_index); } HudGaugeEtsShields::HudGaugeEtsShields(): HudGaugeEts(HUD_OBJECT_ETS_SHIELDS, (int)SHIELDS) { } void HudGaugeEtsShields::render(float /*frametime*/) { int i; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; // no shields, no shields gauge if (Player_obj->flags[Object::Object_Flags::No_shields]) { return; } setGaugeColor(); // draw the letters for the gauge first, before any clipping occurs renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); // draw the gauge for the shield system blitGauge(ship_p->shield_recharge_index); } HudGaugeEtsEngines::HudGaugeEtsEngines(): HudGaugeEts(HUD_OBJECT_ETS_ENGINES, (int)ENGINES) { } void HudGaugeEtsEngines::render(float /*frametime*/) { int i; ship* ship_p = &Ships[Player_obj->instance]; if ( Ets_bar.first_frame < 0 ) { return; } // if at least two gauges are not shown, don't show any i = 0; if (!ship_has_energy_weapons(ship_p)) i++; if (Player_obj->flags[Object::Object_Flags::No_shields]) i++; if (!ship_has_engine_power(ship_p)) i++; if (i >= 2) return; // no engines, no engine gauge if (!ship_has_engine_power(ship_p)) { return; } setGaugeColor(); // draw the letters for the gauge first, before any clipping occurs renderPrintf(position[0] + Letter_offsets[0], position[1] + Letter_offsets[1], NOX("%c"), Letter); // draw the gauge for the engine system blitGauge(ship_p->engine_recharge_index); }
{ "pile_set_name": "Github" }
: # report which #include files can not compile on their own # takes -v option to display compile failure message and line numbers # $PostgreSQL$ trap "rm -f /tmp/$$.c /tmp/$$.o /tmp/$$ /tmp/$$a" 0 1 2 3 15 find . \( -name CVS -a -prune \) -o -name '*.h' -type f -print | while read FILE do sed 's/->[a-zA-Z0-9_\.]*//g' "$FILE" >/tmp/$$a echo "#include \"postgres.h\"" >/tmp/$$.c echo "#include \"/tmp/$$a\"" >>/tmp/$$.c echo "void include_test(void);" >>/tmp/$$.c echo "void include_test() {" >>/tmp/$$.c pgdefine "$FILE" >>/tmp/$$.c echo "}" >>/tmp/$$.c cc -fsyntax-only -Werror -Wall -Wmissing-prototypes \ -Wmissing-declarations -I/pg/include -I/pg/backend \ -I/pg/interfaces/libpq -I`dirname $FILE` $CFLAGS -c /tmp/$$.c \ -o /tmp/$$.o >/tmp/$$ 2>&1 if [ "$?" -ne 0 ] then echo "$FILE" if [ "$1" = "-v" ] then cat /tmp/$$ nl /tmp/$$.c echo fi fi done
{ "pile_set_name": "Github" }
licenses(["notice"]) # Apache 2.0 package(default_visibility = ["//:internal_users"]) cc_library( name = "component", srcs = ["component.cc"], hdrs = ["component.h"], deps = [":context"], ) cc_test( name = "component_test", srcs = ["component_test.cc"], deps = [ ":component", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "context", srcs = ["context.cc"], hdrs = ["context.h"], deps = [ "@com_google_absl//absl/container:flat_hash_map", "@llvm_git//:codegen", "@llvm_git//:machine_code", "@llvm_git//:support", ], ) cc_test( name = "context_test", srcs = ["context_test.cc"], deps = [ ":context", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "log", srcs = ["log.cc"], hdrs = ["log.h"], deps = [ ":component", ], ) cc_library( name = "log_levels", srcs = ["log_levels.cc"], hdrs = ["log_levels.h"], ) cc_library( name = "simulator", srcs = ["simulator.cc"], hdrs = ["simulator.h"], deps = [ ":component", ":context", ":log", "@llvm_git//:machine_code", "@llvm_git//:support", ], ) cc_test( name = "simulator_test", srcs = ["simulator_test.cc"], deps = [ ":component", ":simulator", "@com_google_googletest//:gtest_main", ], )
{ "pile_set_name": "Github" }
/** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g; module.exports = reEscape;
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CKFinder User's Guide</title> <link href="../../files/other/help.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="../../files/other/help.js"></script> <meta name="robots" content="noindex, nofollow" /> </head> <body> <h1> Help Button</h1> <p> The <strong>Help</strong> button is available in the <strong> <a href="005.html">Toolbar</a></strong> for all CKFinder views. When you click it, the "User's Guide" will open in a new browser tab or window.</p> <p style="text-align: center"> <img src="../../files/images/CKFinder_toolbar_help.png" width="266" height="64" alt="Help button in the CKFinder toolbar" />&nbsp;</p> </body> </html>
{ "pile_set_name": "Github" }
package storage // Copyright 2017 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import ( "fmt" "net/http" "net/url" "strconv" ) // Share represents an Azure file share. type Share struct { fsc *FileServiceClient Name string `xml:"Name"` Properties ShareProperties `xml:"Properties"` Metadata map[string]string } // ShareProperties contains various properties of a share. type ShareProperties struct { LastModified string `xml:"Last-Modified"` Etag string `xml:"Etag"` Quota int `xml:"Quota"` } // builds the complete path for this share object. func (s *Share) buildPath() string { return fmt.Sprintf("/%s", s.Name) } // Create this share under the associated account. // If a share with the same name already exists, the operation fails. // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Share func (s *Share) Create(options *FileRequestOptions) error { extraheaders := map[string]string{} if s.Properties.Quota > 0 { extraheaders["x-ms-share-quota"] = strconv.Itoa(s.Properties.Quota) } params := prepareOptions(options) headers, err := s.fsc.createResource(s.buildPath(), resourceShare, params, mergeMDIntoExtraHeaders(s.Metadata, extraheaders), []int{http.StatusCreated}) if err != nil { return err } s.updateEtagAndLastModified(headers) return nil } // CreateIfNotExists creates this share under the associated account if // it does not exist. Returns true if the share is newly created or false if // the share already exists. // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Create-Share func (s *Share) CreateIfNotExists(options *FileRequestOptions) (bool, error) { extraheaders := map[string]string{} if s.Properties.Quota > 0 { extraheaders["x-ms-share-quota"] = strconv.Itoa(s.Properties.Quota) } params := prepareOptions(options) resp, err := s.fsc.createResourceNoClose(s.buildPath(), resourceShare, params, extraheaders) if resp != nil { defer drainRespBody(resp) if resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusConflict { if resp.StatusCode == http.StatusCreated { s.updateEtagAndLastModified(resp.Header) return true, nil } return false, s.FetchAttributes(nil) } } return false, err } // Delete marks this share for deletion. The share along with any files // and directories contained within it are later deleted during garbage // collection. If the share does not exist the operation fails // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Share func (s *Share) Delete(options *FileRequestOptions) error { return s.fsc.deleteResource(s.buildPath(), resourceShare, options) } // DeleteIfExists operation marks this share for deletion if it exists. // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Delete-Share func (s *Share) DeleteIfExists(options *FileRequestOptions) (bool, error) { resp, err := s.fsc.deleteResourceNoClose(s.buildPath(), resourceShare, options) if resp != nil { defer drainRespBody(resp) if resp.StatusCode == http.StatusAccepted || resp.StatusCode == http.StatusNotFound { return resp.StatusCode == http.StatusAccepted, nil } } return false, err } // Exists returns true if this share already exists // on the storage account, otherwise returns false. func (s *Share) Exists() (bool, error) { exists, headers, err := s.fsc.resourceExists(s.buildPath(), resourceShare) if exists { s.updateEtagAndLastModified(headers) s.updateQuota(headers) } return exists, err } // FetchAttributes retrieves metadata and properties for this share. // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/get-share-properties func (s *Share) FetchAttributes(options *FileRequestOptions) error { params := prepareOptions(options) headers, err := s.fsc.getResourceHeaders(s.buildPath(), compNone, resourceShare, params, http.MethodHead) if err != nil { return err } s.updateEtagAndLastModified(headers) s.updateQuota(headers) s.Metadata = getMetadataFromHeaders(headers) return nil } // GetRootDirectoryReference returns a Directory object at the root of this share. func (s *Share) GetRootDirectoryReference() *Directory { return &Directory{ fsc: s.fsc, share: s, } } // ServiceClient returns the FileServiceClient associated with this share. func (s *Share) ServiceClient() *FileServiceClient { return s.fsc } // SetMetadata replaces the metadata for this share. // // Some keys may be converted to Camel-Case before sending. All keys // are returned in lower case by GetShareMetadata. HTTP header names // are case-insensitive so case munging should not matter to other // applications either. // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/set-share-metadata func (s *Share) SetMetadata(options *FileRequestOptions) error { headers, err := s.fsc.setResourceHeaders(s.buildPath(), compMetadata, resourceShare, mergeMDIntoExtraHeaders(s.Metadata, nil), options) if err != nil { return err } s.updateEtagAndLastModified(headers) return nil } // SetProperties sets system properties for this share. // // Some keys may be converted to Camel-Case before sending. All keys // are returned in lower case by SetShareProperties. HTTP header names // are case-insensitive so case munging should not matter to other // applications either. // // See https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/Set-Share-Properties func (s *Share) SetProperties(options *FileRequestOptions) error { extraheaders := map[string]string{} if s.Properties.Quota > 0 { if s.Properties.Quota > 5120 { return fmt.Errorf("invalid value %v for quota, valid values are [1, 5120]", s.Properties.Quota) } extraheaders["x-ms-share-quota"] = strconv.Itoa(s.Properties.Quota) } headers, err := s.fsc.setResourceHeaders(s.buildPath(), compProperties, resourceShare, extraheaders, options) if err != nil { return err } s.updateEtagAndLastModified(headers) return nil } // updates Etag and last modified date func (s *Share) updateEtagAndLastModified(headers http.Header) { s.Properties.Etag = headers.Get("Etag") s.Properties.LastModified = headers.Get("Last-Modified") } // updates quota value func (s *Share) updateQuota(headers http.Header) { quota, err := strconv.Atoi(headers.Get("x-ms-share-quota")) if err == nil { s.Properties.Quota = quota } } // URL gets the canonical URL to this share. This method does not create a publicly accessible // URL if the share is private and this method does not check if the share exists. func (s *Share) URL() string { return s.fsc.client.getEndpoint(fileServiceName, s.buildPath(), url.Values{}) }
{ "pile_set_name": "Github" }
#include "hunt/hunts/HuntT1055.h" #include <Psapi.h> #pragma pack(push, 8) #include <TlHelp32.h> #pragma pack(pop) #include <Windows.h> #include "util/StringUtils.h" #include "util/ThreadPool.h" #include "util/eventlogs/EventLogs.h" #include "util/log/Log.h" #include "util/processes/ProcessUtils.h" #include "util/wrappers.hpp" #include "pe_sieve.h" #include "pe_sieve_types.h" #include "user/bluespawn.h" extern "C" { void __stdcall PESieve_help(void); DWORD __stdcall PESieve_version(void); pesieve::t_report __stdcall PESieve_scan(pesieve::t_params args); }; namespace Hunts { HuntT1055::HuntT1055() : Hunt(L"T1055 - Process Injection") { dwCategoriesAffected = (DWORD) Category::Processes; dwSourcesInvolved = (DWORD) DataSource::Processes; dwTacticsUsed = (DWORD) Tactic::PrivilegeEscalation | (DWORD) Tactic::DefenseEvasion; } void HuntT1055::HandleReport(OUT std::vector<std::shared_ptr<Detection>>& detections, IN CONST Promise<GenericWrapper<pesieve::ReportEx*>>& promise) { auto __name{ this->name }; auto value{ promise.GetValue() }; if(value) { auto report{ *value }; auto summary{ report->scan_report->generateSummary() }; if(summary.skipped) { LOG_INFO(2, "Skipped scanning " << summary.skipped << " modules in process " << report->scan_report->getPid() << ". This is likely due to use of .NET"); } if(summary.suspicious && !summary.errors) { std::wstring path = StringToWidestring(report->scan_report->mainImagePath); for(auto module : report->scan_report->moduleReports) { if(module->status == pesieve::SCAN_SUSPICIOUS) { CREATE_DETECTION_WITH_CONTEXT(Certainty::Strong, ProcessDetectionData::CreateMemoryDetectionData( report->scan_report->getPid(), path, module->module, static_cast<DWORD>(module->moduleSize), StringToWidestring(module->moduleFile), path), DetectionContext{ name }); } } } } } std::vector<std::shared_ptr<Detection>> HuntT1055::RunHunt(const Scope& scope) { HUNT_INIT(); SUBSECTION_INIT(0, Normal); HandleWrapper snapshot{ CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; if(snapshot) { PROCESSENTRY32W info{}; info.dwSize = sizeof(info); if(Process32FirstW(snapshot, &info)) { std::vector<Promise<GenericWrapper<pesieve::ReportEx*>>> results{}; do { auto pid{ info.th32ProcessID }; if(info.szExeFile == std::wstring{ L"vmmem" }) { LOG_INFO(2, L"Skipping scans for process with PID " << pid << "."); continue; } results.emplace_back( ThreadPool::GetInstance().RequestPromise<GenericWrapper<pesieve::ReportEx*>>([pid]() { pesieve::t_params params{ pid, 3, Bluespawn::aggressiveness == Aggressiveness::Intensive ? pesieve::PE_DNET_NONE : pesieve::PE_DNET_SKIP_HOOKS, pesieve::PE_IMPREC_NONE, true, pesieve::OUT_NO_DIR, Bluespawn::aggressiveness != Aggressiveness::Intensive, Bluespawn::aggressiveness == Aggressiveness::Intensive, Bluespawn::aggressiveness == Aggressiveness::Intensive ? pesieve::PE_IATS_FILTERED : pesieve::PE_IATS_NONE, Bluespawn::aggressiveness == Aggressiveness::Intensive ? pesieve::PE_DATA_SCAN_NO_DEP : pesieve::PE_DATA_NO_SCAN, false, pesieve::PE_DUMP_AUTO, false, 0 }; WRAP(pesieve::ReportEx*, report, scan_and_dump(params), delete data); if(!report) { LOG_INFO(2, "Unable to scan process " << pid << " due to an error in PE-Sieve.dll"); throw std::exception{ "Failed to scan process" }; } return report; })); } while(Process32NextW(snapshot, &info)); for(auto& promise : results) { HandleReport(detections, promise); } } else { auto error{ GetLastError() }; LOG_ERROR("Unable to enumerate processes - Process related hunts will not run." << GetLastError()); } } else { LOG_ERROR("Unable to enumerate processes - Process related hunts will not run."); } SUBSECTION_END(); HUNT_END(); } } // namespace Hunts
{ "pile_set_name": "Github" }
; Project file for Independent JPEG Group's software ; ; This project file is for Atari ST/STE/TT systems using Pure C or Turbo C. ; Thanks to Frank Moehle, B. Setzepfandt, and Guido Vollbeding. ; ; To use this file, rename it to jpegtran.prj. ; If you are using Turbo C, change filenames beginning with "pc..." to "tc..." ; Read installation instructions before trying to make the program! ; ; ; * * * Output file * * * jpegtran.ttp ; ; * * * COMPILER OPTIONS * * * .C[-P] ; absolute calls .C[-M] ; and no string merging, folks .C[-w-cln] ; no "constant is long" warnings .C[-w-par] ; no "parameter xxxx unused" .C[-w-rch] ; no "unreachable code" .C[-wsig] ; warn if significant digits may be lost = ; * * * * List of modules * * * * pcstart.o jpegtran.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h,transupp.h,jversion.h) cdjpeg.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) rdswitch.c (cdjpeg.h,jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jerror.h,cderror.h) transupp.c (jinclude.h,jconfig.h,jpeglib.h,jmorecfg.h,jpegint.h,jerror.h,transupp.h) libjpeg.lib ; built by libjpeg.prj pcstdlib.lib ; standard library pcextlib.lib ; extended library
{ "pile_set_name": "Github" }
import { useEffect, useState } from 'react' import { MockProviders, startMSW, setupRequestHandlers, } from '@redwoodjs/testing' export const StorybookProvider: React.FunctionComponent<{ storyFn: Function id: string }> = ({ storyFn, id }) => { const [loading, setLoading] = useState(true) useEffect(() => { const init = async () => { // Import all the `*.mock.*` files. const reqs = require.context( '~__REDWOOD__USER_WEB_SRC', true, /.+(mock).(js|ts)$/ ) reqs.keys().forEach((r) => { reqs(r) }) await startMSW() setupRequestHandlers() setLoading(false) } init() }, [id]) if (loading) { return null } return <MockProviders>{storyFn()}</MockProviders> }
{ "pile_set_name": "Github" }
/* * Copyright 2000-2016 BitMover, 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. */ #include "sccs.h" #include "nested.h" #include "range.h" typedef struct { u32 show_all:1; /* -a show deleted files */ u32 show_gone:1; /* --show-gone: display gone files */ u32 show_diffs:1; /* -r output in rev diff format */ u32 show_path:1; /* -h show PATHNAME(s, d) */ u32 hide_bk:1; /* --hide-bk: hide BitKeeper/ files */ u32 hide_cset:1; /* -H hide ChangeSet file from file list */ u32 hide_comp:1; /* -H also hide component csets */ u32 BAM:1; /* -B only list BAM files */ u32 nested:1; /* -P recurse into nested components */ u32 standalone:1; /* -S standalone */ u32 elide:1; /* elide files with no diffs (e.g. reverted) */ u32 prefix:1; /* add component prefix */ u32 compat:1; /* --compat: old bugs made new */ u32 chksum:1; /* checksum diff */ u32 stats:1; /* output internal work number(s) */ u32 no_print:1; /* for getting stats, squelch data */ u32 subdirs:1; /* with --dir show subdirs */ char **nav; char **aliases; /* -s limit nested output to aliases */ char *limit_dir; nested *n; /* only if -s (and therefore, -P) */ RANGE rargs; /* revisions */ sccs *s; /* pass through */ hash *seen_dir; } Opts; /* * Cset info accumulated in a weave walk */ typedef struct { char *left1; /* cset rev of newest lower bound */ char *left2; /* cset rev of oldest lower bound */ char *right; /* cset rev of upper bound */ char *leftpath1; /* historical path */ char *leftpath2; /* historical path */ char *rightpath; /* historical path */ char *curpath; /* current path */ hash *keys; /* hash of rkoff -> struct rfile */ int weavelines; /* stats: count how many weave lines read */ /* used by --checksum to get some integrity check */ sum_t wantsum; /* used in chksum calc - sum of right */ sum_t sum; /* computed sum for --checksum */ } rset; /* per-file companion struct to above; the value in '->keys' hash */ typedef struct { u32 rkoff; /* offset to rootkey */ u32 tipoff; /* newest dk for this rootkey (for curpath) */ u32 left1; /* newest lowerbound key */ u32 left2; /* oldest lowerbound key */ u32 right; /* upper bound key */ u8 seen; /* LEFT1, LEFT2, RIGHT bit map */ #define LEFT1 0x01 #define LEFT2 0x02 #define RIGHT 0x04 #define LAST 0x08 } rfile; private void rel_diffs(Opts *opts, rset *data); private void rel_list(Opts *opts, rset *data); private sum_t dodiff(sccs *s, u32 rkoff, u32 loff, u32 roff); private rset *weaveExtract(sccs *s, ser_t left1, ser_t left2, ser_t right, Opts *opts); private rset *initrset(sccs *s, ser_t left1, ser_t left2, ser_t right, Opts *opts); private void freeRset(rset *data); private int deltaSkip(sccs *cset, MDBM *sDB, u32 rkoff, u32 dkoff); private char *dirSlash(char *path); int rset_main(int ac, char **av) { int c; comp *cp; int i; char *p; char *freeme = 0; char s_cset[] = CHANGESET; sccs *s = 0; int rc = 1; rset *data = 0; Opts *opts; longopt lopts[] = { { "checksum", 304 }, // bk rset --show-gone --checksum -ra,b { "elide", 305}, // don't show files without diffs { "hide-bk", 310 }, // strip all BitKeeper/ files (export) { "compat", 320 }, // compat/broken output (undoc) { "prefix", 330 }, // add component prefix (doc)? { "show-gone", 350 }, // undoc, not sure { "stats", 360 }, // undoc, how much we read { "no-print", 370 }, // don't print anything (use w/ stats) { "dir;", 380 }, { "subdirs", 390 }, { "subset;", 's' }, // aliases { "standalone", 'S' }, // this repo only { 0, 0 } }; opts = new(Opts); while ((c = getopt(ac, av, "5aBhHl;PR;r;Ss;U", lopts)) != -1) { unless (c == 'r' || c == 'P' || c == 'l' || c == 's' || c == 'S') { opts->nav = bk_saveArg(opts->nav, av, c); } switch (c) { case '5': break; /* ignored, always on */ case 'B': opts->BAM = 1; break; /* undoc */ case 'a': /* doc 2.0 */ opts->show_all = 1; /* show deleted files */ break; case 'h': /* doc 2.0 */ opts->show_path = 1; /* show historic path */ break; case 'H': /* undoc 2.0 */ opts->hide_cset = 1; /* hide ChangeSet file */ opts->hide_comp = 1; /* hide components */ break; case 'l': if (opts->rargs.rstart) usage(); goto range; case 'P': break; /* old, compat */ case 'r': if (opts->rargs.rstart && !opts->show_diffs) { usage(); } opts->show_diffs = 1; /* doc 2.0 */ range: if (range_addArg(&opts->rargs, optarg, 0)) { usage(); } break; case 'R': if (opts->rargs.rstart) usage(); opts->show_diffs = 1; goto range; case 'S': opts->standalone = 1; break; case 's': opts->aliases = addLine(opts->aliases, strdup(optarg)); break; case 'U': opts->hide_cset = 1; opts->hide_comp = 1; opts->hide_bk = 1; break; break; case 304: // --checksum opts->chksum = 1; break; case 305: // --elide opts->elide = 1; break; case 310: // --hide-bk opts->hide_bk = 1; break; case 320: // --compat opts->compat = 1; break; case 330: // --prefix opts->prefix = 1; break; case 350: // --show-gone opts->show_gone = 1; break; case 360: // --stats opts->stats = 1; break; case 370: // --no-print opts->no_print = 1; opts->hide_cset = 1; break; case 380: // --dir=LIMIT_DIR opts->limit_dir = optarg; break; case 390: // --subdirs opts->subdirs = 1; break; default: bk_badArg(c, av); } } /* must have either a -l or -r */ unless (opts->rargs.rstart) usage(); if (opts->show_diffs) { /* compat: only lower bound and has 1 comma: really a range */ if (!opts->rargs.rstop && (p = strchr(opts->rargs.rstart, ','))) { *p++ = 0; opts->rargs.rstop = p; } } else if (opts->rargs.rstop) { /* -l (!show_diffs) and range (stop defined) is illegal */ usage(); } unless (opts->rargs.rstop) { /* for -l and -r single arg, make it the upper bound */ opts->rargs.rstop = opts->rargs.rstart; opts->rargs.rstart = 0; } /* weed out illegal upper bound; must be single rev */ if (opts->rargs.rstop && strchr(opts->rargs.rstop, ',')) { usage(); } if (opts->subdirs && !opts->limit_dir) usage(); if (opts->standalone && opts->aliases) usage(); opts->nested = bk_nested2root(opts->standalone); if (opts->nested && opts->limit_dir) { // If you know what directory you want, then running over // all components is stupid fprintf(stderr, "%s: --dir=DIR requires -S\n", prog); goto out; } /* Let them use -sHERE by default but ignore it in non-products. */ if (!opts->nested && opts->aliases) { EACH(opts->aliases) { unless (streq(opts->aliases[i], ".") || strieq(opts->aliases[i], "HERE")) { fprintf(stderr, "%s: -sALIAS only allowed in product\n", prog); goto out; } } freeLines(opts->aliases, free); opts->aliases = 0; } opts->s = s = sccs_init(s_cset, SILENT); assert(s); s->idDB = loadDB(IDCACHE, 0, DB_IDCACHE); assert(s->idDB); /* special case - if diff and no lower bound, then parents */ if (opts->show_diffs && !opts->rargs.rstart) { char *revP = 0, *revM = 0; if (sccs_parent_revs(s, opts->rargs.rstop, &revP, &revM)) { goto out; } if (revM && !opts->chksum) { assert(revP); opts->rargs.rstart = freeme = aprintf("%s,%s", revP, revM); free(revP); } else if (revP) { opts->rargs.rstart = freeme = revP; } free(revM); } /* hack: librange doesn't like an empty lower bound for endpoints */ unless (opts->rargs.rstart) opts->rargs.rstart = "1.0"; if (range_process( prog, s, (RANGE_ENDPOINTS|RANGE_RSTART2), &opts->rargs)) { goto out; } unless (data = weaveExtract(s, s->rstart, s->rstart2, s->rstop, opts)) { goto out; } if (opts->aliases) { unless ((opts->n = nested_init(s, 0, 0, NESTED_PENDING)) && !nested_aliases(opts->n, 0, &opts->aliases, start_cwd, 1)) { goto out; } c = 0; EACH_STRUCT(opts->n->comps, cp, i) { if (cp->alias && !C_PRESENT(cp)) { unless (c) { c = 1; fprintf(stderr, "%s: error, the following " "components are not populated:\n", prog); } fprintf(stderr, "\t./%s\n", cp->path); } } if (c) goto out; unless (opts->n->product->alias) opts->hide_cset = 1; } if (opts->show_diffs) { rel_diffs(opts, data); } else { rel_list(opts, data); } if (opts->chksum) { if (data->sum != data->wantsum) { fprintf(stderr, "### Checksum in %s for %s\n", data->curpath ? data->curpath : "repo", data->right); fprintf(stderr, "want sum\t%u\ngot sum\t\t%u\n", data->wantsum, data->sum); rc = 1; goto out; } } if (opts->stats) { fprintf(stderr, "%8u weave data lines read in %s for %s\n", data->weavelines, data->curpath ? data->curpath : "repo", data->right); } rc = 0; out: if (freeme) free(freeme); if (data) freeRset(data); if (opts->s) sccs_free(opts->s); if (opts->aliases) freeLines(opts->aliases, free); if (opts->n) nested_free(opts->n); free(opts); return (rc); } /* * See if there was a change in the file or not. Since the data is * most likely coming from weaveExtract(), a file where nothing * changed will have the same deltakey in left1 and right with no * left2, or the same in all keys. That means no change so it should * not be in the diff. */ #define UNCHANGED(file) ( \ ((((file)->left1 == (file)->right) && \ !(file)->left2) || \ (((file)->left2 == (file)->right) && \ (!(file)->left1 || ((file)->left1 == (file)->left2)))) \ ) \ /* * List the rset output for a cset range left1,left2..right * For compactness, keep things in heap offset form. */ rset_df * rset_diff(sccs *cset, ser_t left1, ser_t left2, ser_t right, int showgone) { Opts opts = {0}; rset *data = 0; rfile *file; rset_df *diff = 0, *d; opts.show_gone = showgone; data = weaveExtract(cset, left1, left2, right, &opts); assert(data); EACH_HASH(data->keys) { file = (rfile *)data->keys->vptr; if (UNCHANGED(file)) continue; d = addArray(&diff, 0); d->rkoff = file->rkoff; d->dkleft1 = file->left1; d->dkleft2 = file->left2; d->dkright = file->right; } freeRset(data); return (diff); } /* * Get checksum of cset d relative to cset base (or root if no base) */ u32 rset_checksum(sccs *cset, ser_t d, ser_t base) { Opts opts = {0}; rset *data = 0; rfile *file; u32 sum = 0; opts.chksum = 1; if (base && (base = sccs_getCksumDelta(cset, base))) { sum = SUM(cset, base); } data = weaveExtract(cset, base, 0, d, &opts); assert(data); EACH_HASH(data->keys) { file = (rfile *)data->keys->vptr; sum += dodiff(cset, file->rkoff, file->left1, file->right); } sum = (sum_t)sum; /* truncate */ freeRset(data); return (sum); } /* * return true if the keys v1 and v2 is the same * XXX TODO: We may need to call samekeystr() in slib.c */ private int is_same(sccs *s, u32 v1, u32 v2) { if (v1 == v2) return (1); if (!v2) return (0); if (!v1) return (0); /* check for poly, since delta keys are not unique in heap */ return (streq(HEAP(s, v1), HEAP(s, v2))); } /* * return true if file is deleted */ int isNullFile(char *rev, char *file) { if (strneq(file, "BitKeeper/deleted/", strlen("BitKeeper/deleted/"))) { return (1); } if (streq(rev, "1.0")) return (1); return (0); } /* * Return a malloced string with the pathname where a file * lives currently. * Returns 0 on error * Returns INVALID for a non-present component */ private char * findPath(Opts *opts, rfile *file) { char *path; char *t; char *rkey = HEAP(opts->s, file->rkoff); /* path == path where file lives currently */ if (path = mdbm_fetch_str(opts->s->idDB, rkey)) { path = strdup(path); } else { if (opts->show_gone) { /* or path where file would be if it was here */ t = HEAP(opts->s, file->tipoff); assert(t); unless (path = key2path(t, 0, 0, 0)) { fprintf(stderr, "rset: Can't find %s\n", t); return (0); } } else { unless (path = key2path(rkey, 0, 0, 0)) { fprintf(stderr, "rset: Can't find %s\n", rkey); return (0); } if (streq(path, GCHANGESET) && proj_isProduct(0) && !streq(rkey, proj_rootkey(0))) { /* * skip missing components * This assumes missing components * won't be in the idcache. */ free(path); return (INVALID); } } } return (path); } private int isIdenticalData(sccs *cset, char *file, u32 start, u32 start2, u32 end) { sccs *s; ser_t d1, d2; FILE *file_1 = 0, *file_2 = 0; char *f1d, *f2d; size_t f1s, f2s; char *sfile; int same = 0; sfile = name2sccs(file); s = sccs_init(sfile, INIT_MUSTEXIST|INIT_NOCKSUM); free(sfile); unless (s) return (0); unless (start2) { /* try to avoid generating files .. */ d1 = sccs_findrev(s, HEAP(cset, start)); d2 = sccs_findrev(s, HEAP(cset, end)); unless (d1 && d2) goto out; d1 = sccs_getCksumDelta(s, d1); d2 = sccs_getCksumDelta(s, d2); /* .. if we know they will be the same */ if (d1 == d2) { same = 1; goto out; } /* .. or if we know they will be different */ if (SUM(s, d1) != SUM(s, d2)) goto out; } file_1 = fmem(); if (sccs_get(s, HEAP(cset, start), start2 ? HEAP(cset, start2) : 0, 0, 0, SILENT, 0, file_1)) { goto out; } file_2 = fmem(); if (sccs_get(s, HEAP(cset, end), 0, 0, 0, SILENT, 0, file_2)) { goto out; } f1d = fmem_peek(file_1, &f1s); f2d = fmem_peek(file_2, &f2s); same = ((f1s == f2s) && !memcmp(f1d, f2d, f1s)); out: sccs_free(s); if (file_1) fclose(file_1); if (file_2) fclose(file_2); return (same); } /* * Convert root/start/end keys to sfile|path1|rev1|path2|rev2 format * If we are rset -l<rev> then start is null, and end is <rev>. * If we are rset -r<rev1>,<rev2> then start is <rev1> and end is <rev2>. */ private void process(Opts *opts, rset *data, rfile *file) { comp *c; char *path0 = 0, *path1 = 0, *path1_2 = 0, *path2 = 0; u32 start, start2, end; char *comppath, *comppath2; char *here, *t; int i; u32 rkoff = file->rkoff; char smd5[MD5LEN], smd5_2[MD5LEN], emd5[MD5LEN]; end = file->right; if (file->left1) { start = file->left1; start2 = file->left2; comppath = data->leftpath1; comppath2 = data->leftpath2; } else { start = file->left2; start2 = 0; comppath = data->leftpath2; comppath2 = 0; } /* collapse duplicates on left side, except when comp path is diff */ if (start && start2 && (!opts->show_path || !comppath || streq(comppath, comppath2)) && is_same(opts->s, start, start2)) { start2 = 0; } if (start && end && !start2) { if (is_same(opts->s, start, end)) return; } if (opts->n) { /* opts->n only set if in PRODUCT and with -s aliases*/ /* we're rummaging through all product files/components */ if (c = nested_findKey(opts->n, HEAP(opts->s, rkoff))) { /* this component is not selected by -s */ unless (c->alias) return; } else { /* if -s^PRODUCT skip product files */ unless (opts->n->product->alias) return; } } /* path0 == path where file lives currently */ unless (path0 = findPath(opts, file)) return; if (path0 == INVALID) { /* * skip missing components * This assumes missing components * won't be in the idcache. */ end = 0; path0 = 0; goto done; } if (opts->show_diffs) { if (start) { sccs_key2md5(HEAP(opts->s, start), smd5); } else { start = rkoff; strcpy(smd5, "1.0"); comppath = data->leftpath1; } path1 = key2path(HEAP(opts->s, start), 0, 0, 0); if (start2) { sccs_key2md5(HEAP(opts->s, start2), smd5_2); path1_2 = key2path(HEAP(opts->s, start2), 0, 0, 0); } } if (end) { sccs_key2md5(HEAP(opts->s, end), emd5); } else { end = rkoff; strcpy(emd5, "1.0"); } path2 = key2path(HEAP(opts->s, end), 0, 0, 0); if (opts->no_print) goto done; if (opts->BAM && !weave_isBAM(opts->s, rkoff)) goto done; if (!opts->show_all && sccs_metafile(path0)) goto done; if (opts->hide_comp && streq(basenm(path0), GCHANGESET)) goto done; unless (opts->show_all) { if (opts->show_diffs) { if (isNullFile(smd5, path1) && (!start2 || isNullFile(smd5_2, path1_2)) && isNullFile(emd5, path2)) { goto done; } if (opts->hide_bk && strneq(path1, "BitKeeper/", 10) && (!start2 || strneq(path1_2, "BitKeeper/", 10)) && strneq(path2, "BitKeeper/", 10)) { goto done; } } else { if (isNullFile(emd5, path2)) goto done; if (opts->hide_bk && strneq(path2, "BitKeeper/", 10)) { goto done; } } } if (opts->elide && !streq(basenm(path0), GCHANGESET) && isIdenticalData(opts->s, path0, start, start2, end)) { goto done; } if (opts->limit_dir) { char *dir = dirname_alloc(path2); int match = streq(dir, opts->limit_dir); int c; char *p; c = 0; if (!match && opts->subdirs && (streq(opts->limit_dir, ".") || ((c = paths_overlap(opts->limit_dir, dir)) && !opts->limit_dir[c]))) { if (dir[c] == '/') c++; if (p = strchr(dir+c, '/')) *p = 0; unless (opts->seen_dir) { opts->seen_dir = hash_new(HASH_MEMHASH); } if (hash_insertStr(opts->seen_dir, dir+c, 0)) { printf("|%s\n", dir+c); } } free(dir); unless (match) goto done; } if (data->curpath) fputs(data->curpath, stdout); printf("%s|", path0); if (opts->show_diffs) { if (opts->show_path) { if (comppath) fputs(comppath, stdout); printf("%s|%s|", path1, smd5); if (start2) { if (comppath2) fputs(comppath2, stdout); printf("%s|%s|", path1_2, smd5_2); } } else { fputs(smd5, stdout); if (start2) { printf(",%s", smd5_2); } fputs("..", stdout); } } if (opts->show_path) { if (data->rightpath) fputs(data->rightpath, stdout); printf("%s|", path2); } printf("%s\n", emd5); fflush(stdout); done: if (opts->nested && end && componentKey(HEAP(opts->s, end))) { char **av; /* * call rset recursively here * We silently skip missing components */ dirname(path0); here = strdup(proj_cwd()); if (chdir(path0)) { /* components should all be present */ free(here); goto clear; } av = addLine(0, strdup("bk")); av = addLine(av, strdup("rset")); av = addLine(av, strdup("-HS")); /* we already printed cset */ av = addLine(av, strdup("--prefix")); EACH(opts->nav) av = addLine(av, strdup(opts->nav[i])); if (opts->show_diffs) { if (start2) { t = aprintf("-r%s,%s..%s", smd5, smd5_2, emd5); } else { t = aprintf("-r%s..%s", smd5, emd5); } } else { t = aprintf("-l%s", emd5); } av = addLine(av, t); av = addLine(av, 0); fflush(stdout); spawnvp(_P_WAIT, "bk", av+1); chdir(here); free(here); freeLines(av, free); } clear: if (path0) free(path0); if (path1) free(path1); if (path1_2) free(path1_2); if (path2) free(path2); } private sum_t dodiff(sccs *s, u32 rkoff, u32 loff, u32 roff) { sum_t sum = 0; u8 *p; u8 *root_key = HEAP(s, rkoff); u8 *left = loff ? HEAP(s, loff) : 0; u8 *right = roff ? HEAP(s, roff) : 0; p = right; while (*p) sum += *p++; if (left) { p = left; while (*p) sum -= *p++; } else { /* new file */ p = root_key; while (*p) sum += *p++; sum += ' ' + '\n'; } return (sum); } typedef struct { char *path; /* thing to sort */ rfile *file; /* thing to keep */ u32 component:1; /* is this a component? */ } rline; private int sortpath(const void *a, const void *b) { rline *ra = (rline *)a; rline *rb = (rline *)b; if (ra->component == rb->component) { return (strcmp(ra->path, rb->path)); } return (ra->component - rb->component); } private rline * addRline(rline *list, Opts *opts, rfile *file) { char *path; rline *item; /* path where file lives currently */ unless (path = findPath(opts, file)) return (0); if (path == INVALID) return (list); item = addArray(&list, 0); item->path = path; item->file = file; item->component = changesetKey(HEAP(opts->s, file->rkoff)); return (list); } private char ** sortKeys(Opts *opts, rset *data) { int i; char **keylist = 0; rline *list = 0; hash *db = data->keys; rfile *file; EACH_HASH(db) { file = db->vptr; /* * First round of pruning (more in process()) * Prune where left and right have same content. * Keep where left1 == left2, but != right. */ if (UNCHANGED(file)) continue; list = addRline(list, opts, file); } sortArray(list, sortpath); EACH(list) { keylist = addLine(keylist, list[i].file); FREE(list[i].path); } FREE(list); return (keylist); } /* * Compute diffs of rev1 and rev2 */ private void rel_diffs(Opts *opts, rset *data) { char **keylist; rfile *file; int i; /* * OK, here is the 2 main loops where we produce the * delta list. (via the process() function) * * Print the ChangeSet file first * XXX This assumes the Changset file never moves. * XXX If we move the ChangeSet file, * XXX this needs to be updated. */ unless (opts->hide_cset) { unless (data->left1) data->left1 = strdup("1.0"); fputs("ChangeSet|", stdout); unless (opts->show_path) { if (data->left1) fputs(data->left1, stdout); if (data->left2) { fputc(opts->compat ? '+' : ',', stdout); fputs(data->left2, stdout); } printf("..%s\n", data->right); } else { if (data->left1) { printf("ChangeSet|%s", data->left1); } if (data->left2) { if (opts->compat) { printf("+%s", data->left2); } else { printf("|ChangeSet|%s", data->left2); } } printf("|ChangeSet|%s\n", data->right); } } keylist = sortKeys(opts, data); EACH(keylist) { file = (rfile *)keylist[i]; if (opts->chksum) { assert(!file->left2); data->sum += dodiff( opts->s, file->rkoff, file->left1, file->right); } process(opts, data, file); } freeLines(keylist, 0); } private void rel_list(Opts *opts, rset *data) { char **keylist; int i; rfile *file; unless (opts->hide_cset || (opts->limit_dir && !streq(opts->limit_dir, "."))) { unless (opts->show_path) { printf("ChangeSet|%s\n", opts->rargs.rstop); } else { printf("ChangeSet|ChangeSet|%s\n", opts->rargs.rstop); } } keylist = sortKeys(opts, data); EACH(keylist) { file = (rfile *)keylist[i]; if (opts->chksum) { data->sum += dodiff( opts->s, file->rkoff, 0, file->right); } process(opts, data, file); } freeLines(keylist, 0); } /* * For a given rev, compute the parent (revP) and the merge parent (RevM) */ int sccs_parent_revs(sccs *s, char *rev, char **revP, char **revM) { ser_t d, p, m; d = sccs_findrev(s, rev); unless (d) { fprintf(stderr, "diffs: cannot find rev %s\n", rev); return (-1); } /* * XXX TODO: Could we get meta delta in cset?, should we skip them? */ unless (p = PARENT(s, d)) { fprintf(stderr, "diffs: rev %s has no parent\n", rev); return (-1); } assert(!TAG(s, p)); /* parent should not be a meta delta */ *revP = (p ? strdup(REV(s, p)) : NULL); if (MERGE(s, d)) { m = MERGE(s, d); *revM = (m ? strdup(REV(s, m)) : NULL); } return (0); } private void freeRset(rset *data) { unless (data) return; free(data->left1); free(data->left2); free(data->right); free(data->leftpath1); free(data->leftpath2); free(data->rightpath); free(data->curpath); if (data->keys) hash_free(data->keys); free(data); } /* * Try to walk a minimum amount of graph and weave to compute the rset. * Similar to walkrevs, but saves from hacking in yet another mode * which calls back for all nodes and exposes the counter. * * Loop exit condition has 2 counters that must both be zero: * * 1. when the only csets that remain are in the history of either * none or all the tips (left1,left2,right). * We only know the state of a cset when it is the current loop 'd', but * we know no future cset can have anything other than all or none * if there are no current csets that aren't none or all. * 'nongca' tracks how many current and future nodes are active * in LEFT1, LEFT2 or RIGHT, but not all. When it hits 0, it will * never leave 0. * * 2. when there is no rootkey for which we have seen one side and * and not the other. This is different from counter 1 in two ways: * It works on rootkeys as opposed to csets; and it tracks the left * side as either (LEFT1 | LEFT2) and counter 1 tracks them independently. * What this counter says is that if we find LEFT1 and not LEFT2 * and hit the region where counter 1, nongca == 0, then we know * that when we find LEFT2 that it must be in the history of LEFT1, * and would be ignored. So we ignore it before finding it. * * The code works if nongca and needOther use the same counter, * but then it is likely harder to read. */ private rset * weaveExtract(sccs *s, ser_t left1, ser_t left2, ser_t right, Opts *opts) { rset *data = 0, *ret = 0; ser_t d, e, upper; u8 all = 0; u8 *state = 0; u8 active; u32 seen, newseen; u32 rkoff, dkoff; rfile *file; MDBM *sDB = 0; sccs *sc; kvpair kv; hash *showgone = 0; int nongca = 0; int needOther = 0; #define NONGCA(_state) (_state && (_state != all)) /* some but not all */ #define MARK(_state, _bits, _counter) \ do { if (NONGCA(_state)) _counter--; \ _state |= _bits; \ if (NONGCA(_state)) _counter++; \ } while (0) #define ONE_SIDE(_state) /* something but not both */ \ (_state && !((_state & (LEFT1|LEFT2)) && (_state & RIGHT))) /* * The hack that puts 1.0 as a lower bound sucks, as component path * is 'ChangeSet' and that messes things up. */ if (left1 == TREE(s)) left1 = 0; if (left2 == TREE(s)) left2 = 0; if (left1 && left2 && isReachable(s, left1, left2)) { if (left1 < left2) left1 = left2; left2 = 0; } if (!left1 && left2) { left1 = left2; left2 = 0; } unless (data = initrset(s, left1, left2, right, opts)) goto err; all |= RIGHT; all |= LEFT1; /* if no left1, then diff against empty */ if (left2) all |= LEFT2; state = calloc(TABLE(s) + 1, sizeof(u8)); assert(right); MARK(state[right], RIGHT, nongca); upper = right; if (left1) { MARK(state[left1], LEFT1, nongca); if (left1 > upper) upper = left1; } if (left2) { MARK(state[left2], LEFT2, nongca); if (left2 > upper) upper = left2; } /* * XXX: new files cause the table range '..upper' to be read, * because there's no telling that an upper bound is a new file, * and will have no lower bound. 'needOther' will never hit zero. * * Since new files have 'needOther > 0' all the time, the loop * needs to also stop on end of table. */ sccs_rdweaveInit(s); if (opts->show_gone) { upper = TABLE(s); showgone = hash_new(HASH_U32HASH, sizeof(u32), sizeof(u32)); } else { sDB = mdbm_mem(); /* a cache of sccs_init() for files */ } for (d = upper; ((d >= TREE(s)) && (nongca || needOther)); d--) { if (TAG(s, d)) continue; /* because of show_gone */ if ((active = state[d])) { if (e = PARENT(s, d)) MARK(state[e], active, nongca); if (e = MERGE(s, d)) MARK(state[e], active, nongca); } /* * show_gone needs to log the first (possibly bogus) dkey * to guess at current path. Otherwise, prune inactive. */ unless (active || opts->show_gone) continue; cset_firstPair(s, d); while (e = cset_rdweavePair(s, RWP_ONE, &rkoff, &dkoff)) { assert(d == e); /* end of using 'e'; used to fail */ data->weavelines++; /* stats */ if (showgone) { hash_insertU32U32(showgone, rkoff, dkoff); unless (active) continue; } file = hash_fetch(data->keys, &rkoff, sizeof(rkoff)); seen = file ? file->seen : 0; assert(!(seen & LAST)); unless (dkoff) { if (file) { if (ONE_SIDE(seen)) needOther--; file->seen |= LAST; } continue; } unless (newseen = (active & ~seen)) continue; if (!nongca && (newseen == all)) continue; unless (opts->show_gone || opts->chksum) { if (deltaSkip(s, sDB, rkoff, dkoff)) continue; } unless (file) { file = hash_insert(data->keys, &rkoff, sizeof(rkoff), 0, sizeof(rfile)); file->rkoff = rkoff; if (showgone) { file->tipoff = hash_fetchU32U32(showgone, rkoff); } } /* if new left and not in the history of the other */ if ((newseen & (LEFT1|LEFT2)) && !(active & seen & (LEFT1|LEFT2))) { if (newseen & LEFT1) { file->left1 = dkoff; } if (newseen & LEFT2) { file->left2 = dkoff; } /* Original bk: if two, only use newest */ if (opts->compat && left2) { assert(left1); newseen |= (LEFT1|LEFT2); } } if (newseen & RIGHT) { assert(!file->right); file->right = dkoff; } if (ONE_SIDE(seen)) needOther--; seen |= newseen; if (ONE_SIDE(seen)) needOther++; file->seen = seen; if (!needOther && !nongca) break; /* if done, stop */ } /* if done processing a nongca cset, then one less remains */ if (NONGCA(active)) nongca--; } ret = data; data = 0; err: if (showgone) hash_free(showgone); sccs_rdweaveDone(s); free(state); freeRset(data); if (sDB) { EACH_KV(sDB) { memcpy(&sc, kv.val.dptr, sizeof (sccs *)); if (sc) sccs_free(sc); } mdbm_close(sDB); } return (ret); } private rset * initrset(sccs *s, ser_t left1, ser_t left2, ser_t right, Opts *opts) { rset *data = new(rset); ser_t d; int dopath = (opts->prefix && proj_isComponent(s->proj)); data->keys = hash_new(HASH_U32HASH, sizeof(u32), sizeof(rfile)); if (opts->chksum) { if (left2 || !right) { fprintf(stderr, "checksum - only one lower and upper bound\n"); freeRset(data); return (0); } if (left1 && (d = sccs_getCksumDelta(s, left1))) { data->sum = SUM(s, d); } if (d = sccs_getCksumDelta(s, right)) { data->wantsum = SUM(s, d); } } if (dopath) data->curpath = dirSlash(PATHNAME(s, sccs_top(s))); if (left1) { d = left1; data->left1 = strdup(REV(s, d)); if (dopath) data->leftpath1 = dirSlash(PATHNAME(s, d)); } if (left2) { d = left2; data->left2 = strdup(REV(s, d)); if (dopath) data->leftpath2 = dirSlash(PATHNAME(s, d)); } if (right) { d = right; data->right = strdup(REV(s, d)); if (dopath) data->rightpath = dirSlash(PATHNAME(s, d)); } return (data); } /* * fail if * - the file for rk is there, and delta dk is missing and gone * - the rk is gone and the file is missing * goneDB normally doesn't use the hash value. Here it stores a "1" * in place of the default "" to mean really gone (not in file system). */ private int deltaSkip(sccs *cset, MDBM *sDB, u32 rkoff, u32 dkoff) { sccs *s; char *rkgone; int rc = 0; char *rk = HEAP(cset, rkoff); char *dk = HEAP(cset, dkoff); unless (cset->goneDB) cset->goneDB = loadDB(GONE, 0, DB_GONE); unless ((rkgone = mdbm_fetch_str(cset->goneDB, rk)) || mdbm_fetch_str(cset->goneDB, dk)) { return (0); } if (rkgone && (*rkgone == '1')) return (1); if (s = sccs_keyinitAndCache(cset->proj, rk, SILENT, sDB, cset->idDB)) { /* if file there, but key is missing, ignore line. */ unless (sccs_findKey(s, dk)) rc = 1; } else if (rkgone) { /* if no file, mark goneDB that it was really gone */ mdbm_store_str(cset->goneDB, rk, "1", MDBM_REPLACE); rc = 1; } else { // not rk gone but no keyinit -- let rset fail => rc = 0; } return (rc); } /* * dirname() + '/' || 0 if no dirname */ private char * dirSlash(char *path) { char *p; unless (p = strrchr(path, '/')) return (0); return (strndup(path, p - path + 1)); }
{ "pile_set_name": "Github" }
<?php /* * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * The "reports" collection of methods. * Typical usage is: * <code> * $dfareportingService = new Google_Service_Dfareporting(...); * $reports = $dfareportingService->reports; * </code> */ class Google_Service_Dfareporting_Resource_Reports extends Google_Service_Resource { /** * Deletes a report by its ID. (reports.delete) * * @param string $profileId The DFA user profile ID. * @param string $reportId The ID of the report. * @param array $optParams Optional parameters. */ public function delete($profileId, $reportId, $optParams = array()) { $params = array('profileId' => $profileId, 'reportId' => $reportId); $params = array_merge($params, $optParams); return $this->call('delete', array($params)); } /** * Retrieves a report by its ID. (reports.get) * * @param string $profileId The DFA user profile ID. * @param string $reportId The ID of the report. * @param array $optParams Optional parameters. * @return Google_Service_Dfareporting_Report */ public function get($profileId, $reportId, $optParams = array()) { $params = array('profileId' => $profileId, 'reportId' => $reportId); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Dfareporting_Report"); } /** * Creates a report. (reports.insert) * * @param string $profileId The DFA user profile ID. * @param Google_Service_Dfareporting_Report $postBody * @param array $optParams Optional parameters. * @return Google_Service_Dfareporting_Report */ public function insert($profileId, Google_Service_Dfareporting_Report $postBody, $optParams = array()) { $params = array('profileId' => $profileId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('insert', array($params), "Google_Service_Dfareporting_Report"); } /** * Retrieves list of reports. (reports.listReports) * * @param string $profileId The DFA user profile ID. * @param array $optParams Optional parameters. * * @opt_param int maxResults Maximum number of results to return. * @opt_param string pageToken The value of the nextToken from the previous * result page. * @opt_param string scope The scope that defines which results are returned, * default is 'MINE'. * @opt_param string sortField The field by which to sort the list. * @opt_param string sortOrder Order of sorted results, default is 'DESCENDING'. * @return Google_Service_Dfareporting_ReportList */ public function listReports($profileId, $optParams = array()) { $params = array('profileId' => $profileId); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Dfareporting_ReportList"); } /** * Updates a report. This method supports patch semantics. (reports.patch) * * @param string $profileId The DFA user profile ID. * @param string $reportId The ID of the report. * @param Google_Service_Dfareporting_Report $postBody * @param array $optParams Optional parameters. * @return Google_Service_Dfareporting_Report */ public function patch($profileId, $reportId, Google_Service_Dfareporting_Report $postBody, $optParams = array()) { $params = array('profileId' => $profileId, 'reportId' => $reportId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('patch', array($params), "Google_Service_Dfareporting_Report"); } /** * Runs a report. (reports.run) * * @param string $profileId The DFA profile ID. * @param string $reportId The ID of the report. * @param array $optParams Optional parameters. * * @opt_param bool synchronous If set and true, tries to run the report * synchronously. * @return Google_Service_Dfareporting_DfareportingFile */ public function run($profileId, $reportId, $optParams = array()) { $params = array('profileId' => $profileId, 'reportId' => $reportId); $params = array_merge($params, $optParams); return $this->call('run', array($params), "Google_Service_Dfareporting_DfareportingFile"); } /** * Updates a report. (reports.update) * * @param string $profileId The DFA user profile ID. * @param string $reportId The ID of the report. * @param Google_Service_Dfareporting_Report $postBody * @param array $optParams Optional parameters. * @return Google_Service_Dfareporting_Report */ public function update($profileId, $reportId, Google_Service_Dfareporting_Report $postBody, $optParams = array()) { $params = array('profileId' => $profileId, 'reportId' => $reportId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('update', array($params), "Google_Service_Dfareporting_Report"); } }
{ "pile_set_name": "Github" }
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * 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. * * * * 3. Neither the name of the copyright holder nor the names of its * * contributors may be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * 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. * * * * ========================================================================= */ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ #define LINE_LEN 4096 //== INCLUDES ================================================================= // OpenMesh #include <OpenMesh/Core/System/config.h> #include <OpenMesh/Core/System/omstream.hh> #include <OpenMesh/Core/IO/reader/PLYReader.hh> #include <OpenMesh/Core/IO/IOManager.hh> #include <OpenMesh/Core/Utils/color_cast.hh> //STL #include <fstream> #include <iostream> #include <memory> #ifndef WIN32 #endif //=== NAMESPACES ============================================================== namespace OpenMesh { namespace IO { //============================================================================= //=== INSTANCIATE ============================================================= _PLYReader_ __PLYReaderInstance; _PLYReader_& PLYReader() { return __PLYReaderInstance; } //=== IMPLEMENTATION ========================================================== _PLYReader_::_PLYReader_() { IOManager().register_module(this); // Store sizes in byte of each property type scalar_size_[ValueTypeINT8] = 1; scalar_size_[ValueTypeUINT8] = 1; scalar_size_[ValueTypeINT16] = 2; scalar_size_[ValueTypeUINT16] = 2; scalar_size_[ValueTypeINT32] = 4; scalar_size_[ValueTypeUINT32] = 4; scalar_size_[ValueTypeFLOAT32] = 4; scalar_size_[ValueTypeFLOAT64] = 8; scalar_size_[ValueTypeCHAR] = 1; scalar_size_[ValueTypeUCHAR] = 1; scalar_size_[ValueTypeSHORT] = 2; scalar_size_[ValueTypeUSHORT] = 2; scalar_size_[ValueTypeINT] = 4; scalar_size_[ValueTypeUINT] = 4; scalar_size_[ValueTypeFLOAT] = 4; scalar_size_[ValueTypeDOUBLE] = 8; } //----------------------------------------------------------------------------- bool _PLYReader_::read(const std::string& _filename, BaseImporter& _bi, Options& _opt) { std::fstream in(_filename.c_str(), (std::ios_base::binary | std::ios_base::in) ); if (!in.is_open() || !in.good()) { omerr() << "[PLYReader] : cannot not open file " << _filename << std::endl; return false; } bool result = read(in, _bi, _opt); in.close(); return result; } //----------------------------------------------------------------------------- bool _PLYReader_::read(std::istream& _in, BaseImporter& _bi, Options& _opt) { if (!_in.good()) { omerr() << "[PLYReader] : cannot not use stream" << std::endl; return false; } // filter relevant options for reading bool swap = _opt.check(Options::Swap); userOptions_ = _opt; // build options to be returned _opt.clear(); if (options_.vertex_has_normal() && userOptions_.vertex_has_normal()) { _opt += Options::VertexNormal; } if (options_.vertex_has_texcoord() && userOptions_.vertex_has_texcoord()) { _opt += Options::VertexTexCoord; } if (options_.vertex_has_color() && userOptions_.vertex_has_color()) { _opt += Options::VertexColor; } if (options_.face_has_color() && userOptions_.face_has_color()) { _opt += Options::FaceColor; } if (options_.is_binary()) { _opt += Options::Binary; } if (options_.color_is_float()) { _opt += Options::ColorFloat; } if (options_.check(Options::Custom) && userOptions_.check(Options::Custom)) { _opt += Options::Custom; } // //force user-choice for the alpha value when reading binary // if ( options_.is_binary() && userOptions_.color_has_alpha() ) // options_ += Options::ColorAlpha; return (options_.is_binary() ? read_binary(_in, _bi, swap, _opt) : read_ascii(_in, _bi, _opt)); } template<typename T, typename Handle> struct Handle2Prop; template<typename T> struct Handle2Prop<T,VertexHandle> { typedef OpenMesh::VPropHandleT<T> PropT; }; template<typename T> struct Handle2Prop<T,FaceHandle> { typedef OpenMesh::FPropHandleT<T> PropT; }; //read and assign custom properties with the given type. Also creates property, if not exist template<bool binary, typename T, typename Handle> void _PLYReader_::readCreateCustomProperty(std::istream& _in, BaseImporter& _bi, Handle _h, const std::string& _propName, const _PLYReader_::ValueType _valueType, const _PLYReader_::ValueType _listType) const { if (_listType == Unsupported) //no list type defined -> property is not a list { //get/add property typename Handle2Prop<T,Handle>::PropT prop; if (!_bi.kernel()->get_property_handle(prop,_propName)) { _bi.kernel()->add_property(prop,_propName); _bi.kernel()->property(prop).set_persistent(true); } //read and assign T in; read(_valueType, _in, in, OpenMesh::GenProg::Bool2Type<binary>()); _bi.kernel()->property(prop,_h) = in; } else { //get/add property typename Handle2Prop<std::vector<T>,Handle>::PropT prop; if (!_bi.kernel()->get_property_handle(prop,_propName)) { _bi.kernel()->add_property(prop,_propName); _bi.kernel()->property(prop).set_persistent(true); } //init vector int numberOfValues; read(_listType, _in, numberOfValues, OpenMesh::GenProg::Bool2Type<binary>()); std::vector<T> vec; vec.reserve(numberOfValues); //read and assign for (int i = 0; i < numberOfValues; ++i) { T in; read(_valueType, _in, in, OpenMesh::GenProg::Bool2Type<binary>()); vec.push_back(in); } _bi.kernel()->property(prop,_h) = vec; } } template<bool binary, typename Handle> void _PLYReader_::readCustomProperty(std::istream& _in, BaseImporter& _bi, Handle _h, const std::string& _propName, const _PLYReader_::ValueType _valueType, const _PLYReader_::ValueType _listIndexType) const { switch (_valueType) { case ValueTypeINT8: case ValueTypeCHAR: readCreateCustomProperty<binary,signed char>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeUINT8: case ValueTypeUCHAR: readCreateCustomProperty<binary,unsigned char>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeINT16: case ValueTypeSHORT: readCreateCustomProperty<binary,short>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeUINT16: case ValueTypeUSHORT: readCreateCustomProperty<binary,unsigned short>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeINT32: case ValueTypeINT: readCreateCustomProperty<binary,int>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeUINT32: case ValueTypeUINT: readCreateCustomProperty<binary,unsigned int>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeFLOAT32: case ValueTypeFLOAT: readCreateCustomProperty<binary,float>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; case ValueTypeFLOAT64: case ValueTypeDOUBLE: readCreateCustomProperty<binary,double>(_in,_bi,_h,_propName,_valueType,_listIndexType); break; default: std::cerr << "unsupported type" << std::endl; break; } } //----------------------------------------------------------------------------- bool _PLYReader_::read_ascii(std::istream& _in, BaseImporter& _bi, const Options& _opt) const { // Reparse the header if (!can_u_read(_in)) { omerr() << "[PLYReader] : Unable to parse header\n"; return false; } unsigned int i, j, k, l, idx; unsigned int nV; OpenMesh::Vec3f v, n; std::string trash; OpenMesh::Vec2f t; OpenMesh::Vec4i c; float tmp; BaseImporter::VHandles vhandles; VertexHandle vh; _bi.reserve(vertexCount_, 3* vertexCount_ , faceCount_); if (vertexDimension_ != 3) { omerr() << "[PLYReader] : Only vertex dimension 3 is supported." << std::endl; return false; } const bool err_enabled = omerr().is_enabled(); size_t complex_faces = 0; if (err_enabled) omerr().disable(); // read vertices: for (i = 0; i < vertexCount_ && !_in.eof(); ++i) { vh = _bi.add_vertex(); v[0] = 0.0; v[1] = 0.0; v[2] = 0.0; n[0] = 0.0; n[1] = 0.0; n[2] = 0.0; t[0] = 0.0; t[1] = 0.0; c[0] = 0; c[1] = 0; c[2] = 0; c[3] = 255; for (size_t propertyIndex = 0; propertyIndex < vertexProperties_.size(); ++propertyIndex) { switch (vertexProperties_[propertyIndex].property) { case XCOORD: _in >> v[0]; break; case YCOORD: _in >> v[1]; break; case ZCOORD: _in >> v[2]; break; case XNORM: _in >> n[0]; break; case YNORM: _in >> n[1]; break; case ZNORM: _in >> n[2]; break; case TEXX: _in >> t[0]; break; case TEXY: _in >> t[1]; break; case COLORRED: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { _in >> tmp; c[0] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else _in >> c[0]; break; case COLORGREEN: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { _in >> tmp; c[1] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else _in >> c[1]; break; case COLORBLUE: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { _in >> tmp; c[2] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else _in >> c[2]; break; case COLORALPHA: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { _in >> tmp; c[3] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else _in >> c[3]; break; case CUSTOM_PROP: if (_opt.check(Options::Custom)) readCustomProperty<false>(_in, _bi, vh, vertexProperties_[propertyIndex].name, vertexProperties_[propertyIndex].value, vertexProperties_[propertyIndex].listIndexType); else _in >> trash; break; default: _in >> trash; break; } } _bi.set_point(vh, v); if (_opt.vertex_has_normal()) _bi.set_normal(vh, n); if (_opt.vertex_has_texcoord()) _bi.set_texcoord(vh, t); if (_opt.vertex_has_color()) _bi.set_color(vh, Vec4uc(c)); } // faces for (i = 0; i < faceCount_; ++i) { FaceHandle fh; for (size_t propertyIndex = 0; propertyIndex < faceProperties_.size(); ++propertyIndex) { PropertyInfo prop = faceProperties_[propertyIndex]; switch (prop.property) { case VERTEX_INDICES: // nV = number of Vertices for current face _in >> nV; if (nV == 3) { vhandles.resize(3); _in >> j; _in >> k; _in >> l; vhandles[0] = VertexHandle(j); vhandles[1] = VertexHandle(k); vhandles[2] = VertexHandle(l); } else { vhandles.clear(); for (j = 0; j < nV; ++j) { _in >> idx; vhandles.push_back(VertexHandle(idx)); } } fh = _bi.add_face(vhandles); if (!fh.is_valid()) ++complex_faces; break; case CUSTOM_PROP: if (_opt.check(Options::Custom) && fh.is_valid()) readCustomProperty<false>(_in, _bi, fh, prop.name, prop.value, prop.listIndexType); else _in >> trash; break; default: _in >> trash; break; } } } if (err_enabled) omerr().enable(); if (complex_faces) omerr() << complex_faces << "The reader encountered invalid faces, that could not be added.\n"; // File was successfully parsed. return true; } //----------------------------------------------------------------------------- bool _PLYReader_::read_binary(std::istream& _in, BaseImporter& _bi, bool /*_swap*/, const Options& _opt) const { // Reparse the header if (!can_u_read(_in)) { omerr() << "[PLYReader] : Unable to parse header\n"; return false; } OpenMesh::Vec3f v, n; // Vertex OpenMesh::Vec2f t; // TexCoords BaseImporter::VHandles vhandles; VertexHandle vh; OpenMesh::Vec4i c; // Color float tmp; _bi.reserve(vertexCount_, 3* vertexCount_ , faceCount_); const bool err_enabled = omerr().is_enabled(); size_t complex_faces = 0; if (err_enabled) omerr().disable(); // read vertices: for (unsigned int i = 0; i < vertexCount_ && !_in.eof(); ++i) { vh = _bi.add_vertex(); v[0] = 0.0; v[1] = 0.0; v[2] = 0.0; n[0] = 0.0; n[1] = 0.0; n[2] = 0.0; t[0] = 0.0; t[1] = 0.0; c[0] = 0; c[1] = 0; c[2] = 0; c[3] = 255; for (size_t propertyIndex = 0; propertyIndex < vertexProperties_.size(); ++propertyIndex) { switch (vertexProperties_[propertyIndex].property) { case XCOORD: readValue(vertexProperties_[propertyIndex].value, _in, v[0]); break; case YCOORD: readValue(vertexProperties_[propertyIndex].value, _in, v[1]); break; case ZCOORD: readValue(vertexProperties_[propertyIndex].value, _in, v[2]); break; case XNORM: readValue(vertexProperties_[propertyIndex].value, _in, n[0]); break; case YNORM: readValue(vertexProperties_[propertyIndex].value, _in, n[1]); break; case ZNORM: readValue(vertexProperties_[propertyIndex].value, _in, n[2]); break; case TEXX: readValue(vertexProperties_[propertyIndex].value, _in, t[0]); break; case TEXY: readValue(vertexProperties_[propertyIndex].value, _in, t[1]); break; case COLORRED: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { readValue(vertexProperties_[propertyIndex].value, _in, tmp); c[0] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else readInteger(vertexProperties_[propertyIndex].value, _in, c[0]); break; case COLORGREEN: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { readValue(vertexProperties_[propertyIndex].value, _in, tmp); c[1] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else readInteger(vertexProperties_[propertyIndex].value, _in, c[1]); break; case COLORBLUE: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { readValue(vertexProperties_[propertyIndex].value, _in, tmp); c[2] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else readInteger(vertexProperties_[propertyIndex].value, _in, c[2]); break; case COLORALPHA: if (vertexProperties_[propertyIndex].value == ValueTypeFLOAT32 || vertexProperties_[propertyIndex].value == ValueTypeFLOAT) { readValue(vertexProperties_[propertyIndex].value, _in, tmp); c[3] = static_cast<OpenMesh::Vec4i::value_type> (tmp * 255.0f); } else readInteger(vertexProperties_[propertyIndex].value, _in, c[3]); break; case CUSTOM_PROP: if (_opt.check(Options::Custom)) readCustomProperty<true>(_in, _bi, vh, vertexProperties_[propertyIndex].name, vertexProperties_[propertyIndex].value, vertexProperties_[propertyIndex].listIndexType); else consume_input(_in, scalar_size_[vertexProperties_[propertyIndex].value]); break; default: // Read unsupported property consume_input(_in, scalar_size_[vertexProperties_[propertyIndex].value]); break; } } _bi.set_point(vh,v); if (_opt.vertex_has_normal()) _bi.set_normal(vh, n); if (_opt.vertex_has_texcoord()) _bi.set_texcoord(vh, t); if (_opt.vertex_has_color()) _bi.set_color(vh, Vec4uc(c)); } for (unsigned i = 0; i < faceCount_; ++i) { FaceHandle fh; for (size_t propertyIndex = 0; propertyIndex < faceProperties_.size(); ++propertyIndex) { PropertyInfo prop = faceProperties_[propertyIndex]; switch (prop.property) { case VERTEX_INDICES: // nV = number of Vertices for current face unsigned int nV; readInteger(prop.listIndexType, _in, nV); if (nV == 3) { vhandles.resize(3); unsigned int j,k,l; readInteger(prop.value, _in, j); readInteger(prop.value, _in, k); readInteger(prop.value, _in, l); vhandles[0] = VertexHandle(j); vhandles[1] = VertexHandle(k); vhandles[2] = VertexHandle(l); } else { vhandles.clear(); for (unsigned j = 0; j < nV; ++j) { unsigned int idx; readInteger(prop.value, _in, idx); vhandles.push_back(VertexHandle(idx)); } } fh = _bi.add_face(vhandles); if (!fh.is_valid()) ++complex_faces; break; case CUSTOM_PROP: if (_opt.check(Options::Custom) && fh.is_valid()) readCustomProperty<true>(_in, _bi, fh, prop.name, prop.value, prop.listIndexType); else consume_input(_in, scalar_size_[faceProperties_[propertyIndex].value]); break; default: consume_input(_in, scalar_size_[faceProperties_[propertyIndex].value]); break; } } } if (err_enabled) omerr().enable(); if (complex_faces) omerr() << complex_faces << "The reader encountered invalid faces, that could not be added.\n"; return true; } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, float& _value) const { switch (_type) { case ValueTypeFLOAT32: case ValueTypeFLOAT: float32_t tmp; restore(_in, tmp, options_.check(Options::MSB)); _value = tmp; break; default: _value = 0.0; std::cerr << "unsupported conversion type to float: " << _type << std::endl; break; } } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, double& _value) const { switch (_type) { case ValueTypeFLOAT64: case ValueTypeDOUBLE: float64_t tmp; restore(_in, tmp, options_.check(Options::MSB)); _value = tmp; break; default: _value = 0.0; std::cerr << "unsupported conversion type to double: " << _type << std::endl; break; } } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, unsigned char& _value) const{ unsigned int tmp; readValue(_type,_in,tmp); _value = tmp; } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, unsigned short& _value) const{ unsigned int tmp; readValue(_type,_in,tmp); _value = tmp; } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, signed char& _value) const{ int tmp; readValue(_type,_in,tmp); _value = tmp; } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, short& _value) const{ int tmp; readValue(_type,_in,tmp); _value = tmp; } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, unsigned int& _value) const { uint32_t tmp_uint32_t; uint16_t tmp_uint16_t; uint8_t tmp_uchar; switch (_type) { case ValueTypeUINT: case ValueTypeUINT32: restore(_in, tmp_uint32_t, options_.check(Options::MSB)); _value = tmp_uint32_t; break; case ValueTypeUSHORT: case ValueTypeUINT16: restore(_in, tmp_uint16_t, options_.check(Options::MSB)); _value = tmp_uint16_t; break; case ValueTypeUCHAR: case ValueTypeUINT8: restore(_in, tmp_uchar, options_.check(Options::MSB)); _value = tmp_uchar; break; default: _value = 0; std::cerr << "unsupported conversion type to unsigned int: " << _type << std::endl; break; } } //----------------------------------------------------------------------------- void _PLYReader_::readValue(ValueType _type, std::istream& _in, int& _value) const { int32_t tmp_int32_t; int16_t tmp_int16_t; int8_t tmp_char; switch (_type) { case ValueTypeINT: case ValueTypeINT32: restore(_in, tmp_int32_t, options_.check(Options::MSB)); _value = tmp_int32_t; break; case ValueTypeSHORT: case ValueTypeINT16: restore(_in, tmp_int16_t, options_.check(Options::MSB)); _value = tmp_int16_t; break; case ValueTypeCHAR: case ValueTypeINT8: restore(_in, tmp_char, options_.check(Options::MSB)); _value = tmp_char; break; default: _value = 0; std::cerr << "unsupported conversion type to int: " << _type << std::endl; break; } } //----------------------------------------------------------------------------- void _PLYReader_::readInteger(ValueType _type, std::istream& _in, int& _value) const { int32_t tmp_int32_t; uint32_t tmp_uint32_t; int8_t tmp_char; uint8_t tmp_uchar; switch (_type) { case ValueTypeINT: case ValueTypeINT32: restore(_in, tmp_int32_t, options_.check(Options::MSB)); _value = tmp_int32_t; break; case ValueTypeUINT: case ValueTypeUINT32: restore(_in, tmp_uint32_t, options_.check(Options::MSB)); _value = tmp_uint32_t; break; case ValueTypeCHAR: case ValueTypeINT8: restore(_in, tmp_char, options_.check(Options::MSB)); _value = tmp_char; break; case ValueTypeUCHAR: case ValueTypeUINT8: restore(_in, tmp_uchar, options_.check(Options::MSB)); _value = tmp_uchar; break; default: _value = 0; std::cerr << "unsupported conversion type to int: " << _type << std::endl; break; } } //----------------------------------------------------------------------------- void _PLYReader_::readInteger(ValueType _type, std::istream& _in, unsigned int& _value) const { int32_t tmp_int32_t; uint32_t tmp_uint32_t; int8_t tmp_char; uint8_t tmp_uchar; switch (_type) { case ValueTypeUINT: case ValueTypeUINT32: restore(_in, tmp_uint32_t, options_.check(Options::MSB)); _value = tmp_uint32_t; break; case ValueTypeINT: case ValueTypeINT32: restore(_in, tmp_int32_t, options_.check(Options::MSB)); _value = tmp_int32_t; break; case ValueTypeUCHAR: case ValueTypeUINT8: restore(_in, tmp_uchar, options_.check(Options::MSB)); _value = tmp_uchar; break; case ValueTypeCHAR: case ValueTypeINT8: restore(_in, tmp_char, options_.check(Options::MSB)); _value = tmp_char; break; default: _value = 0; std::cerr << "unsupported conversion type to unsigned int: " << _type << std::endl; break; } } //------------------------------------------------------------------------------ bool _PLYReader_::can_u_read(const std::string& _filename) const { // !!! Assuming BaseReader::can_u_parse( std::string& ) // does not call BaseReader::read_magic()!!! if (BaseReader::can_u_read(_filename)) { std::ifstream ifs(_filename.c_str()); if (ifs.is_open() && can_u_read(ifs)) { ifs.close(); return true; } } return false; } //----------------------------------------------------------------------------- std::string get_property_name(std::string _string1, std::string _string2) { if (_string1 == "float32" || _string1 == "float64" || _string1 == "float" || _string1 == "double" || _string1 == "int8" || _string1 == "uint8" || _string1 == "char" || _string1 == "uchar" || _string1 == "int32" || _string1 == "uint32" || _string1 == "int" || _string1 == "uint" || _string1 == "int16" || _string1 == "uint16" || _string1 == "short" || _string1 == "ushort") return _string2; if (_string2 == "float32" || _string2 == "float64" || _string2 == "float" || _string2 == "double" || _string2 == "int8" || _string2 == "uint8" || _string2 == "char" || _string2 == "uchar" || _string2 == "int32" || _string2 == "uint32" || _string2 == "int" || _string2 == "uint" || _string2 == "int16" || _string2 == "uint16" || _string2 == "short" || _string2 == "ushort") return _string1; std::cerr << "Unsupported entry type" << std::endl; return "Unsupported"; } //----------------------------------------------------------------------------- _PLYReader_::ValueType get_property_type(std::string _string1, std::string _string2) { if (_string1 == "float32" || _string2 == "float32") return _PLYReader_::ValueTypeFLOAT32; else if (_string1 == "float64" || _string2 == "float64") return _PLYReader_::ValueTypeFLOAT64; else if (_string1 == "float" || _string2 == "float") return _PLYReader_::ValueTypeFLOAT; else if (_string1 == "double" || _string2 == "double") return _PLYReader_::ValueTypeDOUBLE; else if (_string1 == "int8" || _string2 == "int8") return _PLYReader_::ValueTypeINT8; else if (_string1 == "uint8" || _string2 == "uint8") return _PLYReader_::ValueTypeUINT8; else if (_string1 == "char" || _string2 == "char") return _PLYReader_::ValueTypeCHAR; else if (_string1 == "uchar" || _string2 == "uchar") return _PLYReader_::ValueTypeUCHAR; else if (_string1 == "int32" || _string2 == "int32") return _PLYReader_::ValueTypeINT32; else if (_string1 == "uint32" || _string2 == "uint32") return _PLYReader_::ValueTypeUINT32; else if (_string1 == "int" || _string2 == "int") return _PLYReader_::ValueTypeINT; else if (_string1 == "uint" || _string2 == "uint") return _PLYReader_::ValueTypeUINT; else if (_string1 == "int16" || _string2 == "int16") return _PLYReader_::ValueTypeINT16; else if (_string1 == "uint16" || _string2 == "uint16") return _PLYReader_::ValueTypeUINT16; else if (_string1 == "short" || _string2 == "short") return _PLYReader_::ValueTypeSHORT; else if (_string1 == "ushort" || _string2 == "ushort") return _PLYReader_::ValueTypeUSHORT; return _PLYReader_::Unsupported; } //----------------------------------------------------------------------------- bool _PLYReader_::can_u_read(std::istream& _is) const { // Clear per file options options_.cleanup(); // clear property maps, will be recreated vertexProperties_.clear(); faceProperties_.clear(); // read 1st line std::string line; std::getline(_is, line); trim(line); // Handle '\r\n' newlines const size_t s = line.size(); if( s > 0 && line[s - 1] == '\r') line.resize(s - 1); //Check if this file is really a ply format if (line != "PLY" && line != "ply") return false; vertexCount_ = 0; faceCount_ = 0; vertexDimension_ = 0; std::string keyword; std::string fileType; std::string elementName = ""; std::string propertyName; std::string listIndexType; std::string listEntryType; float version; _is >> keyword; _is >> fileType; _is >> version; if (_is.bad()) { omerr() << "Defect PLY header detected" << std::endl; return false; } if (fileType == "ascii") { options_ -= Options::Binary; } else if (fileType == "binary_little_endian") { options_ += Options::Binary; options_ += Options::LSB; //if (Endian::local() == Endian::MSB) // options_ += Options::Swap; } else if (fileType == "binary_big_endian") { options_ += Options::Binary; options_ += Options::MSB; //if (Endian::local() == Endian::LSB) // options_ += Options::Swap; } else { omerr() << "Unsupported PLY format: " << fileType << std::endl; return false; } std::streamoff streamPos = _is.tellg(); _is >> keyword; while (keyword != "end_header") { if (keyword == "comment") { std::getline(_is, line); } else if (keyword == "element") { _is >> elementName; if (elementName == "vertex") { _is >> vertexCount_; } else if (elementName == "face") { _is >> faceCount_; } else { omerr() << "PLY header unsupported element type: " << elementName << std::endl; } } else if (keyword == "property") { std::string tmp1; std::string tmp2; // Read first keyword, as it might be a list _is >> tmp1; if (tmp1 == "list") { _is >> listIndexType; _is >> listEntryType; _is >> propertyName; ValueType indexType = Unsupported; ValueType entryType = Unsupported; if (listIndexType == "uint8") { indexType = ValueTypeUINT8; } else if (listIndexType == "uchar") { indexType = ValueTypeUCHAR; } else if (listIndexType == "int") { indexType = ValueTypeINT; } else { omerr() << "Unsupported Index type for property list: " << listIndexType << std::endl; continue; } entryType = get_property_type(listEntryType, listEntryType); if (entryType == Unsupported) { omerr() << "Unsupported Entry type for property list: " << listEntryType << std::endl; } PropertyInfo property(CUSTOM_PROP, entryType, propertyName); property.listIndexType = indexType; // just 2 elements supported by now if (elementName == "vertex") { vertexProperties_.push_back(property); } else if (elementName == "face") { // special case for vertex indices if (propertyName == "vertex_index" || propertyName == "vertex_indices") { property.property = VERTEX_INDICES; if (!faceProperties_.empty()) { omerr() << "Custom face Properties defined, before 'vertex_indices' property was defined. They will be skipped" << std::endl; faceProperties_.clear(); } } faceProperties_.push_back(property); } else omerr() << "property " << propertyName << " belongs to unsupported element " << elementName << std::endl; } else { // as this is not a list property, read second value of property _is >> tmp2; // Extract name and type of property // As the order seems to be different in some files, autodetect it. ValueType valueType = get_property_type(tmp1, tmp2); propertyName = get_property_name(tmp1, tmp2); PropertyInfo entry; //special treatment for some vertex properties. if (elementName == "vertex") { if (propertyName == "x") { entry = PropertyInfo(XCOORD, valueType); vertexDimension_++; } else if (propertyName == "y") { entry = PropertyInfo(YCOORD, valueType); vertexDimension_++; } else if (propertyName == "z") { entry = PropertyInfo(ZCOORD, valueType); vertexDimension_++; } else if (propertyName == "nx") { entry = PropertyInfo(XNORM, valueType); options_ += Options::VertexNormal; } else if (propertyName == "ny") { entry = PropertyInfo(YNORM, valueType); options_ += Options::VertexNormal; } else if (propertyName == "nz") { entry = PropertyInfo(ZNORM, valueType); options_ += Options::VertexNormal; } else if (propertyName == "u" || propertyName == "s") { entry = PropertyInfo(TEXX, valueType); options_ += Options::VertexTexCoord; } else if (propertyName == "v" || propertyName == "t") { entry = PropertyInfo(TEXY, valueType); options_ += Options::VertexTexCoord; } else if (propertyName == "red") { entry = PropertyInfo(COLORRED, valueType); options_ += Options::VertexColor; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } else if (propertyName == "green") { entry = PropertyInfo(COLORGREEN, valueType); options_ += Options::VertexColor; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } else if (propertyName == "blue") { entry = PropertyInfo(COLORBLUE, valueType); options_ += Options::VertexColor; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } else if (propertyName == "diffuse_red") { entry = PropertyInfo(COLORRED, valueType); options_ += Options::VertexColor; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } else if (propertyName == "diffuse_green") { entry = PropertyInfo(COLORGREEN, valueType); options_ += Options::VertexColor; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } else if (propertyName == "diffuse_blue") { entry = PropertyInfo(COLORBLUE, valueType); options_ += Options::VertexColor; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } else if (propertyName == "alpha") { entry = PropertyInfo(COLORALPHA, valueType); options_ += Options::VertexColor; options_ += Options::ColorAlpha; if (valueType == ValueTypeFLOAT || valueType == ValueTypeFLOAT32) options_ += Options::ColorFloat; } } //not a special property, load as custom if (entry.value == Unsupported){ Property prop = CUSTOM_PROP; options_ += Options::Custom; entry = PropertyInfo(prop, valueType, propertyName); } if (entry.property != UNSUPPORTED) { if (elementName == "vertex") vertexProperties_.push_back(entry); else if (elementName == "face") faceProperties_.push_back(entry); else omerr() << "Properties not supported in element " << elementName << std::endl; } } } else { omlog() << "Unsupported keyword : " << keyword << std::endl; } streamPos = _is.tellg(); _is >> keyword; if (_is.bad()) { omerr() << "Error while reading PLY file header" << std::endl; return false; } } // As the binary data is directy after the end_header keyword // and the stream removes too many bytes, seek back to the right position if (options_.is_binary()) { _is.seekg(streamPos); char c1 = 0; char c2 = 0; _is.get(c1); _is.get(c2); if (c1 == 0x0D && c2 == 0x0A) { _is.seekg(streamPos + 14); } else { _is.seekg(streamPos + 12); } } return true; } //============================================================================= } // namespace IO } // namespace OpenMesh //=============================================================================
{ "pile_set_name": "Github" }
/********************************************************************* * SEGGER Microcontroller GmbH * * The Embedded Experts * ********************************************************************** * * * (c) 1995 - 2019 SEGGER Microcontroller GmbH * * * * www.segger.com Support: support@segger.com * * * ********************************************************************** * * * SEGGER RTT * Real Time Transfer for embedded targets * * * ********************************************************************** * * * All rights reserved. * * * * SEGGER strongly recommends to not make any changes * * to or modify the source code of this software in order to stay * * compatible with the RTT protocol and J-Link. * * * * Redistribution and use in source and binary forms, with or * * without modification, are permitted provided that the following * * condition is met: * * * * o Redistributions of source code must retain the above copyright * * notice, this condition and the following disclaimer. * * * * 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 SEGGER Microcontroller 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. * * * ********************************************************************** ---------------------------END-OF-HEADER------------------------------ File : RTT_Syscalls_KEIL.c Purpose : Retargeting module for KEIL MDK-CM3. Low-level functions for using printf() via RTT Revision: $Rev: 17697 $ ---------------------------------------------------------------------- */ #ifdef __CC_ARM #include <stdio.h> #include <stdlib.h> #include <string.h> #include <rt_sys.h> #include <rt_misc.h> #include "SEGGER_RTT.h" /********************************************************************* * * #pragmas * ********************************************************************** */ #pragma import(__use_no_semihosting) #ifdef _MICROLIB #pragma import(__use_full_stdio) #endif /********************************************************************* * * Defines non-configurable * ********************************************************************** */ /* Standard IO device handles - arbitrary, but any real file system handles must be less than 0x8000. */ #define STDIN 0x8001 // Standard Input Stream #define STDOUT 0x8002 // Standard Output Stream #define STDERR 0x8003 // Standard Error Stream /********************************************************************* * * Public const * ********************************************************************** */ #if __ARMCC_VERSION < 5000000 //const char __stdin_name[] = "STDIN"; const char __stdout_name[] = "STDOUT"; const char __stderr_name[] = "STDERR"; #endif /********************************************************************* * * Public code * ********************************************************************** */ /********************************************************************* * * _ttywrch * * Function description: * Outputs a character to the console * * Parameters: * c - character to output * */ void _ttywrch(int c) { fputc(c, stdout); // stdout fflush(stdout); } /********************************************************************* * * _sys_open * * Function description: * Opens the device/file in order to do read/write operations * * Parameters: * sName - sName of the device/file to open * OpenMode - This parameter is currently ignored * * Return value: * != 0 - Handle to the object to open, otherwise * == 0 -"device" is not handled by this module * */ FILEHANDLE _sys_open(const char * sName, int OpenMode) { (void)OpenMode; // Register standard Input Output devices. if (strcmp(sName, __stdout_name) == 0) { return (STDOUT); } else if (strcmp(sName, __stderr_name) == 0) { return (STDERR); } else return (0); // Not implemented } /********************************************************************* * * _sys_close * * Function description: * Closes the handle to the open device/file * * Parameters: * hFile - Handle to a file opened via _sys_open * * Return value: * 0 - device/file closed * */ int _sys_close(FILEHANDLE hFile) { (void)hFile; return 0; // Not implemented } /********************************************************************* * * _sys_write * * Function description: * Writes the data to an open handle. * Currently this function only outputs data to the console * * Parameters: * hFile - Handle to a file opened via _sys_open * pBuffer - Pointer to the data that shall be written * NumBytes - Number of bytes to write * Mode - The Mode that shall be used * * Return value: * Number of bytes *not* written to the file/device * */ int _sys_write(FILEHANDLE hFile, const unsigned char * pBuffer, unsigned NumBytes, int Mode) { int r = 0; (void)Mode; if (hFile == STDOUT) { SEGGER_RTT_Write(0, (const char*)pBuffer, NumBytes); return 0; } return r; } /********************************************************************* * * _sys_read * * Function description: * Reads data from an open handle. * Currently this modules does nothing. * * Parameters: * hFile - Handle to a file opened via _sys_open * pBuffer - Pointer to buffer to store the read data * NumBytes - Number of bytes to read * Mode - The Mode that shall be used * * Return value: * Number of bytes read from the file/device * */ int _sys_read(FILEHANDLE hFile, unsigned char * pBuffer, unsigned NumBytes, int Mode) { (void)hFile; (void)pBuffer; (void)NumBytes; (void)Mode; return (0); // Not implemented } /********************************************************************* * * _sys_istty * * Function description: * This function shall return whether the opened file * is a console device or not. * * Parameters: * hFile - Handle to a file opened via _sys_open * * Return value: * 1 - Device is a console * 0 - Device is not a console * */ int _sys_istty(FILEHANDLE hFile) { if (hFile > 0x8000) { return (1); } return (0); // Not implemented } /********************************************************************* * * _sys_seek * * Function description: * Seeks via the file to a specific position * * Parameters: * hFile - Handle to a file opened via _sys_open * Pos - * * Return value: * int - * */ int _sys_seek(FILEHANDLE hFile, long Pos) { (void)hFile; (void)Pos; return (0); // Not implemented } /********************************************************************* * * _sys_ensure * * Function description: * * * Parameters: * hFile - Handle to a file opened via _sys_open * * Return value: * int - * */ int _sys_ensure(FILEHANDLE hFile) { (void)hFile; return (-1); // Not implemented } /********************************************************************* * * _sys_flen * * Function description: * Returns the length of the opened file handle * * Parameters: * hFile - Handle to a file opened via _sys_open * * Return value: * Length of the file * */ long _sys_flen(FILEHANDLE hFile) { (void)hFile; return (0); // Not implemented } /********************************************************************* * * _sys_tmpnam * * Function description: * This function converts the file number fileno for a temporary * file to a unique filename, for example, tmp0001. * * Parameters: * pBuffer - Pointer to a buffer to store the name * FileNum - file number to convert * MaxLen - Size of the buffer * * Return value: * 1 - Error * 0 - Success * */ int _sys_tmpnam(char * pBuffer, int FileNum, unsigned MaxLen) { (void)pBuffer; (void)FileNum; (void)MaxLen; return (1); // Not implemented } /********************************************************************* * * _sys_command_string * * Function description: * This function shall execute a system command. * * Parameters: * cmd - Pointer to the command string * len - Length of the string * * Return value: * == NULL - Command was not successfully executed * == sCmd - Command was passed successfully * */ char * _sys_command_string(char * cmd, int len) { (void)len; return cmd; // Not implemented } /********************************************************************* * * _sys_exit * * Function description: * This function is called when the application returns from main * * Parameters: * ReturnCode - Return code from the main function * * */ void _sys_exit(int ReturnCode) { (void)ReturnCode; while (1); // Not implemented } #if __ARMCC_VERSION >= 5000000 /********************************************************************* * * stdout_putchar * * Function description: * Put a character to the stdout * * Parameters: * ch - Character to output * * */ int stdout_putchar(int ch) { (void)ch; return ch; // Not implemented } #endif #endif /*************************** End of file ****************************/
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V28.Group; using NHapi.Model.V28.Segment; using NHapi.Model.V28.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V28.Message { ///<summary> /// Represents a EHC_E12 message structure (see chapter 16.3.7). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message Header) </li> ///<li>1: SFT (Software Segment) optional repeating</li> ///<li>2: UAC (User Authentication Credential Segment) optional repeating</li> ///<li>3: RFI (Request for Information) </li> ///<li>4: CTD (Contact Data) optional repeating</li> ///<li>5: IVC (Invoice Segment) </li> ///<li>6: PSS (Product/Service Section) </li> ///<li>7: PSG (Product/Service Group) </li> ///<li>8: PID (Patient Identification) optional </li> ///<li>9: PSL (Product/Service Line Item) optional repeating</li> ///<li>10: EHC_E12_REQUEST (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class EHC_E12 : AbstractMessage { ///<summary> /// Creates a new EHC_E12 Group with custom IModelClassFactory. ///</summary> public EHC_E12(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new EHC_E12 Group with DefaultModelClassFactory. ///</summary> public EHC_E12() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for EHC_E12. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(SFT), false, true); this.add(typeof(UAC), false, true); this.add(typeof(RFI), true, false); this.add(typeof(CTD), false, true); this.add(typeof(IVC), true, false); this.add(typeof(PSS), true, false); this.add(typeof(PSG), true, false); this.add(typeof(PID), false, false); this.add(typeof(PSL), false, true); this.add(typeof(EHC_E12_REQUEST), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating EHC_E12 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message Header) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of SFT (Software Segment) - creates it if necessary ///</summary> public SFT GetSFT() { SFT ret = null; try { ret = (SFT)this.GetStructure("SFT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of SFT /// * (Software Segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public SFT GetSFT(int rep) { return (SFT)this.GetStructure("SFT", rep); } /** * Returns the number of existing repetitions of SFT */ public int SFTRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("SFT").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the SFT results */ public IEnumerable<SFT> SFTs { get { for (int rep = 0; rep < SFTRepetitionsUsed; rep++) { yield return (SFT)this.GetStructure("SFT", rep); } } } ///<summary> ///Adds a new SFT ///</summary> public SFT AddSFT() { return this.AddStructure("SFT") as SFT; } ///<summary> ///Removes the given SFT ///</summary> public void RemoveSFT(SFT toRemove) { this.RemoveStructure("SFT", toRemove); } ///<summary> ///Removes the SFT at the given index ///</summary> public void RemoveSFTAt(int index) { this.RemoveRepetition("SFT", index); } ///<summary> /// Returns first repetition of UAC (User Authentication Credential Segment) - creates it if necessary ///</summary> public UAC GetUAC() { UAC ret = null; try { ret = (UAC)this.GetStructure("UAC"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of UAC /// * (User Authentication Credential Segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public UAC GetUAC(int rep) { return (UAC)this.GetStructure("UAC", rep); } /** * Returns the number of existing repetitions of UAC */ public int UACRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("UAC").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the UAC results */ public IEnumerable<UAC> UACs { get { for (int rep = 0; rep < UACRepetitionsUsed; rep++) { yield return (UAC)this.GetStructure("UAC", rep); } } } ///<summary> ///Adds a new UAC ///</summary> public UAC AddUAC() { return this.AddStructure("UAC") as UAC; } ///<summary> ///Removes the given UAC ///</summary> public void RemoveUAC(UAC toRemove) { this.RemoveStructure("UAC", toRemove); } ///<summary> ///Removes the UAC at the given index ///</summary> public void RemoveUACAt(int index) { this.RemoveRepetition("UAC", index); } ///<summary> /// Returns RFI (Request for Information) - creates it if necessary ///</summary> public RFI RFI { get{ RFI ret = null; try { ret = (RFI)this.GetStructure("RFI"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of CTD (Contact Data) - creates it if necessary ///</summary> public CTD GetCTD() { CTD ret = null; try { ret = (CTD)this.GetStructure("CTD"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of CTD /// * (Contact Data) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public CTD GetCTD(int rep) { return (CTD)this.GetStructure("CTD", rep); } /** * Returns the number of existing repetitions of CTD */ public int CTDRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("CTD").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the CTD results */ public IEnumerable<CTD> CTDs { get { for (int rep = 0; rep < CTDRepetitionsUsed; rep++) { yield return (CTD)this.GetStructure("CTD", rep); } } } ///<summary> ///Adds a new CTD ///</summary> public CTD AddCTD() { return this.AddStructure("CTD") as CTD; } ///<summary> ///Removes the given CTD ///</summary> public void RemoveCTD(CTD toRemove) { this.RemoveStructure("CTD", toRemove); } ///<summary> ///Removes the CTD at the given index ///</summary> public void RemoveCTDAt(int index) { this.RemoveRepetition("CTD", index); } ///<summary> /// Returns IVC (Invoice Segment) - creates it if necessary ///</summary> public IVC IVC { get{ IVC ret = null; try { ret = (IVC)this.GetStructure("IVC"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PSS (Product/Service Section) - creates it if necessary ///</summary> public PSS PSS { get{ PSS ret = null; try { ret = (PSS)this.GetStructure("PSS"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PSG (Product/Service Group) - creates it if necessary ///</summary> public PSG PSG { get{ PSG ret = null; try { ret = (PSG)this.GetStructure("PSG"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns PID (Patient Identification) - creates it if necessary ///</summary> public PID PID { get{ PID ret = null; try { ret = (PID)this.GetStructure("PID"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of PSL (Product/Service Line Item) - creates it if necessary ///</summary> public PSL GetPSL() { PSL ret = null; try { ret = (PSL)this.GetStructure("PSL"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of PSL /// * (Product/Service Line Item) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public PSL GetPSL(int rep) { return (PSL)this.GetStructure("PSL", rep); } /** * Returns the number of existing repetitions of PSL */ public int PSLRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("PSL").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the PSL results */ public IEnumerable<PSL> PSLs { get { for (int rep = 0; rep < PSLRepetitionsUsed; rep++) { yield return (PSL)this.GetStructure("PSL", rep); } } } ///<summary> ///Adds a new PSL ///</summary> public PSL AddPSL() { return this.AddStructure("PSL") as PSL; } ///<summary> ///Removes the given PSL ///</summary> public void RemovePSL(PSL toRemove) { this.RemoveStructure("PSL", toRemove); } ///<summary> ///Removes the PSL at the given index ///</summary> public void RemovePSLAt(int index) { this.RemoveRepetition("PSL", index); } ///<summary> /// Returns first repetition of EHC_E12_REQUEST (a Group object) - creates it if necessary ///</summary> public EHC_E12_REQUEST GetREQUEST() { EHC_E12_REQUEST ret = null; try { ret = (EHC_E12_REQUEST)this.GetStructure("REQUEST"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of EHC_E12_REQUEST /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public EHC_E12_REQUEST GetREQUEST(int rep) { return (EHC_E12_REQUEST)this.GetStructure("REQUEST", rep); } /** * Returns the number of existing repetitions of EHC_E12_REQUEST */ public int REQUESTRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("REQUEST").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the EHC_E12_REQUEST results */ public IEnumerable<EHC_E12_REQUEST> REQUESTs { get { for (int rep = 0; rep < REQUESTRepetitionsUsed; rep++) { yield return (EHC_E12_REQUEST)this.GetStructure("REQUEST", rep); } } } ///<summary> ///Adds a new EHC_E12_REQUEST ///</summary> public EHC_E12_REQUEST AddREQUEST() { return this.AddStructure("REQUEST") as EHC_E12_REQUEST; } ///<summary> ///Removes the given EHC_E12_REQUEST ///</summary> public void RemoveREQUEST(EHC_E12_REQUEST toRemove) { this.RemoveStructure("REQUEST", toRemove); } ///<summary> ///Removes the EHC_E12_REQUEST at the given index ///</summary> public void RemoveREQUESTAt(int index) { this.RemoveRepetition("REQUEST", index); } } }
{ "pile_set_name": "Github" }
'use strict'; var TYPE_STRING = 'string'; var TYPE_EXPRESSION = 'expression'; var TYPE_RAW = 'raw'; var TYPE_ESCAPE = 'escape'; function wrapString(token) { var value = new String(token.value); value.line = token.line; value.start = token.start; value.end = token.end; return value; } function Token(type, value, prevToken) { this.type = type; this.value = value; this.script = null; if (prevToken) { this.line = prevToken.line + prevToken.value.split(/\n/).length - 1; if (this.line === prevToken.line) { this.start = prevToken.end; } else { this.start = prevToken.value.length - prevToken.value.lastIndexOf('\n') - 1; } } else { this.line = 0; this.start = 0; } this.end = this.start + this.value.length; } /** * 将模板转换为 Tokens * @param {string} source * @param {Object[]} rules @see defaults.rules * @param {Object} context * @return {Object[]} */ var tplTokenizer = function tplTokenizer(source, rules) { var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var tokens = [new Token(TYPE_STRING, source)]; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; var flags = rule.test.ignoreCase ? 'ig' : 'g'; var regexp = new RegExp(rule.test.source, flags); for (var _i = 0; _i < tokens.length; _i++) { var token = tokens[_i]; var prevToken = tokens[_i - 1]; if (token.type !== TYPE_STRING) { continue; } var match = void 0, index = 0; var substitute = []; var value = token.value; while ((match = regexp.exec(value)) !== null) { if (match.index > index) { prevToken = new Token(TYPE_STRING, value.slice(index, match.index), prevToken); substitute.push(prevToken); } prevToken = new Token(TYPE_EXPRESSION, match[0], prevToken); match[0] = wrapString(prevToken); prevToken.script = rule.use.apply(context, match); substitute.push(prevToken); index = match.index + match[0].length; } if (index < value.length) { prevToken = new Token(TYPE_STRING, value.slice(index), prevToken); substitute.push(prevToken); } tokens.splice.apply(tokens, [_i, 1].concat(substitute)); _i += substitute.length - 1; } } return tokens; }; tplTokenizer.TYPE_STRING = TYPE_STRING; tplTokenizer.TYPE_EXPRESSION = TYPE_EXPRESSION; tplTokenizer.TYPE_RAW = TYPE_RAW; tplTokenizer.TYPE_ESCAPE = TYPE_ESCAPE; module.exports = tplTokenizer;
{ "pile_set_name": "Github" }
/* Copyright 2006-2014 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/flyweight for library home page. */ #ifndef BOOST_FLYWEIGHT_KEY_VALUE_HPP #define BOOST_FLYWEIGHT_KEY_VALUE_HPP #if defined(_MSC_VER) #pragma once #endif #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <boost/detail/workaround.hpp> #include <boost/flyweight/detail/perfect_fwd.hpp> #include <boost/flyweight/detail/value_tag.hpp> #include <boost/flyweight/key_value_fwd.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits/aligned_storage.hpp> #include <boost/type_traits/alignment_of.hpp> #include <boost/type_traits/is_same.hpp> #include <new> /* key-value policy: flywewight lookup is based on Key, which also serves * to construct Value only when needed (new factory entry). key_value is * used to avoid the construction of temporary values when such construction * is expensive. * Optionally, KeyFromValue extracts the key from a value, which * is needed in expressions like this: * * typedef flyweight<key_value<Key,Value> > fw_t; * fw_t fw; * Value v; * fw=v; // no key explicitly given * * If no KeyFromValue is provided, this latter expression fails to compile. */ namespace boost{ namespace flyweights{ namespace detail{ template<typename Key,typename Value,typename KeyFromValue> struct optimized_key_value:value_marker { typedef Key key_type; typedef Value value_type; class rep_type { public: /* template ctors */ #define BOOST_FLYWEIGHT_PERFECT_FWD_CTR_BODY(args) \ :value_ptr(0) \ { \ new(spc_ptr())key_type(BOOST_FLYWEIGHT_FORWARD(args)); \ } BOOST_FLYWEIGHT_PERFECT_FWD( explicit rep_type, BOOST_FLYWEIGHT_PERFECT_FWD_CTR_BODY) #undef BOOST_FLYWEIGHT_PERFECT_FWD_CTR_BODY rep_type(const rep_type& x):value_ptr(x.value_ptr) { if(!x.value_ptr)new(key_ptr())key_type(*x.key_ptr()); } rep_type(const value_type& x):value_ptr(&x){} #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) rep_type(rep_type&& x):value_ptr(x.value_ptr) { if(!x.value_ptr)new(key_ptr())key_type(std::move(*x.key_ptr())); } rep_type(value_type&& x):value_ptr(&x){} #endif ~rep_type() { if(!value_ptr) key_ptr()->~key_type(); else if(value_cted())value_ptr->~value_type(); } operator const key_type&()const { if(value_ptr)return key_from_value(*value_ptr); else return *key_ptr(); } operator const value_type&()const { /* This is always called after construct_value() or copy_value(), * so we access spc directly rather than through value_ptr to * save us an indirection. */ return *static_cast<value_type*>(spc_ptr()); } private: friend struct optimized_key_value; void* spc_ptr()const{return static_cast<void*>(&spc);} bool value_cted()const{return value_ptr==spc_ptr();} key_type* key_ptr()const { return static_cast<key_type*>(static_cast<void*>(&spc)); } static const key_type& key_from_value(const value_type& x) { KeyFromValue k; return k(x); } void construct_value()const { if(!value_cted()){ /* value_ptr must be ==0, oherwise copy_value would have been called */ #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) key_type k(std::move(*key_ptr())); #else key_type k(*key_ptr()); #endif key_ptr()->~key_type(); value_ptr= /* guarantees key won't be re-dted at ~rep_type if the */ static_cast<value_type*>(spc_ptr())+1; /* next statement throws */ value_ptr=new(spc_ptr())value_type(k); } } void copy_value()const { if(!value_cted())value_ptr=new(spc_ptr())value_type(*value_ptr); } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) void move_value()const { if(!value_cted())value_ptr= new(spc_ptr())value_type(std::move(const_cast<value_type&>(*value_ptr))); } #endif mutable typename boost::aligned_storage< (sizeof(key_type)>sizeof(value_type))? sizeof(key_type):sizeof(value_type), (boost::alignment_of<key_type>::value > boost::alignment_of<value_type>::value)? boost::alignment_of<key_type>::value: boost::alignment_of<value_type>::value >::type spc; mutable const value_type* value_ptr; }; static void construct_value(const rep_type& r) { r.construct_value(); } static void copy_value(const rep_type& r) { r.copy_value(); } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) static void move_value(const rep_type& r) { r.move_value(); } #endif }; template<typename Key,typename Value> struct regular_key_value:value_marker { typedef Key key_type; typedef Value value_type; class rep_type { public: /* template ctors */ #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)&&\ !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)&&\ BOOST_WORKAROUND(__GNUC__,<=4)&&(__GNUC__<4||__GNUC_MINOR__<=4) /* GCC 4.4.2 (and probably prior) bug: the default ctor generated by the * variadic temmplate ctor below fails to value-initialize key. */ rep_type():key(),value_ptr(0){} #endif #define BOOST_FLYWEIGHT_PERFECT_FWD_CTR_BODY(args) \ :key(BOOST_FLYWEIGHT_FORWARD(args)),value_ptr(0){} BOOST_FLYWEIGHT_PERFECT_FWD( explicit rep_type, BOOST_FLYWEIGHT_PERFECT_FWD_CTR_BODY) #undef BOOST_FLYWEIGHT_PERFECT_FWD_CTR_BODY rep_type(const rep_type& x):key(x.key),value_ptr(0){} rep_type(const value_type& x):key(no_key_from_value_failure()){} #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) rep_type(rep_type&& x):key(std::move(x.key)),value_ptr(0){} rep_type(value_type&& x):key(no_key_from_value_failure()){} #endif ~rep_type() { if(value_ptr)value_ptr->~value_type(); } operator const key_type&()const{return key;} operator const value_type&()const { /* This is always called after construct_value(),so we access spc * directly rather than through value_ptr to save us an indirection. */ return *static_cast<value_type*>(spc_ptr()); } private: friend struct regular_key_value; void* spc_ptr()const{return static_cast<void*>(&spc);} struct no_key_from_value_failure { BOOST_MPL_ASSERT_MSG( false, NO_KEY_FROM_VALUE_CONVERSION_PROVIDED, (key_type,value_type)); operator const key_type&()const; }; void construct_value()const { if(!value_ptr)value_ptr=new(spc_ptr())value_type(key); } key_type key; mutable typename boost::aligned_storage< sizeof(value_type), boost::alignment_of<value_type>::value >::type spc; mutable const value_type* value_ptr; }; static void construct_value(const rep_type& r) { r.construct_value(); } /* copy_value() and move_value() can't really ever be called, provided to avoid * compile errors (it is the no_key_from_value_failure compile error we want to * appear in these cases). */ static void copy_value(const rep_type&){} #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) static void move_value(const rep_type&){} #endif }; } /* namespace flyweights::detail */ template<typename Key,typename Value,typename KeyFromValue> struct key_value: mpl::if_< is_same<KeyFromValue,no_key_from_value>, detail::regular_key_value<Key,Value>, detail::optimized_key_value<Key,Value,KeyFromValue> >::type {}; } /* namespace flyweights */ } /* namespace boost */ #endif
{ "pile_set_name": "Github" }
mode: ContinuousDelivery next-version: 8.11.0 major-version-bump-message: '\s?(breaking|major|breaking\schange)' minor-version-bump-message: '\s?(add|feature|minor)' patch-version-bump-message: '\s?(fix|patch)' no-bump-message: '\+semver:\s?(none|skip)' assembly-informational-format: '{NuGetVersionV2}+Sha.{Sha}.Date.{CommitDate}' branches: master: tag: preview pull-request: tag: PR feature: tag: useBranchName increment: Minor regex: f(eature(s)?)?[\/-] source-branches: ['master'] hotfix: tag: fix increment: Patch regex: (hot)?fix(es)?[\/-] source-branches: ['master'] ignore: sha: [] merge-message-formats: {}
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 #include "print_binary.h" #include <linux/log2.h> #include "sane_ctype.h" int binary__fprintf(unsigned char *data, size_t len, size_t bytes_per_line, binary__fprintf_t printer, void *extra, FILE *fp) { size_t i, j, mask; int printed = 0; if (!printer) return 0; bytes_per_line = roundup_pow_of_two(bytes_per_line); mask = bytes_per_line - 1; printed += printer(BINARY_PRINT_DATA_BEGIN, 0, extra, fp); for (i = 0; i < len; i++) { if ((i & mask) == 0) { printed += printer(BINARY_PRINT_LINE_BEGIN, -1, extra, fp); printed += printer(BINARY_PRINT_ADDR, i, extra, fp); } printed += printer(BINARY_PRINT_NUM_DATA, data[i], extra, fp); if (((i & mask) == mask) || i == len - 1) { for (j = 0; j < mask-(i & mask); j++) printed += printer(BINARY_PRINT_NUM_PAD, -1, extra, fp); printer(BINARY_PRINT_SEP, i, extra, fp); for (j = i & ~mask; j <= i; j++) printed += printer(BINARY_PRINT_CHAR_DATA, data[j], extra, fp); for (j = 0; j < mask-(i & mask); j++) printed += printer(BINARY_PRINT_CHAR_PAD, i, extra, fp); printed += printer(BINARY_PRINT_LINE_END, -1, extra, fp); } } printed += printer(BINARY_PRINT_DATA_END, -1, extra, fp); return printed; } int is_printable_array(char *p, unsigned int len) { unsigned int i; if (!p || !len || p[len - 1] != 0) return 0; len--; for (i = 0; i < len; i++) { if (!isprint(p[i]) && !isspace(p[i])) return 0; } return 1; }
{ "pile_set_name": "Github" }
require "#{RAILS_ROOT}/config/environment" require 'rails_generator' require 'rails_generator/scripts/generate' ARGV.shift if ['--help', '-h'].include?(ARGV[0]) Rails::Generator::Scripts::Generate.new.run(ARGV)
{ "pile_set_name": "Github" }
/*---------------------------------------------------------------------------- * Copyright (c) <2016-2018>, <Huawei Technologies Co., Ltd> * 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. * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * 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. *---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- * Notice of Export Control Law * =============================================== * Huawei LiteOS may be subject to applicable export control laws and regulations, which might * include those applicable to Huawei LiteOS of U.S. and the country in which you are located. * Import, export and usage of Huawei LiteOS in any manner by you shall be in compliance with such * applicable export control laws and regulations. *---------------------------------------------------------------------------*/ #include "osport.h" typedef struct { u32_t debugrxmode: 2; //1means ascii 2 hex while others means no debug u32_t debugtxmode: 2; //1means ascii 2 hex while others means no debug } tagIOCB; static tagIOCB gIOCB; //import the uart here extern s32_t uart_read(u8_t *buf, s32_t len, s32_t timeout); extern s32_t uart_write(u8_t *buf, s32_t len, s32_t timeout); #pragma weak uart_read s32_t uart_read(u8_t *buf, s32_t len, s32_t timeout) { return 0; } #pragma weak uart_write s32_t uart_write(u8_t *buf, s32_t len, s32_t timeout) { return 0; } //we do some port here:we port the uart s32_t iodev_open(const char *name, s32_t flags, s32_t mode) { s32_t fd = 1; return fd; } s32_t iodev_read(s32_t fd, u8_t *buf, s32_t len, s32_t timeout) { s32_t i = 0; s32_t ret; ret = uart_read(buf, len, timeout); if(ret > 0) { printf("RCV:%02x Bytes:", ret); for(i = 0; i < ret; i++) { if(gIOCB.debugrxmode == 1) { printf("%c", buf[i]); } else if(gIOCB.debugrxmode == 2) { printf(" %02x", buf[i]); } else { } } printf("\n\r"); } return ret; } s32_t iodev_write(s32_t fd, u8_t *buf, s32_t len, s32_t timeout) { s32_t ret; s32_t i; printf("SND:%02x Bytes:", len); for(i = 0; i < len; i++) { if(gIOCB.debugtxmode == 1) { printf("%c", buf[i]); } else if(gIOCB.debugtxmode == 2) { printf(" %02x", buf[i]); } else { } } printf("\n\r"); ret = uart_write(buf, len, timeout); return ret; } s32_t iodev_close(s32_t fd) { return 0; } s32_t iodev_flush(s32_t fd) { unsigned char buf; s32_t ret; do { ret = iodev_read(fd, &buf, 1, 0); } while(ret > 0); return 0; } void iodev_debugmode(s32_t rxtx, u32_t mode) { if(rxtx == 0) { gIOCB.debugrxmode = mode; } else if(rxtx == 1) { gIOCB.debugtxmode = mode; } else if(rxtx == 2) { gIOCB.debugrxmode = mode; gIOCB.debugtxmode = mode; } else //do nothing here { } return; }
{ "pile_set_name": "Github" }
// +build windows // +build !go1.4 package mousetrap import ( "fmt" "os" "syscall" "unsafe" ) const ( // defined by the Win32 API th32cs_snapprocess uintptr = 0x2 ) var ( kernel = syscall.MustLoadDLL("kernel32.dll") CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot") Process32First = kernel.MustFindProc("Process32FirstW") Process32Next = kernel.MustFindProc("Process32NextW") ) // ProcessEntry32 structure defined by the Win32 API type processEntry32 struct { dwSize uint32 cntUsage uint32 th32ProcessID uint32 th32DefaultHeapID int th32ModuleID uint32 cntThreads uint32 th32ParentProcessID uint32 pcPriClassBase int32 dwFlags uint32 szExeFile [syscall.MAX_PATH]uint16 } func getProcessEntry(pid int) (pe *processEntry32, err error) { snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0)) if snapshot == uintptr(syscall.InvalidHandle) { err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1) return } defer syscall.CloseHandle(syscall.Handle(snapshot)) var processEntry processEntry32 processEntry.dwSize = uint32(unsafe.Sizeof(processEntry)) ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) if ok == 0 { err = fmt.Errorf("Process32First: %v", e1) return } for { if processEntry.th32ProcessID == uint32(pid) { pe = &processEntry return } ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) if ok == 0 { err = fmt.Errorf("Process32Next: %v", e1) return } } } func getppid() (pid int, err error) { pe, err := getProcessEntry(os.Getpid()) if err != nil { return } pid = int(pe.th32ParentProcessID) return } // StartedByExplorer returns true if the program was invoked by the user double-clicking // on the executable from explorer.exe // // It is conservative and returns false if any of the internal calls fail. // It does not guarantee that the program was run from a terminal. It only can tell you // whether it was launched from explorer.exe func StartedByExplorer() bool { ppid, err := getppid() if err != nil { return false } pe, err := getProcessEntry(ppid) if err != nil { return false } name := syscall.UTF16ToString(pe.szExeFile[:]) return name == "explorer.exe" }
{ "pile_set_name": "Github" }
# -*- coding: binary -*- module Rex module Proto module Kerberos module Model # This class provides a representation of a principal, an asset (e.g., a # workstation user or a network server) on a network. class PrincipalName < Element # @!attribute name_type # @return [Integer] The type of name attr_accessor :name_type # @!attribute name_string # @return [Array<String>] A sequence of strings that form a name. attr_accessor :name_string # Decodes a Rex::Proto::Kerberos::Model::PrincipalName # # @param input [String, OpenSSL::ASN1::Sequence] the input to decode from # @return [self] if decoding succeeds # @raise [RuntimeError] if decoding doesn't succeed def decode(input) case input when String decode_string(input) when OpenSSL::ASN1::Sequence decode_asn1(input) else raise ::RuntimeError, 'Failed to decode Principal Name, invalid input' end self end # Encodes a Rex::Proto::Kerberos::Model::PrincipalName into an # ASN.1 String # # @return [String] def encode integer_asn1 = OpenSSL::ASN1::ASN1Data.new([encode_name_type], 0, :CONTEXT_SPECIFIC) string_asn1 = OpenSSL::ASN1::ASN1Data.new([encode_name_string], 1, :CONTEXT_SPECIFIC) seq = OpenSSL::ASN1::Sequence.new([integer_asn1, string_asn1]) seq.to_der end private # Encodes the name_type # # @return [OpenSSL::ASN1::Integer] def encode_name_type int_bn = OpenSSL::BN.new(name_type.to_s) int = OpenSSL::ASN1::Integer.new(int_bn) int end # Encodes the name_string # # @return [OpenSSL::ASN1::Sequence] def encode_name_string strings = [] name_string.each do |s| strings << OpenSSL::ASN1::GeneralString.new(s) end seq_string = OpenSSL::ASN1::Sequence.new(strings) seq_string end # Decodes a Rex::Proto::Kerberos::Model::PrincipalName from an String # # @param input [String] the input to decode from def decode_string(input) asn1 = OpenSSL::ASN1.decode(input) decode_asn1(asn1) end # Decodes a Rex::Proto::Kerberos::Model::PrincipalName from an # OpenSSL::ASN1::Sequence # # @param input [OpenSSL::ASN1::Sequence] the input to decode from def decode_asn1(input) seq_values = input.value self.name_type = decode_name_type(seq_values[0]) self.name_string = decode_name_string(seq_values[1]) end # Decodes the name_type from an OpenSSL::ASN1::ASN1Data # # @param input [OpenSSL::ASN1::ASN1Data] the input to decode from # @return [Integer] def decode_name_type(input) input.value[0].value.to_i end # Decodes the name_string from an OpenSSL::ASN1::ASN1Data # # @param input [OpenSSL::ASN1::ASN1Data] the input to decode from # @return [Array<String>] def decode_name_string(input) strings = [] input.value[0].value.each do |v| strings << v.value end strings end end end end end end
{ "pile_set_name": "Github" }
/* Actiona Copyright (C) 2005 Jonathan Mercier-Ganady Actiona 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. Actiona 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/>. Contact : jmgr@jmgr.info */ #include "scriptproxymodel.h" #include "scriptmodel.h" #include "script.h" #include "actioninstance.h" #include "actiondefinition.h" #include "numberformat.h" #include <QDebug> ScriptProxyModel::ScriptProxyModel(ActionTools::Script *script, QObject *parent) : QSortFilterProxyModel(parent), mScript(script), mFilteringFlags(ActionFilteringFlag::AllFlags) { } void ScriptProxyModel::setFilterString(const QString &filterString) { mFilterString = filterString; invalidateFilter(); } void ScriptProxyModel::setFilteringFlags(ActionFilteringFlags filteringFlags) { mFilteringFlags = filteringFlags; invalidateFilter(); } bool ScriptProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { if(mFilterString.isEmpty()) return true; QModelIndex index = sourceModel()->index(source_row, 0, source_parent); if(!index.isValid()) return false; if(index.row() >= mScript->actionCount()) return false; ActionTools::ActionInstance *actionInstance = mScript->actionAt(index.row()); if(!actionInstance) return false; const ActionTools::ActionDefinition *actionDefinition = actionInstance->definition(); if((mFilteringFlags == 0 || mFilteringFlags.testFlag(ActionFilteringFlag::ActionName)) && actionDefinition->name().contains(mFilterString, Qt::CaseInsensitive)) return true; if((mFilteringFlags == 0 || mFilteringFlags.testFlag(ActionFilteringFlag::Label)) && ((actionInstance->label().contains(mFilterString, Qt::CaseInsensitive)) || ActionTools::NumberFormat::labelIndexString(index.row()).contains(mFilterString, Qt::CaseInsensitive))) return true; if(((mFilteringFlags == 0 || mFilteringFlags.testFlag(ActionFilteringFlag::Comment)) && actionInstance->comment().contains(mFilterString, Qt::CaseInsensitive))) return true; if(mFilteringFlags == 0 || mFilteringFlags.testFlag(ActionFilteringFlag::CodeParameters)) { for(const auto &parameter: actionInstance->parametersData()) { for(const auto &subParameter: parameter.subParameters()) { if(subParameter.isCode() && subParameter.value().contains(mFilterString, Qt::CaseInsensitive)) return true; } } } if(mFilteringFlags == 0 || mFilteringFlags.testFlag(ActionFilteringFlag::TextParameters)) { for(const auto &parameter: actionInstance->parametersData()) { for(const auto &subParameter: parameter.subParameters()) { if(!subParameter.isCode() && subParameter.value().contains(mFilterString, Qt::CaseInsensitive)) return true; } } } return false; }
{ "pile_set_name": "Github" }
/** * * WARNING! This file was autogenerated by: * _ _ _ _ __ __ * | | | | | | |\ \ / / * | | | | |_| | \ V / * | | | | _ | / \ * | |_| | | | |/ /^\ \ * \___/\_| |_/\/ \/ * * This file was autogenerated by UnrealHxGenerator using UHT definitions. * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal; /** WARNING: This type was defined as MinimalAPI on its declaration. Because of that, its properties/methods are inaccessible **/ @:glueCppIncludes("Particles/Rotation/ParticleModuleRotationOverLifetime.h") @:uextern @:uclass extern class UParticleModuleRotationOverLifetime extends unreal.UParticleModuleRotationBase { /** If true, the particle rotation is multiplied by the value retrieved from RotationOverLife. If false, the particle rotation is incremented by the value retrieved from RotationOverLife. **/ @:uproperty public var Scale : Bool; /** The rotation of the particle (1.0 = 360 degrees). The value is retrieved using the RelativeTime of the particle. **/ @:uproperty public var RotationOverLife : unreal.FRawDistributionFloat; }
{ "pile_set_name": "Github" }
# created by tools/loadICU.tcl -- do not edit namespace eval ::tcl::clock { ::msgcat::mcset pl DAYS_OF_WEEK_ABBREV [list \ "N"\ "Pn"\ "Wt"\ "\u015ar"\ "Cz"\ "Pt"\ "So"] ::msgcat::mcset pl DAYS_OF_WEEK_FULL [list \ "niedziela"\ "poniedzia\u0142ek"\ "wtorek"\ "\u015broda"\ "czwartek"\ "pi\u0105tek"\ "sobota"] ::msgcat::mcset pl MONTHS_ABBREV [list \ "sty"\ "lut"\ "mar"\ "kwi"\ "maj"\ "cze"\ "lip"\ "sie"\ "wrz"\ "pa\u017a"\ "lis"\ "gru"\ ""] ::msgcat::mcset pl MONTHS_FULL [list \ "stycze\u0144"\ "luty"\ "marzec"\ "kwiecie\u0144"\ "maj"\ "czerwiec"\ "lipiec"\ "sierpie\u0144"\ "wrzesie\u0144"\ "pa\u017adziernik"\ "listopad"\ "grudzie\u0144"\ ""] ::msgcat::mcset pl BCE "p.n.e." ::msgcat::mcset pl CE "n.e." ::msgcat::mcset pl DATE_FORMAT "%Y-%m-%d" ::msgcat::mcset pl TIME_FORMAT "%H:%M:%S" ::msgcat::mcset pl DATE_TIME_FORMAT "%Y-%m-%d %H:%M:%S %z" }
{ "pile_set_name": "Github" }
#!/bin/bash ###SHELLPACK preamble thotdata-bench 0 ###SHELLPACK parseargBegin ###SHELLPACK parseargInstall ###SHELLPACK parseargParam --min-threads THOTDATA_MIN_THREADS ###SHELLPACK parseargParam --max-threads THOTDATA_MAX_THREADS ###SHELLPACK parseargEnd ###SHELLPACK monitor_hooks ###SHELLPACK check_install_required thotdata-${VERSION} ###SHELLPACK init_complete cd $SHELLPACK_SOURCES/thotdata-${VERSION}-installed || die Failed to change to benchmark directory # Get a list of interleaved CPU between available nodes TIFS=$IFS IFS=" " NODE=0 for LINE in `numactl --hardware | grep cpus: | awk -F ": " '{print $2}'`; do echo $LINE | sed -e 's/ /\n/g' > $SHELLPACK_TEMP/interleave.$NODE.$$ NODE=$((NODE+1)) done cat $SHELLPACK_TEMP/interleave.*.$$ > $SHELLPACK_TEMP/bynode.$$ paste -d '\n' $SHELLPACK_TEMP/interleave.*.$$ > $SHELLPACK_TEMP/interleave.$$ rm $SHELLPACK_TEMP/interleave.*.$$ IFS=$TIFS cpupower frequency-set -g performance for ALIGNMENT in 64 4096 2097152; do ###SHELLPACK threads_powertwo_begin $THOTDATA_MIN_THREADS $THOTDATA_MAX_THREADS CPULIST=`head -$NR_THREADS $SHELLPACK_TEMP/bynode.$$ | tr '\n' ' '` MIN_LATENCY=100000 if [ $ALIGNMENT -eq 2097152 ]; then MIN_LATENCY=3500000 fi monitor_pre_hook $LOGDIR_RESULTS $NR_THREADS-$ALIGNMENT echo Starting $NR_THREADS/$THOTDATA_MAX_THREADS with alignment $ALIGNMENT echo o $CPULIST $TIME_CMD -o $LOGDIR_RESULTS/threads-${NR_THREADS}-$ALIGNMENT.time \ ./thotdata $ALIGNMENT $MIN_LATENCY $CPULIST \ > $LOGDIR_RESULTS/threads-${NR_THREADS}-$ALIGNMENT.log 2>&1 monitor_post_hook $LOGDIR_RESULTS $NR_THREADS-$ALIGNMENT ###SHELLPACK threads_powertwo_end done rm $SHELLPACK_TEMP/interleave.$$ rm $SHELLPACK_TEMP/bynode.$$ exit $SHELLPACK_SUCCESS
{ "pile_set_name": "Github" }
Images, layout descriptions, binary blobs and string dictionaries can be included in your application as resource files. Various Android APIs are designed to operate on the resource IDs instead of dealing with images, strings or binary blobs directly. For example, a sample Android app that contains a user interface layout (main.xml), an internationalization string table (strings.xml) and some icons (drawable-XXX/icon.png) would keep its resources in the "Resources" directory of the application: Resources/ drawable-hdpi/ icon.png drawable-ldpi/ icon.png drawable-mdpi/ icon.png layout/ main.xml values/ strings.xml In order to get the build system to recognize Android resources, set the build action to "AndroidResource". The native Android APIs do not operate directly with filenames, but instead operate on resource IDs. When you compile an Android application that uses resources, the build system will package the resources for distribution and generate a class called "Resource" that contains the tokens for each one of the resources included. For example, for the above Resources layout, this is what the Resource class would expose: public class Resource { public class drawable { public const int icon = 0x123; } public class layout { public const int main = 0x456; } public class strings { public const int first_string = 0xabc; public const int second_string = 0xbcd; } } You would then use R.drawable.icon to reference the drawable/icon.png file, or Resource.layout.main to reference the layout/main.xml file, or Resource.strings.first_string to reference the first string in the dictionary file values/strings.xml.
{ "pile_set_name": "Github" }
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "CWriteFile.h" #include <stdio.h> namespace irr { namespace io { CWriteFile::CWriteFile(const io::path& fileName, bool append) : FileSize(0) { #ifdef _DEBUG setDebugName("CWriteFile"); #endif Filename = fileName; openFile(append); } CWriteFile::~CWriteFile() { if (File) fclose(File); } //! returns if file is open inline bool CWriteFile::isOpen() const { return File != 0; } //! returns how much was read s32 CWriteFile::write(const void* buffer, u32 sizeToWrite) { if (!isOpen()) return 0; return (s32)fwrite(buffer, 1, sizeToWrite, File); } //! changes position in file, returns true if successful //! if relativeMovement==true, the pos is changed relative to current pos, //! otherwise from begin of file bool CWriteFile::seek(long finalPos, bool relativeMovement) { if (!isOpen()) return false; return fseek(File, finalPos, relativeMovement ? SEEK_CUR : SEEK_SET) == 0; } //! returns where in the file we are. long CWriteFile::getPos() const { return ftell(File); } //! opens the file void CWriteFile::openFile(bool append) { if (Filename.size() == 0) { File = 0; return; } #if defined(_IRR_WCHAR_FILESYSTEM) File = _wfopen(Filename.c_str(), append ? L"ab" : L"wb"); #else File = fopen(Filename.c_str(), append ? "ab" : "wb"); #endif if (File) { // get FileSize fseek(File, 0, SEEK_END); FileSize = ftell(File); fseek(File, 0, SEEK_SET); } } //! returns name of file const io::path& CWriteFile::getFileName() const { return Filename; } IWriteFile* createWriteFile(const io::path& fileName, bool append) { CWriteFile* file = new CWriteFile(fileName, append); if (file->isOpen()) return file; file->drop(); return 0; } } // end namespace io } // end namespace irr
{ "pile_set_name": "Github" }
/* Copyright (C) 2001-2006, William Joseph. All Rights Reserved. This file is part of GtkRadiant. GtkRadiant is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GtkRadiant 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 GtkRadiant; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #if !defined(INCLUDED_SELECTION_H) #define INCLUDED_SELECTION_H #include "windowobserver.h" struct rect_t { float min[2]; float max[2]; }; template<typename FirstArgument> class Callback1; typedef Callback1<rect_t> RectangleCallback; class View; class Callback; class SelectionSystemWindowObserver : public WindowObserver { public: virtual void setView(const View& view) = 0; virtual void setRectangleDrawCallback(const RectangleCallback& callback) = 0; }; SelectionSystemWindowObserver* NewWindowObserver(); class AABB; namespace scene { class Graph; } void Scene_BoundsSelected(scene::Graph& graph, AABB& bounds); #endif
{ "pile_set_name": "Github" }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/fastlib/io/bufferedfile.h> #include <vespa/searchlib/common/bitvector.h> #include <vespa/searchlib/common/tunefileinfo.h> #include <vespa/vespalib/stllike/string.h> #include <vespa/vespalib/stllike/allocator.h> #include "bitvectoridxfile.h" namespace search::diskindex { class BitVectorFileWrite : public BitVectorIdxFileWrite { private: using Parent = BitVectorIdxFileWrite; Fast_BufferedFile *_datFile; public: private: uint32_t _datHeaderLen; public: BitVectorFileWrite(const BitVectorFileWrite &) = delete; BitVectorFileWrite(const BitVectorFileWrite &&) = delete; BitVectorFileWrite& operator=(const BitVectorFileWrite &) = delete; BitVectorFileWrite& operator=(const BitVectorFileWrite &&) = delete; BitVectorFileWrite(BitVectorKeyScope scope); ~BitVectorFileWrite(); void open(const vespalib::string &name, uint32_t docIdLimit, const TuneFileSeqWrite &tuneFileWrite, const common::FileHeaderContext &fileHeaderContext); void addWordSingle(uint64_t wordNum, const BitVector &bitVector); void flush(); void sync(); void close(); void makeDatHeader(const common::FileHeaderContext &fileHeaderContext); void updateDatHeader(uint64_t fileBitSize); }; /* * Buffer document ids for a candidate bitvector. */ class BitVectorCandidate { private: std::vector<uint32_t, vespalib::allocator_large<uint32_t>> _array; uint64_t _numDocs; uint32_t _bitVectorLimit; BitVector::UP _bv; public: BitVectorCandidate(uint32_t docIdLimit, uint32_t bitVectorLimit) : _array(), _numDocs(0u), _bitVectorLimit(bitVectorLimit), _bv(BitVector::create(docIdLimit)) { _array.reserve(_bitVectorLimit); } BitVectorCandidate(uint32_t docIdLimit) : BitVectorCandidate(docIdLimit, BitVectorFileWrite::getBitVectorLimit(docIdLimit)) { } ~BitVectorCandidate(); void clear() { if (__builtin_expect(_numDocs > _bitVectorLimit, false)) { _bv->clear(); } _numDocs = 0; _array.clear(); } void flush(BitVector &obv) { if (__builtin_expect(_numDocs > _bitVectorLimit, false)) { obv.orWith(*_bv); } else { for (uint32_t i : _array) { obv.setBit(i); } } clear(); } void add(uint32_t docId) { if (_numDocs < _bitVectorLimit) { _array.push_back(docId); } else { if (__builtin_expect(_numDocs == _bitVectorLimit, false)) { for (uint32_t i : _array) { _bv->setBit(i); } _array.clear(); } _bv->setBit(docId); } ++_numDocs; } /* * Get number of documents buffered. This might include duplicates. */ uint64_t getNumDocs() const { return _numDocs; } bool empty() const { return _numDocs == 0; } /* * Return true if array limit has been exceeded and bitvector has been * populated. */ bool getCrossedBitVectorLimit() const { return _numDocs > _bitVectorLimit; } BitVector &getBitVector() { return *_bv; } }; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Root MajorVersion="0" MinorVersion="33"> <CompositeFile CompositeFileTopName="bd_a493" CanBeSetAsTop="true" CanDisplayChildGraph="true"> <Description>Composite Fileset</Description> <Generation Name="SYNTHESIS" State="GENERATED" Timestamp="1519241076"/> <Generation Name="IMPLEMENTATION" State="GENERATED" Timestamp="1519241076"/> <Generation Name="SIMULATION" State="GENERATED" Timestamp="1519241076"/> <Generation Name="HW_HANDOFF" State="GENERATED" Timestamp="1519241076"/> <FileCollection Name="SOURCES" Type="SOURCES"> <File Name="ip/ip_0/bd_a493_xsdbm_0.xci" Type="IP"> <Instance HierarchyPath="xsdbm"/> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="true" IsStatusTracked="true"/> <Library Name="xil_defaultlib"/> <UsedIn Val="SYNTHESIS"/> <UsedIn Val="IMPLEMENTATION"/> <UsedIn Val="SIMULATION"/> </File> <File Name="ip/ip_1/bd_a493_lut_buffer_0.xci" Type="IP"> <Instance HierarchyPath="lut_buffer"/> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="true" IsStatusTracked="true"/> <Library Name="xil_defaultlib"/> <UsedIn Val="SYNTHESIS"/> <UsedIn Val="IMPLEMENTATION"/> <UsedIn Val="SIMULATION"/> </File> <File Name="synth/bd_a493.v" Type="Verilog"> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="false" IsStatusTracked="false"/> <Library Name="xil_defaultlib"/> <UsedIn Val="SYNTHESIS"/> <UsedIn Val="IMPLEMENTATION"/> </File> <File Name="sim/bd_a493.v" Type="Verilog"> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="false" IsStatusTracked="false"/> <Library Name="xil_defaultlib"/> <UsedIn Val="SIMULATION"/> </File> <File Name="bd_a493_ooc.xdc" Type="XDC"> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="false" IsStatusTracked="false"/> <Library Name="xil_defaultlib"/> <UsedIn Val="SYNTHESIS"/> <UsedIn Val="IMPLEMENTATION"/> <UsedIn Val="OUT_OF_CONTEXT"/> </File> <File Name="hw_handoff/cl_debug_bridge.hwh" Type="HwHandoff"> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="false" IsStatusTracked="false"/> <Library Name="xil_defaultlib"/> <UsedIn Val="HW_HANDOFF"/> </File> <File Name="hw_handoff/cl_debug_bridge_bd.tcl"> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="false" IsStatusTracked="false"/> <Library Name="xil_defaultlib"/> <UsedIn Val="HW_HANDOFF"/> </File> <File Name="synth/cl_debug_bridge.hwdef"> <Properties IsEditable="false" IsVisible="true" Timestamp="0" IsTrackable="false" IsStatusTracked="false"/> <Library Name="xil_defaultlib"/> <UsedIn Val="HW_HANDOFF"/> </File> </FileCollection> </CompositeFile> </Root>
{ "pile_set_name": "Github" }
/* * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodbv2.model.transform; import com.amazonaws.services.dynamodbv2.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.amazonaws.util.json.AwsJsonReader; /** * JSON unmarshaller for response GetItemResult */ public class GetItemResultJsonUnmarshaller implements Unmarshaller<GetItemResult, JsonUnmarshallerContext> { public GetItemResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetItemResult getItemResult = new GetItemResult(); AwsJsonReader reader = context.getReader(); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("Item")) { getItemResult.setItem(new MapUnmarshaller<AttributeValue>( AttributeValueJsonUnmarshaller.getInstance() ) .unmarshall(context)); } else if (name.equals("ConsumedCapacity")) { getItemResult.setConsumedCapacity(ConsumedCapacityJsonUnmarshaller.getInstance() .unmarshall(context)); } else { reader.skipValue(); } } reader.endObject(); return getItemResult; } private static GetItemResultJsonUnmarshaller instance; public static GetItemResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetItemResultJsonUnmarshaller(); return instance; } }
{ "pile_set_name": "Github" }
//================= Hercules Script ======================================= //= _ _ _ //= | | | | | | //= | |_| | ___ _ __ ___ _ _| | ___ ___ //= | _ |/ _ \ '__/ __| | | | |/ _ \/ __| //= | | | | __/ | | (__| |_| | | __/\__ \ //= \_| |_/\___|_| \___|\__,_|_|\___||___/ //================= License =============================================== //= This file is part of Hercules. //= http://herc.ws - http://github.com/HerculesWS/Hercules //= //= Copyright (C) 2017-2020 Hercules Dev Team //= Copyright (C) Dastgir //= Copyright (C) Smokexyz (v2.0) //= //= Hercules 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/>. //========================================================================= //= Shadow Refiner //================= Description =========================================== //= Shadow item refiner //================= Current Version ======================================= //= 2.0 //========================================================================= itemmall,31,76,3 script Shadow Blacksmith#nomal 4_F_JOB_BLACKSMITH,{ // Configuration .@npc_name$ = "[Shadow Blacksmith]"; .@zeny_cost = 20000; // Amount of zeny to be charged for refining. mesf("%s", .@npc_name$); mes("Do you want to refine a Shadow item?"); mes("Please choose the part you want to refine."); if (getbattleflag("features/replace_refine_npcs") == 1) { if (openrefineryui()) close(); } next(); disable_items; setarray(.@position$[0],"Armor","Weapon","Shield","Shoes","Earring","Pendant"); for (.@i=EQI_SHADOW_ARMOR; .@i <= EQI_SHADOW_ACC_L; .@i++){ .@menu$ = .@menu$ + (getequipisequiped(.@i) ? getequipname(.@i) : ("^8C8C8C" + .@position$[.@i-EQI_SHADOW_ARMOR] + " [Not Equipped]^000000" + ":")); } .@menu$ = .@menu$ + "Refine Info"; .@SelectedPart = select(.@menu$) + EQI_SHADOW_ARMOR - 1; if (.@SelectedPart == EQI_SHADOW_ACC_L + 1){ // Refine Info mesf("%s", .@npc_name$); mes("Shadow items gain extra bonus effects depending on their refine level, similar to normal weapon and armor items."); next; mesf("%s", .@npc_name$); mes("Refining effects for each Shadow item parts are -"); mes("Weapon: ATK, MATK + 1 increase for each +1 refine success."); mes("Etc: HP + 10 increase for each +1 refine success."); next; mesf("%s", .@npc_name$); mesf("You need %s and %s as the ingredient, along with a refine fee %d Zeny.", getitemname(Oridecon), getitemname(Elunium), .@zeny_cost); next; mesf("%s", .@npc_name$); mes("When refining to +5 or higher, you risk breaking your Shadow item."); mes("You may also use Enriched or HD ingredients for the refinement."); close; } while(true) { mesf("%s", .@npc_name$); mesf("%d Zeny will be spent as a refine fee.", .@zeny_cost); mes("Choose the ingredient and start refining."); next; .@index = 0; if (.@SelectedPart != EQI_SHADOW_WEAPON) .@index = 1; setarray .@s_material1[0], Oridecon, Elunium; setarray .@s_material2[0], Enriched_Oridecon, Enriched_Elunium; setarray .@s_material3[0], HD_Oridecon, HD_Elunium; .@refine_type = REFINE_CHANCE_TYPE_NORMAL; if (countitem(.@s_material1[.@index])) .@mate$[0] = getitemname(.@s_material1[.@index]); else{ .@mate$[0] = "^8C8C8C"+ getitemname(.@s_material1[.@index]) +"^000000"; .@miss[0] = 1; } if (countitem(.@s_material2[.@index])) .@mate$[1] = getitemname(.@s_material2[.@index]); else{ .@mate$[1] = "^8C8C8C"+ getitemname(.@s_material2[.@index]) +"^000000"; .@miss[1] = 1; } if (getequiprefinerycnt(.@SelectedPart) > 6 && countitem(.@s_material3[.@index])) .@mate$[2] = getitemname(.@s_material3[.@index]); else { .@mate$[2] = "^8C8C8C"+ getitemname(.@s_material3[.@index]) +"^000000"; .@miss[2] = 1; } //----------------------------------------------------------------------------- .@option = select("Cancel", .@mate$[0], .@mate$[1], .@mate$[2]); if (.@option == 1){ mesf("%s", .@npc_name$); mes("You've cancelled refining."); close; } .@option -= 2; .@hoihoi = false; if (.@option == 2){ //HD if (getequiprefinerycnt(.@SelectedPart) < 7){ mesf("%s", .@npc_name$); mes("HD ingredients are only possible to be used when refining an item of quality +7 or higher."); close; } .@hoihoi = true; } else if (.@option == 1) { .@refine_type = REFINE_CHANCE_TYPE_ENRICHED; } if (.@miss[.@option]){ mesf("%s", .@npc_name$); mes("You do not have the proper ingredient to proceed with refining."); close; } .@choose = getd(".@s_weapon"+(.@option+1)+"["+ .@index +"]"); if (Zeny < 20000) { mesf("%s", .@npc_name$); mes("You do not have enough Zeny to pay the refine fee."); close; } if (getequiprefinerycnt(.@SelectedPart) > 9) { mesf("%s", .@npc_name$); mes("Shadow item refining is only possible up to +10 level."); close; } if (!getequipisenableref(.@SelectedPart)) { mesf("%s", .@npc_name$); mes("This item cannot be refined."); close; } if (getequippercentrefinery(.@SelectedPart, .@refine_type) < 100) { mesf("%s", .@npc_name$); mes("Safety guaranteed refine limit for shadow item is until +4."); if (.@hoihoi == false) { mes("If you try more refining, the item might break upon failing. Do you still want to refine?"); } else { mes("If you try more refining, the item refine level might go down when failed. Do you still want to refine?"); } next; if (select("Proceed","Cancel") == 2) { mesf("%s", .@npc_name$); mes("You've cancelled refining."); close; } } //----------------------------------------------------------------------------- mesf("%s", .@npc_name$); mes("Here we go--!!!"); next; if (Zeny < 20000) { mesf("%s", .@npc_name$); mes("You do not have enough Zeny to pay the refine fee."); close; } if (countitem(.@choose) == 0) { mesf("%s", .@npc_name$); mes("You do not have enough "+ getitemname(.@choose) +"."); close; } delitem(.@choose, 1); Zeny -= 20000; if (getequippercentrefinery(.@SelectedPart, .@refine_type) > rand(100)) { successrefitem(.@SelectedPart); mesf("%s", .@npc_name$); mes("Refine was successful."); next; } else { if (.@hoihoi == true) downrefitem(.@SelectedPart); else failedrefitem(.@SelectedPart); mesf("%s", .@npc_name$); mes("Oh no.. Refine has failed."); close; } } }
{ "pile_set_name": "Github" }
# include "thread_view_activatable.h" # include <gtk/gtk.h> # include <webkit2/webkit2.h> /** * SECTION: astroid_threadview_activatable * @short_description: Interface for activatable extensions on the shell * @see_also: #PeasExtensionSet * * #AstroidthreadviewActivatable is an interface which should be implemented by * extensions that should be activated on the Liferea main window. **/ G_DEFINE_INTERFACE (AstroidThreadViewActivatable, astroid_threadview_activatable, G_TYPE_OBJECT) void astroid_threadview_activatable_default_init (AstroidThreadViewActivatableInterface *iface) { static gboolean initialized = FALSE; if (!initialized) { /** * AstroidthreadviewActivatable:window: * * The window property contains the gtr window for this * #AstroidActivatable instance. */ g_object_interface_install_property (iface, g_param_spec_object ("thread_view", "thread_view", "The threadview box", GTK_TYPE_BOX, G_PARAM_READWRITE)); g_object_interface_install_property (iface, g_param_spec_object ("web_view", "web_view", "The WebKit Webview", WEBKIT_TYPE_WEB_VIEW, G_PARAM_READWRITE)); initialized = TRUE; } } /** * astroid_threadview_activatable_activate: * @activatable: A #AstroidThreadViewActivatable. * * Activates the extension on the shell property. */ void astroid_threadview_activatable_activate (AstroidThreadViewActivatable * activatable) { AstroidThreadViewActivatableInterface *iface; g_return_if_fail (ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)); iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->activate) iface->activate (activatable); } /** * astroid_threadview_activatable_deactivate: * @activatable: A #AstroidThreadViewActivatable. * * Deactivates the extension on the shell property. */ void astroid_threadview_activatable_deactivate (AstroidThreadViewActivatable * activatable) { AstroidThreadViewActivatableInterface *iface; g_return_if_fail (ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)); iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->deactivate) iface->deactivate (activatable); } /** * astroid_threadview_activatable_update_state: * @activatable: A #AstroidThreadViewActivatable. * * Triggers an update of the extension internal state to take into account * state changes in the window, due to some event or user action. */ void astroid_threadview_activatable_update_state (AstroidThreadViewActivatable * activatable) { AstroidThreadViewActivatableInterface *iface; g_return_if_fail (ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)); iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->update_state) iface->update_state (activatable); } /** * astroid_activatable_get_avatar_uri: * @activatable: A #AstroidThreadViewActivatable. * @email: A #utf8. * @type: A #string. * @size: A #int. * @message: A #GMime.Message. * * Returns: (transfer none): A #string. */ char * astroid_threadview_activatable_get_avatar_uri (AstroidThreadViewActivatable * activatable, const char * email, const char * type, int size, GMimeMessage * message) { AstroidThreadViewActivatableInterface *iface; if (!ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)) return NULL; iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->get_avatar_uri) return iface->get_avatar_uri (activatable, email, type, size, message); return NULL; } /** * astroid_threadview_activatable_get_allowed_uris: * @activatable: A #AstroidThreadViewActivatable. * * Returns: (element-type utf8) (transfer container): List of allowed uris. */ GList * astroid_threadview_activatable_get_allowed_uris (AstroidThreadViewActivatable * activatable) { AstroidThreadViewActivatableInterface *iface; if (!ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)) return NULL; iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->get_allowed_uris) return iface->get_allowed_uris (activatable); return NULL; } /** * astroid_threadview_activatable_format_tags: * @activatable: A #AstroidThreadViewActivatable. * @bg : A #utf8. * @tags: (element-type utf8) (transfer none): List of #utf8. * @selected: A #bool. * */ char * astroid_threadview_activatable_format_tags (AstroidThreadViewActivatable * activatable, const char * bg, GList * tags, bool selected) { AstroidThreadViewActivatableInterface *iface; if (!ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)) return NULL; iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->format_tags) return iface->format_tags (activatable, bg, tags, selected); return NULL; } /** * astroid_threadview_activatable_filter_part: * @activatable: A #AstroidThreadViewActivatable. * @input_text : A #utf8. * @input_html : A #utf8. * @mime_type : A #utf8. * @is_patch : A #bool. * */ char * astroid_threadview_activatable_filter_part ( AstroidThreadViewActivatable * activatable, const char * input_text, const char * input_html, const char * mime_type, bool is_patch) { AstroidThreadViewActivatableInterface *iface; if (!ASTROID_IS_THREADVIEW_ACTIVATABLE (activatable)) return NULL; iface = ASTROID_THREADVIEW_ACTIVATABLE_GET_IFACE (activatable); if (iface->filter_part) return iface->filter_part (activatable, input_text, input_html, mime_type, is_patch); return NULL; }
{ "pile_set_name": "Github" }
// // Copyright (C) 2013 OpenSim Ltd. // // 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 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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/>. // #include "inet/physicallayer/base/packetlevel/FlatTransmitterBase.h" #include "inet/physicallayer/contract/packetlevel/SignalTag_m.h" namespace inet { namespace physicallayer { FlatTransmitterBase::FlatTransmitterBase() : NarrowbandTransmitterBase(), preambleDuration(-1), headerLength(b(-1)), bitrate(bps(NaN)), power(W(NaN)) { } void FlatTransmitterBase::initialize(int stage) { NarrowbandTransmitterBase::initialize(stage); if (stage == INITSTAGE_LOCAL) { preambleDuration = par("preambleDuration"); headerLength = b(par("headerLength")); bitrate = bps(par("bitrate")); power = W(par("power")); } } std::ostream& FlatTransmitterBase::printToStream(std::ostream& stream, int level) const { if (level <= PRINT_LEVEL_TRACE) stream << ", preambleDuration = " << preambleDuration << ", headerLength = " << headerLength << ", bitrate = " << bitrate << ", power = " << power; return NarrowbandTransmitterBase::printToStream(stream, level); } bps FlatTransmitterBase::computeTransmissionPreambleBitrate(const Packet *packet) const { auto signalBitrateReq = const_cast<Packet *>(packet)->findTag<SignalBitrateReq>(); return signalBitrateReq != nullptr ? signalBitrateReq->getPreambleBitrate() : bitrate; } bps FlatTransmitterBase::computeTransmissionHeaderBitrate(const Packet *packet) const { auto signalBitrateReq = const_cast<Packet *>(packet)->findTag<SignalBitrateReq>(); return signalBitrateReq != nullptr ? signalBitrateReq->getHeaderBitrate() : bitrate; } bps FlatTransmitterBase::computeTransmissionDataBitrate(const Packet *packet) const { auto signalBitrateReq = const_cast<Packet *>(packet)->findTag<SignalBitrateReq>(); return signalBitrateReq != nullptr ? signalBitrateReq->getDataBitrate() : bitrate; } W FlatTransmitterBase::computeTransmissionPower(const Packet *packet) const { auto signalPowerReq = const_cast<Packet *>(packet)->findTag<SignalPowerReq>(); return signalPowerReq != nullptr ? signalPowerReq->getPower() : power; } } // namespace physicallayer } // namespace inet
{ "pile_set_name": "Github" }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.manipulator.mutable.block; import static com.google.common.base.Preconditions.checkNotNull; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.block.ImmutableWallData; import org.spongepowered.api.data.manipulator.mutable.block.WallData; import org.spongepowered.api.data.type.WallType; import org.spongepowered.api.data.type.WallTypes; import org.spongepowered.common.data.manipulator.immutable.block.ImmutableSpongeWallData; import org.spongepowered.common.data.manipulator.mutable.common.AbstractSingleCatalogData; public class SpongeWallData extends AbstractSingleCatalogData<WallType, WallData, ImmutableWallData> implements WallData { public SpongeWallData(WallType wallType) { super(WallData.class, checkNotNull(wallType), Keys.WALL_TYPE, ImmutableSpongeWallData.class); } public SpongeWallData() { this(WallTypes.NORMAL); } }
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris // Package unix contains an interface to the low-level operating system // primitives. OS details vary depending on the underlying system, and // by default, godoc will display OS-specific documentation for the current // system. If you want godoc to display OS documentation for another // system, set $GOOS and $GOARCH to the desired system. For example, if // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS // to freebsd and $GOARCH to arm. // // The primary use of this package is inside other packages that provide a more // portable interface to the system, such as "os", "time" and "net". Use // those packages rather than this one if you can. // // For details of the functions and data types in this package consult // the manuals for the appropriate operating system. // // These calls return err == nil to indicate success; otherwise // err represents an operating system error describing the failure and // holds a value of type syscall.Errno. package unix // import "golang.org/x/sys/unix" import "strings" // ByteSliceFromString returns a NUL-terminated slice of bytes // containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func ByteSliceFromString(s string) ([]byte, error) { if strings.IndexByte(s, 0) != -1 { return nil, EINVAL } a := make([]byte, len(s)+1) copy(a, s) return a, nil } // BytePtrFromString returns a pointer to a NUL-terminated array of // bytes containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func BytePtrFromString(s string) (*byte, error) { a, err := ByteSliceFromString(s) if err != nil { return nil, err } return &a[0], nil } // Single-word zero for use when we need a valid pointer to 0 bytes. // See mkunix.pl. var _zero uintptr
{ "pile_set_name": "Github" }
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2004-2008, Open Source Geospatial Foundation (OSGeo) * * This library 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; * version 2.1 of the License. * * This library 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. */ package org.geotools.xml.handlers; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.geotools.xml.SchemaFactory; import org.geotools.xml.XMLElementHandler; import org.geotools.xml.schema.ComplexType; import org.geotools.xml.schema.Element; import org.geotools.xml.schema.Schema; import org.geotools.xml.schema.SimpleType; import org.geotools.xml.schema.Type; import org.xml.sax.SAXException; /** * This class is used to create handlers for child elements based on the currently defined * namespaces. This class is called by the XMLSAXHandler to help act as a library of prefix -> * Schema mappings. * * @author dzwiers www.refractions.net * @see org.geotools.xml.XMLSAXHandler * @see Schema */ public class ElementHandlerFactory { /** Used to store ElementHandlerFactory */ public static final String KEY = "org.geotools.xml.handlers.ElementHandlerFactory_KEY"; private Logger logger; private Map targSchemas = new HashMap(); // maps prefix -->> Schema private Map prefixURIs = new HashMap(); // maps prefix -->> URI protected URI defaultNS = null; /** * Creates a new ElementHandlerFactory object. * * @param l Logger */ public ElementHandlerFactory(Logger l) { logger = l; } /** @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ public void endPrefixMapping(String prefix) { URI s = (URI) prefixURIs.remove(prefix); if (s != null) { targSchemas.remove(s); } } /** @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ public void startPrefixMapping(String prefix, String targ, URI uri) throws SAXException { logger.finest("Target == '" + targ + "'"); logger.finest("URI == '" + uri + "'"); URI tns = null; try { tns = new URI(targ); } catch (URISyntaxException e) { logger.warning(e.toString()); throw new SAXException(e); } try { Schema s = SchemaFactory.getInstance(tns, uri, logger.getLevel()); if (s != null) { if ((prefix == null) || "".equalsIgnoreCase(prefix)) { defaultNS = s.getTargetNamespace(); } targSchemas.put(s.getTargetNamespace(), s); prefixURIs.put(prefix, tns); } else { prefixURIs.put(prefix, tns); } } catch (Exception e) { logger.log( Level.FINE, "Failed to parse schema from location " + uri + ", ignoring and moving on, this might result in some elements not being parsed properly"); // treating an error the same way as not being able to // get to the schema, e.g., s == null above prefixURIs.put(prefix, tns); } } /** @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ public void startPrefixMapping(String prefix, String targ) throws SAXException { logger.finest("Target == '" + targ + "'"); try { URI tns = new URI(targ); Schema s = SchemaFactory.getInstance(tns); if (s == null) { prefixURIs.put(prefix, tns); return; } if ((prefix == null) || "".equalsIgnoreCase(prefix)) { defaultNS = s.getTargetNamespace(); } targSchemas.put(s.getTargetNamespace(), s); prefixURIs.put(prefix, tns); } catch (URISyntaxException e) { logger.warning(e.toString()); throw new SAXException(e); } } /** @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ protected void startPrefixMapping(String prefix, Schema targ) { logger.finest("Target == '" + targ + "'"); if ((prefix == null) || "".equalsIgnoreCase(prefix)) { defaultNS = targ.getTargetNamespace(); } targSchemas.put(targ.getTargetNamespace(), targ); prefixURIs.put(prefix, targ.getTargetNamespace()); } /** * Creates an element handler for the element specified by name and namespace. Will return null * if a suitable handler is not found. * * @see ElementHandlerFactory#createElementHandler(Element) */ public XMLElementHandler createElementHandler(URI namespaceURI, String localName) throws SAXException { if (localName == null) { return null; } if (namespaceURI == null || "".equals(namespaceURI.toString())) { namespaceURI = defaultNS; } logger.finest( "Trying to create an element handler for " + localName + " :: " + namespaceURI); Schema s = (Schema) targSchemas.get(namespaceURI); if (s == null) { logger.finest("Could not find Schema " + namespaceURI); return null; } logger.finest("Found Schema " + s.getTargetNamespace()); Element[] eth = s.getElements(); if (eth == null) { return null; } for (int i = 0; i < eth.length; i++) { String name = eth[i].getName(); if (localName.equalsIgnoreCase(name) || name.equals(IgnoreHandler.NAME)) { return createElementHandler(eth[i]); } } // TODO search the nesting import stuff return null; } /** * Creates an element handler based on the element provided. * * @param eth Element */ public XMLElementHandler createElementHandler(Element eth) throws SAXException { Type type = eth.getType(); if (type instanceof SimpleType) { return new SimpleElementHandler(eth); } if (type instanceof ComplexType) { return new ComplexElementHandler(this, eth); } return new IgnoreHandler(eth); } public URI getNamespace(String prefix) { URI s = (URI) prefixURIs.get(prefix); return s; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <ApplicationInsights xmlns = "http://schemas.microsoft.com/ApplicationInsights/2013/Settings"> </ApplicationInsights>
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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. */ package com.tencentcloudapi.batch.v20170312.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class SpotMarketOptions extends AbstractModel{ /** * 竞价出价 */ @SerializedName("MaxPrice") @Expose private String MaxPrice; /** * 竞价请求类型,当前仅支持类型:one-time */ @SerializedName("SpotInstanceType") @Expose private String SpotInstanceType; /** * Get 竞价出价 * @return MaxPrice 竞价出价 */ public String getMaxPrice() { return this.MaxPrice; } /** * Set 竞价出价 * @param MaxPrice 竞价出价 */ public void setMaxPrice(String MaxPrice) { this.MaxPrice = MaxPrice; } /** * Get 竞价请求类型,当前仅支持类型:one-time * @return SpotInstanceType 竞价请求类型,当前仅支持类型:one-time */ public String getSpotInstanceType() { return this.SpotInstanceType; } /** * Set 竞价请求类型,当前仅支持类型:one-time * @param SpotInstanceType 竞价请求类型,当前仅支持类型:one-time */ public void setSpotInstanceType(String SpotInstanceType) { this.SpotInstanceType = SpotInstanceType; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "MaxPrice", this.MaxPrice); this.setParamSimple(map, prefix + "SpotInstanceType", this.SpotInstanceType); } }
{ "pile_set_name": "Github" }
FROM ubuntu:14.04 COPY getpid /usr/local/bin/ COPY fork /usr/local/bin/ WORKDIR /data VOLUME ["/data"] CMD [ "getpid" ]
{ "pile_set_name": "Github" }
{% load my_filters %} {% load i18n %} {% load staticfiles %} <!-- Begin Student Groups --> <div class="row" id="groups"> {% trans "Ungrouped" as ungrouped %} <div class="col-md-12"> {% if group_id and group_data %} {# comment "First block is a group summary page for a single group's display" #} {% include "control_panel/partials/_group_summary.html" %} {% else %} <h2> {% trans "Learner Groups" %} <small> <span class="help-tooltip glyphicon glyphicon-question-sign" data-toggle="tooltip" data-placement="right" title="{% blocktrans %}A 'group' is set of learners, such as a classroom of students or all students in one grade.{% endblocktrans %} {% trans 'Add learners by selecting a group.' %}"></span> <!---TODO - Radina: implement accessible tooltip. --> </small> </h2> {% if not groups %} <p class="no-data"> {% trans "You currently have no group data available." %} </p> {% else %} {% if not request.is_teacher %} <p> <button class="delete-group btn btn-success" disabled="disabled" value="#groups">{% trans "Delete Groups" %}</button> </p> {% endif %} <div class="table-responsive"> <table class="table selectable-table"> <thead> <tr class="header-footer-bg"> <th><input class="select-all" type="checkbox" value="#groups" autocomplete="off"/></th> <th>{% trans "Group" %}</th> <th>{% trans "Edit" %}</th> <th>{% trans "Coach" %}</th> <th>{% trans "# Learners" %}</th> <th>{% trans "Logins" %}</th> <th>{% trans "Login Time" %}</th> <th>{% trans "Videos Viewed" %}</th> <th>{% trans "Exercises Completed" %}</th> <th>{% trans "Mastery " %}</th> </tr> </thead> <tbody> {% for group in groups %} {% if group.name != ungrouped or group.total_users != 0 %} <tr {% if group.id %}class="selectable"{% endif %} value="{{ group.id }}" type="groups"> <td>{% if group.id %}<input type="checkbox" value="#groups" autocomplete="off"/>{% endif %}</td> <td> {# Translators: this is a verb; by clicking this link, the user will be able to coach students. #} <a class="group-name" title="{% blocktrans with groupname=group.name %}Manage group {{ groupname }}.{% endblocktrans %}" {% if group.id %} href="{% url 'group_management' zone_id=zone_id facility_id=facility_id group_id=group.id %}"> {% else %} href="{% url 'group_management' zone_id=zone_id facility_id=facility_id group_id=ungrouped_id %}"> {% endif %} {{ group.name }} </a> </td> <td> {% if group.id %} <a href="{% url 'group_edit' group_id=group.id %}?facility={{ facility_id }}&next={{ request.get_full_path|urlencode }}" title="{% trans 'Edit group' %}"> <span aria-hidden="true"><i class="glyphicon glyphicon-pencil"></i></span> <span class="sr-only">{% trans 'Edit group' %}</span> </a> {% else %} N/A {% endif %} </td> <td> {# Translators: this is a verb; by clicking this link, the user will be able to coach students. #} <a title="{% blocktrans with groupname=group.name %}Coach group {{ groupname }}.{% endblocktrans %}" href="{% url 'coach_reports' zone_id=zone_id %}/{{ facility_id }}/{% if group.id %}{{ group.id }}{% else %}{{ ungrouped_id }}{% endif %}/"> <div class="sparklines" sparkType="bar" sparkBarColor="green"> <!-- {{ group.total_logins }}, {{ group.total_videos }}, {{ group.total_exercises }} --> </div></a> </td> <td>{{ group.total_users }}</td> <td>{{ group.total_logins }}</td> <td>{{ group.total_hours|floatformat }} {% trans "hour(s)" %}</td> <td>{{ group.total_videos }}</td> <td>{{ group.total_exercises_completed }}</td> <td>{{ group.pct_mastery|floatformat:1 }}%</td> </tr> {% endif %} {% endfor %} {# 10x td for table formatting purposes #} <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> {% endif %} <div class="row table-bottom-options"> <div class="col-sm-4 col-xs-12"> <p class="add-new-table-item"> <a id="add-a-new-group" href="{% url 'add_group' %}?facility={{ facility_id }}&next={{ request.get_full_path|urlencode }}"> <span aria-hidden="true"><i class="glyphicon glyphicon-plus-sign"></i></span> {% trans 'Add a new group.' %} </a> </p> </div> </div> {% endif %} </div> </div> <!-- End Student Groups -->
{ "pile_set_name": "Github" }
#include "os/os_thread.h" #include "pipe/p_defines.h" #include "util/u_ringbuffer.h" #include "util/u_math.h" #include "util/u_memory.h" /* Generic ringbuffer: */ struct util_ringbuffer { struct util_packet *buf; unsigned mask; /* Can this be done with atomic variables?? */ unsigned head; unsigned tail; cnd_t change; mtx_t mutex; }; struct util_ringbuffer *util_ringbuffer_create( unsigned dwords ) { struct util_ringbuffer *ring = CALLOC_STRUCT(util_ringbuffer); if (!ring) return NULL; assert(util_is_power_of_two_or_zero(dwords)); ring->buf = MALLOC( dwords * sizeof(unsigned) ); if (ring->buf == NULL) goto fail; ring->mask = dwords - 1; cnd_init(&ring->change); (void) mtx_init(&ring->mutex, mtx_plain); return ring; fail: FREE(ring->buf); FREE(ring); return NULL; } void util_ringbuffer_destroy( struct util_ringbuffer *ring ) { cnd_destroy(&ring->change); mtx_destroy(&ring->mutex); FREE(ring->buf); FREE(ring); } /** * Return number of free entries in the ring */ static inline unsigned util_ringbuffer_space( const struct util_ringbuffer *ring ) { return (ring->tail - (ring->head + 1)) & ring->mask; } /** * Is the ring buffer empty? */ static inline boolean util_ringbuffer_empty( const struct util_ringbuffer *ring ) { return util_ringbuffer_space(ring) == ring->mask; } void util_ringbuffer_enqueue( struct util_ringbuffer *ring, const struct util_packet *packet ) { unsigned i; /* XXX: over-reliance on mutexes, etc: */ mtx_lock(&ring->mutex); /* make sure we don't request an impossible amount of space */ assert(packet->dwords <= ring->mask); /* Wait for free space: */ while (util_ringbuffer_space(ring) < packet->dwords) cnd_wait(&ring->change, &ring->mutex); /* Copy data to ring: */ for (i = 0; i < packet->dwords; i++) { /* Copy all dwords of the packet. Note we're abusing the * typesystem a little - we're being passed a pointer to * something, but probably not an array of packet structs: */ ring->buf[ring->head] = packet[i]; ring->head++; ring->head &= ring->mask; } /* Signal change: */ cnd_signal(&ring->change); mtx_unlock(&ring->mutex); } enum pipe_error util_ringbuffer_dequeue( struct util_ringbuffer *ring, struct util_packet *packet, unsigned max_dwords, boolean wait ) { const struct util_packet *ring_packet; unsigned i; int ret = PIPE_OK; /* XXX: over-reliance on mutexes, etc: */ mtx_lock(&ring->mutex); /* Get next ring entry: */ if (wait) { while (util_ringbuffer_empty(ring)) cnd_wait(&ring->change, &ring->mutex); } else { if (util_ringbuffer_empty(ring)) { ret = PIPE_ERROR_OUT_OF_MEMORY; goto out; } } ring_packet = &ring->buf[ring->tail]; /* Both of these are considered bugs. Raise an assert on debug builds. */ if (ring_packet->dwords > ring->mask + 1 - util_ringbuffer_space(ring) || ring_packet->dwords > max_dwords) { assert(0); ret = PIPE_ERROR_BAD_INPUT; goto out; } /* Copy data from ring: */ for (i = 0; i < ring_packet->dwords; i++) { packet[i] = ring->buf[ring->tail]; ring->tail++; ring->tail &= ring->mask; } out: /* Signal change: */ cnd_signal(&ring->change); mtx_unlock(&ring->mutex); return ret; }
{ "pile_set_name": "Github" }
-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDBKo554mzIMY+AByUNpaUOP9bJnQ7ZLQe9XgHwoLJR4VzpyZZZ R9L4WtImEew05FY3Izerfm3MN3+MC0tJ6yQU9sOiU3vBW6RrLIMlfKsnRwBRZ0Kn da+O6xldVSosu8Ev3z9VZ94iC/ZgKzrH7Mjj/U8/MQO7RBS/LAqee8bFNQIDAQAB AoGAWOCF0ZrWxn3XMucWq2LNwPKqlvVGwbIwX3cDmX22zmnM4Fy6arXbYh4XlyCj 9+ofqRrxIFz5k/7tFriTmZ0xag5+Jdx+Kwg0/twiP7XCNKipFogwe1Hznw8OFAoT enKBdj2+/n2o0Bvo/tDB59m9L/538d46JGQUmJlzMyqYikECQQDyoq+8CtMNvE18 8VgHcR/KtApxWAjj4HpaHYL637ATjThetUZkW92mgDgowyplthusxdNqhHWyv7E8 tWNdYErZAkEAy85ShTR0M5aWmrE7o0r0SpWInAkNBH9aXQRRARFYsdBtNfRu6I0i 0lvU9wiu3eF57FMEC86yViZ5UBnQfTu7vQJAVesj/Zt7pwaCDfdMa740OsxMUlyR MVhhGx4OLpYdPJ8qUecxGQKq13XZ7R1HGyNEY4bd2X80Smq08UFuATfC6QJAH8UB yBHtKz2GLIcELOg6PIYizW/7v3+6rlVF60yw7sb2vzpjL40QqIn4IKoR2DSVtOkb 8FtAIX3N21aq0VrGYQJBAIPiaEc2AZ8Bq2GC4F3wOz/BxJ/izvnkiotR12QK4fh5 yjZMhTjWCas5zwHR5PDjlD88AWGDMsZ1PicD4348xJQ= -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIIDxTCCAy6gAwIBAgIJAI18BD7eQxlGMA0GCSqGSIb3DQEBBAUAMIGeMQswCQYD VQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTESMBAGA1UEBxMJU2FuIERpZWdv MRkwFwYDVQQKExBDaGVycnlQeSBQcm9qZWN0MREwDwYDVQQLEwhkZXYtdGVzdDEW MBQGA1UEAxMNQ2hlcnJ5UHkgVGVhbTEgMB4GCSqGSIb3DQEJARYRcmVtaUBjaGVy cnlweS5vcmcwHhcNMDYwOTA5MTkyMDIwWhcNMzQwMTI0MTkyMDIwWjCBnjELMAkG A1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEjAQBgNVBAcTCVNhbiBEaWVn bzEZMBcGA1UEChMQQ2hlcnJ5UHkgUHJvamVjdDERMA8GA1UECxMIZGV2LXRlc3Qx FjAUBgNVBAMTDUNoZXJyeVB5IFRlYW0xIDAeBgkqhkiG9w0BCQEWEXJlbWlAY2hl cnJ5cHkub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBKo554mzIMY+A ByUNpaUOP9bJnQ7ZLQe9XgHwoLJR4VzpyZZZR9L4WtImEew05FY3Izerfm3MN3+M C0tJ6yQU9sOiU3vBW6RrLIMlfKsnRwBRZ0Knda+O6xldVSosu8Ev3z9VZ94iC/Zg KzrH7Mjj/U8/MQO7RBS/LAqee8bFNQIDAQABo4IBBzCCAQMwHQYDVR0OBBYEFDIQ 2feb71tVZCWpU0qJ/Tw+wdtoMIHTBgNVHSMEgcswgciAFDIQ2feb71tVZCWpU0qJ /Tw+wdtooYGkpIGhMIGeMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5p YTESMBAGA1UEBxMJU2FuIERpZWdvMRkwFwYDVQQKExBDaGVycnlQeSBQcm9qZWN0 MREwDwYDVQQLEwhkZXYtdGVzdDEWMBQGA1UEAxMNQ2hlcnJ5UHkgVGVhbTEgMB4G CSqGSIb3DQEJARYRcmVtaUBjaGVycnlweS5vcmeCCQCNfAQ+3kMZRjAMBgNVHRME BTADAQH/MA0GCSqGSIb3DQEBBAUAA4GBAL7AAQz7IePV48ZTAFHKr88ntPALsL5S 8vHCZPNMevNkLTj3DYUw2BcnENxMjm1kou2F2BkvheBPNZKIhc6z4hAml3ed1xa2 D7w6e6OTcstdK/+KrPDDHeOP1dhMWNs2JE1bNlfF1LiXzYKSXpe88eCKjCXsCT/T NluCaWQys3MS -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
package cli import ( "bufio" "errors" "fmt" "io" "os" "os/signal" "strings" "github.com/bgentry/speakeasy" "github.com/mattn/go-isatty" ) // Ui is an interface for interacting with the terminal, or "interface" // of a CLI. This abstraction doesn't have to be used, but helps provide // a simple, layerable way to manage user interactions. type Ui interface { // Ask asks the user for input using the given query. The response is // returned as the given string, or an error. Ask(string) (string, error) // AskSecret asks the user for input using the given query, but does not echo // the keystrokes to the terminal. AskSecret(string) (string, error) // Output is called for normal standard output. Output(string) // Info is called for information related to the previous output. // In general this may be the exact same as Output, but this gives // Ui implementors some flexibility with output formats. Info(string) // Error is used for any error messages that might appear on standard // error. Error(string) // Warn is used for any warning messages that might appear on standard // error. Warn(string) } // BasicUi is an implementation of Ui that just outputs to the given // writer. This UI is not threadsafe by default, but you can wrap it // in a ConcurrentUi to make it safe. type BasicUi struct { Reader io.Reader Writer io.Writer ErrorWriter io.Writer } func (u *BasicUi) Ask(query string) (string, error) { return u.ask(query, false) } func (u *BasicUi) AskSecret(query string) (string, error) { return u.ask(query, true) } func (u *BasicUi) ask(query string, secret bool) (string, error) { if _, err := fmt.Fprint(u.Writer, query+" "); err != nil { return "", err } // Register for interrupts so that we can catch it and immediately // return... sigCh := make(chan os.Signal, 1) signal.Notify(sigCh, os.Interrupt) defer signal.Stop(sigCh) // Ask for input in a go-routine so that we can ignore it. errCh := make(chan error, 1) lineCh := make(chan string, 1) go func() { var line string var err error if secret && isatty.IsTerminal(os.Stdin.Fd()) { line, err = speakeasy.Ask("") } else { r := bufio.NewReader(u.Reader) line, err = r.ReadString('\n') } if err != nil { errCh <- err return } lineCh <- strings.TrimRight(line, "\r\n") }() select { case err := <-errCh: return "", err case line := <-lineCh: return line, nil case <-sigCh: // Print a newline so that any further output starts properly // on a new line. fmt.Fprintln(u.Writer) return "", errors.New("interrupted") } } func (u *BasicUi) Error(message string) { w := u.Writer if u.ErrorWriter != nil { w = u.ErrorWriter } fmt.Fprint(w, message) fmt.Fprint(w, "\n") } func (u *BasicUi) Info(message string) { u.Output(message) } func (u *BasicUi) Output(message string) { fmt.Fprint(u.Writer, message) fmt.Fprint(u.Writer, "\n") } func (u *BasicUi) Warn(message string) { u.Error(message) } // PrefixedUi is an implementation of Ui that prefixes messages. type PrefixedUi struct { AskPrefix string AskSecretPrefix string OutputPrefix string InfoPrefix string ErrorPrefix string WarnPrefix string Ui Ui } func (u *PrefixedUi) Ask(query string) (string, error) { if query != "" { query = fmt.Sprintf("%s%s", u.AskPrefix, query) } return u.Ui.Ask(query) } func (u *PrefixedUi) AskSecret(query string) (string, error) { if query != "" { query = fmt.Sprintf("%s%s", u.AskSecretPrefix, query) } return u.Ui.AskSecret(query) } func (u *PrefixedUi) Error(message string) { if message != "" { message = fmt.Sprintf("%s%s", u.ErrorPrefix, message) } u.Ui.Error(message) } func (u *PrefixedUi) Info(message string) { if message != "" { message = fmt.Sprintf("%s%s", u.InfoPrefix, message) } u.Ui.Info(message) } func (u *PrefixedUi) Output(message string) { if message != "" { message = fmt.Sprintf("%s%s", u.OutputPrefix, message) } u.Ui.Output(message) } func (u *PrefixedUi) Warn(message string) { if message != "" { message = fmt.Sprintf("%s%s", u.WarnPrefix, message) } u.Ui.Warn(message) }
{ "pile_set_name": "Github" }
# include "KNN.h" KNN::KNN(int _k = 3) : k(_k) { } void KNN::train(DataSet* _data) { data = _data; numClasses = 0; // xxx use a MAXIMUM function for (unsigned int i = 0; i < data->Y.size(); i++){ if (data->Y[i] > numClasses) { numClasses = int(data->Y[i]); } } ++numClasses; } std::vector<double> KNN::test(DataSet& testdata) { int p; std::vector<int> labels(testdata.size()); std::vector<double> decisionFunction(testdata.size()); //decisionFunction.reserve(testdata.size()); vector<vector<int> > classes(numClasses); for (int i = 0; i < data->size(); i++) { classes[int(data->Y[i])].push_back(i); } for (unsigned int i = 0; i < testdata.size(); i++) { //labels.push_back(0); vector<double> classSim(numClasses,0); for (int c = 0; c < numClasses; c++) { vector<double> similarities(classes[c].size()); for (unsigned int j = 0; j < classes[c].size(); j++) { p = classes[c][j]; //cout << "about to compute kernel" << endl; similarities[j] = data->kernel->eval(data, p, i, &testdata); //cout << "computed kernel" << endl; } partial_sort(similarities.begin(), similarities.begin() + k, similarities.end(), greater<double>()); for (int j = 0; j < k; j++) { classSim[c] += similarities[j]; } } double largestSimilarity = -1e10; for (int c = 0; c < numClasses; c++) { if (classSim[c] > largestSimilarity) { largestSimilarity = classSim[c]; labels[i] = c; } } // find the second largest similarity: double secondLargestSimilarity = -1e10; for (int c = 0; c < numClasses; c++) { if (!(c == labels[i])){ if (classSim[c] > secondLargestSimilarity) { secondLargestSimilarity = classSim[c]; } } } decisionFunction[i] = largestSimilarity - secondLargestSimilarity; if (numClasses == 2) { decisionFunction[i] = decisionFunction[i] * (labels[i] * 2 - 1); } } cout << labels.size() << " " << decisionFunction.size() << endl; for (int i = 0; i<labels.size(); ++i){ decisionFunction.push_back(labels[i]); } cout << "done testing KNN*****************************" << endl; return decisionFunction; } std::vector<int> KNN::nearestNeighbors(DataSet& testdata, int p) { std::vector<int> neighbors; vector<double> similarities(data->size()); for (int i = 0; i < data->size(); ++i) { similarities[i] = data->kernel->eval(data, i, p, &testdata); } std::vector<double> unorderedSim(similarities); partial_sort(similarities.begin(), similarities.begin() + k, similarities.end(), greater<double>()); for (int j = 0; j < k; ++j) { for (int i = 0; i < data->size(); ++i) { if (unorderedSim[j] == similarities[i]) { neighbors.push_back(i); } } } return neighbors; } std::vector<double> KNN::classScores(DataSet& testdata, int p) { vector<vector<int> > classes(numClasses); for (int i = 0; i < data->size(); i++) { classes[int(data->Y[i])].push_back(i); } vector<double> classSim(numClasses, 0); //cout << "i: " << i << endl; for (int c = 0; c < numClasses; c++) { vector<double> similarities(classes[c].size()); for (unsigned int j = 0; j < classes[c].size(); j++) { p = classes[c][j]; similarities[j] = data->kernel->eval(data, classes[c][j], p, &testdata); } partial_sort(similarities.begin(), similarities.begin() + k, similarities.end(), greater<double>()); for (int j = 0; j < k; j++) { classSim[c] += similarities[j]; } } return classSim; } int KNN::nearestNeighbor(DataSet& data, int pattern) { double maxSim = -1e10; double sim; int nn = 0; for (int i = 0; i < data.size(); i++) { if (i != pattern) { sim = data.kernel->eval(&data, pattern, i, &data); if (sim > maxSim) { maxSim = sim; nn = i; } } } return nn; }
{ "pile_set_name": "Github" }
-- update.test -- -- execsql {CREATE TABLE test1(f1 int,f2 int)} CREATE TABLE test1(f1 int,f2 int)
{ "pile_set_name": "Github" }
import pytest import os from smali.parser import get_op_code def build_op_code_data(): return { hexcode: definition for hexcode, definition in enumerate( open(os.path.join( os.path.dirname(__file__), 'data', 'opcode_list.dat' )).readlines() ) } @pytest.mark.parametrize( 'opcode_value, opcode_source_line', build_op_code_data().items(), ) def test_op_code_building(opcode_value, opcode_source_line): assert opcode_source_line.startswith(get_op_code(opcode_source_line))
{ "pile_set_name": "Github" }
package com.thomsonreuters.upa.valueadd.reactor; import java.nio.ByteBuffer; import com.thomsonreuters.upa.codec.Buffer; import com.thomsonreuters.upa.codec.CodecFactory; import com.thomsonreuters.upa.codec.CodecReturnCodes; /** * This class represents the OAuth credential for authorization with the token service. * * @see ConsumerRole */ public class ReactorOAuthCredential { private Buffer _userName = CodecFactory.createBuffer(); private Buffer _password = CodecFactory.createBuffer(); private Buffer _clientId = CodecFactory.createBuffer(); private Buffer _clientSecret = CodecFactory.createBuffer(); private Buffer _tokenScope = CodecFactory.createBuffer(); private boolean _takeExclusiveSignOnControl = true; private ReactorOAuthCredentialEventCallback _oAuthCredentialEventCallback; Object _userSpecObj = null; /** * Instantiates ReactorOAuthCredential. */ ReactorOAuthCredential() { clear(); } /** * Clears to defaults */ public void clear() { _userName.clear(); _password.clear(); _clientId.clear(); _clientSecret.clear(); _tokenScope.data("trapi.streaming.pricing.read"); _takeExclusiveSignOnControl = true; _oAuthCredentialEventCallback = null; } /** * The user name that was used when sending the authorization request. * * @return - User name buffer. */ public Buffer userName() { return _userName; } /** * Sets userName to authorize with the token service. Mandatory * * @param userName the user name */ public void userName(Buffer userName) { assert(userName != null) : "userName can not be null"; _userName.data(userName.data(), userName.position(), userName.length()); } /** * The password that was used when sending the authorization request. * * @return - Password buffer. */ public Buffer password() { return _password; } /** * Sets password to authorize with the token service. Mandatory * * @param password the password associated with the user name */ public void password(Buffer password) { assert(password != null) : "password can not be null"; _password.data(password.data(), password.position(), password.length()); } /** * The unique identifier that was used when sending the authorization request. * * @return - Client ID buffer. */ public Buffer clientId() { return _clientId; } /** * Sets unique identifier defined for the application or user making a request to the token service. Mandatory * * @param clientId the unique identifier for the application */ public void clientId(Buffer clientId) { assert(clientId != null) : "clientId can not be null"; _clientId.data(clientId.data(), clientId.position(), clientId.length()); } /** * The secret that was used by OAuth Client to authenticate with the token service. * * @return - Client Secret buffer. */ public Buffer clientSecret() { return _clientSecret; } /** * Sets client secret to authorize with the token service. Optional * * @param clientSecret the client secret */ public void clientSecret(Buffer clientSecret) { assert(clientSecret != null) : "clientSecret can not be null"; _clientSecret.data(clientSecret.data(), clientSecret.position(), clientSecret.length()); } /** * The token scope that was used to limit the scope of generated token. * * @return - Token Scope buffer. */ public Buffer tokenScope() { return _tokenScope; } /** * Sets token scope to limit the scope of generated token. Optional * * @param tokenScope the token scope */ public void tokenScope(Buffer tokenScope) { assert(tokenScope != null) : "tokenScope can not be null"; _tokenScope.data(tokenScope.data(), tokenScope.position(), tokenScope.length()); } /** * The exclusive sign on control to force sign-out. * * @return - true to force sign-out using the same credential otherwise false. */ public boolean takeExclusiveSignOnControl() { return _takeExclusiveSignOnControl; } /** * Sets the exclusive sign on control to force sign-out of other applications using the same credentials. * * @param takeExclusiveSignOnControl the exclusive sign on control. */ public void takeExclusiveSignOnControl(boolean takeExclusiveSignOnControl) { _takeExclusiveSignOnControl = takeExclusiveSignOnControl; } /** * Specifies the {@link ReactorOAuthCredentialEventCallback} to submit OAuth sensitive information. * * <p>The Reactor will not copy password and client secret if the callback is specified.</p> * * @param oAuthCredentialEventCallback the OAuth credential event callback. */ public void reactorOAuthCredentialEventCallback(ReactorOAuthCredentialEventCallback oAuthCredentialEventCallback) { _oAuthCredentialEventCallback = oAuthCredentialEventCallback; } /** * The callback to submit OAuth sensitive information. * * @return The {@link ReactorOAuthCredentialEventCallback}. */ public ReactorOAuthCredentialEventCallback reactorOAuthCredentialEventCallback() { return _oAuthCredentialEventCallback; } /** * Specifies a user defined object that can be useful for retrieving sensitive information * via in the {@link ReactorOAuthCredentialEventCallback}. * * @param userSpecObj the userSpecObj * * @return {@link ReactorReturnCodes#SUCCESS} if the userSpecObj is not * null, otherwise {@link ReactorReturnCodes#PARAMETER_INVALID}. */ public int userSpecObj(Object userSpecObj) { if (userSpecObj == null) return ReactorReturnCodes.PARAMETER_INVALID; _userSpecObj = userSpecObj; return ReactorReturnCodes.SUCCESS; } /** * Returns the userSpecObj. * * @return the userSpecObj. */ public Object userSpecObj() { return _userSpecObj; } /** * Performs a deep copy of {@link ReactorOAuthCredential} object. * * @param destReactorOAuthCredential to copy OAuth credential object into. It * cannot be null. * * @return ETA return value indicating success or failure of copy operation. */ public int copy(ReactorOAuthCredential destReactorOAuthCredential) { assert (destReactorOAuthCredential != null) : "destReactorOAuthCredential must be non-null"; if(destReactorOAuthCredential == null) return CodecReturnCodes.FAILURE; if(_userName.length() != 0) { ByteBuffer byteBuffer = ByteBuffer.allocate(_userName.length()); _userName.copy(byteBuffer); destReactorOAuthCredential.userName().data(byteBuffer); } if(_password.length() != 0) { ByteBuffer byteBuffer = ByteBuffer.allocate(_password.length()); _password.copy(byteBuffer); destReactorOAuthCredential.password().data(byteBuffer); } if(_clientId.length() != 0) { ByteBuffer byteBuffer = ByteBuffer.allocate(_clientId.length()); _clientId.copy(byteBuffer); destReactorOAuthCredential.clientId().data(byteBuffer); } if(_clientSecret.length() != 0) { ByteBuffer byteBuffer = ByteBuffer.allocate(_clientSecret.length()); _clientSecret.copy(byteBuffer); destReactorOAuthCredential.clientSecret().data(byteBuffer); } if(_tokenScope.length() != 0) { ByteBuffer byteBuffer = ByteBuffer.allocate(_tokenScope.length()); _tokenScope.copy(byteBuffer); destReactorOAuthCredential.tokenScope().data(byteBuffer); } destReactorOAuthCredential._takeExclusiveSignOnControl = _takeExclusiveSignOnControl; destReactorOAuthCredential._oAuthCredentialEventCallback = _oAuthCredentialEventCallback; destReactorOAuthCredential._userSpecObj = _userSpecObj; return CodecReturnCodes.SUCCESS; } }
{ "pile_set_name": "Github" }
/* Copyright 2018 The Kubernetes 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 v1beta1 import ( apiextv1b1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // KubeFedConfigSpec defines the desired state of KubeFedConfig type KubeFedConfigSpec struct { // The scope of the KubeFed control plane should be either // `Namespaced` or `Cluster`. `Namespaced` indicates that the // KubeFed namespace will be the only target of the control plane. Scope apiextv1b1.ResourceScope `json:"scope"` // +optional ControllerDuration *DurationConfig `json:"controllerDuration,omitempty"` // +optional LeaderElect *LeaderElectConfig `json:"leaderElect,omitempty"` // +optional FeatureGates []FeatureGatesConfig `json:"featureGates,omitempty"` // +optional ClusterHealthCheck *ClusterHealthCheckConfig `json:"clusterHealthCheck,omitempty"` // +optional SyncController *SyncControllerConfig `json:"syncController,omitempty"` } type DurationConfig struct { // Time to wait before reconciling on a healthy cluster. // +optional AvailableDelay *metav1.Duration `json:"availableDelay,omitempty"` // Time to wait before giving up on an unhealthy cluster. // +optional UnavailableDelay *metav1.Duration `json:"unavailableDelay,omitempty"` } type LeaderElectConfig struct { // The duration that non-leader candidates will wait after observing a leadership // renewal until attempting to acquire leadership of a led but unrenewed leader // slot. This is effectively the maximum duration that a leader can be stopped // before it is replaced by another candidate. This is only applicable if leader // election is enabled. // +optional LeaseDuration *metav1.Duration `json:"leaseDuration,omitempty"` // The interval between attempts by the acting master to renew a leadership slot // before it stops leading. This must be less than or equal to the lease duration. // This is only applicable if leader election is enabled. // +optional RenewDeadline *metav1.Duration `json:"renewDeadline,omitempty"` // The duration the clients should wait between attempting acquisition and renewal // of a leadership. This is only applicable if leader election is enabled. // +optional RetryPeriod *metav1.Duration `json:"retryPeriod,omitempty"` // The type of resource object that is used for locking during // leader election. Supported options are `configmaps` (default) and `endpoints`. // +optional ResourceLock *ResourceLockType `json:"resourceLock,omitempty"` } type ResourceLockType string const ( ConfigMapsResourceLock ResourceLockType = "configmaps" EndpointsResourceLock ResourceLockType = "endpoints" ) type FeatureGatesConfig struct { Name string `json:"name"` Configuration ConfigurationMode `json:"configuration"` } type ConfigurationMode string const ( ConfigurationEnabled ConfigurationMode = "Enabled" ConfigurationDisabled ConfigurationMode = "Disabled" ) type ClusterHealthCheckConfig struct { // How often to monitor the cluster health. // +optional Period *metav1.Duration `json:"period,omitempty"` // Minimum consecutive failures for the cluster health to be considered failed after having succeeded. // +optional FailureThreshold *int64 `json:"failureThreshold,omitempty"` // Minimum consecutive successes for the cluster health to be considered successful after having failed. // +optional SuccessThreshold *int64 `json:"successThreshold,omitempty"` // Duration after which the cluster health check times out. // +optional Timeout *metav1.Duration `json:"timeout,omitempty"` } type SyncControllerConfig struct { // Whether to adopt pre-existing resources in member clusters. Defaults to // "Enabled". // +optional AdoptResources *ResourceAdoption `json:"adoptResources,omitempty"` } type ResourceAdoption string const ( AdoptResourcesEnabled ResourceAdoption = "Enabled" AdoptResourcesDisabled ResourceAdoption = "Disabled" ) // +kubebuilder:object:root=true // +kubebuilder:resource:path=kubefedconfigs type KubeFedConfig struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec KubeFedConfigSpec `json:"spec"` } // +kubebuilder:object:root=true // KubeFedConfigList contains a list of KubeFedConfig type KubeFedConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []KubeFedConfig `json:"items"` } func init() { SchemeBuilder.Register(&KubeFedConfig{}, &KubeFedConfigList{}) }
{ "pile_set_name": "Github" }
import unittest import sys from .support import LoggingResult, TestEquality ### Support code for Test_TestSuite ################################################################ class Test(object): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def test_3(self): pass def runTest(self): pass def _mk_TestSuite(*names): return unittest.TestSuite(Test.Foo(n) for n in names) ################################################################ class Test_TestSuite(unittest.TestCase, TestEquality): ### Set up attributes needed by inherited tests ################################################################ # Used by TestEquality.test_eq eq_pairs = [(unittest.TestSuite(), unittest.TestSuite()), (unittest.TestSuite(), unittest.TestSuite([])), (_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))] # Used by TestEquality.test_ne ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1')), (unittest.TestSuite([]), _mk_TestSuite('test_1')), (_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3')), (_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))] ################################################################ ### /Set up attributes needed by inherited tests ### Tests for TestSuite.__init__ ################################################################ # "class TestSuite([tests])" # # The tests iterable should be optional def test_init__tests_optional(self): suite = unittest.TestSuite() self.assertEqual(suite.countTestCases(), 0) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # TestSuite should deal with empty tests iterables by allowing the # creation of an empty suite def test_init__empty_tests(self): suite = unittest.TestSuite([]) self.assertEqual(suite.countTestCases(), 0) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # TestSuite should allow any iterable to provide tests def test_init__tests_from_any_iterable(self): def tests(): yield unittest.FunctionTestCase(lambda: None) yield unittest.FunctionTestCase(lambda: None) suite_1 = unittest.TestSuite(tests()) self.assertEqual(suite_1.countTestCases(), 2) suite_2 = unittest.TestSuite(suite_1) self.assertEqual(suite_2.countTestCases(), 2) suite_3 = unittest.TestSuite(set(suite_1)) self.assertEqual(suite_3.countTestCases(), 2) # "class TestSuite([tests])" # ... # "If tests is given, it must be an iterable of individual test cases # or other test suites that will be used to build the suite initially" # # Does TestSuite() also allow other TestSuite() instances to be present # in the tests iterable? def test_init__TestSuite_instances_in_tests(self): def tests(): ftc = unittest.FunctionTestCase(lambda: None) yield unittest.TestSuite([ftc]) yield unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite(tests()) self.assertEqual(suite.countTestCases(), 2) ################################################################ ### /Tests for TestSuite.__init__ # Container types should support the iter protocol def test_iter(self): test1 = unittest.FunctionTestCase(lambda: None) test2 = unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite((test1, test2)) self.assertEqual(list(suite), [test1, test2]) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Presumably an empty TestSuite returns 0? def test_countTestCases_zero_simple(self): suite = unittest.TestSuite() self.assertEqual(suite.countTestCases(), 0) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Presumably an empty TestSuite (even if it contains other empty # TestSuite instances) returns 0? def test_countTestCases_zero_nested(self): class Test1(unittest.TestCase): def test(self): pass suite = unittest.TestSuite([unittest.TestSuite()]) self.assertEqual(suite.countTestCases(), 0) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" def test_countTestCases_simple(self): test1 = unittest.FunctionTestCase(lambda: None) test2 = unittest.FunctionTestCase(lambda: None) suite = unittest.TestSuite((test1, test2)) self.assertEqual(suite.countTestCases(), 2) # "Return the number of tests represented by the this test object. # ...this method is also implemented by the TestSuite class, which can # return larger [greater than 1] values" # # Make sure this holds for nested TestSuite instances, too def test_countTestCases_nested(self): class Test1(unittest.TestCase): def test1(self): pass def test2(self): pass test2 = unittest.FunctionTestCase(lambda: None) test3 = unittest.FunctionTestCase(lambda: None) child = unittest.TestSuite((Test1('test2'), test2)) parent = unittest.TestSuite((test3, child, Test1('test1'))) self.assertEqual(parent.countTestCases(), 4) # "Run the tests associated with this suite, collecting the result into # the test result object passed as result." # # And if there are no tests? What then? def test_run__empty_suite(self): events = [] result = LoggingResult(events) suite = unittest.TestSuite() suite.run(result) self.assertEqual(events, []) # "Note that unlike TestCase.run(), TestSuite.run() requires the # "result object to be passed in." def test_run__requires_result(self): suite = unittest.TestSuite() try: suite.run() except TypeError: pass else: self.fail("Failed to raise TypeError") # "Run the tests associated with this suite, collecting the result into # the test result object passed as result." def test_run(self): events = [] result = LoggingResult(events) class LoggingCase(unittest.TestCase): def run(self, result): events.append('run %s' % self._testMethodName) def test1(self): pass def test2(self): pass tests = [LoggingCase('test1'), LoggingCase('test2')] unittest.TestSuite(tests).run(result) self.assertEqual(events, ['run test1', 'run test2']) # "Add a TestCase ... to the suite" def test_addTest__TestCase(self): class Foo(unittest.TestCase): def test(self): pass test = Foo('test') suite = unittest.TestSuite() suite.addTest(test) self.assertEqual(suite.countTestCases(), 1) self.assertEqual(list(suite), [test]) # "Add a ... TestSuite to the suite" def test_addTest__TestSuite(self): class Foo(unittest.TestCase): def test(self): pass suite_2 = unittest.TestSuite([Foo('test')]) suite = unittest.TestSuite() suite.addTest(suite_2) self.assertEqual(suite.countTestCases(), 1) self.assertEqual(list(suite), [suite_2]) # "Add all the tests from an iterable of TestCase and TestSuite # instances to this test suite." # # "This is equivalent to iterating over tests, calling addTest() for # each element" def test_addTests(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass test_1 = Foo('test_1') test_2 = Foo('test_2') inner_suite = unittest.TestSuite([test_2]) def gen(): yield test_1 yield test_2 yield inner_suite suite_1 = unittest.TestSuite() suite_1.addTests(gen()) self.assertEqual(list(suite_1), list(gen())) # "This is equivalent to iterating over tests, calling addTest() for # each element" suite_2 = unittest.TestSuite() for t in gen(): suite_2.addTest(t) self.assertEqual(suite_1, suite_2) # "Add all the tests from an iterable of TestCase and TestSuite # instances to this test suite." # # What happens if it doesn't get an iterable? def test_addTest__noniterable(self): suite = unittest.TestSuite() try: suite.addTests(5) except TypeError: pass else: self.fail("Failed to raise TypeError") def test_addTest__noncallable(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTest, 5) def test_addTest__casesuiteclass(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTest, Test_TestSuite) self.assertRaises(TypeError, suite.addTest, unittest.TestSuite) def test_addTests__string(self): suite = unittest.TestSuite() self.assertRaises(TypeError, suite.addTests, "foo") def test_function_in_suite(self): def f(_): pass suite = unittest.TestSuite() suite.addTest(f) # when the bug is fixed this line will not crash suite.run(unittest.TestResult()) def test_basetestsuite(self): class Test(unittest.TestCase): wasSetUp = False wasTornDown = False @classmethod def setUpClass(cls): cls.wasSetUp = True @classmethod def tearDownClass(cls): cls.wasTornDown = True def testPass(self): pass def testFail(self): fail class Module(object): wasSetUp = False wasTornDown = False @staticmethod def setUpModule(): Module.wasSetUp = True @staticmethod def tearDownModule(): Module.wasTornDown = True Test.__module__ = 'Module' sys.modules['Module'] = Module self.addCleanup(sys.modules.pop, 'Module') suite = unittest.BaseTestSuite() suite.addTests([Test('testPass'), Test('testFail')]) self.assertEqual(suite.countTestCases(), 2) result = unittest.TestResult() suite.run(result) self.assertFalse(Module.wasSetUp) self.assertFalse(Module.wasTornDown) self.assertFalse(Test.wasSetUp) self.assertFalse(Test.wasTornDown) self.assertEqual(len(result.errors), 1) self.assertEqual(len(result.failures), 0) self.assertEqual(result.testsRun, 2) def test_overriding_call(self): class MySuite(unittest.TestSuite): called = False def __call__(self, *args, **kw): self.called = True unittest.TestSuite.__call__(self, *args, **kw) suite = MySuite() result = unittest.TestResult() wrapper = unittest.TestSuite() wrapper.addTest(suite) wrapper(result) self.assertTrue(suite.called) # reusing results should be permitted even if abominable self.assertFalse(result._testRunEntered) if __name__ == '__main__': unittest.main()
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Oct 26 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### import wx import wx.xrc ########################################################################### ## Class bootDeviceWin_FlexspiNor ########################################################################### class bootDeviceWin_FlexspiNor ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 656,398 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) self.SetBackgroundColour( wx.SystemSettings.GetColour( wx.SYS_COLOUR_WINDOW ) ) wSizer_win = wx.WrapSizer( wx.HORIZONTAL, wx.WRAPSIZER_DEFAULT_FLAGS ) self.m_staticText_deviceModel = wx.StaticText( self, wx.ID_ANY, u"Use Typical Device Model:", wx.DefaultPosition, wx.Size( 149,-1 ), 0 ) self.m_staticText_deviceModel.Wrap( -1 ) wSizer_win.Add( self.m_staticText_deviceModel, 0, wx.ALL, 5 ) m_choice_deviceModeChoices = [ u"No", u"Complete_FDCB", u"ISSI_IS25LPxxxA_IS25WPxxxA", u"ISSI_IS26KSxxxS", u"Macronix_MX25UMxxx45G_MX66UMxxx45G_MX25LMxxx45G", u"Macronix_MX25UM51345G", u"Macronix_MX25UM51345G_2nd", u"Micron_MT35XLxxxA_MT35XUxxxA", u"Adesto_AT25SFxxxA", u"Adesto_ATXPxxx", u"Cypress_S26KSxxxS", u"GigaDevice_GD25LBxxxE", u"GigaDevice_GD25LTxxxE", u"GigaDevice_GD25LXxxxE", u"Winbond_W25QxxxJV" ] self.m_choice_deviceMode = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 340,-1 ), m_choice_deviceModeChoices, 0 ) self.m_choice_deviceMode.SetSelection( 0 ) wSizer_win.Add( self.m_choice_deviceMode, 0, wx.ALL, 5 ) self.m_checkBox_keepFdcb = wx.CheckBox( self, wx.ID_ANY, u"Keep FDCB", wx.DefaultPosition, wx.Size( 100,-1 ), 0 ) wSizer_win.Add( self.m_checkBox_keepFdcb, 0, wx.ALL, 5 ) self.m_notebook_norOpt0 = wx.Notebook( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_panel_norOpt0 = wx.Panel( self.m_notebook_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL ) gSizer_norOpt0 = wx.GridSizer( 0, 2, 0, 0 ) self.m_staticText_deviceType = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Device Type:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_deviceType.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_deviceType, 0, wx.ALL, 5 ) m_choice_deviceTypeChoices = [ u"QuadSPI SDR NOR", u"QuadSPI DDR NOR", u"Hyper Flash 1.8V", u"Hyper Flash 3.0V", u"Macronix Octal DDR", u"Macronix Octal SDR", u"Micron Octal DDR", u"Micron Octal SDR", u"Adesto EcoXIP DDR", u"Adesto EcoXIP SDR" ] self.m_choice_deviceType = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_deviceTypeChoices, 0 ) self.m_choice_deviceType.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_deviceType, 0, wx.ALL, 5 ) self.m_staticText_queryPads = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Query Pads:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_queryPads.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_queryPads, 0, wx.ALL, 5 ) m_choice_queryPadsChoices = [ u"1", u"4", u"8" ] self.m_choice_queryPads = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_queryPadsChoices, 0 ) self.m_choice_queryPads.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_queryPads, 0, wx.ALL, 5 ) self.m_staticText_cmdPads = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Cmd Pads:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_cmdPads.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_cmdPads, 0, wx.ALL, 5 ) m_choice_cmdPadsChoices = [ u"1", u"4", u"8" ] self.m_choice_cmdPads = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_cmdPadsChoices, 0 ) self.m_choice_cmdPads.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_cmdPads, 0, wx.ALL, 5 ) self.m_staticText_quadModeSetting = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Quad Mode Setting:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_quadModeSetting.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_quadModeSetting, 0, wx.ALL, 5 ) m_choice_quadModeSettingChoices = [ u"Not Configured", u"Set StatusReg1[6]", u"Set StatusReg2[1]", u"Set StatusReg2[7]", u"Set StatusReg2[1] by 0x31" ] self.m_choice_quadModeSetting = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_quadModeSettingChoices, 0 ) self.m_choice_quadModeSetting.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_quadModeSetting, 0, wx.ALL, 5 ) self.m_staticText_miscMode = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Misc Mode:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_miscMode.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_miscMode, 0, wx.ALL, 5 ) m_choice_miscModeChoices = [ u"Disabled", u"0_4_4 Mode", u"0_8_8 Mode", u"Data Order Swapped", u"Data Samp Intr Loopback", u"Stand SPI mode" ] self.m_choice_miscMode = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_miscModeChoices, 0 ) self.m_choice_miscMode.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_miscMode, 0, wx.ALL, 5 ) self.m_staticText_maxFrequency = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Max Frequency:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_maxFrequency.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_maxFrequency, 0, wx.ALL, 5 ) m_choice_maxFrequencyChoices = [ u"30MHz", u"50MHz", u"60MHz", u"75MHz", u"80MHz", u"100MHz", u"133MHz", u"166MHz" ] self.m_choice_maxFrequency = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_maxFrequencyChoices, 0 ) self.m_choice_maxFrequency.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_maxFrequency, 0, wx.ALL, 5 ) self.m_staticText_hasOption1 = wx.StaticText( self.m_panel_norOpt0, wx.ID_ANY, u"Has Option1:", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText_hasOption1.Wrap( -1 ) gSizer_norOpt0.Add( self.m_staticText_hasOption1, 0, wx.ALL, 5 ) m_choice_hasOption1Choices = [ u"No", u"Yes" ] self.m_choice_hasOption1 = wx.Choice( self.m_panel_norOpt0, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_hasOption1Choices, 0 ) self.m_choice_hasOption1.SetSelection( 0 ) gSizer_norOpt0.Add( self.m_choice_hasOption1, 0, wx.ALL, 5 ) self.m_panel_norOpt0.SetSizer( gSizer_norOpt0 ) self.m_panel_norOpt0.Layout() gSizer_norOpt0.Fit( self.m_panel_norOpt0 ) self.m_notebook_norOpt0.AddPage( self.m_panel_norOpt0, u"Nor Option0", False ) wSizer_win.Add( self.m_notebook_norOpt0, 1, wx.EXPAND |wx.ALL, 5 ) self.m_notebook_norOpt1 = wx.Notebook( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_panel_norOpt1 = wx.Panel( self.m_notebook_norOpt1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL ) gSizer_norOpt1 = wx.GridSizer( 0, 2, 0, 0 ) self.m_staticText_flashConnection = wx.StaticText( self.m_panel_norOpt1, wx.ID_ANY, u"Flash Connection:", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) self.m_staticText_flashConnection.Wrap( -1 ) gSizer_norOpt1.Add( self.m_staticText_flashConnection, 0, wx.ALL, 5 ) m_choice_flashConnectionChoices = [ u"Single Port A", u"Parallel", u"Single Port B", u"Both Ports" ] self.m_choice_flashConnection = wx.Choice( self.m_panel_norOpt1, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_flashConnectionChoices, 0 ) self.m_choice_flashConnection.SetSelection( 0 ) gSizer_norOpt1.Add( self.m_choice_flashConnection, 0, wx.ALL, 5 ) self.m_staticText_driveStrength = wx.StaticText( self.m_panel_norOpt1, wx.ID_ANY, u"Drive Strength:", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) self.m_staticText_driveStrength.Wrap( -1 ) gSizer_norOpt1.Add( self.m_staticText_driveStrength, 0, wx.ALL, 5 ) self.m_textCtrl_driveStrength = wx.TextCtrl( self.m_panel_norOpt1, wx.ID_ANY, u"0", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) gSizer_norOpt1.Add( self.m_textCtrl_driveStrength, 0, wx.ALL, 5 ) self.m_staticText_dqsPinmuxGroup = wx.StaticText( self.m_panel_norOpt1, wx.ID_ANY, u"DQS Pinmux Group:", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) self.m_staticText_dqsPinmuxGroup.Wrap( -1 ) gSizer_norOpt1.Add( self.m_staticText_dqsPinmuxGroup, 0, wx.ALL, 5 ) self.m_textCtrl_dqsPinmuxGroup = wx.TextCtrl( self.m_panel_norOpt1, wx.ID_ANY, u"0", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) gSizer_norOpt1.Add( self.m_textCtrl_dqsPinmuxGroup, 0, wx.ALL, 5 ) self.m_staticText_enableSecondPinmux = wx.StaticText( self.m_panel_norOpt1, wx.ID_ANY, u"Enable Second Pinmux:", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) self.m_staticText_enableSecondPinmux.Wrap( -1 ) gSizer_norOpt1.Add( self.m_staticText_enableSecondPinmux, 0, wx.ALL, 5 ) m_choice_enableSecondPinmuxChoices = [ u"No", u"Yes" ] self.m_choice_enableSecondPinmux = wx.Choice( self.m_panel_norOpt1, wx.ID_ANY, wx.DefaultPosition, wx.Size( 140,-1 ), m_choice_enableSecondPinmuxChoices, 0 ) self.m_choice_enableSecondPinmux.SetSelection( 0 ) gSizer_norOpt1.Add( self.m_choice_enableSecondPinmux, 0, wx.ALL, 5 ) self.m_staticText_statusOverride = wx.StaticText( self.m_panel_norOpt1, wx.ID_ANY, u"Status Override:", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) self.m_staticText_statusOverride.Wrap( -1 ) gSizer_norOpt1.Add( self.m_staticText_statusOverride, 0, wx.ALL, 5 ) self.m_textCtrl_statusOverride = wx.TextCtrl( self.m_panel_norOpt1, wx.ID_ANY, u"0", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) gSizer_norOpt1.Add( self.m_textCtrl_statusOverride, 0, wx.ALL, 5 ) self.m_staticText_dummyCycles = wx.StaticText( self.m_panel_norOpt1, wx.ID_ANY, u"Dummy Cycles:", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) self.m_staticText_dummyCycles.Wrap( -1 ) gSizer_norOpt1.Add( self.m_staticText_dummyCycles, 0, wx.ALL, 5 ) self.m_textCtrl_dummyCycles = wx.TextCtrl( self.m_panel_norOpt1, wx.ID_ANY, u"0", wx.DefaultPosition, wx.Size( 140,-1 ), 0 ) gSizer_norOpt1.Add( self.m_textCtrl_dummyCycles, 0, wx.ALL, 5 ) self.m_panel_norOpt1.SetSizer( gSizer_norOpt1 ) self.m_panel_norOpt1.Layout() gSizer_norOpt1.Fit( self.m_panel_norOpt1 ) self.m_notebook_norOpt1.AddPage( self.m_panel_norOpt1, u"Nor Option1", False ) wSizer_win.Add( self.m_notebook_norOpt1, 1, wx.EXPAND |wx.ALL, 5 ) self.m_staticText_winNull0 = wx.StaticText( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 20,-1 ), 0 ) self.m_staticText_winNull0.Wrap( -1 ) wSizer_win.Add( self.m_staticText_winNull0, 0, wx.ALL, 5 ) self.m_button_completeFdcb = wx.Button( self, wx.ID_ANY, u"Complete FDCB Configuration (512bytes)", wx.DefaultPosition, wx.Size( 238,-1 ), 0 ) wSizer_win.Add( self.m_button_completeFdcb, 0, wx.ALL, 5 ) self.m_staticText_winNull1 = wx.StaticText( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 78,-1 ), 0 ) self.m_staticText_winNull1.Wrap( -1 ) wSizer_win.Add( self.m_staticText_winNull1, 0, wx.ALL, 5 ) self.m_button_ok = wx.Button( self, wx.ID_ANY, u"Ok", wx.DefaultPosition, wx.Size( 100,-1 ), 0 ) wSizer_win.Add( self.m_button_ok, 0, wx.ALL, 5 ) self.m_button_cancel = wx.Button( self, wx.ID_ANY, u"Cancel", wx.DefaultPosition, wx.Size( 100,-1 ), 0 ) wSizer_win.Add( self.m_button_cancel, 0, wx.ALL, 5 ) self.SetSizer( wSizer_win ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.Bind( wx.EVT_CLOSE, self.callbackClose ) self.m_choice_deviceMode.Bind( wx.EVT_CHOICE, self.callbackUseTypicalDeviceModel ) self.m_choice_hasOption1.Bind( wx.EVT_CHOICE, self.callbackHasOption1 ) self.m_button_completeFdcb.Bind( wx.EVT_BUTTON, self.callbackSetCompleteFdcb ) self.m_button_ok.Bind( wx.EVT_BUTTON, self.callbackOk ) self.m_button_cancel.Bind( wx.EVT_BUTTON, self.callbackCancel ) def __del__( self ): pass # Virtual event handlers, overide them in your derived class def callbackClose( self, event ): event.Skip() def callbackUseTypicalDeviceModel( self, event ): event.Skip() def callbackHasOption1( self, event ): event.Skip() def callbackSetCompleteFdcb( self, event ): event.Skip() def callbackOk( self, event ): event.Skip() def callbackCancel( self, event ): event.Skip()
{ "pile_set_name": "Github" }
import React from 'react' import DelayedSort from '../../utils/DelayedSort' import PropTypes from 'prop-types' import SceneThumb from '../SceneThumb' import SceneThumbContainer from '../../containers/SceneThumb' import styled from 'styled-components' import { SortableContainer, SortableElement } from 'react-sortable-hoc' const Wrapper = styled.ul` display: flex; flex-wrap: wrap; > li { width: 12.5%; } ` const SortableItem = SortableElement(({ item }) => <li><SceneThumbContainer key={item.id} id={item.id} /></li> ) const SortableList = SortableContainer(({ items, onAddClick }) => <Wrapper> {items.map((item, index) => ( <SortableItem key={item.id} index={index} item={item} /> ))} <li><SceneThumb onClick={onAddClick}>+</SceneThumb></li> </Wrapper> ) // Using DelayedSort helper util to stop flickering class SceneList extends DelayedSort { updateExternalStateAfterSort (oldIndex, newIndex) { this.props.onSortEnd(oldIndex, newIndex) } render () { return <SortableList {...this.props} items={this.state.items} helperClass='is-sorting' pressDelay={300} axis='xy' onSortEnd={this.handleOnSortEnd} /> } } SceneList.propTypes = { onSortEnd: PropTypes.func.isRequired, items: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string, title: PropTypes.string, }) ), } export default SceneList
{ "pile_set_name": "Github" }
/** * * WARNING! This file was autogenerated by: * _ _ _ _ __ __ * | | | | | | |\ \ / / * | | | | |_| | \ V / * | | | | _ | / \ * | |_| | | | |/ /^\ \ * \___/\_| |_/\/ \/ * * This file was autogenerated by UnrealHxGenerator using UHT definitions. * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal.umg; @:umodule("UMG") @:glueCppIncludes("UMG.h") @:uextern @:uclass extern class UUMGSequencePlayer extends unreal.UObject { }
{ "pile_set_name": "Github" }
apiVersion: operators.coreos.com/v1alpha1 kind: ClusterServiceVersion metadata: annotations: alm-examples: '[{"apiVersion":"redhatcop.redhat.io/v1alpha1","kind":"NamespaceConfig","metadata":{"name":"example-namespaceconfig"},"spec":{"size":3}}]' capabilities: Full Lifecycle categories: Security certified: "false" containerImage: quay.io/redhat-cop/namespace-configuration-operator:latest createdAt: 5/28/2019 description: This operator provides a facility to define and enforce namespace configurations repository: https://github.com/redhat-cop/namespace-configuration-operator support: Best Effort name: namespace-configuration-operator.v0.0.2 namespace: namespace-configuration-operator spec: apiservicedefinitions: {} customresourcedefinitions: owned: - description: Represent the desired configuration for a set of namespaces selected via labels displayName: Namespace Configuration kind: NamespaceConfig name: namespaceconfigs.redhatcop.redhat.io version: v1alpha1 description: "The namespace configuration operator helps keeping a namespace's configuration aligned with one of more policies specified as a CRs.\n\nThe `NamespaceConfig` CR allows specifying one or more objects that will be created in the selected namespaces.\n\nFor example using this operator an administrator can enforce a specific ResourceQuota or LimitRange on a set of namespaces. For example with the following snippet:\n\n```\napiVersion: redhatcop.redhat.io/v1alpha1\nkind: NamespaceConfig\nmetadata:\n name: small-size\nspec:\n selector:\n matchLabels:\n \ size: small \n resources:\n - apiVersion: v1\n kind: ResourceQuota\n \ metadata:\n name: small-size \n spec:\n hard:\n requests.cpu: \"4\"\n requests.memory: \"2Gi\"\n```\n\nwe are enforcing that all the namespaces with label: `size=small` receive the specified resource quota. \n" displayName: Namespace Configuration Operator icon: - base64data: iVBORw0KGgoAAAANSUhEUgAAAOoAAADYCAMAAADS+I/aAAAAgVBMVEX///8AAAD29vb8/Pz5+fnz8/Pq6urf3994eHjIyMi8vLzU1NTQ0NB8fHzx8fGrq6szMzOQkJBtbW2enp5BQUGxsbGkpKRJSUlfX1/d3d1mZmaEhITAwMA5OTkVFRXl5eVTU1MmJiYfHx+WlpZaWloODg6Li4suLi4ZGRk9PT1HR0fjV/a/AAAPPUlEQVR4nM1daUPqOhBVQHZEQJBVWhHw+v9/4LWt0LQ9k8xkaT2fru9BkiHbmTUPD0HxvNlPZ5P559vh5QeH72g9709mq+lw1GuF7blGHPen7eFRi8P2NDw2PU43dIe7b72QKr4vw27TI7ZCdzl/54t5w0d/+Nz0yGUYzWK5mDccTpumx8/FeGIv5g27UdNSmLHZucuZ4dJrWhYdWtMXX4ImOEw7TUtEoNf3KWeGyV+c2oHgWpHgbdC0ZCUM4zCCJvgYNi2dguVXOEETvC+blvAX+zisoAn+xMyODfzWFw7jhgXtrusRNMFnowx5Vp+gCWaNCTo41yvpD5q5eVrb2gX9wbwBAjVsQtAE+5oF7dhM6dt2t1gth4PxDwbD5eo0Wb9aNNOvVdKxbHCH/mpAGVTavf1iHouae6+RGF/4wzrPpxxFuzNaSdbJKriIGZ7Yq249FRnHequI2/I2lHAFjJij6Q/a8sY7+zmv9Y8a+MSKNZK5wwW45y3l4FcsR/1+WVrMp4rONGZ0E3jDvplHMPdiARsxpnbioyMCT1dj9xdvZtyu2SD36auvCo7Gvk9eaVvLqE28+uxOQc/U8cw7P+2YbvBrEEpsumT6TyF6fTZcPh8B/HgGSb+DkbWNnrG8e/+FDZIGtXMta5V1o+1tG1iJ7GhX8YfX3vVnbw0a5EDX/9WRsah41nUU1eLgb+vsdd/+utH5hBfeujFAt2O9cYl/mk5q9IMeY3oYnjiiho3+qzc6RbOIvXD/E93+3Ef7nsbiQafb063Xtk1Zo3HW1bt02414jOgL/sO16ZhsuiF3UZd0KTjam2ia0ljAzdMHNSSno4m+yxqMUeiQK83h56c3aqMRgW1K1nf7NkkvccOxj+S8Wt9+5C3WeIRNi6KqlpoHaWD5A0Fx5NayU+io5Vu31w+Cul+tljBlxucf6a3jcTPaHI9dj/rkHRRvsiCIlI7K1SGK7oi3i3fGscDjO8tbIrSIiPftJxBXOfMc1EzQm4u0HcJZfGauRezwmPjV+Qhfg/QmjJ2aaeFve1YRiGM4krUyxa1wbaCkqH5dSkToiehkauM2+Cc5HdPu1d+Nt2ssaQLzpC9BC7QbbScURwus0QkM8B08SBFLGpNmRp/XDnY6CC4c7P+SnuLExff4Imzn5+raflGd49XDpjl4UuUGjRaxiqUcOjXtX4mLCi9hbtPYg2tD8rHLUBhOdjs4sJ0ME8Qps234ZUtVELoMJQ20P+9fw5c6jHVi7lbM862JDriiBfpuV7UkwXnFuiaPq8Cj88QfnXks/Mug6IHDxwXcJKyzDy9+Fz2sQmrYV2t5gcFz+AkOmHO0QKbuZMiv0MSI+cUK53qDH4MHPYOVYa8xVyqICi1nWvaqBw5e+Zhxm+MG4E/k5p2pbgnOdmhVVd4D8VF4O5rHDH8h7k5dHFAcZfXcYCjpyGFBqZBwWo2UBx5K3KSP9BR5KQsLBmJWe5EuSvMCyGRNBxO0szDv1JvqFxXvP6DQmRk/8NRrDhpoCDOoxnApcNXpXM1QlwEyY5ov+OqRpNVCYeyuvgfoj+Iaa1Sh7sbiNsqCNO+I6gLWuorhvaG3RiBCGfEELWlE0ZFukRPxWf7RDVYU1I2WtsP1yzfVFNnH5OdmaxOx0mYWXDJZmq4OGMOl+wKySwk8eeWZuFDa+WMklNTMfZDeqnO5oLgdCX2gJKvCwPhLkv4zd43MYbofCA1KYpMX5Bppl3BJ0neGfw0eTOn/aXeej73RaLRRJUFGqUggqcb+W4Xmsi67FlhxOkj3vF6L5//2HkKAFoEs0leQu0trlLmkryempO3uwJxCkeBmYEOlHYSBxXxRCY1MXVs/3GWz3hlW72Y6iQQ5w9nUIUshNR4KkhxIHO+ZS8qxfJBnPIkRNUxxLJAk/RydkPkgGF13LMoXpD4KtFXloUCSmgJVPpNLyrFvxnJJM0qEyJVYUlYyGSmrTFJmVmQJiWUL/Gcrvxk7C/WxbP7O9ylHUn3uBIlXrA3bhe1JykupsuZzyrri7CY1MYcjA4Rl1J42geIHqsk/14aFkkoutgLwqWQn6YM2HjtZKyovu8kqlVQTqqzFB+T6DJpNob2i6cuiaCXLZM1XApOgcTPBy9jCgBG3yIXufjXrr6PXKjsd/9DlOP8ztfbfNUAuFbUVdQmXPtd3Z5Z6syxY0xK9RrGUqbKySbc20YlGjLUgryFkLdUKmFB45QLOZRWoF2S4txZHTAs9x4/lrtLH81Px75usEkXKqgTS8AEbC/1KWrgJ0/xEhURmsop2DHbB6ZH68oCOQPlI7KHYa9P8ROXUtwjykR9MUfo9YIQPkKGvEKlUN1fmuQZZf02CgGZ5jab6hbLBUmtw36k7oay/9gygfDlEBdBQeFSq97vJaixroOJ2oQDdy9u1WoByKHiQlc6mquCuu4Bg5UBR+hpZxXHLP+dwzJQ0/x3BN0KlvSnRHFHyt9u8QutfFVH+BeAxC5ZlMi2NwFFWTtUi1WcJ1ny41CHPsjJsAaqRF4gasFKVImt5v9qoU0RUeo6CjQH8/5B14T3LarB7FA9Y8IEgBWhuUGRN6zooFMamUqH2gi2ZyMAnwtYHUGRNeZMiq02Y6jOt05W3f52z2km3hiLrvxL3t5G1TZXwqVh46zyWvrNyOoqsh0RWRX9d2zSLHQvVwAtB9Jcr3m6lgxRZ03pYCjm10qpQTE9cDaUDFCJQ6nzGbtI1rPCmtB6Wwk6lPsAUwDABdmFc/VQYYnibunR7KLKef4TvKGsrXg164tOiEqKONiGg+54KQI4K3d0XabZEVePHERnzDtG6f1kMN8yQzpKskPAB0uylDNjwvXCD331XtwWqyjrSFfr8XrAoTcFGhqktOL58FGnZFluqSFr0eSz1kSN9zk3fvV/QO2IlAIOLe0X01s1l8KuI3levWvhKPUu2Bu8sK9OitT9Ndgt6+wEzmnNWYis/ZVKyByUVhTt5sXcB35lrzbGOytXmiqTlW13ikLUiF0UgPcixyWJQxvxOhqr8RfKGk7usSA1y4/tUoAByZUqe/XEu0Y60ICeLCxVShH0GkqrlzjcDaNPpYhVJWuD6RrgavYC+53LcEe5P2hEvCIyxqHNRAPhZrSj3L4hQBc03BE8rOBYiQO5Kh+aIClyaQbZ5wZ8p3PRLFM1uq8Y9Lcgp0pyfgnBitxsHRQjYeW2etVeHRlZBfI7btIIGraih6RUCjWOGrjtXPjTdCKKncEpzPBzN2YkyI4+TzkOvdPPay/ngKUiWyqwpgA7cxq6m7LcZFYim0wpG1FBKTDqsU5QeJlRy7qtA5elOHlF0AAqL+NOlIwugG0DXgLItO/mB51bPCNU8FtmCCwyJllpzrqMY3+IHbreYmzkTkQjJdaPeFYdnMoQq0jQBUiXKeyh7WFHXCAMoIE3ADVVJU3MgPqE+tLa/6uerBtLhP3djBBoZewWrkqb3MSb8Z71tt7KJ/MeJpUBOD+4ZrIbBZd4l+JqwQdKq3hqoijYiK8ziQ2oZ0Gx00FkUmwwblQ0eIk7sgQhQZOnBaiHbjOSm5qJxyWT1arTRV37tULXR0UHC6ktRZDJJE+p1LUXCcgzL1dsmUJgCDJ9g+IgUeTJJV7cpvJ/qy2dWldfqbfMVxvcJV7A51FBR2jJJk2WYXlP5KcwdAlB0w2xXaMwyfUmxDWarPaF3UfKP9p0ysUMzoaExxENpsOCjoSMlUrUkqWL0ZntKCfXcf2gnVBgNBrr8/sxcpsP7v3INWGCmpizC3l9Cgi4F7U+aT0OU/p1Lqgxa4CcgrS6xZy8+TB/UTut9zWfZ48u7zIo5QqRc0pnGns8naOrTscP7BZXO3OouqX2YL23o98sncCVazZ14s5qlrOqEJBVbMunMZr9BN7ALzdK5UblkJyVrNjNcKJJaPEdIrmG/gee4G1qXu7vwVsNEA8ve91ITamwGcSQ8OH5jAbGBUqOiFz53TndsOU3KAhtkZPX9hg4OTaB7Kehd6ewrt8yXvTu6MyxJu/Me9Ei4Tkj9S/18upeUxef6DGF3MN31+/P+brEPwvpxFAZ90Cs65qBYl+IcMlA8w3G1282mtmkGRAohHQikLNjBSAkTNFlXPOB2/l0ttzERSEQfMLjAiP8HQ8t4jvPe7JIVibrlNBWAj+kY7UjOKNok7YoAEH5DmvarWfK3nkM8eFJAp5Swb0cbUfXBR12SUbtswI3shi9BZdtYRb4Qz8W8a2aqeAnW8AhilSnbbVeCmOkaUxWFIKmvRaAr0WrPUAqyTh/r3JzRhxqeBoTGTbvYLaoKi97u0R0sl4PwvIHKDLO8XGNC1oYecyyCyAuzzDYgKzc1/CBeAmp72Q6NDL4OmOzJA/kknnWLVAhHDdRWC/JRR4tU9V+Qz5mHJ7c60LGIDkyUjCv7aFBWWlInozhppqxBESUA2PYvIqd2qUC4x8bOYU1GrqMipclrbuTBTvL48DAeOpaziSewNdVbPbjqNOk+NXD6IjQ1EZwzUhJo0gc8ZDJJoEk8ivz0ENM9xDUSpydNGoPowT9dH3QXNW5YbZELb9e85tirxdyQQJs153FtaetynWu4dTbaOGOvnkh9iZRAsXE59Emfnn9qvaxnTwn4RN/kS5gpvJsKDKVv1sE4cdeQFxjgVzaVN54FsXB3TAnLQcw/xpL6/kPG2tqKygkCHYnGMuFnvyFjbfP7AcFKmplT1s4rb8u4ZZzRx/eAXA08U1fBxUv/R0ai/cEyyoIJTpp05Hwo7jnZZl7f0kbg1R/eORCYDa9KRA0aJOGjKyOeWUm7mcW89oOSlhuOzME8nid7kbnnaT/h1kq91qU8Cl5sOFz2rFF19xfBgy1eTA484JBLEuuTpjJUuzc8SR6GeazZqNUVFDa44W17WSz349Gm1zv2NqPxYLm4mGoOIXzXbYI2JZQHQ4iMBQOOvLK8nvHdjBfQWL7VP7ynKnDRsnw8xxbz4DFfGowYpNgXDo14ThRoHB1ecW7AbVKB/FU6CzRw7iJ0zJqlIxbBwxXZMBtGXPBHZvSOKRGA6YprY/eLBgPJU3hMrP9EPBjA0erdIBJfp8YDpHQYeGMV/b86oTnaQ0lJQgLzQC+R+MeAbU4AOO9qMab4Q28q1LczrKd/IFjTAr1pX1Cv79q3Tgz6G2iNpxOjZhvtpqOw9uv68DwaTmeT+fbz7fUlwb/vt8/5fHJZTIfjXt2s7z9MqsTdLqoFFgAAAABJRU5ErkJggg== mediatype: image/png install: spec: clusterPermissions: - rules: - apiGroups: - '*' resources: - '*' verbs: - '*' serviceAccountName: namespace-configuration-operator deployments: - name: namespace-configuration-operator spec: replicas: 1 selector: matchLabels: name: namespace-configuration-operator strategy: {} template: metadata: labels: name: namespace-configuration-operator spec: containers: - command: - namespace-configuration-operator env: - name: WATCH_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.annotations['olm.targetNamespaces'] - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: OPERATOR_NAME value: namespace-configuration-operator image: quay.io/redhat-cop/namespace-configuration-operator:v0.0.2 imagePullPolicy: Always name: namespace-configuration-operator resources: {} serviceAccountName: namespace-configuration-operator permissions: - rules: - apiGroups: - "" resources: - configmaps - pods verbs: - '*' - apiGroups: - "" resources: - services verbs: - '*' - apiGroups: - apps resources: - replicasets - deployments verbs: - get - list - apiGroups: - monitoring.coreos.com resources: - servicemonitors verbs: - get - create - apiGroups: - apps resourceNames: - namespace-configuration-operator resources: - deployments/finalizers verbs: - update serviceAccountName: namespace-configuration-operator strategy: deployment installModes: - supported: true type: OwnNamespace - supported: true type: SingleNamespace - supported: false type: MultiNamespace - supported: false type: AllNamespaces keywords: - namespace - configuration - policy - management links: - name: repository url: https://github.com/redhat-cop/namespace-configuration-operator - name: conatinerImage url: https://quay.io/redhat-cop/namespace-configuration-operator:latest - name: blog url: https://blog.openshift.com/controlling-namespace-configurations maintainers: - email: rspazzol@redhat.com name: Raffaele Spazzoli maturity: alpha provider: name: Containers & PaaS CoP replaces: namespace-configuration-operator.v0.0.1 version: 0.0.2
{ "pile_set_name": "Github" }