text
stringlengths
101
197k
meta
stringlengths
167
272
import KUTE from '../objects/kute.js' import numbers from '../interpolation/numbers.js' import colors from '../interpolation/colors.js' // const filterEffects = { property : 'filter', subProperties: {}, defaultValue: {}, interpolators: {} }, functions = { prepareStart, prepareProperty, onStart, crossCheck } // Component Interpolation export function dropShadow(a,b,v){ let params = [], unit = 'px' for (let i=0; i<3; i++){ params[i] = ((numbers(a[i],b[i],v) * 100 >>0) /100) + unit } return `drop-shadow(${params.concat( colors(a[3],b[3],v) ).join(' ') })` } // Component Functions export function onStartFilter(tweenProp) { if ( this.valuesEnd[tweenProp] && !KUTE[tweenProp]) { KUTE[tweenProp] = (elem, a, b, v) => { elem.style[tweenProp] = (b.url ? `url(${b.url})` : '') + (a.opacity||b.opacity ? `opacity(${((numbers(a.opacity,b.opacity,v) * 100)>>0)/100}%)` : '') + (a.blur||b.blur ? `blur(${((numbers(a.blur,b.blur,v) * 100)>>0)/100}em)` : '') + (a.saturate||b.saturate ? `saturate(${((numbers(a.saturate,b.saturate,v) * 100)>>0)/100}%)` : '') + (a.invert||b.invert ? `invert(${((numbers(a.invert,b.invert,v) * 100)>>0)/100}%)` : '') + (a.grayscale||b.grayscale ? `grayscale(${((numbers(a.grayscale,b.grayscale,v) * 100)>>0)/100}%)` : '') + (a.hueRotate||b.hueRotate ? `hue-rotate(${((numbers(a.hueRotate,b.hueRotate,v) * 100)>>0)/100 }deg)` : '') + (a.sepia||b.sepia ? `sepia(${((numbers(a.sepia,b.sepia,v) * 100)>>0)/100 }%)` : '') + (a.brightness||b.brightness ? `brightness(${((numbers(a.brightness,b.brightness,v) * 100)>>0)/100 }%)` : '') + (a.contrast||b.contrast ? `contrast(${((numbers(a.contrast,b.contrast,v) * 100)>>0)/100 }%)` : '') + (a.dropShadow||b.dropShadow ? dropShadow(a.dropShadow,b.dropShadow,v) : '') } } } // Base Component const baseFilter = { component: 'baseFilter', property: 'filter', // subProperties: ['blur', 'brightness','contrast','dropShadow','hueRotate','grayscale','invert','opacity','saturate','sepia','url'], // opacity function interfere with opacityProperty // defaultValue: {opacity: 100, blur: 0, saturate: 100, grayscale: 0, brightness: 100, contrast: 100, sepia: 0, invert: 0, hueRotate:0, dropShadow: [0,0,0,{r:0,g:0,b:0}], url:''}, Interpolate: { opacity: numbers, blur: numbers, saturate: numbers, grayscale: numbers, brightness: numbers, contrast: numbers, sepia: numbers, invert: numbers, hueRotate: numbers, dropShadow: {numbers,colors,dropShadow} }, functions: {onStart:onStartFilter} } export default baseFilter
{'repo_name': 'thednp/kute.js', 'stars': '1982', 'repo_language': 'JavaScript', 'file_name': 'kute.esm.js', 'mime_type': 'text/plain', 'hash': -2805295512324576553, 'source_dataset': 'data'}
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.analysis.constraints; import com.google.auto.value.AutoValue; import com.google.devtools.build.lib.analysis.LabelAndLocation; import com.google.devtools.build.lib.analysis.TransitiveInfoProvider; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec; /** * A provider that advertises which environments the associated target is compatible with * (from the point of view of the constraint enforcement system). */ public interface SupportedEnvironmentsProvider extends TransitiveInfoProvider { /** * Returns the static environments this target is compatible with. Static environments * are those that are independent of build configuration (e.g. declared in {@code restricted_to} / * {@code compatible_with}). See {@link ConstraintSemantics} for details. */ EnvironmentCollection getStaticEnvironments(); /** * Returns the refined environments this rule is compatible with. Refined environments are * static environments with unsupported environments from {@code select}able deps removed (on the * principle that others paths in the select would have provided those environments, so this rule * is "refined" to match whichever deps got chosen). * * <p>>Refined environments require knowledge of the build configuration. See * {@link ConstraintSemantics} for details. */ EnvironmentCollection getRefinedEnvironments(); /** * Provides all context necessary to communicate which dependencies caused an environment to be * refined out of the current rule. * * <p>The culprit<b>s</b> are actually two rules: * * <pre> * some_rule(name = "adep", restricted_to = ["//foo:a"]) * * some_rule(name = "bdep", restricted_to = ["//foo:b"]) * * some_rule( * name = "has_select", * restricted_to = ["//foo:a", "//foo:b"], * deps = select({ * ":acond": [:"adep"], * ":bcond": [:"bdep"], * } * </pre> * * <p>If we build a target with <code>":has_select"</code> somewhere in its deps and trigger * <code>":bcond"</code> and that strips <code>"//foo:a"</code> out of the top-level target's * environments in a way that triggers an error, the user needs to understand two rules to trace * this error. <code>":has_select"</code> is the direct culprit, because this is the first rule * that strips <code>"//foo:a"</code>. But it does that because its <code>select()</code> path * chooses <code>":bdep"</code>, and <code>":bdep"</code> is why <code>":has_select"</code> * decides it's a <code>"//foo:b"</code>-only rule for this build. */ @AutoValue abstract class RemovedEnvironmentCulprit { @AutoCodec.Instantiator public static RemovedEnvironmentCulprit create(LabelAndLocation culprit, Label selectedDepForCulprit) { return new AutoValue_SupportedEnvironmentsProvider_RemovedEnvironmentCulprit(culprit, selectedDepForCulprit); } abstract LabelAndLocation culprit(); abstract Label selectedDepForCulprit(); } /** * If the given environment was refined away from this target's set of supported environments, * returns the dependency that originally removed the environment. * * <p>For example, if the current rule is restricted_to [E] and depends on D1, D1 is restricted_to * [E] and depends on D2, and D2 is restricted_to [E, F] and has a select() with one path * following an E-restricted dep and the other path following an F-restricted dep, then when the * build chooses the F path the current rule has [E] refined to [] and D2 is the culprit. * * <p>If the given environment was not refined away for this rule, returns null. * * <p>See {@link ConstraintSemantics} class documentation for more details on refinement. */ RemovedEnvironmentCulprit getRemovedEnvironmentCulprit(Label environment); }
{'repo_name': 'bazelbuild/bazel', 'stars': '15030', 'repo_language': 'Java', 'file_name': 'BUILD', 'mime_type': 'text/plain', 'hash': -3036885757875539740, 'source_dataset': 'data'}
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (c) 2011+, HL7, Inc. 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 HL7 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. Generated on Fri, Nov 1, 2019 09:29+1100 for FHIR v4.0.1 Note: the schemas &amp; schematrons do not contain all of the rules about what makes resources valid. Implementers will still need to be familiar with the content of the specification and with any profiles that apply to the resources in order to make a conformant implementation. --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://hl7.org/fhir" xmlns:xhtml="http://www.w3.org/1999/xhtml" targetNamespace="http://hl7.org/fhir" elementFormDefault="qualified" version="1.0"> <xs:include schemaLocation="fhir-base.xsd"/> <xs:element name="SubstancePolymer" type="SubstancePolymer"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:complexType name="SubstancePolymer"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> <xs:documentation xml:lang="en">If the element is present, it must have either a @value, an @id, or extensions</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="DomainResource"> <xs:sequence> <xs:element name="class" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="geometry" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="copolymerConnectivity" minOccurs="0" maxOccurs="unbounded" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="modification" minOccurs="0" maxOccurs="unbounded" type="string"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="monomerSet" type="SubstancePolymer.MonomerSet" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="repeat" type="SubstancePolymer.Repeat" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="SubstancePolymer.MonomerSet"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="BackboneElement"> <xs:sequence> <xs:element name="ratioType" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="startingMaterial" type="SubstancePolymer.StartingMaterial" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="SubstancePolymer.StartingMaterial"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="BackboneElement"> <xs:sequence> <xs:element name="material" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="type" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="isDefining" minOccurs="0" maxOccurs="1" type="boolean"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="amount" minOccurs="0" maxOccurs="1" type="SubstanceAmount"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="SubstancePolymer.Repeat"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="BackboneElement"> <xs:sequence> <xs:element name="numberOfUnits" minOccurs="0" maxOccurs="1" type="integer"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="averageMolecularFormula" minOccurs="0" maxOccurs="1" type="string"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="repeatUnitAmountType" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="repeatUnit" type="SubstancePolymer.RepeatUnit" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="SubstancePolymer.RepeatUnit"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="BackboneElement"> <xs:sequence> <xs:element name="orientationOfPolymerisation" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="repeatUnit" minOccurs="0" maxOccurs="1" type="string"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="amount" minOccurs="0" maxOccurs="1" type="SubstanceAmount"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="degreeOfPolymerisation" type="SubstancePolymer.DegreeOfPolymerisation" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="structuralRepresentation" type="SubstancePolymer.StructuralRepresentation" minOccurs="0" maxOccurs="unbounded"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="SubstancePolymer.DegreeOfPolymerisation"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="BackboneElement"> <xs:sequence> <xs:element name="degree" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="amount" minOccurs="0" maxOccurs="1" type="SubstanceAmount"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> <xs:complexType name="SubstancePolymer.StructuralRepresentation"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> <xs:complexContent> <xs:extension base="BackboneElement"> <xs:sequence> <xs:element name="type" minOccurs="0" maxOccurs="1" type="CodeableConcept"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="representation" minOccurs="0" maxOccurs="1" type="string"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> <xs:element name="attachment" minOccurs="0" maxOccurs="1" type="Attachment"> <xs:annotation> <xs:documentation xml:lang="en">Todo.</xs:documentation> </xs:annotation> </xs:element> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> </xs:schema>
{'repo_name': 'jamesagnew/hapi-fhir', 'stars': '1022', 'repo_language': 'Java', 'file_name': 'GenericClientDstu3IT.java', 'mime_type': 'text/x-java', 'hash': -8129267705267359886, 'source_dataset': 'data'}
// Copyright 2017 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 !linux package ipv6 import ( "golang.org/x/net/bpf" "golang.org/x/net/internal/socket" ) func (so *sockOpt) setAttachFilter(c *socket.Conn, f []bpf.RawInstruction) error { return errNotImplemented }
{'repo_name': 'moby/libnetwork', 'stars': '1690', 'repo_language': 'Go', 'file_name': 'readme.go', 'mime_type': 'text/x-c', 'hash': 5373937891878641086, 'source_dataset': 'data'}
10 dir 15 http://172.29.142.136/svn/ComPerformance/trunk/webadmin/static/grappelli/tinymce/jscripts/tiny_mce/plugins/advimage_orig/js http://172.29.142.136/svn/ComPerformance 2012-12-17T23:48:53.124555Z 14 guomeng 195aecd3-0995-4018-8772-f786c0b7483b image.js file 2012-12-17T00:16:42.000000Z 87dd2b03a37248f7615277e160d4bdcd 2012-12-17T23:48:53.124555Z 14 guomeng 12806
{'repo_name': 'gnemoug/ComPerformance', 'stars': '360', 'repo_language': 'JavaScript', 'file_name': 'captcha_clean.py.svn-base', 'mime_type': 'text/x-python', 'hash': 6615608471489709913, 'source_dataset': 'data'}
set step-mode on set disassemble-next-line on display/i $pc set architecture i386:x86-64 set disassembly-flavor intel define trem target remote localhost:1234 end set substitute-path /home/spse/swift-kernel-lib /Users/spse/Files/src/swift-kernel-lib set substitute-path /home/spse/src/project1 /Users/spse/Files/src/project1 file output/kernel.elf break abort break debugger_hook
{'repo_name': 'spevans/swift-project1', 'stars': '189', 'repo_language': 'Swift', 'file_name': 'other-notes.md', 'mime_type': 'text/plain', 'hash': -6714076499259609481, 'source_dataset': 'data'}
/* * Copyright 2018, GeoSolutions Sas. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ const expect = require('expect'); const { searchTextSelector, isFeaturedMapsEnabled } = require('../featuredmaps'); describe('featuredMaps selectors', () => { it('test searchTextSelector', () => { const state = { featuredmaps: { searchText: 'text' } }; expect(searchTextSelector(state)).toBe('text'); expect(searchTextSelector()).toBe(''); }); it('test isFeaturedMapsEnabled', () => { const state = { featuredmaps: { enabled: true } }; expect(isFeaturedMapsEnabled(state)).toBeTruthy(); }); });
{'repo_name': 'geosolutions-it/MapStore2', 'stars': '213', 'repo_language': 'JavaScript', 'file_name': 'app.js', 'mime_type': 'text/html', 'hash': -719504683102238005, 'source_dataset': 'data'}
var $lang={ errAlertMsg: "\u4E0D\u5408\u6CD5\u7684\u65E5\u671F\u683C\u5F0F\u6216\u8005\u65E5\u671F\u8D85\u51FA\u9650\u5B9A\u7BC4\u570D,\u9700\u8981\u64A4\u92B7\u55CE?", aWeekStr: ["\u5468","\u65E5","\u4E00","\u4E8C","\u4E09","\u56DB","\u4E94","\u516D"], aLongWeekStr:["\u5468","\u661F\u671F\u65E5","\u661F\u671F\u4E00","\u661F\u671F\u4E8C","\u661F\u671F\u4E09","\u661F\u671F\u56DB","\u661F\u671F\u4E94","\u661F\u671F\u516D"], aMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00","\u5341\u4E8C"], aLongMonStr: ["\u4E00\u6708","\u4E8C\u6708","\u4E09\u6708","\u56DB\u6708","\u4E94\u6708","\u516D\u6708","\u4E03\u6708","\u516B\u6708","\u4E5D\u6708","\u5341\u6708","\u5341\u4E00\u6708","\u5341\u4E8C\u6708"], clearStr: "\u6E05\u7A7A", todayStr: "\u4ECA\u5929", okStr: "\u78BA\u5B9A", updateStr: "\u78BA\u5B9A", timeStr: "\u6642\u9593", quickStr: "\u5FEB\u901F\u9078\u64C7", err_1: '\u6700\u5C0F\u65E5\u671F\u4E0D\u80FD\u5927\u65BC\u6700\u5927\u65E5\u671F!' }
{'repo_name': 'alibaba/mdrill', 'stars': '1429', 'repo_language': 'Java', 'file_name': 'INSTALL_SINGLE.txt', 'mime_type': 'text/plain', 'hash': 3512891487011310384, 'source_dataset': 'data'}
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga 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; either version 2.1 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" /* * Atari keyboard events manager, using Gemdos * * Patrice Mandin */ #ifndef _SDL_ATARI_GEMDOSEVENTS_H_ #define _SDL_ATARI_GEMDOSEVENTS_H_ #include "../SDL_sysvideo.h" /* Hidden "this" pointer for the video functions */ #define _THIS SDL_VideoDevice *this extern void AtariGemdos_InitOSKeymap(_THIS); extern void AtariGemdos_PumpEvents(_THIS); extern void AtariGemdos_ShutdownEvents(void); #endif /* _SDL_ATARI_GEMDOSEVENTS_H_ */
{'repo_name': 'joncampbell123/dosbox-x', 'stars': '780', 'repo_language': 'C', 'file_name': 'pegc.h', 'mime_type': 'text/x-c', 'hash': 7149593565140703731, 'source_dataset': 'data'}
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id$ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_View_Helper_Abstract.php */ #require_once 'Zend/View/Helper/Abstract.php'; /** * Renders a template and stores the rendered output as a placeholder * variable for later use. * * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_View_Helper_RenderToPlaceholder extends Zend_View_Helper_Abstract { /** * Renders a template and stores the rendered output as a placeholder * variable for later use. * * @param string $script The template script to render * @param string $placeholder The placeholder variable name in which to store the rendered output * @return void */ public function renderToPlaceholder($script, $placeholder) { $this->view->placeholder($placeholder)->captureStart(); echo $this->view->render($script); $this->view->placeholder($placeholder)->captureEnd(); } }
{'repo_name': 'OpenMage/magento-mirror', 'stars': '617', 'repo_language': 'PHP', 'file_name': 'editor_plugin_src.js', 'mime_type': 'text/plain', 'hash': 9098917923965124115, 'source_dataset': 'data'}
// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 <fastrtps/types/AnnotationDescriptor.h> #include <fastrtps/types/DynamicType.h> #include <fastrtps/types/DynamicTypeBuilder.h> #include <fastrtps/types/DynamicTypeBuilderFactory.h> #include <fastrtps/types/TypeDescriptor.h> #include <fastrtps/types/DynamicTypeMember.h> #include <fastdds/dds/log/Log.hpp> #include <dds/core/LengthUnlimited.hpp> namespace eprosima { namespace fastrtps { namespace types { DynamicType::DynamicType() : descriptor_(nullptr) , name_("") , kind_(TK_NONE) , is_key_defined_(false) { } DynamicType::DynamicType( const TypeDescriptor* descriptor) : is_key_defined_(false) { descriptor_ = new TypeDescriptor(descriptor); try { name_ = descriptor->get_name(); kind_ = descriptor->get_kind(); } catch (...) { name_ = ""; kind_ = TK_NONE; } // Alias types use the same members than it's base class. if (kind_ == TK_ALIAS) { for (auto it = descriptor_->get_base_type()->member_by_id_.begin(); it != descriptor_->get_base_type()->member_by_id_.end(); ++it) { member_by_name_.insert(std::make_pair(it->second->get_name(), it->second)); } } } DynamicType::DynamicType( const DynamicTypeBuilder* other) : descriptor_(nullptr) , name_("") , kind_(TK_NONE) , is_key_defined_(false) { copy_from_builder(other); } DynamicType::~DynamicType() { clear(); } ReturnCode_t DynamicType::apply_annotation( AnnotationDescriptor& descriptor) { if (descriptor.is_consistent()) { AnnotationDescriptor* pNewDescriptor = new AnnotationDescriptor(); pNewDescriptor->copy_from(&descriptor); descriptor_->annotation_.push_back(pNewDescriptor); is_key_defined_ = key_annotation(); return ReturnCode_t::RETCODE_OK; } else { logError(DYN_TYPES, "Error applying annotation. The input descriptor isn't consistent."); return ReturnCode_t::RETCODE_BAD_PARAMETER; } } ReturnCode_t DynamicType::apply_annotation( const std::string& annotation_name, const std::string& key, const std::string& value) { AnnotationDescriptor* ann = descriptor_->get_annotation(annotation_name); if (ann != nullptr) { ann->set_value(key, value); } else { AnnotationDescriptor* pNewDescriptor = new AnnotationDescriptor(); pNewDescriptor->set_type( DynamicTypeBuilderFactory::get_instance()->create_annotation_primitive(annotation_name)); pNewDescriptor->set_value(key, value); descriptor_->annotation_.push_back(pNewDescriptor); is_key_defined_ = key_annotation(); } return ReturnCode_t::RETCODE_OK; } ReturnCode_t DynamicType::apply_annotation_to_member( MemberId id, AnnotationDescriptor& descriptor) { if (descriptor.is_consistent()) { auto it = member_by_id_.find(id); if (it != member_by_id_.end()) { it->second->apply_annotation(descriptor); return ReturnCode_t::RETCODE_OK; } else { logError(DYN_TYPES, "Error applying annotation to member. MemberId not found."); return ReturnCode_t::RETCODE_BAD_PARAMETER; } } else { logError(DYN_TYPES, "Error applying annotation to member. The input descriptor isn't consistent."); return ReturnCode_t::RETCODE_BAD_PARAMETER; } } ReturnCode_t DynamicType::apply_annotation_to_member( MemberId id, const std::string& annotation_name, const std::string& key, const std::string& value) { auto it = member_by_id_.find(id); if (it != member_by_id_.end()) { it->second->apply_annotation(annotation_name, key, value); return ReturnCode_t::RETCODE_OK; } else { logError(DYN_TYPES, "Error applying annotation to member. MemberId not found."); return ReturnCode_t::RETCODE_BAD_PARAMETER; } } void DynamicType::clear() { name_ = ""; kind_ = 0; if (descriptor_ != nullptr) { delete descriptor_; descriptor_ = nullptr; } for (auto it = member_by_id_.begin(); it != member_by_id_.end(); ++it) { delete it->second; } member_by_id_.clear(); member_by_name_.clear(); } ReturnCode_t DynamicType::copy_from_builder( const DynamicTypeBuilder* other) { if (other != nullptr) { clear(); name_ = other->name_; kind_ = other->kind_; descriptor_ = new TypeDescriptor(other->descriptor_); for (auto it = other->member_by_id_.begin(); it != other->member_by_id_.end(); ++it) { DynamicTypeMember* newMember = new DynamicTypeMember(it->second); newMember->set_parent(this); is_key_defined_ = newMember->key_annotation(); member_by_id_.insert(std::make_pair(newMember->get_id(), newMember)); member_by_name_.insert(std::make_pair(newMember->get_name(), newMember)); } return ReturnCode_t::RETCODE_OK; } else { logError(DYN_TYPES, "Error copying DynamicType, invalid input type"); return ReturnCode_t::RETCODE_BAD_PARAMETER; } } bool DynamicType::exists_member_by_name( const std::string& name) const { if (descriptor_->get_base_type() != nullptr) { if (descriptor_->get_base_type()->exists_member_by_name(name)) { return true; } } return member_by_name_.find(name) != member_by_name_.end(); } ReturnCode_t DynamicType::get_descriptor( TypeDescriptor* descriptor) const { if (descriptor != nullptr) { descriptor->copy_from(descriptor_); return ReturnCode_t::RETCODE_OK; } else { logError(DYN_TYPES, "Error getting TypeDescriptor, invalid input descriptor"); return ReturnCode_t::RETCODE_BAD_PARAMETER; } } const TypeDescriptor* DynamicType::get_descriptor() const { return descriptor_; } TypeDescriptor* DynamicType::get_descriptor() { return descriptor_; } bool DynamicType::key_annotation() const { for (auto anIt = descriptor_->annotation_.begin(); anIt != descriptor_->annotation_.end(); ++anIt) { if ((*anIt)->key_annotation()) { return true; } } return false; } bool DynamicType::equals( const DynamicType* other) const { if (other != nullptr && descriptor_->annotation_.size() == other->descriptor_->annotation_.size() && member_by_id_.size() == other->member_by_id_.size() && member_by_name_.size() == other->member_by_name_.size()) { // Check the annotation list for (auto it = descriptor_->annotation_.begin(), it2 = other->descriptor_->annotation_.begin(); it != descriptor_->annotation_.end(); ++it, ++it2) { if (!(*it)->equals(*it)) { return false; } } // Check the members by Id for (auto it = member_by_id_.begin(); it != member_by_id_.end(); ++it) { auto it2 = other->member_by_id_.find(it->first); if (it2 == other->member_by_id_.end() || !it2->second->equals(it->second)) { return false; } } for (auto it = other->member_by_id_.begin(); it != other->member_by_id_.end(); ++it) { auto it2 = member_by_id_.find(it->first); if (it2 == member_by_id_.end() || !it2->second->equals(it->second)) { return false; } } // Check the members by Name for (auto it = member_by_name_.begin(); it != member_by_name_.end(); ++it) { auto it2 = other->member_by_name_.find(it->first); if (it2 == other->member_by_name_.end() || !it2->second->equals(it->second)) { return false; } } for (auto it = other->member_by_name_.begin(); it != other->member_by_name_.end(); ++it) { auto it2 = member_by_name_.find(it->first); if (it2 == member_by_name_.end() || !it2->second->equals(it->second)) { return false; } } return true; } return false; } MemberId DynamicType::get_members_count() const { return static_cast<MemberId>(member_by_id_.size()); } std::string DynamicType::get_name() const { return name_; } ReturnCode_t DynamicType::get_member_by_name( DynamicTypeMember& member, const std::string& name) { auto it = member_by_name_.find(name); if (it != member_by_name_.end()) { member = it->second; return ReturnCode_t::RETCODE_OK; } else { logWarning(DYN_TYPES, "Error getting member by name, member not found."); return ReturnCode_t::RETCODE_ERROR; } } ReturnCode_t DynamicType::get_all_members_by_name( std::map<std::string, DynamicTypeMember*>& members) { members = member_by_name_; return ReturnCode_t::RETCODE_OK; } ReturnCode_t DynamicType::get_member( DynamicTypeMember& member, MemberId id) { auto it = member_by_id_.find(id); if (it != member_by_id_.end()) { member = it->second; return ReturnCode_t::RETCODE_OK; } else { logWarning(DYN_TYPES, "Error getting member, member not found."); return ReturnCode_t::RETCODE_ERROR; } } ReturnCode_t DynamicType::get_all_members( std::map<MemberId, DynamicTypeMember*>& members) { members = member_by_id_; return ReturnCode_t::RETCODE_OK; } uint32_t DynamicType::get_annotation_count() { return static_cast<uint32_t>(descriptor_->annotation_.size()); } ReturnCode_t DynamicType::get_annotation( AnnotationDescriptor& descriptor, uint32_t idx) { if (idx < descriptor_->annotation_.size()) { descriptor = *descriptor_->annotation_[idx]; return ReturnCode_t::RETCODE_OK; } else { logWarning(DYN_TYPES, "Error getting annotation, annotation not found."); return ReturnCode_t::RETCODE_ERROR; } } DynamicType_ptr DynamicType::get_base_type() const { if (descriptor_ != nullptr) { return descriptor_->get_base_type(); } return DynamicType_ptr(nullptr); } uint32_t DynamicType::get_bounds( uint32_t index /*= 0*/) const { if (descriptor_ != nullptr) { return descriptor_->get_bounds(index); } return ::dds::core::LENGTH_UNLIMITED; } uint32_t DynamicType::get_bounds_size() const { if (descriptor_ != nullptr) { return descriptor_->get_bounds_size(); } return 0; } DynamicType_ptr DynamicType::get_discriminator_type() const { if (descriptor_ != nullptr) { return descriptor_->get_discriminator_type(); } return DynamicType_ptr(nullptr); } DynamicType_ptr DynamicType::get_element_type() const { if (descriptor_ != nullptr) { return descriptor_->get_element_type(); } return DynamicType_ptr(nullptr); } DynamicType_ptr DynamicType::get_key_element_type() const { if (descriptor_ != nullptr) { return descriptor_->get_key_element_type(); } return DynamicType_ptr(nullptr); } uint32_t DynamicType::get_total_bounds() const { if (descriptor_ != nullptr) { return descriptor_->get_total_bounds(); } return ::dds::core::LENGTH_UNLIMITED; } bool DynamicType::has_children() const { return kind_ == TK_ANNOTATION || kind_ == TK_ARRAY || kind_ == TK_MAP || kind_ == TK_SEQUENCE || kind_ == TK_STRUCTURE || kind_ == TK_UNION || kind_ == TK_BITSET; } bool DynamicType::is_complex_kind() const { return kind_ == TK_ANNOTATION || kind_ == TK_ARRAY || kind_ == TK_BITMASK || kind_ == TK_ENUM || kind_ == TK_MAP || kind_ == TK_SEQUENCE || kind_ == TK_STRUCTURE || kind_ == TK_UNION || kind_ == TK_BITSET; } bool DynamicType::is_consistent() const { return descriptor_->is_consistent(); } bool DynamicType::is_discriminator_type() const { if (kind_ == TK_ALIAS && descriptor_ != nullptr && descriptor_->get_base_type() != nullptr) { return descriptor_->get_base_type()->is_discriminator_type(); } return kind_ == TK_BOOLEAN || kind_ == TK_BYTE || kind_ == TK_INT16 || kind_ == TK_INT32 || kind_ == TK_INT64 || kind_ == TK_UINT16 || kind_ == TK_UINT32 || kind_ == TK_UINT64 || kind_ == TK_FLOAT32 || kind_ == TK_FLOAT64 || kind_ == TK_FLOAT128 || kind_ == TK_CHAR8 || kind_ == TK_CHAR16 || kind_ == TK_STRING8 || kind_ == TK_STRING16 || kind_ == TK_ENUM || kind_ == TK_BITMASK; } void DynamicType::set_name( const std::string& name) { if (descriptor_ != nullptr) { descriptor_->set_name(name); } name_ = name; } size_t DynamicType::get_size() const { switch (kind_) { case TK_BOOLEAN: case TK_BYTE: case TK_CHAR8: return 1; case TK_INT16: case TK_UINT16: case TK_CHAR16: return 2; case TK_INT32: case TK_UINT32: case TK_FLOAT32: return 4; case TK_INT64: case TK_UINT64: case TK_FLOAT64: return 8; case TK_FLOAT128: return 16; case TK_BITMASK: case TK_ENUM: { size_t bits = descriptor_->get_bounds(0); if (bits % 8 == 0) { return bits / 8; } else { return (bits / 8) + 1; } } } logError(DYN_TYPES, "Called get_size() within a non primitive type! This is a program's logic error."); return 0; } } // namespace types } // namespace fastrtps } // namespace eprosima
{'repo_name': 'eProsima/Fast-DDS', 'stars': '564', 'repo_language': 'C++', 'file_name': 'org.eclipse.cdt.codan.core.prefs', 'mime_type': 'text/plain', 'hash': -3403926745616095540, 'source_dataset': 'data'}
/* * 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.tia.v20180226.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class Model extends AbstractModel{ /** * 模型名称 */ @SerializedName("Name") @Expose private String Name; /** * 模型描述 */ @SerializedName("Description") @Expose private String Description; /** * 集群名称 */ @SerializedName("Cluster") @Expose private String Cluster; /** * 模型地址 */ @SerializedName("Model") @Expose private String Model; /** * 运行环境编号 */ @SerializedName("RuntimeVersion") @Expose private String RuntimeVersion; /** * 模型创建时间 */ @SerializedName("CreateTime") @Expose private String CreateTime; /** * 模型运行状态 */ @SerializedName("State") @Expose private String State; /** * 提供服务的url */ @SerializedName("ServingUrl") @Expose private String ServingUrl; /** * 相关消息 */ @SerializedName("Message") @Expose private String Message; /** * 编号 */ @SerializedName("AppId") @Expose private Long AppId; /** * 机型 */ @SerializedName("ServType") @Expose private String ServType; /** * 模型暴露方式 */ @SerializedName("Expose") @Expose private String Expose; /** * 部署副本数量 */ @SerializedName("Replicas") @Expose private Long Replicas; /** * 模型Id */ @SerializedName("Id") @Expose private String Id; /** * 创建任务的Uin */ @SerializedName("Uin") @Expose private String Uin; /** * 模型删除时间,格式为:2006-01-02 15:04:05.999999999 -0700 MST */ @SerializedName("DelTime") @Expose private String DelTime; /** * Get 模型名称 * @return Name 模型名称 */ public String getName() { return this.Name; } /** * Set 模型名称 * @param Name 模型名称 */ public void setName(String Name) { this.Name = Name; } /** * Get 模型描述 * @return Description 模型描述 */ public String getDescription() { return this.Description; } /** * Set 模型描述 * @param Description 模型描述 */ public void setDescription(String Description) { this.Description = Description; } /** * Get 集群名称 * @return Cluster 集群名称 */ public String getCluster() { return this.Cluster; } /** * Set 集群名称 * @param Cluster 集群名称 */ public void setCluster(String Cluster) { this.Cluster = Cluster; } /** * Get 模型地址 * @return Model 模型地址 */ public String getModel() { return this.Model; } /** * Set 模型地址 * @param Model 模型地址 */ public void setModel(String Model) { this.Model = Model; } /** * Get 运行环境编号 * @return RuntimeVersion 运行环境编号 */ public String getRuntimeVersion() { return this.RuntimeVersion; } /** * Set 运行环境编号 * @param RuntimeVersion 运行环境编号 */ public void setRuntimeVersion(String RuntimeVersion) { this.RuntimeVersion = RuntimeVersion; } /** * Get 模型创建时间 * @return CreateTime 模型创建时间 */ public String getCreateTime() { return this.CreateTime; } /** * Set 模型创建时间 * @param CreateTime 模型创建时间 */ public void setCreateTime(String CreateTime) { this.CreateTime = CreateTime; } /** * Get 模型运行状态 * @return State 模型运行状态 */ public String getState() { return this.State; } /** * Set 模型运行状态 * @param State 模型运行状态 */ public void setState(String State) { this.State = State; } /** * Get 提供服务的url * @return ServingUrl 提供服务的url */ public String getServingUrl() { return this.ServingUrl; } /** * Set 提供服务的url * @param ServingUrl 提供服务的url */ public void setServingUrl(String ServingUrl) { this.ServingUrl = ServingUrl; } /** * Get 相关消息 * @return Message 相关消息 */ public String getMessage() { return this.Message; } /** * Set 相关消息 * @param Message 相关消息 */ public void setMessage(String Message) { this.Message = Message; } /** * Get 编号 * @return AppId 编号 */ public Long getAppId() { return this.AppId; } /** * Set 编号 * @param AppId 编号 */ public void setAppId(Long AppId) { this.AppId = AppId; } /** * Get 机型 * @return ServType 机型 */ public String getServType() { return this.ServType; } /** * Set 机型 * @param ServType 机型 */ public void setServType(String ServType) { this.ServType = ServType; } /** * Get 模型暴露方式 * @return Expose 模型暴露方式 */ public String getExpose() { return this.Expose; } /** * Set 模型暴露方式 * @param Expose 模型暴露方式 */ public void setExpose(String Expose) { this.Expose = Expose; } /** * Get 部署副本数量 * @return Replicas 部署副本数量 */ public Long getReplicas() { return this.Replicas; } /** * Set 部署副本数量 * @param Replicas 部署副本数量 */ public void setReplicas(Long Replicas) { this.Replicas = Replicas; } /** * Get 模型Id * @return Id 模型Id */ public String getId() { return this.Id; } /** * Set 模型Id * @param Id 模型Id */ public void setId(String Id) { this.Id = Id; } /** * Get 创建任务的Uin * @return Uin 创建任务的Uin */ public String getUin() { return this.Uin; } /** * Set 创建任务的Uin * @param Uin 创建任务的Uin */ public void setUin(String Uin) { this.Uin = Uin; } /** * Get 模型删除时间,格式为:2006-01-02 15:04:05.999999999 -0700 MST * @return DelTime 模型删除时间,格式为:2006-01-02 15:04:05.999999999 -0700 MST */ public String getDelTime() { return this.DelTime; } /** * Set 模型删除时间,格式为:2006-01-02 15:04:05.999999999 -0700 MST * @param DelTime 模型删除时间,格式为:2006-01-02 15:04:05.999999999 -0700 MST */ public void setDelTime(String DelTime) { this.DelTime = DelTime; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Name", this.Name); this.setParamSimple(map, prefix + "Description", this.Description); this.setParamSimple(map, prefix + "Cluster", this.Cluster); this.setParamSimple(map, prefix + "Model", this.Model); this.setParamSimple(map, prefix + "RuntimeVersion", this.RuntimeVersion); this.setParamSimple(map, prefix + "CreateTime", this.CreateTime); this.setParamSimple(map, prefix + "State", this.State); this.setParamSimple(map, prefix + "ServingUrl", this.ServingUrl); this.setParamSimple(map, prefix + "Message", this.Message); this.setParamSimple(map, prefix + "AppId", this.AppId); this.setParamSimple(map, prefix + "ServType", this.ServType); this.setParamSimple(map, prefix + "Expose", this.Expose); this.setParamSimple(map, prefix + "Replicas", this.Replicas); this.setParamSimple(map, prefix + "Id", this.Id); this.setParamSimple(map, prefix + "Uin", this.Uin); this.setParamSimple(map, prefix + "DelTime", this.DelTime); } }
{'repo_name': 'TencentCloud/tencentcloud-sdk-java', 'stars': '220', 'repo_language': 'Java', 'file_name': 'EvaluationExamples.java', 'mime_type': 'text/x-java', 'hash': -8092960346279739640, 'source_dataset': 'data'}
// // TUTNotificationMessage.m // tutanota // // Created by Tutao GmbH on 17.06.19. // Copyright © 2019 Tutao GmbH. All rights reserved. // #import "TUTMissedNotification.h" #import "TUTAlarmNotification.h" #import "../Utils/Swiftier.h" #import "../Utils/PSPDFFastEnumeration.h" @implementation TUTMissedNotification - (TUTMissedNotification *)initWithalarmNotifications:(NSArray<TUTAlarmNotification *> *)alarmNotifications lastProcessedNotificationId:(NSString *)lastProcessedNotificationId { self = [super init]; _alarmNotifications = alarmNotifications; _lastProcessedNotificationId = lastProcessedNotificationId; return self; } +(TUTMissedNotification *)fromJSON:(NSDictionary *)jsonDict{ NSArray<NSDictionary *> *notificationsJson = jsonDict[@"alarmNotifications"]; NSMutableArray<TUTAlarmNotification *> *notifications = [NSMutableArray new]; foreach(notification, notificationsJson) { [notifications addObject:[TUTAlarmNotification fromJSON:notification]]; } NSString *lastProcessedNotificationId = jsonDict[@"lastProcessedNotificationId"]; return [[TUTMissedNotification alloc] initWithalarmNotifications:notifications lastProcessedNotificationId:lastProcessedNotificationId]; } @end
{'repo_name': 'tutao/tutanota', 'stars': '3382', 'repo_language': 'JavaScript', 'file_name': 'notifications.md', 'mime_type': 'text/plain', 'hash': 3352379160710285359, 'source_dataset': 'data'}
/* Copyright 2014 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package gcp_credentials import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "strings" "testing" "k8s.io/kubernetes/pkg/credentialprovider" ) const email = "foo@bar.com" // From oauth2/jwt_test.go var ( dummyPrivateKey = `-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK 1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9 /E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt 3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn 2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3 nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK 6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf 5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1 M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y 1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw 5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84 OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ 5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg== -----END RSA PRIVATE KEY-----` jsonKey = fmt.Sprintf(`{"private_key":"%[1]s", "client_email":"%[2]s"}`, strings.Replace(dummyPrivateKey, "\n", "\\n", -1), email) ) func TestJwtProvider(t *testing.T) { token := "asdhflkjsdfkjhsdf" // Modeled after oauth2/jwt_test.go ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(fmt.Sprintf(`{ "access_token": "%[1]s", "scope": "user", "token_type": "bearer", "expires_in": 3600 }`, token))) })) defer ts.Close() file, err := ioutil.TempFile(os.TempDir(), "temp") if err != nil { t.Fatalf("Error creating temp file: %v", err) } filename := file.Name() _, err = file.WriteString(jsonKey) if err != nil { t.Fatalf("Error writing temp file: %v", err) } provider := &jwtProvider{ path: &filename, tokenUrl: ts.URL, } if !provider.Enabled() { t.Fatalf("Provider is unexpectedly disabled") } keyring := &credentialprovider.BasicDockerKeyring{} keyring.Add(provider.Provide()) // Verify that we get the expected username/password combo for // a gcr.io image name. registryUrl := "gcr.io/foo/bar" creds, ok := keyring.Lookup(registryUrl) if !ok { t.Errorf("Didn't find expected URL: %s", registryUrl) return } if len(creds) > 1 { t.Errorf("Got more hits than expected: %s", creds) } val := creds[0] if "_token" != val.Username { t.Errorf("Unexpected username value, want: _token, got: %s", val.Username) } if token != val.Password { t.Errorf("Unexpected password value, want: %s, got: %s", token, val.Password) } if email != val.Email { t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email) } }
{'repo_name': 'fabric8io/configmapcontroller', 'stars': '196', 'repo_language': 'Go', 'file_name': 'controller.go', 'mime_type': 'text/plain', 'hash': -2901861933243163046, 'source_dataset': 'data'}
import 'package:flutter/material.dart'; import 'package:flutter_i18n/flutter_i18n.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_web_browser/flutter_web_browser.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; import '../../repositories/index.dart'; import '../widgets/index.dart'; /// This screen loads the [CHANGELOG.md] file from GitHub, /// and displays its content, using the Markdown plugin. class ChangelogScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Consumer<ChangelogRepository>( builder: (context, model, child) => ReloadablePage<ChangelogRepository>( title: FlutterI18n.translate(context, 'about.version.changelog'), body: Markdown( data: model.changelog ?? '', onTapLink: (url) => FlutterWebBrowser.openWebPage( url: url, androidToolbarColor: Theme.of(context).primaryColor, ), styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith( blockSpacing: 10, h2: GoogleFonts.rubikTextTheme(Theme.of(context).textTheme) .subtitle1 .copyWith( fontWeight: FontWeight.bold, ), p: GoogleFonts.rubikTextTheme(Theme.of(context).textTheme) .bodyText2 .copyWith( color: Theme.of(context).textTheme.caption.color, ), ), ), ), ); } }
{'repo_name': 'jesusrp98/spacex-go', 'stars': '454', 'repo_language': 'Dart', 'file_name': 'launchpad.dart', 'mime_type': 'text/x-c++', 'hash': -356202213710554437, 'source_dataset': 'data'}
/* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing; /** * Constants used to control the window-closing operation. * The <code>setDefaultCloseOperation</code> and * <code>getDefaultCloseOperation</code> methods * provided by <code>JFrame</code>, * <code>JInternalFrame</code>, and * <code>JDialog</code> * use these constants. * For examples of setting the default window-closing operation, see * <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/frame.html#windowevents">Responding to Window-Closing Events</a>, * a section in <em>The Java Tutorial</em>. * @see JFrame#setDefaultCloseOperation(int) * @see JDialog#setDefaultCloseOperation(int) * @see JInternalFrame#setDefaultCloseOperation(int) * * * @author Amy Fowler * @since 1.2 */ public interface WindowConstants { /** * The do-nothing default window close operation. */ public static final int DO_NOTHING_ON_CLOSE = 0; /** * The hide-window default window close operation */ public static final int HIDE_ON_CLOSE = 1; /** * The dispose-window default window close operation. * <p> * <b>Note</b>: When the last displayable window * within the Java virtual machine (VM) is disposed of, the VM may * terminate. See <a href="../../java/awt/doc-files/AWTThreadIssues.html"> * AWT Threading Issues</a> for more information. * @see java.awt.Window#dispose() * @see JInternalFrame#dispose() */ public static final int DISPOSE_ON_CLOSE = 2; /** * The exit application default window close operation. Attempting * to set this on Windows that support this, such as * <code>JFrame</code>, may throw a <code>SecurityException</code> based * on the <code>SecurityManager</code>. * It is recommended you only use this in an application. * * @since 1.4 * @see JFrame#setDefaultCloseOperation */ public static final int EXIT_ON_CLOSE = 3; }
{'repo_name': 'kangjianwei/LearningJDK', 'stars': '587', 'repo_language': 'Java', 'file_name': 'PKCS11Exception.java', 'mime_type': 'text/html', 'hash': 4868764317119396759, 'source_dataset': 'data'}
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_STEP_STATS_COLLECTOR_H_ #define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_STEP_STATS_COLLECTOR_H_ #include <unordered_map> #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { class CostModelManager; class Graph; class NodeExecStats; class StepStats; // StepStatsCollector manages the collection of a StepStats object. // The StepStats object holds multiple DeviceStats. // Each DeviceStats object holds multiple NodeExecStats. class StepStatsCollector { public: explicit StepStatsCollector(StepStats* ss); // BuildCostModel builds or updates a CostModel managed by cost_model_manager, // using the currently collected DeviceStats associated with the devices in // device_map. void BuildCostModel( CostModelManager* cost_model_manager, const std::unordered_map<string, const Graph*>& device_map); // Save saves nt to the DeviceStats object associated with device. void Save(const string& device, NodeExecStats* nt); // Swap replaces the current step stats with ss. void Swap(StepStats* ss); private: // TODO(suharshs): Make this configurable if its not possible to find a value // that works for all cases. const uint64 kMaxCollectedNodes = 1 << 20; mutex mu_; StepStats* step_stats_ GUARDED_BY(mu_); uint64 collectedNodes GUARDED_BY(mu_) = 0; }; } // namespace tensorflow #endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_STEP_STATS_COLLECTOR_H_
{'repo_name': 'ryfeus/lambda-packs', 'stars': '940', 'repo_language': 'Python', 'file_name': 'six.py', 'mime_type': 'text/x-python', 'hash': 6933506131813158553, 'source_dataset': 'data'}
<?php namespace Kunstmaan\SeoBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; /** * KunstmaanSeoBundle */ class KunstmaanSeoBundle extends Bundle { }
{'repo_name': 'Kunstmaan/KunstmaanBundlesCMS', 'stars': '334', 'repo_language': 'PHP', 'file_name': 'build-gc-skeleton.js', 'mime_type': 'text/html', 'hash': 2046309027344547149, 'source_dataset': 'data'}
/* * Copyright (c) 2014 - 2019 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 com.github.ferstl.depgraph; import java.io.File; import java.nio.file.FileSystems; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import io.takari.maven.testing.TestResources; import io.takari.maven.testing.executor.MavenExecutionResult; import io.takari.maven.testing.executor.MavenRuntime; import io.takari.maven.testing.executor.MavenVersions; import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner; import static com.github.ferstl.depgraph.MavenVersion.MAX_VERSION; import static com.github.ferstl.depgraph.MavenVersion.MIN_VERSION; import static io.takari.maven.testing.TestResources.assertFileContents; import static io.takari.maven.testing.TestResources.assertFilesPresent; @RunWith(MavenJUnitTestRunner.class) @MavenVersions({MAX_VERSION, MIN_VERSION}) public class MergeOptionsIntegrationTest { @Rule public final TestResources resources = new TestResources(); private final MavenRuntime mavenRuntime; public MergeOptionsIntegrationTest(MavenRuntime.MavenRuntimeBuilder builder) throws Exception { this.mavenRuntime = builder.build(); } @Before public void before() { // Workaround for https://github.com/takari/takari-plugin-testing-project/issues/14 FileSystems.getDefault(); } @Test public void graphNoMerge() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:graph"); result.assertErrorFreeLog(); assertFilesPresent( basedir, "module-1/target/dependency-graph.dot", "module-2/target/dependency-graph.dot", "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/graph_module-1_no-merge.dot", "module-1/target/dependency-graph.dot"); } @Test public void aggregateNoMerge() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate_no-merge.dot", "target/dependency-graph.dot"); } @Test public void aggregateByGroupIdNoMerge() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate-by-groupid"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate-by-groupid_no-merge.dot", "target/dependency-graph.dot"); } @Test public void aggregateMergeScopes() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeScopes") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate_mergeScopes.dot", "target/dependency-graph.dot"); } @Test public void aggregateByGroupIdMergeScopes() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeScopes") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate-by-groupid"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate-by-groupid_mergeScopes.dot", "target/dependency-graph.dot"); } @Test public void graphMergeClassifiers() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeClassifiers") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:graph"); result.assertErrorFreeLog(); assertFilesPresent( basedir, "module-1/target/dependency-graph.dot", "module-2/target/dependency-graph.dot", "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/graph_module-1_mergeClassifiers.dot", "module-1/target/dependency-graph.dot"); } @Test public void graphMergeTypes() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeTypes") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:graph"); result.assertErrorFreeLog(); assertFilesPresent( basedir, "module-1/target/dependency-graph.dot", "module-2/target/dependency-graph.dot", "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/graph_module-1_mergeTypes.dot", "module-1/target/dependency-graph.dot"); } @Test public void graphMergeTypesAndClassifiers() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeTypes") .withCliOption("-DmergeClassifiers") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:graph"); result.assertErrorFreeLog(); assertFilesPresent( basedir, "module-1/target/dependency-graph.dot", "module-2/target/dependency-graph.dot", "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/graph_module-1_mergeTypes-mergeClassifiers.dot", "module-1/target/dependency-graph.dot"); } @Test public void aggregateMergeClassifiers() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeClassifiers") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate_mergeClassifiers.dot", "target/dependency-graph.dot"); } @Test public void aggregateMergeTypes() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeTypes") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate_mergeTypes.dot", "target/dependency-graph.dot"); } @Test public void aggregateMergeTypesAndClassifiers() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeTypes") .withCliOption("-DmergeClassifiers") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate_mergeTypes-mergeClassifiers.dot", "target/dependency-graph.dot"); } @Test public void aggregateMergeTypesAndClassifiersAndScopes() throws Exception { File basedir = this.resources.getBasedir("merge-test"); MavenExecutionResult result = this.mavenRuntime .forProject(basedir) .withCliOption("-DmergeTypes") .withCliOption("-DmergeClassifiers") .withCliOption("-DmergeScopes") // Maven 3.1 does not resolve the module-2 ZIP dependency from the reactor. That's why we need to execute "install". .execute("clean", "install", "depgraph:aggregate"); result.assertErrorFreeLog(); assertFilesPresent(basedir, "target/dependency-graph.dot"); assertFileContents(basedir, "expectations/aggregate_mergeTypes-mergeClassifiers-mergeScopes.dot", "target/dependency-graph.dot"); } }
{'repo_name': 'ferstl/depgraph-maven-plugin', 'stars': '259', 'repo_language': 'Java', 'file_name': 'header.txt', 'mime_type': 'text/plain', 'hash': 4212041539119074729, 'source_dataset': 'data'}
<?php /** * Created by PhpStorm. * User: yp-tc-7176 * Date: 17/7/16 * Time: 20:28 */ namespace app\common\modules\yop\sdk\Util; use app\common\modules\yop\sdk\Util\StringBuilder; abstract class HttpUtils { /** * Normalize a string for use in url path. The algorithm is: * <p> * <p> * <ol> * <li>Normalize the string</li> * <li>replace all "%2F" with "/"</li> * <li>replace all "//" with "/%2F"</li> * </ol> * <p> * <p> * object key can contain arbitrary characters, which may result double slash in the url path. Apache http * client will replace "//" in the path with a single '/', which makes the object key incorrect. Thus we replace * "//" with "/%2F" here. * * @param path the path string to normalize. * @return the normalized path string. * @see #normalize(String) */ public static function normalizePath($path) { return str_replace("%2F", "/",HttpUtils::normalize($path)); } /** * @param $value * @return string */ public static function normalize($value) { return rawurlencode($value); } public static function startsWith($haystack, $needle) { // search backwards starting from haystack length characters from the end return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE; } public static function endsWith($haystack, $needle) { // search forward starting from end minus needle length characters return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE); } /** * @param $path * @return string */ public static function getCanonicalURIPath($path) { if ($path == null) { return "/"; } else if (HttpUtils::startsWith($path,'/')) { return HttpUtils::normalizePath($path); } else { return "/" + HttpUtils::normalizePath($path); } } }
{'repo_name': 'sulianapp-com/sulianapp', 'stars': '192', 'repo_language': 'PHP', 'file_name': 'autoload.php', 'mime_type': 'text/x-php', 'hash': 8698407363156674783, 'source_dataset': 'data'}
#region License // Copyright (c) 2013, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This file is part of the ClearCanvas RIS/PACS open source project. // // The ClearCanvas RIS/PACS open source project 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. // // The ClearCanvas RIS/PACS open source project 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 // the ClearCanvas RIS/PACS open source project. If not, see // <http://www.gnu.org/licenses/>. #endregion using ClearCanvas.Enterprise.Core; namespace ClearCanvas.Healthcare { public class RegistrationWorklistItemSearchCriteria : WorklistItemSearchCriteria { } }
{'repo_name': 'ClearCanvas/ClearCanvas', 'stars': '318', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -7457988351431658288, 'source_dataset': 'data'}
/* * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq.impl; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.jooq.DiagnosticsContext; import org.jooq.tools.JooqLogger; /** * @author Lukas Eder */ final class DefaultDiagnosticsContext implements DiagnosticsContext { private static final JooqLogger log = JooqLogger.getLogger(DefaultDiagnosticsContext.class); ResultSet resultSet; DiagnosticsResultSet resultSetWrapper; boolean resultSetClosing; int resultSetFetchedColumnCount; int resultSetConsumedColumnCount; int resultSetFetchedRows; int resultSetConsumedRows; final String actualStatement; final String normalisedStatement; final Set<String> duplicateStatements; final List<String> repeatedStatements; boolean resultSetUnnecessaryWasNullCall; boolean resultSetMissingWasNullCall; int resultSetColumnIndex; DefaultDiagnosticsContext(String actualStatement) { this(actualStatement, actualStatement, Collections.singleton(actualStatement), Collections.singletonList(actualStatement)); } DefaultDiagnosticsContext(String actualStatement, String normalisedStatement, Set<String> duplicateStatements, List<String> repeatedStatements) { this.actualStatement = actualStatement; this.normalisedStatement = normalisedStatement; this.duplicateStatements = duplicateStatements == null ? Collections.<String>emptySet() : duplicateStatements; this.repeatedStatements = repeatedStatements == null ? Collections.<String>emptyList() : repeatedStatements; } @Override public final ResultSet resultSet() { return resultSet; } @Override public final int resultSetConsumedRows() { return resultSet == null ? -1 : resultSetConsumedRows; } @Override public final int resultSetFetchedRows() { if (resultSet == null) return -1; try { if (resultSetClosing || resultSet.getType() != ResultSet.TYPE_FORWARD_ONLY) { while (resultSet.next()) resultSetFetchedRows++; resultSet.absolute(resultSetConsumedRows); } } catch (SQLException ignore) {} return resultSetFetchedRows; } @Override public final int resultSetConsumedColumnCount() { return resultSet == null ? -1 : resultSetConsumedColumnCount; } @Override public final int resultSetFetchedColumnCount() { return resultSet == null ? -1 : resultSetFetchedColumnCount; } @Override public final List<String> resultSetConsumedColumnNames() { return resultSetColumnNames(false); } @Override public final List<String> resultSetFetchedColumnNames() { return resultSetColumnNames(true); } private final List<String> resultSetColumnNames(boolean fetched) { List<String> result = new ArrayList<>(); if (resultSet != null) { try { ResultSetMetaData meta = resultSet.getMetaData(); for (int i = 1; i <= meta.getColumnCount(); i++) if (fetched || resultSetWrapper.read.get(i - 1)) result.add(meta.getColumnLabel(i)); } catch (SQLException e) { log.info(e); } } return Collections.unmodifiableList(result); } @Override public final boolean resultSetUnnecessaryWasNullCall() { return resultSet == null ? false : resultSetUnnecessaryWasNullCall; } @Override public final boolean resultSetMissingWasNullCall() { return resultSet == null ? false : resultSetMissingWasNullCall; } @Override public final int resultSetColumnIndex() { return resultSet == null ? 0 : resultSetColumnIndex; } @Override public final String actualStatement() { return actualStatement; } @Override public final String normalisedStatement() { return normalisedStatement; } @Override public final Set<String> duplicateStatements() { return Collections.unmodifiableSet(duplicateStatements); } @Override public final List<String> repeatedStatements() { return Collections.unmodifiableList(repeatedStatements); } }
{'repo_name': 'jOOQ/jOOQ', 'stars': '3902', 'repo_language': 'TSQL', 'file_name': 'DDLDatabase.java', 'mime_type': 'text/x-java', 'hash': -3487642878471255719, 'source_dataset': 'data'}
#ifndef _ASM_POWERPC_PGALLOC_32_H #define _ASM_POWERPC_PGALLOC_32_H #include <linux/threads.h> /* For 32-bit, all levels of page tables are just drawn from get_free_page() */ #define MAX_PGTABLE_INDEX_SIZE 0 extern void __bad_pte(pmd_t *pmd); extern pgd_t *pgd_alloc(struct mm_struct *mm); extern void pgd_free(struct mm_struct *mm, pgd_t *pgd); /* * We don't have any real pmd's, and this code never triggers because * the pgd will always be present.. */ /* #define pmd_alloc_one(mm,address) ({ BUG(); ((pmd_t *)2); }) */ #define pmd_free(mm, x) do { } while (0) #define __pmd_free_tlb(tlb,x,a) do { } while (0) /* #define pgd_populate(mm, pmd, pte) BUG() */ #ifndef CONFIG_BOOKE #define pmd_populate_kernel(mm, pmd, pte) \ (pmd_val(*(pmd)) = __pa(pte) | _PMD_PRESENT) #define pmd_populate(mm, pmd, pte) \ (pmd_val(*(pmd)) = (page_to_pfn(pte) << PAGE_SHIFT) | _PMD_PRESENT) #define pmd_pgtable(pmd) pmd_page(pmd) #else #define pmd_populate_kernel(mm, pmd, pte) \ (pmd_val(*(pmd)) = (unsigned long)pte | _PMD_PRESENT) #define pmd_populate(mm, pmd, pte) \ (pmd_val(*(pmd)) = (unsigned long)lowmem_page_address(pte) | _PMD_PRESENT) #define pmd_pgtable(pmd) pmd_page(pmd) #endif extern pte_t *pte_alloc_one_kernel(struct mm_struct *mm, unsigned long addr); extern pgtable_t pte_alloc_one(struct mm_struct *mm, unsigned long addr); static inline void pgtable_free(void *table, unsigned index_size) { BUG_ON(index_size); /* 32-bit doesn't use this */ free_page((unsigned long)table); } #define check_pgt_cache() do { } while (0) #endif /* _ASM_POWERPC_PGALLOC_32_H */
{'repo_name': 'CyanogenMod/android_kernel_oneplus_msm8974', 'stars': '129', 'repo_language': 'C', 'file_name': 'usb.h', 'mime_type': 'text/x-c', 'hash': -7812459506430871225, 'source_dataset': 'data'}
using System; using System.Collections.Generic; namespace Eto.Serialization.Json { public class NamespaceManager { readonly Dictionary<string, NamespaceInfo> namespaces = new Dictionary<string, NamespaceInfo>(); public NamespaceInfo DefaultNamespace { get; set; } public IDictionary<string, NamespaceInfo> Namespaces { get { return namespaces;} } public NamespaceInfo LookupNamespace (string prefix) { if (string.IsNullOrEmpty (prefix)) return DefaultNamespace; NamespaceInfo val; return namespaces.TryGetValue(prefix, out val) ? val : null; } public Type LookupType (string typeName) { var prefixIndex = typeName.IndexOf (':'); NamespaceInfo ns; if (prefixIndex > 0) { var prefix = typeName.Substring (0, prefixIndex); typeName = typeName.Substring (prefixIndex + 1); ns = LookupNamespace(prefix); } else ns = DefaultNamespace; return ns != null ? ns.FindType(typeName) : null; } } }
{'repo_name': 'picoe/Eto', 'stars': '2541', 'repo_language': 'C#', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': -7714743053044926451, 'source_dataset': 'data'}
# Simulation Quality and Stability Tips ## Constraint Stabilization If you are observing ununsual oscillations, bouncing, or outright explosions, constraints are likely related. Most constraint-related stability issues take one of two forms: 1. Failure to completely propagate forces through the constraint graph. 2. Excessive constraint stiffness. Incomplete force propagation usually manifests as bouncing or mild oscillation. This is often observed in tall stacks of bodies. With insufficient iterations or timesteps, stacks can start to bounce and wiggle a bit. Generally, if you zoom in, any local pair of bodies in the stack is behaving reasonably, but tiny errors accumulate and make the whole the dance. In other words, the solver can't converge to a solution for all the constraints at once. In this case, increasing `Simulation.Solver.IterationCount` or setting it to a higher value in `Simulation.Create` usually helps. An example of what it looks like when the solver needs more iterations: ![bounceybounce](images/lowiterationcount.gif) One notable pathological case for the solver is high mass ratios. Very heavy objects rigidly depending on very light objects can make it nearly impossible for the solver to converge in a reasonable number of velocity iterations. One common example of this is a wrecking ball at the end of a rope composed of a bunch linked bodies. With constraint stiffness configured high enough to hold the wrecking ball, it's unlikely that a 60hz solver update rate and 8 velocity iterations will be sufficient to keep things stable at a 100:1 mass ratio. There are ways around this issue, though. Reducing lever arms, adjusting inertias, and adding more paths for the solver to propagate impulses through are useful tricks that can stabilize even some fairly extreme cases. Check out the [RopeStabilityDemo](../Demos/Demos/RopeStabilityDemo.cs) for details. The second class of failure, excessive stiffness, is more difficult to hack away. If you configure a constraint with a frequency of 120hz and your simulation is running at 60hz, the integrator is going to have trouble representing the resulting motion. It won't *always* explode, but if you throw a bunch of 240hz constraints together at a 60hz solver rate, bad things are likely. If you can, avoid using a constraint frequency greater than half of your solver update rate. That is, if the solver is running at 60hz, stick to 30hz or below for your constraints' spring settings. Sometimes, though, you can't use tricks or hacks (as admirable as they are) to stabilize a simulation, or you just want very stiff and stable response. Sometimes you don't have enough control over the simulation to add specific countermeasures- user generated content is rarely simulation friendly. At this point, the solver just needs to run more frequently to compensate. The obvious way to increase the solver's execution rate is to call `Simulation.Timestep` more frequently with a smaller `dt` parameter. If you can afford it, this is the highest quality option since it also performs collision detection more frequently. If you're only concerned about solver stability, then you can instead use the `SubsteppingTimestepper` or another custom `ITimestepper` that works similarly. When calling `Simulation.Create`, pass the SubsteppingTimestepper with the desired number of substeps. For example, if the SubsteppingTimestepper uses 4 substeps and Simulation.Timestep is called at a rate of 60hz, then the solver and integrator will actually run at 240hz. Notably, because increasing the update rate is such a powerful stabilizer, you can usually drop the number of solver velocity iterations to save some simulation time. Using higher update rates can enable the simulation of otherwise impossible mass ratios, like 1000:1, even with fairly low velocity iterations. Here's a rope connected by 240hz frequency constraints with a 1000:1 mass ratio wrecking ball at the end, showing how the number of substeps affects quality: ![](images/massratiosubstepping.gif) For more examples of substepping, check out the [SubsteppingDemo](../Demos/Demos/SubsteppingDemo.cs). So, if you're encountering constraint instability, here are some general guidelines for debugging: 1. First, try increasing the update rate to a really high value (600hz or more). If the problem goes away, then it's probably related to the difficulty of the simulation and a lack of convergence and not to a configuration error. 2. Drop back down to a normal update rate and increase the solver iteration count. If going up to 10 or 15 solver iterations fixes it, then it was likely just a mild convergence failure. If you can't identify any issues in the configuration that would make convergence more difficult than it needs to be (and there aren't any tricks available like the rope stuff described above), then using more solver iterations might just be required. 3. If you need way more solver iterations- 30, 50, 100, or even 10000 isn't fixing it- then a higher update is likely required. This is especially true if you are observing constraint 'explosions' where bodies start flying all over the place. Try using the `SubsteppingTimestepper` and gradually increase the number of substeps until the simulation becomes stable. To preserve performance, try also dropping the number of solver velocity iterations as you increase the substeps. Using more than 4 velocity iterations with 4+ substeps is often pointless. 4. If using a substepping timestepper does not fix the problem but increasing full simulation update rate does, it's possible that collision detection requires the extra temporal resolution. This is pretty rare and may imply that the speculative margins surrounding shapes need to be larger. Some general guidelines: 1. While many simple simulations can work fine with only 1 solver iteration, using a minimum of 2 is recommended for most simulations. Simulations with greater degrees of complexity- articulated robots, ragdolls, stacks- will often need more. (Unless you're using a high solver update rate!) 2. The "mass ratios" problem: avoid making heavy objects depend on light objects. A tiny box can sit on top of a tank without any issues at all, but a tank would squish a tiny box. Larger mass ratios yield larger stability problems. 3. If constraints are taking too many iterations to converge and the design allows it, try softening the constraints. A little bit of softness can significantly stabilize a constraint system and avoid the need for higher update rates. 4. Avoid configuring constraints to 'fight' each other. Opposing constraints tend to require more iterations to converge, and if they're extremely rigid, it can require shorter timesteps or substepping. 5. When tuning the `SpringSettings.Frequency` of constraints, prefer values smaller than `0.5 / timeStepDuration`. Higher values increase the risk of instability. 6. If your simulation requires a lot of solver velocity iterations to be stable, try using substepping with lower velocity iteration counts. It might end up more stable *and* faster! ## Contact Generation While nonzero speculative margins are required for stable contact, overly large margins can sometimes cause 'ghost' contacts when objects are moving quickly relative to each other. It might look like one object is bouncing off the air a foot away from the other shape. To avoid this, use a smaller speculative margin and consider explicitly enabling continuous collision detection for the shape. Prefer simpler shapes. In particular, avoid highly complex convex hulls with a bunch of faces separated by only a few degrees. The solver likes temporally coherent contacts, and excess complexity can cause the set of generated contacts to vary significantly with small rotations. Also, complicated hulls are slower!
{'repo_name': 'bepu/bepuphysics2', 'stars': '663', 'repo_language': 'C#', 'file_name': 'RaceTrack.cs', 'mime_type': 'text/plain', 'hash': 5365045371990971216, 'source_dataset': 'data'}
/** * @file rtp/yuri_decoders.h * @author Martin Pulec <pulec@cesnet.cz> */ /* * Copyright (c) 2014 CESNET, z. s. p. o. * * Redistribution and use in source and binary forms, with or without * modification, is 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 CESNET 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 AUTHORS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESSED 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. */ struct coded_data; #ifdef __cplusplus #include "yuri/log/Log.h" #include "yuri/core/frame/Frame.h" struct yuri_decoder_data { yuri_decoder_data(yuri::log::Log &log_) : log(log_) {} yuri::log::Log &log; yuri::core::pFrame yuri_frame; }; #endif #ifdef __cplusplus extern "C" { #endif // __cplusplus int decode_yuri_frame(struct coded_data *received_data, void *decoder_data); #ifdef __cplusplus } #endif // __cplusplus
{'repo_name': 'CESNET/UltraGrid', 'stars': '203', 'repo_language': 'C', 'file_name': 'uv', 'mime_type': 'text/plain', 'hash': 1941885959063439416, 'source_dataset': 'data'}
<?xml version='1.0' encoding='utf-8'?> <fluidity_options> <simulation_name> <string_value lines="1">MMS_E_cv</string_value> </simulation_name> <problem_type> <string_value lines="1">fluids</string_value> </problem_type> <geometry> <dimension> <integer_value rank="0">2</integer_value> </dimension> <mesh name="CoordinateMesh"> <from_file file_name="MMS_E"> <format name="gmsh"/> <stat> <include_in_stat/> </stat> </from_file> </mesh> <mesh name="VelocityMesh"> <from_mesh> <mesh name="CoordinateMesh"/> <stat> <exclude_from_stat/> </stat> </from_mesh> </mesh> <mesh name="PressureMesh"> <from_mesh> <mesh name="CoordinateMesh"/> <stat> <exclude_from_stat/> </stat> </from_mesh> </mesh> <quadrature> <degree> <integer_value rank="0">5</integer_value> </degree> <controlvolume_surface_degree> <integer_value rank="0">5</integer_value> </controlvolume_surface_degree> </quadrature> </geometry> <io> <dump_format> <string_value>vtk</string_value> </dump_format> <dump_period> <constant> <real_value rank="0">1000.0</real_value> </constant> </dump_period> <output_mesh name="VelocityMesh"/> <stat/> </io> <timestepping> <current_time> <real_value rank="0">0.0</real_value> </current_time> <timestep> <real_value rank="0">0.00052280323880171751</real_value> <comment>0.00052280323880171751 gives a cv cfl number of 0.5</comment> </timestep> <finish_time> <real_value rank="0">5.0</real_value> </finish_time> <steady_state> <tolerance> <real_value rank="0">1.E-10</real_value> <infinity_norm/> </tolerance> <acceleration_form/> </steady_state> </timestepping> <material_phase name="Burgers"> <vector_field rank="1" name="Velocity"> <prescribed> <mesh name="VelocityMesh"/> <value name="WholeMesh"> <python> <string_value type="code" language="python" lines="20">def val(XX, t): from math import sin,cos x = XX[0]; y = XX[1]; x2 = x*x; y2 = y*y; u = sin(5*(x2+y2)); v = cos(3*(x2-y2)); return (u, v)</string_value> </python> </value> <output/> <stat> <include_in_stat/> </stat> <detectors> <exclude_from_detectors/> </detectors> <particles> <exclude_from_particles/> </particles> </prescribed> </vector_field> <scalar_field rank="0" name="NumericalSolution"> <prognostic> <mesh name="VelocityMesh"/> <equation name="AdvectionDiffusion"/> <spatial_discretisation> <control_volumes> <mass_terms> <exclude_mass_terms/> </mass_terms> <face_value name="FirstOrderUpwind"/> <diffusion_scheme name="BassiRebay"/> </control_volumes> <conservative_advection> <real_value rank="0">0.0</real_value> </conservative_advection> </spatial_discretisation> <temporal_discretisation> <theta> <real_value rank="0">1.0</real_value> </theta> </temporal_discretisation> <solver> <iterative_method name="gmres"> <restart> <integer_value rank="0">30</integer_value> </restart> </iterative_method> <preconditioner name="sor"/> <relative_error> <real_value rank="0">1.E-10</real_value> </relative_error> <max_iterations> <integer_value rank="0">350</integer_value> </max_iterations> <never_ignore_solver_failures/> <diagnostics> <monitors/> </diagnostics> </solver> <initial_condition name="WholeMesh"> <constant> <real_value rank="0">0.0</real_value> </constant> </initial_condition> <boundary_conditions name="sides"> <surface_ids> <integer_value rank="1" shape="4">7 8 9 10</integer_value> </surface_ids> <type name="dirichlet"> <apply_weakly/> <python> <string_value type="code" language="python" lines="20">def val(XX, t): from math import sin,cos,sqrt omega = 0.0; x = XX[0]; y = XX[1]; x4 = x*x*x*x; y2 = y*y; u = sin(25*x*y+omega*t)-2*y/(sqrt(x)); return u</string_value> </python> </type> </boundary_conditions> <scalar_field name="Source" rank="0"> <prescribed> <value name="WholeMesh"> <python> <string_value type="code" language="python" lines="20">def val(XX, t): from math import sin,cos,sqrt omega = 0.0; x = XX[0]; y = XX[1]; x2 = x*x; y2 = y*y; xp5 = sqrt(x) x1p5 = xp5*x S = (25*y*cos(25*x*y) + 1.0*y/x1p5)*sin(5*(y2 + x2)) + (25*x*cos(25*x*y) - 2/xp5)*cos(3*(x2 - y2)); return S</string_value> </python> </value> <output/> <stat/> <detectors> <exclude_from_detectors/> </detectors> <particles> <exclude_from_particles/> </particles> </prescribed> </scalar_field> <output> <include_previous_time_step/> </output> <stat/> <convergence> <include_in_convergence/> </convergence> <detectors> <include_in_detectors/> </detectors> <particles> <exclude_from_particles/> </particles> <steady_state> <include_in_steady_state/> </steady_state> <consistent_interpolation/> </prognostic> </scalar_field> <scalar_field rank="0" name="AnalyticalSolution"> <prescribed> <mesh name="VelocityMesh"/> <value name="WholeMesh"> <python> <string_value type="code" language="python" lines="20">def val(XX, t): from math import sin,cos,sqrt omega = 0.0; x = XX[0]; y = XX[1]; u = sin(25*x*y + omega*t) - 2*y/(sqrt(x)); return u</string_value> </python> </value> <output/> <stat/> <detectors> <exclude_from_detectors/> </detectors> <particles> <exclude_from_particles/> </particles> </prescribed> </scalar_field> <scalar_field rank="0" name="ControlVolumeCFLNumber"> <diagnostic> <algorithm name="Internal" material_phase_support="multiple"/> <mesh name="VelocityMesh"/> <output/> <stat/> <convergence> <include_in_convergence/> </convergence> <detectors> <include_in_detectors/> </detectors> <particles> <exclude_from_particles/> </particles> <steady_state> <include_in_steady_state/> </steady_state> </diagnostic> </scalar_field> <scalar_field rank="0" name="AbsoluteDifference"> <diagnostic field_name_a="AnalyticalSolution" field_name_b="NumericalSolution"> <algorithm name="Internal" material_phase_support="multiple"/> <mesh name="VelocityMesh"/> <output/> <stat> <include_cv_stats/> </stat> <convergence> <include_in_convergence/> </convergence> <detectors> <include_in_detectors/> </detectors> <particles> <exclude_from_particles/> </particles> <steady_state> <include_in_steady_state/> </steady_state> </diagnostic> </scalar_field> </material_phase> </fluidity_options>
{'repo_name': 'FluidityProject/fluidity', 'stars': '213', 'repo_language': 'Fortran', 'file_name': 'test_fluxes_reader_wrapper.F90', 'mime_type': 'text/plain', 'hash': -3370476903014110738, 'source_dataset': 'data'}
/* * Copyright 2010 Tilera Corporation. All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, version 2. * * 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for * more details. */ #ifndef _ASM_TILE_SIGCONTEXT_H #define _ASM_TILE_SIGCONTEXT_H #include <arch/abi.h> /* * struct sigcontext has the same shape as struct pt_regs, * but is simplified since we know the fault is from userspace. */ struct sigcontext { uint_reg_t gregs[53]; /* General-purpose registers. */ uint_reg_t tp; /* Aliases gregs[TREG_TP]. */ uint_reg_t sp; /* Aliases gregs[TREG_SP]. */ uint_reg_t lr; /* Aliases gregs[TREG_LR]. */ uint_reg_t pc; /* Program counter. */ uint_reg_t ics; /* In Interrupt Critical Section? */ uint_reg_t faultnum; /* Fault number. */ uint_reg_t pad[5]; }; #endif /* _ASM_TILE_SIGCONTEXT_H */
{'repo_name': 'RMerl/asuswrt-merlin.ng', 'stars': '2126', 'repo_language': 'None', 'file_name': 'cpu_vect.h', 'mime_type': 'text/x-c', 'hash': -6538868522435694995, 'source_dataset': 'data'}
#include "insert.h" #include <cad/primitive/insert.h> using namespace lc; using namespace builder; InsertBuilder::InsertBuilder() : _displayBlock(nullptr) { } bool InsertBuilder::checkValues(bool throwExceptions) const { if (!throwExceptions) { return CADEntityBuilder::checkValues(throwExceptions) && _displayBlock != nullptr && _document != nullptr; } else { if (_displayBlock == nullptr) { throw std::runtime_error("Display block cannot be NULL"); } if (_document == nullptr) { throw std::runtime_error("Document cannot be NULL"); } return CADEntityBuilder::checkValues(throwExceptions); } } const meta::Block_CSPtr& InsertBuilder::displayBlock() const { return _displayBlock; } InsertBuilder* InsertBuilder::setDisplayBlock(const meta::Block_CSPtr& displayBlock) { _displayBlock = displayBlock; return this; } entity::Insert_CSPtr InsertBuilder::build() { if(!checkValues()) { throw std::runtime_error("Missing values"); } return entity::Insert_CSPtr(new entity::Insert(*this)); } const geo::Coordinate& InsertBuilder::coordinate() const { return _coordinate; } InsertBuilder* InsertBuilder::setCoordinate(const geo::Coordinate& coordinate) { _coordinate = coordinate; return this; } const storage::Document_SPtr& InsertBuilder::document() const { return _document; } InsertBuilder* InsertBuilder::setDocument(const storage::Document_SPtr& document) { _document = document; return this; }
{'repo_name': 'LibreCAD/LibreCAD_3', 'stars': '151', 'repo_language': 'C++', 'file_name': 'dirent.h', 'mime_type': 'text/x-c', 'hash': 7547922059277763919, 'source_dataset': 'data'}
#region License /* * 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. */ #endregion using System; using System.Collections.Generic; namespace Gremlin.Net.Process.Traversal { #pragma warning disable 1591 public class GryoVersion : EnumWrapper { private GryoVersion(string enumValue) : base("GryoVersion", enumValue) { } public static GryoVersion V1_0 => new GryoVersion("V1_0"); public static GryoVersion V3_0 => new GryoVersion("V3_0"); private static readonly IDictionary<string, GryoVersion> Properties = new Dictionary<string, GryoVersion> { { "V1_0", V1_0 }, { "V3_0", V3_0 }, }; /// <summary> /// Gets the GryoVersion enumeration by value. /// </summary> public static GryoVersion GetByValue(string value) { if (!Properties.TryGetValue(value, out var property)) { throw new ArgumentException($"No matching GryoVersion for value '{value}'"); } return property; } } #pragma warning restore 1591 }
{'repo_name': 'apache/tinkerpop', 'stars': '1155', 'repo_language': 'Java', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 5248073252186039946, 'source_dataset': 'data'}
#lang python from '(planet aml/rosetta)' import * from xyz import XYZ backend(rhino5) def shaft(p, shaft_h, base_r, top_r): cone_frustum(p, base_r, shaft_h, top_r) def echinus(p, echinus_h, base_r, top_r): cone_frustum(p, base_r, echinus_h, top_r) def abacus(p, abacus_h, abacus_l): box(p + xyz(-abacus_l / 2, -abacus_l / 2, 0), \ abacus_l, \ abacus_l, \ abacus_h) def column(p, shaft_h, shaft_base_r, \ echinus_h, echinus_base_r, \ abacus_h, abacus_l): shaft(p, shaft_h, shaft_base_r, echinus_base_r) echinus(p + z(shaft_h), echinus_h, echinus_base_r, abacus_l/2) abacus(p + z(shaft_h + echinus_h), abacus_h, abacus_l)
{'repo_name': 'pedropramos/PyonR', 'stars': '120', 'repo_language': 'Racket', 'file_name': 'build_others_unix.sh', 'mime_type': 'text/plain', 'hash': 4208675221149921701, 'source_dataset': 'data'}
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- padnavigator.qdoc --> <head> <title>Qt 4.6: Pad Navigator Example</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">All&nbsp;Functions</font></a>&nbsp;&middot; <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">Pad Navigator Example<br /><span class="subtitle"></span> </h1> <p>Files:</p> <ul> <li><a href="graphicsview-padnavigator-backside-ui.html">graphicsview/padnavigator/backside.ui</a></li> <li><a href="graphicsview-padnavigator-panel-cpp.html">graphicsview/padnavigator/panel.cpp</a></li> <li><a href="graphicsview-padnavigator-panel-h.html">graphicsview/padnavigator/panel.h</a></li> <li><a href="graphicsview-padnavigator-roundrectitem-cpp.html">graphicsview/padnavigator/roundrectitem.cpp</a></li> <li><a href="graphicsview-padnavigator-roundrectitem-h.html">graphicsview/padnavigator/roundrectitem.h</a></li> <li><a href="graphicsview-padnavigator-splashitem-cpp.html">graphicsview/padnavigator/splashitem.cpp</a></li> <li><a href="graphicsview-padnavigator-splashitem-h.html">graphicsview/padnavigator/splashitem.h</a></li> <li><a href="graphicsview-padnavigator-main-cpp.html">graphicsview/padnavigator/main.cpp</a></li> <li><a href="graphicsview-padnavigator-padnavigator-pro.html">graphicsview/padnavigator/padnavigator.pro</a></li> <li><a href="graphicsview-padnavigator-padnavigator-qrc.html">graphicsview/padnavigator/padnavigator.qrc</a></li> </ul> <p>The Pad Navigator Example shows how you can use Graphics View together with embedded widgets to create a simple but useful dynamic user interface for embedded devices.</p> <p align="center"><img src="images/padnavigator-example.png" /></p><p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="40%" align="left">Copyright &copy; 2009 Nokia Corporation and/or its subsidiary(-ies)</td> <td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="40%" align="right"><div align="right">Qt 4.6.0</div></td> </tr></table></div></address></body> </html>
{'repo_name': 'edent/BMW-OpenSource', 'stars': '560', 'repo_language': 'C', 'file_name': 'README', 'mime_type': 'text/plain', 'hash': -4324109062340466324, 'source_dataset': 'data'}
/* Copyright 2015 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 namer import ( "strings" "k8s.io/gengo/types" ) var consonants = "bcdfghjklmnpqrsttvwxyz" type pluralNamer struct { // key is the case-sensitive type name, value is the case-insensitive // intended output. exceptions map[string]string finalize func(string) string } // NewPublicPluralNamer returns a namer that returns the plural form of the input // type's name, starting with a uppercase letter. func NewPublicPluralNamer(exceptions map[string]string) *pluralNamer { return &pluralNamer{exceptions, IC} } // NewPrivatePluralNamer returns a namer that returns the plural form of the input // type's name, starting with a lowercase letter. func NewPrivatePluralNamer(exceptions map[string]string) *pluralNamer { return &pluralNamer{exceptions, IL} } // NewAllLowercasePluralNamer returns a namer that returns the plural form of the input // type's name, with all letters in lowercase. func NewAllLowercasePluralNamer(exceptions map[string]string) *pluralNamer { return &pluralNamer{exceptions, strings.ToLower} } // Name returns the plural form of the type's name. If the type's name is found // in the exceptions map, the map value is returned. func (r *pluralNamer) Name(t *types.Type) string { singular := t.Name.Name var plural string var ok bool if plural, ok = r.exceptions[singular]; ok { return r.finalize(plural) } if len(singular) < 2 { return r.finalize(singular) } switch rune(singular[len(singular)-1]) { case 's', 'x', 'z': plural = esPlural(singular) case 'y': sl := rune(singular[len(singular)-2]) if isConsonant(sl) { plural = iesPlural(singular) } else { plural = sPlural(singular) } case 'h': sl := rune(singular[len(singular)-2]) if sl == 'c' || sl == 's' { plural = esPlural(singular) } else { plural = sPlural(singular) } case 'e': sl := rune(singular[len(singular)-2]) if sl == 'f' { plural = vesPlural(singular[:len(singular)-1]) } else { plural = sPlural(singular) } case 'f': plural = vesPlural(singular) default: plural = sPlural(singular) } return r.finalize(plural) } func iesPlural(singular string) string { return singular[:len(singular)-1] + "ies" } func vesPlural(singular string) string { return singular[:len(singular)-1] + "ves" } func esPlural(singular string) string { return singular + "es" } func sPlural(singular string) string { return singular + "s" } func isConsonant(char rune) bool { for _, c := range consonants { if char == c { return true } } return false }
{'repo_name': 'kubernetes-sigs/kube-batch', 'stars': '685', 'repo_language': 'Go', 'file_name': 'options_test.go', 'mime_type': 'text/plain', 'hash': 3897822093179489246, 'source_dataset': 'data'}
/** @file * CFGM - Configuration Manager. */ /* * Copyright (C) 2006-2010 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ #ifndef ___VBox_vmm_cfgm_h #define ___VBox_vmm_cfgm_h #include <VBox/types.h> #include <iprt/stdarg.h> /** @defgroup grp_cfgm The Configuration Manager API * @{ */ /** * Configuration manager value type. */ typedef enum CFGMVALUETYPE { /** Integer value. */ CFGMVALUETYPE_INTEGER = 1, /** String value. */ CFGMVALUETYPE_STRING, /** Bytestring value. */ CFGMVALUETYPE_BYTES } CFGMVALUETYPE; /** Pointer to configuration manager property type. */ typedef CFGMVALUETYPE *PCFGMVALUETYPE; RT_C_DECLS_BEGIN #ifdef IN_RING3 /** @defgroup grp_cfgm_r3 The CFGM Host Context Ring-3 API * @ingroup grp_cfgm * @{ */ typedef enum CFGMCONFIGTYPE { /** pvConfig points to nothing, use defaults. */ CFGMCONFIGTYPE_NONE = 0, /** pvConfig points to a IMachine interface. */ CFGMCONFIGTYPE_IMACHINE } CFGMCONFIGTYPE; /** * CFGM init callback for constructing the configuration tree. * * This is called from the emulation thread, and the one interfacing the VM * can make any necessary per-thread initializations at this point. * * @returns VBox status code. * @param pVM VM handle. * @param pvUser The argument supplied to VMR3Create(). */ typedef DECLCALLBACK(int) FNCFGMCONSTRUCTOR(PVM pVM, void *pvUser); /** Pointer to a FNCFGMCONSTRUCTOR(). */ typedef FNCFGMCONSTRUCTOR *PFNCFGMCONSTRUCTOR; VMMR3DECL(int) CFGMR3Init(PVM pVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUser); VMMR3DECL(int) CFGMR3Term(PVM pVM); VMMR3DECL(PCFGMNODE) CFGMR3CreateTree(PVM pVM); VMMR3DECL(int) CFGMR3ConstructDefaultTree(PVM pVM); VMMR3DECL(void) CFGMR3Dump(PCFGMNODE pRoot); VMMR3DECL(int) CFGMR3DuplicateSubTree(PCFGMNODE pRoot, PCFGMNODE *ppCopy); VMMR3DECL(int) CFGMR3ReplaceSubTree(PCFGMNODE pRoot, PCFGMNODE pNewRoot); VMMR3DECL(int) CFGMR3InsertSubTree(PCFGMNODE pNode, const char *pszName, PCFGMNODE pSubTree, PCFGMNODE *ppChild); VMMR3DECL(int) CFGMR3InsertNode(PCFGMNODE pNode, const char *pszName, PCFGMNODE *ppChild); VMMR3DECL(int) CFGMR3InsertNodeF(PCFGMNODE pNode, PCFGMNODE *ppChild, const char *pszNameFormat, ...); VMMR3DECL(int) CFGMR3InsertNodeFV(PCFGMNODE pNode, PCFGMNODE *ppChild, const char *pszNameFormat, va_list Args); VMMR3DECL(void) CFGMR3SetRestrictedRoot(PCFGMNODE pNode); VMMR3DECL(void) CFGMR3RemoveNode(PCFGMNODE pNode); VMMR3DECL(int) CFGMR3InsertInteger(PCFGMNODE pNode, const char *pszName, uint64_t u64Integer); VMMR3DECL(int) CFGMR3InsertString(PCFGMNODE pNode, const char *pszName, const char *pszString); VMMR3DECL(int) CFGMR3InsertStringN(PCFGMNODE pNode, const char *pszName, const char *pszString, size_t cchString); VMMR3DECL(int) CFGMR3InsertStringF(PCFGMNODE pNode, const char *pszName, const char *pszFormat, ...); VMMR3DECL(int) CFGMR3InsertStringFV(PCFGMNODE pNode, const char *pszName, const char *pszFormat, va_list va); VMMR3DECL(int) CFGMR3InsertStringW(PCFGMNODE pNode, const char *pszName, PCRTUTF16 pwszValue); VMMR3DECL(int) CFGMR3InsertBytes(PCFGMNODE pNode, const char *pszName, const void *pvBytes, size_t cbBytes); VMMR3DECL(int) CFGMR3InsertValue(PCFGMNODE pNode, PCFGMLEAF pValue); VMMR3DECL(int) CFGMR3RemoveValue(PCFGMNODE pNode, const char *pszName); /** @name CFGMR3CopyTree flags. * @{ */ /** Reserved value disposition \#0. */ #define CFGM_COPY_FLAGS_RESERVED_VALUE_DISP_0 UINT32_C(0x00000000) /** Reserved value disposition \#1. */ #define CFGM_COPY_FLAGS_RESERVED_VALUE_DISP_1 UINT32_C(0x00000001) /** Replace exiting values. */ #define CFGM_COPY_FLAGS_REPLACE_VALUES UINT32_C(0x00000002) /** Ignore exiting values. */ #define CFGM_COPY_FLAGS_IGNORE_EXISTING_VALUES UINT32_C(0x00000003) /** Value disposition mask. */ #define CFGM_COPY_FLAGS_VALUE_DISP_MASK UINT32_C(0x00000003) /** Replace exiting keys. */ #define CFGM_COPY_FLAGS_RESERVED_KEY_DISP UINT32_C(0x00000000) /** Replace exiting keys. */ #define CFGM_COPY_FLAGS_MERGE_KEYS UINT32_C(0x00000010) /** Replace exiting keys. */ #define CFGM_COPY_FLAGS_REPLACE_KEYS UINT32_C(0x00000020) /** Ignore existing keys. */ #define CFGM_COPY_FLAGS_IGNORE_EXISTING_KEYS UINT32_C(0x00000030) /** Key disposition. */ #define CFGM_COPY_FLAGS_KEY_DISP_MASK UINT32_C(0x00000030) /** @} */ VMMR3DECL(int) CFGMR3CopyTree(PCFGMNODE pDstTree, PCFGMNODE pSrcTree, uint32_t fFlags); VMMR3DECL(int) CFGMR3QueryType( PCFGMNODE pNode, const char *pszName, PCFGMVALUETYPE penmType); VMMR3DECL(int) CFGMR3QuerySize( PCFGMNODE pNode, const char *pszName, size_t *pcb); VMMR3DECL(int) CFGMR3QueryInteger( PCFGMNODE pNode, const char *pszName, uint64_t *pu64); VMMR3DECL(int) CFGMR3QueryIntegerDef( PCFGMNODE pNode, const char *pszName, uint64_t *pu64, uint64_t u64Def); VMMR3DECL(int) CFGMR3QueryString( PCFGMNODE pNode, const char *pszName, char *pszString, size_t cchString); VMMR3DECL(int) CFGMR3QueryStringDef( PCFGMNODE pNode, const char *pszName, char *pszString, size_t cchString, const char *pszDef); VMMR3DECL(int) CFGMR3QueryBytes( PCFGMNODE pNode, const char *pszName, void *pvData, size_t cbData); /** @name Helpers * @{ */ VMMR3DECL(int) CFGMR3QueryU64( PCFGMNODE pNode, const char *pszName, uint64_t *pu64); VMMR3DECL(int) CFGMR3QueryU64Def( PCFGMNODE pNode, const char *pszName, uint64_t *pu64, uint64_t u64Def); VMMR3DECL(int) CFGMR3QueryS64( PCFGMNODE pNode, const char *pszName, int64_t *pi64); VMMR3DECL(int) CFGMR3QueryS64Def( PCFGMNODE pNode, const char *pszName, int64_t *pi64, int64_t i64Def); VMMR3DECL(int) CFGMR3QueryU32( PCFGMNODE pNode, const char *pszName, uint32_t *pu32); VMMR3DECL(int) CFGMR3QueryU32Def( PCFGMNODE pNode, const char *pszName, uint32_t *pu32, uint32_t u32Def); VMMR3DECL(int) CFGMR3QueryS32( PCFGMNODE pNode, const char *pszName, int32_t *pi32); VMMR3DECL(int) CFGMR3QueryS32Def( PCFGMNODE pNode, const char *pszName, int32_t *pi32, int32_t i32Def); VMMR3DECL(int) CFGMR3QueryU16( PCFGMNODE pNode, const char *pszName, uint16_t *pu16); VMMR3DECL(int) CFGMR3QueryU16Def( PCFGMNODE pNode, const char *pszName, uint16_t *pu16, uint16_t u16Def); VMMR3DECL(int) CFGMR3QueryS16( PCFGMNODE pNode, const char *pszName, int16_t *pi16); VMMR3DECL(int) CFGMR3QueryS16Def( PCFGMNODE pNode, const char *pszName, int16_t *pi16, int16_t i16Def); VMMR3DECL(int) CFGMR3QueryU8( PCFGMNODE pNode, const char *pszName, uint8_t *pu8); VMMR3DECL(int) CFGMR3QueryU8Def( PCFGMNODE pNode, const char *pszName, uint8_t *pu8, uint8_t u8Def); VMMR3DECL(int) CFGMR3QueryS8( PCFGMNODE pNode, const char *pszName, int8_t *pi8); VMMR3DECL(int) CFGMR3QueryS8Def( PCFGMNODE pNode, const char *pszName, int8_t *pi8, int8_t i8Def); VMMR3DECL(int) CFGMR3QueryBool( PCFGMNODE pNode, const char *pszName, bool *pf); VMMR3DECL(int) CFGMR3QueryBoolDef( PCFGMNODE pNode, const char *pszName, bool *pf, bool fDef); VMMR3DECL(int) CFGMR3QueryPort( PCFGMNODE pNode, const char *pszName, PRTIOPORT pPort); VMMR3DECL(int) CFGMR3QueryPortDef( PCFGMNODE pNode, const char *pszName, PRTIOPORT pPort, RTIOPORT PortDef); VMMR3DECL(int) CFGMR3QueryUInt( PCFGMNODE pNode, const char *pszName, unsigned int *pu); VMMR3DECL(int) CFGMR3QueryUIntDef( PCFGMNODE pNode, const char *pszName, unsigned int *pu, unsigned int uDef); VMMR3DECL(int) CFGMR3QuerySInt( PCFGMNODE pNode, const char *pszName, signed int *pi); VMMR3DECL(int) CFGMR3QuerySIntDef( PCFGMNODE pNode, const char *pszName, signed int *pi, signed int iDef); VMMR3DECL(int) CFGMR3QueryPtr( PCFGMNODE pNode, const char *pszName, void **ppv); VMMR3DECL(int) CFGMR3QueryPtrDef( PCFGMNODE pNode, const char *pszName, void **ppv, void *pvDef); VMMR3DECL(int) CFGMR3QueryGCPtr( PCFGMNODE pNode, const char *pszName, PRTGCPTR pGCPtr); VMMR3DECL(int) CFGMR3QueryGCPtrDef( PCFGMNODE pNode, const char *pszName, PRTGCPTR pGCPtr, RTGCPTR GCPtrDef); VMMR3DECL(int) CFGMR3QueryGCPtrU( PCFGMNODE pNode, const char *pszName, PRTGCUINTPTR pGCPtr); VMMR3DECL(int) CFGMR3QueryGCPtrUDef( PCFGMNODE pNode, const char *pszName, PRTGCUINTPTR pGCPtr, RTGCUINTPTR GCPtrDef); VMMR3DECL(int) CFGMR3QueryGCPtrS( PCFGMNODE pNode, const char *pszName, PRTGCINTPTR pGCPtr); VMMR3DECL(int) CFGMR3QueryGCPtrSDef( PCFGMNODE pNode, const char *pszName, PRTGCINTPTR pGCPtr, RTGCINTPTR GCPtrDef); VMMR3DECL(int) CFGMR3QueryStringAlloc( PCFGMNODE pNode, const char *pszName, char **ppszString); VMMR3DECL(int) CFGMR3QueryStringAllocDef(PCFGMNODE pNode, const char *pszName, char **ppszString, const char *pszDef); /** @} */ /** @name Tree Navigation and Enumeration. * @{ */ VMMR3DECL(PCFGMNODE) CFGMR3GetRoot(PVM pVM); VMMR3DECL(PCFGMNODE) CFGMR3GetParent(PCFGMNODE pNode); VMMR3DECL(PCFGMNODE) CFGMR3GetParentEx(PVM pVM, PCFGMNODE pNode); VMMR3DECL(PCFGMNODE) CFGMR3GetChild(PCFGMNODE pNode, const char *pszPath); VMMR3DECL(PCFGMNODE) CFGMR3GetChildF(PCFGMNODE pNode, const char *pszPathFormat, ...); VMMR3DECL(PCFGMNODE) CFGMR3GetChildFV(PCFGMNODE pNode, const char *pszPathFormat, va_list Args); VMMR3DECL(PCFGMNODE) CFGMR3GetFirstChild(PCFGMNODE pNode); VMMR3DECL(PCFGMNODE) CFGMR3GetNextChild(PCFGMNODE pCur); VMMR3DECL(int) CFGMR3GetName(PCFGMNODE pCur, char *pszName, size_t cchName); VMMR3DECL(size_t) CFGMR3GetNameLen(PCFGMNODE pCur); VMMR3DECL(bool) CFGMR3AreChildrenValid(PCFGMNODE pNode, const char *pszzValid); VMMR3DECL(PCFGMLEAF) CFGMR3GetFirstValue(PCFGMNODE pCur); VMMR3DECL(PCFGMLEAF) CFGMR3GetNextValue(PCFGMLEAF pCur); VMMR3DECL(int) CFGMR3GetValueName(PCFGMLEAF pCur, char *pszName, size_t cchName); VMMR3DECL(size_t) CFGMR3GetValueNameLen(PCFGMLEAF pCur); VMMR3DECL(CFGMVALUETYPE) CFGMR3GetValueType(PCFGMLEAF pCur); VMMR3DECL(bool) CFGMR3AreValuesValid(PCFGMNODE pNode, const char *pszzValid); VMMR3DECL(int) CFGMR3ValidateConfig(PCFGMNODE pNode, const char *pszNode, const char *pszValidValues, const char *pszValidNodes, const char *pszWho, uint32_t uInstance); /** @} */ /** @} */ #endif /* IN_RING3 */ RT_C_DECLS_END /** @} */ #endif
{'repo_name': 'VirtualMonitor/VirtualMonitor', 'stars': '152', 'repo_language': 'C', 'file_name': 'lintian-override.in', 'mime_type': 'text/plain', 'hash': 374012745483834342, 'source_dataset': 'data'}
using System; using System.Collections.Generic; using System.Text; using Manatee.Json.Schema; using NUnit.Framework; namespace Manatee.Json.Tests.Schema { [TestFixture] public class UnevaluatedItemsTests { [TestCase("[true,\"hello\", false]", true)] [TestCase("[1,3,4]", true)] [TestCase("[true, false]", false)] public void SpecIssue810_EdgeCases(string jsonText, bool passes) { var schema = new JsonSchema() .Type(JsonSchemaType.Array) .OneOf(new JsonSchema().Contains(new JsonSchema().Type(JsonSchemaType.String)), new JsonSchema().Items(new JsonSchema().Type(JsonSchemaType.Integer))) .UnevaluatedItems(new JsonSchema().Type(JsonSchemaType.Boolean)); var json = JsonValue.Parse(jsonText); var result = schema.Validate(json); if (passes) result.AssertValid(); else result.AssertInvalid(); } } }
{'repo_name': 'gregsdennis/Manatee.Json', 'stars': '168', 'repo_language': 'C#', 'file_name': 'Program.cs', 'mime_type': 'text/x-c++', 'hash': -7965842097506372224, 'source_dataset': 'data'}
var gulp = require('gulp'); var runSequence = require('run-sequence'); var changed = require('gulp-changed'); var plumber = require('gulp-plumber'); var to5 = require('gulp-babel'); var sourcemaps = require('gulp-sourcemaps'); var paths = require('../paths'); var compilerOptions = require('../babel-options'); var assign = Object.assign || require('object.assign'); var notify = require('gulp-notify'); var exec = require('child_process').exec; var htmlmin = require('gulp-htmlmin'); // transpiles changed es6 files to SystemJS format // the plumber() call prevents 'pipe breaking' caused // by errors from other gulp plugins // https://www.npmjs.com/package/gulp-plumber gulp.task('build-system', function() { return gulp.src(paths.source) .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) .pipe(changed(paths.output, {extension: '.js'})) .pipe(sourcemaps.init({loadMaps: true})) .pipe(to5(assign({}, compilerOptions.system()))) .pipe(sourcemaps.write({includeContent: false, sourceRoot: '/src'})) .pipe(gulp.dest(paths.output)); }); // copies changed html files to the output directory gulp.task('build-html', function() { return gulp.src(paths.html) .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) .pipe(changed(paths.output, {extension: '.html'})) .pipe(htmlmin({collapseWhitespace: true})) .pipe(gulp.dest(paths.output)); }); // copies changed css files to the output directory gulp.task('build-css', function() { return gulp.src(paths.css) .pipe(changed(paths.output, {extension: '.css'})) .pipe(gulp.dest(paths.output)) }); // this task calls the clean task (located // in ./clean.js), then runs the build-system // and build-html tasks in parallel // https://www.npmjs.com/package/gulp-run-sequence gulp.task('build', function(callback) { return runSequence( 'clean', ['build-system', 'build-html', 'build-css'], callback ); });
{'repo_name': 'aurelia/skeleton-navigation', 'stars': '754', 'repo_language': 'JavaScript', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': -7507507046929633588, 'source_dataset': 'data'}
package epi.test_framework.serialization_traits; import epi.test_framework.minimal_json.JsonValue; import java.util.Collections; import java.util.List; import java.util.Objects; public class BooleanTrait extends SerializationTrait { @Override public String name() { return "bool"; } @Override public Object parse(JsonValue jsonObject) { return jsonObject.asBoolean(); } @Override public List<String> getMetricNames(String argName) { return Collections.emptyList(); } @Override public List<Integer> getMetrics(Object x) { if (x instanceof Boolean) { return Collections.emptyList(); } else { throw new RuntimeException("Expected Boolean"); } } }
{'repo_name': 'adnanaziz/EPIJudge', 'stars': '1618', 'repo_language': 'C++', 'file_name': 'ParseException.java', 'mime_type': 'text/plain', 'hash': 1952987825684988159, 'source_dataset': 'data'}
# # This is a project Makefile. It is assumed the directory this Makefile resides in is a # project subdirectory. # PROJECT_NAME := himem_test include $(IDF_PATH)/make/project.mk
{'repo_name': 'espressif/esp-idf', 'stars': '5095', 'repo_language': 'C', 'file_name': 'project.mk', 'mime_type': 'text/x-makefile', 'hash': 8464791207633409645, 'source_dataset': 'data'}
title "Errors on eth0" area :first hide_legend false field :receiving, :color => "green", :alias => "Receiving", :data => "node.interface.errors.eth0.rx" field :transmitting, :color => "blue", :alias => "Transmiting", :data => "node.interface.errors.eth0.tx"
{'repo_name': 'ripienaar/gdash', 'stars': '765', 'repo_language': 'CSS', 'file_name': 'forms.html', 'mime_type': 'text/html', 'hash': 1547250403806876910, 'source_dataset': 'data'}
// Copyright 2018 LinkedIn Corp. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #import "LOKLayoutBuilder.h" @class LOKTextViewLayout; /** LayoutBuilder for @c LOKTextViewLayout. */ @interface LOKTextViewLayoutBuilder: NSObject<LOKLayoutBuilder> /** Creates a @c LOKTextViewLayoutBuilder with the given string. @param string The string set to the underlying @c UITextView's text. */ - (nonnull instancetype)initWithString:(nullable NSString *)string; /** Creates a @c LOKTextViewLayoutBuilder with the given attributed string. @param attributedString The attributed string set as the underlying @c UITextView's attributedText. */ - (nonnull instancetype)initWithAttributedString:(nullable NSAttributedString *)attributedString; + (nonnull instancetype)withString:(nullable NSString *)string; + (nonnull instancetype)withAttributedString:(nullable NSAttributedString *)attributedString; /** @c LOKTextViewLayoutBuilder block for setting font of the @c LOKTextViewLayout. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^font)(UIFont * _Nullable); /** @c LOKTextViewLayoutBuilder block for setting insets for the text container of @c UITextViewLayout. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^textContainerInset)(UIEdgeInsets); /** @c LOKTextViewLayoutBuilder block for setting line padding between text container and actual text in @c LOKTextViewLayout. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^lineFragmentPadding)(CGFloat); /** @c LOKTextViewLayoutBuilder block for defining how this layout is positioned inside its parent layout. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^alignment)(LOKAlignment * _Nullable); /** @c LOKTextViewLayoutBuilder block for setting flexibility of the @c LOKTextViewLayout. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^flexibility)(LOKFlexibility * _Nullable); /** @c LOKTextViewLayoutBuilder block for setting the viewReuseId used by LayoutKit. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^viewReuseId)(NSString * _Nullable); /** @c LOKTextViewLayoutBuilder block for setting the view class of the @c LOKTextViewLayout(should be @c UITextView */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^viewClass)(Class _Nullable); /** Layoutkit configuration block called with the created @c UITextView (or subclass). */ @property (nonatomic, nonnull, readonly) LOKTextViewLayoutBuilder * _Nonnull(^config)( void(^ _Nullable)(UITextView *_Nonnull)); /** @c LOKTextViewLayoutBuilder block for setting edge inset (positive) for the @c LOKTextViewLayout. */ @property (nonatomic, nonnull, readonly) LOKInsetLayoutBuilder * _Nonnull(^insets)(LOKEdgeInsets); /** Calling this builds and returns the @c LOKTextViewLayout. */ @property (nonatomic, nonnull, readonly) LOKTextViewLayout *layout; @end
{'repo_name': 'linkedin/LayoutKit', 'stars': '3090', 'repo_language': 'Swift', 'file_name': 'LayoutKit-macOS.xcscheme', 'mime_type': 'text/xml', 'hash': 4375065950729221432, 'source_dataset': 'data'}
// -------------------------------------------------------------------------------------------------- // Copyright (c) 2016 Microsoft Corporation // // 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 com.microsoft.Malmo.MissionHandlers; import java.util.ArrayList; import java.util.HashMap; import com.microsoft.Malmo.MissionHandlerInterfaces.ICommandHandler; import com.microsoft.Malmo.Schemas.MissionInit; /** Composite class that manages a set of ICommandHandler objects.<br> */ public class CommandGroup extends CommandBase { private ArrayList<ICommandHandler> handlers; private boolean isOverriding = false; private boolean shareParametersWithChildren = false; public CommandGroup() { this.handlers = new ArrayList<ICommandHandler>(); } /** Call this to give a copy of the group's parameter block to all children.<br> * Useful for composite handlers like CommandForStandardRobot etc, where the children * aren't specified in the XML directly and so have no other opportunity to be parameterised. * This must be set before parseParameters is called in order for it to take effect. * (parseParameters is called shortly after construction, so the constructor is the best place to set this.) * @param share true if the children should get a copy of the parent's parameter block. */ protected void setShareParametersWithChildren(boolean share) { this.shareParametersWithChildren = share; } void addCommandHandler(ICommandHandler handler) { if (handler != null) { this.handlers.add(handler); handler.setOverriding(this.isOverriding); } } @Override protected boolean onExecute(String verb, String parameter, MissionInit missionInit) { for (ICommandHandler han : this.handlers) { if (han.execute(verb + " " + parameter, missionInit)) { return true; } } return false; } @Override public void install(MissionInit missionInit) { for (ICommandHandler han : this.handlers) { han.install(missionInit); } } @Override public void deinstall(MissionInit missionInit) { for (ICommandHandler han : this.handlers) { han.deinstall(missionInit); } } @Override public boolean isOverriding() { return this.isOverriding; } @Override public void setOverriding(boolean b) { this.isOverriding = b; for (ICommandHandler han : this.handlers) { han.setOverriding(b); } } @Override public void setParentBehaviour(MissionBehaviour mb) { super.setParentBehaviour(mb); for (ICommandHandler han : this.handlers) ((HandlerBase)han).setParentBehaviour(mb); } @Override public void appendExtraServerInformation(HashMap<String, String> map) { for (ICommandHandler han : this.handlers) { if (han instanceof HandlerBase) ((HandlerBase)han).appendExtraServerInformation(map); } } @Override public boolean parseParameters(Object params) { // Normal handling: boolean ok = super.parseParameters(params); // Now, pass the params to each child handler, if that was requested: if (this.shareParametersWithChildren) { // AND the results, but without short-circuit evaluation. for (ICommandHandler han : this.handlers) { if (han instanceof HandlerBase) { ok &= ((HandlerBase) han).parseParameters(params); } } } return ok; } public boolean isFixed() { return false; // Return true to stop MissionBehaviour from adding new handlers to this group. } }
{'repo_name': 'microsoft/malmo', 'stars': '3553', 'repo_language': 'Java', 'file_name': 'FindALE.cmake', 'mime_type': 'text/plain', 'hash': -9105345727905868494, 'source_dataset': 'data'}
// // Mono.Math.Prime.Generator.NextPrimeFinder.cs - Prime Generator // // Authors: // Ben Maurer // // Copyright (c) 2003 Ben Maurer. All rights reserved // // // 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. // using System; namespace Mono.Math.Prime.Generator { /// <summary> /// Finds the next prime after a given number. /// </summary> #if INSIDE_CORLIB internal #else public #endif class NextPrimeFinder : SequentialSearchPrimeGeneratorBase { protected override BigInteger GenerateSearchBase (int bits, object Context) { if (Context == null) throw new ArgumentNullException ("Context"); BigInteger ret = new BigInteger ((BigInteger)Context); ret.SetBit (0); return ret; } } }
{'repo_name': 'xamarin/XamarinComponents', 'stars': '1853', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': 6968479939035657000, 'source_dataset': 'data'}
/** Generated Model - DO NOT CHANGE */ package de.metas.contracts.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; /** Generated Model for C_Invoice_Candidate_Assignment_Aggregate_V * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_C_Invoice_Candidate_Assignment_Aggregate_V extends org.compiere.model.PO implements I_C_Invoice_Candidate_Assignment_Aggregate_V, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 1709043075L; /** Standard Constructor */ public X_C_Invoice_Candidate_Assignment_Aggregate_V (Properties ctx, int C_Invoice_Candidate_Assignment_Aggregate_V_ID, String trxName) { super (ctx, C_Invoice_Candidate_Assignment_Aggregate_V_ID, trxName); /** if (C_Invoice_Candidate_Assignment_Aggregate_V_ID == 0) { } */ } /** Load Constructor */ public X_C_Invoice_Candidate_Assignment_Aggregate_V (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Zugeordneter Geldbetrag. @param AssignedMoneyAmount Zugeordneter Geldbetrag, in der Währung des Vertrags-Rechnungskandidaten. */ @Override public void setAssignedMoneyAmount (java.math.BigDecimal AssignedMoneyAmount) { set_ValueNoCheck (COLUMNNAME_AssignedMoneyAmount, AssignedMoneyAmount); } /** Get Zugeordneter Geldbetrag. @return Zugeordneter Geldbetrag, in der Währung des Vertrags-Rechnungskandidaten. */ @Override public java.math.BigDecimal getAssignedMoneyAmount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedMoneyAmount); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zugeordnete Menge. @param AssignedQuantity Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes */ @Override public void setAssignedQuantity (java.math.BigDecimal AssignedQuantity) { set_ValueNoCheck (COLUMNNAME_AssignedQuantity, AssignedQuantity); } /** Get Zugeordnete Menge. @return Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes */ @Override public java.math.BigDecimal getAssignedQuantity () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedQuantity); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public de.metas.contracts.model.I_C_Flatrate_RefundConfig getC_Flatrate_RefundConfig() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class); } @Override public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig) { set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig); } /** Set C_Flatrate_RefundConfig. @param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */ @Override public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID) { if (C_Flatrate_RefundConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID)); } /** Get C_Flatrate_RefundConfig. @return C_Flatrate_RefundConfig */ @Override public int getC_Flatrate_RefundConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) { if (C_Invoice_Candidate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } }
{'repo_name': 'metasfresh/metasfresh', 'stars': '653', 'repo_language': 'TSQL', 'file_name': 'I_C_NonBusinessDay.java', 'mime_type': 'text/plain', 'hash': -6765081399963231269, 'source_dataset': 'data'}
/* * Copyright 2010-2018 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.ec2.model; import java.io.Serializable; /** * <p> * Describes association information for an Elastic IP address. * </p> */ public class NetworkInterfaceAssociation implements Serializable { /** * The address of the Elastic IP address bound to the network interface. */ private String publicIp; /** * The public DNS name. */ private String publicDnsName; /** * The ID of the Elastic IP address owner. */ private String ipOwnerId; /** * The allocation ID. */ private String allocationId; /** * The association ID. */ private String associationId; /** * The address of the Elastic IP address bound to the network interface. * * @return The address of the Elastic IP address bound to the network interface. */ public String getPublicIp() { return publicIp; } /** * The address of the Elastic IP address bound to the network interface. * * @param publicIp The address of the Elastic IP address bound to the network interface. */ public void setPublicIp(String publicIp) { this.publicIp = publicIp; } /** * The address of the Elastic IP address bound to the network interface. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param publicIp The address of the Elastic IP address bound to the network interface. * * @return A reference to this updated object so that method calls can be chained * together. */ public NetworkInterfaceAssociation withPublicIp(String publicIp) { this.publicIp = publicIp; return this; } /** * The public DNS name. * * @return The public DNS name. */ public String getPublicDnsName() { return publicDnsName; } /** * The public DNS name. * * @param publicDnsName The public DNS name. */ public void setPublicDnsName(String publicDnsName) { this.publicDnsName = publicDnsName; } /** * The public DNS name. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param publicDnsName The public DNS name. * * @return A reference to this updated object so that method calls can be chained * together. */ public NetworkInterfaceAssociation withPublicDnsName(String publicDnsName) { this.publicDnsName = publicDnsName; return this; } /** * The ID of the Elastic IP address owner. * * @return The ID of the Elastic IP address owner. */ public String getIpOwnerId() { return ipOwnerId; } /** * The ID of the Elastic IP address owner. * * @param ipOwnerId The ID of the Elastic IP address owner. */ public void setIpOwnerId(String ipOwnerId) { this.ipOwnerId = ipOwnerId; } /** * The ID of the Elastic IP address owner. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param ipOwnerId The ID of the Elastic IP address owner. * * @return A reference to this updated object so that method calls can be chained * together. */ public NetworkInterfaceAssociation withIpOwnerId(String ipOwnerId) { this.ipOwnerId = ipOwnerId; return this; } /** * The allocation ID. * * @return The allocation ID. */ public String getAllocationId() { return allocationId; } /** * The allocation ID. * * @param allocationId The allocation ID. */ public void setAllocationId(String allocationId) { this.allocationId = allocationId; } /** * The allocation ID. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param allocationId The allocation ID. * * @return A reference to this updated object so that method calls can be chained * together. */ public NetworkInterfaceAssociation withAllocationId(String allocationId) { this.allocationId = allocationId; return this; } /** * The association ID. * * @return The association ID. */ public String getAssociationId() { return associationId; } /** * The association ID. * * @param associationId The association ID. */ public void setAssociationId(String associationId) { this.associationId = associationId; } /** * The association ID. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param associationId The association ID. * * @return A reference to this updated object so that method calls can be chained * together. */ public NetworkInterfaceAssociation withAssociationId(String associationId) { this.associationId = associationId; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPublicIp() != null) sb.append("PublicIp: " + getPublicIp() + ","); if (getPublicDnsName() != null) sb.append("PublicDnsName: " + getPublicDnsName() + ","); if (getIpOwnerId() != null) sb.append("IpOwnerId: " + getIpOwnerId() + ","); if (getAllocationId() != null) sb.append("AllocationId: " + getAllocationId() + ","); if (getAssociationId() != null) sb.append("AssociationId: " + getAssociationId() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPublicIp() == null) ? 0 : getPublicIp().hashCode()); hashCode = prime * hashCode + ((getPublicDnsName() == null) ? 0 : getPublicDnsName().hashCode()); hashCode = prime * hashCode + ((getIpOwnerId() == null) ? 0 : getIpOwnerId().hashCode()); hashCode = prime * hashCode + ((getAllocationId() == null) ? 0 : getAllocationId().hashCode()); hashCode = prime * hashCode + ((getAssociationId() == null) ? 0 : getAssociationId().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof NetworkInterfaceAssociation == false) return false; NetworkInterfaceAssociation other = (NetworkInterfaceAssociation)obj; if (other.getPublicIp() == null ^ this.getPublicIp() == null) return false; if (other.getPublicIp() != null && other.getPublicIp().equals(this.getPublicIp()) == false) return false; if (other.getPublicDnsName() == null ^ this.getPublicDnsName() == null) return false; if (other.getPublicDnsName() != null && other.getPublicDnsName().equals(this.getPublicDnsName()) == false) return false; if (other.getIpOwnerId() == null ^ this.getIpOwnerId() == null) return false; if (other.getIpOwnerId() != null && other.getIpOwnerId().equals(this.getIpOwnerId()) == false) return false; if (other.getAllocationId() == null ^ this.getAllocationId() == null) return false; if (other.getAllocationId() != null && other.getAllocationId().equals(this.getAllocationId()) == false) return false; if (other.getAssociationId() == null ^ this.getAssociationId() == null) return false; if (other.getAssociationId() != null && other.getAssociationId().equals(this.getAssociationId()) == false) return false; return true; } }
{'repo_name': 'aws-amplify/aws-sdk-android', 'stars': '772', 'repo_language': 'Java', 'file_name': 'DynamoDBv2Actions.java', 'mime_type': 'text/x-java', 'hash': -4578590814514753629, 'source_dataset': 'data'}
/******************************* MODULE HEADER ****************************** * initdll.c * Dynamic Link Library initialization module. These functions are * invoked when the DLL is initially loaded by NT. * * This document contains confidential/proprietary information. * Copyright (c) 1991 - 1992 Microsoft Corporation, All Rights Reserved. * * Revision History: * 12:59 on Fri 13 Mar 1992 -by- Lindsay Harris [lindsayh] * Update to create heap. * * [00] 24-Jun-91 stevecat created * [01] 4-Oct-91 stevecat new dll init logic * ****************************************************************************/ #include "rasuipch.h" /* * Global data. These are references in the dialog style code, in the * font installer and numberous other places. */ HMODULE hModule; HANDLE hHeap; /* For whoever needs */ CRITICAL_SECTION RasdduiCriticalSection; /* Critical Section Object */ #define HEAP_MIN_SIZE ( 64 * 1024) #define HEAP_MAX_SIZE (1024 * 1024) /*************************** Function Header ****************************** * DllInitialize () * DLL initialization procedure. Save the module handle since it is needed * by other library routines to get resources (strings, dialog boxes, etc.) * from the DLL's resource data area. * * RETURNS: * TRUE/FALSE, FALSE only if HeapCreate fails. * * HISTORY: * 13:02 on Fri 13 Mar 1992 -by- Lindsay Harris [lindsayh] * Added HeapCreate/Destroy code. * * [01] 4-Oct-91 stevecat new dll init logic * [00] 24-Jun-91 stevecat created * * 27-Apr-1994 Wed 17:01:18 updated -by- Daniel Chou (danielc) * Free up the HTUI.dll when we exit * ***************************************************************************/ BOOL DllInitialize( hmod, ulReason, pctx ) PVOID hmod; ULONG ulReason; PCONTEXT pctx; { WCHAR wName[MAX_PATH + 32]; BOOL bRet; UNREFERENCED_PARAMETER( pctx ); bRet = TRUE; switch (ulReason) { case DLL_PROCESS_ATTACH: if( !(hHeap = HeapCreate(0, HEAP_MIN_SIZE, 0))) { #if DBG DbgPrint( "HeapCreate fails in Rasddui!DllInitialize\n" ); #endif bRet = FALSE; } else { InitializeCriticalSection(&RasdduiCriticalSection); //Load itself for performance if (GetModuleFileName(hModule = hmod, wName,COUNT_ARRAY(wName))) { LoadLibrary(wName); } else { #if DBG DbgPrint( "DllInitialize: GetModuleFileName() FAILED!"); #endif } } break; case DLL_PROCESS_DETACH: if (hHeap) { HeapDestroy(hHeap); hHeap = NULL; } DeleteCriticalSection(&RasdduiCriticalSection); break; } return(bRet); }
{'repo_name': 'ZoloZiak/WinNT4', 'stars': '168', 'repo_language': 'C', 'file_name': 'dc21x4.hpj', 'mime_type': 'text/plain', 'hash': 8928000022287346812, 'source_dataset': 'data'}
{ "name": "RZBluetooth", "version": "1.3.0", "summary": "A Core Bluetooth helper library to simplify the development and testing of Core Bluetooth applications.", "description": "RZBluetooth is a Core Bluetooth helper with 3 primary goals:\n\n- Simplify the delegate callbacks and encourage best practices\n- Provide a pattern for Profile level APIs, with support for public profiles\n- Simplify and encourage testing - including unit tests, automated integration tests, and manual tests.", "homepage": "http://github.com/Raizlabs/RZBluetooth", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Brian King": "brianaking@gmail.com" }, "source": { "git": "https://github.com/Raizlabs/RZBluetooth.git", "tag": "1.3.0" }, "requires_arc": true, "platforms": { "osx": "10.10", "ios": "8.0", "watchos": "4.0" }, "default_subspecs": "Core", "subspecs": [ { "name": "Core", "platforms": { "osx": "10.10", "ios": "8.0", "watchos": "4.0" }, "pod_target_xcconfig": { "CLANG_WARN_UNGUARDED_AVAILABILITY": "NO" }, "source_files": "RZBluetooth/**/*.{h,m}", "public_header_files": "RZBluetooth/**/*.h", "private_header_files": [ "RZBluetooth/**/*+Private.h", "RZBluetooth/Command/*.h", "RZBluetooth/RZBCentralManager+CommandHelper.h" ] }, { "name": "Mock", "platforms": { "osx": "10.10", "ios": "8.0" }, "dependencies": { "RZBluetooth/Core": [ ] }, "source_files": "RZMockBluetooth/**/*.{h,m}", "public_header_files": "RZMockBluetooth/**/*.h", "private_header_files": "RZMockBluetooth/**/*+Private.h" }, { "name": "Test", "platforms": { "osx": "10.10", "ios": "8.0" }, "dependencies": { "RZBluetooth/Mock": [ ] }, "frameworks": "XCTest", "source_files": [ "RZBluetoothTests/RZBTestDefines.h", "RZBluetoothTests/RZBSimulatedTestCase.{h,m}", "RZBluetoothTests/Helpers/NSRunLoop+RZBWaitFor.{h,m}" ], "public_header_files": [ "RZBluetoothTests/RZBSimulatedTestCase.h", "RZBluetoothTests/RZBTestDefines.h" ] } ] }
{'repo_name': 'Rightpoint/RZBluetooth', 'stars': '119', 'repo_language': 'Objective-C', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -8836462011293642865, 'source_dataset': 'data'}
Bitballoon ---------- Bitballoon can easily be set up for continuous deployment off a github branch, which typically is the preferred method for deployment. However, if you want to set up the initial deploy, or prefer manually deploy rather than linking to github, this deployer should fit the bill. ### Config Values - **name**: name of the site you want to deploy - **access_token**: an oauth access token from bitballoon ### Generating an Access Token Luckily, it's very simple to generate an access token without having to jump through the usual oauth hoops. To do so, log into your bitballoon account, and head over to the **Applications** menu item. ![Bitballoon Applications](http://cl.ly/Y0Xn/Screen%20Shot%202014-10-13%20at%2012.34.37%20PM.png) Once on this page, generate a new **Personal Access Token** as such: ![Bitballoon Personal Access Token 1](http://cl.ly/Y0eT/Screen%20Shot%202014-10-13%20at%2012.28.43%20PM.png) ![Bitballoon Personal Access Token 2](http://cl.ly/XzyO/Screen%20Shot%202014-10-13%20at%2012.29.31%20PM.png) ![Bitballoon Personal Access Token 3](http://cl.ly/Y0hs/Screen%20Shot%202014-10-13%20at%2012.29.39%20PM.png) Now just copy that token and add it to your `ship.conf` file, or just enter it in the command line prompt the first time you run `ship` for the site. And no, don't try to use the token in the image above, it's just there as an example and is not a valid token. Make your own tokens holmes.
{'repo_name': 'carrot/ship', 'stars': '152', 'repo_language': 'CoffeeScript', 'file_name': 'mock_stream.coffee', 'mime_type': 'text/plain', 'hash': -7953770005932844668, 'source_dataset': 'data'}
<!-- <body style="background-image:url('/images/back.jpg');background-size:100% 100%;background-repeat:no-repeat;color:#234069;text-align:center"> --> <div style="margin:20px auto;width:30em;text-align:right;float:right;font-size:20px;padding-right:8em" > </div> <div style="margin:0px auto;width:45em;clear:both"> <span style="text-align:left;float:left;width:128px;padding-top:1.75em"><img src="/images/PACO128.png"></span> <span style="text-align:right;float:right:width:440px;padding-left:.5em"><img src="/images/paco_word_crop.png"></span> </div> <div style="margin:0px auto;clear:both"> <span style="text-align:center;float:center"><img src="/images/phrase.png"></span> </div> <div style="text-align:left;margin-left: auto; margin-right: auto; width: 50em;"> <hr> <div style="font-weight:bold;font-size:35px;padding-bottom:.5em">What is PACO?</div> <div style="font-style:italic;font-weight:bold;font-size:25px;padding-bottom:.5em">It's a tool for building your own Personal Science experiments - in minutes!</div><div><span style="font-style:italic;font-size:15px;">(On Android devices!&nbsp; On iOS 5 devices someday..)</span></div> <div style="padding-top:1em;"> <p><span style="font-size:30px;color:#B00530"">Join the announcement list for an invitation to the beta trial.</span><br/></p> </div> <div> <form action="http://groups.google.com/group/paco-announcements/boxsubscribe"> Email: <input type=text name=email> <input type=submit name="sub" value="Join"> </form> </div> <div style="text-align:left;margin-top:7em"> <hr> <div style="text-align:center;font-style:italic;font-size:35px;padding-bottom:.5em">Learn More about PACO</div> <hr> <div style="font-weight:bold;font-size:35px;padding-bottom:.5em">What is PACO good for?</div> <div style="font-style:italic;font-weight:bold;font-size:25px;padding-bottom:.5em"><b>Many types of mobile experiments!</b></div> <div dir="ltr"><b>Quantified Self</b></div> <div dir="ltr">Ever wonder how happy you are? Whether your weight is trending up or down? Do you want one place to manage the data and reminder scheduling for all your mobile exercise trackers, weight trackers, baby's bowel movement trackers, fuel consumption trackers (is that the same as the previous one?)?&nbsp;</div> <div dir="ltr"><br> </div> <div dir="ltr"><b>Mobile Population Studies - Wellness, Corporate environment, or Whatever</b></div> <div dir="ltr">Ever want to design, iterate, and deliver a social science experiment or mobile wellness intervention to a group of people on Android mobile phones in a matter of minutes? (You social and behavioral scientists out there know who you are.)</div> <div dir="ltr"><br> </div> <div dir="ltr"><b>User Control of Data</b></div> <div dir="ltr">Do you want to be able to <b>correlate your data across multiple trackers</b>?&nbsp;</div> <div dir="ltr">Do you want your <b>data kept private and under your control</b>? With informed consent about what you are sharing and with whom?</div> <div dir="ltr"><br> </div> <hr> <div dir="ltr">If you answered yes to any or all of these questions, then, <b>Paco is the tool for you! </b>Though we are still building a lot of these features, so don't be too judgmental just yet - instead <a href="http://code.google.com/p/paco">chip in some of your own 20% time.</a></div> <div dir="ltr"><b><br> </b></div> <hr> <div style="font-weight:bold;font-size:35px;padding-bottom:.5em">What does PACO provide?</div> <div dir="ltr"><b>PACO allows rapid creation and iteration of experimental trackers and interventions.</b></div> <div dir="ltr"><b><br> </b></div> <div dir="ltr"><b><span style="font-weight:normal">You can create a new mobile phone experiment in a matter of minutes on the PACO website. Once you save it, it is ready to download into the PACO Android app. You can keep your experiment designs private, share them with select groups of people, or with the world (Gmail logins for the moment). If you decide that an experimental input isn't quite right, just update it and then within a day the Android app will pick up the new definition.</span></b></div> <div dir="ltr"><b><span style="font-weight:normal"><br> </span></b></div> <div dir="ltr"><b>PACO uses a novel, but validated sampling technique known as Experiential Sampling.</b></div> <div dir="ltr"><br> </div> <div dir="ltr"><b><span style="font-weight:normal">Experiential Sampling was developed by Psychology researchers and has been used in 10s of 1000s of experiments over the last 40 years. It provides a much more accurate way to gather a sample of daily experience by pinging randomly over a period of time. However, PACO can also do more traditional sampling schedules if necessary.</span></b></div> <div dir="ltr"><b><span style="font-weight:normal"><br> </span></b></div> <div dir="ltr"> <div dir="ltr"><b>PACO allows users to easily explore and ask questions about their data.</b></div> <div dir="ltr"><br> </div> <div dir="ltr">PACO comes with a feature called, Explore Data, that guides the user through answering specific questions about their data. It offers a choice of questions about trends in the data, relationships in the data, and the distribution of the data. It allows the user to chart data across experiments as well to visualize any relationships that might exists between different data sets.</div> <div dir="ltr"><br> </div> <div dir="ltr"><br> </div> </div> <hr> <div style="font-weight:bold;font-size:25px;padding-bottom:.75em">PACO Examples</div> <div dir="ltr"><b><br> </b></div> <div dir="ltr"> <div dir="ltr">PACO is designed so that you can hear about a new medical study on the radio and then build a version for yourself in minutes.&nbsp;</div> <div dir="ltr"><br> </div> <div dir="ltr">Here are some types of "experiments" PACO can help you create:</div> <div dir="ltr"> <ul><li>Personal diet and wellness data</li> <ul><li>Example: You decide to practice healthy eating by following, say, the guidelines in Michael Pollan's&nbsp;<a href="http://michaelpollan.com/books/food-rules/">Food Rules</a>, and you want to see how well are following the program.&nbsp;&nbsp;With PACO and an Android phone you can easily create a personal "experiment" that will automatically ask you to rate your meal based on the three core food rules (Did you eat food? Was it mostly plants? Was it too much?) and help you track them. You can also easily add weight, blood pressure, cholesterol, etc., to the data you track and collect.</li> <li>Below are sample screen from Alberto's LowCarbTracker experiment:</li></ul></ul> </div> </div> <div dir="ltr"> <div style="display:block;margin-right:auto;margin-left:auto;text-align:center"> <img border="0" height="320" src="/images/LowCarbTrackerOnAndroid.png?height=320&amp;width=180" width="180"> <img border="0" height="320" src="/images/LowCarbTrackerDataScreen.png?height=320&amp;width=221" width="221"></div> <div style="display:block;text-align:left"><br> </div> </div> <div dir="ltr"><br> </div> <div dir="ltr"> <ul><li>Personal exercise or activity data</li> <ul><li>Example: You are a runner and you want to track not only how many miles you run each day but also, say, how you feel before, during and after a run. PACO makes it easy to create a study to collect, store and analyze this data.</li></ul></ul> <ul><li>Personal work data</li> <ul><li>Example: You would like to keep track of where you spend your time at work (34% of my time in meetings! Aaargh!) and how productive or passionate you are feeling about your work. &nbsp;The best way to collect this data is to use <a href="http://en.wikipedia.org/wiki/Experience_sampling_method">Experience Sampling Method</a> (ESM for short.) With PACO you can easily create a simple ESM study that will ask you at random times what you are doing and, say, if you are feeling productive and passionate at that particular time.</li></ul></ul> </div> </div> </div>
{'repo_name': 'google/paco', 'stars': '317', 'repo_language': 'Objective-C', 'file_name': 'InfoPlist.strings', 'mime_type': 'text/plain', 'hash': 8266123337261514186, 'source_dataset': 'data'}
<?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_IdentityToolkit_UploadAccountResponse extends Google_Collection { protected $collection_key = 'error'; protected $errorType = 'Google_Service_IdentityToolkit_UploadAccountResponseError'; protected $errorDataType = 'array'; public $kind; public function setError($error) { $this->error = $error; } public function getError() { return $this->error; } public function setKind($kind) { $this->kind = $kind; } public function getKind() { return $this->kind; } }
{'repo_name': 'FriendUPCloud/friendup', 'stars': '216', 'repo_language': 'C', 'file_name': 'filesystem_action_event.sql', 'mime_type': 'text/plain', 'hash': -4891084099270772748, 'source_dataset': 'data'}
package checkpoint import ( "github.com/docker/docker/api/server/httputils" "github.com/docker/docker/api/server/router" ) // checkpointRouter is a router to talk with the checkpoint controller type checkpointRouter struct { backend Backend decoder httputils.ContainerDecoder routes []router.Route } // NewRouter initializes a new checkpoint router func NewRouter(b Backend, decoder httputils.ContainerDecoder) router.Router { r := &checkpointRouter{ backend: b, decoder: decoder, } r.initRoutes() return r } // Routes returns the available routers to the checkpoint controller func (r *checkpointRouter) Routes() []router.Route { return r.routes } func (r *checkpointRouter) initRoutes() { r.routes = []router.Route{ router.Experimental(router.NewGetRoute("/containers/{name:.*}/checkpoints", r.getContainerCheckpoints)), router.Experimental(router.NewPostRoute("/containers/{name:.*}/checkpoints", r.postContainerCheckpoint)), router.Experimental(router.NewDeleteRoute("/containers/{name}/checkpoints/{checkpoint}", r.deleteContainerCheckpoint)), } }
{'repo_name': 'elastos/Elastos', 'stars': '101', 'repo_language': 'Go', 'file_name': 'codereview.cfg', 'mime_type': 'text/plain', 'hash': 6465201291446297458, 'source_dataset': 'data'}
/* Copyright 2017 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. */ // This file was automatically generated by lister-gen package v1 import ( "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" api "k8s.io/kubernetes/pkg/api" v1 "k8s.io/kubernetes/pkg/api/v1" ) // ServiceAccountLister helps list ServiceAccounts. type ServiceAccountLister interface { // List lists all ServiceAccounts in the indexer. List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) // ServiceAccounts returns an object that can list and get ServiceAccounts. ServiceAccounts(namespace string) ServiceAccountNamespaceLister ServiceAccountListerExpansion } // serviceAccountLister implements the ServiceAccountLister interface. type serviceAccountLister struct { indexer cache.Indexer } // NewServiceAccountLister returns a new ServiceAccountLister. func NewServiceAccountLister(indexer cache.Indexer) ServiceAccountLister { return &serviceAccountLister{indexer: indexer} } // List lists all ServiceAccounts in the indexer. func (s *serviceAccountLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1.ServiceAccount)) }) return ret, err } // ServiceAccounts returns an object that can list and get ServiceAccounts. func (s *serviceAccountLister) ServiceAccounts(namespace string) ServiceAccountNamespaceLister { return serviceAccountNamespaceLister{indexer: s.indexer, namespace: namespace} } // ServiceAccountNamespaceLister helps list and get ServiceAccounts. type ServiceAccountNamespaceLister interface { // List lists all ServiceAccounts in the indexer for a given namespace. List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) // Get retrieves the ServiceAccount from the indexer for a given namespace and name. Get(name string) (*v1.ServiceAccount, error) ServiceAccountNamespaceListerExpansion } // serviceAccountNamespaceLister implements the ServiceAccountNamespaceLister // interface. type serviceAccountNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all ServiceAccounts in the indexer for a given namespace. func (s serviceAccountNamespaceLister) List(selector labels.Selector) (ret []*v1.ServiceAccount, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1.ServiceAccount)) }) return ret, err } // Get retrieves the ServiceAccount from the indexer for a given namespace and name. func (s serviceAccountNamespaceLister) Get(name string) (*v1.ServiceAccount, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(api.Resource("serviceaccount"), name) } return obj.(*v1.ServiceAccount), nil }
{'repo_name': 'munnerz/keepalived-cloud-provider', 'stars': '143', 'repo_language': 'Go', 'file_name': 'config_test.go', 'mime_type': 'text/plain', 'hash': -5928937246552951855, 'source_dataset': 'data'}
<?xml version="1.0" encoding="GB2312"?> <rule> <readme><!-- 项目自述 --> <name>漏洞感知项目</name> <Initiator>Greekn--fplythoner</Initiator> <emailone>ms016@qq.com--980348599@qq.com</emailone> <content>主要帮助大家-记录一些重大漏洞-漏洞方面的细节</content> <version>v1.20</version> <github>https://github.com/greekn/rce-bug</github> </readme> <details><!--漏洞收集信息 --> <loopholename>Harmonic NSG 9000设备默认密码</loopholename><!-- 漏洞名称--> <loopholenumber>CVE-2018-14943</loopholenumber><!--漏洞编号 --> <loopholetype>默认密码</loopholetype><!--漏洞类型 --> <middleware>X</middleware><!--中间件 --> <defaultport>80</defaultport><!-- 默认开放端口--> <loopholecomponent>X</loopholecomponent><!--漏洞组件 --> <loopholefeatures>X</loopholefeatures><!-- 漏洞特征 --> <softwareversion>X</softwareversion><!--受影响组件版本号--> <pocurl>nsgadmin/nsgguest/nsgconfig/</pocurl><!--漏洞验证脚本网址 --> <expurl>X</expurl><!-- 漏洞利用脚本网址 --> <loopholedemourl></loopholedemourl><!-- 漏洞复现网址 --> <foakeyword>LICA</foakeyword><!--fofa资产搜索关键词 --> <zoomeyekeyword>LICA</zoomeyekeyword><!--钟馗之眼搜索关键词 --> <shodankeyword>LICA</shodankeyword><!-- shodan资产搜索关键词 --> <patchurl>X</patchurl><!--补丁网址 --> <bigdataassets>132</bigdataassets><!--大数据资产统计new--> <loopholeopentime>2018/8/5/</loopholeopentime><!--漏洞创建时间 --> <timeone></timeone><!-- 漏洞收集时间 --> <!--后面需要添加什么请联系上面邮箱 --> </details> <trackingnote><!-- 漏洞追踪描述--> <loopholetracking>中危</loopholetracking><!--漏洞追踪笔记--> <networkenvironment>内网</networkenvironment><!--网络环境new--> <attackvector>X</attackvector><!--攻击向量--> <loopholepocopen>公开</loopholepocopen><!--漏洞验证脚本是否公开 --> <loopholedetails>公开</loopholedetails><!-- 漏洞细节是否公开--> <cvss3.0>X</cvss3.0><!--漏洞评分--> <collector>Greekn</collector><!--漏洞收集人 --> <email>ms016@qq.com</email><!--漏洞收集人邮箱 --> <time>2018/8/5/</time><!-- 漏洞收集时间 --> <!--后面需要添加什么请联系上面邮箱 --> </trackingnote> </rule>
{'repo_name': 'greekn/rce-bug', 'stars': '205', 'repo_language': 'Python', 'file_name': 'CVE-2018-10088.xml', 'mime_type': 'text/xml', 'hash': -8146932653376275780, 'source_dataset': 'data'}
/* * SpanDSP - a series of DSP components for telephony * * private/sig_tone.h - Signalling tone processing for the 2280Hz, 2400Hz, 2600Hz * and similar signalling tones used in older protocols. * * Written by Steve Underwood <steveu@coppice.org> * * Copyright (C) 2004 Steve Underwood * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #if !defined(_SPANDSP_PRIVATE_SIG_TONE_H_) #define _SPANDSP_PRIVATE_SIG_TONE_H_ /*! \brief The coefficient set for a pair of cascaded bi-quads that make a signalling notch filter. */ typedef struct { #if defined(SPANDSP_USE_FIXED_POINT) int16_t a1[3]; int16_t b1[3]; int16_t a2[3]; int16_t b2[3]; int postscale; #else float a1[3]; float b1[3]; float a2[3]; float b2[3]; #endif } sig_tone_notch_coeffs_t; /*! \brief The coefficient set for a bi-quad that makes a signalling flat filter. Some signalling tone schemes require such a filter, and some don't. It is termed a flat filter, to distinguish it from the sharp filter, but obviously it is not actually flat. It is a broad band weighting filter. */ typedef struct { #if defined(SPANDSP_USE_FIXED_POINT) /*! \brief Flat mode bandpass bi-quad parameters */ int16_t a[3]; /*! \brief Flat mode bandpass bi-quad parameters */ int16_t b[3]; /*! \brief Post filter scaling */ int postscale; #else /*! \brief Flat mode bandpass bi-quad parameters */ float a[3]; /*! \brief Flat mode bandpass bi-quad parameters */ float b[3]; #endif } sig_tone_flat_coeffs_t; /*! signalling tone descriptor. This defines the working state for a single instance of the transmit and receive sides of a signalling tone processor. */ typedef struct { /*! \brief The tones used. */ int tone_freq[2]; /*! \brief The high and low tone amplitudes for each of the tones, in dBm0. */ int tone_amp[2][2]; /*! \brief The delay, in audio samples, before the high level tone drops to a low level tone. Some signalling protocols require the signalling tone be started at a high level, to ensure crisp initial detection at the receiver, but require the tone amplitude to drop by a number of dBs if it is sustained, to reduce crosstalk levels. */ int high_low_timeout; /*! \brief Some signalling tone detectors use a sharp initial filter, changing to a broader, flatter, filter after some delay. This parameter defines the delay. 0 means it never changes. */ int sharp_flat_timeout; /*! \brief Parameters to control the behaviour of the notch filter, used to remove the tone from the voice path in some protocols. The notch is applied as fast as possible, when the signalling tone is detected. Its removal is delayed by this timeout, to avoid clicky noises from repeated switching of the filter on rapid pulses of signalling tone. */ int notch_lag_time; /*! \brief The tone on persistence check, in audio samples. */ int tone_on_check_time; /*! \brief The tone off persistence check, in audio samples. */ int tone_off_check_time; /*! \brief The number of tones used. */ int tones; /*! \brief The coefficients for the cascaded bi-quads notch filter. */ const sig_tone_notch_coeffs_t *notch[2]; /*! \brief The coefficients for the single bi-quad flat mode filter. */ const sig_tone_flat_coeffs_t *flat; /*! \brief Minimum signalling tone to total power ratio, in dB */ int16_t detection_ratio; /*! \brief Minimum total power for detection in sharp mode, in dB */ int16_t sharp_detection_threshold; /*! \brief Minimum total power for detection in flat mode, in dB */ int16_t flat_detection_threshold; } sig_tone_descriptor_t; /*! Signalling tone transmit state */ struct sig_tone_tx_state_s { /*! \brief The callback function used to handle signalling changes. */ tone_report_func_t sig_update; /*! \brief A user specified opaque pointer passed to the callback function. */ void *user_data; /*! \brief Tone descriptor */ const sig_tone_descriptor_t *desc; /*! The phase rates for the one or two tones */ int32_t phase_rate[2]; /*! The phase accumulators for the one or two tones */ uint32_t phase_acc[2]; /*! The scaling values for the one or two tones, and the high and low level of each tone */ int16_t tone_scaling[2][2]; /*! The sample timer, used to switch between the high and low level tones. */ int high_low_timer; /*! \brief Current transmit tone */ int current_tx_tone; /*! \brief Current transmit timeout */ int current_tx_timeout; /*! \brief Time in current signalling state, in samples. */ int signalling_state_duration; }; /*! Signalling tone receive state */ struct sig_tone_rx_state_s { /*! \brief The callback function used to handle signalling changes. */ tone_report_func_t sig_update; /*! \brief A user specified opaque pointer passed to the callback function. */ void *user_data; /*! \brief Tone descriptor */ const sig_tone_descriptor_t *desc; /*! \brief The current receive tone */ int current_rx_tone; /*! \brief The timeout for switching from the high level to low level tone detector. */ int high_low_timer; /*! \brief ??? */ int current_notch_filter; struct { #if defined(SPANDSP_USE_FIXED_POINT) /*! \brief The z's for the notch filter */ int16_t notch_z1[2]; /*! \brief The z's for the notch filter */ int16_t notch_z2[2]; #else /*! \brief The z's for the notch filter */ float notch_z1[2]; /*! \brief The z's for the notch filter */ float notch_z2[2]; #endif /*! \brief The power output of the notch. */ power_meter_t power; } tone[3]; #if defined(SPANDSP_USE_FIXED_POINT) /*! \brief The z's for the weighting/bandpass filter. */ int16_t flat_z[2]; #else /*! \brief The z's for the weighting/bandpass filter. */ float flat_z[2]; #endif /*! \brief The output power of the flat (unfiltered or flat filtered) path. */ power_meter_t flat_power; /*! \brief Persistence check for tone present */ int tone_persistence_timeout; /*! \brief The tone pattern on the last audio sample */ int last_sample_tone_present; /*! \brief The minimum reading from the power meter for detection in flat mode */ int32_t flat_detection_threshold; /*! \brief The minimum reading from the power meter for detection in sharp mode */ int32_t sharp_detection_threshold; /*! \brief The minimum ratio between notched power and total power for detection */ int32_t detection_ratio; /*! \brief TRUE if in flat mode. FALSE if in sharp mode. */ int flat_mode; /*! \brief TRUE if the notch filter is enabled in the media path */ int notch_enabled; /*! \brief ??? */ int flat_mode_timeout; /*! \brief ??? */ int notch_insertion_timeout; /*! \brief ??? */ int signalling_state; /*! \brief ??? */ int signalling_state_duration; }; #endif /*- End of file ------------------------------------------------------------*/
{'repo_name': 'artclarke/xuggle-xuggler', 'stars': '328', 'repo_language': 'C', 'file_name': 'org.eclipse.cdt.ui.prefs', 'mime_type': 'text/plain', 'hash': 6390983815192495827, 'source_dataset': 'data'}
/* * Copyright (C) 2012 Andrew Neal 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.andrew.apollo.ui.activities; import static com.andrew.apollo.utils.MusicUtils.mService; import android.app.SearchManager; import android.app.SearchableInfo; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.media.AudioManager; import android.media.audiofx.AudioEffect; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.support.v4.view.ViewPager; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.widget.SearchView; import com.actionbarsherlock.widget.SearchView.OnQueryTextListener; import com.andrew.apollo.IApolloService; import com.andrew.apollo.MusicPlaybackService; import com.andrew.apollo.R; import com.andrew.apollo.adapters.PagerAdapter; import com.andrew.apollo.cache.ImageFetcher; import com.andrew.apollo.ui.fragments.LyricsFragment; import com.andrew.apollo.ui.fragments.QueueFragment; import com.andrew.apollo.utils.ApolloUtils; import com.andrew.apollo.utils.MusicUtils; import com.andrew.apollo.utils.MusicUtils.ServiceToken; import com.andrew.apollo.utils.NavUtils; import com.andrew.apollo.utils.ThemeUtils; import com.andrew.apollo.widgets.PlayPauseButton; import com.andrew.apollo.widgets.RepeatButton; import com.andrew.apollo.widgets.RepeatingImageButton; import com.andrew.apollo.widgets.ShuffleButton; import com.nineoldandroids.animation.ObjectAnimator; import java.lang.ref.WeakReference; /** * Apollo's "now playing" interface. * * @author Andrew Neal (andrewdneal@gmail.com) */ public class AudioPlayerActivity extends SherlockFragmentActivity implements ServiceConnection, OnSeekBarChangeListener { // Message to refresh the time private static final int REFRESH_TIME = 1; // The service token private ServiceToken mToken; // Play and pause button private PlayPauseButton mPlayPauseButton; // Repeat button private RepeatButton mRepeatButton; // Shuffle button private ShuffleButton mShuffleButton; // Previous button private RepeatingImageButton mPreviousButton; // Next button private RepeatingImageButton mNextButton; // Track name private TextView mTrackName; // Artist name private TextView mArtistName; // Album art private ImageView mAlbumArt; // Tiny artwork private ImageView mAlbumArtSmall; // Current time private TextView mCurrentTime; // Total time private TextView mTotalTime; // Queue switch private ImageView mQueueSwitch; // Progess private SeekBar mProgress; // Broadcast receiver private PlaybackStatus mPlaybackStatus; // Handler used to update the current time private TimeHandler mTimeHandler; // View pager private ViewPager mViewPager; // Pager adpater private PagerAdapter mPagerAdapter; // ViewPager container private FrameLayout mPageContainer; // Header private LinearLayout mAudioPlayerHeader; // Image cache private ImageFetcher mImageFetcher; // Theme resources private ThemeUtils mResources; private long mPosOverride = -1; private long mStartSeekPos = 0; private long mLastSeekEventTime; private boolean mIsPaused = false; private boolean mFromTouch = false; /** * {@inheritDoc} */ @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Title bar shows up in gingerbread, I'm too tired to figure out why. if (!ApolloUtils.hasHoneycomb()) { requestWindowFeature(Window.FEATURE_NO_TITLE); } // Initialze the theme resources mResources = new ThemeUtils(this); // Set the overflow style mResources.setOverflowStyle(this); // Fade it in overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); // Control the media volume setVolumeControlStream(AudioManager.STREAM_MUSIC); // Bind Apollo's service mToken = MusicUtils.bindToService(this, this); // Initialize the image fetcher/cache mImageFetcher = ApolloUtils.getImageFetcher(this); // Initialize the handler used to update the current time mTimeHandler = new TimeHandler(this); // Initialize the broadcast receiver mPlaybackStatus = new PlaybackStatus(this); // Theme the action bar final ActionBar actionBar = getSupportActionBar(); mResources.themeActionBar(actionBar, getString(R.string.app_name)); actionBar.setDisplayHomeAsUpEnabled(true); // Set the layout setContentView(R.layout.activity_player_base); // Cache all the items initPlaybackControls(); } /** * {@inheritDoc} */ @Override public void onServiceConnected(final ComponentName name, final IBinder service) { mService = IApolloService.Stub.asInterface(service); // Set the playback drawables updatePlaybackControls(); // Current info updateNowPlayingInfo(); // Update the favorites icon invalidateOptionsMenu(); } /** * {@inheritDoc} */ @Override public void onServiceDisconnected(final ComponentName name) { mService = null; } /** * {@inheritDoc} */ @Override public void onProgressChanged(final SeekBar bar, final int progress, final boolean fromuser) { if (!fromuser || mService == null) { return; } final long now = SystemClock.elapsedRealtime(); if (now - mLastSeekEventTime > 250) { mLastSeekEventTime = now; mPosOverride = MusicUtils.duration() * progress / 1000; MusicUtils.seek(mPosOverride); if (!mFromTouch) { // refreshCurrentTime(); mPosOverride = -1; } } } /** * {@inheritDoc} */ @Override public void onStartTrackingTouch(final SeekBar bar) { mLastSeekEventTime = 0; mFromTouch = true; } /** * {@inheritDoc} */ @Override public void onStopTrackingTouch(final SeekBar bar) { mPosOverride = -1; mFromTouch = false; } /** * {@inheritDoc} */ @Override public boolean onPrepareOptionsMenu(final Menu menu) { mResources.setFavoriteIcon(menu); // Hide the EQ option if it can't be opened final MenuItem effects = menu.findItem(R.id.menu_audio_player_equalizer); final Intent intent = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL); if (getPackageManager().resolveActivity(intent, 0) == null) { effects.setVisible(false); } return true; } /** * {@inheritDoc} */ @Override public boolean onCreateOptionsMenu(final Menu menu) { // Search view getSupportMenuInflater().inflate(R.menu.search, menu); // Theme the search icon mResources.setSearchIcon(menu); final SearchView searchView = (SearchView)menu.findItem(R.id.menu_search).getActionView(); // Add voice search final SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE); final SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName()); searchView.setSearchableInfo(searchableInfo); // Perform the search searchView.setOnQueryTextListener(new OnQueryTextListener() { @Override public boolean onQueryTextSubmit(final String query) { // Open the search activity NavUtils.openSearch(AudioPlayerActivity.this, query); return true; } @Override public boolean onQueryTextChange(final String newText) { // Nothing to do return false; } }); // Favorite action getSupportMenuInflater().inflate(R.menu.favorite, menu); // Shuffle all getSupportMenuInflater().inflate(R.menu.shuffle, menu); // Share, ringtone, and equalizer getSupportMenuInflater().inflate(R.menu.audio_player, menu); // Settings getSupportMenuInflater().inflate(R.menu.activity_base, menu); return true; } /** * {@inheritDoc} */ @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Go back to the home activity NavUtils.goHome(this); return true; case R.id.menu_shuffle: // Shuffle all the songs MusicUtils.shuffleAll(this); // Refresh the queue ((QueueFragment)mPagerAdapter.getFragment(0)).refreshQueue(); return true; case R.id.menu_favorite: // Toggle the current track as a favorite and update the menu // item MusicUtils.toggleFavorite(); invalidateOptionsMenu(); return true; case R.id.menu_audio_player_ringtone: // Set the current track as a ringtone MusicUtils.setRingtone(this, MusicUtils.getCurrentAudioId()); return true; case R.id.menu_audio_player_share: // Share the current meta data shareCurrentTrack(); return true; case R.id.menu_audio_player_equalizer: // Sound effects NavUtils.openEffectsPanel(this); return true; case R.id.menu_download_lyrics: updateLyrics(true); hideAlbumArt(); return true; case R.id.menu_settings: // Settings NavUtils.openSettings(this); return true; default: break; } return super.onOptionsItemSelected(item); } /** * {@inheritDoc} */ @Override public void onBackPressed() { super.onBackPressed(); NavUtils.goHome(this); } /** * {@inheritDoc} */ @Override protected void onResume() { super.onResume(); // Hide Apollo's notification MusicUtils.killForegroundService(this); // Set the playback drawables updatePlaybackControls(); // Current info updateNowPlayingInfo(); // Refresh the queue ((QueueFragment)mPagerAdapter.getFragment(0)).refreshQueue(); } /** * {@inheritDoc} */ @Override protected void onStart() { super.onStart(); final IntentFilter filter = new IntentFilter(); // Play and pause changes filter.addAction(MusicPlaybackService.PLAYSTATE_CHANGED); // Shuffle and repeat changes filter.addAction(MusicPlaybackService.SHUFFLEMODE_CHANGED); filter.addAction(MusicPlaybackService.REPEATMODE_CHANGED); // Track changes filter.addAction(MusicPlaybackService.META_CHANGED); // Update a list, probably the playlist fragment's filter.addAction(MusicPlaybackService.REFRESH); registerReceiver(mPlaybackStatus, filter); // Refresh the current time final long next = refreshCurrentTime(); queueNextRefresh(next); } /** * {@inheritDoc} */ @Override protected void onPause() { super.onPause(); // Show Apollo's notification if (MusicUtils.isPlaying() && ApolloUtils.isApplicationSentToBackground(this)) { MusicUtils.startBackgroundService(this); } mImageFetcher.flush(); } /** * {@inheritDoc} */ @Override protected void onDestroy() { super.onDestroy(); mIsPaused = false; mTimeHandler.removeMessages(REFRESH_TIME); // Unbind from the service if (mService != null) { MusicUtils.unbindFromService(mToken); mToken = null; } // Unregister the receiver try { unregisterReceiver(mPlaybackStatus); } catch (final Throwable e) { //$FALL-THROUGH$ } } /** * Initializes the items in the now playing screen */ @SuppressWarnings("deprecation") private void initPlaybackControls() { // ViewPager container mPageContainer = (FrameLayout)findViewById(R.id.audio_player_pager_container); // Theme the pager container background mPageContainer .setBackgroundDrawable(mResources.getDrawable("audio_player_pager_container")); // Now playing header mAudioPlayerHeader = (LinearLayout)findViewById(R.id.audio_player_header); // Opens the currently playing album profile mAudioPlayerHeader.setOnClickListener(mOpenAlbumProfile); // Used to hide the artwork and show the queue/lyrics final FrameLayout mSwitch = (FrameLayout)findViewById(R.id.audio_player_switch); mSwitch.setOnClickListener(mToggleHiddenPanel); // Initialize the pager adapter mPagerAdapter = new PagerAdapter(this); // Queue mPagerAdapter.add(QueueFragment.class, null); // Lyrics mPagerAdapter.add(LyricsFragment.class, null); // Initialize the ViewPager mViewPager = (ViewPager)findViewById(R.id.audio_player_pager); // Attch the adapter mViewPager.setAdapter(mPagerAdapter); // Offscreen pager loading limit mViewPager.setOffscreenPageLimit(mPagerAdapter.getCount() - 1); // Play and pause button mPlayPauseButton = (PlayPauseButton)findViewById(R.id.action_button_play); // Shuffle button mShuffleButton = (ShuffleButton)findViewById(R.id.action_button_shuffle); // Repeat button mRepeatButton = (RepeatButton)findViewById(R.id.action_button_repeat); // Previous button mPreviousButton = (RepeatingImageButton)findViewById(R.id.action_button_previous); // Next button mNextButton = (RepeatingImageButton)findViewById(R.id.action_button_next); // Track name mTrackName = (TextView)findViewById(R.id.audio_player_track_name); // Artist name mArtistName = (TextView)findViewById(R.id.audio_player_artist_name); // Album art mAlbumArt = (ImageView)findViewById(R.id.audio_player_album_art); // Small album art mAlbumArtSmall = (ImageView)findViewById(R.id.audio_player_switch_album_art); // Current time mCurrentTime = (TextView)findViewById(R.id.audio_player_current_time); // Total time mTotalTime = (TextView)findViewById(R.id.audio_player_total_time); // Used to show and hide the queue and lyrics fragments mQueueSwitch = (ImageView)findViewById(R.id.audio_player_switch_queue); // Theme the queue switch icon mQueueSwitch.setImageDrawable(mResources.getDrawable("btn_switch_queue")); // Progress mProgress = (SeekBar)findViewById(android.R.id.progress); // Set the repeat listner for the previous button mPreviousButton.setRepeatListener(mRewindListener); // Set the repeat listner for the next button mNextButton.setRepeatListener(mFastForwardListener); // Update the progress mProgress.setOnSeekBarChangeListener(this); } /** * Sets the track name, album name, and album art. */ private void updateNowPlayingInfo() { // Set the track name mTrackName.setText(MusicUtils.getTrackName()); // Set the artist name mArtistName.setText(MusicUtils.getArtistName()); // Set the total time mTotalTime.setText(MusicUtils.makeTimeString(this, MusicUtils.duration() / 1000)); // Set the album art mImageFetcher.loadCurrentArtwork(mAlbumArt); // Set the small artwork mImageFetcher.loadCurrentArtwork(mAlbumArtSmall); // Update the current time queueNextRefresh(1); } /** * Sets the correct drawable states for the playback controls. */ private void updatePlaybackControls() { // Set the play and pause image mPlayPauseButton.updateState(); // Set the shuffle image mShuffleButton.updateShuffleState(); // Set the repeat image mRepeatButton.updateRepeatState(); } /** * Refreshes the lyrics and moves the view pager to the lyrics fragment. */ public void updateLyrics(final boolean force) { ((LyricsFragment)mPagerAdapter.getFragment(1)).fetchLyrics(force); if (force && mViewPager.getCurrentItem() != 1) { mViewPager.setCurrentItem(1, true); } } /** * @param delay When to update */ private void queueNextRefresh(final long delay) { if (!mIsPaused) { final Message message = mTimeHandler.obtainMessage(REFRESH_TIME); mTimeHandler.removeMessages(REFRESH_TIME); mTimeHandler.sendMessageDelayed(message, delay); } } /** * Used to scan backwards in time through the curren track * * @param repcnt The repeat count * @param delta The long press duration */ private void scanBackward(final int repcnt, long delta) { if (mService == null) { return; } if (repcnt == 0) { mStartSeekPos = MusicUtils.position(); mLastSeekEventTime = 0; } else { if (delta < 5000) { // seek at 10x speed for the first 5 seconds delta = delta * 10; } else { // seek at 40x after that delta = 50000 + (delta - 5000) * 40; } long newpos = mStartSeekPos - delta; if (newpos < 0) { // move to previous track MusicUtils.previous(this); final long duration = MusicUtils.duration(); mStartSeekPos += duration; newpos += duration; } if (delta - mLastSeekEventTime > 250 || repcnt < 0) { MusicUtils.seek(newpos); mLastSeekEventTime = delta; } if (repcnt >= 0) { mPosOverride = newpos; } else { mPosOverride = -1; } refreshCurrentTime(); } } /** * Used to scan forwards in time through the curren track * * @param repcnt The repeat count * @param delta The long press duration */ private void scanForward(final int repcnt, long delta) { if (mService == null) { return; } if (repcnt == 0) { mStartSeekPos = MusicUtils.position(); mLastSeekEventTime = 0; } else { if (delta < 5000) { // seek at 10x speed for the first 5 seconds delta = delta * 10; } else { // seek at 40x after that delta = 50000 + (delta - 5000) * 40; } long newpos = mStartSeekPos + delta; final long duration = MusicUtils.duration(); if (newpos >= duration) { // move to next track MusicUtils.next(); mStartSeekPos -= duration; // is OK to go negative newpos -= duration; } if (delta - mLastSeekEventTime > 250 || repcnt < 0) { MusicUtils.seek(newpos); mLastSeekEventTime = delta; } if (repcnt >= 0) { mPosOverride = newpos; } else { mPosOverride = -1; } refreshCurrentTime(); } } /* Used to update the current time string */ private long refreshCurrentTime() { if (mService == null) { return 500; } try { final long pos = mPosOverride < 0 ? MusicUtils.position() : mPosOverride; if (pos >= 0 && MusicUtils.duration() > 0) { mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000)); final int progress = (int)(1000 * pos / MusicUtils.duration()); mProgress.setProgress(progress); if (MusicUtils.isPlaying()) { mCurrentTime.setVisibility(View.VISIBLE); } else { // blink the counter final int vis = mCurrentTime.getVisibility(); mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE); return 500; } } else { mCurrentTime.setText("--:--"); mProgress.setProgress(1000); } // calculate the number of milliseconds until the next full second, // so // the counter can be updated at just the right time final long remaining = 1000 - pos % 1000; // approximate how often we would need to refresh the slider to // move it smoothly int width = mProgress.getWidth(); if (width == 0) { width = 320; } final long smoothrefreshtime = MusicUtils.duration() / width; if (smoothrefreshtime > remaining) { return remaining; } if (smoothrefreshtime < 20) { return 20; } return smoothrefreshtime; } catch (final Exception ignored) { } return 500; } /** * @param v The view to animate * @param alpha The alpha to apply */ private void fade(final View v, final float alpha) { final ObjectAnimator fade = ObjectAnimator.ofFloat(v, "alpha", alpha); fade.setInterpolator(AnimationUtils.loadInterpolator(this, android.R.anim.accelerate_decelerate_interpolator)); fade.setDuration(400); fade.start(); } /** * Called to show the album art and hide the queue/lyrics */ private void showAlbumArt() { mPageContainer.setVisibility(View.INVISIBLE); mAlbumArtSmall.setVisibility(View.GONE); mQueueSwitch.setVisibility(View.VISIBLE); // Fade out the pager container fade(mPageContainer, 0f); // Fade in the album art fade(mAlbumArt, 1f); } /** * Called to hide the album art and show the queue/lyrics */ public void hideAlbumArt() { mPageContainer.setVisibility(View.VISIBLE); mQueueSwitch.setVisibility(View.GONE); mAlbumArtSmall.setVisibility(View.VISIBLE); // Fade out the artwork fade(mAlbumArt, 0f); // Fade in the pager container fade(mPageContainer, 1f); } /** * /** Used to shared what the user is currently listening to */ private void shareCurrentTrack() { if (MusicUtils.getTrackName() == null || MusicUtils.getArtistName() == null) { return; } final Intent shareIntent = new Intent(); final String shareMessage = getString(R.string.now_listening_to) + " " + MusicUtils.getTrackName() + " " + getString(R.string.by) + " " + MusicUtils.getArtistName() + " " + getString(R.string.hash_apollo); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_track_using))); } /** * Used to scan backwards through the track */ private final RepeatingImageButton.RepeatListener mRewindListener = new RepeatingImageButton.RepeatListener() { /** * {@inheritDoc} */ @Override public void onRepeat(final View v, final long howlong, final int repcnt) { scanBackward(repcnt, howlong); } }; /** * Used to scan ahead through the track */ private final RepeatingImageButton.RepeatListener mFastForwardListener = new RepeatingImageButton.RepeatListener() { /** * {@inheritDoc} */ @Override public void onRepeat(final View v, final long howlong, final int repcnt) { scanForward(repcnt, howlong); } }; /** * Switches from the large album art screen to show the queue and lyric * fragments, then back again */ private final OnClickListener mToggleHiddenPanel = new OnClickListener() { /** * {@inheritDoc} */ @Override public void onClick(final View v) { if (mPageContainer.getVisibility() == View.VISIBLE) { // Open the current album profile mAudioPlayerHeader.setOnClickListener(mOpenAlbumProfile); // Show the artwork, hide the queue and lyrics showAlbumArt(); } else { // Scroll to the current track mAudioPlayerHeader.setOnClickListener(mScrollToCurrentSong); // Show the queue and lyrics, hide the artwork hideAlbumArt(); } } }; /** * Opens to the current album profile */ private final OnClickListener mOpenAlbumProfile = new OnClickListener() { @Override public void onClick(final View v) { NavUtils.openAlbumProfile(AudioPlayerActivity.this, MusicUtils.getAlbumName(), MusicUtils.getArtistName()); } }; /** * Scrolls the queue to the currently playing song */ private final OnClickListener mScrollToCurrentSong = new OnClickListener() { @Override public void onClick(final View v) { ((QueueFragment)mPagerAdapter.getFragment(0)).scrollToCurrentSong(); } }; /** * Used to update the current time string */ private static final class TimeHandler extends Handler { private final WeakReference<AudioPlayerActivity> mAudioPlayer; /** * Constructor of <code>TimeHandler</code> */ public TimeHandler(final AudioPlayerActivity player) { mAudioPlayer = new WeakReference<AudioPlayerActivity>(player); } @Override public void handleMessage(final Message msg) { switch (msg.what) { case REFRESH_TIME: final long next = mAudioPlayer.get().refreshCurrentTime(); mAudioPlayer.get().queueNextRefresh(next); break; default: break; } } }; /** * Used to monitor the state of playback */ private static final class PlaybackStatus extends BroadcastReceiver { private final WeakReference<AudioPlayerActivity> mReference; /** * Constructor of <code>PlaybackStatus</code> */ public PlaybackStatus(final AudioPlayerActivity activity) { mReference = new WeakReference<AudioPlayerActivity>(activity); } /** * {@inheritDoc} */ @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (action.equals(MusicPlaybackService.META_CHANGED)) { // Current info mReference.get().updateNowPlayingInfo(); // Update the favorites icon mReference.get().invalidateOptionsMenu(); // Update the lyrics mReference.get().updateLyrics(false); } else if (action.equals(MusicPlaybackService.PLAYSTATE_CHANGED)) { // Set the play and pause image mReference.get().mPlayPauseButton.updateState(); } else if (action.equals(MusicPlaybackService.REPEATMODE_CHANGED) || action.equals(MusicPlaybackService.SHUFFLEMODE_CHANGED)) { // Set the repeat image mReference.get().mRepeatButton.updateRepeatState(); // Set the shuffle image mReference.get().mShuffleButton.updateShuffleState(); } } } }
{'repo_name': 'adneal/Apollo-CM', 'stars': '192', 'repo_language': 'Java', 'file_name': 'notification_template_expanded_base.xml', 'mime_type': 'text/xml', 'hash': -3348822399850986184, 'source_dataset': 'data'}
const ghpages = require('../../lib/index'); const sinon = require('sinon'); const cli = require('../../bin/gh-pages'); const assert = require('../helper').assert; const beforeAdd = require('./fixtures/beforeAdd'); describe('gh-pages', () => { describe('main', () => { beforeEach(() => { sinon .stub(ghpages, 'publish') .callsFake((basePath, config, callback) => callback()); }); afterEach(() => { ghpages.publish.restore(); }); const scenarios = [ { args: ['--dist', 'lib'], dist: 'lib', config: ghpages.defaults }, { args: ['--dist', 'lib', '-n'], dist: 'lib', config: {push: false} }, { args: ['--dist', 'lib', '-f'], dist: 'lib', config: {history: false} }, { args: ['--dist', 'lib', '-x'], dist: 'lib', config: {silent: true} }, { args: ['--dist', 'lib', '--dotfiles'], dist: 'lib', config: {dotfiles: true} }, { args: ['--dist', 'lib', '--dest', 'target'], dist: 'lib', config: {dest: 'target'} }, { args: ['--dist', 'lib', '-a', 'target'], dist: 'lib', config: {add: true} }, { args: ['--dist', 'lib', '--git', 'path/to/git'], dist: 'lib', config: {git: 'path/to/git'} }, { args: ['--dist', 'lib', '--user', 'Full Name <email@example.com>'], dist: 'lib', config: {user: {name: 'Full Name', email: 'email@example.com'}} }, { args: ['--dist', 'lib', '--user', 'email@example.com'], dist: 'lib', config: {user: {name: null, email: 'email@example.com'}} }, { args: ['--dist', 'lib', '-u', 'Full Name <email@example.com>'], dist: 'lib', config: {user: {name: 'Full Name', email: 'email@example.com'}} }, { args: [ '--dist', 'lib', '--before-add', require.resolve('./fixtures/beforeAdd') ], dist: 'lib', config: {beforeAdd} }, { args: ['--dist', 'lib', '-u', 'junk email'], dist: 'lib', error: 'Could not parse name and email from user option "junk email" (format should be "Your Name <email@example.com>")' } ]; scenarios.forEach(({args, dist, config, error}) => { let title = args.join(' '); if (error) { title += ' (user error)'; } it(title, done => { cli(['node', 'gh-pages'].concat(args)) .then(() => { if (error) { done(new Error(`Expected error "${error}" but got success`)); return; } sinon.assert.calledWithMatch(ghpages.publish, dist, config); done(); }) .catch(err => { if (!error) { done(err); return; } assert.equal(err.message, error); done(); }); }); }); }); });
{'repo_name': 'tschaub/gh-pages', 'stars': '2207', 'repo_language': 'JavaScript', 'file_name': 'changelog.sh', 'mime_type': 'text/x-shellscript', 'hash': -1396131565176612456, 'source_dataset': 'data'}
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package einterfaces import ( "github.com/mattermost/mattermost-server/v5/model" ) type ComplianceInterface interface { StartComplianceDailyJob() RunComplianceJob(job *model.Compliance) *model.AppError }
{'repo_name': 'mattermost/mattermost-server', 'stars': '18594', 'repo_language': 'Go', 'file_name': 'export.go', 'mime_type': 'text/plain', 'hash': -6049484360631645344, 'source_dataset': 'data'}
# Build Emacs from a fresh tarball or version-control checkout. # Copyright (C) 2011-2017 Free Software Foundation, Inc. # # This file is part of GNU Emacs. # # GNU Emacs 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. # # GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>. # # written by Paul Eggert # This GNUmakefile is for GNU Make. It is for convenience, so that # one can run 'make' in an unconfigured source tree. In such a tree, # this file causes GNU Make to first create a standard configuration # with the default options, and then reinvokes itself on the # newly-built Makefile. If the source tree is already configured, # this file defers to the existing Makefile. # If you are using a non-GNU 'make', or if you want non-default build # options, or if you want to build in an out-of-source tree, please # run "configure" by hand. But run autogen.sh first, if the source # was checked out directly from the repository. # If a Makefile already exists, just use it. ifeq ($(wildcard Makefile),Makefile) include Makefile else # If cleaning and Makefile does not exist, don't bother creating it. # The source tree is already clean, or is in a weird state that # requires expert attention. ifeq ($(filter-out %clean,$(or $(MAKECMDGOALS),default)),) $(MAKECMDGOALS): @echo >&2 'No Makefile; skipping $@.' else # No Makefile, and not cleaning. # If 'configure' does not exist, Emacs must have been checked # out directly from the repository; run ./autogen.sh. # Once 'configure' exists, run it. # Finally, run the actual 'make'. ORDINARY_GOALS = $(filter-out configure Makefile bootstrap,$(MAKECMDGOALS)) default $(ORDINARY_GOALS): Makefile $(MAKE) -f Makefile $(MAKECMDGOALS) # Execute in sequence, so that multiple user goals don't conflict. .NOTPARALLEL: configure: @echo >&2 'There seems to be no "configure" file in this directory.' @echo >&2 'Running ./autogen.sh ...' ./autogen.sh @echo >&2 '"configure" file built.' Makefile: configure @echo >&2 'There seems to be no Makefile in this directory.' @echo >&2 'Running ./configure ...' ./configure @echo >&2 'Makefile built.' # 'make bootstrap' in a fresh checkout needn't run 'configure' twice. bootstrap: Makefile $(MAKE) -f Makefile all .PHONY: bootstrap default $(ORDINARY_GOALS) endif endif
{'repo_name': 'aquamacs-emacs/aquamacs-emacs', 'stars': '365', 'repo_language': 'Emacs Lisp', 'file_name': 'tex-ref.tex', 'mime_type': 'text/x-tex', 'hash': -4013942956781006452, 'source_dataset': 'data'}
fileFormatVersion: 2 guid: 9dbe0eee945399346bf4dcec3bdf72bf timeCreated: 1436617353 licenseType: Free MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{'repo_name': 'devdogio/Inventory-Pro', 'stars': '449', 'repo_language': 'C#', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': 167867769167279281, 'source_dataset': 'data'}
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google 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. // Author: kenton@google.com (Kenton Varda) // // emulates google3/base/once.h // // This header is intended to be included only by internal .cc files and // generated .pb.cc files. Users should not use this directly. #include <google/protobuf/stubs/once.h> #ifndef GOOGLE_PROTOBUF_NO_THREAD_SAFETY #ifdef _WIN32 #include <windows.h> #else #include <sched.h> #endif #include <google/protobuf/stubs/atomicops.h> namespace google { namespace protobuf { namespace { void SchedYield() { #ifdef _WIN32 Sleep(0); #else // POSIX sched_yield(); #endif } } // namespace void GoogleOnceInitImpl(ProtobufOnceType* once, Closure* closure) { internal::AtomicWord state = internal::Acquire_Load(once); // Fast path. The provided closure was already executed. if (state == ONCE_STATE_DONE) { return; } // The closure execution did not complete yet. The once object can be in one // of the two following states: // - UNINITIALIZED: We are the first thread calling this function. // - EXECUTING_CLOSURE: Another thread is already executing the closure. // // First, try to change the state from UNINITIALIZED to EXECUTING_CLOSURE // atomically. state = internal::Acquire_CompareAndSwap( once, ONCE_STATE_UNINITIALIZED, ONCE_STATE_EXECUTING_CLOSURE); if (state == ONCE_STATE_UNINITIALIZED) { // We are the first thread to call this function, so we have to call the // closure. closure->Run(); internal::Release_Store(once, ONCE_STATE_DONE); } else { // Another thread has already started executing the closure. We need to // wait until it completes the initialization. while (state == ONCE_STATE_EXECUTING_CLOSURE) { // Note that futex() could be used here on Linux as an improvement. SchedYield(); state = internal::Acquire_Load(once); } } } } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_NO_THREAD_SAFETY
{'repo_name': 'linkingvision/rapidvms', 'stars': '351', 'repo_language': 'C++', 'file_name': 'SQLite_vs100.vcxproj.filters', 'mime_type': 'text/xml', 'hash': 1733124773751320330, 'source_dataset': 'data'}
using System; using System.Collections.Generic; using System.IO; using i18n.Domain.Abstract; namespace i18n.Domain.Tests { public class SettingService_Mock : AbstractSettingService { private readonly IDictionary<string, string> _settings = new Dictionary<string, string>(); public SettingService_Mock() : base(String.Empty) { } public override string GetConfigFileLocation() { //TODO get exec location return Path.Combine(Directory.GetCurrentDirectory(), "SettingService_Mock.cs"); } public override string GetSetting(string key) { if (_settings.ContainsKey(key)) return _settings[key]; return null; } public override void SetSetting(string key, string value) { if (!_settings.ContainsKey(key)) _settings.Add(key, value); else _settings[key] = value; } public override void RemoveSetting(string key) { if (_settings.ContainsKey(key)) _settings.Remove(key); } } }
{'repo_name': 'turquoiseowl/i18n', 'stars': '518', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': 2536765010087266441, 'source_dataset': 'data'}
using System; using System.Data; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; namespace Serenity.Data { public sealed class SingleField : GenericValueField<Single> { public SingleField(ICollection<Field> collection, string name, LocalText caption = null, int size = 0, FieldFlags flags = FieldFlags.Default, Func<Row, Single?> getValue = null, Action<Row, Single?> setValue = null) : base(collection, FieldType.Single, name, caption, size, flags, getValue, setValue) { } public static SingleField Factory(ICollection<Field> collection, string name, LocalText caption, int size, FieldFlags flags, Func<Row, Single?> getValue, Action<Row, Single?> setValue) { return new SingleField(collection, name, caption, size, flags, getValue, setValue); } public override void GetFromReader(IDataReader reader, int index, Row row) { if (reader == null) throw new ArgumentNullException("reader"); var value = reader.GetValue(index); if (value is DBNull) _setValue(row, null); else if (value is Single) _setValue(row, (Single)value); else _setValue(row, Convert.ToSingle(value, CultureInfo.InvariantCulture)); if (row.tracking) row.FieldAssignedValue(this); } public override void ValueToJson(JsonWriter writer, Row row, JsonSerializer serializer) { writer.WriteValue(_getValue(row)); } public override void ValueFromJson(JsonReader reader, Row row, JsonSerializer serializer) { if (reader == null) throw new ArgumentNullException("reader"); switch (reader.TokenType) { case JsonToken.Null: case JsonToken.Undefined: _setValue(row, null); break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: _setValue(row, Convert.ToSingle(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.String: var s = ((string)reader.Value).TrimToNull(); if (s == null) _setValue(row, null); else _setValue(row, Convert.ToSingle(s, CultureInfo.InvariantCulture)); break; default: throw JsonUnexpectedToken(reader); } if (row.tracking) row.FieldAssignedValue(this); } } }
{'repo_name': 'volkanceylan/Serenity', 'stars': '1950', 'repo_language': 'C#', 'file_name': 'CreateDatabase.sql', 'mime_type': 'text/plain', 'hash': 1070979346771988661, 'source_dataset': 'data'}
package edu.knowitall.srlie import edu.knowitall.collection.immutable.Interval import scala.util.control.Exception import edu.knowitall.tool.parse.graph.DependencyNode import edu.knowitall.tool.srl.Role import edu.knowitall.tool.srl.Frame import edu.knowitall.tool.parse.graph.DependencyGraph import edu.knowitall.tool.srl.Roles import edu.knowitall.collection.immutable.graph.Graph.Edge import edu.knowitall.collection.immutable.graph.DirectedEdge import edu.knowitall.collection.immutable.graph.Direction import edu.knowitall.tool.srl.Roles.R import edu.knowitall.tool.srl.FrameHierarchy import edu.knowitall.collection.immutable.graph.UpEdge import edu.knowitall.collection.immutable.graph.Graph import edu.knowitall.srlie.SrlExtraction._ import scala.collection.immutable.SortedSet import edu.knowitall.tool.tokenize.Token import edu.knowitall.tool.tokenize.Tokenizer case class SrlExtraction(relation: Relation, arg1: Argument, arg2s: Seq[Argument], context: Option[Context], negated: Boolean) { def rel = relation def relationArgument = { if (this.active) { this.arg2s.find(arg2 => arg2.role == Roles.A1 || arg2.role == Roles.A2) } else if (this.passive) { this.arg2s.find(_.role == Roles.A2) } else { None } } def intervals = (arg1.interval +: relation.intervals) ++ arg2s.map(_.interval) def tokens = relation.tokens ++ arg1.tokens ++ arg2s.flatMap(_.tokens) private val bePresentVerbs = Set("am", "are", "is") private val bePastVerbs = Set("was", "were") private val beVerbs = bePastVerbs ++ bePresentVerbs def transformations(transformations: Transformation*): Seq[SrlExtraction] = { def passiveDobj = { for { a1 <- arg2s.find(_.role == Roles.A1).toSeq a2 <- arg2s.find(_.role == Roles.A2) if a1.tokens.exists(token => token.isNoun || token.isPronoun) if a2.tokens.exists(token => token.isNoun || token.isPronoun) a0 = arg1 if a0.role == Roles.A0 if !this.context.isDefined } yield { // val a0New = new Argument("[by] " + a0.text, a0.tokens, a0.interval, a0.role) val arg2s = /* a0New +: */ this.arg2s.filterNot(_ == a1) val inferred = if (this.rel.tokens.exists(token => token.text == "has" || token.text == "have")) { "[been]" } else if (arg1.plural) { "[were]" } else { "[was]" } val (before, after) = this.rel.tokens.filter { token => !beVerbs.contains(token.text) }.span(node => node.postag == "MD" || node.text == "has" || node.text == "have") val text = Iterable(before.iterator.map(_.text), Iterable(inferred), after.iterator.map(_.text)).flatten.mkString(" ") val rel = new Relation(text, this.rel.sense, this.rel.tokens, this.rel.intervals) SrlExtraction(rel, a1, arg2s, context, negated) } } if (transformations.contains(PassiveDobj)) { passiveDobj } else { Seq.empty } } def triplize(includeDobj: Boolean = true): Seq[SrlExtraction] = { val relArg = if (includeDobj) this.relationArgument else None val filteredArg2s = (arg2s filterNot (arg2 => relArg.exists(_ == arg2))) val tripleExtrs = if (filteredArg2s.isEmpty) { Seq(this) } else { val extrs = relArg match { case Some(relArg) => arg2s.map { arg2 => val rel = if (arg2 == relArg) { relation } else { val tokens = (relation.tokens ++ relArg.tokens).sortBy(_.tokenInterval) val text = relation.text + " " + relArg.tokens.iterator.map(_.text).mkString(" ") relation.copy(text = text, tokens = tokens, intervals = relation.intervals :+ relArg.interval) } new SrlExtraction(rel, this.arg1, Seq(arg2), context, negated) } case None => filteredArg2s.map { arg2 => new SrlExtraction(rel, this.arg1, Seq(arg2), context, negated) } } // don't include dobj if we create any intransitives if (extrs exists (_.intransitive)) { this.triplize(false) } else { extrs } } tripleExtrs.filter { extr => // filter extractions where the rel overlaps the arg2 extr.arg2s.forall(arg2 => extr.rel.intervals.forall(relInterval => !(arg2.interval intersects relInterval))) }.flatMap { extr => // move preposition to relation if it leads the arg2 extr.arg2s match { case Seq(arg2) if arg2.hasLeadingPreposition => // since we are removing text and tokens from the arg2, // we might violate a requirement that the text and the // number of tokens is non empty. Exception.catching(classOf[Exception]).opt(arg2.withoutLeadingPreposition).map { newArg2 => val leadingPreposition = arg2.leadingPrepositionToken.get val newRel = extr.rel.copy( text = extr.rel.text + " " + leadingPreposition.text, tokens = extr.rel.tokens :+ leadingPreposition, intervals = extr.rel.intervals :+ Interval.singleton(arg2.interval.start) ) extr.copy(relation = newRel, arg2s = Seq(newArg2)) } case _ => Some(extr) } // make sure the arg2 still contains tokens }.filter { extr => extr.arg2s.forall(!_.tokens.isEmpty) } } def basicTripleString = { Iterable(arg1.text, relation.text, arg2s.iterator.map(_.text).mkString("; ")).mkString("(", "; ", ")") } override def toString = { val parts = Iterable(arg1.toString, relation.toString, arg2s.iterator.map(_.toString).mkString("; ")) val prefix = context match { case Some(context) => context.text + ":" case None => "" } prefix + parts.mkString("(", "; ", ")") } def intransitive = arg2s.isEmpty // an extraction is active if A0 is the first A* def active = !intransitive && this.arg1.role == Roles.A0 // an extraction is active if it's not passive def passive = !intransitive && !active } object SrlExtraction { case class Sense(name: String, id: String) sealed abstract class Transformation case object PassiveDobj extends Transformation def create(relation: Relation, arguments: Seq[Argument], context: Option[Context], negated: Boolean) = { val arg1 = arguments.find(arg => (arg.role.label matches "A\\d+") && (relation.intervals.forall(interval => arg.interval leftOf interval))).getOrElse { throw new IllegalArgumentException("Extraction has no arg1.") } // look for potential arguments that are right of the relation val rightArg2s = arguments.filter { arg => relation.intervals.forall(interval => arg.interval rightOf interval) } ++ arguments.filter { arg => !relation.intervals.forall(interval => arg.interval rightOf interval) && (arg.role == Roles.AM_TMP || arg.role == Roles.AM_LOC) } val arg2s = // if we didn't find any, use any prime arguments that were found if (rightArg2s.isEmpty) { arguments.filter(arg => arg != arg1 && (arg.role.label matches "A\\d+")) } else { rightArg2s } new SrlExtraction(relation, arg1, arg2s, context, negated) } abstract class Part { def text: String def tokens: Seq[DependencyNode] def tokenSpan: Interval require(!text.isEmpty, "Extraction part text may not be empty.") require(!tokens.isEmpty, "Extraction part tokens may not be empty.") // require(tokens.sorted == tokens) } abstract class MultiPart extends Part { def intervals: Seq[Interval] def span = Interval.span(intervals) def tokenIntervals = intervals def tokenSpan = span override def hashCode = intervals.hashCode * 39 + tokens.hashCode def canEqual(that: Any): Boolean = that.isInstanceOf[MultiPart] override def equals(that: Any): Boolean = that match { case that: MultiPart => ( that.canEqual(this) && this.text == that.text && this.tokens == that.tokens && this.intervals == that.intervals ) case _ => false } } abstract class SinglePart extends Part { def interval: Interval def tokenInterval = interval def tokenSpan = tokenInterval def offsets = Interval.open( this.tokens.head.offsets.start, this.tokens.last.offsets.end ) } class Context(val text: String, val tokens: Seq[DependencyNode], val intervals: Seq[Interval]) extends MultiPart { override def toString = text override def canEqual(that: Any): Boolean = that.isInstanceOf[Context] override def equals(that: Any): Boolean = that match { case that: Context => ( that.canEqual(this) && this.text == that.text && this.tokens == that.tokens && this.intervals == that.intervals ) case _ => false } override def hashCode(): Int = { val state = Seq(text, tokens, intervals) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) } } abstract class Argument extends SinglePart { def text: String def tokens: Seq[DependencyNode] def interval: Interval def role: Role override def toString = text def plural = tokens.exists { token => token.isPluralNoun } def hasLeadingPreposition: Boolean = { leadingPrepositionToken.isDefined } def leadingPrepositionToken: Option[DependencyNode] = { tokens.headOption.filter { head => head.postag == "IN" || head.postag == "TO" } } def withoutLeadingPreposition: Argument = { if (!leadingPrepositionToken.isDefined) { this } else { new SimpleArgument(tokens.drop(1), Interval.open(interval.start + 1, interval.end), role) } } } abstract class SemanticArgument extends Argument case class SimpleArgument(val text: String, val tokens: Seq[DependencyNode], val interval: Interval, val role: Role) extends Argument { def this(tokens: Seq[DependencyNode], interval: Interval, role: Role) = this(Tokenizer.originalText(tokens).trim, tokens, interval, role) override def toString = text } case class TemporalArgument(val text: String, val tokens: Seq[DependencyNode], val interval: Interval, val role: Role) extends SemanticArgument { def this(tokens: Seq[DependencyNode], interval: Interval, role: Role) = this(Tokenizer.originalText(tokens).trim, tokens, interval, role) override def toString = "T:" + super.toString override def withoutLeadingPreposition: TemporalArgument = { if (!leadingPrepositionToken.isDefined) { this } else { new TemporalArgument(tokens.drop(1), Interval.open(interval.start + 1, interval.end), role) } } } case class LocationArgument(val text: String, val tokens: Seq[DependencyNode], val interval: Interval, val role: Role) extends SemanticArgument { def this(tokens: Seq[DependencyNode], interval: Interval, role: Role) = this(Tokenizer.originalText(tokens).trim, tokens, interval, role) override def toString = "L:" + super.toString override def withoutLeadingPreposition: LocationArgument = { if (!leadingPrepositionToken.isDefined) { this } else { new LocationArgument(tokens.drop(1), Interval.open(interval.start + 1, interval.end), role) } } } case class Relation(text: String, sense: Option[Sense], tokens: Seq[DependencyNode], intervals: Seq[Interval]) extends MultiPart { // make sure all the intervals are disjoint try { require(intervals.forall(x => !intervals.exists(y => x != y && (x intersects y)))) } catch { case e: Exception => System.out.println("Panic on line: " + text) } override def toString = text override def canEqual(that: Any): Boolean = that.isInstanceOf[Relation] override def equals(that: Any): Boolean = that match { case that: Relation => ( that.canEqual(this) && this.text == that.text && this.sense == that.sense && this.tokens == that.tokens && this.intervals == that.intervals ) case _ => false } def concat(other: Relation) = { Relation(this.text + " " + other.text, None, this.tokens ++ other.tokens, this.intervals ++ other.intervals) } override def hashCode(): Int = { val state = Seq(text, sense, tokens, intervals) state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b) } } object Relation { val expansionLabels = Set("advmod", "neg", "aux", "cop", "auxpass", "prt", "acomp") } def contiguousAdjacent(graph: DependencyGraph, node: DependencyNode, cond: DirectedEdge[DependencyNode] => Boolean, until: Set[DependencyNode]) = { def takeAdjacent(interval: Interval, nodes: List[DependencyNode], pool: List[DependencyNode]): List[DependencyNode] = pool match { // can we add the top node? case head :: tail if (head.indices borders interval) && !until.contains(head) => takeAdjacent(interval union head.indices, head :: nodes, tail) // otherwise abort case _ => nodes } val inferiors = graph.graph.connected(node, dedge => cond(dedge) && !(until contains dedge.end)) val span = Interval.span(inferiors.map(_.indices)) val contiguous = graph.nodes.drop(span.start).take(span.length).toList.sorted // split into nodes left and right of node val lefts = contiguous.takeWhile(_ != node).reverse val rights = contiguous.dropWhile(_ != node).drop(1) // take adjacent nodes from each list val withLefts = takeAdjacent(node.indices, List(node), lefts) val expanded = takeAdjacent(node.indices, withLefts, rights).sortBy(_.indices) // only take items that are inferiors expanded.slice(expanded.indexWhere(inferiors contains _), 1 + expanded.lastIndexWhere(inferiors contains _)) } /** Find all nodes in a components next to the node. * * @param node components will be found adjacent to this node * @param labels components may be connected by edges with any of these labels * @param without components may not include any of these nodes */ def components(graph: DependencyGraph, node: DependencyNode, labels: Set[String], without: Set[DependencyNode], nested: Boolean) = { // nodes across an allowed label to a subcomponent val across = graph.graph.neighbors(node, (dedge: DirectedEdge[_]) => dedge.dir match { case Direction.Down if labels.contains(dedge.edge.label) => true case _ => false }) across.flatMap { start => // get inferiors without passing back to node val inferiors = graph.graph.inferiors( start, (e: Graph.Edge[DependencyNode]) => // don't cross a conjunction that goes back an across node !((e.label startsWith "conj") && (across contains e.dest)) && // make sure we don't cycle out of the component e.dest != node && // make sure we don't descend into another component // i.e. "John M. Synge who came to us with his play direct // from the Aran Islands , where the material for most of // his later works was gathered" if nested is false (nested || !labels.contains(e.label)) ) // make sure none of the without nodes are in the component if (without.forall(!inferiors.contains(_))) { val span = Interval.span(inferiors.map(_.indices).toSeq) Some(graph.nodes.filter(node => span.superset(node.indices)).toList) } else { None } } } val componentEdgeLabels = Set("rcmod", "infmod", "partmod", "ref", "prepc_of", "advcl") val forbiddenEdgeLabel = Set("appos", "punct", "cc") ++ componentEdgeLabels def fromFrame(dgraph: DependencyGraph)(frame: Frame): Option[SrlExtraction] = { val argsNotBoundaries = frame.arguments.filterNot { arg => arg.role match { case Roles.AM_MNR => true case Roles.AM_MOD => true case Roles.AM_NEG => true case Roles.AM_ADV => true case _: Roles.C => true case _ => false } } // context information val negated = frame.arguments.find(_.role == Roles.AM_NEG).isDefined val boundaries = argsNotBoundaries.map(_.node).toSet + frame.relation.node val args = argsNotBoundaries.filterNot { arg => arg.role match { case _: Roles.R => true case _ => false } } val rel = { // sometimes we need detached tokens: "John shouts profanities out loud." val nodes = dgraph.graph.inferiors(frame.relation.node, edge => (Relation.expansionLabels contains edge.label) && !(boundaries contains edge.dest)) val additionalNodes = // sometimes we need to go up a pcomp dgraph.graph.predecessors(frame.relation.node, edge => edge.label == "pcomp" && nodes.exists { node => node.tokenInterval borders edge.source.tokenInterval }) val remoteNodes = ( // expand to certain nodes connected by a conj edge (dgraph.graph.superiors(frame.relation.node, edge => edge.label == "conj") - frame.relation.node) flatMap (node => dgraph.graph.inferiors(node, edge => edge.label == "aux" && edge.dest.text == "to") - node) ).filter(_.index < frame.relation.node.index) val nodeSeq = (remoteNodes ++ nodes ++ additionalNodes).toSeq.sorted /** create a minimal spanning set of the supplied intervals. * * @returns a sorted minimal spanning set */ def minimal(intervals: Iterable[Interval]): List[Interval] = { val set = collection.immutable.SortedSet.empty[Int] ++ intervals.flatten set.foldLeft(List.empty[Interval]) { case (list, i) => val singleton = Interval.singleton(i) list match { case Nil => List(singleton) case x :: xs if x borders singleton => (x union singleton) :: xs case xs => singleton :: xs } }.reverse } val intervals = minimal(nodeSeq.map(_.tokenInterval)) val text = nodeSeq.iterator.map(_.text).mkString(" ") Relation(text, Some(Sense(frame.relation.name, frame.relation.sense)), nodeSeq, intervals) } val mappedArgs = args.map { arg => val immediateNodes = // expand along certain contiguous nodes contiguousAdjacent(dgraph, arg.node, dedge => dedge.dir == Direction.Down && !(forbiddenEdgeLabel contains dedge.edge.label), boundaries) val componentNodes: Set[List[DependencyNode]] = if (immediateNodes.exists(_.isProperNoun)) { Set.empty } else { components(dgraph, arg.node, componentEdgeLabels, boundaries, false) } val nodeSpan = Interval.span(immediateNodes.map(_.tokenInterval) ++ componentNodes.map(_.tokenInterval)) val nodes = dgraph.nodes.slice(nodeSpan.start, nodeSpan.end) val nodeSeq = nodes.toSeq arg.role match { case Roles.AM_TMP => new TemporalArgument(nodeSeq, Interval.span(nodes.map(_.indices)), arg.role) case Roles.AM_LOC => new LocationArgument(nodeSeq, Interval.span(nodes.map(_.indices)), arg.role) case _ => new SimpleArgument(nodeSeq, Interval.span(nodes.map(_.indices)), arg.role) } } Exception.catching(classOf[IllegalArgumentException]) opt SrlExtraction.create(rel, mappedArgs, None, negated) } def fromFrameHierarchy(dgraph: DependencyGraph)(frameh: FrameHierarchy): Seq[SrlExtraction] = { def rec(frameh: FrameHierarchy): Seq[SrlExtraction] = { if (frameh.children.isEmpty) { SrlExtraction.fromFrame(dgraph)(frameh.frame).toSeq } else { SrlExtraction.fromFrame(dgraph)(frameh.frame) match { case Some(extr) => val context = { extr.context match { case Some(context) => val intervals = SortedSet.empty[Interval] ++ extr.rel.intervals + extr.arg1.interval val tokens = (Set.empty[DependencyNode] ++ extr.arg1.tokens ++ extr.rel.tokens).toSeq.sortBy(_.tokenInterval) new Context(tokens.iterator.map(_.string).mkString(" "), tokens, intervals.toSeq) case None => val intervals = extr.rel.intervals :+ extr.arg1.interval val tokens = extr.arg1.tokens ++ extr.rel.tokens new Context(tokens.iterator.map(_.string).mkString(" "), tokens, intervals) } } val subextrs = frameh.children flatMap rec // triplize to include dobj in rel val relation = extr.relationArgument match { case Some(arg) if subextrs.forall(_.arg2s.forall(arg2 => !(arg2.interval intersects arg.interval))) && (arg.interval borders extr.relation.span) => extr.relation.copy(tokens = (arg.tokens ++ extr.relation.tokens).sorted, text = extr.relation.text + " " + arg.text) case _ => extr.relation } extr +: (subextrs flatMap { subextr => Exception.catching(classOf[IllegalArgumentException]) opt { val combinedContext = subextr.context match { case Some(subcontext) => val intervals = (context.intervals ++ subcontext.intervals).toSet.toSeq.sorted val tokens = (context.tokens ++ subcontext.tokens).toSet val sortedToken = tokens.toSeq.sortBy(_.tokenInterval) new Context(sortedToken.iterator.map(_.string).mkString(" "), sortedToken, intervals) case None => context } if (extr.arg1 == subextr.arg1) { // combine the relations to make a more informative relation phrase SrlExtraction(relation concat subextr.relation, subextr.arg1, subextr.arg2s, Some(combinedContext), extr.negated || subextr.negated) } else { // the nested extraction has a different arg1 SrlExtraction(subextr.relation, subextr.arg1, subextr.arg2s, Some(combinedContext), subextr.negated) } } }) case None => Seq.empty } } } rec(frameh) } }
{'repo_name': 'allenai/openie-standalone', 'stars': '306', 'repo_language': 'Scala', 'file_name': 'publish.sh', 'mime_type': 'text/x-shellscript', 'hash': -3889524108818456221, 'source_dataset': 'data'}
/* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ #ifndef JUCE_BYTEORDER_H_INCLUDED #define JUCE_BYTEORDER_H_INCLUDED //============================================================================== /** Contains static methods for converting the byte order between different endiannesses. */ class JUCE_API ByteOrder { public: //============================================================================== /** Swaps the upper and lower bytes of a 16-bit integer. */ static uint16 swap (uint16 value) noexcept; /** Reverses the order of the 4 bytes in a 32-bit integer. */ static uint32 swap (uint32 value) noexcept; /** Reverses the order of the 8 bytes in a 64-bit integer. */ static uint64 swap (uint64 value) noexcept; //============================================================================== /** Swaps the byte order of a 16-bit unsigned int if the CPU is big-endian */ static uint16 swapIfBigEndian (uint16 value) noexcept; /** Swaps the byte order of a 32-bit unsigned int if the CPU is big-endian */ static uint32 swapIfBigEndian (uint32 value) noexcept; /** Swaps the byte order of a 64-bit unsigned int if the CPU is big-endian */ static uint64 swapIfBigEndian (uint64 value) noexcept; /** Swaps the byte order of a 16-bit signed int if the CPU is big-endian */ static int16 swapIfBigEndian (int16 value) noexcept; /** Swaps the byte order of a 32-bit signed int if the CPU is big-endian */ static int32 swapIfBigEndian (int32 value) noexcept; /** Swaps the byte order of a 64-bit signed int if the CPU is big-endian */ static int64 swapIfBigEndian (int64 value) noexcept; /** Swaps the byte order of a 32-bit float if the CPU is big-endian */ static float swapIfBigEndian (float value) noexcept; /** Swaps the byte order of a 64-bit float if the CPU is big-endian */ static double swapIfBigEndian (double value) noexcept; /** Swaps the byte order of a 16-bit unsigned int if the CPU is little-endian */ static uint16 swapIfLittleEndian (uint16 value) noexcept; /** Swaps the byte order of a 32-bit unsigned int if the CPU is little-endian */ static uint32 swapIfLittleEndian (uint32 value) noexcept; /** Swaps the byte order of a 64-bit unsigned int if the CPU is little-endian */ static uint64 swapIfLittleEndian (uint64 value) noexcept; /** Swaps the byte order of a 16-bit signed int if the CPU is little-endian */ static int16 swapIfLittleEndian (int16 value) noexcept; /** Swaps the byte order of a 32-bit signed int if the CPU is little-endian */ static int32 swapIfLittleEndian (int32 value) noexcept; /** Swaps the byte order of a 64-bit signed int if the CPU is little-endian */ static int64 swapIfLittleEndian (int64 value) noexcept; /** Swaps the byte order of a 32-bit float if the CPU is little-endian */ static float swapIfLittleEndian (float value) noexcept; /** Swaps the byte order of a 64-bit float if the CPU is little-endian */ static double swapIfLittleEndian (double value) noexcept; //============================================================================== /** Turns 4 bytes into a little-endian integer. */ static uint32 littleEndianInt (const void* bytes) noexcept; /** Turns 8 bytes into a little-endian integer. */ static uint64 littleEndianInt64 (const void* bytes) noexcept; /** Turns 2 bytes into a little-endian integer. */ static uint16 littleEndianShort (const void* bytes) noexcept; /** Turns 4 bytes into a big-endian integer. */ static uint32 bigEndianInt (const void* bytes) noexcept; /** Turns 8 bytes into a big-endian integer. */ static uint64 bigEndianInt64 (const void* bytes) noexcept; /** Turns 2 bytes into a big-endian integer. */ static uint16 bigEndianShort (const void* bytes) noexcept; //============================================================================== /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */ static int littleEndian24Bit (const void* bytes) noexcept; /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */ static int bigEndian24Bit (const void* bytes) noexcept; /** Copies a 24-bit number to 3 little-endian bytes. */ static void littleEndian24BitToChars (int value, void* destBytes) noexcept; /** Copies a 24-bit number to 3 big-endian bytes. */ static void bigEndian24BitToChars (int value, void* destBytes) noexcept; //============================================================================== /** Returns true if the current CPU is big-endian. */ static bool isBigEndian() noexcept; private: ByteOrder() JUCE_DELETED_FUNCTION; JUCE_DECLARE_NON_COPYABLE (ByteOrder) }; //============================================================================== #if JUCE_USE_MSVC_INTRINSICS && ! defined (__INTEL_COMPILER) #pragma intrinsic (_byteswap_ulong) #endif inline uint16 ByteOrder::swap (uint16 n) noexcept { #if JUCE_USE_MSVC_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic! return static_cast<uint16> (_byteswap_ushort (n)); #else return static_cast<uint16> ((n << 8) | (n >> 8)); #endif } inline uint32 ByteOrder::swap (uint32 n) noexcept { #if JUCE_MAC || JUCE_IOS return OSSwapInt32 (n); #elif JUCE_GCC && JUCE_INTEL && ! JUCE_NO_INLINE_ASM asm("bswap %%eax" : "=a"(n) : "a"(n)); return n; #elif JUCE_USE_MSVC_INTRINSICS return _byteswap_ulong (n); #elif JUCE_MSVC && ! JUCE_NO_INLINE_ASM __asm { mov eax, n bswap eax mov n, eax } return n; #elif JUCE_ANDROID return bswap_32 (n); #else return (n << 24) | (n >> 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8); #endif } inline uint64 ByteOrder::swap (uint64 value) noexcept { #if JUCE_MAC || JUCE_IOS return OSSwapInt64 (value); #elif JUCE_USE_MSVC_INTRINSICS return _byteswap_uint64 (value); #else return (((uint64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32)); #endif } #if JUCE_LITTLE_ENDIAN inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) noexcept { return v; } inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) noexcept { return v; } inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) noexcept { return v; } inline int16 ByteOrder::swapIfBigEndian (const int16 v) noexcept { return v; } inline int32 ByteOrder::swapIfBigEndian (const int32 v) noexcept { return v; } inline int64 ByteOrder::swapIfBigEndian (const int64 v) noexcept { return v; } inline float ByteOrder::swapIfBigEndian (const float v) noexcept { return v; } inline double ByteOrder::swapIfBigEndian (const double v) noexcept { return v; } inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) noexcept { return swap (v); } inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) noexcept { return swap (v); } inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) noexcept { return swap (v); } inline int16 ByteOrder::swapIfLittleEndian (const int16 v) noexcept { return static_cast<int16> (swap (static_cast<uint16> (v))); } inline int32 ByteOrder::swapIfLittleEndian (const int32 v) noexcept { return static_cast<int32> (swap (static_cast<uint32> (v))); } inline int64 ByteOrder::swapIfLittleEndian (const int64 v) noexcept { return static_cast<int64> (swap (static_cast<uint64> (v))); } inline float ByteOrder::swapIfLittleEndian (const float v) noexcept { union { uint32 asUInt; float asFloat; } n; n.asFloat = v; n.asUInt = ByteOrder::swap (n.asUInt); return n.asFloat; } inline double ByteOrder::swapIfLittleEndian (const double v) noexcept { union { uint64 asUInt; double asFloat; } n; n.asFloat = v; n.asUInt = ByteOrder::swap (n.asUInt); return n.asFloat; } inline uint32 ByteOrder::littleEndianInt (const void* const bytes) noexcept { return *static_cast<const uint32*> (bytes); } inline uint64 ByteOrder::littleEndianInt64 (const void* const bytes) noexcept { return *static_cast<const uint64*> (bytes); } inline uint16 ByteOrder::littleEndianShort (const void* const bytes) noexcept { return *static_cast<const uint16*> (bytes); } inline uint32 ByteOrder::bigEndianInt (const void* const bytes) noexcept { return swap (*static_cast<const uint32*> (bytes)); } inline uint64 ByteOrder::bigEndianInt64 (const void* const bytes) noexcept { return swap (*static_cast<const uint64*> (bytes)); } inline uint16 ByteOrder::bigEndianShort (const void* const bytes) noexcept { return swap (*static_cast<const uint16*> (bytes)); } inline bool ByteOrder::isBigEndian() noexcept { return false; } #else inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) noexcept { return swap (v); } inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) noexcept { return swap (v); } inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) noexcept { return swap (v); } inline int16 ByteOrder::swapIfBigEndian (const int16 v) noexcept { return static_cast<int16> (swap (static_cast<uint16> (v))); } inline int32 ByteOrder::swapIfBigEndian (const int32 v) noexcept { return static_cast<int16> (swap (static_cast<uint16> (v))); } inline int64 ByteOrder::swapIfBigEndian (const int64 v) noexcept { return static_cast<int16> (swap (static_cast<uint16> (v))); } inline float ByteOrder::swapIfBigEndian (const float v) noexcept { union { uint32 asUInt; float asFloat; } n; n.asFloat = v; n.asUInt = ByteOrder::swap (n.asUInt); return n.asFloat; } inline double ByteOrder::swapIfBigEndian (const double v) noexcept { union { uint64 asUInt; double asFloat; } n; n.asFloat = v; n.asUInt = ByteOrder::swap (n.asUInt); return n.asFloat; } inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) noexcept { return v; } inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) noexcept { return v; } inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) noexcept { return v; } inline int16 ByteOrder::swapIfLittleEndian (const int16 v) noexcept { return v; } inline int32 ByteOrder::swapIfLittleEndian (const int32 v) noexcept { return v; } inline int64 ByteOrder::swapIfLittleEndian (const int64 v) noexcept { return v; } inline float ByteOrder::swapIfLittleEndian (const float v) noexcept { return v; } inline double ByteOrder::swapIfLittleEndian (const double v) noexcept { return v; } inline uint32 ByteOrder::littleEndianInt (const void* const bytes) noexcept { return swap (*static_cast<const uint32*> (bytes)); } inline uint64 ByteOrder::littleEndianInt64 (const void* const bytes) noexcept { return swap (*static_cast<const uint64*> (bytes)); } inline uint16 ByteOrder::littleEndianShort (const void* const bytes) noexcept { return swap (*static_cast<const uint16*> (bytes)); } inline uint32 ByteOrder::bigEndianInt (const void* const bytes) noexcept { return *static_cast<const uint32*> (bytes); } inline uint64 ByteOrder::bigEndianInt64 (const void* const bytes) noexcept { return *static_cast<const uint64*> (bytes); } inline uint16 ByteOrder::bigEndianShort (const void* const bytes) noexcept { return *static_cast<const uint16*> (bytes); } inline bool ByteOrder::isBigEndian() noexcept { return true; } #endif inline int ByteOrder::littleEndian24Bit (const void* const bytes) noexcept { return (((int) static_cast<const int8*> (bytes)[2]) << 16) | (((int) static_cast<const uint8*> (bytes)[1]) << 8) | ((int) static_cast<const uint8*> (bytes)[0]); } inline int ByteOrder::bigEndian24Bit (const void* const bytes) noexcept { return (((int) static_cast<const int8*> (bytes)[0]) << 16) | (((int) static_cast<const uint8*> (bytes)[1]) << 8) | ((int) static_cast<const uint8*> (bytes)[2]); } inline void ByteOrder::littleEndian24BitToChars (const int value, void* const destBytes) noexcept { static_cast<uint8*> (destBytes)[0] = (uint8) value; static_cast<uint8*> (destBytes)[1] = (uint8) (value >> 8); static_cast<uint8*> (destBytes)[2] = (uint8) (value >> 16); } inline void ByteOrder::bigEndian24BitToChars (const int value, void* const destBytes) noexcept { static_cast<uint8*> (destBytes)[0] = (uint8) (value >> 16); static_cast<uint8*> (destBytes)[1] = (uint8) (value >> 8); static_cast<uint8*> (destBytes)[2] = (uint8) value; } #endif // JUCE_BYTEORDER_H_INCLUDED
{'repo_name': 'peersuasive/luce', 'stars': '115', 'repo_language': 'C++', 'file_name': 'juce_linux_BluetoothMidiDevicePairingDialogue.cpp', 'mime_type': 'text/plain', 'hash': -8533665632555464923, 'source_dataset': 'data'}
/*** ESSENTIAL STYLES ***/ .sf-menu, .sf-menu * { margin: 0; padding: 0; list-style: none; } .sf-menu li { position: relative; } .sf-menu ul { position: absolute; display: none; top: 100%; left: 0; z-index: 99; } .sf-menu > li { float: left; } .sf-menu li:hover > ul, .sf-menu li.sfHover > ul { display: block; } .sf-menu a { display: block; position: relative; } .sf-menu ul ul { top: 0; left: 100%; } /*** DEMO SKIN ***/ .sf-menu { float: left; margin-bottom: 1em; } .sf-menu ul { box-shadow: 2px 2px 6px rgba(0,0,0,.2); min-width: 12em; /* allow long menu items to determine submenu width */ *width: 12em; /* no auto sub width for IE7, see white-space comment below */ } .sf-menu a { border-left: 1px solid #fff; border-top: 1px solid #dFeEFF; /* fallback colour must use full shorthand */ border-top: 1px solid rgba(255,255,255,.5); padding: .75em 1em; text-decoration: none; zoom: 1; /* IE7 */ } .sf-menu a { color: #13a; } .sf-menu li { background: #BDD2FF; white-space: nowrap; /* no need for Supersubs plugin */ *white-space: normal; /* ...unless you support IE7 (let it wrap) */ -webkit-transition: background .2s; transition: background .2s; } .sf-menu ul li { background: #AABDE6; } .sf-menu ul ul li { background: #9AAEDB; } .sf-menu li:hover, .sf-menu li.sfHover { background: #CFDEFF; /* only transition out, not in */ -webkit-transition: none; transition: none; } /*** arrows (for all except IE7) **/ .sf-arrows .sf-with-ul { padding-right: 2.5em; *padding-right: 1em; /* no CSS arrows for IE7 (lack pseudo-elements) */ } /* styling for both css and generated arrows */ .sf-arrows .sf-with-ul:after { content: ''; position: absolute; top: 50%; right: 1em; margin-top: -3px; height: 0; width: 0; /* order of following 3 rules important for fallbacks to work */ border: 5px solid transparent; border-top-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */ border-top-color: rgba(255,255,255,.5); } .sf-arrows > li > .sf-with-ul:focus:after, .sf-arrows > li:hover > .sf-with-ul:after, .sf-arrows > .sfHover > .sf-with-ul:after { border-top-color: white; /* IE8 fallback colour */ } /* styling for right-facing arrows */ .sf-arrows ul .sf-with-ul:after { margin-top: -5px; margin-right: -3px; border-color: transparent; border-left-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */ border-left-color: rgba(255,255,255,.5); } .sf-arrows ul li > .sf-with-ul:focus:after, .sf-arrows ul li:hover > .sf-with-ul:after, .sf-arrows ul .sfHover > .sf-with-ul:after { border-left-color: white; }
{'repo_name': 'crits/crits', 'stars': '721', 'repo_language': 'JavaScript', 'file_name': 'jquery.colorhelpers.js', 'mime_type': 'text/plain', 'hash': 3296491003711851826, 'source_dataset': 'data'}
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Spaghetti: Web Server Security Scanner # # @url: https://github.com/m4ll0k/Spaghetti # @author: Momo Outaadi (M4ll0k) # @license: See the file 'doc/LICENSE' import AdminInterfaces import AllowMethod import ApacheUsers import ApacheXss import Backdoor import Backup import Captcha import ClientAccessPolicy import CommonDirectory import CommonFile import Cookie import HtmlObject import LDAPInjection import ModStatus import Email import MultiIndex import PrivateIP import Robots def All(url,agent,proxy,redirect): Cookie.Cookie(url,agent,proxy,redirect).Run() AllowMethod.AllowMethod(url,agent,proxy,redirect).Run() Robots.Robots(url,agent,proxy,redirect).Run() ClientAccessPolicy.ClientAccessPolicy(url,agent,proxy,redirect).Run() PrivateIP.PrivateIP(url,agent,proxy,redirect).Run() Email.Email(url,agent,proxy,redirect).Run() MultiIndex.MultiIndex(url,agent,proxy,redirect).Run() Captcha.Captcha(url,agent,proxy,redirect).Run() ApacheUsers.ApacheUsers(url,agent,proxy,redirect).Run() ApacheXss.ApacheXss(url,agent,proxy,redirect).Run() HtmlObject.HtmlObject(url,agent,proxy,redirect).Run() LDAPInjection.LDAPInjection(url,agent,proxy,redirect).Run() ModStatus.ModStatus(url,agent,proxy,redirect).Run() AdminInterfaces.AdminInterfaces(url,agent,proxy,redirect).Run() Backdoor.Backdoors(url,agent,proxy,redirect).Run() Backup.Backup(url,agent,proxy,redirect).Run() CommonDirectory.CommonDirectory(url,agent,proxy,redirect).Run() CommonFile.CommonFile(url,agent,proxy,redirect).Run() def AdminInterface(url,agent,proxy,redirect): AdminInterfaces.AdminInterfaces(url,agent,proxy,redirect).Run() def Misconfiguration(url,agent,proxy,redirect): MultiIndex.MultiIndex(url,agent,proxy,redirect).Run() ModStatus.ModStatus(url,agent,proxy,redirect).Run() Backdoor.Backdoors(url,agent,proxy,redirect).Run() Backup.Backup(url,agent,proxy,redirect).Run() CommonDirectory.CommonDirectory(url,agent,proxy,redirect).Run() CommonFile.CommonFile(url,agent,proxy,redirect).Run() def InfoDisclosure(url,agent,proxy,redirect): Robots.Robots(url,agent,proxy,redirect).Run() ClientAccessPolicy.ClientAccessPolicy(url,agent,proxy,redirect).Run() PrivateIP.PrivateIP(url,agent,proxy,redirect).Run() Email.Email(url,agent,proxy,redirect).Run()
{'repo_name': 'pikpikcu/Pentest-Tools-Framework', 'stars': '143', 'repo_language': 'Python', 'file_name': '__init__.py', 'mime_type': 'text/x-python', 'hash': 1601527496477570752, 'source_dataset': 'data'}
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_VALUE_STORE_VALUE_STORE_UNITTEST_H_ #define CHROME_BROWSER_VALUE_STORE_VALUE_STORE_UNITTEST_H_ #include "testing/gtest/include/gtest/gtest.h" #include "base/files/scoped_temp_dir.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/value_store/value_store.h" #include "chrome/test/base/testing_profile.h" #include "content/public/test/test_browser_thread.h" // Parameter type for the value-parameterized tests. typedef ValueStore* (*ValueStoreTestParam)(const base::FilePath& file_path); // Test fixture for ValueStore tests. Tests are defined in // settings_storage_unittest.cc with configurations for both cached // and non-cached leveldb storage, and cached no-op storage. class ValueStoreTest : public testing::TestWithParam<ValueStoreTestParam> { public: ValueStoreTest(); virtual ~ValueStoreTest(); virtual void SetUp() OVERRIDE; virtual void TearDown() OVERRIDE; protected: scoped_ptr<ValueStore> storage_; std::string key1_; std::string key2_; std::string key3_; scoped_ptr<base::Value> val1_; scoped_ptr<base::Value> val2_; scoped_ptr<base::Value> val3_; std::vector<std::string> empty_list_; std::vector<std::string> list1_; std::vector<std::string> list2_; std::vector<std::string> list3_; std::vector<std::string> list12_; std::vector<std::string> list13_; std::vector<std::string> list123_; std::set<std::string> empty_set_; std::set<std::string> set1_; std::set<std::string> set2_; std::set<std::string> set3_; std::set<std::string> set12_; std::set<std::string> set13_; std::set<std::string> set123_; scoped_ptr<base::DictionaryValue> empty_dict_; scoped_ptr<base::DictionaryValue> dict1_; scoped_ptr<base::DictionaryValue> dict3_; scoped_ptr<base::DictionaryValue> dict12_; scoped_ptr<base::DictionaryValue> dict123_; private: base::ScopedTempDir temp_dir_; // Need these so that the DCHECKs for running on FILE or UI threads pass. base::MessageLoop message_loop_; content::TestBrowserThread ui_thread_; content::TestBrowserThread file_thread_; }; #endif // CHROME_BROWSER_VALUE_STORE_VALUE_STORE_UNITTEST_H_
{'repo_name': 'ChromiumWebApps/chromium', 'stars': '184', 'repo_language': 'C++', 'file_name': 'content_setting_media_menu_model.cc', 'mime_type': 'text/x-c', 'hash': -2045047665971110528, 'source_dataset': 'data'}
[InternetShortcut] URL=http://www.freertos.org/trace IDList= [{000214A0-0000-0000-C000-000000000046}] Prop3=19,2
{'repo_name': 'istarc/stm32', 'stars': '141', 'repo_language': 'C', 'file_name': 'Makefile-lib', 'mime_type': 'text/x-makefile', 'hash': 95631887232400529, 'source_dataset': 'data'}
--- udver: '2' layout: relation title: 'cop' shortdef: 'copula' --- A `cop` (copula) is the relation of a function word used to link a subject to a nonverbal predicate. UD generally only annotates forms of "to be" as cop, which in German would be the forms of the verb "sein". More about copula in UD can be found on the main documentation page for [cop]() or [here](https://universaldependencies.org/v2/copula.html#guidelines-for-udv2). ~~~ sdparse Er ist ein guter Student . \n He is a good student . cop(Student, ist) cop(student, is) ~~~ ~~~ sdparse Alles wird besser sein . \n Everything will be better . aux(besser, wird) cop(besser, sein) aux(better, will) cop(better, be) ~~~ Note that the verbs sein and werden can be also used as full verbs. Examples for that case can be found under the `nsubj` relation.
{'repo_name': 'UniversalDependencies/docs', 'stars': '176', 'repo_language': 'HTML', 'file_name': 'template-index.md', 'mime_type': 'text/plain', 'hash': -7493579892914101897, 'source_dataset': 'data'}
/***************************************************************************** * Author: Valient Gough <vgough@pobox.com> * ***************************************************************************** * Copyright (c) 2004, Valient Gough * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "FileIO.h" FileIO::FileIO() { } FileIO::~FileIO() { } int FileIO::blockSize() const { return 1; } bool FileIO::setIV( uint64_t iv ) { (void)iv; return true; }
{'repo_name': 'neurodroid/cryptonite', 'stars': '185', 'repo_language': 'C', 'file_name': 'build.sh', 'mime_type': 'text/x-shellscript', 'hash': 5312754873190711064, 'source_dataset': 'data'}
/* * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "eng_int.h" /* Basic get/set stuff */ int ENGINE_set_load_privkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpriv_f) { e->load_privkey = loadpriv_f; return 1; } int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f) { e->load_pubkey = loadpub_f; return 1; } int ENGINE_set_load_ssl_client_cert_function(ENGINE *e, ENGINE_SSL_CLIENT_CERT_PTR loadssl_f) { e->load_ssl_client_cert = loadssl_f; return 1; } ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e) { return e->load_privkey; } ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e) { return e->load_pubkey; } ENGINE_SSL_CLIENT_CERT_PTR ENGINE_get_ssl_client_cert_function(const ENGINE *e) { return e->load_ssl_client_cert; } /* API functions to load public/private keys */ EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id, UI_METHOD *ui_method, void *callback_data) { EVP_PKEY *pkey; if (e == NULL) { ENGINEerr(ENGINE_F_ENGINE_LOAD_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER); return 0; } CRYPTO_THREAD_write_lock(global_engine_lock); if (e->funct_ref == 0) { CRYPTO_THREAD_unlock(global_engine_lock); ENGINEerr(ENGINE_F_ENGINE_LOAD_PRIVATE_KEY, ENGINE_R_NOT_INITIALISED); return 0; } CRYPTO_THREAD_unlock(global_engine_lock); if (!e->load_privkey) { ENGINEerr(ENGINE_F_ENGINE_LOAD_PRIVATE_KEY, ENGINE_R_NO_LOAD_FUNCTION); return 0; } pkey = e->load_privkey(e, key_id, ui_method, callback_data); if (!pkey) { ENGINEerr(ENGINE_F_ENGINE_LOAD_PRIVATE_KEY, ENGINE_R_FAILED_LOADING_PRIVATE_KEY); return 0; } return pkey; } EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id, UI_METHOD *ui_method, void *callback_data) { EVP_PKEY *pkey; if (e == NULL) { ENGINEerr(ENGINE_F_ENGINE_LOAD_PUBLIC_KEY, ERR_R_PASSED_NULL_PARAMETER); return 0; } CRYPTO_THREAD_write_lock(global_engine_lock); if (e->funct_ref == 0) { CRYPTO_THREAD_unlock(global_engine_lock); ENGINEerr(ENGINE_F_ENGINE_LOAD_PUBLIC_KEY, ENGINE_R_NOT_INITIALISED); return 0; } CRYPTO_THREAD_unlock(global_engine_lock); if (!e->load_pubkey) { ENGINEerr(ENGINE_F_ENGINE_LOAD_PUBLIC_KEY, ENGINE_R_NO_LOAD_FUNCTION); return 0; } pkey = e->load_pubkey(e, key_id, ui_method, callback_data); if (!pkey) { ENGINEerr(ENGINE_F_ENGINE_LOAD_PUBLIC_KEY, ENGINE_R_FAILED_LOADING_PUBLIC_KEY); return 0; } return pkey; } int ENGINE_load_ssl_client_cert(ENGINE *e, SSL *s, STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **ppkey, STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data) { if (e == NULL) { ENGINEerr(ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT, ERR_R_PASSED_NULL_PARAMETER); return 0; } CRYPTO_THREAD_write_lock(global_engine_lock); if (e->funct_ref == 0) { CRYPTO_THREAD_unlock(global_engine_lock); ENGINEerr(ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT, ENGINE_R_NOT_INITIALISED); return 0; } CRYPTO_THREAD_unlock(global_engine_lock); if (!e->load_ssl_client_cert) { ENGINEerr(ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT, ENGINE_R_NO_LOAD_FUNCTION); return 0; } return e->load_ssl_client_cert(e, s, ca_dn, pcert, ppkey, pother, ui_method, callback_data); }
{'repo_name': 'versatica/mediasoup', 'stars': '2327', 'repo_language': 'C++', 'file_name': 'VP8.hpp', 'mime_type': 'text/x-c++', 'hash': -5493169462403635130, 'source_dataset': 'data'}
/*MIT License C++ 3D Game Tutorial Series (https://github.com/PardCode/CPP-3D-Game-Tutorial-Series) Copyright (c) 2019-2020, PardCode 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.*/ #include "PixelShader.h" #include "RenderSystem.h" #include <exception> PixelShader::PixelShader(const void* shader_byte_code, size_t byte_code_size,RenderSystem * system) : m_system(system) { if (!SUCCEEDED(m_system->m_d3d_device->CreatePixelShader(shader_byte_code, byte_code_size, nullptr, &m_ps))) throw std::exception("PixelShader not created successfully"); } PixelShader::~PixelShader() { m_ps->Release(); }
{'repo_name': 'PardCode/CPP-3D-Game-Tutorial-Series', 'stars': '258', 'repo_language': 'C++', 'file_name': 'AppWindow.h', 'mime_type': 'text/x-c++', 'hash': 6988026150417960849, 'source_dataset': 'data'}
#%RAML 1.0 title: Enums create String.java source file types: Bus: type: object properties: metadata: type: array items: enum: [ac, multi-axle, reading-light, sleeper] /bus: get: description: Get a bus. responses: 200: body: application/json: type: Bus
{'repo_name': 'phoenixnap/springmvc-raml-plugin', 'stars': '136', 'repo_language': 'Java', 'file_name': 'UnionTypeInterpretorTest.java', 'mime_type': 'text/x-java', 'hash': -4671165472048418073, 'source_dataset': 'data'}
/** * A specialized version of `_.forEach` for arrays without support for callback * shorthands or `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach;
{'repo_name': 'notepadqq/notepadqq', 'stars': '1417', 'repo_language': 'C++', 'file_name': 'pre-commit', 'mime_type': 'text/x-shellscript', 'hash': 2544394504799879231, 'source_dataset': 'data'}
package org.bouncycastle.pqc.math.linearalgebra; import java.math.BigInteger; import java.security.SecureRandom; /** * Class of number-theory related functions for use with integers represented as * <tt>int</tt>'s or <tt>BigInteger</tt> objects. */ public final class IntegerFunctions { private static final BigInteger ZERO = BigInteger.valueOf(0); private static final BigInteger ONE = BigInteger.valueOf(1); private static final BigInteger TWO = BigInteger.valueOf(2); private static final BigInteger FOUR = BigInteger.valueOf(4); private static final int[] SMALL_PRIMES = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41}; private static final long SMALL_PRIME_PRODUCT = 3L * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41; private static SecureRandom sr = null; // the jacobi function uses this lookup table private static final int[] jacobiTable = {0, 1, 0, -1, 0, -1, 0, 1}; private IntegerFunctions() { // empty } /** * Computes the value of the Jacobi symbol (A|B). The following properties * hold for the Jacobi symbol which makes it a very efficient way to * evaluate the Legendre symbol * <p> * (A|B) = 0 IF gcd(A,B) &gt; 1<br> * (-1|B) = 1 IF n = 1 (mod 1)<br> * (-1|B) = -1 IF n = 3 (mod 4)<br> * (A|B) (C|B) = (AC|B)<br> * (A|B) (A|C) = (A|CB)<br> * (A|B) = (C|B) IF A = C (mod B)<br> * (2|B) = 1 IF N = 1 OR 7 (mod 8)<br> * (2|B) = 1 IF N = 3 OR 5 (mod 8) * * @param A integer value * @param B integer value * @return value of the jacobi symbol (A|B) */ public static int jacobi(BigInteger A, BigInteger B) { BigInteger a, b, v; long k = 1; k = 1; // test trivial cases if (B.equals(ZERO)) { a = A.abs(); return a.equals(ONE) ? 1 : 0; } if (!A.testBit(0) && !B.testBit(0)) { return 0; } a = A; b = B; if (b.signum() == -1) { // b < 0 b = b.negate(); // b = -b if (a.signum() == -1) { k = -1; } } v = ZERO; while (!b.testBit(0)) { v = v.add(ONE); // v = v + 1 b = b.divide(TWO); // b = b/2 } if (v.testBit(0)) { k = k * jacobiTable[a.intValue() & 7]; } if (a.signum() < 0) { // a < 0 if (b.testBit(1)) { k = -k; // k = -k } a = a.negate(); // a = -a } // main loop while (a.signum() != 0) { v = ZERO; while (!a.testBit(0)) { // a is even v = v.add(ONE); a = a.divide(TWO); } if (v.testBit(0)) { k = k * jacobiTable[b.intValue() & 7]; } if (a.compareTo(b) < 0) { // a < b // swap and correct intermediate result BigInteger x = a; a = b; b = x; if (a.testBit(1) && b.testBit(1)) { k = -k; } } a = a.subtract(b); } return b.equals(ONE) ? (int)k : 0; } /** * Computes the square root of a BigInteger modulo a prime employing the * Shanks-Tonelli algorithm. * * @param a value out of which we extract the square root * @param p prime modulus that determines the underlying field * @return a number <tt>b</tt> such that b<sup>2</sup> = a (mod p) if * <tt>a</tt> is a quadratic residue modulo <tt>p</tt>. * @throws NoQuadraticResidueException if <tt>a</tt> is a quadratic non-residue modulo <tt>p</tt> */ public static BigInteger ressol(BigInteger a, BigInteger p) throws IllegalArgumentException { BigInteger v = null; if (a.compareTo(ZERO) < 0) { a = a.add(p); } if (a.equals(ZERO)) { return ZERO; } if (p.equals(TWO)) { return a; } // p = 3 mod 4 if (p.testBit(0) && p.testBit(1)) { if (jacobi(a, p) == 1) { // a quadr. residue mod p v = p.add(ONE); // v = p+1 v = v.shiftRight(2); // v = v/4 return a.modPow(v, p); // return a^v mod p // return --> a^((p+1)/4) mod p } throw new IllegalArgumentException("No quadratic residue: " + a + ", " + p); } long t = 0; // initialization // compute k and s, where p = 2^s (2k+1) +1 BigInteger k = p.subtract(ONE); // k = p-1 long s = 0; while (!k.testBit(0)) { // while k is even s++; // s = s+1 k = k.shiftRight(1); // k = k/2 } k = k.subtract(ONE); // k = k - 1 k = k.shiftRight(1); // k = k/2 // initial values BigInteger r = a.modPow(k, p); // r = a^k mod p BigInteger n = r.multiply(r).remainder(p); // n = r^2 % p n = n.multiply(a).remainder(p); // n = n * a % p r = r.multiply(a).remainder(p); // r = r * a %p if (n.equals(ONE)) { return r; } // non-quadratic residue BigInteger z = TWO; // z = 2 while (jacobi(z, p) == 1) { // while z quadratic residue z = z.add(ONE); // z = z + 1 } v = k; v = v.multiply(TWO); // v = 2k v = v.add(ONE); // v = 2k + 1 BigInteger c = z.modPow(v, p); // c = z^v mod p // iteration while (n.compareTo(ONE) == 1) { // n > 1 k = n; // k = n t = s; // t = s s = 0; while (!k.equals(ONE)) { // k != 1 k = k.multiply(k).mod(p); // k = k^2 % p s++; // s = s + 1 } t -= s; // t = t - s if (t == 0) { throw new IllegalArgumentException("No quadratic residue: " + a + ", " + p); } v = ONE; for (long i = 0; i < t - 1; i++) { v = v.shiftLeft(1); // v = 1 * 2^(t - 1) } c = c.modPow(v, p); // c = c^v mod p r = r.multiply(c).remainder(p); // r = r * c % p c = c.multiply(c).remainder(p); // c = c^2 % p n = n.multiply(c).mod(p); // n = n * c % p } return r; } /** * Computes the greatest common divisor of the two specified integers * * @param u - first integer * @param v - second integer * @return gcd(a, b) */ public static int gcd(int u, int v) { return BigInteger.valueOf(u).gcd(BigInteger.valueOf(v)).intValue(); } /** * Extended euclidian algorithm (computes gcd and representation). * * @param a the first integer * @param b the second integer * @return <tt>(g,u,v)</tt>, where <tt>g = gcd(abs(a),abs(b)) = ua + vb</tt> */ public static int[] extGCD(int a, int b) { BigInteger ba = BigInteger.valueOf(a); BigInteger bb = BigInteger.valueOf(b); BigInteger[] bresult = extgcd(ba, bb); int[] result = new int[3]; result[0] = bresult[0].intValue(); result[1] = bresult[1].intValue(); result[2] = bresult[2].intValue(); return result; } public static BigInteger divideAndRound(BigInteger a, BigInteger b) { if (a.signum() < 0) { return divideAndRound(a.negate(), b).negate(); } if (b.signum() < 0) { return divideAndRound(a, b.negate()).negate(); } return a.shiftLeft(1).add(b).divide(b.shiftLeft(1)); } public static BigInteger[] divideAndRound(BigInteger[] a, BigInteger b) { BigInteger[] out = new BigInteger[a.length]; for (int i = 0; i < a.length; i++) { out[i] = divideAndRound(a[i], b); } return out; } /** * Compute the smallest integer that is greater than or equal to the * logarithm to the base 2 of the given BigInteger. * * @param a the integer * @return ceil[log(a)] */ public static int ceilLog(BigInteger a) { int result = 0; BigInteger p = ONE; while (p.compareTo(a) < 0) { result++; p = p.shiftLeft(1); } return result; } /** * Compute the smallest integer that is greater than or equal to the * logarithm to the base 2 of the given integer. * * @param a the integer * @return ceil[log(a)] */ public static int ceilLog(int a) { int log = 0; int i = 1; while (i < a) { i <<= 1; log++; } return log; } /** * Compute <tt>ceil(log_256 n)</tt>, the number of bytes needed to encode * the integer <tt>n</tt>. * * @param n the integer * @return the number of bytes needed to encode <tt>n</tt> */ public static int ceilLog256(int n) { if (n == 0) { return 1; } int m; if (n < 0) { m = -n; } else { m = n; } int d = 0; while (m > 0) { d++; m >>>= 8; } return d; } /** * Compute <tt>ceil(log_256 n)</tt>, the number of bytes needed to encode * the long integer <tt>n</tt>. * * @param n the long integer * @return the number of bytes needed to encode <tt>n</tt> */ public static int ceilLog256(long n) { if (n == 0) { return 1; } long m; if (n < 0) { m = -n; } else { m = n; } int d = 0; while (m > 0) { d++; m >>>= 8; } return d; } /** * Compute the integer part of the logarithm to the base 2 of the given * integer. * * @param a the integer * @return floor[log(a)] */ public static int floorLog(BigInteger a) { int result = -1; BigInteger p = ONE; while (p.compareTo(a) <= 0) { result++; p = p.shiftLeft(1); } return result; } /** * Compute the integer part of the logarithm to the base 2 of the given * integer. * * @param a the integer * @return floor[log(a)] */ public static int floorLog(int a) { int h = 0; if (a <= 0) { return -1; } int p = a >>> 1; while (p > 0) { h++; p >>>= 1; } return h; } /** * Compute the largest <tt>h</tt> with <tt>2^h | a</tt> if <tt>a!=0</tt>. * * @param a an integer * @return the largest <tt>h</tt> with <tt>2^h | a</tt> if <tt>a!=0</tt>, * <tt>0</tt> otherwise */ public static int maxPower(int a) { int h = 0; if (a != 0) { int p = 1; while ((a & p) == 0) { h++; p <<= 1; } } return h; } /** * @param a an integer * @return the number of ones in the binary representation of an integer * <tt>a</tt> */ public static int bitCount(int a) { int h = 0; while (a != 0) { h += a & 1; a >>>= 1; } return h; } /** * determines the order of g modulo p, p prime and 1 &lt; g &lt; p. This algorithm * is only efficient for small p (see X9.62-1998, p. 68). * * @param g an integer with 1 &lt; g &lt; p * @param p a prime * @return the order k of g (that is k is the smallest integer with * g<sup>k</sup> = 1 mod p */ public static int order(int g, int p) { int b, j; b = g % p; // Reduce g mod p first. j = 1; // Check whether g == 0 mod p (avoiding endless loop). if (b == 0) { throw new IllegalArgumentException(g + " is not an element of Z/(" + p + "Z)^*; it is not meaningful to compute its order."); } // Compute the order of g mod p: while (b != 1) { b *= g; b %= p; if (b < 0) { b += p; } j++; } return j; } /** * Reduces an integer into a given interval * * @param n - the integer * @param begin - left bound of the interval * @param end - right bound of the interval * @return <tt>n</tt> reduced into <tt>[begin,end]</tt> */ public static BigInteger reduceInto(BigInteger n, BigInteger begin, BigInteger end) { return n.subtract(begin).mod(end.subtract(begin)).add(begin); } /** * Compute <tt>a<sup>e</sup></tt>. * * @param a the base * @param e the exponent * @return <tt>a<sup>e</sup></tt> */ public static int pow(int a, int e) { int result = 1; while (e > 0) { if ((e & 1) == 1) { result *= a; } a *= a; e >>>= 1; } return result; } /** * Compute <tt>a<sup>e</sup></tt>. * * @param a the base * @param e the exponent * @return <tt>a<sup>e</sup></tt> */ public static long pow(long a, int e) { long result = 1; while (e > 0) { if ((e & 1) == 1) { result *= a; } a *= a; e >>>= 1; } return result; } /** * Compute <tt>a<sup>e</sup> mod n</tt>. * * @param a the base * @param e the exponent * @param n the modulus * @return <tt>a<sup>e</sup> mod n</tt> */ public static int modPow(int a, int e, int n) { if (n <= 0 || (n * n) > Integer.MAX_VALUE || e < 0) { return 0; } int result = 1; a = (a % n + n) % n; while (e > 0) { if ((e & 1) == 1) { result = (result * a) % n; } a = (a * a) % n; e >>>= 1; } return result; } /** * Extended euclidian algorithm (computes gcd and representation). * * @param a - the first integer * @param b - the second integer * @return <tt>(d,u,v)</tt>, where <tt>d = gcd(a,b) = ua + vb</tt> */ public static BigInteger[] extgcd(BigInteger a, BigInteger b) { BigInteger u = ONE; BigInteger v = ZERO; BigInteger d = a; if (b.signum() != 0) { BigInteger v1 = ZERO; BigInteger v3 = b; while (v3.signum() != 0) { BigInteger[] tmp = d.divideAndRemainder(v3); BigInteger q = tmp[0]; BigInteger t3 = tmp[1]; BigInteger t1 = u.subtract(q.multiply(v1)); u = v1; d = v3; v1 = t1; v3 = t3; } v = d.subtract(a.multiply(u)).divide(b); } return new BigInteger[]{d, u, v}; } /** * Computation of the least common multiple of a set of BigIntegers. * * @param numbers - the set of numbers * @return the lcm(numbers) */ public static BigInteger leastCommonMultiple(BigInteger[] numbers) { int n = numbers.length; BigInteger result = numbers[0]; for (int i = 1; i < n; i++) { BigInteger gcd = result.gcd(numbers[i]); result = result.multiply(numbers[i]).divide(gcd); } return result; } /** * Returns a long integer whose value is <tt>(a mod m</tt>). This method * differs from <tt>%</tt> in that it always returns a <i>non-negative</i> * integer. * * @param a value on which the modulo operation has to be performed. * @param m the modulus. * @return <tt>a mod m</tt> */ public static long mod(long a, long m) { long result = a % m; if (result < 0) { result += m; } return result; } /** * Computes the modular inverse of an integer a * * @param a - the integer to invert * @param mod - the modulus * @return <tt>a<sup>-1</sup> mod n</tt> */ public static int modInverse(int a, int mod) { return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(mod)) .intValue(); } /** * Computes the modular inverse of an integer a * * @param a - the integer to invert * @param mod - the modulus * @return <tt>a<sup>-1</sup> mod n</tt> */ public static long modInverse(long a, long mod) { return BigInteger.valueOf(a).modInverse(BigInteger.valueOf(mod)) .longValue(); } /** * Tests whether an integer <tt>a</tt> is power of another integer * <tt>p</tt>. * * @param a - the first integer * @param p - the second integer * @return n if a = p^n or -1 otherwise */ public static int isPower(int a, int p) { if (a <= 0) { return -1; } int n = 0; int d = a; while (d > 1) { if (d % p != 0) { return -1; } d /= p; n++; } return n; } /** * Find and return the least non-trivial divisor of an integer <tt>a</tt>. * * @param a - the integer * @return divisor p &gt;1 or 1 if a = -1,0,1 */ public static int leastDiv(int a) { if (a < 0) { a = -a; } if (a == 0) { return 1; } if ((a & 1) == 0) { return 2; } int p = 3; while (p <= (a / p)) { if ((a % p) == 0) { return p; } p += 2; } return a; } /** * Miller-Rabin-Test, determines wether the given integer is probably prime * or composite. This method returns <tt>true</tt> if the given integer is * prime with probability <tt>1 - 2<sup>-20</sup></tt>. * * @param n the integer to test for primality * @return <tt>true</tt> if the given integer is prime with probability * 2<sup>-100</sup>, <tt>false</tt> otherwise */ public static boolean isPrime(int n) { if (n < 2) { return false; } if (n == 2) { return true; } if ((n & 1) == 0) { return false; } if (n < 42) { for (int i = 0; i < SMALL_PRIMES.length; i++) { if (n == SMALL_PRIMES[i]) { return true; } } } if ((n % 3 == 0) || (n % 5 == 0) || (n % 7 == 0) || (n % 11 == 0) || (n % 13 == 0) || (n % 17 == 0) || (n % 19 == 0) || (n % 23 == 0) || (n % 29 == 0) || (n % 31 == 0) || (n % 37 == 0) || (n % 41 == 0)) { return false; } return BigInteger.valueOf(n).isProbablePrime(20); } /** * Short trial-division test to find out whether a number is not prime. This * test is usually used before a Miller-Rabin primality test. * * @param candidate the number to test * @return <tt>true</tt> if the number has no factor of the tested primes, * <tt>false</tt> if the number is definitely composite */ public static boolean passesSmallPrimeTest(BigInteger candidate) { final int[] smallPrime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499}; for (int i = 0; i < smallPrime.length; i++) { if (candidate.mod(BigInteger.valueOf(smallPrime[i])).equals( ZERO)) { return false; } } return true; } /** * Returns the largest prime smaller than the given integer * * @param n - upper bound * @return the largest prime smaller than <tt>n</tt>, or <tt>1</tt> if * <tt>n &lt;= 2</tt> */ public static int nextSmallerPrime(int n) { if (n <= 2) { return 1; } if (n == 3) { return 2; } if ((n & 1) == 0) { n--; } else { n -= 2; } while (n > 3 & !isPrime(n)) { n -= 2; } return n; } /** * Compute the next probable prime greater than <tt>n</tt> with the * specified certainty. * * @param n a integer number * @param certainty the certainty that the generated number is prime * @return the next prime greater than <tt>n</tt> */ public static BigInteger nextProbablePrime(BigInteger n, int certainty) { if (n.signum() < 0 || n.signum() == 0 || n.equals(ONE)) { return TWO; } BigInteger result = n.add(ONE); // Ensure an odd number if (!result.testBit(0)) { result = result.add(ONE); } while (true) { // Do cheap "pre-test" if applicable if (result.bitLength() > 6) { long r = result.remainder( BigInteger.valueOf(SMALL_PRIME_PRODUCT)).longValue(); if ((r % 3 == 0) || (r % 5 == 0) || (r % 7 == 0) || (r % 11 == 0) || (r % 13 == 0) || (r % 17 == 0) || (r % 19 == 0) || (r % 23 == 0) || (r % 29 == 0) || (r % 31 == 0) || (r % 37 == 0) || (r % 41 == 0)) { result = result.add(TWO); continue; // Candidate is composite; try another } } // All candidates of bitLength 2 and 3 are prime by this point if (result.bitLength() < 4) { return result; } // The expensive test if (result.isProbablePrime(certainty)) { return result; } result = result.add(TWO); } } /** * Compute the next probable prime greater than <tt>n</tt> with the default * certainty (20). * * @param n a integer number * @return the next prime greater than <tt>n</tt> */ public static BigInteger nextProbablePrime(BigInteger n) { return nextProbablePrime(n, 20); } /** * Computes the next prime greater than n. * * @param n a integer number * @return the next prime greater than n */ public static BigInteger nextPrime(long n) { long i; boolean found = false; long result = 0; if (n <= 1) { return BigInteger.valueOf(2); } if (n == 2) { return BigInteger.valueOf(3); } for (i = n + 1 + (n & 1); (i <= n << 1) && !found; i += 2) { for (long j = 3; (j <= i >> 1) && !found; j += 2) { if (i % j == 0) { found = true; } } if (found) { found = false; } else { result = i; found = true; } } return BigInteger.valueOf(result); } /** * Computes the binomial coefficient (n|t) ("n over t"). Formula: * <ul> * <li>if n !=0 and t != 0 then (n|t) = Mult(i=1, t): (n-(i-1))/i</li> * <li>if t = 0 then (n|t) = 1</li> * <li>if n = 0 and t &gt; 0 then (n|t) = 0</li> * </ul> * * @param n - the "upper" integer * @param t - the "lower" integer * @return the binomialcoefficient "n over t" as BigInteger */ public static BigInteger binomial(int n, int t) { BigInteger result = ONE; if (n == 0) { if (t == 0) { return result; } return ZERO; } // the property (n|t) = (n|n-t) be used to reduce numbers of operations if (t > (n >>> 1)) { t = n - t; } for (int i = 1; i <= t; i++) { result = (result.multiply(BigInteger.valueOf(n - (i - 1)))) .divide(BigInteger.valueOf(i)); } return result; } public static BigInteger randomize(BigInteger upperBound) { if (sr == null) { sr = new SecureRandom(); } return randomize(upperBound, sr); } public static BigInteger randomize(BigInteger upperBound, SecureRandom prng) { int blen = upperBound.bitLength(); BigInteger randomNum = BigInteger.valueOf(0); if (prng == null) { prng = sr != null ? sr : new SecureRandom(); } for (int i = 0; i < 20; i++) { randomNum = new BigInteger(blen, prng); if (randomNum.compareTo(upperBound) < 0) { return randomNum; } } return randomNum.mod(upperBound); } /** * Extract the truncated square root of a BigInteger. * * @param a - value out of which we extract the square root * @return the truncated square root of <tt>a</tt> */ public static BigInteger squareRoot(BigInteger a) { int bl; BigInteger result, remainder, b; if (a.compareTo(ZERO) < 0) { throw new ArithmeticException( "cannot extract root of negative number" + a + "."); } bl = a.bitLength(); result = ZERO; remainder = ZERO; // if the bit length is odd then extra step if ((bl & 1) != 0) { result = result.add(ONE); bl--; } while (bl > 0) { remainder = remainder.multiply(FOUR); remainder = remainder.add(BigInteger.valueOf((a.testBit(--bl) ? 2 : 0) + (a.testBit(--bl) ? 1 : 0))); b = result.multiply(FOUR).add(ONE); result = result.multiply(TWO); if (remainder.compareTo(b) != -1) { result = result.add(ONE); remainder = remainder.subtract(b); } } return result; } /** * Takes an approximation of the root from an integer base, using newton's * algorithm * * @param base the base to take the root from * @param root the root, for example 2 for a square root */ public static float intRoot(int base, int root) { float gNew = base / root; float gOld = 0; int counter = 0; while (Math.abs(gOld - gNew) > 0.0001) { float gPow = floatPow(gNew, root); while (Float.isInfinite(gPow)) { gNew = (gNew + gOld) / 2; gPow = floatPow(gNew, root); } counter += 1; gOld = gNew; gNew = gOld - (gPow - base) / (root * floatPow(gOld, root - 1)); } return gNew; } /** * Calculation of a logarithmus of a float param * * @param param * @return */ public static float floatLog(float param) { double arg = (param - 1) / (param + 1); double arg2 = arg; int counter = 1; float result = (float)arg; while (arg2 > 0.001) { counter += 2; arg2 *= arg * arg; result += (1. / counter) * arg2; } return 2 * result; } /** * int power of a base float, only use for small ints * * @param f * @param i * @return */ public static float floatPow(float f, int i) { float g = 1; for (; i > 0; i--) { g *= f; } return g; } /** * calculate the logarithm to the base 2. * * @param x any double value * @return log_2(x) * @deprecated use MathFunctions.log(double) instead */ public static double log(double x) { if (x > 0 && x < 1) { double d = 1 / x; double result = -log(d); return result; } int tmp = 0; double tmp2 = 1; double d = x; while (d > 2) { d = d / 2; tmp += 1; tmp2 *= 2; } double rem = x / tmp2; rem = logBKM(rem); return tmp + rem; } /** * calculate the logarithm to the base 2. * * @param x any long value &gt;=1 * @return log_2(x) * @deprecated use MathFunctions.log(long) instead */ public static double log(long x) { int tmp = floorLog(BigInteger.valueOf(x)); long tmp2 = 1 << tmp; double rem = (double)x / (double)tmp2; rem = logBKM(rem); return tmp + rem; } /** * BKM Algorithm to calculate logarithms to the base 2. * * @param arg a double value with 1<= arg<= 4.768462058 * @return log_2(arg) * @deprecated use MathFunctions.logBKM(double) instead */ private static double logBKM(double arg) { double ae[] = // A_e[k] = log_2 (1 + 0.5^k) { 1.0000000000000000000000000000000000000000000000000000000000000000000000000000, 0.5849625007211561814537389439478165087598144076924810604557526545410982276485, 0.3219280948873623478703194294893901758648313930245806120547563958159347765589, 0.1699250014423123629074778878956330175196288153849621209115053090821964552970, 0.0874628412503394082540660108104043540112672823448206881266090643866965081686, 0.0443941193584534376531019906736094674630459333742491317685543002674288465967, 0.0223678130284545082671320837460849094932677948156179815932199216587899627785, 0.0112272554232541203378805844158839407281095943600297940811823651462712311786, 0.0056245491938781069198591026740666017211096815383520359072957784732489771013, 0.0028150156070540381547362547502839489729507927389771959487826944878598909400, 0.0014081943928083889066101665016890524233311715793462235597709051792834906001, 0.0007042690112466432585379340422201964456668872087249334581924550139514213168, 0.0003521774803010272377989609925281744988670304302127133979341729842842377649, 0.0001760994864425060348637509459678580940163670081839283659942864068257522373, 0.0000880524301221769086378699983597183301490534085738474534831071719854721939, 0.0000440268868273167176441087067175806394819146645511899503059774914593663365, 0.0000220136113603404964890728830697555571275493801909791504158295359319433723, 0.0000110068476674814423006223021573490183469930819844945565597452748333526464, 0.0000055034343306486037230640321058826431606183125807276574241540303833251704, 0.0000027517197895612831123023958331509538486493412831626219340570294203116559, 0.0000013758605508411382010566802834037147561973553922354232704569052932922954, 0.0000006879304394358496786728937442939160483304056131990916985043387874690617, 0.0000003439652607217645360118314743718005315334062644619363447395987584138324, 0.0000001719826406118446361936972479533123619972434705828085978955697643547921, 0.0000000859913228686632156462565208266682841603921494181830811515318381744650, 0.0000000429956620750168703982940244684787907148132725669106053076409624949917, 0.0000000214978311976797556164155504126645192380395989504741781512309853438587, 0.0000000107489156388827085092095702361647949603617203979413516082280717515504, 0.0000000053744578294520620044408178949217773318785601260677517784797554422804, 0.0000000026872289172287079490026152352638891824761667284401180026908031182361, 0.0000000013436144592400232123622589569799954658536700992739887706412976115422, 0.0000000006718072297764289157920422846078078155859484240808550018085324187007, 0.0000000003359036149273187853169587152657145221968468364663464125722491530858, 0.0000000001679518074734354745159899223037458278711244127245990591908996412262, 0.0000000000839759037391617577226571237484864917411614198675604731728132152582, 0.0000000000419879518701918839775296677020135040214077417929807824842667285938, 0.0000000000209939759352486932678195559552767641474249812845414125580747434389, 0.0000000000104969879676625344536740142096218372850561859495065136990936290929, 0.0000000000052484939838408141817781356260462777942148580518406975851213868092, 0.0000000000026242469919227938296243586262369156865545638305682553644113887909, 0.0000000000013121234959619935994960031017850191710121890821178731821983105443, 0.0000000000006560617479811459709189576337295395590603644549624717910616347038, 0.0000000000003280308739906102782522178545328259781415615142931952662153623493, 0.0000000000001640154369953144623242936888032768768777422997704541618141646683, 0.0000000000000820077184976595619616930350508356401599552034612281802599177300, 0.0000000000000410038592488303636807330652208397742314215159774270270147020117, 0.0000000000000205019296244153275153381695384157073687186580546938331088730952, 0.0000000000000102509648122077001764119940017243502120046885379813510430378661, 0.0000000000000051254824061038591928917243090559919209628584150482483994782302, 0.0000000000000025627412030519318726172939815845367496027046030028595094737777, 0.0000000000000012813706015259665053515049475574143952543145124550608158430592, 0.0000000000000006406853007629833949364669629701200556369782295210193569318434, 0.0000000000000003203426503814917330334121037829290364330169106716787999052925, 0.0000000000000001601713251907458754080007074659337446341494733882570243497196, 0.0000000000000000800856625953729399268240176265844257044861248416330071223615, 0.0000000000000000400428312976864705191179247866966320469710511619971334577509, 0.0000000000000000200214156488432353984854413866994246781519154793320684126179, 0.0000000000000000100107078244216177339743404416874899847406043033792202127070, 0.0000000000000000050053539122108088756700751579281894640362199287591340285355, 0.0000000000000000025026769561054044400057638132352058574658089256646014899499, 0.0000000000000000012513384780527022205455634651853807110362316427807660551208, 0.0000000000000000006256692390263511104084521222346348012116229213309001913762, 0.0000000000000000003128346195131755552381436585278035120438976487697544916191, 0.0000000000000000001564173097565877776275512286165232838833090480508502328437, 0.0000000000000000000782086548782938888158954641464170239072244145219054734086, 0.0000000000000000000391043274391469444084776945327473574450334092075712154016, 0.0000000000000000000195521637195734722043713378812583900953755962557525252782, 0.0000000000000000000097760818597867361022187915943503728909029699365320287407, 0.0000000000000000000048880409298933680511176764606054809062553340323879609794, 0.0000000000000000000024440204649466840255609083961603140683286362962192177597, 0.0000000000000000000012220102324733420127809717395445504379645613448652614939, 0.0000000000000000000006110051162366710063906152551383735699323415812152114058, 0.0000000000000000000003055025581183355031953399739107113727036860315024588989, 0.0000000000000000000001527512790591677515976780735407368332862218276873443537, 0.0000000000000000000000763756395295838757988410584167137033767056170417508383, 0.0000000000000000000000381878197647919378994210346199431733717514843471513618, 0.0000000000000000000000190939098823959689497106436628681671067254111334889005, 0.0000000000000000000000095469549411979844748553534196582286585751228071408728, 0.0000000000000000000000047734774705989922374276846068851506055906657137209047, 0.0000000000000000000000023867387352994961187138442777065843718711089344045782, 0.0000000000000000000000011933693676497480593569226324192944532044984865894525, 0.0000000000000000000000005966846838248740296784614396011477934194852481410926, 0.0000000000000000000000002983423419124370148392307506484490384140516252814304, 0.0000000000000000000000001491711709562185074196153830361933046331030629430117, 0.0000000000000000000000000745855854781092537098076934460888486730708440475045, 0.0000000000000000000000000372927927390546268549038472050424734256652501673274, 0.0000000000000000000000000186463963695273134274519237230207489851150821191330, 0.0000000000000000000000000093231981847636567137259618916352525606281553180093, 0.0000000000000000000000000046615990923818283568629809533488457973317312233323, 0.0000000000000000000000000023307995461909141784314904785572277779202790023236, 0.0000000000000000000000000011653997730954570892157452397493151087737428485431, 0.0000000000000000000000000005826998865477285446078726199923328593402722606924, 0.0000000000000000000000000002913499432738642723039363100255852559084863397344, 0.0000000000000000000000000001456749716369321361519681550201473345138307215067, 0.0000000000000000000000000000728374858184660680759840775119123438968122488047, 0.0000000000000000000000000000364187429092330340379920387564158411083803465567, 0.0000000000000000000000000000182093714546165170189960193783228378441837282509, 0.0000000000000000000000000000091046857273082585094980096891901482445902524441, 0.0000000000000000000000000000045523428636541292547490048446022564529197237262, 0.0000000000000000000000000000022761714318270646273745024223029238091160103901}; int n = 53; double x = 1; double y = 0; double z; double s = 1; int k; for (k = 0; k < n; k++) { z = x + x * s; if (z <= arg) { x = z; y += ae[k]; } s *= 0.5; } return y; } public static boolean isIncreasing(int[] a) { for (int i = 1; i < a.length; i++) { if (a[i - 1] >= a[i]) { System.out.println("a[" + (i - 1) + "] = " + a[i - 1] + " >= " + a[i] + " = a[" + i + "]"); return false; } } return true; } public static byte[] integerToOctets(BigInteger val) { byte[] valBytes = val.abs().toByteArray(); // check whether the array includes a sign bit if ((val.bitLength() & 7) != 0) { return valBytes; } // get rid of the sign bit (first byte) byte[] tmp = new byte[val.bitLength() >> 3]; System.arraycopy(valBytes, 1, tmp, 0, tmp.length); return tmp; } public static BigInteger octetsToInteger(byte[] data, int offset, int length) { byte[] val = new byte[length + 1]; val[0] = 0; System.arraycopy(data, offset, val, 1, length); return new BigInteger(val); } public static BigInteger octetsToInteger(byte[] data) { return octetsToInteger(data, 0, data.length); } public static void main(String[] args) { System.out.println("test"); // System.out.println(intRoot(37, 5)); // System.out.println(floatPow((float)2.5, 4)); System.out.println(floatLog(10)); System.out.println("test2"); } }
{'repo_name': 'redfish64/TinyTravelTracker', 'stars': '104', 'repo_language': 'Java', 'file_name': 'notes.txt~', 'mime_type': 'text/plain', 'hash': 1038594959928350304, 'source_dataset': 'data'}
--- title: FIELD_INFO_FIELDS | Microsoft Docs ms.date: 11/04/2016 ms.topic: reference f1_keywords: - FIELD_INFO_FIELDS helpviewer_keywords: - FIELD_INFO_FIELDS enumeration ms.assetid: a69487d2-e701-4165-804a-8a011df9a3bd author: acangialosi ms.author: anthc manager: jillfra ms.workload: - vssdk dev_langs: - CPP - CSharp --- # FIELD_INFO_FIELDS Specifies what information to retrieve about an [IDebugField](../../../extensibility/debugger/reference/idebugfield.md) object. ## Syntax ```cpp enum enum_FIELD_INFO_FIELDS {  FIF_FULLNAME = 0x0001, FIF_NAME = 0x0002, FIF_TYPE = 0x0004, FIF_MODIFIERS = 0x0008, FIF_ALL = 0xffffffff, FIF_NONE = 0x0000 }; typedef DWORD FIELD_INFO_FIELDS; ``` ```csharp public enum enum_FIELD_INFO_FIELDS { FIF_FULLNAME = 0x0001, FIF_NAME = 0x0002, FIF_TYPE = 0x0004, FIF_MODIFIERS = 0x0008, FIF_ALL = 0xffffffff, FIF_NONE = 0x0000 }; ``` ## Fields `FIF_FULLNAME`\ Initialize/use the `bstrFullName` field in the [FIELD_INFO](../../../extensibility/debugger/reference/field-info.md) structure. `FIF_NAME`\ Initialize/use the `bstrName` field in the `FIELD_INFO` structure. `FIF_TYPE`\ Initialize/use the `bstrType` field in the `FIELD_INFO` structure. `FIF_MODIFIERS`\ Initialize/use the `bstrModifiers` field in the `FIELD_INFO` structure. ## Remarks These values are also passed as an argument to the [GetInfo](../../../extensibility/debugger/reference/idebugfield-getinfo.md) method to specify which fields of the [FIELD_INFO](../../../extensibility/debugger/reference/field-info.md) structure are to be initialized. These values are also used in the `dwFields` member of the `FIELD_INFO` structure to indicate which fields are used and valid. These flags may be combined with a bitwise `OR`. ## Requirements Header: sh.h Namespace: Microsoft.VisualStudio.Debugger.Interop Assembly: Microsoft.VisualStudio.Debugger.Interop.dll ## See also - [Enumerations](../../../extensibility/debugger/reference/enumerations-visual-studio-debugging.md) - [FIELD_INFO](../../../extensibility/debugger/reference/field-info.md) - [IDebugField](../../../extensibility/debugger/reference/idebugfield.md) - [GetInfo](../../../extensibility/debugger/reference/idebugfield-getinfo.md)
{'repo_name': 'MicrosoftDocs/visualstudio-docs', 'stars': '606', 'repo_language': 'Python', 'file_name': 'how-to-create-a-basic-3-d-model.md', 'mime_type': 'text/plain', 'hash': 5812993260724440680, 'source_dataset': 'data'}
<schemalist> <!-- from the GSettings docs. Should work, I guess :) --> <enum id="myenum"> <value nick="first" value="1"/> <value nick="second" value="2"/> </enum> <schema id="org.gtk.test"> <key name="key-with-range" type="i"> <range min="1" max="100"/> <default>10</default> </key> <key name="key-with-choices" type="s"> <choices> <choice value='Elisabeth'/> <choice value='Annabeth'/> <choice value='Joe'/> </choices> <aliases> <alias value='Anna' target='Annabeth'/> <alias value='Beth' target='Elisabeth'/> </aliases> <default>'Joe'</default> </key> <key name='enumerated-key' enum='myenum'> <default>'first'</default> </key> </schema> </schemalist>
{'repo_name': 'minixalpha/SourceLearning', 'stars': '107', 'repo_language': 'C', 'file_name': 'ByteArrayInputStream.markdown', 'mime_type': 'text/plain', 'hash': -1511104223717005089, 'source_dataset': 'data'}
/* * */ #undef BOOTSTRAP #include "config.h" #include "libopenbios/bindings.h" #include "libopenbios/elfload.h" #include "arch/common/nvram.h" #include "libc/diskio.h" #include "libopenbios/sys_info.h" int elf_load(struct sys_info *, const char *filename, const char *cmdline); int linux_load(struct sys_info *, const char *filename, const char *cmdline); void boot(void); void boot(void) { char *path=pop_fstr_copy(), *param; // char *param="root=/dev/hda2 console=ttyS0,115200n8 console=tty0"; if(!path) { printk("[x86] Booting default not supported.\n"); return; } param = strchr(path, ' '); if(param) { *param = '\0'; param++; } printk("[x86] Booting file '%s' with parameters '%s'\n",path, param); if (elf_load(&sys_info, path, param) == LOADER_NOT_SUPPORT) if (linux_load(&sys_info, path, param) == LOADER_NOT_SUPPORT) printk("Unsupported image format\n"); free(path); }
{'repo_name': 'andreafioraldi/qasan', 'stars': '137', 'repo_language': 'C', 'file_name': 'hooks.c', 'mime_type': 'text/x-c', 'hash': -1848534917680603862, 'source_dataset': 'data'}
# -*- coding: UTF-8 -*- class MessageSlicerByTime: """ Separate messages into slices by time, for time display in html. A new day always begins a new slice. """ def __init__(self, diff_thres=5 * 60): self.diff_thres = diff_thres def slice(self, msgs): ret = [] now = [] for m in msgs: if len(now) == 0: now.append(m) continue nowtime, lasttime = m.createTime, now[-1].createTime if nowtime.date() == lasttime.date() and \ (nowtime - lasttime).seconds < self.diff_thres: now.append(m) continue ret.append(now) now = [m] ret.append(now) assert len(msgs) == sum([len(k) for k in ret]) return ret class MessageSlicerBySize: """ Separate messages into slices by max slice size, to avoid too large html. """ def __init__(self, size=1500): """ a slice will have <= 1.5 * cnt messages""" self.size = size assert self.size > 1 def slice(self, msgs): ret = [] now = [] for m in msgs: if len(now) >= self.size: nowtime, lasttime = m.createTime, now[-1].createTime if nowtime.date() != lasttime.date(): ret.append(now) now = [m] continue now.append(m) if len(now) > self.size / 2 or len(ret) == 0: ret.append(now) else: ret[-1].extend(now) assert len(msgs) == sum([len(k) for k in ret]) return ret
{'repo_name': 'ppwwyyxx/wechat-dump', 'stars': '1037', 'repo_language': 'Python', 'file_name': 'config.conf', 'mime_type': 'text/plain', 'hash': -951034692670859203, 'source_dataset': 'data'}
#begin -- common conustructions tests -- -- Literals -- -- -- String literal SELECT 'hello world'; select N'testing conflict on N - spec symbol and N - as identifier' as n; select n'abc' as tstConstrN; select N'abc' "bcd" 'asdfasdf' as tstConstNAndConcat; select 'afdf' "erwhg" "ads" 'dgs' "rter" as tstDiffQuoteConcat; select 'some string' COLLATE latin1_danish_ci as tstCollate; select _latin1'some string' COLLATE latin1_danish_ci as tstCollate; select '\'' as c1, '\"' as c2, '\b' as c3, '\n' as c4, '\r' as c5, '\t' as c6, '\Z' as c7, '\\' as c8, '\%' as c9, '\_' as c10; #end #begin -- -- -- String literal spec symbols -- bug: two symbols ' afer each other: '' select '\'Quoted string\'' col1, 'backslash \\ ' ', two double quote "" ' ', two single quote ''' as col2; select '\'Quoted string\' ' col1, 'backslash \\ ' ', two double quote "" ' ', two single quote ''' as col2; select * from `select` where `varchar` = 'abc \' ' and `varchar2` = '\'bca'; #end #begin -- -- -- Number literal SELECT 1; select 1.e-3 as 123e; select del1.e123 as c from del1; select -1, 3e-2, 2.34E0; SELECT -4.1234e-2, 0.2e-3 as c; SELECT .1e10; SELECT -.1e10; select 15e3, .2e5 as col1; select .2e3 c1, .2e-4 as c5; #end #begin -- -- -- Number float collision test select t1e2 as e1 from t; select 1e2t as col from t; #end #begin -- -- -- Hexadecimal literal select X'4D7953514C'; select x'4D7953514C'; select 0x636174; select 0x636174 c1; select x'4D7953514C' c1, 0x636174 c2; select x'79' as `select`, 0x2930 cc, 0x313233 as c2; #end #begin -- -- -- Null literal SELECT null; SELECT not null; select \N; select ((\N)); select not ((\N)); #end #begin -- -- -- mixed literals select \N as c1, null as c2, N'string'; select 4e15 colum, 'hello, ' 'world', X'53514C'; select 'abc' ' bcd' ' \' \' ' as col, \N c2, -.1e-3; #end #begin -- -- Variables SELECT @myvar; #end #begin -- select_column tests select * from `select`; select *, `select`.*, `select`.* from `select`; select *, 'abc' from `select`; select *, 1, \N, N'string' 'string2' from `select`; #end #begin -- UNION tests select 1 union select 2 limit 0,5; select * from (select 1 union select 2 union select 0) as t order by 1 limit 0,10; select col1 from t1 union select * from (select 1 as col2) as newt; select col1 from t1 union (select * from (select 1 as col2) as newt); select 1 as c1 union (((select 2))); #end #begin -- -- -- subquery in UNION select 1 union select * from (select 2 union select 3) as table1; select 1 union (select * from (select 2 union select 3) as table1); #end #begin -- subquery FROM select * from (((((((select col1 from t1) as ttt)))))); select ship_power.gun_power, ship_info.* FROM ( select s.name as ship_name, sum(g.power) as gun_power, max(callibr) as max_callibr from ships s inner join ships_guns sg on s.id = sg.ship_id inner join guns g on g.id = sg.guns_id group by s.name ) ship_power inner join ( select s.name as ship_name, sc.class_name, sc.tonange, sc.max_length, sc.start_build, sc.max_guns_size from ships s inner join ship_class sc on s.class_id = sc.id ) ship_info using (ship_name) order by ship_power.ship_name; #end #begin -- JOIN -- -- -- join condition select * from t1 inner join (t1 as tt1, t2 as tt2) on t1.col1 = tt1.col1; select * from (t1 as tt1, t2 as tt2) inner join t1 on t1.col1 = tt1.col1; select * from t1 as tt1, t2 as tt2 inner join t1 on true; #end #begin -- where_condition test select col1 from t1 inner join t2 on (t1.col1 = t2.col2); #end #begin -- identifiers tests select 1 as 123e; #end #begin -- not latin1 literals select CONVERT( LEFT( CONVERT( '自動下書き' USING binary ), 100 ) USING utf8 ) AS x_0; select CONVERT( LEFT( CONVERT( '自動' USING binary ), 6 ) USING utf8 ) AS x_0; select t.*, tt.* FROM wptests_terms AS t INNER JOIN wptests_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') AND t.name IN ('远征手记') ORDER BY t.name ASC; #end #begin -- cast as integer SELECT CAST('1' AS INT); SELECT CAST('1' AS INTEGER); #end
{'repo_name': 'debezium/debezium', 'stars': '3394', 'repo_language': 'Java', 'file_name': 'MySqlDdlParserPerf.java', 'mime_type': 'text/x-java', 'hash': -6479626284890410196, 'source_dataset': 'data'}
name: linty fresh categories: - linter tags: - python license: Other types: - cli source: 'https://github.com/lyft/linty_fresh' homepage: 'https://github.com/lyft/linty_fresh' description: Parse lint errors and report them to Github as comments on a pull request.
{'repo_name': 'analysis-tools-dev/static-analysis', 'stars': '7378', 'repo_language': 'Rust', 'file_name': 'README.md', 'mime_type': 'text/html', 'hash': 697214131081494952, 'source_dataset': 'data'}
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef _TOOLS_LE_BYTESHIFT_H #define _TOOLS_LE_BYTESHIFT_H #include <stdint.h> static inline uint16_t __get_unaligned_le16(const uint8_t *p) { return p[0] | p[1] << 8; } static inline uint32_t __get_unaligned_le32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24; } static inline uint64_t __get_unaligned_le64(const uint8_t *p) { return (uint64_t)__get_unaligned_le32(p + 4) << 32 | __get_unaligned_le32(p); } static inline void __put_unaligned_le16(uint16_t val, uint8_t *p) { *p++ = val; *p++ = val >> 8; } static inline void __put_unaligned_le32(uint32_t val, uint8_t *p) { __put_unaligned_le16(val >> 16, p + 2); __put_unaligned_le16(val, p); } static inline void __put_unaligned_le64(uint64_t val, uint8_t *p) { __put_unaligned_le32(val >> 32, p + 4); __put_unaligned_le32(val, p); } static inline uint16_t get_unaligned_le16(const void *p) { return __get_unaligned_le16((const uint8_t *)p); } static inline uint32_t get_unaligned_le32(const void *p) { return __get_unaligned_le32((const uint8_t *)p); } static inline uint64_t get_unaligned_le64(const void *p) { return __get_unaligned_le64((const uint8_t *)p); } static inline void put_unaligned_le16(uint16_t val, void *p) { __put_unaligned_le16(val, p); } static inline void put_unaligned_le32(uint32_t val, void *p) { __put_unaligned_le32(val, p); } static inline void put_unaligned_le64(uint64_t val, void *p) { __put_unaligned_le64(val, p); } #endif /* _TOOLS_LE_BYTESHIFT_H */
{'repo_name': 'GrapheneOS/linux-hardened', 'stars': '324', 'repo_language': 'C', 'file_name': 'wlan_bssdef.h', 'mime_type': 'text/x-c', 'hash': -2150244407949210961, 'source_dataset': 'data'}
/* FUSE: Filesystem in Userspace Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu> This program can be distributed under the terms of the GNU GPL. See the file COPYING. */ #include "fuse_i.h" #include <linux/init.h> #include <linux/module.h> #include <linux/poll.h> #include <linux/uio.h> #include <linux/miscdevice.h> #include <linux/pagemap.h> #include <linux/file.h> #include <linux/slab.h> #include <linux/pipe_fs_i.h> #include <linux/swap.h> #include <linux/splice.h> MODULE_ALIAS_MISCDEV(FUSE_MINOR); MODULE_ALIAS("devname:fuse"); static struct kmem_cache *fuse_req_cachep; static struct fuse_conn *fuse_get_conn(struct file *file) { /* * Lockless access is OK, because file->private data is set * once during mount and is valid until the file is released. */ return file->private_data; } static void fuse_request_init(struct fuse_req *req) { memset(req, 0, sizeof(*req)); INIT_LIST_HEAD(&req->list); INIT_LIST_HEAD(&req->intr_entry); init_waitqueue_head(&req->waitq); atomic_set(&req->count, 1); } struct fuse_req *fuse_request_alloc(void) { struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_KERNEL); if (req) fuse_request_init(req); return req; } EXPORT_SYMBOL_GPL(fuse_request_alloc); struct fuse_req *fuse_request_alloc_nofs(void) { struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, GFP_NOFS); if (req) fuse_request_init(req); return req; } void fuse_request_free(struct fuse_req *req) { kmem_cache_free(fuse_req_cachep, req); } static void block_sigs(sigset_t *oldset) { sigset_t mask; siginitsetinv(&mask, sigmask(SIGKILL)); sigprocmask(SIG_BLOCK, &mask, oldset); } static void restore_sigs(sigset_t *oldset) { sigprocmask(SIG_SETMASK, oldset, NULL); } static void __fuse_get_request(struct fuse_req *req) { atomic_inc(&req->count); } /* Must be called with > 1 refcount */ static void __fuse_put_request(struct fuse_req *req) { BUG_ON(atomic_read(&req->count) < 2); atomic_dec(&req->count); } static void fuse_req_init_context(struct fuse_req *req) { req->in.h.uid = current_fsuid(); req->in.h.gid = current_fsgid(); req->in.h.pid = current->pid; } struct fuse_req *fuse_get_req(struct fuse_conn *fc) { struct fuse_req *req; sigset_t oldset; int intr; int err; atomic_inc(&fc->num_waiting); block_sigs(&oldset); intr = wait_event_interruptible(fc->blocked_waitq, !fc->blocked); restore_sigs(&oldset); err = -EINTR; if (intr) goto out; err = -ENOTCONN; if (!fc->connected) goto out; req = fuse_request_alloc(); err = -ENOMEM; if (!req) goto out; fuse_req_init_context(req); req->waiting = 1; return req; out: atomic_dec(&fc->num_waiting); return ERR_PTR(err); } EXPORT_SYMBOL_GPL(fuse_get_req); /* * Return request in fuse_file->reserved_req. However that may * currently be in use. If that is the case, wait for it to become * available. */ static struct fuse_req *get_reserved_req(struct fuse_conn *fc, struct file *file) { struct fuse_req *req = NULL; struct fuse_file *ff = file->private_data; do { wait_event(fc->reserved_req_waitq, ff->reserved_req); spin_lock(&fc->lock); if (ff->reserved_req) { req = ff->reserved_req; ff->reserved_req = NULL; get_file(file); req->stolen_file = file; } spin_unlock(&fc->lock); } while (!req); return req; } /* * Put stolen request back into fuse_file->reserved_req */ static void put_reserved_req(struct fuse_conn *fc, struct fuse_req *req) { struct file *file = req->stolen_file; struct fuse_file *ff = file->private_data; spin_lock(&fc->lock); fuse_request_init(req); BUG_ON(ff->reserved_req); ff->reserved_req = req; wake_up_all(&fc->reserved_req_waitq); spin_unlock(&fc->lock); fput(file); } /* * Gets a requests for a file operation, always succeeds * * This is used for sending the FLUSH request, which must get to * userspace, due to POSIX locks which may need to be unlocked. * * If allocation fails due to OOM, use the reserved request in * fuse_file. * * This is very unlikely to deadlock accidentally, since the * filesystem should not have it's own file open. If deadlock is * intentional, it can still be broken by "aborting" the filesystem. */ struct fuse_req *fuse_get_req_nofail(struct fuse_conn *fc, struct file *file) { struct fuse_req *req; atomic_inc(&fc->num_waiting); wait_event(fc->blocked_waitq, !fc->blocked); req = fuse_request_alloc(); if (!req) req = get_reserved_req(fc, file); fuse_req_init_context(req); req->waiting = 1; return req; } void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req) { if (atomic_dec_and_test(&req->count)) { if (req->waiting) atomic_dec(&fc->num_waiting); if (req->stolen_file) put_reserved_req(fc, req); else fuse_request_free(req); } } EXPORT_SYMBOL_GPL(fuse_put_request); static unsigned len_args(unsigned numargs, struct fuse_arg *args) { unsigned nbytes = 0; unsigned i; for (i = 0; i < numargs; i++) nbytes += args[i].size; return nbytes; } static u64 fuse_get_unique(struct fuse_conn *fc) { fc->reqctr++; /* zero is special */ if (fc->reqctr == 0) fc->reqctr = 1; return fc->reqctr; } static void queue_request(struct fuse_conn *fc, struct fuse_req *req) { req->in.h.len = sizeof(struct fuse_in_header) + len_args(req->in.numargs, (struct fuse_arg *) req->in.args); list_add_tail(&req->list, &fc->pending); req->state = FUSE_REQ_PENDING; if (!req->waiting) { req->waiting = 1; atomic_inc(&fc->num_waiting); } wake_up(&fc->waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } static void flush_bg_queue(struct fuse_conn *fc) { while (fc->active_background < fc->max_background && !list_empty(&fc->bg_queue)) { struct fuse_req *req; req = list_entry(fc->bg_queue.next, struct fuse_req, list); list_del(&req->list); fc->active_background++; req->in.h.unique = fuse_get_unique(fc); queue_request(fc, req); } } /* * This function is called when a request is finished. Either a reply * has arrived or it was aborted (and not yet sent) or some error * occurred during communication with userspace, or the device file * was closed. The requester thread is woken up (if still waiting), * the 'end' callback is called if given, else the reference to the * request is released * * Called with fc->lock, unlocks it */ static void request_end(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) { void (*end) (struct fuse_conn *, struct fuse_req *) = req->end; req->end = NULL; list_del(&req->list); list_del(&req->intr_entry); req->state = FUSE_REQ_FINISHED; if (req->background) { if (fc->num_background == fc->max_background) { fc->blocked = 0; wake_up_all(&fc->blocked_waitq); } if (fc->num_background == fc->congestion_threshold && fc->connected && fc->bdi_initialized) { clear_bdi_congested(&fc->bdi, BLK_RW_SYNC); clear_bdi_congested(&fc->bdi, BLK_RW_ASYNC); } fc->num_background--; fc->active_background--; flush_bg_queue(fc); } spin_unlock(&fc->lock); wake_up(&req->waitq); if (end) end(fc, req); fuse_put_request(fc, req); } static void wait_answer_interruptible(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) __acquires(fc->lock) { if (signal_pending(current)) return; spin_unlock(&fc->lock); wait_event_interruptible(req->waitq, req->state == FUSE_REQ_FINISHED); spin_lock(&fc->lock); } static void queue_interrupt(struct fuse_conn *fc, struct fuse_req *req) { list_add_tail(&req->intr_entry, &fc->interrupts); wake_up(&fc->waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } static void request_wait_answer(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) __acquires(fc->lock) { if (!fc->no_interrupt) { /* Any signal may interrupt this */ wait_answer_interruptible(fc, req); if (req->aborted) goto aborted; if (req->state == FUSE_REQ_FINISHED) return; req->interrupted = 1; if (req->state == FUSE_REQ_SENT) queue_interrupt(fc, req); } if (!req->force) { sigset_t oldset; /* Only fatal signals may interrupt this */ block_sigs(&oldset); wait_answer_interruptible(fc, req); restore_sigs(&oldset); if (req->aborted) goto aborted; if (req->state == FUSE_REQ_FINISHED) return; /* Request is not yet in userspace, bail out */ if (req->state == FUSE_REQ_PENDING) { list_del(&req->list); __fuse_put_request(req); req->out.h.error = -EINTR; return; } } /* * Either request is already in userspace, or it was forced. * Wait it out. */ spin_unlock(&fc->lock); wait_event(req->waitq, req->state == FUSE_REQ_FINISHED); spin_lock(&fc->lock); if (!req->aborted) return; aborted: BUG_ON(req->state != FUSE_REQ_FINISHED); if (req->locked) { /* This is uninterruptible sleep, because data is being copied to/from the buffers of req. During locked state, there mustn't be any filesystem operation (e.g. page fault), since that could lead to deadlock */ spin_unlock(&fc->lock); wait_event(req->waitq, !req->locked); spin_lock(&fc->lock); } } void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 1; spin_lock(&fc->lock); if (!fc->connected) req->out.h.error = -ENOTCONN; else if (fc->conn_error) req->out.h.error = -ECONNREFUSED; else { req->in.h.unique = fuse_get_unique(fc); queue_request(fc, req); /* acquire extra reference, since request is still needed after request_end() */ __fuse_get_request(req); request_wait_answer(fc, req); } spin_unlock(&fc->lock); } EXPORT_SYMBOL_GPL(fuse_request_send); static void fuse_request_send_nowait_locked(struct fuse_conn *fc, struct fuse_req *req) { req->background = 1; fc->num_background++; if (fc->num_background == fc->max_background) fc->blocked = 1; if (fc->num_background == fc->congestion_threshold && fc->bdi_initialized) { set_bdi_congested(&fc->bdi, BLK_RW_SYNC); set_bdi_congested(&fc->bdi, BLK_RW_ASYNC); } list_add_tail(&req->list, &fc->bg_queue); flush_bg_queue(fc); } static void fuse_request_send_nowait(struct fuse_conn *fc, struct fuse_req *req) { spin_lock(&fc->lock); if (fc->connected) { fuse_request_send_nowait_locked(fc, req); spin_unlock(&fc->lock); } else { req->out.h.error = -ENOTCONN; request_end(fc, req); } } void fuse_request_send_noreply(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 0; fuse_request_send_nowait(fc, req); } void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 1; fuse_request_send_nowait(fc, req); } EXPORT_SYMBOL_GPL(fuse_request_send_background); static int fuse_request_send_notify_reply(struct fuse_conn *fc, struct fuse_req *req, u64 unique) { int err = -ENODEV; req->isreply = 0; req->in.h.unique = unique; spin_lock(&fc->lock); if (fc->connected) { queue_request(fc, req); err = 0; } spin_unlock(&fc->lock); return err; } /* * Called under fc->lock * * fc->connected must have been checked previously */ void fuse_request_send_background_locked(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 1; fuse_request_send_nowait_locked(fc, req); } /* * Lock the request. Up to the next unlock_request() there mustn't be * anything that could cause a page-fault. If the request was already * aborted bail out. */ static int lock_request(struct fuse_conn *fc, struct fuse_req *req) { int err = 0; if (req) { spin_lock(&fc->lock); if (req->aborted) err = -ENOENT; else req->locked = 1; spin_unlock(&fc->lock); } return err; } /* * Unlock request. If it was aborted during being locked, the * requester thread is currently waiting for it to be unlocked, so * wake it up. */ static void unlock_request(struct fuse_conn *fc, struct fuse_req *req) { if (req) { spin_lock(&fc->lock); req->locked = 0; if (req->aborted) wake_up(&req->waitq); spin_unlock(&fc->lock); } } struct fuse_copy_state { struct fuse_conn *fc; int write; struct fuse_req *req; const struct iovec *iov; struct pipe_buffer *pipebufs; struct pipe_buffer *currbuf; struct pipe_inode_info *pipe; unsigned long nr_segs; unsigned long seglen; unsigned long addr; struct page *pg; void *mapaddr; void *buf; unsigned len; unsigned move_pages:1; }; static void fuse_copy_init(struct fuse_copy_state *cs, struct fuse_conn *fc, int write, const struct iovec *iov, unsigned long nr_segs) { memset(cs, 0, sizeof(*cs)); cs->fc = fc; cs->write = write; cs->iov = iov; cs->nr_segs = nr_segs; } /* Unmap and put previous page of userspace buffer */ static void fuse_copy_finish(struct fuse_copy_state *cs) { if (cs->currbuf) { struct pipe_buffer *buf = cs->currbuf; if (!cs->write) { buf->ops->unmap(cs->pipe, buf, cs->mapaddr); } else { kunmap(buf->page); buf->len = PAGE_SIZE - cs->len; } cs->currbuf = NULL; cs->mapaddr = NULL; } else if (cs->mapaddr) { kunmap(cs->pg); if (cs->write) { flush_dcache_page(cs->pg); set_page_dirty_lock(cs->pg); } put_page(cs->pg); cs->mapaddr = NULL; } } /* * Get another pagefull of userspace buffer, and map it to kernel * address space, and lock request */ static int fuse_copy_fill(struct fuse_copy_state *cs) { unsigned long offset; int err; unlock_request(cs->fc, cs->req); fuse_copy_finish(cs); if (cs->pipebufs) { struct pipe_buffer *buf = cs->pipebufs; if (!cs->write) { err = buf->ops->confirm(cs->pipe, buf); if (err) return err; BUG_ON(!cs->nr_segs); cs->currbuf = buf; cs->mapaddr = buf->ops->map(cs->pipe, buf, 0); cs->len = buf->len; cs->buf = cs->mapaddr + buf->offset; cs->pipebufs++; cs->nr_segs--; } else { struct page *page; if (cs->nr_segs == cs->pipe->buffers) return -EIO; page = alloc_page(GFP_HIGHUSER); if (!page) return -ENOMEM; buf->page = page; buf->offset = 0; buf->len = 0; cs->currbuf = buf; cs->mapaddr = kmap(page); cs->buf = cs->mapaddr; cs->len = PAGE_SIZE; cs->pipebufs++; cs->nr_segs++; } } else { if (!cs->seglen) { BUG_ON(!cs->nr_segs); cs->seglen = cs->iov[0].iov_len; cs->addr = (unsigned long) cs->iov[0].iov_base; cs->iov++; cs->nr_segs--; } err = get_user_pages_fast(cs->addr, 1, cs->write, &cs->pg); if (err < 0) return err; BUG_ON(err != 1); offset = cs->addr % PAGE_SIZE; cs->mapaddr = kmap(cs->pg); cs->buf = cs->mapaddr + offset; cs->len = min(PAGE_SIZE - offset, cs->seglen); cs->seglen -= cs->len; cs->addr += cs->len; } return lock_request(cs->fc, cs->req); } /* Do as much copy to/from userspace buffer as we can */ static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size) { unsigned ncpy = min(*size, cs->len); if (val) { if (cs->write) memcpy(cs->buf, *val, ncpy); else memcpy(*val, cs->buf, ncpy); *val += ncpy; } *size -= ncpy; cs->len -= ncpy; cs->buf += ncpy; return ncpy; } static int fuse_check_page(struct page *page) { if (page_mapcount(page) || page->mapping != NULL || page_count(page) != 1 || (page->flags & PAGE_FLAGS_CHECK_AT_PREP & ~(1 << PG_locked | 1 << PG_referenced | 1 << PG_uptodate | 1 << PG_lru | 1 << PG_active | 1 << PG_reclaim))) { printk(KERN_WARNING "fuse: trying to steal weird page\n"); printk(KERN_WARNING " page=%p index=%li flags=%08lx, count=%i, mapcount=%i, mapping=%p\n", page, page->index, page->flags, page_count(page), page_mapcount(page), page->mapping); return 1; } return 0; } static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep) { int err; struct page *oldpage = *pagep; struct page *newpage; struct pipe_buffer *buf = cs->pipebufs; struct address_space *mapping; pgoff_t index; unlock_request(cs->fc, cs->req); fuse_copy_finish(cs); err = buf->ops->confirm(cs->pipe, buf); if (err) return err; BUG_ON(!cs->nr_segs); cs->currbuf = buf; cs->len = buf->len; cs->pipebufs++; cs->nr_segs--; if (cs->len != PAGE_SIZE) goto out_fallback; if (buf->ops->steal(cs->pipe, buf) != 0) goto out_fallback; newpage = buf->page; if (WARN_ON(!PageUptodate(newpage))) return -EIO; ClearPageMappedToDisk(newpage); if (fuse_check_page(newpage) != 0) goto out_fallback_unlock; mapping = oldpage->mapping; index = oldpage->index; /* * This is a new and locked page, it shouldn't be mapped or * have any special flags on it */ if (WARN_ON(page_mapped(oldpage))) goto out_fallback_unlock; if (WARN_ON(page_has_private(oldpage))) goto out_fallback_unlock; if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage))) goto out_fallback_unlock; if (WARN_ON(PageMlocked(oldpage))) goto out_fallback_unlock; remove_from_page_cache(oldpage); page_cache_release(oldpage); err = add_to_page_cache_locked(newpage, mapping, index, GFP_KERNEL); if (err) { printk(KERN_WARNING "fuse_try_move_page: failed to add page"); goto out_fallback_unlock; } page_cache_get(newpage); if (!(buf->flags & PIPE_BUF_FLAG_LRU)) lru_cache_add_file(newpage); err = 0; spin_lock(&cs->fc->lock); if (cs->req->aborted) err = -ENOENT; else *pagep = newpage; spin_unlock(&cs->fc->lock); if (err) { unlock_page(newpage); page_cache_release(newpage); return err; } unlock_page(oldpage); page_cache_release(oldpage); cs->len = 0; return 0; out_fallback_unlock: unlock_page(newpage); out_fallback: cs->mapaddr = buf->ops->map(cs->pipe, buf, 1); cs->buf = cs->mapaddr + buf->offset; err = lock_request(cs->fc, cs->req); if (err) return err; return 1; } static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page, unsigned offset, unsigned count) { struct pipe_buffer *buf; if (cs->nr_segs == cs->pipe->buffers) return -EIO; unlock_request(cs->fc, cs->req); fuse_copy_finish(cs); buf = cs->pipebufs; page_cache_get(page); buf->page = page; buf->offset = offset; buf->len = count; cs->pipebufs++; cs->nr_segs++; cs->len = 0; return 0; } /* * Copy a page in the request to/from the userspace buffer. Must be * done atomically */ static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep, unsigned offset, unsigned count, int zeroing) { int err; struct page *page = *pagep; if (page && zeroing && count < PAGE_SIZE) { void *mapaddr = kmap_atomic(page, KM_USER1); memset(mapaddr, 0, PAGE_SIZE); kunmap_atomic(mapaddr, KM_USER1); } while (count) { if (cs->write && cs->pipebufs && page) { return fuse_ref_page(cs, page, offset, count); } else if (!cs->len) { if (cs->move_pages && page && offset == 0 && count == PAGE_SIZE) { err = fuse_try_move_page(cs, pagep); if (err <= 0) return err; } else { err = fuse_copy_fill(cs); if (err) return err; } } if (page) { void *mapaddr = kmap_atomic(page, KM_USER1); void *buf = mapaddr + offset; offset += fuse_copy_do(cs, &buf, &count); kunmap_atomic(mapaddr, KM_USER1); } else offset += fuse_copy_do(cs, NULL, &count); } if (page && !cs->write) flush_dcache_page(page); return 0; } /* Copy pages in the request to/from userspace buffer */ static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes, int zeroing) { unsigned i; struct fuse_req *req = cs->req; unsigned offset = req->page_offset; unsigned count = min(nbytes, (unsigned) PAGE_SIZE - offset); for (i = 0; i < req->num_pages && (nbytes || zeroing); i++) { int err; err = fuse_copy_page(cs, &req->pages[i], offset, count, zeroing); if (err) return err; nbytes -= count; count = min(nbytes, (unsigned) PAGE_SIZE); offset = 0; } return 0; } /* Copy a single argument in the request to/from userspace buffer */ static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size) { while (size) { if (!cs->len) { int err = fuse_copy_fill(cs); if (err) return err; } fuse_copy_do(cs, &val, &size); } return 0; } /* Copy request arguments to/from userspace buffer */ static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs, unsigned argpages, struct fuse_arg *args, int zeroing) { int err = 0; unsigned i; for (i = 0; !err && i < numargs; i++) { struct fuse_arg *arg = &args[i]; if (i == numargs - 1 && argpages) err = fuse_copy_pages(cs, arg->size, zeroing); else err = fuse_copy_one(cs, arg->value, arg->size); } return err; } static int request_pending(struct fuse_conn *fc) { return !list_empty(&fc->pending) || !list_empty(&fc->interrupts); } /* Wait until a request is available on the pending list */ static void request_wait(struct fuse_conn *fc) __releases(fc->lock) __acquires(fc->lock) { DECLARE_WAITQUEUE(wait, current); add_wait_queue_exclusive(&fc->waitq, &wait); while (fc->connected && !request_pending(fc)) { set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) break; spin_unlock(&fc->lock); schedule(); spin_lock(&fc->lock); } set_current_state(TASK_RUNNING); remove_wait_queue(&fc->waitq, &wait); } /* * Transfer an interrupt request to userspace * * Unlike other requests this is assembled on demand, without a need * to allocate a separate fuse_req structure. * * Called with fc->lock held, releases it */ static int fuse_read_interrupt(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes, struct fuse_req *req) __releases(fc->lock) { struct fuse_in_header ih; struct fuse_interrupt_in arg; unsigned reqsize = sizeof(ih) + sizeof(arg); int err; list_del_init(&req->intr_entry); req->intr_unique = fuse_get_unique(fc); memset(&ih, 0, sizeof(ih)); memset(&arg, 0, sizeof(arg)); ih.len = reqsize; ih.opcode = FUSE_INTERRUPT; ih.unique = req->intr_unique; arg.unique = req->in.h.unique; spin_unlock(&fc->lock); if (nbytes < reqsize) return -EINVAL; err = fuse_copy_one(cs, &ih, sizeof(ih)); if (!err) err = fuse_copy_one(cs, &arg, sizeof(arg)); fuse_copy_finish(cs); return err ? err : reqsize; } /* * Read a single request into the userspace filesystem's buffer. This * function waits until a request is available, then removes it from * the pending list and copies request data to userspace buffer. If * no reply is needed (FORGET) or request has been aborted or there * was an error during the copying then it's finished by calling * request_end(). Otherwise add it to the processing list, and set * the 'sent' flag. */ static ssize_t fuse_dev_do_read(struct fuse_conn *fc, struct file *file, struct fuse_copy_state *cs, size_t nbytes) { int err; struct fuse_req *req; struct fuse_in *in; unsigned reqsize; restart: spin_lock(&fc->lock); err = -EAGAIN; if ((file->f_flags & O_NONBLOCK) && fc->connected && !request_pending(fc)) goto err_unlock; request_wait(fc); err = -ENODEV; if (!fc->connected) goto err_unlock; err = -ERESTARTSYS; if (!request_pending(fc)) goto err_unlock; if (!list_empty(&fc->interrupts)) { req = list_entry(fc->interrupts.next, struct fuse_req, intr_entry); return fuse_read_interrupt(fc, cs, nbytes, req); } req = list_entry(fc->pending.next, struct fuse_req, list); req->state = FUSE_REQ_READING; list_move(&req->list, &fc->io); in = &req->in; reqsize = in->h.len; /* If request is too large, reply with an error and restart the read */ if (nbytes < reqsize) { req->out.h.error = -EIO; /* SETXATTR is special, since it may contain too large data */ if (in->h.opcode == FUSE_SETXATTR) req->out.h.error = -E2BIG; request_end(fc, req); goto restart; } spin_unlock(&fc->lock); cs->req = req; err = fuse_copy_one(cs, &in->h, sizeof(in->h)); if (!err) err = fuse_copy_args(cs, in->numargs, in->argpages, (struct fuse_arg *) in->args, 0); fuse_copy_finish(cs); spin_lock(&fc->lock); req->locked = 0; if (req->aborted) { request_end(fc, req); return -ENODEV; } if (err) { req->out.h.error = -EIO; request_end(fc, req); return err; } if (!req->isreply) request_end(fc, req); else { req->state = FUSE_REQ_SENT; list_move_tail(&req->list, &fc->processing); if (req->interrupted) queue_interrupt(fc, req); spin_unlock(&fc->lock); } return reqsize; err_unlock: spin_unlock(&fc->lock); return err; } static ssize_t fuse_dev_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct fuse_copy_state cs; struct file *file = iocb->ki_filp; struct fuse_conn *fc = fuse_get_conn(file); if (!fc) return -EPERM; fuse_copy_init(&cs, fc, 1, iov, nr_segs); return fuse_dev_do_read(fc, file, &cs, iov_length(iov, nr_segs)); } static int fuse_dev_pipe_buf_steal(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { return 1; } static const struct pipe_buf_operations fuse_dev_pipe_buf_ops = { .can_merge = 0, .map = generic_pipe_buf_map, .unmap = generic_pipe_buf_unmap, .confirm = generic_pipe_buf_confirm, .release = generic_pipe_buf_release, .steal = fuse_dev_pipe_buf_steal, .get = generic_pipe_buf_get, }; static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { int ret; int page_nr = 0; int do_wakeup = 0; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_conn *fc = fuse_get_conn(in); if (!fc) return -EPERM; bufs = kmalloc(pipe->buffers * sizeof (struct pipe_buffer), GFP_KERNEL); if (!bufs) return -ENOMEM; fuse_copy_init(&cs, fc, 1, NULL, 0); cs.pipebufs = bufs; cs.pipe = pipe; ret = fuse_dev_do_read(fc, in, &cs, len); if (ret < 0) goto out; ret = 0; pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; goto out_unlock; } if (pipe->nrbufs + cs.nr_segs > pipe->buffers) { ret = -EIO; goto out_unlock; } while (page_nr < cs.nr_segs) { int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + newbuf; buf->page = bufs[page_nr].page; buf->offset = bufs[page_nr].offset; buf->len = bufs[page_nr].len; buf->ops = &fuse_dev_pipe_buf_ops; pipe->nrbufs++; page_nr++; ret += buf->len; if (pipe->inode) do_wakeup = 1; } out_unlock: pipe_unlock(pipe); if (do_wakeup) { smp_mb(); if (waitqueue_active(&pipe->wait)) wake_up_interruptible(&pipe->wait); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } out: for (; page_nr < cs.nr_segs; page_nr++) page_cache_release(bufs[page_nr].page); kfree(bufs); return ret; } static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_poll_wakeup_out outarg; int err = -EINVAL; if (size != sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; fuse_copy_finish(cs); return fuse_notify_poll_wakeup(fc, &outarg); err: fuse_copy_finish(cs); return err; } static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_inode_out outarg; int err = -EINVAL; if (size != sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; fuse_copy_finish(cs); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) { err = fuse_reverse_inval_inode(fc->sb, outarg.ino, outarg.off, outarg.len); } up_read(&fc->killsb); return err; err: fuse_copy_finish(cs); return err; } static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_entry_out outarg; int err = -ENOMEM; char *buf; struct qstr name; buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL); if (!buf) goto err; err = -EINVAL; if (size < sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; err = -ENAMETOOLONG; if (outarg.namelen > FUSE_NAME_MAX) goto err; name.name = buf; name.len = outarg.namelen; err = fuse_copy_one(cs, buf, outarg.namelen + 1); if (err) goto err; fuse_copy_finish(cs); buf[outarg.namelen] = 0; name.hash = full_name_hash(name.name, name.len); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) err = fuse_reverse_inval_entry(fc->sb, outarg.parent, &name); up_read(&fc->killsb); kfree(buf); return err; err: kfree(buf); fuse_copy_finish(cs); return err; } static int fuse_notify_store(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_store_out outarg; struct inode *inode; struct address_space *mapping; u64 nodeid; int err; pgoff_t index; unsigned int offset; unsigned int num; loff_t file_size; loff_t end; err = -EINVAL; if (size < sizeof(outarg)) goto out_finish; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto out_finish; err = -EINVAL; if (size - sizeof(outarg) != outarg.size) goto out_finish; nodeid = outarg.nodeid; down_read(&fc->killsb); err = -ENOENT; if (!fc->sb) goto out_up_killsb; inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid); if (!inode) goto out_up_killsb; mapping = inode->i_mapping; index = outarg.offset >> PAGE_CACHE_SHIFT; offset = outarg.offset & ~PAGE_CACHE_MASK; file_size = i_size_read(inode); end = outarg.offset + outarg.size; if (end > file_size) { file_size = end; fuse_write_update_size(inode, file_size); } num = outarg.size; while (num) { struct page *page; unsigned int this_num; err = -ENOMEM; page = find_or_create_page(mapping, index, mapping_gfp_mask(mapping)); if (!page) goto out_iput; this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset); err = fuse_copy_page(cs, &page, offset, this_num, 0); if (!err && offset == 0 && (num != 0 || file_size == end)) SetPageUptodate(page); unlock_page(page); page_cache_release(page); if (err) goto out_iput; num -= this_num; offset = 0; index++; } err = 0; out_iput: iput(inode); out_up_killsb: up_read(&fc->killsb); out_finish: fuse_copy_finish(cs); return err; } static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_req *req) { int i; for (i = 0; i < req->num_pages; i++) { struct page *page = req->pages[i]; page_cache_release(page); } } static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode, struct fuse_notify_retrieve_out *outarg) { int err; struct address_space *mapping = inode->i_mapping; struct fuse_req *req; pgoff_t index; loff_t file_size; unsigned int num; unsigned int offset; size_t total_len = 0; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); offset = outarg->offset & ~PAGE_CACHE_MASK; req->in.h.opcode = FUSE_NOTIFY_REPLY; req->in.h.nodeid = outarg->nodeid; req->in.numargs = 2; req->in.argpages = 1; req->page_offset = offset; req->end = fuse_retrieve_end; index = outarg->offset >> PAGE_CACHE_SHIFT; file_size = i_size_read(inode); num = outarg->size; if (outarg->offset > file_size) num = 0; else if (outarg->offset + num > file_size) num = file_size - outarg->offset; while (num) { struct page *page; unsigned int this_num; page = find_get_page(mapping, index); if (!page) break; this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset); req->pages[req->num_pages] = page; req->num_pages++; num -= this_num; total_len += this_num; } req->misc.retrieve_in.offset = outarg->offset; req->misc.retrieve_in.size = total_len; req->in.args[0].size = sizeof(req->misc.retrieve_in); req->in.args[0].value = &req->misc.retrieve_in; req->in.args[1].size = total_len; err = fuse_request_send_notify_reply(fc, req, outarg->notify_unique); if (err) fuse_retrieve_end(fc, req); return err; } static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_retrieve_out outarg; struct inode *inode; int err; err = -EINVAL; if (size != sizeof(outarg)) goto copy_finish; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto copy_finish; fuse_copy_finish(cs); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) { u64 nodeid = outarg.nodeid; inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid); if (inode) { err = fuse_retrieve(fc, inode, &outarg); iput(inode); } } up_read(&fc->killsb); return err; copy_finish: fuse_copy_finish(cs); return err; } static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code, unsigned int size, struct fuse_copy_state *cs) { switch (code) { case FUSE_NOTIFY_POLL: return fuse_notify_poll(fc, size, cs); case FUSE_NOTIFY_INVAL_INODE: return fuse_notify_inval_inode(fc, size, cs); case FUSE_NOTIFY_INVAL_ENTRY: return fuse_notify_inval_entry(fc, size, cs); case FUSE_NOTIFY_STORE: return fuse_notify_store(fc, size, cs); case FUSE_NOTIFY_RETRIEVE: return fuse_notify_retrieve(fc, size, cs); default: fuse_copy_finish(cs); return -EINVAL; } } /* Look up request on processing list by unique ID */ static struct fuse_req *request_find(struct fuse_conn *fc, u64 unique) { struct list_head *entry; list_for_each(entry, &fc->processing) { struct fuse_req *req; req = list_entry(entry, struct fuse_req, list); if (req->in.h.unique == unique || req->intr_unique == unique) return req; } return NULL; } static int copy_out_args(struct fuse_copy_state *cs, struct fuse_out *out, unsigned nbytes) { unsigned reqsize = sizeof(struct fuse_out_header); if (out->h.error) return nbytes != reqsize ? -EINVAL : 0; reqsize += len_args(out->numargs, out->args); if (reqsize < nbytes || (reqsize > nbytes && !out->argvar)) return -EINVAL; else if (reqsize > nbytes) { struct fuse_arg *lastarg = &out->args[out->numargs-1]; unsigned diffsize = reqsize - nbytes; if (diffsize > lastarg->size) return -EINVAL; lastarg->size -= diffsize; } return fuse_copy_args(cs, out->numargs, out->argpages, out->args, out->page_zeroing); } /* * Write a single reply to a request. First the header is copied from * the write buffer. The request is then searched on the processing * list by the unique ID found in the header. If found, then remove * it from the list and copy the rest of the buffer to the request. * The request is finished by calling request_end() */ static ssize_t fuse_dev_do_write(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes) { int err; struct fuse_req *req; struct fuse_out_header oh; if (nbytes < sizeof(struct fuse_out_header)) return -EINVAL; err = fuse_copy_one(cs, &oh, sizeof(oh)); if (err) goto err_finish; err = -EINVAL; if (oh.len != nbytes) goto err_finish; /* * Zero oh.unique indicates unsolicited notification message * and error contains notification code. */ if (!oh.unique) { err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs); return err ? err : nbytes; } err = -EINVAL; if (oh.error <= -1000 || oh.error > 0) goto err_finish; spin_lock(&fc->lock); err = -ENOENT; if (!fc->connected) goto err_unlock; req = request_find(fc, oh.unique); if (!req) goto err_unlock; if (req->aborted) { spin_unlock(&fc->lock); fuse_copy_finish(cs); spin_lock(&fc->lock); request_end(fc, req); return -ENOENT; } /* Is it an interrupt reply? */ if (req->intr_unique == oh.unique) { err = -EINVAL; if (nbytes != sizeof(struct fuse_out_header)) goto err_unlock; if (oh.error == -ENOSYS) fc->no_interrupt = 1; else if (oh.error == -EAGAIN) queue_interrupt(fc, req); spin_unlock(&fc->lock); fuse_copy_finish(cs); return nbytes; } req->state = FUSE_REQ_WRITING; list_move(&req->list, &fc->io); req->out.h = oh; req->locked = 1; cs->req = req; if (!req->out.page_replace) cs->move_pages = 0; spin_unlock(&fc->lock); err = copy_out_args(cs, &req->out, nbytes); fuse_copy_finish(cs); spin_lock(&fc->lock); req->locked = 0; if (!err) { if (req->aborted) err = -ENOENT; } else if (!req->aborted) req->out.h.error = -EIO; request_end(fc, req); return err ? err : nbytes; err_unlock: spin_unlock(&fc->lock); err_finish: fuse_copy_finish(cs); return err; } static ssize_t fuse_dev_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct fuse_copy_state cs; struct fuse_conn *fc = fuse_get_conn(iocb->ki_filp); if (!fc) return -EPERM; fuse_copy_init(&cs, fc, 0, iov, nr_segs); return fuse_dev_do_write(fc, &cs, iov_length(iov, nr_segs)); } static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { unsigned nbuf; unsigned idx; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_conn *fc; size_t rem; ssize_t ret; fc = fuse_get_conn(out); if (!fc) return -EPERM; bufs = kmalloc(pipe->buffers * sizeof (struct pipe_buffer), GFP_KERNEL); if (!bufs) return -ENOMEM; pipe_lock(pipe); nbuf = 0; rem = 0; for (idx = 0; idx < pipe->nrbufs && rem < len; idx++) rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len; ret = -EINVAL; if (rem < len) { pipe_unlock(pipe); goto out; } rem = len; while (rem) { struct pipe_buffer *ibuf; struct pipe_buffer *obuf; BUG_ON(nbuf >= pipe->buffers); BUG_ON(!pipe->nrbufs); ibuf = &pipe->bufs[pipe->curbuf]; obuf = &bufs[nbuf]; if (rem >= ibuf->len) { *obuf = *ibuf; ibuf->ops = NULL; pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1); pipe->nrbufs--; } else { ibuf->ops->get(pipe, ibuf); *obuf = *ibuf; obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } nbuf++; rem -= obuf->len; } pipe_unlock(pipe); fuse_copy_init(&cs, fc, 0, NULL, nbuf); cs.pipebufs = bufs; cs.pipe = pipe; if (flags & SPLICE_F_MOVE) cs.move_pages = 1; ret = fuse_dev_do_write(fc, &cs, len); for (idx = 0; idx < nbuf; idx++) { struct pipe_buffer *buf = &bufs[idx]; buf->ops->release(pipe, buf); } out: kfree(bufs); return ret; } static unsigned fuse_dev_poll(struct file *file, poll_table *wait) { unsigned mask = POLLOUT | POLLWRNORM; struct fuse_conn *fc = fuse_get_conn(file); if (!fc) return POLLERR; poll_wait(file, &fc->waitq, wait); spin_lock(&fc->lock); if (!fc->connected) mask = POLLERR; else if (request_pending(fc)) mask |= POLLIN | POLLRDNORM; spin_unlock(&fc->lock); return mask; } /* * Abort all requests on the given list (pending or processing) * * This function releases and reacquires fc->lock */ static void end_requests(struct fuse_conn *fc, struct list_head *head) __releases(fc->lock) __acquires(fc->lock) { while (!list_empty(head)) { struct fuse_req *req; req = list_entry(head->next, struct fuse_req, list); req->out.h.error = -ECONNABORTED; request_end(fc, req); spin_lock(&fc->lock); } } /* * Abort requests under I/O * * The requests are set to aborted and finished, and the request * waiter is woken up. This will make request_wait_answer() wait * until the request is unlocked and then return. * * If the request is asynchronous, then the end function needs to be * called after waiting for the request to be unlocked (if it was * locked). */ static void end_io_requests(struct fuse_conn *fc) __releases(fc->lock) __acquires(fc->lock) { while (!list_empty(&fc->io)) { struct fuse_req *req = list_entry(fc->io.next, struct fuse_req, list); void (*end) (struct fuse_conn *, struct fuse_req *) = req->end; req->aborted = 1; req->out.h.error = -ECONNABORTED; req->state = FUSE_REQ_FINISHED; list_del_init(&req->list); wake_up(&req->waitq); if (end) { req->end = NULL; __fuse_get_request(req); spin_unlock(&fc->lock); wait_event(req->waitq, !req->locked); end(fc, req); fuse_put_request(fc, req); spin_lock(&fc->lock); } } } static void end_queued_requests(struct fuse_conn *fc) __releases(fc->lock) __acquires(fc->lock) { fc->max_background = UINT_MAX; flush_bg_queue(fc); end_requests(fc, &fc->pending); end_requests(fc, &fc->processing); } /* * Abort all requests. * * Emergency exit in case of a malicious or accidental deadlock, or * just a hung filesystem. * * The same effect is usually achievable through killing the * filesystem daemon and all users of the filesystem. The exception * is the combination of an asynchronous request and the tricky * deadlock (see Documentation/filesystems/fuse.txt). * * During the aborting, progression of requests from the pending and * processing lists onto the io list, and progression of new requests * onto the pending list is prevented by req->connected being false. * * Progression of requests under I/O to the processing list is * prevented by the req->aborted flag being true for these requests. * For this reason requests on the io list must be aborted first. */ void fuse_abort_conn(struct fuse_conn *fc) { spin_lock(&fc->lock); if (fc->connected) { fc->connected = 0; fc->blocked = 0; end_io_requests(fc); end_queued_requests(fc); wake_up_all(&fc->waitq); wake_up_all(&fc->blocked_waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } spin_unlock(&fc->lock); } EXPORT_SYMBOL_GPL(fuse_abort_conn); int fuse_dev_release(struct inode *inode, struct file *file) { struct fuse_conn *fc = fuse_get_conn(file); if (fc) { spin_lock(&fc->lock); fc->connected = 0; fc->blocked = 0; end_queued_requests(fc); wake_up_all(&fc->blocked_waitq); spin_unlock(&fc->lock); fuse_conn_put(fc); } return 0; } EXPORT_SYMBOL_GPL(fuse_dev_release); static int fuse_dev_fasync(int fd, struct file *file, int on) { struct fuse_conn *fc = fuse_get_conn(file); if (!fc) return -EPERM; /* No locking - fasync_helper does its own locking */ return fasync_helper(fd, file, on, &fc->fasync); } const struct file_operations fuse_dev_operations = { .owner = THIS_MODULE, .llseek = no_llseek, .read = do_sync_read, .aio_read = fuse_dev_read, .splice_read = fuse_dev_splice_read, .write = do_sync_write, .aio_write = fuse_dev_write, .splice_write = fuse_dev_splice_write, .poll = fuse_dev_poll, .release = fuse_dev_release, .fasync = fuse_dev_fasync, }; EXPORT_SYMBOL_GPL(fuse_dev_operations); static struct miscdevice fuse_miscdevice = { .minor = FUSE_MINOR, .name = "fuse", .fops = &fuse_dev_operations, }; int __init fuse_dev_init(void) { int err = -ENOMEM; fuse_req_cachep = kmem_cache_create("fuse_request", sizeof(struct fuse_req), 0, 0, NULL); if (!fuse_req_cachep) goto out; err = misc_register(&fuse_miscdevice); if (err) goto out_cache_clean; return 0; out_cache_clean: kmem_cache_destroy(fuse_req_cachep); out: return err; } void fuse_dev_cleanup(void) { misc_deregister(&fuse_miscdevice); kmem_cache_destroy(fuse_req_cachep); }
{'repo_name': 'RMerl/asuswrt-merlin.ng', 'stars': '2126', 'repo_language': 'None', 'file_name': 'cpu_vect.h', 'mime_type': 'text/x-c', 'hash': -8089203584638942924, 'source_dataset': 'data'}
# paxos 声明: 1. 本文思路完成模仿 [朱一聪][1] 老师的的 [如何浅显易懂地解说 Paxos][2] 而得,版权属于 [朱一聪][3] 老师 。只是为了自己理解更加透彻,又重新推导了一下而已。文章发出已经获得 [朱一聪][4] 老师的同意。 2. 本文最后结论完全引用 [Paxos Made Simple][5] 中文翻译版 3. 学习 paxos 请优先选择 [Paxos Made Simple][6] 和 [Paxos lecture][7],不要选择本文。本文仅能起到引导思路的作用 4. 文章肯定有不严谨,推导不严谨的地方,欢迎讨论。 ### 背景: 在一个高可用分布式存储系统中,如果只使用一台机器,只要这台机器故障,系统就会崩溃。所以肯定需要多台机器,但是由于网络延迟,机器崩溃等原因,多台机器对于数据很难达成共识(Consensus not Consistency)。而 paxos 协议就是用来使各个机器达成共识的协议。 ### 如何理解共识(Consensus): 共识就是在一个或多个进程提议了一个值应当是什么后,使系统中所有进程对这个值达成一致意见。但是必须明确:在一个完全异步且可能出现任何故障的系统中,不存在一个算法可以确保达到共识([FLP Impossibility][8])。 ### 前提: #### 需要保证安全性: 1. 只有被提出的提案才能被选定 2. 只能有一个值被选定 3. 如果某个进程认为某个提案被选定了,那么这个提案必须是真的被选定的那个 #### 可能出现的场景 1. 进程之间的通信可能出现故障 2. 每个进程都可能提出不同的值 3. 每个进程也可能随时崩溃 4. 进程之间传输的数据不会篡改 #### 达成共识的条件 N 个进程中大多数(超过一半)进程都选定了同一个值 ### 推导流程 假设存在三个进程 p1 p2 p3,共同决定 v 的值 #### 1.1 每个进程只接受收到的第一个提案 ##### 场景 1.1.1 p1 proposal:v = a p2 proposal: v = b p3 proposal: 无 假设是 p1 的 proposal 优先到达 p3,p2 的 proposal 在到达 p3 时会被拒绝,系统就 v = a 达成了共识,反之如果 p2 的 proposal 优先到达,系统会就 v = b 达成共识。 ##### 场景 1.1.2 p1 proposal:v = a p2 proposal: v = b p3 proposal: v = c 这样每个机器只能接受自己机器上的 proposal,对于 v 的值就永远不能达成共识了。 ##### 结论 1.1: 1. 进程必须能够多次改写 v 的值,否则可能永远达不成共识 2. 进程必须接受第一个 proposal,否则可能永远达不成共识(系统只有一个提案时) #### 1.2 每个进程只接受 proposal_id 大的提案 根据 1.1 的结论,进程必须接受第一个 proposal, 所以需要一种拒绝策略或者修正后到达的 proposal 的 value 我们需要额外的信息作为依据来完成。 1. 我们得到哪些信息呢? 提出 proposal 进程的标识 process_id,当前进行到轮次 round_number(每个进程自增) 2. 这些信息有什么用? 这两个信息加在一起标识唯一的 proposal 暂定 proposal_id = round_number + process_id 3. 如何更新 proposal_id? 每个 process 的 proposal_id = max(proposal_id, a_proposal_id) ##### 场景 1.2.1 假设 p1_proposal_id > p2_proposal_id p1 proposal:v = a p2 proposal: v = b p3 proposal: 无 如果 p1 proposal 先到达 p3 ,p2 后到达,会形成 p1 proposal:v = a p2 proposal: v = a p3 proposal: v = a 系统就 v = a 达成共识。 ##### 场景 1.2.2 如果 p2 proposal 先到达 p3 , p1 后到达,p3 会先接受 p2 proposal,形成 p1 proposal:v = a p2 proposal: v = b p3 proposal: v = b 系统就 v = b 达成共识,因为 p1 proposal 也已经发出,接着又会形成 p1 proposal:v = a p2 proposal: v = a p3 proposal: v = a 系统又就 v = a 达成了共识。 在这个策略中,有两个值先后达成共识,不满足安全性。 ##### 结论 1.2: 按照现有 1.2 策略存在proposal id 小 proposal 先到达,系统多次就不同的值达成共识的问题。从如下几个角度思考解决此问题 1. p3 可以拒绝 p2 proposal(p2 proposal 先到达 p3,p2_proposal_id < p1_proposal_id ) 2. 限制 p1 提出的 proposal #### 1.3 p3 可以拒绝 p2 proposal 角度 1. 发送带有 proposal_id PreProposal, 2. 接收到 PreProposal 的进程,根据 proposal_id = max(proposal_id, accept_proposal_id) 进行更新 3. 进程发送 proposal 4. 每个进程只接受 proposal_id 大的 proposal 假设 p1_proposal_id > p2_proposal_id p1 proposal:v = a p2 proposal: v = b p3 proposal: 无 ##### 场景 1.3.1 1. p1_PreProposal 携带 p1_proposal_id 到达 p3 2. P3 更新 p3_proposal_id 为 p1_proposal_id, P2 更新 p2_proposal_id 为 p1_proposal_id 3. p2_PreProposal 携带 p2_proposal_id 到达,p2_proposal_id < p1_proposal_id,被拒绝。 4. p1_proposal (v = a)到达 p2, p3 5. 此时系统就 v = a 达成共识 - p1: v = a - p2: v = a - p3: v = a ##### 场景 1.3.2 1. p2_PreProposal 携带 p2_proposal_id 进行广播,到达 p3 2. P3 更新 p3_proposal_id 为 p2_proposal_id 3. p2_proposal (v = b)到达 p3,系统此时会就 v = b 达成共识 - p1: v = a - p2: v = b - p3: v = b 4. p1_PreProposal 携带 p1_proposal_id 进行广播,到达 p2, p3, p2_proposal_id < p1_proposal_id,p2 p3 更新 proposal_id 为 p1_proposal_id 5. p1_proposal (v = a)到达 p2, p3 6. 此时系统就 v = a 达成共识 - p1: v = a - p2: v = a - p3: v = a ##### 结论 1.3: 1.3 策略解决了一部分问题,但是还是依赖消息到达的先后顺序。在某些条件下还是不能保证安全性。 #### 1.4 限制 p1 提出的 proposal 现在已知 process_id round_number,还能得到哪些信息? 按照 1.3 的策略,我们只是更新了接受 pre_proposal 的 accept_process 的 proposal_id 为较大的 proposal_id,并没有回复给发送 pre_propoal 的 send_process 任何消息。是不是可以把 accept_process 已经获得的提案的 proposal_id 和 proposal 这样是不是限制 send_process 接下来发送的 proposal ?现在模拟一下流程,看看能否解决 1.3 中存在的问题。 1. 发送带有 proposal_id 的 PreProposal 2. 接收到 PreProposal 的进程,根据 proposal_id = max(proposal_id, accept_proposal_id) 进行更新,并回复当前进程已经接收到的 proposal_id 3. 进程发送 proposal 4. 每个进程只接受 proposal_id 大的 proposal 假设 p1_proposal_id > p2_proposal_id p1 proposal:v = a p2 proposal: v = b p3 proposal: 无 ##### 场景 1.4.1 1. p2_PreProposal 携带 p2_proposal_id 进行广播,到达 p3 2. P3 更新 p3_proposal_id 为 p2_proposal_id 3. P3 给 P2回复 (p2_proposal_id, v=NULL) 3. p2_proposal (v = b)到达 p3,系统此时会就 v = b 达成共识 - p1: v = a - p2: v = b - p3: v = b 4. p1_PreProposal 携带 p1_proposal_id 进行广播,到达 p2, p3, p2_proposal_id < p1_proposal_id,p2 p3 更新 proposal_id 为 p1_proposal_id 5. P3 回复 P1 (p2_proposal_id, v=b) 6. P1 发现 P3 已经接受了 v = b,把自己的提案 v = a 修改成 v = b 5. p1_proposal (v = b)到达 p2, p3 6. 此时系统还是就 v = b 达成共识 - p1: v = b - p2: v = b - p3: v = b 问题得到了解决。 上文所有的推导,全部来源于三个进程,看似问题已经解决。但是这个流程能否一般化,应用于 N 个进程呢?提案数从 2 到 N 呢? #### 泛化推导, ##### 场景 1.5 进程数从 3 到 N Pi 进程集合:提出 PreProposal-i,Proposal-i(v = a) Qi 进程集合:接受了 Proposal-i 的超半数进程 Pj 进程集合:提出 PreProposal-j,Proposal-j(v = b) Qj 进程集合:接受了 Proposal-j 的超半数进程 Pk 进程集合:Qi 和 Qj 的进程集合交集 只要 Pk 能够拒绝 Proposal-i 和 Proposal-j 的一个就是安全的 每个 Proposal-j-id < Proposal-i-id 1. Proposal-j 到达部分进程,此时系统未达成共识 2. PreProposal-i 到达部分进程,此时系统未达成共识 3. 所有接收到 PreProposal-i 的进程回复(Proposal-j-id, v = b)或者 (NULL, NULL) 给 Pi 4. Pi 接受到(Proposal-j-id,v = b),将 Proposal-i 原先的 v = a 修改成 v = b,然后进行广播。 5. 系统就 v = b 达成共识。 ##### 场景 1.6 不同的 proposal 由 2 到 N 假设 j - i = N,b - a = N Pi Pi+1 ... Pi+N-1 Pj 每个进程组都会提出 Proposal(v = a, a+1, .. a+N-1, b) Proposal_id 大小顺序相反 Qi -> Qj 与 Pi 相对 Pk 是收到了很多不同提案的进程的集合,但是一直没有达成共识。 1. Proposal-i+1 Proposal-i+2 到达 Pk,系统并没有达成共识。 2. PreProposal-j 发出到达部分进程 3. 接收到 PreProposal-j 的进程选择 [(Proposal-i+1-id, v = a + 1), (Proposal-i+2-id, v = a + 2)] 其中的一个或者两个一起回复给 Pj 4. Pj 应该选择哪个 v 值修改自己的 proposal 呢 - 回顾前边的逻辑,每个进程会拒绝 Proposal-id 较小的提案,Proposal-i+1-id > Proposal-i+2-id - Proposal-i+1-id 相比 Proposal-i+2-id 的提案肯定先到 Pk 的,系统还有一部分进程没有接收到 (Proposal-i+1-id, v = a + 1),没有就 (Proposal-i+1-id, v = a + 1) 形成共识 - 假设 Pj 选择 proposal_id 较小的 proposal ,那么会选择 (Proposal-i+2-id, v = a + 2) ,在 Pj 发出 (Proposal-j, v = a + 2) 之前,没有收到 (Proposal-i+1-id, v = a + 1) 的进程可能恰好收到了,系统就 v = a + 1 达成了共识。此后(Proposal-j, v = a + 2) 达到了, 系统又 v = a + 2 达成的共识。系统两次达成共识,存在问题。 - 假设 Pj 选择 proposal_id 较大的 proposal,那么会选择 (Proposal-i+1-id, v = a + 1) ,在 Pj 发出 (Proposal-j, v = a + 1) 之前,没有收到 (Proposal-i+1-id, v = a + 1) 的进程可能恰好收到了,系统就 v = a + 1 达成了共识。此后(Proposal-j, v = a + 2) 达到了,还是 v = a + 1。不存在问题。 - 系统选择 proposal_id 较大的修改依据 5. Pj 选择 proposal_id 较大的 proposal,修改 v = a + 1,并发出 (Proposal-j, v = a + 2) 6. 系统就 v = a + 2 达成共识 #### 不能覆盖的场景 如果每次 proposal 被接受之前,先接受了携带较大 proposal-id 的 PreProposal,这样每次都会拒绝即将成功的达成共识的 proposal 系统每次都不会达成共识。这个场景可以通过不断重试解决。 #### paxos Proposer: 发起提案的进程 Acceptor: 接受题提案的进程 一个进程可能充当多个角色 ##### Phase 1: 1. Proposer 选择一个提案编号 n,然后向 Acceptors 的某个 majority 集合的成员发送编号为 n 的prepare请求。 2. 如果一个Acceptor收到一个编号为 n 的prepare请求,且 n 大于它已经响应的所有prepare请求的编号,那么它就会保证不会再通过(accept)任何编号小于 n 的提案,同时将它已经通过的最大编号的提案(如果存在的话)作为响应。 ##### Phase 2 1. 如果 Proposer 收到来自半数以上的 Acceptor 对于它的 prepare 请求(编号为 n)的响应,那么它就会发送一个针对编号为 n ,value 值为 v 的提案的 accept 请求给 Acceptors,在这里 v 是收到的响应中编号最大的提案的值,如果响应中不包含提案,那么它就是任意值。 2. 如果 Acceptor 收到一个针对编号 n 的提案的accept请求,只要它还未对编号大于 n 的 prepare 请求作出响应,它就可以通过这个提案。 [1]: https://www.zhihu.com/people/zhu-yicong/answers [2]: https://www.zhihu.com/question/19787937/answer/82340987 [3]: https://www.zhihu.com/people/zhu-yicong/answers [4]: https://www.zhihu.com/people/zhu-yicong/answers [5]: http://dsdoc.net/paxosmadesimple/index.html [6]: http://lamport.azurewebsites.net/pubs/paxos-simple.pdf [7]: https://www.youtube.com/watch?v=JEpsBg0AO6o [8]: http://the-paper-trail.org/blog/a-brief-tour-of-flp-impossibility/
{'repo_name': 'acmerfight/insight_python', 'stars': '122', 'repo_language': 'None', 'file_name': 'memory_management.md', 'mime_type': 'text/plain', 'hash': -9193862745071470518, 'source_dataset': 'data'}
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #ifndef __BASIC_TYPES_H__ #define __BASIC_TYPES_H__ #define SUCCESS 0 #define FAIL (-1) #ifndef TRUE #define _TRUE 1 #else #define _TRUE TRUE #endif #ifndef FALSE #define _FALSE 0 #else #define _FALSE FALSE #endif #ifdef PLATFORM_WINDOWS typedef signed char s8; typedef unsigned char u8; typedef signed short s16; typedef unsigned short u16; typedef signed long s32; typedef unsigned long u32; typedef unsigned int uint; typedef signed int sint; typedef signed long long s64; typedef unsigned long long u64; #ifdef NDIS50_MINIPORT #define NDIS_MAJOR_VERSION 5 #define NDIS_MINOR_VERSION 0 #endif #ifdef NDIS51_MINIPORT #define NDIS_MAJOR_VERSION 5 #define NDIS_MINOR_VERSION 1 #endif typedef NDIS_PROC proc_t; typedef LONG atomic_t; #endif #ifdef PLATFORM_LINUX #include <linux/version.h> #include <linux/types.h> #define IN #define OUT #define VOID void #define NDIS_OID uint #define NDIS_STATUS uint typedef signed int sint; #ifndef PVOID typedef void * PVOID; //#define PVOID (void *) #endif #define UCHAR u8 #define USHORT u16 #define UINT u32 #define ULONG u32 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19)) typedef _Bool bool; #endif typedef void (*proc_t)(void*); typedef __kernel_size_t SIZE_T; typedef __kernel_ssize_t SSIZE_T; #define FIELD_OFFSET(s,field) ((SSIZE_T)&((s*)(0))->field) #endif #ifdef PLATFORM_FREEBSD typedef signed char s8; typedef unsigned char u8; typedef signed short s16; typedef unsigned short u16; typedef signed int s32; typedef unsigned int u32; typedef unsigned int uint; typedef signed int sint; typedef long atomic_t; typedef signed long long s64; typedef unsigned long long u64; #define IN #define OUT #define VOID void #define NDIS_OID uint #define NDIS_STATUS uint #ifndef PVOID typedef void * PVOID; //#define PVOID (void *) #endif typedef u32 dma_addr_t; #define UCHAR u8 #define USHORT u16 #define UINT u32 #define ULONG u32 typedef void (*proc_t)(void*); typedef unsigned int __kernel_size_t; typedef int __kernel_ssize_t; typedef __kernel_size_t SIZE_T; typedef __kernel_ssize_t SSIZE_T; #define FIELD_OFFSET(s,field) ((SSIZE_T)&((s*)(0))->field) #endif #define MEM_ALIGNMENT_OFFSET (sizeof (SIZE_T)) #define MEM_ALIGNMENT_PADDING (sizeof(SIZE_T) - 1) #define SIZE_PTR SIZE_T #define SSIZE_PTR SSIZE_T //port from fw by thomas // TODO: Belows are Sync from SD7-Driver. It is necessary to check correctness /* * Call endian free function when * 1. Read/write packet content. * 2. Before write integer to IO. * 3. After read integer from IO. */ // // Byte Swapping routine. // #define EF1Byte (u8) #define EF2Byte le16_to_cpu #define EF4Byte le32_to_cpu // // Read LE format data from memory // #define ReadEF1Byte(_ptr) EF1Byte(*((u8 *)(_ptr))) #define ReadEF2Byte(_ptr) EF2Byte(*((u16 *)(_ptr))) #define ReadEF4Byte(_ptr) EF4Byte(*((u32 *)(_ptr))) // // Write LE data to memory // #define WriteEF1Byte(_ptr, _val) (*((u8 *)(_ptr)))=EF1Byte(_val) #define WriteEF2Byte(_ptr, _val) (*((u16 *)(_ptr)))=EF2Byte(_val) #define WriteEF4Byte(_ptr, _val) (*((u32 *)(_ptr)))=EF4Byte(_val) // // Example: // BIT_LEN_MASK_32(0) => 0x00000000 // BIT_LEN_MASK_32(1) => 0x00000001 // BIT_LEN_MASK_32(2) => 0x00000003 // BIT_LEN_MASK_32(32) => 0xFFFFFFFF // #define BIT_LEN_MASK_32(__BitLen) \ (0xFFFFFFFF >> (32 - (__BitLen))) // // Example: // BIT_OFFSET_LEN_MASK_32(0, 2) => 0x00000003 // BIT_OFFSET_LEN_MASK_32(16, 2) => 0x00030000 // #define BIT_OFFSET_LEN_MASK_32(__BitOffset, __BitLen) \ (BIT_LEN_MASK_32(__BitLen) << (__BitOffset)) // // Description: // Return 4-byte value in host byte ordering from // 4-byte pointer in litten-endian system. // #define LE_P4BYTE_TO_HOST_4BYTE(__pStart) \ (EF4Byte(*((u32 *)(__pStart)))) // // Description: // Translate subfield (continuous bits in little-endian) of 4-byte value in litten byte to // 4-byte value in host byte ordering. // #define LE_BITS_TO_4BYTE(__pStart, __BitOffset, __BitLen) \ ( \ ( LE_P4BYTE_TO_HOST_4BYTE(__pStart) >> (__BitOffset) ) \ & \ BIT_LEN_MASK_32(__BitLen) \ ) // // Description: // Mask subfield (continuous bits in little-endian) of 4-byte value in litten byte oredering // and return the result in 4-byte value in host byte ordering. // #define LE_BITS_CLEARED_TO_4BYTE(__pStart, __BitOffset, __BitLen) \ ( \ LE_P4BYTE_TO_HOST_4BYTE(__pStart) \ & \ ( ~BIT_OFFSET_LEN_MASK_32(__BitOffset, __BitLen) ) \ ) // // Description: // Set subfield of little-endian 4-byte value to specified value. // #define SET_BITS_TO_LE_4BYTE(__pStart, __BitOffset, __BitLen, __Value) \ *((u32 *)(__pStart)) = \ EF4Byte( \ LE_BITS_CLEARED_TO_4BYTE(__pStart, __BitOffset, __BitLen) \ | \ ( (((u32)__Value) & BIT_LEN_MASK_32(__BitLen)) << (__BitOffset) ) \ ); #define BIT_LEN_MASK_16(__BitLen) \ (0xFFFF >> (16 - (__BitLen))) #define BIT_OFFSET_LEN_MASK_16(__BitOffset, __BitLen) \ (BIT_LEN_MASK_16(__BitLen) << (__BitOffset)) #define LE_P2BYTE_TO_HOST_2BYTE(__pStart) \ (EF2Byte(*((u16 *)(__pStart)))) #define LE_BITS_TO_2BYTE(__pStart, __BitOffset, __BitLen) \ ( \ ( LE_P2BYTE_TO_HOST_2BYTE(__pStart) >> (__BitOffset) ) \ & \ BIT_LEN_MASK_16(__BitLen) \ ) #define LE_BITS_CLEARED_TO_2BYTE(__pStart, __BitOffset, __BitLen) \ ( \ LE_P2BYTE_TO_HOST_2BYTE(__pStart) \ & \ (u16)(~BIT_OFFSET_LEN_MASK_16(__BitOffset, __BitLen))\ ) #define SET_BITS_TO_LE_2BYTE(__pStart, __BitOffset, __BitLen, __Value) \ *((u16 *)(__pStart)) = \ EF2Byte( \ LE_BITS_CLEARED_TO_2BYTE(__pStart, __BitOffset, __BitLen) \ | \ ( (((u16)__Value) & BIT_LEN_MASK_16(__BitLen)) << (__BitOffset) ) \ ); #define BIT_LEN_MASK_8(__BitLen) \ (0xFF >> (8 - (__BitLen))) #define BIT_OFFSET_LEN_MASK_8(__BitOffset, __BitLen) \ (BIT_LEN_MASK_8(__BitLen) << (__BitOffset)) #define LE_P1BYTE_TO_HOST_1BYTE(__pStart) \ (EF1Byte(*((u8 *)(__pStart)))) #define LE_BITS_TO_1BYTE(__pStart, __BitOffset, __BitLen) \ ( \ ( LE_P1BYTE_TO_HOST_1BYTE(__pStart) >> (__BitOffset) ) \ & \ BIT_LEN_MASK_8(__BitLen) \ ) #define LE_BITS_CLEARED_TO_1BYTE(__pStart, __BitOffset, __BitLen) \ ( \ LE_P1BYTE_TO_HOST_1BYTE(__pStart) \ & \ (u8)(~BIT_OFFSET_LEN_MASK_8(__BitOffset, __BitLen))\ ) #define SET_BITS_TO_LE_1BYTE(__pStart, __BitOffset, __BitLen, __Value) \ *((u8 *)(__pStart)) = \ EF1Byte( \ LE_BITS_CLEARED_TO_1BYTE(__pStart, __BitOffset, __BitLen) \ | \ ( (((u8)__Value) & BIT_LEN_MASK_8(__BitLen)) << (__BitOffset) ) \ ); #define LE_BITS_CLEARED_TO_2BYTE_16BIT(__pStart, __BitOffset, __BitLen) \ ( \ LE_P2BYTE_TO_HOST_2BYTE(__pStart) \ ) #define SET_BITS_TO_LE_2BYTE_16BIT(__pStart, __BitOffset, __BitLen, __Value) \ *((u16 *)(__pStart)) = \ EF2Byte( \ LE_BITS_CLEARED_TO_2BYTE_16BIT(__pStart, __BitOffset, __BitLen) \ | \ ( (u16)__Value) \ ); #define LE_BITS_CLEARED_TO_1BYTE_8BIT(__pStart, __BitOffset, __BitLen) \ ( \ LE_P1BYTE_TO_HOST_1BYTE(__pStart) \ ) #define SET_BITS_TO_LE_1BYTE_8BIT(__pStart, __BitOffset, __BitLen, __Value) \ do { \ *((u8 *)(__pStart)) = \ EF1Byte( \ LE_BITS_CLEARED_TO_1BYTE_8BIT(__pStart, __BitOffset, __BitLen) \ | \ ((u8)__Value) \ ); \ } while (0) // Get the N-bytes aligment offset from the current length #define N_BYTE_ALIGMENT(__Value, __Aligment) ((__Aligment == 1) ? (__Value) : (((__Value + __Aligment - 1) / __Aligment) * __Aligment)) typedef unsigned char BOOLEAN,*PBOOLEAN; #define TEST_FLAG(__Flag,__testFlag) (((__Flag) & (__testFlag)) != 0) #define SET_FLAG(__Flag, __setFlag) ((__Flag) |= __setFlag) #define CLEAR_FLAG(__Flag, __clearFlag) ((__Flag) &= ~(__clearFlag)) #define CLEAR_FLAGS(__Flag) ((__Flag) = 0) #define TEST_FLAGS(__Flag, __testFlags) (((__Flag) & (__testFlags)) == (__testFlags)) #endif //__BASIC_TYPES_H__
{'repo_name': 'OLIMEX/DIY-LAPTOP', 'stars': '358', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': 8843953434340748368, 'source_dataset': 'data'}
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "exception.h" #include "string.h" #include "debug.h" #include "threadlocal.h" #include "miniposix.h" #include <stdlib.h> #include <exception> #include <new> #include <signal.h> #ifndef _WIN32 #include <sys/mman.h> #endif #include "io.h" #if (__linux__ && __GLIBC__) || __APPLE__ #define KJ_HAS_BACKTRACE 1 #include <execinfo.h> #endif #if _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "windows-sanity.h" #include <dbghelp.h> #endif #if (__linux__ || __APPLE__) #include <stdio.h> #include <pthread.h> #endif namespace kj { StringPtr KJ_STRINGIFY(LogSeverity severity) { static const char* SEVERITY_STRINGS[] = { "info", "warning", "error", "fatal", "debug" }; return SEVERITY_STRINGS[static_cast<uint>(severity)]; } #if _WIN32 && _M_X64 // Currently the Win32 stack-trace code only supports x86_64. We could easily extend it to support // i386 as well but it requires some code changes around how we read the context to start the // trace. namespace { struct Dbghelp { // Load dbghelp.dll dynamically since we don't really need it, it's just for debugging. HINSTANCE lib; BOOL (WINAPI *symInitialize)(HANDLE hProcess,PCSTR UserSearchPath,BOOL fInvadeProcess); BOOL (WINAPI *stackWalk64)( DWORD MachineType,HANDLE hProcess,HANDLE hThread, LPSTACKFRAME64 StackFrame,PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); PVOID (WINAPI *symFunctionTableAccess64)(HANDLE hProcess,DWORD64 AddrBase); DWORD64 (WINAPI *symGetModuleBase64)(HANDLE hProcess,DWORD64 qwAddr); BOOL (WINAPI *symGetLineFromAddr64)( HANDLE hProcess,DWORD64 qwAddr,PDWORD pdwDisplacement,PIMAGEHLP_LINE64 Line64); Dbghelp() : lib(LoadLibraryA("dbghelp.dll")), symInitialize(lib == nullptr ? nullptr : reinterpret_cast<decltype(symInitialize)>( GetProcAddress(lib, "SymInitialize"))), stackWalk64(symInitialize == nullptr ? nullptr : reinterpret_cast<decltype(stackWalk64)>( GetProcAddress(lib, "StackWalk64"))), symFunctionTableAccess64(symInitialize == nullptr ? nullptr : reinterpret_cast<decltype(symFunctionTableAccess64)>( GetProcAddress(lib, "SymFunctionTableAccess64"))), symGetModuleBase64(symInitialize == nullptr ? nullptr : reinterpret_cast<decltype(symGetModuleBase64)>( GetProcAddress(lib, "SymGetModuleBase64"))), symGetLineFromAddr64(symInitialize == nullptr ? nullptr : reinterpret_cast<decltype(symGetLineFromAddr64)>( GetProcAddress(lib, "SymGetLineFromAddr64"))) { if (symInitialize != nullptr) { symInitialize(GetCurrentProcess(), NULL, TRUE); } } }; const Dbghelp& getDbghelp() { static Dbghelp dbghelp; return dbghelp; } ArrayPtr<void* const> getStackTrace(ArrayPtr<void*> space, uint ignoreCount, HANDLE thread, CONTEXT& context) { const Dbghelp& dbghelp = getDbghelp(); if (dbghelp.stackWalk64 == nullptr || dbghelp.symFunctionTableAccess64 == nullptr || dbghelp.symGetModuleBase64 == nullptr) { return nullptr; } STACKFRAME64 frame; memset(&frame, 0, sizeof(frame)); frame.AddrPC.Offset = context.Rip; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Offset = context.Rsp; frame.AddrStack.Mode = AddrModeFlat; frame.AddrFrame.Offset = context.Rbp; frame.AddrFrame.Mode = AddrModeFlat; HANDLE process = GetCurrentProcess(); uint count = 0; for (; count < space.size(); count++) { if (!dbghelp.stackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &context, NULL, dbghelp.symFunctionTableAccess64, dbghelp.symGetModuleBase64, NULL)){ break; } space[count] = reinterpret_cast<void*>(frame.AddrPC.Offset); } return space.slice(kj::min(ignoreCount, count), count); } } // namespace #endif ArrayPtr<void* const> getStackTrace(ArrayPtr<void*> space, uint ignoreCount) { if (getExceptionCallback().stackTraceMode() == ExceptionCallback::StackTraceMode::NONE) { return nullptr; } #if _WIN32 && _M_X64 CONTEXT context; RtlCaptureContext(&context); return getStackTrace(space, ignoreCount, GetCurrentThread(), context); #elif KJ_HAS_BACKTRACE size_t size = backtrace(space.begin(), space.size()); return space.slice(kj::min(ignoreCount + 1, size), size); #else return nullptr; #endif } String stringifyStackTrace(ArrayPtr<void* const> trace) { if (trace.size() == 0) return nullptr; if (getExceptionCallback().stackTraceMode() != ExceptionCallback::StackTraceMode::FULL) { return nullptr; } #if _WIN32 && _M_X64 && _MSC_VER // Try to get file/line using SymGetLineFromAddr64(). We don't bother if we aren't on MSVC since // this requires MSVC debug info. // // TODO(someday): We could perhaps shell out to addr2line on MinGW. const Dbghelp& dbghelp = getDbghelp(); if (dbghelp.symGetLineFromAddr64 == nullptr) return nullptr; HANDLE process = GetCurrentProcess(); KJ_STACK_ARRAY(String, lines, trace.size(), 32, 32); for (auto i: kj::indices(trace)) { IMAGEHLP_LINE64 lineInfo; memset(&lineInfo, 0, sizeof(lineInfo)); lineInfo.SizeOfStruct = sizeof(lineInfo); if (dbghelp.symGetLineFromAddr64(process, reinterpret_cast<DWORD64>(trace[i]), NULL, &lineInfo)) { lines[i] = kj::str('\n', lineInfo.FileName, ':', lineInfo.LineNumber); } } return strArray(lines, ""); #elif (__linux__ || __APPLE__) && !__ANDROID__ // We want to generate a human-readable stack trace. // TODO(someday): It would be really great if we could avoid farming out to another process // and do this all in-process, but that may involve onerous requirements like large library // dependencies or using -rdynamic. // The environment manipulation is not thread-safe, so lock a mutex. This could still be // problematic if another thread is manipulating the environment in unrelated code, but there's // not much we can do about that. This is debug-only anyway and only an issue when LD_PRELOAD // is in use. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); KJ_DEFER(pthread_mutex_unlock(&mutex)); // Don't heapcheck / intercept syscalls. const char* preload = getenv("LD_PRELOAD"); String oldPreload; if (preload != nullptr) { oldPreload = heapString(preload); unsetenv("LD_PRELOAD"); } KJ_DEFER(if (oldPreload != nullptr) { setenv("LD_PRELOAD", oldPreload.cStr(), true); }); String lines[32]; FILE* p = nullptr; auto strTrace = strArray(trace, " "); #if __linux__ if (access("/proc/self/exe", R_OK) < 0) { // Apparently /proc is not available? return nullptr; } // Obtain symbolic stack trace using addr2line. // TODO(cleanup): Use fork() and exec() or maybe our own Subprocess API (once it exists), to // avoid depending on a shell. p = popen(str("addr2line -e /proc/", getpid(), "/exe ", strTrace).cStr(), "r"); #elif __APPLE__ // The Mac OS X equivalent of addr2line is atos. // (Internally, it uses the private CoreSymbolication.framework library.) p = popen(str("xcrun atos -p ", getpid(), ' ', strTrace).cStr(), "r"); #endif if (p == nullptr) { return nullptr; } char line[512]; size_t i = 0; while (i < kj::size(lines) && fgets(line, sizeof(line), p) != nullptr) { // Don't include exception-handling infrastructure or promise infrastructure in stack trace. // addr2line output matches file names; atos output matches symbol names. if (strstr(line, "kj/common.c++") != nullptr || strstr(line, "kj/exception.") != nullptr || strstr(line, "kj/debug.") != nullptr || strstr(line, "kj/async.") != nullptr || strstr(line, "kj/async-prelude.h") != nullptr || strstr(line, "kj/async-inl.h") != nullptr || strstr(line, "kj::Exception") != nullptr || strstr(line, "kj::_::Debug") != nullptr) { continue; } size_t len = strlen(line); if (len > 0 && line[len-1] == '\n') line[len-1] = '\0'; lines[i++] = str("\n ", trimSourceFilename(line), ": returning here"); } // Skip remaining input. while (fgets(line, sizeof(line), p) != nullptr) {} pclose(p); return strArray(arrayPtr(lines, i), ""); #else return nullptr; #endif } String getStackTrace() { void* space[32]; auto trace = getStackTrace(space, 2); return kj::str(kj::strArray(trace, " "), stringifyStackTrace(trace)); } #if _WIN32 && _M_X64 namespace { DWORD mainThreadId = 0; BOOL WINAPI breakHandler(DWORD type) { switch (type) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: { HANDLE thread = OpenThread(THREAD_ALL_ACCESS, FALSE, mainThreadId); if (thread != NULL) { if (SuspendThread(thread) != (DWORD)-1) { CONTEXT context; memset(&context, 0, sizeof(context)); context.ContextFlags = CONTEXT_FULL; if (GetThreadContext(thread, &context)) { void* traceSpace[32]; auto trace = getStackTrace(traceSpace, 2, thread, context); ResumeThread(thread); auto message = kj::str("*** Received CTRL+C. stack: ", strArray(trace, " "), stringifyStackTrace(trace), '\n'); FdOutputStream(STDERR_FILENO).write(message.begin(), message.size()); } else { ResumeThread(thread); } } CloseHandle(thread); } break; } default: break; } return FALSE; // still crash } } // namespace void printStackTraceOnCrash() { mainThreadId = GetCurrentThreadId(); KJ_WIN32(SetConsoleCtrlHandler(breakHandler, TRUE)); } #elif KJ_HAS_BACKTRACE namespace { void crashHandler(int signo, siginfo_t* info, void* context) { void* traceSpace[32]; // ignoreCount = 2 to ignore crashHandler() and signal trampoline. auto trace = getStackTrace(traceSpace, 2); auto message = kj::str("*** Received signal #", signo, ": ", strsignal(signo), "\nstack: ", strArray(trace, " "), stringifyStackTrace(trace), '\n'); FdOutputStream(STDERR_FILENO).write(message.begin(), message.size()); _exit(1); } } // namespace void printStackTraceOnCrash() { // Set up alternate signal stack so that stack overflows can be handled. stack_t stack; memset(&stack, 0, sizeof(stack)); #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #ifndef MAP_GROWSDOWN #define MAP_GROWSDOWN 0 #endif stack.ss_size = 65536; // Note: ss_sp is char* on FreeBSD, void* on Linux and OSX. stack.ss_sp = reinterpret_cast<char*>(mmap( nullptr, stack.ss_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_GROWSDOWN, -1, 0)); KJ_SYSCALL(sigaltstack(&stack, nullptr)); // Catch all relevant signals. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_NODEFER | SA_RESETHAND; action.sa_sigaction = &crashHandler; // Dump stack on common "crash" signals. KJ_SYSCALL(sigaction(SIGSEGV, &action, nullptr)); KJ_SYSCALL(sigaction(SIGBUS, &action, nullptr)); KJ_SYSCALL(sigaction(SIGFPE, &action, nullptr)); KJ_SYSCALL(sigaction(SIGABRT, &action, nullptr)); KJ_SYSCALL(sigaction(SIGILL, &action, nullptr)); // Dump stack on unimplemented syscalls -- useful in seccomp sandboxes. KJ_SYSCALL(sigaction(SIGSYS, &action, nullptr)); #ifdef KJ_DEBUG // Dump stack on keyboard interrupt -- useful for infinite loops. Only in debug mode, though, // because stack traces on ctrl+c can be obnoxious for, say, command-line tools. KJ_SYSCALL(sigaction(SIGINT, &action, nullptr)); #endif } #else void printStackTraceOnCrash() { } #endif kj::StringPtr trimSourceFilename(kj::StringPtr filename) { // Removes noisy prefixes from source code file name. // // The goal here is to produce the "canonical" filename given the filename returned by e.g. // addr2line. addr2line gives us the full path of the file as passed on the compiler // command-line, which in turn is affected by build system and by whether and where we're // performing an out-of-tree build. // // To deal with all this, we look for directory names in the path which we recognize to be // locations that represent roots of the source tree. We strip said root and everything before // it. // // On Windows, we often get filenames containing backslashes. Since we aren't allowed to allocate // a new string here, we can't do much about this, so our returned "canonical" name will // unfortunately end up with backslashes. static constexpr const char* ROOTS[] = { "ekam-provider/canonical/", // Ekam source file. "ekam-provider/c++header/", // Ekam include file. "src/", // Non-Ekam source root. "tmp/", // Non-Ekam generated code. #if _WIN32 "src\\", // Win32 source root. "tmp\\", // Win32 generated code. #endif }; retry: for (size_t i: kj::indices(filename)) { if (i == 0 || filename[i-1] == '/' #if _WIN32 || filename[i-1] == '\\' #endif ) { // We're at the start of a directory name. Check for valid prefixes. for (kj::StringPtr root: ROOTS) { if (filename.slice(i).startsWith(root)) { filename = filename.slice(i + root.size()); // We should keep searching to find the last instance of a root name. `i` is no longer // a valid index for `filename` so start the loop over. goto retry; } } } } return filename; } StringPtr KJ_STRINGIFY(Exception::Type type) { static const char* TYPE_STRINGS[] = { "failed", "overloaded", "disconnected", "unimplemented" }; return TYPE_STRINGS[static_cast<uint>(type)]; } String KJ_STRINGIFY(const Exception& e) { uint contextDepth = 0; Maybe<const Exception::Context&> contextPtr = e.getContext(); for (;;) { KJ_IF_MAYBE(c, contextPtr) { ++contextDepth; contextPtr = c->next; } else { break; } } Array<String> contextText = heapArray<String>(contextDepth); contextDepth = 0; contextPtr = e.getContext(); for (;;) { KJ_IF_MAYBE(c, contextPtr) { contextText[contextDepth++] = str(c->file, ":", c->line, ": context: ", c->description, "\n"); contextPtr = c->next; } else { break; } } return str(strArray(contextText, ""), e.getFile(), ":", e.getLine(), ": ", e.getType(), e.getDescription() == nullptr ? "" : ": ", e.getDescription(), e.getStackTrace().size() > 0 ? "\nstack: " : "", strArray(e.getStackTrace(), " "), stringifyStackTrace(e.getStackTrace())); } Exception::Exception(Type type, const char* file, int line, String description) noexcept : file(trimSourceFilename(file).cStr()), line(line), type(type), description(mv(description)), traceCount(0) {} Exception::Exception(Type type, String file, int line, String description) noexcept : ownFile(kj::mv(file)), file(trimSourceFilename(ownFile).cStr()), line(line), type(type), description(mv(description)), traceCount(0) {} Exception::Exception(const Exception& other) noexcept : file(other.file), line(other.line), type(other.type), description(heapString(other.description)), traceCount(other.traceCount) { if (file == other.ownFile.cStr()) { ownFile = heapString(other.ownFile); file = ownFile.cStr(); } memcpy(trace, other.trace, sizeof(trace[0]) * traceCount); KJ_IF_MAYBE(c, other.context) { context = heap(**c); } } Exception::~Exception() noexcept {} Exception::Context::Context(const Context& other) noexcept : file(other.file), line(other.line), description(str(other.description)) { KJ_IF_MAYBE(n, other.next) { next = heap(**n); } } void Exception::wrapContext(const char* file, int line, String&& description) { context = heap<Context>(file, line, mv(description), mv(context)); } void Exception::extendTrace(uint ignoreCount) { KJ_STACK_ARRAY(void*, newTraceSpace, kj::size(trace) + ignoreCount + 1, sizeof(trace)/sizeof(trace[0]) + 8, 128); auto newTrace = kj::getStackTrace(newTraceSpace, ignoreCount + 1); if (newTrace.size() > ignoreCount + 2) { // Remove suffix that won't fit into our static-sized trace. newTrace = newTrace.slice(0, kj::min(kj::size(trace) - traceCount, newTrace.size())); // Copy the rest into our trace. memcpy(trace + traceCount, newTrace.begin(), newTrace.asBytes().size()); traceCount += newTrace.size(); } } void Exception::truncateCommonTrace() { if (traceCount > 0) { // Create a "reference" stack trace that is a little bit deeper than the one in the exception. void* refTraceSpace[sizeof(this->trace) / sizeof(this->trace[0]) + 4]; auto refTrace = kj::getStackTrace(refTraceSpace, 0); // We expect that the deepest frame in the exception's stack trace should be somewhere in our // own trace, since our own trace has a deeper limit. Search for it. for (uint i = refTrace.size(); i > 0; i--) { if (refTrace[i-1] == trace[traceCount-1]) { // See how many frames match. for (uint j = 0; j < i; j++) { if (j >= traceCount) { // We matched the whole trace, apparently? traceCount = 0; return; } else if (refTrace[i-j-1] != trace[traceCount-j-1]) { // Found mismatching entry. // If we matched more than half of the reference trace, guess that this is in fact // the prefix we're looking for. if (j > refTrace.size() / 2) { // Delete the matching suffix. Also delete one non-matched entry on the assumption // that both traces contain that stack frame but are simply at different points in // the function. traceCount -= j + 1; return; } } } } } // No match. Ignore. } } void Exception::addTrace(void* ptr) { if (traceCount < kj::size(trace)) { trace[traceCount++] = ptr; } } class ExceptionImpl: public Exception, public std::exception { public: inline ExceptionImpl(Exception&& other): Exception(mv(other)) {} ExceptionImpl(const ExceptionImpl& other): Exception(other) { // No need to copy whatBuffer since it's just to hold the return value of what(). } const char* what() const noexcept override; private: mutable String whatBuffer; }; const char* ExceptionImpl::what() const noexcept { whatBuffer = str(*this); return whatBuffer.begin(); } // ======================================================================================= namespace { KJ_THREADLOCAL_PTR(ExceptionCallback) threadLocalCallback = nullptr; } // namespace ExceptionCallback::ExceptionCallback(): next(getExceptionCallback()) { char stackVar; ptrdiff_t offset = reinterpret_cast<char*>(this) - &stackVar; KJ_ASSERT(offset < 65536 && offset > -65536, "ExceptionCallback must be allocated on the stack."); threadLocalCallback = this; } ExceptionCallback::ExceptionCallback(ExceptionCallback& next): next(next) {} ExceptionCallback::~ExceptionCallback() noexcept(false) { if (&next != this) { threadLocalCallback = &next; } } void ExceptionCallback::onRecoverableException(Exception&& exception) { next.onRecoverableException(mv(exception)); } void ExceptionCallback::onFatalException(Exception&& exception) { next.onFatalException(mv(exception)); } void ExceptionCallback::logMessage( LogSeverity severity, const char* file, int line, int contextDepth, String&& text) { next.logMessage(severity, file, line, contextDepth, mv(text)); } ExceptionCallback::StackTraceMode ExceptionCallback::stackTraceMode() { return next.stackTraceMode(); } class ExceptionCallback::RootExceptionCallback: public ExceptionCallback { public: RootExceptionCallback(): ExceptionCallback(*this) {} void onRecoverableException(Exception&& exception) override { #if KJ_NO_EXCEPTIONS logException(LogSeverity::ERROR, mv(exception)); #else if (std::uncaught_exception()) { // Bad time to throw an exception. Just log instead. // // TODO(someday): We should really compare uncaughtExceptionCount() against the count at // the innermost runCatchingExceptions() frame in this thread to tell if exceptions are // being caught correctly. logException(LogSeverity::ERROR, mv(exception)); } else { throw ExceptionImpl(mv(exception)); } #endif } void onFatalException(Exception&& exception) override { #if KJ_NO_EXCEPTIONS logException(LogSeverity::FATAL, mv(exception)); #else throw ExceptionImpl(mv(exception)); #endif } void logMessage(LogSeverity severity, const char* file, int line, int contextDepth, String&& text) override { text = str(kj::repeat('_', contextDepth), file, ":", line, ": ", severity, ": ", mv(text), '\n'); StringPtr textPtr = text; while (text != nullptr) { miniposix::ssize_t n = miniposix::write(STDERR_FILENO, textPtr.begin(), textPtr.size()); if (n <= 0) { // stderr is broken. Give up. return; } textPtr = textPtr.slice(n); } } StackTraceMode stackTraceMode() override { #ifdef KJ_DEBUG return StackTraceMode::FULL; #else return StackTraceMode::ADDRESS_ONLY; #endif } private: void logException(LogSeverity severity, Exception&& e) { // We intentionally go back to the top exception callback on the stack because we don't want to // bypass whatever log processing is in effect. // // We intentionally don't log the context since it should get re-added by the exception callback // anyway. getExceptionCallback().logMessage(severity, e.getFile(), e.getLine(), 0, str( e.getType(), e.getDescription() == nullptr ? "" : ": ", e.getDescription(), e.getStackTrace().size() > 0 ? "\nstack: " : "", strArray(e.getStackTrace(), " "), stringifyStackTrace(e.getStackTrace()), "\n")); } }; ExceptionCallback& getExceptionCallback() { static ExceptionCallback::RootExceptionCallback defaultCallback; ExceptionCallback* scoped = threadLocalCallback; return scoped != nullptr ? *scoped : defaultCallback; } void throwFatalException(kj::Exception&& exception, uint ignoreCount) { exception.extendTrace(ignoreCount + 1); getExceptionCallback().onFatalException(kj::mv(exception)); abort(); } void throwRecoverableException(kj::Exception&& exception, uint ignoreCount) { exception.extendTrace(ignoreCount + 1); getExceptionCallback().onRecoverableException(kj::mv(exception)); } // ======================================================================================= namespace _ { // private #if __GNUC__ // Horrible -- but working -- hack: We can dig into __cxa_get_globals() in order to extract the // count of uncaught exceptions. This function is part of the C++ ABI implementation used on Linux, // OSX, and probably other platforms that use GCC. Unfortunately, __cxa_get_globals() is only // actually defined in cxxabi.h on some platforms (e.g. Linux, but not OSX), and even where it is // defined, it returns an incomplete type. Here we use the same hack used by Evgeny Panasyuk: // https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp // // Notice that a similar hack is possible on MSVC -- if its C++11 support ever gets to the point of // supporting KJ in the first place. // // It appears likely that a future version of the C++ standard may include an // uncaught_exception_count() function in the standard library, or an equivalent language feature. // Some discussion: // https://groups.google.com/a/isocpp.org/d/msg/std-proposals/HglEslyZFYs/kKdu5jJw5AgJ struct FakeEhGlobals { // Fake void* caughtExceptions; uint uncaughtExceptions; }; // Because of the 'extern "C"', the symbol name is not mangled and thus the namespace is effectively // ignored for linking. Thus it doesn't matter that we are declaring __cxa_get_globals() in a // different namespace from the ABI's definition. extern "C" { FakeEhGlobals* __cxa_get_globals(); } uint uncaughtExceptionCount() { // TODO(perf): Use __cxa_get_globals_fast()? Requires that __cxa_get_globals() has been called // from somewhere. return __cxa_get_globals()->uncaughtExceptions; } #elif _MSC_VER #if _MSC_VER >= 1900 // MSVC14 has a refactored CRT which now provides a direct accessor for this value. // See https://svn.boost.org/trac/boost/ticket/10158 for a brief discussion. extern "C" int *__cdecl __processing_throw(); uint uncaughtExceptionCount() { return static_cast<uint>(*__processing_throw()); } #elif _MSC_VER >= 1400 // The below was copied from: // https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp extern "C" char *__cdecl _getptd(); uint uncaughtExceptionCount() { return *reinterpret_cast<uint*>(_getptd() + (sizeof(void*) == 8 ? 0x100 : 0x90)); } #else uint uncaughtExceptionCount() { // Since the above doesn't work, fall back to uncaught_exception(). This will produce incorrect // results in very obscure cases that Cap'n Proto doesn't really rely on anyway. return std::uncaught_exception(); } #endif #else #error "This needs to be ported to your compiler / C++ ABI." #endif } // namespace _ (private) UnwindDetector::UnwindDetector(): uncaughtCount(_::uncaughtExceptionCount()) {} bool UnwindDetector::isUnwinding() const { return _::uncaughtExceptionCount() > uncaughtCount; } void UnwindDetector::catchExceptionsAsSecondaryFaults(_::Runnable& runnable) const { // TODO(someday): Attach the secondary exception to whatever primary exception is causing // the unwind. For now we just drop it on the floor as this is probably fine most of the // time. runCatchingExceptions(runnable); } namespace _ { // private class RecoverableExceptionCatcher: public ExceptionCallback { // Catches a recoverable exception without using try/catch. Used when compiled with // -fno-exceptions. public: virtual ~RecoverableExceptionCatcher() noexcept(false) {} void onRecoverableException(Exception&& exception) override { if (caught == nullptr) { caught = mv(exception); } else { // TODO(someday): Consider it a secondary fault? } } Maybe<Exception> caught; }; Maybe<Exception> runCatchingExceptions(Runnable& runnable) noexcept { #if KJ_NO_EXCEPTIONS RecoverableExceptionCatcher catcher; runnable.run(); KJ_IF_MAYBE(e, catcher.caught) { e->truncateCommonTrace(); } return mv(catcher.caught); #else try { runnable.run(); return nullptr; } catch (Exception& e) { e.truncateCommonTrace(); return kj::mv(e); } catch (std::bad_alloc& e) { return Exception(Exception::Type::OVERLOADED, "(unknown)", -1, str("std::bad_alloc: ", e.what())); } catch (std::exception& e) { return Exception(Exception::Type::FAILED, "(unknown)", -1, str("std::exception: ", e.what())); } catch (...) { return Exception(Exception::Type::FAILED, "(unknown)", -1, str("Unknown non-KJ exception.")); } #endif } } // namespace _ (private) } // namespace kj
{'repo_name': 'openai/retro', 'stars': '2128', 'repo_language': 'C', 'file_name': 'gcw0readme.txt', 'mime_type': 'text/plain', 'hash': -9018746685574956758, 'source_dataset': 'data'}
import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") } }
{'repo_name': 'twostraws/Sitrep', 'stars': '705', 'repo_language': 'Swift', 'file_name': 'SitrepTests.swift', 'mime_type': 'text/plain', 'hash': -571782105719984974, 'source_dataset': 'data'}
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) { if (prev == CodeMirror.Init) prev = false; if (prev && !val) cm.removeOverlay("trailingspace"); else if (!prev && val) cm.addOverlay({ token: function(stream) { for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {} if (i > stream.pos) { stream.pos = i; return null; } stream.pos = l; return "trailingspace"; }, name: "trailingspace" }); }); });
{'repo_name': 'crmeb/CRMEB', 'stars': '2615', 'repo_language': 'JavaScript', 'file_name': '前端下载地址.md', 'mime_type': 'text/plain', 'hash': -8129682310108420849, 'source_dataset': 'data'}
<!--- 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. --> # org.apache.cordova.vibration Este plugin se alinea con la vibración W3C especificación http://www.w3.org/TR/vibration/ Este plugin proporciona una manera de vibrar el dispositivo. ## Instalación cordova plugin add org.apache.cordova.vibration ## Plataformas soportadas Navigator.Vibrate Navigator.Notification.Vibrate - Amazon fuego OS - sistema operativo Android - BlackBerry 10 - Firefox - iOS - Windows Phone 7 y 8 navigator.notification.vibrateWithPattern, navigator.notification.cancelVibration - Android ## vibrar (recomendado) Esta función tiene tres diferentes funcionalidades basadas en los parámetros pasados a él. ### Estándar de vibrar Vibra el dispositivo para una cantidad dada de tiempo. navigator.vibrate(time) o navigator.vibrate([time]) -**tiempo**: milisegundos a vibrar el dispositivo. *(Número)* #### Ejemplo // Vibrate for 3 seconds navigator.vibrate(3000); // Vibrate for 3 seconds navigator.vibrate([3000]); #### iOS rarezas * **time**: ignora el tiempo especificado y vibra por un tiempo preestablecido. navigator.vibrate(3000); // 3000 is ignored #### Windows y rarezas de Blackberry * **tiempo**: tiempo máximo es 5000ms (5s) y min tiempo 1ms navigator.vibrate(8000); // will be truncated to 5000 ### Vibrar con un patrón (Android y Windows solamente) Vibra el dispositivo con un patrón determinado navigator.vibrate(pattern); * **patrón**: secuencia de duraciones (en milisegundos) que desea activar o desactivar el vibrador. *(Matriz de números)* #### Ejemplo // Vibrate for 1 second // Wait for 1 second // Vibrate for 3 seconds // Wait for 1 second // Vibrate for 5 seconds navigator.vibrate([1000, 1000, 3000, 1000, 5000]); ### Cancelar vibración (no soportada en iOS) Inmediatamente se cancela cualquier vibración actualmente en ejecución. navigator.vibrate(0) o navigator.vibrate([]) o navigator.vibrate([0]) Pasando en un parámetro de 0, una matriz vacía o una matriz con un elemento de valor 0 se cancelará cualquier vibraciones. ## *Notification.Vibrate (obsoleto) Vibra el dispositivo para una cantidad dada de tiempo. navigator.notification.vibrate(time) * **tiempo**: milisegundos a vibrar el dispositivo. *(Número)* ### Ejemplo // Vibrate for 2.5 seconds navigator.notification.vibrate(2500); ### iOS rarezas * **time**: ignora el tiempo especificado y vibra por un tiempo preestablecido. navigator.notification.vibrate(); navigator.notification.vibrate(2500); // 2500 is ignored ## *Notification.vibrateWithPattern (obsoleto) Vibra el dispositivo con un patrón determinado. navigator.notification.vibrateWithPattern(pattern, repeat) * **patrón**: secuencia de duraciones (en milisegundos) que desea activar o desactivar el vibrador. *(Matriz de números)* * **repito**: índice opcional en la matriz de patrón en el cual comenzar repitiendo (se repite hasta que se cancele), o -1 para la no repetición (por defecto). *(Número)* ### Ejemplo // Immediately start vibrating // vibrate for 100ms, // wait for 100ms, // vibrate for 200ms, // wait for 100ms, // vibrate for 400ms, // wait for 100ms, // vibrate for 800ms, // (do not repeat) navigator.notification.vibrateWithPattern([0, 100, 100, 200, 100, 400, 100, 800]); ## *Notification.cancelVibration (obsoleto) Inmediatamente se cancela cualquier vibración actualmente en ejecución. navigator.notification.cancelVibration() * Nota: debido a la alineación con la especificación del w3c, los métodos favoritos a ser eliminados
{'repo_name': 'blangslet/treasure-hunt', 'stars': '104', 'repo_language': 'Objective-C', 'file_name': 'crossdomain.xml', 'mime_type': 'text/xml', 'hash': 3013374103347810665, 'source_dataset': 'data'}
{ "ver": "1.0.1", "uuid": "92736375-1111-4844-b612-97f5f47a233c", "downloadMode": 0, "subMetas": {} }
{'repo_name': 'ares5221/cocos-creator-game', 'stars': '154', 'repo_language': 'JavaScript', 'file_name': 'game-scene.js', 'mime_type': 'text/plain', 'hash': 8723897835901750633, 'source_dataset': 'data'}
/* * Copyright 2013 ZXing 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. */ #import "ZXDataMatrixEncoder.h" @interface ZXDataMatrixEdifactEncoder : NSObject <ZXDataMatrixEncoder> @end
{'repo_name': 'januslo/react-native-bluetooth-escpos-printer', 'stars': '136', 'repo_language': 'Objective-C', 'file_name': 'settings.json', 'mime_type': 'text/plain', 'hash': -3779127211328006964, 'source_dataset': 'data'}
#ifndef __ADAU1373_H__ #define __ADAU1373_H__ enum adau1373_pll_src { ADAU1373_PLL_SRC_MCLK1 = 0, ADAU1373_PLL_SRC_BCLK1 = 1, ADAU1373_PLL_SRC_BCLK2 = 2, ADAU1373_PLL_SRC_BCLK3 = 3, ADAU1373_PLL_SRC_LRCLK1 = 4, ADAU1373_PLL_SRC_LRCLK2 = 5, ADAU1373_PLL_SRC_LRCLK3 = 6, ADAU1373_PLL_SRC_GPIO1 = 7, ADAU1373_PLL_SRC_GPIO2 = 8, ADAU1373_PLL_SRC_GPIO3 = 9, ADAU1373_PLL_SRC_GPIO4 = 10, ADAU1373_PLL_SRC_MCLK2 = 11, }; enum adau1373_pll { ADAU1373_PLL1 = 0, ADAU1373_PLL2 = 1, }; enum adau1373_clk_src { ADAU1373_CLK_SRC_PLL1 = 0, ADAU1373_CLK_SRC_PLL2 = 1, }; #endif
{'repo_name': 'CyanogenMod/android_kernel_oneplus_msm8974', 'stars': '129', 'repo_language': 'C', 'file_name': 'usb.h', 'mime_type': 'text/x-c', 'hash': 7422501435910657312, 'source_dataset': 'data'}
<?php /** * Theme filters. */ namespace App; /** * Add "… Continued" to the excerpt. * * @return string */ add_filter('excerpt_more', function () { return ' &hellip; <a href="' . get_permalink() . '">' . __('Continued', 'sage') . '</a>'; });
{'repo_name': 'roots/sage', 'stars': '10720', 'repo_language': 'PHP', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 5849809257018653063, 'source_dataset': 'data'}
using System; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using GlobalResources; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Exceptions; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Infrastructure.Models; using Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.Security; namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.WebApiControllers { [Authorize] [WebApiCSRFValidation] public abstract class WebApiControllerBase : ApiController { protected async Task<HttpResponseMessage> GetServiceResponseAsync(Func<Task> getData) { if (getData == null) { throw new ArgumentNullException("getData"); } return await GetServiceResponseAsync<object>(async () => { await getData(); return null; }); } /// <summary> /// Wraps the response from the getData call into a ServiceResponse object /// If an exception is thrown it is caught and put into the Error property of the service response /// </summary> /// <typeparam name="T">Type returned by the getData call</typeparam> /// <param name="getData">Lambda to actually take the action of retrieving the data from the business logic layer</param> /// <returns></returns> protected async Task<HttpResponseMessage> GetServiceResponseAsync<T>(Func<Task<T>> getData) { if (getData == null) { throw new ArgumentNullException("getData"); } return await GetServiceResponseAsync(getData, true); } /// <summary> /// Wraps the response from the getData call into a ServiceResponse object /// If an exception is thrown it is caught and put into the Error property of the service response /// </summary> /// <typeparam name="T">Type returned by the getData call</typeparam> /// <param name="getData">Lambda to actually take the action of retrieving the data from the business logic layer</param> /// <param name="useServiceResponse">Returns a service response wrapping the data in a Data property in the response, this is ignored if there is an error</param> /// <returns></returns> protected async Task<HttpResponseMessage> GetServiceResponseAsync<T>(Func<Task<T>> getData, bool useServiceResponse) { ServiceResponse<T> response = new ServiceResponse<T>(); if (getData == null) { throw new ArgumentNullException("getData"); } try { response.Data = await getData(); } catch (ValidationException ex) { if (ex.Errors == null || ex.Errors.Count == 0) { response.Error.Add(new Error("Unknown validation error")); } else { foreach (string error in ex.Errors) { response.Error.Add(new Error(error)); } } } catch (DeviceAdministrationExceptionBase ex) { response.Error.Add(new Error(ex.Message)); } catch (HttpResponseException) { throw; } catch (Exception ex) { response.Error.Add(new Error(ex)); Debug.Write(FormatExceptionMessage(ex), " GetServiceResponseAsync Exception"); } // if there's an error or we've been asked to use a service response, then return a service response if (response.Error.Count > 0 || useServiceResponse) { return Request.CreateResponse( response.Error != null && response.Error.Any() ? HttpStatusCode.BadRequest : HttpStatusCode.OK, response); } // otherwise there's no error and we need to return the data at the root of the response return Request.CreateResponse(HttpStatusCode.OK, response.Data); } protected HttpResponseMessage GetNullRequestErrorResponse<T>() { ServiceResponse<T> response = new ServiceResponse<T>(); response.Error.Add(new Error(Strings.RequestNullError)); return Request.CreateResponse(HttpStatusCode.BadRequest, response); } protected HttpResponseMessage GetFormatErrorResponse<T>(string parameterName, string type) { ServiceResponse<T> response = new ServiceResponse<T>(); string errorMessage = String.Format( CultureInfo.CurrentCulture, Strings.RequestFormatError, parameterName, type); response.Error.Add(new Error(errorMessage)); return Request.CreateResponse(HttpStatusCode.BadRequest, response); } protected void TerminateProcessingWithMessage(HttpStatusCode statusCode, string message) { HttpResponseMessage responseMessage = new HttpResponseMessage() { StatusCode = statusCode, ReasonPhrase = message }; throw new HttpResponseException(responseMessage); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.WebApiControllers.WebApiControllerBase.TerminateProcessingWithMessage(System.Net.HttpStatusCode,System.String)")] protected void ValidateArgumentNotNullOrWhitespace(string argumentName, string value) { Debug.Assert( !string.IsNullOrWhiteSpace(argumentName), "argumentName is a null reference, empty string, or contains only whitespace."); if (string.IsNullOrWhiteSpace(value)) { // Error strings are not localized. string errorText = string.Format( CultureInfo.InvariantCulture, "{0} is null, empty, or just whitespace.", argumentName); TerminateProcessingWithMessage(HttpStatusCode.BadRequest, errorText); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.WebApiControllers.WebApiControllerBase.TerminateProcessingWithMessage(System.Net.HttpStatusCode,System.String)")] protected void ValidateArgumentNotNull(string argumentName, object value) { Debug.Assert( !string.IsNullOrWhiteSpace(argumentName), "argumentName is a null reference, empty string, or contains only whitespace."); if (value == null) { // Error strings are not localized. string errorText = string.Format(CultureInfo.InvariantCulture, "{0} is a null reference.", argumentName); TerminateProcessingWithMessage(HttpStatusCode.BadRequest, errorText); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Azure.Devices.Applications.RemoteMonitoring.DeviceAdmin.Web.WebApiControllers.WebApiControllerBase.TerminateProcessingWithMessage(System.Net.HttpStatusCode,System.String)")] protected void ValidatePositiveValue(string argumentName, int value) { Debug.Assert( !string.IsNullOrWhiteSpace(argumentName), "argumentName is a null reference, empty string, or contains only whitespace."); if (value <= 0) { // Error strings are not localized. string errorText = string.Format( CultureInfo.InvariantCulture, "{0} is not a positive integer.", argumentName); TerminateProcessingWithMessage(HttpStatusCode.BadRequest, errorText); } } private static string FormatExceptionMessage(Exception ex) { Debug.Assert(ex != null, "ex is a null reference."); // Error strings are not localized return string.Format( CultureInfo.CurrentCulture, "{0}{0}*** EXCEPTION ***{0}{0}{1}{0}{0}", Console.Out.NewLine, ex); } } }
{'repo_name': 'Azure/azure-iot-remote-monitoring', 'stars': '254', 'repo_language': 'C#', 'file_name': 'dev-setup.md', 'mime_type': 'text/plain', 'hash': -55160042141248251, 'source_dataset': 'data'}
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tibialyzer { class TimestampManager { public static int createStamp() { var time = DateTime.Now; int hour = time.Hour; int minute = time.Minute; return getStamp(hour, minute); } public static Tuple<int, int> ParseTimestamp(string timestamp) { if (timestamp.Length < 5) return null; return new Tuple<int, int>(int.Parse(timestamp.Substring(0, 2)), int.Parse(timestamp.Substring(3, 2))); } public static int getStamp(int hour, int minute) { return hour * 60 + minute; } public static List<string> getLatestTimes(int count, int ignoreStamp = -1) { var time = DateTime.Now; int hour = time.Hour; int minute = time.Minute; return getLatestTimes(hour, minute, count, ignoreStamp); } public static string FormatTimestamp(int hour, int minute) { while (hour < 0) { hour += 24; } while (minute < 0) { minute += 60; } return String.Format("{0:00}:{1:00}", hour, minute); } public static string getCurrentTimestamp() { var time = DateTime.Now; int hour = time.Hour; int minute = time.Minute; return FormatTimestamp(hour, minute); } public static Tuple<int, int> getCurrentTime() { var time = DateTime.Now; return new Tuple<int, int>(time.Hour, time.Minute); } public static List<string> getLatestTimes(int hour, int minute, int count, int ignoreStamp = -1) { List<string> stamps = new List<string>(); for (int i = 0; i < count; i++) { if (getStamp(hour, minute) == ignoreStamp) return stamps; stamps.Add(FormatTimestamp(hour, minute)); if (minute == 0) { hour = hour > 0 ? hour - 1 : 23; minute = 59; } else { minute = minute - 1; } } return stamps; } public static List<int> getLatestStamps(int count, int ignoreStamp = -1) { var time = DateTime.Now; int hour = time.Hour; int minute = time.Minute; return getLatestStamps(hour, minute, count, ignoreStamp); } public static List<int> getLatestStamps(int hour, int minute, int count, int ignoreStamp = -1) { List<int> stamps = new List<int>(); for (int i = 0; i < count; i++) { int stamp = getStamp(hour, minute); stamps.Add(stamp); if (stamp == ignoreStamp) return stamps; if (minute == 0) { hour = hour > 0 ? hour - 1 : 23; minute = 59; } else { minute = minute - 1; } } return stamps; } public static int getDayStamp() { var t = DateTime.Now; return t.Year * 400 + t.Month * 40 + t.Day; } public static int Distance(string timestamp, string timestamp2) { var one = ParseTimestamp(timestamp); var two = ParseTimestamp(timestamp2); return Distance(one.Item1, one.Item2, two.Item1, two.Item2); } public static int Distance(int hour, int minute, int hour2, int minute2) { int v1 = hour * 60 + minute; int v2 = hour2 * 60 + minute2; return Math.Min(Math.Abs(v2 - v1), Math.Abs((Math.Max(v1, v2) - 60 * 24) - Math.Min(v1, v2))); } } }
{'repo_name': 'Mytherin/Tibialyzer', 'stars': '166', 'repo_language': 'C#', 'file_name': 'Resources.Designer.cs', 'mime_type': 'text/plain', 'hash': 7786856797093920791, 'source_dataset': 'data'}
package io.cattle.platform.servicediscovery.service.impl; import static io.cattle.platform.core.model.tables.AccountLinkTable.*; import static io.cattle.platform.core.model.tables.RegionTable.*; import static io.cattle.platform.core.model.tables.ServiceConsumeMapTable.*; import static io.cattle.platform.core.model.tables.ServiceTable.*; import io.cattle.platform.agent.instance.dao.AgentInstanceDao; import io.cattle.platform.core.addon.ExternalCredential; import io.cattle.platform.core.addon.LbConfig; import io.cattle.platform.core.addon.PortRule; import io.cattle.platform.core.constants.AccountConstants; import io.cattle.platform.core.constants.AgentConstants; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.CredentialConstants; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.constants.ServiceConstants; import io.cattle.platform.core.model.Account; import io.cattle.platform.core.model.AccountLink; import io.cattle.platform.core.model.Agent; import io.cattle.platform.core.model.Region; import io.cattle.platform.core.model.Service; import io.cattle.platform.core.model.ServiceConsumeMap; import io.cattle.platform.core.util.SystemLabels; import io.cattle.platform.iaas.api.filter.apikey.ApiKeyFilter; import io.cattle.platform.json.JsonMapper; import io.cattle.platform.lock.LockCallbackNoReturn; import io.cattle.platform.lock.LockManager; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.process.ObjectProcessManager; import io.cattle.platform.object.process.StandardProcess; import io.cattle.platform.object.util.DataAccessor; import io.cattle.platform.process.common.lock.AccountLinksUpdateLock; import io.cattle.platform.servicediscovery.service.RegionService; import io.cattle.platform.servicediscovery.service.impl.RegionUtil.ExternalAccountLink; import io.cattle.platform.servicediscovery.service.impl.RegionUtil.ExternalAgent; import io.cattle.platform.servicediscovery.service.impl.RegionUtil.ExternalProject; import io.cattle.platform.servicediscovery.service.impl.RegionUtil.ExternalProjectResponse; import io.cattle.platform.servicediscovery.service.impl.RegionUtil.ExternalRegion; import io.github.ibuildthecloud.gdapi.condition.Condition; import io.github.ibuildthecloud.gdapi.condition.ConditionType; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RegionServiceImpl implements RegionService { private static final Logger log = LoggerFactory.getLogger(RegionServiceImpl.class); private static final List<String> INVALID_STATES = Arrays.asList(CommonStatesConstants.REMOVING, CommonStatesConstants.REMOVED); @Inject ObjectManager objectManager; @Inject JsonMapper jsonMapper; @Inject ObjectProcessManager objectProcessManager; @Inject AgentInstanceDao agentInstanceDao; @Inject LockManager lockManager; @Override public void reconcileExternalLinks(long accountId) { lockManager.lock(new AccountLinksUpdateLock(accountId), new LockCallbackNoReturn() { @Override public void doWithLockNoResult() { List<Region> regions = objectManager.find(Region.class, REGION.REMOVED, new Condition(ConditionType.NULL)); if (regions.size() == 0) { return; } Account localAccount = objectManager.loadResource(Account.class, accountId); if (INVALID_STATES.contains(localAccount.getState())) { return; } Map<String, Region> regionsMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); Region localRegion = null; for (Region region : regions) { regionsMap.put(region.getName(), region); if (region.getLocal()) { localRegion = region; } } List<AccountLink> toRemove = new ArrayList<>(); List<AccountLink> toUpdate = new ArrayList<>(); Set<String> toCreate = new HashSet<>(); fetchAccountLinks(accountId, regionsMap, localRegion, toRemove, toUpdate, toCreate); reconcileAccountLinks(accountId, regionsMap, toRemove, toUpdate, toCreate); } }); } private void reconcileAccountLinks(long accountId, Map<String, Region> regionsMap, List<AccountLink> toRemove, List<AccountLink> toUpdate, Set<String> toCreate) { for (AccountLink item : toRemove) { if (!item.getState().equalsIgnoreCase(CommonStatesConstants.REMOVING)) { objectProcessManager.scheduleStandardProcess(StandardProcess.REMOVE, item, null); } } Set<String> invalidAccounts = new HashSet<>(); for (String item : toCreate) { String[] splitted = item.split(":"); String regionName = splitted[0]; String envName = splitted[1]; Region region = regionsMap.get(regionName); ExternalProject externalProject = null; if (region != null && !INVALID_STATES.contains(region.getState())) { try { String externalProjectKey = String.format("%s:%s", regionName, envName); if(invalidAccounts.contains(externalProjectKey)) { continue; } ExternalProjectResponse externalProjectResponse = RegionUtil.getTargetProjectByName(region, envName, jsonMapper); externalProject = externalProjectResponse.externalProject; if(externalProject == null) { invalidAccounts.add(externalProjectKey); continue; } AccountLink link = objectManager.create(AccountLink.class, ACCOUNT_LINK.ACCOUNT_ID, accountId, ACCOUNT_LINK.LINKED_ACCOUNT, envName, ACCOUNT_LINK.LINKED_REGION, regionName, ACCOUNT_LINK.LINKED_REGION_ID, region.getId(), "linkedAccountUuid", externalProject.getUuid()); toUpdate.add(link); } catch(Exception ex) { log.warn(String.format("Failed to find account for %s - %s", envName, ex)); } } } for (AccountLink item : toUpdate) { if (item.getState().equalsIgnoreCase(CommonStatesConstants.REQUESTED)) { objectProcessManager.scheduleStandardProcessAsync(StandardProcess.CREATE, item, null); } } } private void fetchAccountLinks(long accountId, Map<String, Region> regionsMap, Region localRegion, List<AccountLink> toRemove, List<AccountLink> toUpdate, Set<String> toCreate) { List<? extends ServiceConsumeMap> links = objectManager.find(ServiceConsumeMap.class, SERVICE_CONSUME_MAP.ACCOUNT_ID, accountId, SERVICE_CONSUME_MAP.REMOVED, null, SERVICE_CONSUME_MAP.CONSUMED_SERVICE, new Condition(ConditionType.NOTNULL)); Set<String> toAdd = new HashSet<>(); for (ServiceConsumeMap link : links) { if (INVALID_STATES.contains(link.getState())) { continue; } if (link.getConsumedService() == null) { continue; } String[] splitted = link.getConsumedService().split("/"); if (splitted.length < 3) { continue; } if (splitted.length == 4) { if (regionsMap.containsKey(splitted[0])) { toAdd.add(getUUID(splitted[0], splitted[1])); } } else if (splitted.length == 3) { toAdd.add(getUUID(localRegion.getName(), splitted[0])); } } List<? extends Service> lbs = objectManager.find(Service.class, SERVICE.ACCOUNT_ID, accountId, SERVICE.REMOVED, null, SERVICE.KIND, ServiceConstants.KIND_LOAD_BALANCER_SERVICE); for (Service lb : lbs) { if (INVALID_STATES.contains(lb.getState())) { continue; } LbConfig lbConfig = DataAccessor.field(lb, ServiceConstants.FIELD_LB_CONFIG, jsonMapper, LbConfig.class); if (lbConfig != null && lbConfig.getPortRules() != null) { for (PortRule rule : lbConfig.getPortRules()) { String rName = rule.getRegion(); String eName = rule.getEnvironment(); if (StringUtils.isEmpty(eName)) { continue; } if (StringUtils.isEmpty(rName)) { rName = localRegion.getName(); } if (regionsMap.containsKey(rName)) { toAdd.add(getUUID(rName, eName)); } } } } List<? extends AccountLink> existingLinks = objectManager.find(AccountLink.class, ACCOUNT_LINK.ACCOUNT_ID, accountId, ACCOUNT_LINK.REMOVED, null, ACCOUNT_LINK.LINKED_ACCOUNT, new Condition(ConditionType.NOTNULL), ACCOUNT_LINK.LINKED_REGION, new Condition(ConditionType.NOTNULL), ACCOUNT_LINK.EXTERNAL, false); Set<String> existingLinksKeys = new HashSet<>(); for (AccountLink existingLink : existingLinks) { existingLinksKeys.add(getUUID(existingLink.getLinkedRegion(), existingLink.getLinkedAccount())); } for (AccountLink link : existingLinks) { if (!toAdd.contains(getUUID(link.getLinkedRegion(), link.getLinkedAccount()))) { toRemove.add(link); } else { toUpdate.add(link); } } for (String item : toAdd) { if (!existingLinksKeys.contains(item)) { toCreate.add(item); } } } private String getUUID(String regionName, String envName) { return String.format("%s:%s", regionName, envName); } @Override public boolean isRegionsEmpty(Agent agent, Account account, Map<String, Long> externalLinks, Map<String, ExternalProject> projects, Map<Long, Region> regionsIds, Map<String, Region> regionNameToRegion) { List<Region> regions = objectManager.find(Region.class, REGION.REMOVED, (Object) null); for(Region region : regions) { regionsIds.put(region.getId(), region); regionNameToRegion.put(region.getName(), region); } getLinkedEnvironments(account.getId(), externalLinks, regionsIds, projects); boolean noExternalLinks = externalLinks.isEmpty(); List<? extends ExternalCredential> existing = DataAccessor.fieldObjectList(agent, AccountConstants.FIELD_EXTERNAL_CREDENTIALS, ExternalCredential.class, jsonMapper); boolean noExternalCreds = existing.isEmpty(); if (noExternalLinks && noExternalCreds) { return true; } return false; } @Override public boolean reconcileAgentExternalCredentials(Agent agent, Account account, Map<String, Long> externalLinks, Map<String, ExternalProject> projects, Map<Long, Region> regionsIds, Map<String, Region> regionNameToRegion) { Region localRegion = null; for (Region region : regionsIds.values()) { if (region.getLocal()) { localRegion = region; } } boolean success = true; // 2. Reconcile agent's credentials try { reconcileExternalCredentials(account, agent, localRegion, externalLinks, projects, regionNameToRegion); } catch (Exception ex) { success = false; log.error(String.format("Fail to reconcile credentials for agent [%d]", agent.getId()), ex); } return success; } protected void reconcileExternalCredentials(Account account, Agent agent, Region localRegion, Map<String, Long> externalLinks, Map<String, ExternalProject> externalProjects, Map<String, Region> regionNameToRegion) { // 1. Set credentials Map<String, ExternalCredential> toAdd = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); Map<String, ExternalCredential> toRemove = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); Map<String, ExternalCredential> toRetain = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); setCredentials(agent, externalLinks, toAdd, toRemove, toRetain); // 2. Reconcile agents reconcileExternalAgents(account, agent, localRegion, regionNameToRegion, toAdd, toRemove, toRetain, externalProjects); } private ExternalAgent createExternalAgent(Agent agent, Account account, Region localRegion, Region targetRegion, ExternalCredential cred, Map<String, ExternalProject> externalProjects) { // Create external agent with local credentials try { String UUID = getUUID(targetRegion.getName(), cred.getEnvironmentName()); ExternalProject targetResourceAccount = null; if (externalProjects.containsKey(UUID)) { targetResourceAccount = externalProjects.get(UUID); } else { ExternalProjectResponse externalProjectResponse = RegionUtil.getTargetProjectByName(targetRegion, cred.getEnvironmentName(), jsonMapper); targetResourceAccount = externalProjectResponse.externalProject; if (targetResourceAccount == null) { throw new RuntimeException(String.format("Failed to find target environment by name [%s] in region [%s]", cred.getEnvironmentName(), targetRegion.getName())); } externalProjects.put(UUID, targetResourceAccount); } String targetAgentUri = RegionUtil.getTargetAgentUri(localRegion.getName(), account.getName(), agent.getUuid(), targetResourceAccount.getUuid()); log.info(String.format("Creating external agent with uri [%s] in environment [%s] in region [%s]", targetAgentUri, cred.getEnvironmentName(), cred.getRegionName())); Map<String, Object> data = new HashMap<>(); data.put(AgentConstants.DATA_AGENT_RESOURCES_ACCOUNT_ID, targetResourceAccount.getId()); data.put(CredentialConstants.PUBLIC_VALUE, cred.getPublicValue()); data.put(CredentialConstants.SECRET_VALUE, cred.getSecretValue()); data.put(AgentConstants.FIELD_URI, targetAgentUri); data.put(AgentConstants.FIELD_EXTERNAL_ID, agent.getUuid()); Map<String, String> labels = new HashMap<>(); labels.put(SystemLabels.LABEL_AGENT_SERVICE_METADATA, "true"); data.put(InstanceConstants.FIELD_LABELS, labels); data.put("activateOnCreate", true); return RegionUtil.createExternalAgent(targetRegion, cred.getEnvironmentName(), data, jsonMapper); } catch (Exception e) { log.error("Failed to create external agent", e); return null; } } @Override /** * This method creates an external account link in the target environment as ipsec service * would need two way links */ public void createExternalAccountLink(AccountLink link) { if (link.getExternal()) { return; } try { Region targetRegion = objectManager.loadResource(Region.class, link.getLinkedRegionId()); Region localRegion = objectManager.findAny(Region.class, REGION.LOCAL, true, REGION.REMOVED, null); if(localRegion == null) { log.warn("No local region present"); return; } ExternalRegion externalRegion = RegionUtil.getExternalRegion(targetRegion, localRegion.getName(), jsonMapper); if (externalRegion == null) { throw new RuntimeException(String.format("Failed to find local region [%s] in external region [%s]", localRegion.getName(), targetRegion.getName())); } ExternalProjectResponse externalProjectResponse = RegionUtil.getTargetProjectByName(targetRegion, link.getLinkedAccount(), jsonMapper); ExternalProject targetResourceAccount = externalProjectResponse.externalProject; if (targetResourceAccount == null) { throw new RuntimeException(String.format("Failed to find target environment by name [%s] in region [%s]", link.getLinkedAccount(), localRegion.getName())); } Account localAccount = objectManager.loadResource(Account.class, link.getAccountId()); ExternalAccountLink externalLink = RegionUtil.getExternalAccountLink(targetRegion, targetResourceAccount, localAccount, jsonMapper); if (externalLink != null) { return; } Map<String, Object> data = new HashMap<>(); data.put("accountId", targetResourceAccount.getId()); data.put("external", "true"); data.put("linkedAccount", localAccount.getName()); data.put("linkedRegion", externalRegion.getName()); data.put("linkedRegionId", externalRegion.getId()); data.put("linkedAccountUuid", localAccount.getUuid()); externalLink = RegionUtil.createExternalAccountLink(targetRegion, data, jsonMapper); } catch (Exception ex) { throw new RuntimeException(String.format("Failed to create external account link for accountLink [%d]", link.getId()), ex); } } @Override public boolean deleteExternalAccountLink(AccountLink link) { if (link.getExternal()) { return true; } try { Region targetRegion = objectManager.loadResource(Region.class, link.getLinkedRegionId()); if(targetRegion == null) { return true; } ExternalProjectResponse externalProjectResponse = RegionUtil.getTargetProjectByName(targetRegion, link.getLinkedAccount(), jsonMapper); ExternalProject targetResourceAccount = externalProjectResponse.externalProject; if (targetResourceAccount == null) { String UUID = DataAccessor.fieldString(link, "linkedAccountUuid"); targetResourceAccount = RegionUtil.getTargetProjectByUUID(targetRegion, UUID, jsonMapper); if (targetResourceAccount == null) { log.info(String.format("Failed to find target environment by UUID [%s] in region [%s]", UUID, targetRegion.getName())); return true; } } Account localAccount = objectManager.loadResource(Account.class, link.getAccountId()); ExternalAccountLink externalLink = RegionUtil.getExternalAccountLink(targetRegion, targetResourceAccount, localAccount, jsonMapper); if (externalLink == null) { return true; } RegionUtil.deleteExternalAccountLink(targetRegion, externalLink); return true; } catch (Exception ex) { log.error(String.format("Failed to delete external account link for accountLink [%d]", link.getId()), ex); return false; } } private void reconcileExternalAgents(Account account, Agent agent, Region localRegion, Map<String, Region> regions, Map<String, ExternalCredential> toAdd, Map<String, ExternalCredential> toRemove, Map<String, ExternalCredential> toRetain, Map<String, ExternalProject> externalProjects) { // 1. Add missing agents boolean changed = false; for (String key : toAdd.keySet()) { ExternalCredential value = toAdd.get(key); ExternalAgent externalAgent = createExternalAgent(agent, account, localRegion, regions.get(value.getRegionName()), toAdd.get(key), externalProjects); if (externalAgent != null) { value.setAgentUuid(externalAgent.getUuid()); // only add credential of the agent which got created successfully toRetain.put(key, value); changed = true; } } // 2. Remove extra agents. for (String key : toRemove.keySet()) { ExternalCredential value = toRemove.get(key); deactivateAndRemoveExternalAgent(agent, value); changed = true; } if (changed) { objectManager.setFields(agent, AccountConstants.FIELD_EXTERNAL_CREDENTIALS, toRetain.values()); } } protected boolean deactivateAndRemoveExternalAgent(Agent agent, ExternalCredential cred) { Region targetRegion = objectManager.loadResource(Region.class, cred.getRegionId()); if (targetRegion == null) { log.info(String.format("Failed to find target region by name [%s]", cred.getRegionName())); return true; } String regionName = cred.getRegionName(); String envName = cred.getEnvironmentName(); try { log.info(String.format("Removing agent with externalId [%s] in environment [%s] and region [%s]", agent.getUuid(), regionName, envName)); ExternalAgent externalAgent = RegionUtil.getExternalAgent(targetRegion, cred.getAgentUuid(), jsonMapper); if (externalAgent == null) { log.info(String.format("Failed to find agent by externalId [%s] in environment [%s] and region [%s]", agent.getUuid(), regionName, envName)); return true; } RegionUtil.deleteExternalAgent(agent, targetRegion, externalAgent); return true; } catch (Exception e) { log.error( String.format("Failed to deactivate agent with externalId [%s] in environment [%s] and region [%s]", agent.getUuid(), regionName, envName), e); return false; } } private void setCredentials(Agent agent, Map<String, Long> externalLinks, Map<String, ExternalCredential> toAdd, Map<String, ExternalCredential> toRemove, Map<String, ExternalCredential> toRetain) { List<? extends ExternalCredential> existing = DataAccessor.fieldObjectList(agent, AccountConstants.FIELD_EXTERNAL_CREDENTIALS, ExternalCredential.class, jsonMapper); Map<String, ExternalCredential> existingCredentials = new HashMap<>(); for (ExternalCredential cred : existing) { existingCredentials.put(getUUID(cred.getRegionName(), cred.getEnvironmentName()), cred); } for (String key : externalLinks.keySet()) { String[] splitted = key.split(":"); String regionName = splitted[0]; String envName = splitted[1]; String uuid = getUUID(regionName, envName); if (existingCredentials.containsKey(uuid)) { toRetain.put(uuid, existingCredentials.get(uuid)); } else { String[] keys = ApiKeyFilter.generateKeys(); toAdd.put(uuid, new ExternalCredential(envName, regionName, keys[0], keys[1], externalLinks.get(key))); } } for (String key : existingCredentials.keySet()) { if (!(toAdd.containsKey(key) || toRetain.containsKey(key))) { toRemove.put(key, existingCredentials.get(key)); } } } private void getLinkedEnvironments(long accountId, Map<String, Long> links, Map<Long, Region> regionsIds, Map<String, ExternalProject> externalProjects) { List<AccountLink> accountLinks = objectManager.find(AccountLink.class, ACCOUNT_LINK.ACCOUNT_ID, accountId, ACCOUNT_LINK.REMOVED, null, ACCOUNT_LINK.LINKED_REGION_ID, new Condition(ConditionType.NOTNULL)); for (AccountLink link : accountLinks) { if (link.getState().equalsIgnoreCase(CommonStatesConstants.REMOVING)) { continue; } if(link.getState().equalsIgnoreCase(CommonStatesConstants.REMOVED)) { continue; } Region targetRegion = regionsIds.get(link.getLinkedRegionId()); if (targetRegion == null) { continue; } String UUID = getUUID(targetRegion.getName(), link.getLinkedAccount()); if (!externalProjects.containsKey(UUID)) { links.put(UUID, targetRegion.getId()); } } } @Override public boolean deactivateAndRemoveExternalAgent(Agent agent) { List<? extends ExternalCredential> creds = DataAccessor.fieldObjectList(agent, AccountConstants.FIELD_EXTERNAL_CREDENTIALS, ExternalCredential.class, jsonMapper); if (creds.isEmpty()) { return true; } Map<String, Region> regions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Region region : objectManager.find(Region.class, REGION.REMOVED, new Condition(ConditionType.NULL))) { regions.put(region.getName(), region); } for (ExternalCredential cred : creds) { if (!deactivateAndRemoveExternalAgent(agent, cred)) { return false; } } return true; } }
{'repo_name': 'rancher/cattle', 'stars': '557', 'repo_language': 'Java', 'file_name': 'key.pem', 'mime_type': 'text/plain', 'hash': -3147716183969784083, 'source_dataset': 'data'}
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.util; /** * The {@code TimerTask} class represents a task to run at a specified time. The task * may be run once or repeatedly. * * @see Timer * @see java.lang.Object#wait(long) */ public abstract class TimerTask implements Runnable { /* Lock object for synchronization. It's also used by Timer class. */ final Object lock = new Object(); /* If timer was cancelled */ boolean cancelled; /* Slots used by Timer */ long when; long period; boolean fixedRate; /* * The time when task will be executed, or the time when task was launched * if this is task in progress. */ private long scheduledTime; /* * Method called from the Timer for synchronized getting of when field. */ long getWhen() { synchronized (lock) { return when; } } /* * Method called from the Timer object when scheduling an event @param time */ void setScheduledTime(long time) { synchronized (lock) { scheduledTime = time; } } /* * Is TimerTask scheduled into any timer? * * @return {@code true} if the timer task is scheduled, {@code false} * otherwise. */ boolean isScheduled() { synchronized (lock) { return when > 0 || scheduledTime > 0; } } /** * Creates a new {@code TimerTask}. */ protected TimerTask() { super(); } /** * Cancels the {@code TimerTask} and removes it from the {@code Timer}'s queue. Generally, it * returns {@code false} if the call did not prevent a {@code TimerTask} from running at * least once. Subsequent calls have no effect. * * @return {@code true} if the call prevented a scheduled execution * from taking place, {@code false} otherwise. */ public boolean cancel() { synchronized (lock) { boolean willRun = !cancelled && when > 0; cancelled = true; return willRun; } } /** * Returns the scheduled execution time. If the task execution is in * progress it returns the execution time of the ongoing task. Tasks which * have not yet run return an undefined value. * * @return the most recent execution time. */ public long scheduledExecutionTime() { synchronized (lock) { return scheduledTime; } } /** * The task to run should be specified in the implementation of the {@code run()} * method. */ public abstract void run(); }
{'repo_name': 'openweave/openweave-core', 'stars': '172', 'repo_language': 'C++', 'file_name': 'missing-space-after-else-if.cmp', 'mime_type': 'text/plain', 'hash': 8729209115718349387, 'source_dataset': 'data'}
typedef float tocheck_t; #define ESIZE 8 #define MSIZE 23 #define FUNC(x) x##f #include "test-arith.c"
{'repo_name': 'bminor/glibc', 'stars': '400', 'repo_language': 'C', 'file_name': 'check_fds.c', 'mime_type': 'text/x-c', 'hash': -8404801540995662651, 'source_dataset': 'data'}
var nativeCreate = require('./_nativeCreate'); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet;
{'repo_name': 'ZhuPeng/mp-githubtrending', 'stars': '163', 'repo_language': 'JavaScript', 'file_name': 'HISTORY.md', 'mime_type': 'text/plain', 'hash': -3955121372658426389, 'source_dataset': 'data'}
/*---------------------------------------------------------------- Copyright (C) 2020 Senparc 文件名:EncryptResponseMessage.cs 文件功能描述:返回给服务器的加密消息 创建标识:Senparc - 20150313 修改标识:Senparc - 20150313 修改描述:整理接口 ----------------------------------------------------------------*/ namespace Senparc.Weixin.Work.Entities.Response { /// <summary> /// 返回给服务器的加密消息 /// </summary> public class EncryptResponseMessage { public string Encrypt { get; set; } public string MsgSignature { get; set; } public string TimeStamp { get; set; } public string Nonce { get; set; } } }
{'repo_name': 'JeffreySu/WeiXinMPSDK', 'stars': '6300', 'repo_language': 'C#', 'file_name': 'readme.md', 'mime_type': 'text/plain', 'hash': 732963491761181724, 'source_dataset': 'data'}
object Form1: TForm1 Left = 0 Top = 0 Caption = 'Form1' ClientHeight = 577 ClientWidth = 351 FormFactor.Width = 320 FormFactor.Height = 480 FormFactor.Devices = [Desktop] OnClose = FormClose OnShow = FormShow DesignerMasterStyle = 1 object Panel1: TPanel Align = Client Size.Width = 351.000000000000000000 Size.Height = 577.000000000000000000 Size.PlatformDefault = False TabOrder = 12 object TabControl1: TTabControl Align = Client FullSize = True Size.Width = 351.000000000000000000 Size.Height = 577.000000000000000000 Size.PlatformDefault = False TabHeight = 49.000000000000000000 TabIndex = 0 TabOrder = 1 TabPosition = Bottom object TabItem1: TTabItem CustomIcon = < item end> IsSelected = True Size.Width = 176.000000000000000000 Size.Height = 49.000000000000000000 Size.PlatformDefault = False TabOrder = 0 Text = 'Bluetooth settings' object ButtonDiscover: TButton Position.X = 4.000000000000000000 Position.Y = 59.000000000000000000 Size.Width = 158.000000000000000000 Size.Height = 31.000000000000000000 Size.PlatformDefault = False TabOrder = 0 Text = 'Discover devices' OnClick = ButtonDiscoverClick end object ButtonPair: TButton Position.X = 183.000000000000000000 Position.Y = 59.000000000000000000 Size.Width = 78.000000000000000000 Size.Height = 31.000000000000000000 Size.PlatformDefault = False TabOrder = 1 Text = 'Pair' OnClick = ButtonPairClick end object ButtonPairedDevices: TButton Position.X = 4.000000000000000000 Position.Y = 140.000000000000000000 Size.Width = 158.000000000000000000 Size.Height = 31.000000000000000000 Size.PlatformDefault = False TabOrder = 2 Text = 'Paired Devices' OnClick = ButtonPairedDevicesClick end object ButtonUnPair: TButton Position.X = 269.000000000000000000 Position.Y = 59.000000000000000000 Size.Width = 80.000000000000000000 Size.Height = 31.000000000000000000 Size.PlatformDefault = False TabOrder = 3 Text = 'UnPair' OnClick = ButtonUnPairClick end object ComboBoxDevices: TComboBox Position.X = 4.000000000000000000 Position.Y = 92.000000000000000000 Size.Width = 352.000000000000000000 Size.Height = 32.000000000000000000 Size.PlatformDefault = False TabOrder = 4 end object ComboBoxPaired: TComboBox Position.X = 4.000000000000000000 Position.Y = 173.000000000000000000 Size.Width = 352.000000000000000000 Size.Height = 32.000000000000000000 Size.PlatformDefault = False TabOrder = 5 OnChange = ComboBoxPairedChange end object ButtonServices: TButton Position.X = 4.000000000000000000 Position.Y = 221.000000000000000000 Size.Width = 158.000000000000000000 Size.Height = 31.000000000000000000 Size.PlatformDefault = False TabOrder = 6 Text = 'Services' OnClick = ButtonServicesClick end object ComboBoxServices: TComboBox Position.X = 4.000000000000000000 Position.Y = 254.000000000000000000 Size.Width = 352.000000000000000000 Size.Height = 32.000000000000000000 Size.PlatformDefault = False TabOrder = 7 end end object TabItem2: TTabItem CustomIcon = < item end> IsSelected = False Size.Width = 175.000000000000000000 Size.Height = 49.000000000000000000 Size.PlatformDefault = False TabOrder = 0 Text = 'Service demo' object PanelClient: TPanel Position.Y = 134.000000000000000000 Size.Width = 360.000000000000000000 Size.Height = 153.000000000000000000 Size.PlatformDefault = False TabOrder = 0 object Button2: TButton Position.X = 4.000000000000000000 Position.Y = 115.000000000000000000 Size.Width = 73.000000000000000000 Size.Height = 25.000000000000000000 Size.PlatformDefault = False TabOrder = 0 Text = 'Clear' OnClick = Button2Click end object Edit1: TEdit Touch.InteractiveGestures = [LongTap, DoubleTap] TabOrder = 1 Text = 'I am the text sent' Position.X = 4.000000000000000000 Position.Y = 71.000000000000000000 Size.Width = 343.000000000000000000 Size.Height = 32.000000000000000000 Size.PlatformDefault = False end object FreeSocket: TButton Position.X = 190.000000000000000000 Position.Y = 115.000000000000000000 Size.Width = 157.000000000000000000 Size.Height = 25.000000000000000000 Size.PlatformDefault = False TabOrder = 2 Text = 'Free Client Socket' OnClick = FreeSocketClick end object LabelNameServer: TLabel Position.X = 157.000000000000000000 Position.Y = 22.000000000000000000 Size.Width = 180.000000000000000000 Size.Height = 40.000000000000000000 Size.PlatformDefault = False end object LabelClient: TLabel StyledSettings = [Family, Size, FontColor] Position.X = 4.000000000000000000 Size.Width = 227.000000000000000000 Size.Height = 20.000000000000000000 Size.PlatformDefault = False Text = 'Client' end object ButtonConnectToRFCOMM: TButton Position.X = 4.000000000000000000 Position.Y = 28.000000000000000000 Size.Width = 143.000000000000000000 Size.Height = 33.000000000000000000 Size.PlatformDefault = False TabOrder = 5 Text = 'Send text to ->' OnClick = ButtonConnectToRFCOMMClick end end object PanelServer: TPanel Position.Y = 40.000000000000000000 Size.Width = 360.000000000000000000 Size.Height = 93.000000000000000000 Size.PlatformDefault = False TabOrder = 1 object ButtonCloseReadingSocket: TButton Position.X = 195.000000000000000000 Position.Y = 32.000000000000000000 Size.Width = 160.000000000000000000 Size.Height = 36.000000000000000000 Size.PlatformDefault = False TabOrder = 0 Text = 'Remove text service' OnClick = ButtonCloseReadingSocketClick end object ButtonOpenReadingSocket: TButton Position.X = 4.000000000000000000 Position.Y = 32.000000000000000000 Size.Width = 160.000000000000000000 Size.Height = 36.000000000000000000 Size.PlatformDefault = False TabOrder = 1 Text = 'Create text service' OnClick = ButtonOpenReadingSocketClick end object LabelServer: TLabel StyledSettings = [Family, Size, FontColor] Position.X = 4.000000000000000000 Size.Width = 227.000000000000000000 Size.Height = 20.000000000000000000 Size.PlatformDefault = False Text = 'Server' end end end end object Labeldiscoverable: TLabel StyledSettings = [Family, Style, FontColor] Position.X = 16.000000000000000000 Position.Y = 8.000000000000000000 Size.Width = 321.000000000000000000 Size.Height = 23.000000000000000000 Size.PlatformDefault = False end object DisplayR: TMemo Touch.InteractiveGestures = [Pan, LongTap, DoubleTap] Anchors = [akLeft, akTop, akRight] Position.Y = 288.000000000000000000 Size.Width = 351.000000000000000000 Size.Height = 232.000000000000000000 Size.PlatformDefault = False TabOrder = 2 TabStop = False ReadOnly = True ShowSizeGrip = True end end end
{'repo_name': 'FMXExpress/Firemonkey', 'stars': '137', 'repo_language': 'Pascal', 'file_name': 'ExplorerDevicesLECppPCH1.h', 'mime_type': 'text/x-c', 'hash': -6401851681079547426, 'source_dataset': 'data'}