Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
10
99.9k
meta
dict
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// /// Auto-generated by Stone, do not modify. /// #import <Foundation/Foundation.h> #import "DBSerializableProtocol.h" @class DBTEAMPOLICIESSharedFolderJoinPolicy; NS_ASSUME_NONNULL_BEGIN #pragma mark - API Object /// /// The `SharedFolderJoinPolicy` union. /// /// Policy governing which shared folders a team member can join. /// /// This class implements the `DBSerializable` protocol (serialize and /// deserialize instance methods), which is required for all Obj-C SDK API route /// objects. /// @interface DBTEAMPOLICIESSharedFolderJoinPolicy : NSObject <DBSerializable, NSCopying> #pragma mark - Instance fields /// The `DBTEAMPOLICIESSharedFolderJoinPolicyTag` enum type represents the /// possible tag states with which the `DBTEAMPOLICIESSharedFolderJoinPolicy` /// union can exist. typedef NS_CLOSED_ENUM(NSInteger, DBTEAMPOLICIESSharedFolderJoinPolicyTag){ /// Team members can only join folders shared by teammates. DBTEAMPOLICIESSharedFolderJoinPolicyFromTeamOnly, /// Team members can join any shared folder, including those shared by users /// outside the team. DBTEAMPOLICIESSharedFolderJoinPolicyFromAnyone, /// (no description). DBTEAMPOLICIESSharedFolderJoinPolicyOther, }; /// Represents the union's current tag state. @property (nonatomic, readonly) DBTEAMPOLICIESSharedFolderJoinPolicyTag tag; #pragma mark - Constructors /// /// Initializes union class with tag state of "from_team_only". /// /// Description of the "from_team_only" tag state: Team members can only join /// folders shared by teammates. /// /// @return An initialized instance. /// - (instancetype)initWithFromTeamOnly; /// /// Initializes union class with tag state of "from_anyone". /// /// Description of the "from_anyone" tag state: Team members can join any shared /// folder, including those shared by users outside the team. /// /// @return An initialized instance. /// - (instancetype)initWithFromAnyone; /// /// Initializes union class with tag state of "other". /// /// @return An initialized instance. /// - (instancetype)initWithOther; - (instancetype)init NS_UNAVAILABLE; #pragma mark - Tag state methods /// /// Retrieves whether the union's current tag state has value "from_team_only". /// /// @return Whether the union's current tag state has value "from_team_only". /// - (BOOL)isFromTeamOnly; /// /// Retrieves whether the union's current tag state has value "from_anyone". /// /// @return Whether the union's current tag state has value "from_anyone". /// - (BOOL)isFromAnyone; /// /// Retrieves whether the union's current tag state has value "other". /// /// @return Whether the union's current tag state has value "other". /// - (BOOL)isOther; /// /// Retrieves string value of union's current tag state. /// /// @return A human-readable string representing the union's current tag state. /// - (NSString *)tagName; @end #pragma mark - Serializer Object /// /// The serialization class for the `DBTEAMPOLICIESSharedFolderJoinPolicy` /// union. /// @interface DBTEAMPOLICIESSharedFolderJoinPolicySerializer : NSObject /// /// Serializes `DBTEAMPOLICIESSharedFolderJoinPolicy` instances. /// /// @param instance An instance of the `DBTEAMPOLICIESSharedFolderJoinPolicy` /// API object. /// /// @return A json-compatible dictionary representation of the /// `DBTEAMPOLICIESSharedFolderJoinPolicy` API object. /// + (nullable NSDictionary<NSString *, id> *)serialize:(DBTEAMPOLICIESSharedFolderJoinPolicy *)instance; /// /// Deserializes `DBTEAMPOLICIESSharedFolderJoinPolicy` instances. /// /// @param dict A json-compatible dictionary representation of the /// `DBTEAMPOLICIESSharedFolderJoinPolicy` API object. /// /// @return An instantiation of the `DBTEAMPOLICIESSharedFolderJoinPolicy` /// object. /// + (DBTEAMPOLICIESSharedFolderJoinPolicy *)deserialize:(NSDictionary<NSString *, id> *)dict; @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
/*********************************************************************** !!!!!! DO NOT MODIFY !!!!!! GacGen.exe Resource.xml This file is generated by Workflow compiler https://github.com/vczh-libraries ***********************************************************************/ #ifndef VCZH_WORKFLOW_COMPILER_GENERATED_DEMOREFLECTION #define VCZH_WORKFLOW_COMPILER_GENERATED_DEMOREFLECTION #include "Demo.h" #ifndef VCZH_DEBUG_NO_REFLECTION #include "GacUIReflection.h" #endif #if defined( _MSC_VER) #pragma warning(push) #pragma warning(disable:4250) #elif defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wparentheses-equality" #elif defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wparentheses-equality" #endif /*********************************************************************** Reflection ***********************************************************************/ namespace vl { namespace reflection { namespace description { #ifndef VCZH_DEBUG_NO_REFLECTION DECL_TYPE_INFO(::demo::MainWindow) DECL_TYPE_INFO(::demo::MainWindowConstructor) #endif extern bool LoadDemoTypes(); } } } #if defined( _MSC_VER) #pragma warning(pop) #elif defined(__GNUC__) #pragma GCC diagnostic pop #elif defined(__clang__) #pragma clang diagnostic pop #endif #endif
{ "pile_set_name": "Github" }
--- sandbox/linux/BUILD.gn.orig 2019-04-08 08:18:26 UTC +++ sandbox/linux/BUILD.gn @@ -12,12 +12,12 @@ if (is_android) { } declare_args() { - compile_suid_client = is_linux + compile_suid_client = is_linux && !is_bsd - compile_credentials = is_linux + compile_credentials = is_linux && !is_bsd # On Android, use plain GTest. - use_base_test_suite = is_linux + use_base_test_suite = is_linux && !is_bsd } if (is_nacl_nonsfi) { @@ -379,7 +379,7 @@ component("sandbox_services") { public_deps += [ ":sandbox_services_headers" ] } - if (is_nacl_nonsfi) { + if (is_nacl_nonsfi || is_bsd) { cflags = [ "-fgnu-inline-asm" ] sources -= [ @@ -387,6 +387,8 @@ component("sandbox_services") { "services/init_process_reaper.h", "services/scoped_process.cc", "services/scoped_process.h", + "services/syscall_wrappers.cc", + "services/syscall_wrappers.h", "services/yama.cc", "services/yama.h", "syscall_broker/broker_channel.cc", @@ -405,6 +407,10 @@ component("sandbox_services") { "syscall_broker/broker_process.h", "syscall_broker/broker_simple_message.cc", "syscall_broker/broker_simple_message.h", + ] + sources += [ + "services/libc_interceptor.cc", + "services/libc_interceptor.h", ] } else if (!is_android) { sources += [
{ "pile_set_name": "Github" }
.theme-dusk,.theme-midnight { .hljs { display: block; overflow-x: auto; background: #232323; color: #e6e1dc; } .hljs-comment, .hljs-quote { color: #bc9458; font-style: italic; } .hljs-keyword, .hljs-selector-tag { color: #c26230; } .hljs-string, .hljs-number, .hljs-regexp, .hljs-variable, .hljs-template-variable { color: #a5c261; } .hljs-subst { color: #519f50; } .hljs-tag, .hljs-name { color: #e8bf6a; } .hljs-type { color: #da4939; } .hljs-symbol, .hljs-bullet, .hljs-built_in, .hljs-builtin-name, .hljs-attr, .hljs-link { color: #6d9cbe; } .hljs-params { color: #d0d0ff; } .hljs-attribute { color: #cda869; } .hljs-meta { color: #9b859d; } .hljs-title, .hljs-section { color: #ffc66d; } .hljs-addition { background-color: #144212; color: #e6e1dc; display: inline-block; width: 100%; } .hljs-deletion { background-color: #600; color: #e6e1dc; display: inline-block; width: 100%; } .hljs-selector-class { color: #9b703f; } .hljs-selector-id { color: #8b98ab; } .hljs-emphasis { font-style: italic; } .hljs-strong { font-weight: bold; } .hljs-link { text-decoration: underline; } }
{ "pile_set_name": "Github" }
#ifndef CREATE_EMPTY_DIRECTED_GRAPH_WITH_GRAPH_NAME_H #define CREATE_EMPTY_DIRECTED_GRAPH_WITH_GRAPH_NAME_H #include <boost/graph/adjacency_list.hpp> boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, boost::no_property, boost::property<boost::graph_name_t, std::string>> create_empty_directed_graph_with_graph_name() noexcept; #endif // CREATE_EMPTY_DIRECTED_GRAPH_WITH_GRAPH_NAME_H
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.stanbol.entityhub.web.reader; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.apache.clerezza.commons.rdf.Graph; import org.apache.clerezza.commons.rdf.BlankNodeOrIRI; import org.apache.clerezza.commons.rdf.Triple; import org.apache.clerezza.commons.rdf.IRI; import org.apache.clerezza.rdf.core.serializedform.Parser; import org.apache.clerezza.rdf.core.serializedform.SupportedFormat; import org.apache.clerezza.rdf.core.serializedform.UnsupportedParsingFormatException; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.stanbol.commons.indexedgraph.IndexedGraph; import org.apache.stanbol.entityhub.jersey.utils.JerseyUtils; import org.apache.stanbol.entityhub.jersey.utils.MessageBodyReaderUtils; import org.apache.stanbol.entityhub.jersey.utils.MessageBodyReaderUtils.RequestData; import org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory; import org.apache.stanbol.entityhub.servicesapi.model.Representation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides support for reading Representation form Requests. This implementation * supports all RDF supports as well as {@link MediaType#APPLICATION_FORM_URLENCODED} * - in case the data are sent from an HTML form - and * {@link MediaType#MULTIPART_FORM_DATA} - mime encoded data. * In case of an HTML form the encoding need to be specified by the parameter * "encoding" for the entity data the parameters "entity" or "content" can be * used. * @author Rupert Westenthaler * */ @Component @Service(Object.class) @Property(name="javax.ws.rs", boolValue=true) @Provider @Consumes({ //First the data types directly supported for parsing representations MediaType.APPLICATION_JSON, SupportedFormat.N3, SupportedFormat.N_TRIPLE, SupportedFormat.RDF_XML, SupportedFormat.TURTLE, SupportedFormat.X_TURTLE, SupportedFormat.RDF_JSON, //finally this also supports sending the data as form and mime multipart MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA}) public class RepresentationReader implements MessageBodyReader<Map<String,Representation>> { private static final Logger log = LoggerFactory.getLogger(RepresentationReader.class); public static final Set<String> supportedMediaTypes; private static final MediaType DEFAULT_ACCEPTED_MEDIA_TYPE = MediaType.TEXT_PLAIN_TYPE; static { Set<String> types = new HashSet<String>(); //ensure everything is lower case types.add(MediaType.APPLICATION_JSON.toLowerCase()); types.add(SupportedFormat.N3.toLowerCase()); types.add(SupportedFormat.N_TRIPLE.toLowerCase()); types.add(SupportedFormat.RDF_JSON.toLowerCase()); types.add(SupportedFormat.RDF_XML.toLowerCase()); types.add(SupportedFormat.TURTLE.toLowerCase()); types.add(SupportedFormat.X_TURTLE.toLowerCase()); supportedMediaTypes = Collections.unmodifiableSet(types); } @Reference private Parser parser; @Override public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { String mediaTypeWithoutParameter = mediaType.getType().toLowerCase()+'/'+ mediaType.getSubtype().toLowerCase(); log.debug("isreadable: [genericType: {}| mediaType {}]", genericType,mediaTypeWithoutParameter); //second the media type boolean mediaTypeOK = (//the MimeTypes of Representations supportedMediaTypes.contains(mediaTypeWithoutParameter) || //as well as URL encoded MediaType.APPLICATION_FORM_URLENCODED.equals(mediaTypeWithoutParameter) || //and mime multipart MediaType.MULTIPART_FORM_DATA.equals(mediaTypeWithoutParameter)); boolean typeOk = JerseyUtils.testParameterizedType(Map.class, new Class[]{String.class,Representation.class}, genericType); log.debug("type is {} for {} against Map<String,Representation>", typeOk ? "compatible" : "incompatible" ,genericType); return typeOk && mediaTypeOK; } @Override public Map<String,Representation> readFrom(Class<Map<String,Representation>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { log.info("Read Representations from Request Data"); long start = System.currentTimeMillis(); //(1) get the charset and the acceptedMediaType String charset = "UTF-8"; if(mediaType.getParameters().containsKey("charset")){ charset = mediaType.getParameters().get("charset"); } MediaType acceptedMediaType = getAcceptedMediaType(httpHeaders); log.info("readFrom: mediaType {} | accepted {} | charset {}", new Object[]{mediaType,acceptedMediaType,charset}); // (2) read the Content from the request (this needs to deal with // MediaType.APPLICATION_FORM_URLENCODED_TYPE and // MediaType.MULTIPART_FORM_DATA_TYPE requests! RequestData content; if(mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) { try { content = MessageBodyReaderUtils.formForm(entityStream, charset, "encoding",Arrays.asList("entity","content")); } catch (IllegalArgumentException e) { log.info("Bad Request: {}",e); throw new WebApplicationException( Response.status(Status.BAD_REQUEST).entity(e.toString()). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } if(content.getMediaType() == null){ String message = String.format( "Missing parameter %s used to specify the media type" + "(supported values: %s", "encoding",supportedMediaTypes); log.info("Bad Request: {}",message); throw new WebApplicationException( Response.status(Status.BAD_REQUEST).entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } if(!isSupported(content.getMediaType())){ String message = String.format( "Unsupported Content-Type specified by parameter " + "encoding=%s (supported: %s)", content.getMediaType().toString(),supportedMediaTypes); log.info("Bad Request: {}",message); throw new WebApplicationException( Response.status(Status.BAD_REQUEST). entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } } else if(mediaType.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)){ log.info("read from MimeMultipart"); List<RequestData> contents; try { contents = MessageBodyReaderUtils.fromMultipart(entityStream, mediaType); } catch (IllegalArgumentException e) { log.info("Bad Request: {}",e.toString()); throw new WebApplicationException( Response.status(Status.BAD_REQUEST).entity(e.toString()). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } if(contents.isEmpty()){ String message = "Request does not contain any Mime BodyParts."; log.info("Bad Request: {}",message); throw new WebApplicationException( Response.status(Status.BAD_REQUEST).entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } else if(contents.size()>1){ //print warnings about ignored parts log.warn("{} Request contains more than one Parts: others than " + "the first will be ignored", MediaType.MULTIPART_FORM_DATA_TYPE); for(int i=1;i<contents.size();i++){ RequestData ignored = contents.get(i); log.warn(" ignore Content {}: Name {}| MediaType {}", new Object[] {i+1,ignored.getName(),ignored.getMediaType()}); } } content = contents.get(0); if(content.getMediaType() == null){ String message = String.format( "MediaType not specified for mime body part for file %s. " + "The media type must be one of the supported values: %s", content.getName(), supportedMediaTypes); log.info("Bad Request: {}",message); throw new WebApplicationException( Response.status(Status.BAD_REQUEST).entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } if(!isSupported(content.getMediaType())){ String message = String.format( "Unsupported Content-Type %s specified for mime body part " + "for file %s (supported: %s)", content.getMediaType(),content.getName(),supportedMediaTypes); log.info("Bad Request: {}",message); throw new WebApplicationException( Response.status(Status.BAD_REQUEST). entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } } else { content = new RequestData(mediaType, null, entityStream); } long readingCompleted = System.currentTimeMillis(); log.info(" ... reading request data {}ms",readingCompleted-start); Map<String,Representation> parsed = parseFromContent(content,acceptedMediaType); long parsingCompleted = System.currentTimeMillis(); log.info(" ... parsing data {}ms",parsingCompleted-readingCompleted); return parsed; } public Map<String,Representation> parseFromContent(RequestData content, MediaType acceptedMediaType){ // (3) Parse the Representtion(s) form the entity stream if(content.getMediaType().isCompatible(MediaType.APPLICATION_JSON_TYPE)){ //parse from json throw new UnsupportedOperationException("Parsing of JSON not yet implemented :("); } else if(isSupported(content.getMediaType())){ //from RDF serialisation RdfValueFactory valueFactory = RdfValueFactory.getInstance(); Map<String,Representation> representations = new HashMap<String,Representation>(); Set<BlankNodeOrIRI> processed = new HashSet<BlankNodeOrIRI>(); Graph graph = new IndexedGraph(); try { parser.parse(graph,content.getEntityStream(), content.getMediaType().toString()); } catch (UnsupportedParsingFormatException e) { //String acceptedMediaType = httpHeaders.getFirst("Accept"); //throw an internal server Error, because we check in //isReadable(..) for supported types and still we get here a //unsupported format -> therefore it looks like an configuration //error the server (e.g. a missing Bundle with the required bundle) String message = "Unable to create the Parser for the supported format" +content.getMediaType()+" ("+e+")"; log.error(message,e); throw new WebApplicationException( Response.status(Status.INTERNAL_SERVER_ERROR). entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } catch (RuntimeException e){ //NOTE: Clerezza seams not to provide specific exceptions on // parsing errors. Hence the catch for all RuntimeException String message = "Unable to parse the provided RDF data (format: " +content.getMediaType()+", message: "+e.getMessage()+")"; log.error(message,e); throw new WebApplicationException( Response.status(Status.BAD_REQUEST). entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } for(Iterator<Triple> st = graph.iterator();st.hasNext();){ BlankNodeOrIRI resource = st.next().getSubject(); if(resource instanceof IRI && processed.add(resource)){ //build a new representation representations.put(((IRI)resource).getUnicodeString(), valueFactory.createRdfRepresentation((IRI)resource, graph)); } } return representations; } else { //unsupported media type String message = String.format( "Parsed Content-Type '%s' is not one of the supported %s", content.getMediaType(),supportedMediaTypes); log.info("Bad Request: {}",message); throw new WebApplicationException( Response.status(Status.BAD_REQUEST). entity(message). header(HttpHeaders.ACCEPT, acceptedMediaType).build()); } } /** * Internally used to get the accepted media type used when returning * {@link WebApplicationException}s. * @param httpHeaders * @param acceptedMediaType * @return */ private static MediaType getAcceptedMediaType(MultivaluedMap<String,String> httpHeaders) { MediaType acceptedMediaType; String acceptedMediaTypeString = httpHeaders.getFirst("Accept"); if(acceptedMediaTypeString != null){ try { acceptedMediaType = MediaType.valueOf(acceptedMediaTypeString); if(acceptedMediaType.isWildcardType()){ acceptedMediaType = DEFAULT_ACCEPTED_MEDIA_TYPE; } } catch (IllegalArgumentException e) { acceptedMediaType = DEFAULT_ACCEPTED_MEDIA_TYPE; } } else { acceptedMediaType = DEFAULT_ACCEPTED_MEDIA_TYPE; } return acceptedMediaType; } /** * Converts the type and the subtype of the parsed media type to the * string representation as stored in {@link #supportedMediaTypes} and than * checks if the parsed media type is contained in this list. * @param mediaType the MediaType instance to check * @return <code>true</code> if the parsed media type is not * <code>null</code> and supported. */ private boolean isSupported(MediaType mediaType){ return mediaType == null ? false : supportedMediaTypes.contains( mediaType.getType().toLowerCase()+'/'+ mediaType.getSubtype().toLowerCase()); } }
{ "pile_set_name": "Github" }
#if !defined(BOOST_PP_IS_ITERATING) ///// header body #ifndef BOOST_MPL_AUX778076_ADVANCE_BACKWARD_HPP_INCLUDED #define BOOST_MPL_AUX778076_ADVANCE_BACKWARD_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/prior.hpp> # include <boost/mpl/apply_wrap.hpp> #endif #include <boost/mpl/aux_/config/use_preprocessed.hpp> #if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) # define BOOST_MPL_PREPROCESSED_HEADER advance_backward.hpp # include <boost/mpl/aux_/include_preprocessed.hpp> #else # include <boost/mpl/limits/unrolling.hpp> # include <boost/mpl/aux_/nttp_decl.hpp> # include <boost/mpl/aux_/config/eti.hpp> # include <boost/preprocessor/iterate.hpp> # include <boost/preprocessor/cat.hpp> # include <boost/preprocessor/inc.hpp> namespace boost { namespace mpl { namespace aux { // forward declaration template< BOOST_MPL_AUX_NTTP_DECL(long, N) > struct advance_backward; # define BOOST_PP_ITERATION_PARAMS_1 \ (3,(0, BOOST_MPL_LIMIT_UNROLLING, <boost/mpl/aux_/advance_backward.hpp>)) # include BOOST_PP_ITERATE() // implementation for N that exceeds BOOST_MPL_LIMIT_UNROLLING template< BOOST_MPL_AUX_NTTP_DECL(long, N) > struct advance_backward { template< typename Iterator > struct apply { typedef typename apply_wrap1< advance_backward<BOOST_MPL_LIMIT_UNROLLING> , Iterator >::type chunk_result_; typedef typename apply_wrap1< advance_backward<( (N - BOOST_MPL_LIMIT_UNROLLING) < 0 ? 0 : N - BOOST_MPL_LIMIT_UNROLLING )> , chunk_result_ >::type type; }; }; }}} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // BOOST_MPL_AUX778076_ADVANCE_BACKWARD_HPP_INCLUDED ///// iteration, depth == 1 // For gcc 4.4 compatability, we must include the // BOOST_PP_ITERATION_DEPTH test inside an #else clause. #else // BOOST_PP_IS_ITERATING #if BOOST_PP_ITERATION_DEPTH() == 1 #define i_ BOOST_PP_FRAME_ITERATION(1) template<> struct advance_backward< BOOST_PP_FRAME_ITERATION(1) > { template< typename Iterator > struct apply { typedef Iterator iter0; #if i_ > 0 # define BOOST_PP_ITERATION_PARAMS_2 \ (3,(1, BOOST_PP_FRAME_ITERATION(1), <boost/mpl/aux_/advance_backward.hpp>)) # include BOOST_PP_ITERATE() #endif typedef BOOST_PP_CAT(iter,BOOST_PP_FRAME_ITERATION(1)) type; }; #if defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG) /// ETI workaround template<> struct apply<int> { typedef int type; }; #endif }; #undef i_ ///// iteration, depth == 2 #elif BOOST_PP_ITERATION_DEPTH() == 2 # define AUX778076_ITER_0 BOOST_PP_CAT(iter,BOOST_PP_DEC(BOOST_PP_FRAME_ITERATION(2))) # define AUX778076_ITER_1 BOOST_PP_CAT(iter,BOOST_PP_FRAME_ITERATION(2)) typedef typename prior<AUX778076_ITER_0>::type AUX778076_ITER_1; # undef AUX778076_ITER_1 # undef AUX778076_ITER_0 #endif // BOOST_PP_ITERATION_DEPTH() #endif // BOOST_PP_IS_ITERATING
{ "pile_set_name": "Github" }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.impl import com.intellij.ProjectTopics import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsDirectoryMapping import com.intellij.openapi.vfs.VirtualFile internal class ModuleVcsDetector(private val project: Project) { private val vcsManager by lazy(LazyThreadSafetyMode.NONE) { (ProjectLevelVcsManager.getInstance(project) as ProjectLevelVcsManagerImpl) } internal class MyPostStartUpActivity : StartupActivity.DumbAware { init { if (ApplicationManager.getApplication().isUnitTestMode) { throw ExtensionNotApplicableException.INSTANCE } } override fun runActivity(project: Project) { val vcsDetector = project.service<ModuleVcsDetector>() val listener = vcsDetector.MyModulesListener() val busConnection = project.messageBus.connect() busConnection.subscribe(ProjectTopics.MODULES, listener) busConnection.subscribe(ProjectTopics.PROJECT_ROOTS, listener) if (vcsDetector.vcsManager.needAutodetectMappings()) { vcsDetector.autoDetectVcsMappings(true) } } } private inner class MyModulesListener : ModuleRootListener, ModuleListener { private val myMappingsForRemovedModules: MutableList<VcsDirectoryMapping> = mutableListOf() override fun beforeRootsChange(event: ModuleRootEvent) { myMappingsForRemovedModules.clear() } override fun rootsChanged(event: ModuleRootEvent) { myMappingsForRemovedModules.forEach { mapping -> vcsManager.removeDirectoryMapping(mapping) } // the check calculates to true only before user has done any change to mappings, i.e. in case modules are detected/added automatically // on start etc (look inside) if (vcsManager.needAutodetectMappings()) { autoDetectVcsMappings(false) } } override fun moduleAdded(project: Project, module: Module) { myMappingsForRemovedModules.removeAll(getMappings(module)) autoDetectModuleVcsMapping(module) } override fun beforeModuleRemoved(project: Project, module: Module) { myMappingsForRemovedModules.addAll(getMappings(module)) } } private fun autoDetectVcsMappings(tryMapPieces: Boolean) { if (vcsManager.haveDefaultMapping() != null) return val usedVcses = mutableSetOf<AbstractVcs?>() val detectedRoots = mutableSetOf<Pair<VirtualFile, AbstractVcs>>() val roots = ModuleManager.getInstance(project).modules.flatMap { it.rootManager.contentRoots.asIterable() }.distinct() for (root in roots) { val moduleVcs = vcsManager.findVersioningVcs(root) if (moduleVcs != null) { detectedRoots.add(Pair(root, moduleVcs)) } usedVcses.add(moduleVcs) // put 'null' for unmapped module } val commonVcs = usedVcses.singleOrNull() if (commonVcs != null) { // Remove existing mappings that will duplicate added <Project> mapping. val rootPaths = roots.map { it.path }.toSet() val additionalMappings = vcsManager.directoryMappings.filter { it.directory !in rootPaths } vcsManager.setAutoDirectoryMappings(additionalMappings + VcsDirectoryMapping.createDefault(commonVcs.name)) } else if (tryMapPieces) { val newMappings = detectedRoots.map { (root, vcs) -> VcsDirectoryMapping(root.path, vcs.name) } vcsManager.setAutoDirectoryMappings(vcsManager.directoryMappings + newMappings) } } private fun autoDetectModuleVcsMapping(module: Module) { if (vcsManager.haveDefaultMapping() != null) return val newMappings = mutableListOf<VcsDirectoryMapping>() for (file in module.rootManager.contentRoots) { val vcs = vcsManager.findVersioningVcs(file) if (vcs != null && vcs !== vcsManager.getVcsFor(file)) { newMappings.add(VcsDirectoryMapping(file.path, vcs.name)) } } if (newMappings.isNotEmpty()) { vcsManager.setAutoDirectoryMappings(vcsManager.directoryMappings + newMappings) } } private fun getMappings(module: Module): List<VcsDirectoryMapping> { return module.rootManager.contentRoots .mapNotNull { root -> vcsManager.directoryMappings.firstOrNull { it.directory == root.path } } } }
{ "pile_set_name": "Github" }
package io.gitlab.arturbosch.detekt.generator.collection import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.generator.collection.exception.InvalidDocumentationException import io.gitlab.arturbosch.detekt.rules.isOverride import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.psi.KtSuperTypeList import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.referenceExpression data class MultiRule( val name: String, val rules: List<String> = listOf() ) { operator fun contains(ruleName: String) = ruleName in this.rules } private val multiRule = io.gitlab.arturbosch.detekt.api.MultiRule::class.simpleName ?: "" class MultiRuleCollector : Collector<MultiRule> { override val items = mutableListOf<MultiRule>() override fun visit(file: KtFile) { val visitor = MultiRuleVisitor() file.accept(visitor) if (visitor.containsMultiRule) { items.add(visitor.getMultiRule()) } } } class MultiRuleVisitor : DetektVisitor() { val containsMultiRule get() = classesMap.any { it.value } private var classesMap = mutableMapOf<String, Boolean>() private var name = "" private val rulesVisitor = RuleListVisitor() private val properties: MutableMap<String, String> = mutableMapOf() fun getMultiRule(): MultiRule { val rules = mutableListOf<String>() val ruleProperties = rulesVisitor.ruleProperties .mapNotNull { properties[it] } rules.addAll(ruleProperties) rules.addAll(rulesVisitor.ruleNames) if (name.isEmpty()) { throw InvalidDocumentationException("MultiRule without name found.") } if (rules.isEmpty()) { throw InvalidDocumentationException("MultiRule $name contains no rules.") } return MultiRule(name, rules) } override fun visitSuperTypeList(list: KtSuperTypeList) { val isMultiRule = list.entries ?.mapNotNull { it.typeAsUserType?.referencedName } ?.any { it == multiRule } ?: false val containingClass = list.containingClass() val className = containingClass?.name if (containingClass != null && className != null && !classesMap.containsKey(className)) { classesMap[className] = isMultiRule } super.visitSuperTypeList(list) } override fun visitClassOrObject(classOrObject: KtClassOrObject) { super.visitClassOrObject(classOrObject) if (classesMap[classOrObject.name] != true) { return } name = classOrObject.name?.trim() ?: "" } override fun visitProperty(property: KtProperty) { super.visitProperty(property) if (classesMap[property.containingClass()?.name] != true) { return } if (property.isOverride() && property.name != null && property.name == "rules") { property.accept(rulesVisitor) } else { val name = property.name val initializer = property.initializer?.referenceExpression()?.text if (name != null && initializer != null) { properties[name] = initializer } } } } class RuleListVisitor : DetektVisitor() { var ruleNames: MutableSet<String> = mutableSetOf() private set var ruleProperties: MutableSet<String> = mutableSetOf() private set override fun visitValueArgumentList(list: KtValueArgumentList) { super.visitValueArgumentList(list) val argumentExpressions = list.arguments.map { it.getArgumentExpression() } // Call Expression = Constructor of rule ruleNames.addAll(argumentExpressions .filterIsInstance<KtCallExpression>() .map { it.calleeExpression?.text ?: "" }) // Reference Expression = variable we need to search for ruleProperties.addAll(argumentExpressions .filterIsInstance<KtReferenceExpression>() .map { it.text ?: "" }) } }
{ "pile_set_name": "Github" }
package tk.woppo.sunday.model; import android.database.Cursor; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import java.util.HashMap; import tk.woppo.sunday.dao.WeatherDataHelper; import tk.woppo.sunday.dao.WeatherTodayDataHelper; /** * Created by Ho on 2014/7/4. */ public class WeatherTodayModel extends BaseModel { private static final HashMap<String, WeatherTodayModel> CACHE = new HashMap<String, WeatherTodayModel>(); /** 城市ID */ @SerializedName("cityid") public String id; /** 城市名称 */ @SerializedName("city") public String cityName; /** 温度 */ public String temp; /** 天气 */ public String weather; /** 风向 */ @SerializedName("WD") public String wind; /** 风力 */ @SerializedName("WS") public String ws; /** 湿度 */ @SerializedName("SD") public String sd; /** 发布时间 */ public String time; private static void addToCache(WeatherTodayModel model) { CACHE.put(model.id, model); } private static WeatherTodayModel getFromCache(String id) { return CACHE.get(id); } public static WeatherTodayModel fromJson(String json) { return new Gson().fromJson(json, WeatherTodayModel.class); } public static WeatherTodayModel fromCursor(Cursor cursor) { String id = cursor.getString(cursor.getColumnIndex(WeatherDataHelper.WeatherDBInfo.ID)); WeatherTodayModel model = getFromCache(id); if (model != null) { return model; } model = new Gson().fromJson(cursor.getString(cursor.getColumnIndex(WeatherTodayDataHelper.WeatherTodayDBInfo.JSON)), WeatherTodayModel.class); addToCache(model); return model; } public static class WeatherTodayRequestData { public WeatherTodayModel weatherinfo; } }
{ "pile_set_name": "Github" }
/* * Copyright 2010-2013 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. */ #import "SimpleDBMissingParameterException.h" @implementation SimpleDBMissingParameterException @synthesize boxUsage; -(id)initWithMessage:(NSString *)theMessage { if (self = [super initWithMessage:theMessage]) { } return self; } -(void)setPropertiesWithException:(AmazonServiceException *)theException { [super setPropertiesWithException:theException]; if ([theException.additionalFields valueForKey:@"BoxUsage"] != nil) { self.boxUsage = [AmazonSDKUtil convertStringToNumber:[theException.additionalFields valueForKey:@"BoxUsage"]]; } } -(NSString *)description { NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256]; [buffer appendString:@"{"]; [buffer appendString:[[[NSString alloc] initWithFormat:@"BoxUsage: %@,", boxUsage] autorelease]]; [buffer appendString:[super description]]; [buffer appendString:@"}"]; return [buffer autorelease]; } -(void)dealloc { [boxUsage release]; [super dealloc]; } @end
{ "pile_set_name": "Github" }
package network // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) // VpnSitesClient is the network Client type VpnSitesClient struct { BaseClient } // NewVpnSitesClient creates an instance of the VpnSitesClient client. func NewVpnSitesClient(subscriptionID string) VpnSitesClient { return NewVpnSitesClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewVpnSitesClientWithBaseURI creates an instance of the VpnSitesClient client. func NewVpnSitesClientWithBaseURI(baseURI string, subscriptionID string) VpnSitesClient { return VpnSitesClient{NewWithBaseURI(baseURI, subscriptionID)} } // CreateOrUpdate creates a VpnSite resource if it doesn't exist else updates the existing VpnSite. // Parameters: // resourceGroupName - the resource group name of the VpnSite. // vpnSiteName - the name of the VpnSite being created or updated. // vpnSiteParameters - parameters supplied to create or update VpnSite. func (client VpnSitesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VpnSite) (result VpnSitesCreateOrUpdateFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.CreateOrUpdate") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "CreateOrUpdate", nil, "Failure preparing request") return } result, err = client.CreateOrUpdateSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "CreateOrUpdate", result.Response(), "Failure sending request") return } return } // CreateOrUpdatePreparer prepares the CreateOrUpdate request. func (client VpnSitesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters VpnSite) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vpnSiteName": autorest.Encode("path", vpnSiteName), } const APIVersion = "2018-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPut(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), autorest.WithJSON(vpnSiteParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the // http.Response Body if it receives an error. func (client VpnSitesClient) CreateOrUpdateSender(req *http.Request) (future VpnSitesCreateOrUpdateFuture, err error) { var resp *http.Response resp, err = autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always // closes the http.Response Body. func (client VpnSitesClient) CreateOrUpdateResponder(resp *http.Response) (result VpnSite, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // Delete deletes a VpnSite. // Parameters: // resourceGroupName - the resource group name of the VpnSite. // vpnSiteName - the name of the VpnSite being deleted. func (client VpnSitesClient) Delete(ctx context.Context, resourceGroupName string, vpnSiteName string) (result VpnSitesDeleteFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.Delete") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.DeletePreparer(ctx, resourceGroupName, vpnSiteName) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Delete", nil, "Failure preparing request") return } result, err = client.DeleteSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Delete", result.Response(), "Failure sending request") return } return } // DeletePreparer prepares the Delete request. func (client VpnSitesClient) DeletePreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vpnSiteName": autorest.Encode("path", vpnSiteName), } const APIVersion = "2018-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsDelete(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // DeleteSender sends the Delete request. The method will close the // http.Response Body if it receives an error. func (client VpnSitesClient) DeleteSender(req *http.Request) (future VpnSitesDeleteFuture, err error) { var resp *http.Response resp, err = autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // DeleteResponder handles the response to the Delete request. The method always // closes the http.Response Body. func (client VpnSitesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), autorest.ByClosing()) result.Response = resp return } // Get retrieves the details of a VPNsite. // Parameters: // resourceGroupName - the resource group name of the VpnSite. // vpnSiteName - the name of the VpnSite being retrieved. func (client VpnSitesClient) Get(ctx context.Context, resourceGroupName string, vpnSiteName string) (result VpnSite, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.GetPreparer(ctx, resourceGroupName, vpnSiteName) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client VpnSitesClient) GetPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vpnSiteName": autorest.Encode("path", vpnSiteName), } const APIVersion = "2018-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client VpnSitesClient) GetSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client VpnSitesClient) GetResponder(resp *http.Response) (result VpnSite, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List lists all the VpnSites in a subscription. func (client VpnSitesClient) List(ctx context.Context) (result ListVpnSitesResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.List") defer func() { sc := -1 if result.lvsr.Response.Response != nil { sc = result.lvsr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listNextResults req, err := client.ListPreparer(ctx) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.lvsr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", resp, "Failure sending request") return } result.lvsr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client VpnSitesClient) ListPreparer(ctx context.Context) (*http.Request, error) { pathParameters := map[string]interface{}{ "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2018-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnSites", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client VpnSitesClient) ListSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client VpnSitesClient) ListResponder(resp *http.Response) (result ListVpnSitesResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client VpnSitesClient) listNextResults(ctx context.Context, lastResults ListVpnSitesResult) (result ListVpnSitesResult, err error) { req, err := lastResults.listVpnSitesResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client VpnSitesClient) ListComplete(ctx context.Context) (result ListVpnSitesResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx) return } // ListByResourceGroup lists all the vpnSites in a resource group. // Parameters: // resourceGroupName - the resource group name of the VpnSite. func (client VpnSitesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ListVpnSitesResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.ListByResourceGroup") defer func() { sc := -1 if result.lvsr.Response.Response != nil { sc = result.lvsr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.fn = client.listByResourceGroupNextResults req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", nil, "Failure preparing request") return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.lvsr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", resp, "Failure sending request") return } result.lvsr, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "ListByResourceGroup", resp, "Failure responding to request") } return } // ListByResourceGroupPreparer prepares the ListByResourceGroup request. func (client VpnSitesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2018-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the // http.Response Body if it receives an error. func (client VpnSitesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { return autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) } // ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always // closes the http.Response Body. func (client VpnSitesClient) ListByResourceGroupResponder(resp *http.Response) (result ListVpnSitesResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByResourceGroupNextResults retrieves the next set of results, if any. func (client VpnSitesClient) listByResourceGroupNextResults(ctx context.Context, lastResults ListVpnSitesResult) (result ListVpnSitesResult, err error) { req, err := lastResults.listVpnSitesResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByResourceGroupSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") } result, err = client.ListByResourceGroupResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") } return } // ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. func (client VpnSitesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ListVpnSitesResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.ListByResourceGroup") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) return } // UpdateTags updates VpnSite tags. // Parameters: // resourceGroupName - the resource group name of the VpnSite. // vpnSiteName - the name of the VpnSite being updated. // vpnSiteParameters - parameters supplied to update VpnSite tags. func (client VpnSitesClient) UpdateTags(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject) (result VpnSitesUpdateTagsFuture, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VpnSitesClient.UpdateTags") defer func() { sc := -1 if result.Response() != nil { sc = result.Response().StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, vpnSiteName, vpnSiteParameters) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", nil, "Failure preparing request") return } result, err = client.UpdateTagsSender(req) if err != nil { err = autorest.NewErrorWithError(err, "network.VpnSitesClient", "UpdateTags", result.Response(), "Failure sending request") return } return } // UpdateTagsPreparer prepares the UpdateTags request. func (client VpnSitesClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, vpnSiteName string, vpnSiteParameters TagsObject) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "vpnSiteName": autorest.Encode("path", vpnSiteName), } const APIVersion = "2018-10-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsContentType("application/json; charset=utf-8"), autorest.AsPatch(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}", pathParameters), autorest.WithJSON(vpnSiteParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // UpdateTagsSender sends the UpdateTags request. The method will close the // http.Response Body if it receives an error. func (client VpnSitesClient) UpdateTagsSender(req *http.Request) (future VpnSitesUpdateTagsFuture, err error) { var resp *http.Response resp, err = autorest.SendWithSender(client, req, azure.DoRetryWithRegistration(client.Client)) if err != nil { return } future.Future, err = azure.NewFutureFromResponse(resp) return } // UpdateTagsResponder handles the response to the UpdateTags request. The method always // closes the http.Response Body. func (client VpnSitesClient) UpdateTagsResponder(resp *http.Response) (result VpnSite, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "pile_set_name": "Github" }
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "Dinda", "Dilolo" ], "DAY": [ "Lumingu", "Nkodya", "Nd\u00e0ay\u00e0", "Ndang\u00f9", "Nj\u00f2wa", "Ng\u00f2vya", "Lubingu" ], "MONTH": [ "Ciongo", "L\u00f9ishi", "Lus\u00f2lo", "M\u00f9uy\u00e0", "Lum\u00f9ng\u00f9l\u00f9", "Lufuimi", "Kab\u00e0l\u00e0sh\u00ecp\u00f9", "L\u00f9sh\u00eck\u00e0", "Lutongolo", "Lung\u00f9di", "Kasw\u00e8k\u00e8s\u00e8", "Cisw\u00e0" ], "SHORTDAY": [ "Lum", "Nko", "Ndy", "Ndg", "Njw", "Ngv", "Lub" ], "SHORTMONTH": [ "Cio", "Lui", "Lus", "Muu", "Lum", "Luf", "Kab", "Lush", "Lut", "Lun", "Kas", "Cis" ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "d/M/y HH:mm", "shortDate": "d/M/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "FrCD", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "lu-cd", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
package com.android.inputmethodcommon; class InputMethodSettingsInterface { } class InputMethodSettingsImpl { int mContext; int mImi; int mImm; int mSubtypeEnablerIcon; int mSubtypeEnablerIconRes; int mSubtypeEnablerTitle; int mSubtypeEnablerTitleRes; int mInputMethodSettingsCategoryTitle; int mInputMethodSettingsCategoryTitleRes; int mSubtypeEnablerPreference; } class InputMethodSettingsFragment { int mSettings; } class InputMethodSettingsActivity { int mSettings; }
{ "pile_set_name": "Github" }
/*####################################################### * Copyright (c) 2014 Jeff Martin * Copyright (c) 2015 Pedro Lafuente * Copyright (c) 2017-2019 Gregor Santner * * Licensed under the MIT license. * You can get a copy of the license text here: * https://opensource.org/licenses/MIT ###########################################################*/ package other.writeily.ui; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import net.gsantner.markor.R; import net.gsantner.markor.util.AppSettings; import java.io.Serializable; public class WrConfirmDialog extends DialogFragment { public static final String FRAGMENT_TAG = "WrConfirmDialog"; private static final String EXTRA_TITLE = "EXTRA_TITLE"; private static final String EXTRA_MESSAGE = "EXTRA_MESSAGE"; public static final String EXTRA_DATA = "EXTRA_DATA"; private Serializable _data; private ConfirmDialogCallback[] _callbacks; private String _summary; public static WrConfirmDialog newInstance(String title, String message, Serializable data, ConfirmDialogCallback... callbacks) { WrConfirmDialog confirmDialog = new WrConfirmDialog(); Bundle args = new Bundle(); args.putSerializable(EXTRA_DATA, data); args.putString(EXTRA_TITLE, title); args.putString(EXTRA_MESSAGE, message); confirmDialog.setArguments(args); confirmDialog.setCallbacks(callbacks); return confirmDialog; } public void setCallbacks(ConfirmDialogCallback[] callbacks) { _callbacks = callbacks; } @Override @NonNull public Dialog onCreateDialog(Bundle savedInstanceState) { String title = getArguments().getString(EXTRA_TITLE); String message = getArguments().getString(EXTRA_MESSAGE); _data = getArguments().getSerializable(EXTRA_DATA); AlertDialog.Builder dialogBuilder; boolean darkTheme = AppSettings.get().isDarkThemeEnabled(); dialogBuilder = new AlertDialog.Builder(getActivity(), darkTheme ? R.style.Theme_AppCompat_Dialog : R.style.Theme_AppCompat_Light_Dialog); dialogBuilder.setTitle(title); if (!TextUtils.isEmpty(message)) { dialogBuilder.setMessage(message); } dialogBuilder.setPositiveButton(getString(android.R.string.ok), (dialog, which) -> { if (_callbacks != null) { for (ConfirmDialogCallback cdc : _callbacks) { if (cdc != null) { cdc.onConfirmDialogAnswer(true, _data); } } } }); dialogBuilder.setNegativeButton(getString(R.string.cancel), (dialog, which) -> { dialog.dismiss(); for (ConfirmDialogCallback cdc : _callbacks) { cdc.onConfirmDialogAnswer(false, _data); } }); return dialogBuilder.show(); } public interface ConfirmDialogCallback { void onConfirmDialogAnswer(boolean confirmed, Serializable data); } }
{ "pile_set_name": "Github" }
// Copyright 2004-present Facebook. All Rights Reserved. #include "SamplingProfilerJniMethod.h" #include <JavaScriptCore/JSProfilerPrivate.h> #include <jschelpers/JSCHelpers.h> #include <jni.h> #include <string> using namespace facebook::jni; namespace facebook { namespace react { /* static */ jni::local_ref<SamplingProfilerJniMethod::jhybriddata> SamplingProfilerJniMethod::initHybrid(jni::alias_ref<jclass>, jlong javaScriptContext) { return makeCxxInstance(javaScriptContext); } /* static */ void SamplingProfilerJniMethod::registerNatives() { registerHybrid( {makeNativeMethod("initHybrid", SamplingProfilerJniMethod::initHybrid), makeNativeMethod("poke", SamplingProfilerJniMethod::poke)}); } SamplingProfilerJniMethod::SamplingProfilerJniMethod(jlong javaScriptContext) { context_ = reinterpret_cast<JSGlobalContextRef>(javaScriptContext); } void SamplingProfilerJniMethod::poke( jni::alias_ref<JSPackagerClientResponder::javaobject> responder) { if (!JSC_JSSamplingProfilerEnabled(context_)) { responder->error("The JSSamplingProfiler is disabled. See this " "https://fburl.com/u4lw7xeq for some help"); return; } JSValueRef jsResult = JSC_JSPokeSamplingProfiler(context_); if (JSC_JSValueGetType(context_, jsResult) == kJSTypeNull) { responder->respond("started"); } else { JSStringRef resultStrRef = JSValueToStringCopy(context_, jsResult, nullptr); size_t length = JSStringGetLength(resultStrRef); char buffer[length + 1]; JSStringGetUTF8CString(resultStrRef, buffer, length + 1); JSStringRelease(resultStrRef); responder->respond(buffer); } } } }
{ "pile_set_name": "Github" }
def extractStartlingSurprisesAtEveryStep(item): vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'bu bu jing xin' in item['tags']: return buildReleaseMessageWithType(item, 'Bu Bu Jing Xin', vol, chp, frag=frag, postfix=postfix) return False
{ "pile_set_name": "Github" }
'use strict'; var dbm; var type; var seed; /** * We receive the dbmigrate dependency from dbmigrate initially. * This enables us to not have to rely on NODE_PATH. */ exports.setup = function (options, seedLink) { dbm = options.dbmigrate; type = dbm.dataType; seed = seedLink; }; exports.up = function (db) { return Promise.all([ db.runSql('UPDATE office SET name = \'Office of Brazil and Southern Cone (WHA/BSC)\' where name=\'Office of Brail and Southern Cone (WHA/BSC)\''), db.runSql('UPDATE office SET name = \'U.S. Embassy La Paz\' where name=\'U.S. Embassy LaPaz\''), ]); }; exports.down = function (db) { return Promise.all([ db.runSql('UPDATE office SET name = \'Office of Brail and Southern Cone (WHA/BSC)\' where name=\'Office of Brazil and Southern Cone (WHA/BSC)\''), db.runSql('UPDATE office SET name = \'U.S. Embassy LaPaz\' where name=\'U.S. Embassy La Paz\''), ]); };
{ "pile_set_name": "Github" }
# Copyright 2016 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. mojom = "//url/mojo/url.mojom" public_headers = [ "//url/gurl.h" ] traits_headers = [ "//url/mojo/url_gurl_struct_traits.h" ] deps = [ "//url", ] type_mappings = [ "url.mojom.Url=GURL" ]
{ "pile_set_name": "Github" }
package org.basex.query.func.validate; import org.basex.query.*; import org.basex.query.func.*; import org.basex.query.value.item.*; import org.basex.util.*; /** * Function implementation. * * @author BaseX Team 2005-20, BSD License * @author Christian Gruen */ public final class ValidateXsdProcessor extends StandardFunc { @Override public Item item(final QueryContext qc, final InputInfo ii) { return Str.get(ValidateXsd.IMPL[ValidateXsd.OFFSET + 1]); } }
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -emit-llvm -triple i386-apple-macosx10.7.2 < %s | FileCheck %s // The preferred alignment for a long long on x86-32 is 8; make sure the // alloca for x uses that alignment. int test (long long x) { return (int)x; } // CHECK-LABEL: define i32 @test // CHECK: alloca i64, align 8 // Make sure we honor the aligned attribute. struct X { int x,y,z,a; }; int test2(struct X x __attribute((aligned(16)))) { return x.z; } // CHECK-LABEL: define i32 @test2 // CHECK: alloca %struct._Z1X, align 16
{ "pile_set_name": "Github" }
export const environment = { production: true };
{ "pile_set_name": "Github" }
import { Component, Inject, Input } from '@angular/core'; import { MediaObserver } from '@angular/flex-layout'; import { Observable } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; import { API_BASE_URL } from '../../app.tokens'; import { Product } from '../../shared/services'; @Component({ selector: 'nga-product-suggestion', styleUrls: [ './product-suggestion.component.scss' ], templateUrl: './product-suggestion.component.html' }) export class ProductSuggestionComponent { @Input() products: Product[]; readonly columns$: Observable<number>; readonly breakpointsToColumnsNumber = new Map([ [ 'xs', 2 ], [ 'sm', 3 ], [ 'md', 5 ], [ 'lg', 2 ], [ 'xl', 3 ], ]); constructor( @Inject(API_BASE_URL) private readonly baseUrl: string, private readonly media: MediaObserver ) { // If the initial screen size is xs ObservableMedia doesn't emit an event // In the older versions of flex-layout we used ObservableMedia, which is deprecated. // Use MediaObserver instead this.columns$ = this.media.media$ .pipe( map(mc => <number>this.breakpointsToColumnsNumber.get(mc.mqAlias)), startWith(3) ); } urlFor(product: Product): string { return `${this.baseUrl}/${product.imageUrl}`; } }
{ "pile_set_name": "Github" }
package org.jetbrains.dokka.base.transformers.documentables import org.jetbrains.dokka.model.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.transformers.documentation.PreMergeDocumentableTransformer import org.jetbrains.dokka.transformers.documentation.perPackageOptions import org.jetbrains.dokka.transformers.documentation.source import org.jetbrains.dokka.transformers.documentation.sourceSet import java.io.File class SuppressedDocumentableFilterTransformer(val context: DokkaContext) : PreMergeDocumentableTransformer { override fun invoke(modules: List<DModule>): List<DModule> { return modules.mapNotNull(::filterModule) } private fun filterModule(module: DModule): DModule? { val packages = module.packages.mapNotNull { pkg -> filterPackage(pkg) } return when { packages == module.packages -> module packages.isEmpty() -> null else -> module.copy(packages = packages) } } private fun filterPackage(pkg: DPackage): DPackage? { val options = perPackageOptions(pkg) if (options?.suppress == true) { return null } val filteredChildren = pkg.children.filterNot(::isSuppressed) return when { filteredChildren == pkg.children -> pkg filteredChildren.isEmpty() -> null else -> pkg.copy( functions = filteredChildren.filterIsInstance<DFunction>(), classlikes = filteredChildren.filterIsInstance<DClasslike>(), typealiases = filteredChildren.filterIsInstance<DTypeAlias>(), properties = filteredChildren.filterIsInstance<DProperty>() ) } } private fun isSuppressed(documentable: Documentable): Boolean { if (documentable !is WithSources) return false val sourceFile = File(source(documentable).path).absoluteFile return sourceSet(documentable).suppressedFiles.any { suppressedFile -> sourceFile.startsWith(suppressedFile.absoluteFile) } } }
{ "pile_set_name": "Github" }
if (global.GENTLY) require = GENTLY.hijack(require); var crypto = require('crypto'); var fs = require('fs'); var util = require('util'), path = require('path'), File = require('./file'), MultipartParser = require('./multipart_parser').MultipartParser, QuerystringParser = require('./querystring_parser').QuerystringParser, OctetParser = require('./octet_parser').OctetParser, JSONParser = require('./json_parser').JSONParser, StringDecoder = require('string_decoder').StringDecoder, EventEmitter = require('events').EventEmitter, Stream = require('stream').Stream, os = require('os'); function IncomingForm(opts) { if (!(this instanceof IncomingForm)) return new IncomingForm(opts); EventEmitter.call(this); opts=opts||{}; this.error = null; this.ended = false; this.maxFields = opts.maxFields || 1000; this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024; this.keepExtensions = opts.keepExtensions || false; this.uploadDir = opts.uploadDir || os.tmpDir(); this.encoding = opts.encoding || 'utf-8'; this.headers = null; this.type = null; this.hash = opts.hash || false; this.multiples = opts.multiples || false; this.bytesReceived = null; this.bytesExpected = null; this._parser = null; this._flushing = 0; this._fieldsSize = 0; this.openedFiles = []; return this; } util.inherits(IncomingForm, EventEmitter); exports.IncomingForm = IncomingForm; IncomingForm.prototype.parse = function(req, cb) { this.pause = function() { try { req.pause(); } catch (err) { // the stream was destroyed if (!this.ended) { // before it was completed, crash & burn this._error(err); } return false; } return true; }; this.resume = function() { try { req.resume(); } catch (err) { // the stream was destroyed if (!this.ended) { // before it was completed, crash & burn this._error(err); } return false; } return true; }; // Setup callback first, so we don't miss anything from data events emitted // immediately. if (cb) { var fields = {}, files = {}; this .on('field', function(name, value) { fields[name] = value; }) .on('file', function(name, file) { if (this.multiples) { if (files[name]) { if (!Array.isArray(files[name])) { files[name] = [files[name]]; } files[name].push(file); } else { files[name] = file; } } else { files[name] = file; } }) .on('error', function(err) { cb(err, fields, files); }) .on('end', function() { cb(null, fields, files); }); } // Parse headers and setup the parser, ready to start listening for data. this.writeHeaders(req.headers); // Start listening for data. var self = this; req .on('error', function(err) { self._error(err); }) .on('aborted', function() { self.emit('aborted'); self._error(new Error('Request aborted')); }) .on('data', function(buffer) { self.write(buffer); }) .on('end', function() { if (self.error) { return; } var err = self._parser.end(); if (err) { self._error(err); } }); return this; }; IncomingForm.prototype.writeHeaders = function(headers) { this.headers = headers; this._parseContentLength(); this._parseContentType(); }; IncomingForm.prototype.write = function(buffer) { if (this.error) { return; } if (!this._parser) { this._error(new Error('uninitialized parser')); return; } this.bytesReceived += buffer.length; this.emit('progress', this.bytesReceived, this.bytesExpected); var bytesParsed = this._parser.write(buffer); if (bytesParsed !== buffer.length) { this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); } return bytesParsed; }; IncomingForm.prototype.pause = function() { // this does nothing, unless overwritten in IncomingForm.parse return false; }; IncomingForm.prototype.resume = function() { // this does nothing, unless overwritten in IncomingForm.parse return false; }; IncomingForm.prototype.onPart = function(part) { // this method can be overwritten by the user this.handlePart(part); }; IncomingForm.prototype.handlePart = function(part) { var self = this; if (part.filename === undefined) { var value = '' , decoder = new StringDecoder(this.encoding); part.on('data', function(buffer) { self._fieldsSize += buffer.length; if (self._fieldsSize > self.maxFieldsSize) { self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); return; } value += decoder.write(buffer); }); part.on('end', function() { self.emit('field', part.name, value); }); return; } this._flushing++; var file = new File({ path: this._uploadPath(part.filename), name: part.filename, type: part.mime, hash: self.hash }); this.emit('fileBegin', part.name, file); file.open(); this.openedFiles.push(file); part.on('data', function(buffer) { if (buffer.length == 0) { return; } self.pause(); file.write(buffer, function() { self.resume(); }); }); part.on('end', function() { file.end(function() { self._flushing--; self.emit('file', part.name, file); self._maybeEnd(); }); }); }; function dummyParser(self) { return { end: function () { self.ended = true; self._maybeEnd(); return null; } }; } IncomingForm.prototype._parseContentType = function() { if (this.bytesExpected === 0) { this._parser = dummyParser(this); return; } if (!this.headers['content-type']) { this._error(new Error('bad content-type header, no content-type')); return; } if (this.headers['content-type'].match(/octet-stream/i)) { this._initOctetStream(); return; } if (this.headers['content-type'].match(/urlencoded/i)) { this._initUrlencoded(); return; } if (this.headers['content-type'].match(/multipart/i)) { var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); if (m) { this._initMultipart(m[1] || m[2]); } else { this._error(new Error('bad content-type header, no multipart boundary')); } return; } if (this.headers['content-type'].match(/json/i)) { this._initJSONencoded(); return; } this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); }; IncomingForm.prototype._error = function(err) { if (this.error || this.ended) { return; } this.error = err; this.emit('error', err); if (Array.isArray(this.openedFiles)) { this.openedFiles.forEach(function(file) { file._writeStream.destroy(); setTimeout(fs.unlink, 0, file.path, function(error) { }); }); } }; IncomingForm.prototype._parseContentLength = function() { this.bytesReceived = 0; if (this.headers['content-length']) { this.bytesExpected = parseInt(this.headers['content-length'], 10); } else if (this.headers['transfer-encoding'] === undefined) { this.bytesExpected = 0; } if (this.bytesExpected !== null) { this.emit('progress', this.bytesReceived, this.bytesExpected); } }; IncomingForm.prototype._newParser = function() { return new MultipartParser(); }; IncomingForm.prototype._initMultipart = function(boundary) { this.type = 'multipart'; var parser = new MultipartParser(), self = this, headerField, headerValue, part; parser.initWithBoundary(boundary); parser.onPartBegin = function() { part = new Stream(); part.readable = true; part.headers = {}; part.name = null; part.filename = null; part.mime = null; part.transferEncoding = 'binary'; part.transferBuffer = ''; headerField = ''; headerValue = ''; }; parser.onHeaderField = function(b, start, end) { headerField += b.toString(self.encoding, start, end); }; parser.onHeaderValue = function(b, start, end) { headerValue += b.toString(self.encoding, start, end); }; parser.onHeaderEnd = function() { headerField = headerField.toLowerCase(); part.headers[headerField] = headerValue; var m = headerValue.match(/\bname="([^"]+)"/i); if (headerField == 'content-disposition') { if (m) { part.name = m[1]; } part.filename = self._fileName(headerValue); } else if (headerField == 'content-type') { part.mime = headerValue; } else if (headerField == 'content-transfer-encoding') { part.transferEncoding = headerValue.toLowerCase(); } headerField = ''; headerValue = ''; }; parser.onHeadersEnd = function() { switch(part.transferEncoding){ case 'binary': case '7bit': case '8bit': parser.onPartData = function(b, start, end) { part.emit('data', b.slice(start, end)); }; parser.onPartEnd = function() { part.emit('end'); }; break; case 'base64': parser.onPartData = function(b, start, end) { part.transferBuffer += b.slice(start, end).toString('ascii'); /* four bytes (chars) in base64 converts to three bytes in binary encoding. So we should always work with a number of bytes that can be divided by 4, it will result in a number of buytes that can be divided vy 3. */ var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); part.transferBuffer = part.transferBuffer.substring(offset); }; parser.onPartEnd = function() { part.emit('data', new Buffer(part.transferBuffer, 'base64')); part.emit('end'); }; break; default: return self._error(new Error('unknown transfer-encoding')); } self.onPart(part); }; parser.onEnd = function() { self.ended = true; self._maybeEnd(); }; this._parser = parser; }; IncomingForm.prototype._fileName = function(headerValue) { var m = headerValue.match(/\bfilename="(.*?)"($|; )/i); if (!m) return; var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); filename = filename.replace(/%22/g, '"'); filename = filename.replace(/&#([\d]{4});/g, function(m, code) { return String.fromCharCode(code); }); return filename; }; IncomingForm.prototype._initUrlencoded = function() { this.type = 'urlencoded'; var parser = new QuerystringParser(this.maxFields) , self = this; parser.onField = function(key, val) { self.emit('field', key, val); }; parser.onEnd = function() { self.ended = true; self._maybeEnd(); }; this._parser = parser; }; IncomingForm.prototype._initOctetStream = function() { this.type = 'octet-stream'; var filename = this.headers['x-file-name']; var mime = this.headers['content-type']; var file = new File({ path: this._uploadPath(filename), name: filename, type: mime }); this.emit('fileBegin', filename, file); file.open(); this._flushing++; var self = this; self._parser = new OctetParser(); //Keep track of writes that haven't finished so we don't emit the file before it's done being written var outstandingWrites = 0; self._parser.on('data', function(buffer){ self.pause(); outstandingWrites++; file.write(buffer, function() { outstandingWrites--; self.resume(); if(self.ended){ self._parser.emit('doneWritingFile'); } }); }); self._parser.on('end', function(){ self._flushing--; self.ended = true; var done = function(){ file.end(function() { self.emit('file', 'file', file); self._maybeEnd(); }); }; if(outstandingWrites === 0){ done(); } else { self._parser.once('doneWritingFile', done); } }); }; IncomingForm.prototype._initJSONencoded = function() { this.type = 'json'; var parser = new JSONParser() , self = this; if (this.bytesExpected) { parser.initWithLength(this.bytesExpected); } parser.onField = function(key, val) { self.emit('field', key, val); }; parser.onEnd = function() { self.ended = true; self._maybeEnd(); }; this._parser = parser; }; IncomingForm.prototype._uploadPath = function(filename) { var name = 'upload_'; var buf = crypto.randomBytes(16); for (var i = 0; i < buf.length; ++i) { name += ('0' + buf[i].toString(16)).slice(-2); } if (this.keepExtensions) { var ext = path.extname(filename); ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); name += ext; } return path.join(this.uploadDir, name); }; IncomingForm.prototype._maybeEnd = function() { if (!this.ended || this._flushing || this.error) { return; } this.emit('end'); };
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_REF_H #define EIGEN_REF_H namespace Eigen { template<typename Derived> class RefBase; template<typename PlainObjectType, int Options = 0, typename StrideType = typename internal::conditional<PlainObjectType::IsVectorAtCompileTime,InnerStride<1>,OuterStride<> >::type > class Ref; /** \class Ref * \ingroup Core_Module * * \brief A matrix or vector expression mapping an existing expressions * * \tparam PlainObjectType the equivalent matrix type of the mapped data * \tparam Options specifies whether the pointer is \c #Aligned, or \c #Unaligned. * The default is \c #Unaligned. * \tparam StrideType optionally specifies strides. By default, Ref implies a contiguous storage along the inner dimension (inner stride==1), * but accept a variable outer stride (leading dimension). * This can be overridden by specifying strides. * The type passed here must be a specialization of the Stride template, see examples below. * * This class permits to write non template functions taking Eigen's object as parameters while limiting the number of copies. * A Ref<> object can represent either a const expression or a l-value: * \code * // in-out argument: * void foo1(Ref<VectorXf> x); * * // read-only const argument: * void foo2(const Ref<const VectorXf>& x); * \endcode * * In the in-out case, the input argument must satisfies the constraints of the actual Ref<> type, otherwise a compilation issue will be triggered. * By default, a Ref<VectorXf> can reference any dense vector expression of float having a contiguous memory layout. * Likewise, a Ref<MatrixXf> can reference any column major dense matrix expression of float whose column's elements are contiguously stored with * the possibility to have a constant space inbetween each column, i.e.: the inner stride mmust be equal to 1, but the outer-stride (or leading dimension), * can be greater than the number of rows. * * In the const case, if the input expression does not match the above requirement, then it is evaluated into a temporary before being passed to the function. * Here are some examples: * \code * MatrixXf A; * VectorXf a; * foo1(a.head()); // OK * foo1(A.col()); // OK * foo1(A.row()); // compilation error because here innerstride!=1 * foo2(A.row()); // The row is copied into a contiguous temporary * foo2(2*a); // The expression is evaluated into a temporary * foo2(A.col().segment(2,4)); // No temporary * \endcode * * The range of inputs that can be referenced without temporary can be enlarged using the last two template parameter. * Here is an example accepting an innerstride!=1: * \code * // in-out argument: * void foo3(Ref<VectorXf,0,InnerStride<> > x); * foo3(A.row()); // OK * \endcode * The downside here is that the function foo3 might be significantly slower than foo1 because it won't be able to exploit vectorization, and will involved more * expensive address computations even if the input is contiguously stored in memory. To overcome this issue, one might propose to overloads internally calling a * template function, e.g.: * \code * // in the .h: * void foo(const Ref<MatrixXf>& A); * void foo(const Ref<MatrixXf,0,Stride<> >& A); * * // in the .cpp: * template<typename TypeOfA> void foo_impl(const TypeOfA& A) { * ... // crazy code goes here * } * void foo(const Ref<MatrixXf>& A) { foo_impl(A); } * void foo(const Ref<MatrixXf,0,Stride<> >& A) { foo_impl(A); } * \endcode * * * \sa PlainObjectBase::Map(), \ref TopicStorageOrders */ namespace internal { template<typename _PlainObjectType, int _Options, typename _StrideType> struct traits<Ref<_PlainObjectType, _Options, _StrideType> > : public traits<Map<_PlainObjectType, _Options, _StrideType> > { typedef _PlainObjectType PlainObjectType; typedef _StrideType StrideType; enum { Options = _Options, Flags = traits<Map<_PlainObjectType, _Options, _StrideType> >::Flags | NestByRefBit }; template<typename Derived> struct match { enum { HasDirectAccess = internal::has_direct_access<Derived>::ret, StorageOrderMatch = PlainObjectType::IsVectorAtCompileTime || ((PlainObjectType::Flags&RowMajorBit)==(Derived::Flags&RowMajorBit)), InnerStrideMatch = int(StrideType::InnerStrideAtCompileTime)==int(Dynamic) || int(StrideType::InnerStrideAtCompileTime)==int(Derived::InnerStrideAtCompileTime) || (int(StrideType::InnerStrideAtCompileTime)==0 && int(Derived::InnerStrideAtCompileTime)==1), OuterStrideMatch = Derived::IsVectorAtCompileTime || int(StrideType::OuterStrideAtCompileTime)==int(Dynamic) || int(StrideType::OuterStrideAtCompileTime)==int(Derived::OuterStrideAtCompileTime), AlignmentMatch = (_Options!=Aligned) || ((PlainObjectType::Flags&AlignedBit)==0) || ((traits<Derived>::Flags&AlignedBit)==AlignedBit), MatchAtCompileTime = HasDirectAccess && StorageOrderMatch && InnerStrideMatch && OuterStrideMatch && AlignmentMatch }; typedef typename internal::conditional<MatchAtCompileTime,internal::true_type,internal::false_type>::type type; }; }; template<typename Derived> struct traits<RefBase<Derived> > : public traits<Derived> {}; } template<typename Derived> class RefBase : public MapBase<Derived> { typedef typename internal::traits<Derived>::PlainObjectType PlainObjectType; typedef typename internal::traits<Derived>::StrideType StrideType; public: typedef MapBase<Derived> Base; EIGEN_DENSE_PUBLIC_INTERFACE(RefBase) inline Index innerStride() const { return StrideType::InnerStrideAtCompileTime != 0 ? m_stride.inner() : 1; } inline Index outerStride() const { return StrideType::OuterStrideAtCompileTime != 0 ? m_stride.outer() : IsVectorAtCompileTime ? this->size() : int(Flags)&RowMajorBit ? this->cols() : this->rows(); } RefBase() : Base(0,RowsAtCompileTime==Dynamic?0:RowsAtCompileTime,ColsAtCompileTime==Dynamic?0:ColsAtCompileTime), // Stride<> does not allow default ctor for Dynamic strides, so let' initialize it with dummy values: m_stride(StrideType::OuterStrideAtCompileTime==Dynamic?0:StrideType::OuterStrideAtCompileTime, StrideType::InnerStrideAtCompileTime==Dynamic?0:StrideType::InnerStrideAtCompileTime) {} EIGEN_INHERIT_ASSIGNMENT_OPERATORS(RefBase) protected: typedef Stride<StrideType::OuterStrideAtCompileTime,StrideType::InnerStrideAtCompileTime> StrideBase; template<typename Expression> void construct(Expression& expr) { if(PlainObjectType::RowsAtCompileTime==1) { eigen_assert(expr.rows()==1 || expr.cols()==1); ::new (static_cast<Base*>(this)) Base(expr.data(), 1, expr.size()); } else if(PlainObjectType::ColsAtCompileTime==1) { eigen_assert(expr.rows()==1 || expr.cols()==1); ::new (static_cast<Base*>(this)) Base(expr.data(), expr.size(), 1); } else ::new (static_cast<Base*>(this)) Base(expr.data(), expr.rows(), expr.cols()); ::new (&m_stride) StrideBase(StrideType::OuterStrideAtCompileTime==0?0:expr.outerStride(), StrideType::InnerStrideAtCompileTime==0?0:expr.innerStride()); } StrideBase m_stride; }; template<typename PlainObjectType, int Options, typename StrideType> class Ref : public RefBase<Ref<PlainObjectType, Options, StrideType> > { typedef internal::traits<Ref> Traits; public: typedef RefBase<Ref> Base; EIGEN_DENSE_PUBLIC_INTERFACE(Ref) #ifndef EIGEN_PARSED_BY_DOXYGEN template<typename Derived> inline Ref(PlainObjectBase<Derived>& expr, typename internal::enable_if<bool(Traits::template match<Derived>::MatchAtCompileTime),Derived>::type* = 0) { Base::construct(expr); } template<typename Derived> inline Ref(const DenseBase<Derived>& expr, typename internal::enable_if<bool(internal::is_lvalue<Derived>::value&&bool(Traits::template match<Derived>::MatchAtCompileTime)),Derived>::type* = 0, int = Derived::ThisConstantIsPrivateInPlainObjectBase) #else template<typename Derived> inline Ref(DenseBase<Derived>& expr) #endif { Base::construct(expr.const_cast_derived()); } EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Ref) }; // this is the const ref version template<typename TPlainObjectType, int Options, typename StrideType> class Ref<const TPlainObjectType, Options, StrideType> : public RefBase<Ref<const TPlainObjectType, Options, StrideType> > { typedef internal::traits<Ref> Traits; public: typedef RefBase<Ref> Base; EIGEN_DENSE_PUBLIC_INTERFACE(Ref) template<typename Derived> inline Ref(const DenseBase<Derived>& expr) { // std::cout << match_helper<Derived>::HasDirectAccess << "," << match_helper<Derived>::OuterStrideMatch << "," << match_helper<Derived>::InnerStrideMatch << "\n"; // std::cout << int(StrideType::OuterStrideAtCompileTime) << " - " << int(Derived::OuterStrideAtCompileTime) << "\n"; // std::cout << int(StrideType::InnerStrideAtCompileTime) << " - " << int(Derived::InnerStrideAtCompileTime) << "\n"; construct(expr.derived(), typename Traits::template match<Derived>::type()); } protected: template<typename Expression> void construct(const Expression& expr,internal::true_type) { Base::construct(expr); } template<typename Expression> void construct(const Expression& expr, internal::false_type) { m_object.lazyAssign(expr); Base::construct(m_object); } protected: TPlainObjectType m_object; }; } // end namespace Eigen #endif // EIGEN_REF_H
{ "pile_set_name": "Github" }
<import src="../../../common/head.wxml"/> <import src="../../../common/foot.wxml"/> <view class="container"> <template is="head" data="{{title: 'sendMessage'}}"/> <view class="page-body"> <view class="weui-cells__title">发送内容(以下字段可自由适配)</view> <view class="weui-cells weui-cells_after-title"> <view class="weui-cell weui-cell_input"> <view class="weui-cell__hd"> <view class="weui-label">实例字段</view> </view> <view class="weui-cell__bd"> <input class="weui-input" type="text" placeholder="请输入"></input> </view> </view> <view class="weui-cell weui-cell_input"> <view class="weui-cell__hd"> <view class="weui-label">实例字段</view> </view> <view class="weui-cell__bd"> <input class="weui-input" type="text" placeholder="请输入"></input> </view> </view> </view> <view class="weui-cells"> <view class="weui-cell weui-cell_input"> <view class="weui-cell__hd"> <view class="weui-label">跳转链接</view> </view> <view class="weui-cell__bd"> <input class="weui-input" type="text" placeholder="请输入" value="{{shareData.path}}"></input> </view> </view> </view> <view class="btn-area"> <button type="primary">发送模板消息</button> </view> </view> <template is="foot"/> </view>
{ "pile_set_name": "Github" }
// Copyright (C) 2005-2006 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Authors: Douglas Gregor // Andrew Lumsdaine #ifndef BOOST_GRAPH_DETAIL_REMOTE_UPDATE_SET_HPP #define BOOST_GRAPH_DETAIL_REMOTE_UPDATE_SET_HPP #ifndef BOOST_GRAPH_USE_MPI #error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included" #endif #include <boost/graph/parallel/process_group.hpp> #include <boost/type_traits/is_convertible.hpp> #include <vector> #include <boost/assert.hpp> #include <boost/optional.hpp> #include <queue> namespace boost { namespace graph { namespace detail { template<typename ProcessGroup> void do_synchronize(ProcessGroup& pg) { using boost::parallel::synchronize; synchronize(pg); } struct remote_set_queued {}; struct remote_set_immediate {}; template<typename ProcessGroup> class remote_set_semantics { BOOST_STATIC_CONSTANT (bool, queued = (is_convertible< typename ProcessGroup::communication_category, boost::parallel::bsp_process_group_tag>::value)); public: typedef typename mpl::if_c<queued, remote_set_queued, remote_set_immediate>::type type; }; template<typename Derived, typename ProcessGroup, typename Value, typename OwnerMap, typename Semantics = typename remote_set_semantics<ProcessGroup>::type> class remote_update_set; /********************************************************************** * Remote updating set that queues messages until synchronization * **********************************************************************/ template<typename Derived, typename ProcessGroup, typename Value, typename OwnerMap> class remote_update_set<Derived, ProcessGroup, Value, OwnerMap, remote_set_queued> { typedef typename property_traits<OwnerMap>::key_type Key; typedef std::vector<std::pair<Key, Value> > Updates; typedef typename Updates::size_type updates_size_type; typedef typename Updates::value_type updates_pair_type; public: private: typedef typename ProcessGroup::process_id_type process_id_type; enum message_kind { /** Message containing the number of updates that will be sent in * a msg_updates message that will immediately follow. This * message will contain a single value of type * updates_size_type. */ msg_num_updates, /** Contains (key, value) pairs with all of the updates from a * particular source. The number of updates is variable, but will * be provided in a msg_num_updates message that immediately * preceeds this message. * */ msg_updates }; struct handle_messages { explicit handle_messages(remote_update_set* self, const ProcessGroup& pg) : self(self), update_sizes(num_processes(pg), 0) { } void operator()(process_id_type source, int tag) { switch(tag) { case msg_num_updates: { // Receive the # of updates updates_size_type num_updates; receive(self->process_group, source, tag, num_updates); update_sizes[source] = num_updates; } break; case msg_updates: { updates_size_type num_updates = update_sizes[source]; BOOST_ASSERT(num_updates); // Receive the actual updates std::vector<updates_pair_type> updates(num_updates); receive(self->process_group, source, msg_updates, &updates[0], num_updates); // Send updates to derived "receive_update" member Derived* derived = static_cast<Derived*>(self); for (updates_size_type u = 0; u < num_updates; ++u) derived->receive_update(source, updates[u].first, updates[u].second); update_sizes[source] = 0; } break; }; } private: remote_update_set* self; std::vector<updates_size_type> update_sizes; }; friend struct handle_messages; protected: remote_update_set(const ProcessGroup& pg, const OwnerMap& owner) : process_group(pg, handle_messages(this, pg)), updates(num_processes(pg)), owner(owner) { } void update(const Key& key, const Value& value) { if (get(owner, key) == process_id(process_group)) { Derived* derived = static_cast<Derived*>(this); derived->receive_update(get(owner, key), key, value); } else { updates[get(owner, key)].push_back(std::make_pair(key, value)); } } void collect() { } void synchronize() { // Emit all updates and then remove them process_id_type num_processes = updates.size(); for (process_id_type p = 0; p < num_processes; ++p) { if (!updates[p].empty()) { send(process_group, p, msg_num_updates, updates[p].size()); send(process_group, p, msg_updates, &updates[p].front(), updates[p].size()); updates[p].clear(); } } do_synchronize(process_group); } ProcessGroup process_group; private: std::vector<Updates> updates; OwnerMap owner; }; /********************************************************************** * Remote updating set that sends messages immediately * **********************************************************************/ template<typename Derived, typename ProcessGroup, typename Value, typename OwnerMap> class remote_update_set<Derived, ProcessGroup, Value, OwnerMap, remote_set_immediate> { typedef typename property_traits<OwnerMap>::key_type Key; typedef std::pair<Key, Value> update_pair_type; typedef typename std::vector<update_pair_type>::size_type updates_size_type; public: typedef typename ProcessGroup::process_id_type process_id_type; private: enum message_kind { /** Contains a (key, value) pair that will be updated. */ msg_update }; struct handle_messages { explicit handle_messages(remote_update_set* self, const ProcessGroup& pg) : self(self) { update_sizes.resize(num_processes(pg), 0); } void operator()(process_id_type source, int tag) { // Receive the # of updates BOOST_ASSERT(tag == msg_update); update_pair_type update; receive(self->process_group, source, tag, update); // Send update to derived "receive_update" member Derived* derived = static_cast<Derived*>(self); derived->receive_update(source, update.first, update.second); } private: std::vector<updates_size_type> update_sizes; remote_update_set* self; }; friend struct handle_messages; protected: remote_update_set(const ProcessGroup& pg, const OwnerMap& owner) : process_group(pg, handle_messages(this, pg)), owner(owner) { } void update(const Key& key, const Value& value) { if (get(owner, key) == process_id(process_group)) { Derived* derived = static_cast<Derived*>(this); derived->receive_update(get(owner, key), key, value); } else send(process_group, get(owner, key), msg_update, update_pair_type(key, value)); } void collect() { typedef std::pair<process_id_type, int> probe_type; handle_messages handler(this, process_group); while (optional<probe_type> stp = probe(process_group)) if (stp->second == msg_update) handler(stp->first, stp->second); } void synchronize() { do_synchronize(process_group); } ProcessGroup process_group; OwnerMap owner; }; } } } // end namespace boost::graph::detail #endif // BOOST_GRAPH_DETAIL_REMOTE_UPDATE_SET_HPP
{ "pile_set_name": "Github" }
package com.tencent.mm.ui.chatting; import android.view.View; import android.view.ViewStub; import android.view.animation.AnimationUtils; import android.widget.ListView; import com.tencent.mm.e.a.nq; import com.tencent.mm.plugin.sight.encode.ui.ChattingSightContainerView.a; import com.tencent.mm.sdk.c.a; import com.tencent.mm.sdk.platformtools.ac; import com.tencent.mm.ui.j; import com.tencent.mm.ui.o; final class ChattingUI$a$84$2 implements ChattingSightContainerView.a { View lBB = null; ChattingUI$a$84$2(ChattingUI.a.84 param84) {} public final void azd() { nq localnq = new nq(); avS.type = 6; a.kug.y(localnq); lBA.lAY.setRequestedOrientation(1); lBA.lAY.Xk(); lBA.lAY.bkT(); lBA.lAY.blj(); if (lBB == null) { lBB = ((ViewStub)lBA.lAY.findViewById(2131755932)).inflate(); } lBB.setVisibility(0); lBB.startAnimation(AnimationUtils.loadAnimation(lBA.lAY.kNN.kOg, 2130968612)); } public final void onHide() { lBA.lAY.setRequestedOrientation(-1); lBA.lAY.bkT(); if ((lBB != null) && (lBB.getVisibility() == 0)) { lBB.setVisibility(8); lBB.startAnimation(AnimationUtils.loadAnimation(lBA.lAY.kNN.kOg, 2130968613)); } new ac().post(new Runnable() { public final void run() { nq localnq = new nq(); avS.type = 7; avS.avT = ChattingUI.a.e(lBA.lAY).getFirstVisiblePosition(); avS.avU = ChattingUI.a.e(lBA.lAY).getLastVisiblePosition(); avS.avV = ChattingUI.a.e(lBA.lAY).getHeaderViewsCount(); a.kug.y(localnq); } }); } } /* Location: * Qualified Name: com.tencent.mm.ui.chatting.ChattingUI.a.84.2 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
{ "pile_set_name": "Github" }
PREFIX dc: <http://purl.org/dc/elements/1.1/> PREFIX ns: <http://example.org/ns#> SELECT ?title ?price { ?x ns:price ?p . ?x ns:discount ?discount BIND (?p*(1-?discount) AS ?price) FILTER(?price < 20) ?x dc:title ?title . }
{ "pile_set_name": "Github" }
/* * TupleTypeUtil.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2019 Apple Inc. and the FoundationDB project 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.apple.foundationdb.record.metadata; import com.apple.foundationdb.record.provider.foundationdb.FDBRecordVersion; import com.apple.foundationdb.tuple.Tuple; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors; import com.google.protobuf.ProtocolMessageEnum; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; /** * Utility class for dealing with {@link Tuple} types. In theory, these methods should live in * {@link com.apple.foundationdb.tuple.TupleHelpers TupleHelpers} except that they use some Protobuf specific things * like the {@link ByteString} class, and {@code TupleHelpers} is defined in the * <a href="https://javadoc.io/doc/org.foundationdb/fdb-extensions/">fdb-extensions</a> sub-project * which does not (and probably should not) take Protobuf as a dependency. */ class TupleTypeUtil { @Nonnull private static final BigInteger BIG_INT_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); @Nonnull private static final BigInteger BIG_INT_MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); /** * Normalize a list of values so that it can be checked for equality with other lists sharing * the same {@link Tuple} representation. In other words, it should be the case that: * * <pre> {@code * toTupleEquivalentValue(list1).equals(toTupleEquivalentValue) * == Arrays.equals(Tuple.fromList(toTupleAppropriateList(list1)).pack(), Tuple.fromList(toTupleAppropriateList(list2)).pack()) * }</pre> * * <p> * for any two lists {@code list1} and {@code list2}. * </p> * * @param values the list of values to normalized * @return a new list containing the normalized elements of {@code values} */ @Nonnull static List<Object> toTupleEquivalentList(@Nonnull List<?> values) { List<Object> tupleEquivalentList = new ArrayList<>(values.size()); for (Object o : values) { tupleEquivalentList.add(toTupleEquivalentValue(o)); } return tupleEquivalentList; } /** * Normalize a value so that it compares equal to anything with the same {@link Tuple} representation. * The value that is returned cannot necessarily be packed by a {@code Tuple} (for example, * a <code>byte[]</code> is returned as a {@link ByteString}), but it does implement {@link Object#equals(Object)} * and {@link Object#hashCode()}, so the value can be used in hash-based data structures like * {@link java.util.HashSet HashSet}s and {@link java.util.HashMap HashMap}s. In other words, it should * bethe case that: * * <pre> {@code * Objects.equals(toTupleEquivalentValue(value1), toTupleEquivalentValue(value2)) * == Arrays.equals(Tuple.from(value1).pack(), Tuple.from(value2).pack()) * }</pre> * * <p> * for any two values {@code value1} and {@code value2}. * </p> * * <p> * This will only return {@code null} if {@link #toTupleAppropriateValue(Object)} would return {@code null} * on the same input. If the object is already in * </p> * * @param obj the value to normalize * @return a value that has the same representation when {@link Tuple}-encoded */ @Nullable static Object toTupleEquivalentValue(@Nullable Object obj) { if (obj == null || obj instanceof Key.Evaluated.NullStandin) { return null; } else if (obj instanceof List<?>) { List<?> list = (List<?>)obj; return toTupleEquivalentList(list); } else if (obj instanceof Tuple) { return toTupleEquivalentList(((Tuple)obj).getItems()); } else if (obj instanceof byte[]) { return ByteString.copyFrom((byte[]) obj); } else if ((obj instanceof Byte) || (obj instanceof Short) || (obj instanceof Integer)) { return ((Number)obj).longValue(); } else if (obj instanceof BigInteger) { BigInteger bigInt = (BigInteger)obj; if (bigInt.compareTo(BIG_INT_MIN_LONG) > 0 && bigInt.compareTo(BIG_INT_MAX_LONG) < 0) { return bigInt.longValue(); } else { return bigInt; } } else if (obj instanceof ProtocolMessageEnum) { return (long)((ProtocolMessageEnum)obj).getNumber(); } else if (obj instanceof Descriptors.EnumValueDescriptor) { return (long)((Descriptors.EnumValueDescriptor)obj).getNumber(); } else if (obj instanceof FDBRecordVersion) { return ((FDBRecordVersion)obj).toVersionstamp(false); } else { return obj; } } /** * Convert a list of values into items that can all be stored within a {@link Tuple}. * * @param values a list of values * @return a new list with {@link Tuple}-encodable versions of the elements of {@code values} */ @Nonnull static List<Object> toTupleAppropriateList(@Nonnull List<?> values) { List<Object> tupleAppropriateList = new ArrayList<>(values.size()); for (Object o : values) { tupleAppropriateList.add(toTupleAppropriateValue(o)); } return tupleAppropriateList; } /** * Convert a value into a type that can be stored within a {@link Tuple}. * * @param obj the value to convert * @return the value converted to some {@link Tuple}-encodable type */ @Nullable static Object toTupleAppropriateValue(@Nullable Object obj) { if (obj instanceof Key.Evaluated.NullStandin) { return null; } else if (obj instanceof ByteString) { return ((ByteString) obj).toByteArray(); } else if (obj instanceof List) { return toTupleAppropriateList((List<?>) obj); // Following two are both Internal.EnumLite, so could use that, too. } else if (obj instanceof ProtocolMessageEnum) { return ((ProtocolMessageEnum) obj).getNumber(); } else if (obj instanceof Descriptors.EnumValueDescriptor) { return ((Descriptors.EnumValueDescriptor) obj).getNumber(); } else if (obj instanceof FDBRecordVersion) { return ((FDBRecordVersion) obj).toVersionstamp(false); } else { return obj; } } private TupleTypeUtil() { } }
{ "pile_set_name": "Github" }
# coding=utf-8 import typing from pyramid.config import Configurator import transaction from tracim_backend.app_models.contents import FOLDER_TYPE from tracim_backend.app_models.contents import content_type_list from tracim_backend.config import CFG from tracim_backend.exceptions import ContentFilenameAlreadyUsedInFolder from tracim_backend.exceptions import EmptyLabelNotAllowed from tracim_backend.extensions import hapic from tracim_backend.lib.core.content import ContentApi from tracim_backend.lib.utils.authorization import ContentTypeChecker from tracim_backend.lib.utils.authorization import check_right from tracim_backend.lib.utils.authorization import is_contributor from tracim_backend.lib.utils.authorization import is_reader from tracim_backend.lib.utils.request import TracimRequest from tracim_backend.lib.utils.utils import generate_documentation_swagger_tag from tracim_backend.models.context_models import ContentInContext from tracim_backend.models.context_models import RevisionInContext from tracim_backend.models.revision_protection import new_revision from tracim_backend.views.controllers import Controller from tracim_backend.views.core_api.schemas import FolderContentModifySchema from tracim_backend.views.core_api.schemas import NoContentSchema from tracim_backend.views.core_api.schemas import SetContentStatusSchema from tracim_backend.views.core_api.schemas import TextBasedContentSchema from tracim_backend.views.core_api.schemas import TextBasedRevisionSchema from tracim_backend.views.core_api.schemas import WorkspaceAndContentIdPathSchema from tracim_backend.views.swagger_generic_section import SWAGGER_TAG__CONTENT_ENDPOINTS try: # Python 3.5+ from http import HTTPStatus except ImportError: from http import client as HTTPStatus SWAGGER_TAG__CONTENT_FOLDER_SECTION = "Folders" SWAGGER_TAG__CONTENT_FOLDER_ENDPOINTS = generate_documentation_swagger_tag( SWAGGER_TAG__CONTENT_ENDPOINTS, SWAGGER_TAG__CONTENT_FOLDER_SECTION ) is_folder_content = ContentTypeChecker([FOLDER_TYPE]) class FolderController(Controller): @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_FOLDER_ENDPOINTS]) @check_right(is_reader) @check_right(is_folder_content) @hapic.input_path(WorkspaceAndContentIdPathSchema()) @hapic.output_body(TextBasedContentSchema()) def get_folder(self, context, request: TracimRequest, hapic_data=None) -> ContentInContext: """ Get folder info """ app_config = request.registry.settings["CFG"] # type: CFG api = ContentApi( show_archived=True, show_deleted=True, current_user=request.current_user, session=request.dbsession, config=app_config, ) content = api.get_one(hapic_data.path.content_id, content_type=content_type_list.Any_SLUG) return api.get_content_in_context(content) @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_FOLDER_ENDPOINTS]) @hapic.handle_exception(EmptyLabelNotAllowed, HTTPStatus.BAD_REQUEST) @hapic.handle_exception(ContentFilenameAlreadyUsedInFolder, HTTPStatus.BAD_REQUEST) @check_right(is_contributor) @check_right(is_folder_content) @hapic.input_path(WorkspaceAndContentIdPathSchema()) @hapic.input_body(FolderContentModifySchema()) @hapic.output_body(TextBasedContentSchema()) def update_folder(self, context, request: TracimRequest, hapic_data=None) -> ContentInContext: """ update folder """ app_config = request.registry.settings["CFG"] # type: CFG api = ContentApi( show_archived=True, show_deleted=True, current_user=request.current_user, session=request.dbsession, config=app_config, ) content = api.get_one(hapic_data.path.content_id, content_type=content_type_list.Any_SLUG) with new_revision(session=request.dbsession, tm=transaction.manager, content=content): api.update_container_content( item=content, new_label=hapic_data.body.label, new_content=hapic_data.body.raw_content, allowed_content_type_slug_list=hapic_data.body.sub_content_types, ) api.save(content) api.execute_update_content_actions(content) return api.get_content_in_context(content) @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_FOLDER_ENDPOINTS]) @check_right(is_reader) @check_right(is_folder_content) @hapic.input_path(WorkspaceAndContentIdPathSchema()) @hapic.output_body(TextBasedRevisionSchema(many=True)) def get_folder_revisions( self, context, request: TracimRequest, hapic_data=None ) -> typing.List[RevisionInContext]: """ get folder revisions """ app_config = request.registry.settings["CFG"] # type: CFG api = ContentApi( show_archived=True, show_deleted=True, current_user=request.current_user, session=request.dbsession, config=app_config, ) content = api.get_one(hapic_data.path.content_id, content_type=content_type_list.Any_SLUG) revisions = content.revisions return [api.get_revision_in_context(revision) for revision in revisions] @hapic.with_api_doc(tags=[SWAGGER_TAG__CONTENT_FOLDER_ENDPOINTS]) @check_right(is_contributor) @check_right(is_folder_content) @hapic.input_path(WorkspaceAndContentIdPathSchema()) @hapic.input_body(SetContentStatusSchema()) @hapic.output_body(NoContentSchema(), default_http_code=HTTPStatus.NO_CONTENT) def set_folder_status(self, context, request: TracimRequest, hapic_data=None) -> None: """ set folder status """ app_config = request.registry.settings["CFG"] # type: CFG api = ContentApi( show_archived=True, show_deleted=True, current_user=request.current_user, session=request.dbsession, config=app_config, ) content = api.get_one(hapic_data.path.content_id, content_type=content_type_list.Any_SLUG) with new_revision(session=request.dbsession, tm=transaction.manager, content=content): api.set_status(content, hapic_data.body.status) api.save(content) api.execute_update_content_actions(content) return def bind(self, configurator: Configurator) -> None: # Get folder configurator.add_route( "folder", "/workspaces/{workspace_id}/folders/{content_id}", request_method="GET" ) configurator.add_view(self.get_folder, route_name="folder") # update folder configurator.add_route( "update_folder", "/workspaces/{workspace_id}/folders/{content_id}", request_method="PUT" ) configurator.add_view(self.update_folder, route_name="update_folder") # get folder revisions configurator.add_route( "folder_revisions", "/workspaces/{workspace_id}/folders/{content_id}/revisions", request_method="GET", ) configurator.add_view(self.get_folder_revisions, route_name="folder_revisions") # get folder revisions configurator.add_route( "set_folder_status", "/workspaces/{workspace_id}/folders/{content_id}/status", request_method="PUT", ) configurator.add_view(self.set_folder_status, route_name="set_folder_status")
{ "pile_set_name": "Github" }
/** @file Intel Processor Power Management ACPI Code. Copyright (c) 2018 - 2019, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "CpuPowerMgmt.h" DefinitionBlock ( "CPU0PSD.aml", "SSDT", 0x02, "PmRef", "Cpu0Psd", 0x3000 ) { External(\PC00, IntObj) External(\TCNT, FieldUnitObj) External(\_SB.CFGD, FieldUnitObj) External(\_SB.PR00, DeviceObj) Scope(\_SB.PR00) { Name(HPSD,Package() // HW_ALL { Package() {5, // NumEntries. Current Value is 5. 0, // Revision. Current Value is 0. 0, // Domain. 0xFE, // Coordination type 0xFE = HW_ALL 0x80 // Number of processors. } }) Name(SPSD,Package() // SW_ALL { Package() {5, // NumEntries. Current Value is 5. 0, // Revision. Current Value is 0. 0, // Domain. 0xFC, // Coordination type 0xFC = SW_ALL 0x80 // Number of processors. } }) // // The _PSD object provides information to the OSPM related // to P-State coordination between processors in a multi-processor // configurations. // Method(_PSD,0) { If (And(\_SB.CFGD, PPM_TURBO_BOOST_MAX)) // Intel Turbo Boost Max 3.0 { Store (0, Index(DerefOf(Index(HPSD, 0)),2)) // Domain Store (1, Index(DerefOf(Index(HPSD, 0)),4)) // Number of processors belonging to the domain. } Else { Store (TCNT, Index(DerefOf(Index(HPSD, 0)),4)) Store (TCNT, Index(DerefOf(Index(SPSD, 0)),4)) } If(And(PC00,0x0800)) // If Hardware co-ordination of P states { Return(HPSD) } Return(SPSD) } } // End of Scope(\_SB.PR00) } // End of Definition Block
{ "pile_set_name": "Github" }
/* Copyright 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. */ // Code generated by client-gen. DO NOT EDIT. package v1 type JobExpansion interface{}
{ "pile_set_name": "Github" }
using System; using ModuleManager.Progress; namespace ModuleManager.Patches.PassSpecifiers { public class LegacyPassSpecifier : IPassSpecifier { public bool CheckNeeds(INeedsChecker needsChecker, IPatchProgress progress) { if (needsChecker == null) throw new ArgumentNullException(nameof(needsChecker)); if (progress == null) throw new ArgumentNullException(nameof(progress)); return true; } public string Descriptor => ":LEGACY (default)"; } }
{ "pile_set_name": "Github" }
require([ 'gitbook' ], function (gitbook) { gitbook.events.bind('page.change', function () { mermaid.init(); }); });
{ "pile_set_name": "Github" }
package de.peeeq.wurstscript.utils; import de.peeeq.wurstscript.WLogger; public class ExecutiontimeMeasure implements AutoCloseable { private String message; private long startTime; public ExecutiontimeMeasure(String message) { this.message = message; this.startTime = System.currentTimeMillis(); } @Override public void close() { long time = System.currentTimeMillis() - startTime; WLogger.info("Executed " + message + " in " + time + "ms."); } }
{ "pile_set_name": "Github" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by AsyncGenerator. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System.Collections.Generic; using NUnit.Framework; using NHibernate.Criterion; namespace NHibernate.Test.NHSpecificTest.NH2546 { using System.Threading.Tasks; [TestFixture] public class SetCommandParameterSizesFalseFixtureAsync : BugTestCase { protected override bool AppliesTo(Dialect.Dialect dialect) { return dialect is Dialect.MsSql2008Dialect; } protected override void OnSetUp() { using (ISession session = Sfi.OpenSession()) { session.Persist(new Student() { StringTypeWithLengthDefined = "Julian Maughan" }); session.Persist(new Student() { StringTypeWithLengthDefined = "Bill Clinton" }); session.Flush(); } } protected override void OnTearDown() { using (ISession session = Sfi.OpenSession()) { session.CreateQuery("delete from Student").ExecuteUpdate(); session.Flush(); } base.OnTearDown(); } [Test] public async Task LikeExpressionWithinDefinedTypeSizeAsync() { using (ISession session = Sfi.OpenSession()) { ICriteria criteria = session .CreateCriteria<Student>() .Add(Restrictions.Like("StringTypeWithLengthDefined", "Julian%")); IList<Student> list = await (criteria.ListAsync<Student>()); Assert.That(list.Count, Is.EqualTo(1)); } } [Test] public async Task LikeExpressionExceedsDefinedTypeSizeAsync() { // In this case we are forcing the usage of LikeExpression class where the length of the associated property is ignored using (ISession session = Sfi.OpenSession()) { ICriteria criteria = session .CreateCriteria<Student>() .Add(Restrictions.Like("StringTypeWithLengthDefined", "[a-z][a-z][a-z]ian%", MatchMode.Exact, null)); IList<Student> list = await (criteria.ListAsync<Student>()); Assert.That(list.Count, Is.EqualTo(1)); } } } }
{ "pile_set_name": "Github" }
goog.module('nested.exported.enums'); /** @const */ exports = { /** @const @enum {string} */ A: { A1: 'a1', }, // The structure of the AST changes if this extra property is present. B: 0, };
{ "pile_set_name": "Github" }
/* Copyright 2019 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ import {Polygon} from '/lib/math/polygon2d.js'; import * as moduleInterface from '/lib/module_interface.js'; import * as moduleTicker from '/client/modules/module_ticker.js'; import * as network from '/client/network/network.js'; import * as peerNetwork from '/client/network/peer.js'; import {easyLog} from '/lib/log.js'; import assert from '/lib/assert.js'; import asset from '/client/asset/asset.js'; import conform from '/lib/conform.js'; import inject from '/lib/inject.js'; import * as stateManager from '/client/state/state_manager.js'; import {TitleCard} from '/client/title_card.js'; import * as time from '/client/util/time.js'; import {delay} from '/lib/promise.js'; function createNewContainer(name) { var newContainer = document.createElement('div'); newContainer.className = 'container'; newContainer.id = 't-' + time.now(); newContainer.setAttribute('moduleName', name); return newContainer; } export const FadeTransition = { start(container) { if (container) { container.style.opacity = 0.001; document.querySelector('#containers').appendChild(container); } }, async perform(oldModule, newModule, deadline) { if (newModule.name == '_empty') { // Fading out.. so fade *out* the *old* container. oldModule.container.style.transition = 'opacity ' + time.until(deadline).toFixed(0) + 'ms'; oldModule.container.style.opacity = 0.0; } else { newModule.container.style.transition = 'opacity ' + time.until(deadline).toFixed(0) + 'ms'; newModule.container.style.opacity = 1.0; } // TODO(applmak): Maybe wait until css says that the transition is done? await delay(time.until(deadline)); } } export class ClientModule { constructor(name, path, config, titleCard, deadline, geo, transition) { // The module name. this.name = name; // The path to the main file of this module. this.path = path; // The module config. this.config = config; // The title card instance for this module. this.titleCard = titleCard; // Absolute time when this module is supposed to be visible. Module will // actually be faded in by deadline + 5000ms. this.deadline = deadline; // The wall geometry. this.geo = geo; // The transition to use to transition to this module. this.transition = transition; // The dom container for the module's content. this.container = null; // Module class instance. this.instance = null; // Network instance for this module. this.network = null; } // Deserializes from the json serialized form of ModuleDef in the server. static deserialize(bits) { if (bits.module.name == '_empty') { return ClientModule.newEmptyModule(bits.time); } return new ClientModule( bits.module.name, bits.module.path, bits.module.config, new TitleCard(bits.module.credit), bits.time, new Polygon(bits.geo), FadeTransition, ); } static newEmptyModule(deadline = 0, transition = FadeTransition) { return new ClientModule( '_empty', '', {}, new TitleCard({}), deadline, new Polygon([{x: 0, y:0}]), transition ); } // Extracted out for testing purposes. static async loadPath(path) { return await import(path); } async instantiate() { this.container = createNewContainer(this.name); if (!this.path) { return; } const INSTANTIATION_ID = `${this.geo.extents.serialize()}-${this.deadline}`; this.network = network.forModule(INSTANTIATION_ID); let openNetwork = this.network.open(); this.stateManager = stateManager.forModule(network, INSTANTIATION_ID); const fakeEnv = { asset, debug: easyLog('wall:module:' + this.name), game: undefined, network: openNetwork, titleCard: this.titleCard.getModuleAPI(), state: this.stateManager.open(), wallGeometry: this.geo, peerNetwork, assert, }; try { const {load} = await ClientModule.loadPath(this.path); if (!load) { throw new Error(`${this.name} did not export a 'load' function!`); } const {client} = inject(load, fakeEnv); conform(client, moduleInterface.Client); this.instance = new client(this.config); } catch (e) { // something went very wrong. Wind everything down.! this.network.close(); this.network = null; throw e; } } // Returns true if module is still OK. async willBeShownSoon() { if (!this.path) { return; } // Prep the container for transition. // TODO(applmak): Move the transition smarts out of ClientModule. this.transition.start(this.container); try { await this.instance.willBeShownSoon(this.container, this.deadline); } catch(e) { this.dispose(); throw e; } } // Returns true if module is still OK. beginTransitionIn(deadline) { if (!this.path) { return; } moduleTicker.add(this.name, this.instance); try { this.instance.beginFadeIn(deadline); } catch (e) { this.dispose(); throw e; } } finishTransitionIn() { if (!this.path) { return; } this.titleCard.enter(); this.instance.finishFadeIn(); } beginTransitionOut(deadline) { if (!this.path) { return; } this.titleCard.exit(); this.instance.beginFadeOut(deadline); } finishTransitionOut() { if (!this.path) { return; } this.instance.finishFadeOut(); } async performTransition(otherModule, transitionFinishDeadline) { await this.transition.perform(otherModule, this, transitionFinishDeadline); } dispose() { if (this.container) { this.container.remove(); this.container = null; } if (!this.path) { return; } this.titleCard.exit(); // Just in case. moduleTicker.remove(this.instance); if (this.network) { this.stateManager.close(); this.stateManager = null; this.network.close(); this.network = null; } } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.TestModels.ProviderAgnosticModel { using System; public enum AllTypesEnum { EnumValue0 = 0, EnumValue1 = 1, EnumValue2 = 2, EnumValue3 = 3, }; public class AllTypes { public int Id { get; set; } public bool BooleanProperty { get; set; } public byte ByteProperty { get; set; } public DateTime DateTimeProperty { get; set; } public decimal DecimalProperty { get; set; } public double DoubleProperty { get; set; } public byte[] FixedLengthBinaryProperty { get; set; } public string FixedLengthStringProperty { get; set; } public string FixedLengthUnicodeStringProperty { get; set; } public float FloatProperty { get; set; } public Guid GuidProperty { get; set; } public short Int16Property { get; set; } public int Int32Property { get; set; } public long Int64Property { get; set; } public byte[] MaxLengthBinaryProperty { get; set; } public string MaxLengthStringProperty { get; set; } public string MaxLengthUnicodeStringProperty { get; set; } public TimeSpan TimeSpanProperty { get; set; } public string VariableLengthStringProperty { get; set; } public byte[] VariableLengthBinaryProperty { get; set; } public string VariableLengthUnicodeStringProperty { get; set; } public AllTypesEnum EnumProperty { get; set; } } }
{ "pile_set_name": "Github" }
<?php /** * Specialized implementation of hook_page_manager_task_tasks(). See api-task.html for * more information. */ function page_manager_contact_user_page_manager_tasks() { if (!module_exists('contact')) { return; } return array( // This is a 'page' task and will fall under the page admin UI 'task type' => 'page', 'title' => t('User contact'), 'admin title' => t('User contact'), 'admin description' => t('When enabled, this overrides the default Drupal behavior for displaying the user contact form at <em>user/%user/contact</em>. If no variant is selected, the default Drupal user contact form will be used.'), 'admin path' => 'user/%user/contact', // Callback to add items to the page managertask administration form: 'task admin' => 'page_manager_contact_user_task_admin', 'hook menu alter' => 'page_manager_contact_user_menu_alter', // This is task uses 'context' handlers and must implement these to give the // handler data it needs. 'handler type' => 'context', // handler type -- misnamed 'get arguments' => 'page_manager_contact_user_get_arguments', 'get context placeholders' => 'page_manager_contact_user_get_contexts', // Allow this to be enabled or disabled: 'disabled' => variable_get('page_manager_contact_user_disabled', TRUE), 'enable callback' => 'page_manager_contact_user_enable', ); } /** * Callback defined by page_manager_contact_user_page_manager_tasks(). * * Alter the user view input so that user view comes to us rather than the * normal user view process. */ function page_manager_contact_user_menu_alter(&$items, $task) { if (variable_get('page_manager_contact_user_disabled', TRUE)) { return; } // Override the user view handler for our purpose. if ($items['user/%user/contact']['page callback'] == 'contact_user_page' || variable_get('page_manager_override_anyway', FALSE)) { $items['user/%user/contact']['page callback'] = 'page_manager_contact_user'; $items['user/%user/contact']['file path'] = $task['path']; $items['user/%user/contact']['file'] = $task['file']; } else { // automatically disable this task if it cannot be enabled. variable_set('page_manager_contact_user_disabled', TRUE); if (!empty($GLOBALS['page_manager_enabling_contact_user'])) { drupal_set_message(t('Page manager module is unable to enable user/%user/contact because some other module already has overridden with %callback.', array('%callback' => $items['user/%user/contact']['page callback'])), 'error'); } } } /** * Entry point for our overridden user view. * * This function asks its assigned handlers who, if anyone, would like * to run with it. If no one does, it passes through to Drupal core's * user view, which is user_page_view(). */ function page_manager_contact_user($account) { // Load my task plugin: $task = page_manager_get_task('contact_user'); // Load the account into a context. ctools_include('context'); ctools_include('context-task-handler'); $contexts = ctools_context_handler_get_task_contexts($task, '', array($account)); $output = ctools_context_handler_render($task, '', $contexts, array($account->uid)); if ($output !== FALSE) { return $output; } module_load_include('inc', 'contact', 'contact.pages'); $function = 'contact_user_page'; foreach (module_implements('page_manager_override') as $module) { $call = $module . '_page_manager_override'; if (($rc = $call('contact_user')) && function_exists($rc)) { $function = $rc; break; } } // Otherwise, fall back. return $function($account); } /** * Callback to get arguments provided by this task handler. * * Since this is the node view and there is no UI on the arguments, we * create dummy arguments that contain the needed data. */ function page_manager_contact_user_get_arguments($task, $subtask_id) { return array( array( 'keyword' => 'user', 'identifier' => t('User being viewed'), 'id' => 1, 'name' => 'uid', 'settings' => array(), ), ); } /** * Callback to get context placeholders provided by this handler. */ function page_manager_contact_user_get_contexts($task, $subtask_id) { return ctools_context_get_placeholders_from_argument(page_manager_contact_user_get_arguments($task, $subtask_id)); } /** * Callback to enable/disable the page from the UI. */ function page_manager_contact_user_enable($cache, $status) { variable_set('page_manager_contact_user_disabled', $status); // Set a global flag so that the menu routine knows it needs // to set a message if enabling cannot be done. if (!$status) { $GLOBALS['page_manager_enabling_contact_user'] = TRUE; } }
{ "pile_set_name": "Github" }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
5