text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
package com.example.cpv.security; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; /** * Utility class for Spring Security. */ public final class SecurityUtils { private SecurityUtils() { } /** * Get the login of the current user. * * @return the login of the current user */ public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; } /** * Check if a user is authenticated. * * @return true if the user is authenticated, false otherwise */ public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); Collection<? extends GrantedAuthority> authorities = securityContext.getAuthentication().getAuthorities(); if (authorities != null) { for (GrantedAuthority authority : authorities) { if (authority.getAuthority().equals(AuthoritiesConstants.ANONYMOUS)) { return false; } } } return true; } /** * If the current user has a specific authority (security role). * * <p>The name of this method comes from the isUserInRole() method in the Servlet API</p> * * @param authority the authorithy to check * @return true if the current user has the authority, false otherwise */ public static boolean isCurrentUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority)); } } return false; } }
{'content_hash': '059a87c612be2f2ede0f455029622a94', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 114, 'avg_line_length': 38.27272727272727, 'alnum_prop': 0.673566338649474, 'repo_name': 'borisbsu/continious-delivery-test', 'id': '141d1300c902c9e22d7097d23074a8f2e500953a', 'size': '2947', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/example/cpv/security/SecurityUtils.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '6671'}, {'name': 'Dockerfile', 'bytes': '200'}, {'name': 'Gherkin', 'bytes': '161'}, {'name': 'HTML', 'bytes': '111331'}, {'name': 'Java', 'bytes': '215248'}, {'name': 'JavaScript', 'bytes': '189746'}]}
package org.wso2.carbon.registry.extensions.handlers; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axiom.om.util.AXIOMUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.uddi.api_v3.AuthToken; import org.wso2.carbon.registry.common.utils.artifact.manager.ArtifactManager; import org.wso2.carbon.registry.core.*; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.handlers.Handler; import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; import org.wso2.carbon.registry.core.utils.RegistryUtils; import org.wso2.carbon.registry.extensions.beans.BusinessServiceInfo; import org.wso2.carbon.registry.extensions.handlers.utils.*; import org.wso2.carbon.registry.extensions.services.Utils; import org.wso2.carbon.registry.extensions.utils.CommonConstants; import org.wso2.carbon.registry.extensions.utils.CommonUtil; import org.wso2.carbon.registry.uddi.utils.UDDIUtil; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.StringReader; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; /** * Handler to process the service. */ public class ServiceMediaTypeHandler extends Handler { private static final Log log = LogFactory.getLog(ServiceMediaTypeHandler.class); private static final String TRUNK = "trunk"; private String defaultEnvironment; private boolean disableWSDLValidation = false; private boolean disableWADLValidation = false; private List<String> smartLifecycleLinks = new LinkedList<String>(); private String defaultServiceVersion = CommonConstants.SERVICE_VERSION_DEFAULT_VALUE; private boolean disableSymlinkCreation = true; public void setDefaultServiceVersion(String defaultServiceVersion) { this.defaultServiceVersion = defaultServiceVersion; } public void setSmartLifecycleLinks(OMElement locationConfiguration) throws RegistryException { Iterator confElements = locationConfiguration.getChildElements(); while (confElements.hasNext()) { OMElement confElement = (OMElement)confElements.next(); if (confElement.getQName().equals(new QName("key"))) { smartLifecycleLinks.add(confElement.getText()); } } } public boolean isDisableSymlinkCreation() { return disableSymlinkCreation; } public void setDisableSymlinkCreation(String disableSymlinkCreation) { this.disableSymlinkCreation = Boolean.toString(true).equals(disableSymlinkCreation); } public void put(RequestContext requestContext) throws RegistryException { WSDLProcessor wsdl = null; if (!CommonUtil.isUpdateLockAvailable()) { return; } CommonUtil.acquireUpdateLock(); try { Registry registry = requestContext.getRegistry(); Resource resource = requestContext.getResource(); if (resource == null) { throw new RegistryException("The resource is not available."); } String originalServicePath = requestContext.getResourcePath().getPath(); String resourceName = RegistryUtils.getResourceName(originalServicePath); OMElement serviceInfoElement, previousServiceInfoElement = null; Object resourceContent = resource.getContent(); String serviceInfo; if (resourceContent instanceof String) { serviceInfo = (String) resourceContent; } else { serviceInfo = RegistryUtils.decodeBytes((byte[]) resourceContent); } try { XMLStreamReader reader = XMLInputFactory.newInstance(). createXMLStreamReader(new StringReader(serviceInfo)); StAXOMBuilder builder = new StAXOMBuilder(reader); serviceInfoElement = builder.getDocumentElement(); } catch (Exception e) { String msg = "Error in parsing the service content of the service. " + "The requested path to store the service: " + originalServicePath + "."; log.error(msg); throw new RegistryException(msg, e); } // derive the service path that the service should be saved. String serviceName = CommonUtil.getServiceName(serviceInfoElement); String serviceNamespace = CommonUtil.getServiceNamespace(serviceInfoElement); String serviceVersion = CommonUtil.getServiceVersion( serviceInfoElement); if (serviceVersion.length() == 0) { serviceVersion = defaultServiceVersion; CommonUtil.setServiceVersion(serviceInfoElement, serviceVersion); resource.setContent(serviceInfoElement.toString()); } String servicePath = ""; if(serviceInfoElement.getChildrenWithLocalName("newServicePath").hasNext()){ Iterator OmElementIterator = serviceInfoElement.getChildrenWithLocalName("newServicePath"); while (OmElementIterator.hasNext()) { OMElement next = (OMElement) OmElementIterator.next(); servicePath = next.getText(); break; } } else{ if (registry.resourceExists(originalServicePath)) { //Fixing REGISTRY-1790. Save the Service to the given original //service path if there is a service already exists there servicePath = originalServicePath; } else { if (Utils.getRxtService() == null) { servicePath = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), registry.getRegistryContext().getServicePath() + (serviceNamespace == null ? "" : CommonUtil .derivePathFragmentFromNamespace( serviceNamespace)) + serviceVersion + "/" + serviceName); } else { String pathExpression = Utils.getRxtService().getStoragePath(resource.getMediaType()); servicePath = CommonUtil.getPathFromPathExpression(pathExpression, serviceInfoElement); } } } // saving the artifact id. String serviceId = resource.getUUID(); if (serviceId == null) { // generate a service id serviceId = UUID.randomUUID().toString(); resource.setUUID(serviceId); } if (registry.resourceExists(servicePath)) { Resource oldResource = registry.get(servicePath); String oldContent; Object content = oldResource.getContent(); if (content instanceof String) { oldContent = (String) content; } else { oldContent = RegistryUtils.decodeBytes((byte[]) content); } OMElement oldServiceInfoElement = null; if (serviceInfo.equals(oldContent)) { //TODO: This needs a better solution. This fix was put in place to avoid // duplication of services under /_system/governance, when no changes were made. // However, the fix is not perfect and needs to be rethought. Perhaps the logic // below can be reshaped a bit, or may be we don't need to compare the // difference over here with a little fix to the Governance API end. - Janaka. //We have fixed this assuming that the temp path where services are stored is under // /_system/governance/[serviceName] //Hence if we are to change that location, then we need to change the following code segment as well String tempPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + RegistryConstants.PATH_SEPARATOR + resourceName; if (!originalServicePath.equals(tempPath)) { String path = RegistryUtils.getRelativePathToOriginal(servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH); ArtifactManager.getArtifactManager().getTenantArtifactRepository(). addArtifact(path); return; } requestContext.setProcessingComplete(true); return; } if ("true".equals(resource.getProperty("registry.DefinitionImport"))) { resource.removeProperty("registry.DefinitionImport"); try { XMLStreamReader reader = XMLInputFactory.newInstance(). createXMLStreamReader(new StringReader(oldContent)); StAXOMBuilder builder = new StAXOMBuilder(reader); oldServiceInfoElement = builder.getDocumentElement(); CommonUtil.setServiceName(oldServiceInfoElement, CommonUtil.getServiceName(serviceInfoElement)); CommonUtil.setServiceNamespace(oldServiceInfoElement, CommonUtil.getServiceNamespace(serviceInfoElement)); CommonUtil.setDefinitionURL(oldServiceInfoElement, CommonUtil.getDefinitionURL(serviceInfoElement)); CommonUtil.setEndpointEntries(oldServiceInfoElement, CommonUtil.getEndpointEntries(serviceInfoElement)); CommonUtil.setServiceVersion(oldServiceInfoElement, org.wso2.carbon.registry.common.utils.CommonUtil.getServiceVersion( serviceInfoElement)); serviceInfoElement = oldServiceInfoElement; resource.setContent(serviceInfoElement.toString()); resource.setDescription(oldResource.getDescription()); } catch (Exception e) { String msg = "Error in parsing the service content of the service. " + "The requested path to store the service: " + originalServicePath + "."; log.error(msg); throw new RegistryException(msg, e); } } try { previousServiceInfoElement = AXIOMUtil.stringToOM(oldContent); } catch (XMLStreamException e) { String msg = "Error in parsing the service content of the service. " + "The requested path to store the service: " + originalServicePath + "."; log.error(msg); throw new RegistryException(msg, e); } } else if ("true".equals(resource.getProperty("registry.DefinitionImport"))) { resource.removeProperty("registry.DefinitionImport"); } // CommonUtil.addGovernanceArtifactEntryWithAbsoluteValues( // CommonUtil.getUnchrootedSystemRegistry(requestContext), // serviceId, servicePath); String definitionURL = CommonUtil.getDefinitionURL(serviceInfoElement); String oldDefinition = null; if (previousServiceInfoElement != null) { oldDefinition = CommonUtil.getDefinitionURL(previousServiceInfoElement); if ((!"".equals(oldDefinition) && "".equals(definitionURL)) || (!"".endsWith(oldDefinition) && !oldDefinition.equals(definitionURL))) { try { registry.removeAssociation(servicePath, oldDefinition, CommonConstants.DEPENDS); registry.removeAssociation(oldDefinition, servicePath, CommonConstants.USED_BY); EndpointUtils.removeEndpointEntry(oldDefinition, serviceInfoElement, registry); resource.setContent(RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes())); } catch (RegistryException e) { throw new RegistryException("Failed to remove endpoints from Service UI : "+serviceName,e); } } } boolean alreadyAdded = false; if (definitionURL != null && (definitionURL.startsWith("http://") || definitionURL.startsWith("https://"))) { String definitionPath; if(definitionURL.toLowerCase().endsWith("wsdl")) { wsdl = buildWSDLProcessor(requestContext); RequestContext context = new RequestContext(registry, requestContext.getRepository(), requestContext.getVersionRepository()); context.setResourcePath(new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wsdl")); context.setSourceURL(definitionURL); Resource tmpResource = new ResourceImpl(); tmpResource.setProperty("version", serviceVersion); tmpResource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO); context.setResource(tmpResource); definitionPath = wsdl.addWSDLToRegistry(context, definitionURL, null, false, false, disableWSDLValidation,disableSymlinkCreation); } else if(definitionURL.toLowerCase().endsWith("wadl")) { WADLProcessor wadlProcessor = buildWADLProcessor(requestContext); wadlProcessor.setCreateService(false); RequestContext context = new RequestContext(registry, requestContext.getRepository(), requestContext.getVersionRepository()); context.setResourcePath(new ResourcePath(RegistryConstants.PATH_SEPARATOR + serviceName + ".wadl")); context.setSourceURL(definitionURL); Resource tmpResource = new ResourceImpl(); tmpResource.setProperty("version", serviceVersion); tmpResource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO); context.setResource(tmpResource); definitionPath = wadlProcessor.importWADLToRegistry(context, null, disableWADLValidation); } else { throw new RegistryException("Invalid service definition found. " + "Please enter a valid WSDL/WADL URL"); } if (definitionPath == null) { return; } definitionURL = RegistryUtils.getRelativePath(requestContext.getRegistryContext(), definitionPath); CommonUtil.setDefinitionURL(serviceInfoElement, definitionURL); resource.setContent(RegistryUtils.decodeBytes((serviceInfoElement.toString()).getBytes())); // updating the wsdl/wadl url ((ResourceImpl) resource).prepareContentForPut(); persistServiceResource(registry, resource, servicePath); alreadyAdded = true; // and make the associations registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS); registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY); } else if (definitionURL != null && definitionURL.startsWith(RegistryConstants.ROOT_PATH)) { // it seems definitionUrl is a registry path.. String definitionPath = RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(), definitionURL); if (!definitionPath.startsWith(RegistryUtils.getAbsolutePath( requestContext.getRegistryContext(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH))) { definitionPath = RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + definitionPath; } boolean addItHere = false; if (!registry.resourceExists(definitionPath)) { String msg = "Associating service to a non-existing WSDL. wsdl url: " + definitionPath + ", " + "service path: " + servicePath + "."; log.error(msg); throw new RegistryException(msg); } if (!registry.resourceExists(servicePath)) { addItHere = true; } else { Association[] dependencies = registry.getAssociations(servicePath, CommonConstants.DEPENDS); boolean dependencyFound = false; if (dependencies != null) { for (Association dependency : dependencies) { if (definitionPath.equals(dependency.getDestinationPath())) { dependencyFound = true; } } } if (!dependencyFound) { addItHere = true; } } if (addItHere) { // add the service right here.. ((ResourceImpl) resource).prepareContentForPut(); persistServiceResource(registry, resource, servicePath); alreadyAdded = true; // and make the associations registry.addAssociation(servicePath, definitionPath, CommonConstants.DEPENDS); registry.addAssociation(definitionPath, servicePath, CommonConstants.USED_BY); } } if (!alreadyAdded) { // we are adding the resource anyway. ((ResourceImpl) resource).prepareContentForPut(); persistServiceResource(registry, resource, servicePath); } /* if (!servicePath.contains(registry.getRegistryContext().getServicePath())) { if (defaultEnvironment == null) { String serviceDefaultEnvironment = registry.getRegistryContext().getServicePath(); String relativePath = serviceDefaultEnvironment.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH, ""); relativePath = relativePath.replace(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace),""); defaultEnvironment = relativePath; } String currentRelativePath = servicePath.substring(0, servicePath.indexOf(CommonUtil.derivePathFragmentFromNamespace(serviceNamespace))); currentRelativePath = currentRelativePath.replace(RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH,""); String endpointEnv = EndpointUtils.getEndpointLocation(); String[] pathSegments = defaultEnvironment.split(RegistryConstants.PATH_SEPARATOR); for (String pathSegment : pathSegments) { endpointEnv = endpointEnv.replace(pathSegment,""); currentRelativePath = currentRelativePath.replace(pathSegment,""); } while(endpointEnv.startsWith(RegistryConstants.PATH_SEPARATOR)){ endpointEnv = endpointEnv.replaceFirst(RegistryConstants.PATH_SEPARATOR,""); } environment = currentRelativePath + endpointEnv; } */ if (definitionURL != null) { if (oldDefinition == null) { EndpointUtils.saveEndpointsFromServices(servicePath,serviceInfoElement, registry,CommonUtil.getUnchrootedSystemRegistry(requestContext)); } else if (oldDefinition != null && !definitionURL.equals(oldDefinition)){ EndpointUtils.saveEndpointsFromServices(servicePath,serviceInfoElement, registry,CommonUtil.getUnchrootedSystemRegistry(requestContext)); } } String symlinkLocation = RegistryUtils.getAbsolutePath(requestContext.getRegistryContext(), requestContext.getResource().getProperty(RegistryConstants.SYMLINK_PROPERTY_NAME)); if (!servicePath.equals(originalServicePath) && requestContext.getRegistry().resourceExists(originalServicePath)) { // we are creating a sym link from service path to original service path. Resource serviceResource = requestContext.getRegistry().get( RegistryUtils.getParentPath(originalServicePath)); String isLink = serviceResource.getProperty("registry.link"); String mountPoint = serviceResource.getProperty("registry.mountpoint"); String targetPoint = serviceResource.getProperty("registry.targetpoint"); String actualPath = serviceResource.getProperty("registry.actualpath"); if (isLink != null && mountPoint != null && targetPoint != null) { symlinkLocation = actualPath + RegistryConstants.PATH_SEPARATOR; } if (symlinkLocation != null) { requestContext.getSystemRegistry().createLink(symlinkLocation + resourceName, servicePath); } } // in this flow the resource is already added. marking the process completed.. requestContext.setProcessingComplete(true); if (wsdl != null && CommonConstants.ENABLE.equals(System.getProperty(CommonConstants.UDDI_SYSTEM_PROPERTY))) { AuthToken authToken = UDDIUtil.getPublisherAuthToken(); if (authToken == null) { return; } //creating the business service info bean BusinessServiceInfo businessServiceInfo = new BusinessServiceInfo(); //Following lines removed for fixing REGISTRY-1898. // businessServiceInfo.setServiceName(serviceName.trim()); // businessServiceInfo.setServiceNamespace(serviceNamespace.trim()); // businessServiceInfo.setServiceEndpoints(CommonUtil.getEndpointEntries(serviceInfoElement)); // businessServiceInfo.setDocuments(CommonUtil.getDocLinks(serviceInfoElement)); businessServiceInfo.setServiceDescription(CommonUtil.getServiceDescription(serviceInfoElement)); WSDLInfo wsdlInfo = wsdl.getMasterWSDLInfo(); businessServiceInfo.setServiceWSDLInfo(wsdlInfo); UDDIPublisher publisher = new UDDIPublisher(); publisher.publishBusinessService(authToken, businessServiceInfo); } String path = RegistryUtils.getRelativePathToOriginal(servicePath, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH); ArtifactManager.getArtifactManager().getTenantArtifactRepository().addArtifact(path); } finally { CommonUtil.releaseUpdateLock(); } } /** * Method to customize the WSDL Processor. * @param requestContext the request context for the import/put operation * @return the WSDL Processor instance. */ @SuppressWarnings("unused") protected WSDLProcessor buildWSDLProcessor(RequestContext requestContext) { return new WSDLProcessor(requestContext); } /** * Method to customize the WADL Processor. * @param requestContext the request context for the import/put operation * @return the WADL Processor instance. */ @SuppressWarnings("unused") protected WADLProcessor buildWADLProcessor(RequestContext requestContext) { return new WADLProcessor(requestContext); } private void persistServiceResource(Registry registry, Resource resource, String servicePath) throws RegistryException { registry.put(servicePath, resource); } public void setDisableWSDLValidation(String disableWSDLValidation) { this.disableWSDLValidation = Boolean.toString(true).equals(disableWSDLValidation); } public void setDisableWADLValidation(String disableWADLValidation) { this.disableWADLValidation = Boolean.getBoolean(disableWADLValidation); } public String mergeServiceContent(String newContent, String oldContent) { return newContent; } @Override public void delete(RequestContext requestContext) throws RegistryException { if (!CommonUtil.isUpdateLockAvailable()) { return; } CommonUtil.acquireUpdateLock(); try { Registry registry = requestContext.getRegistry(); ResourcePath resourcePath = requestContext.getResourcePath(); if (resourcePath == null) { throw new RegistryException("The resource path is not available."); } Resource resource = registry.get(resourcePath.getPath()); } finally { CommonUtil.releaseUpdateLock(); } } }
{'content_hash': '978a3dfc165a2d06ee37ff9568b7cdf2', 'timestamp': '', 'source': 'github', 'line_count': 491, 'max_line_length': 153, 'avg_line_length': 53.26272912423625, 'alnum_prop': 0.6024395839706332, 'repo_name': 'prasa7/carbon-registry', 'id': '1189f8aa051a85fee810450150003b1621e6c095', 'size': '26819', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'components/registry/org.wso2.carbon.registry.extensions/src/main/java/org/wso2/carbon/registry/extensions/handlers/ServiceMediaTypeHandler.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '55076'}, {'name': 'CSS', 'bytes': '41227'}, {'name': 'HTML', 'bytes': '44327'}, {'name': 'Java', 'bytes': '5195559'}, {'name': 'JavaScript', 'bytes': '302871'}, {'name': 'PLSQL', 'bytes': '182616'}, {'name': 'Shell', 'bytes': '70140'}, {'name': 'XSLT', 'bytes': '76117'}]}
geocoder ======== Geocoding service based on TIGER files Steps to set up: * Install gdal (http://www.gdal.org/) * Get TIGER shape files (http://www.census.gov/geo/maps-data/data/tiger-line.html) * Convert shapefile to GeoJSON: ```ogr2ogr -f "GeoJSON" output_features.json input_features.shp``` * load into mongo ```mongoimport -d geo -c features output_features.json``` * convert address range fields to numbers and save street name as uppercase: ``` db.features.find({properties: {$exists:true}, "properties.FULLNAME" : {$ne: null}}).forEach( function(doc) { db.features.update( { _id: doc._id}, { $set : { "nameupper": doc.properties.FULLNAME.toUpperCase().replace("NORTH ","N ").replace("SOUTH ","S ").replace("EAST ","E ").replace("WEST ","W ") , "properties.RFROMADD" : parseInt(doc.properties.RFROMADD), "properties.RTOADD" : parseInt(doc.properties.RTOADD), "properties.LFROMADD" : parseInt(doc.properties.LFROMADD), "properties.LTOADD" : parseInt(doc.properties.LTOADD) } } ) }) ``` * create spatial index (from mongo shell): ``` db.features.ensureIndex({geometry:"2dsphere"}) ``` * test the query: ``` db.features.find( { geometry : {$nearSphere : { $geometry : { type: "Point" , coordinates: [-78.767779, 43.034796]}, $maxDistance: 100 }}}) ```
{'content_hash': '7109214d5119eb223a7f83f88a407dff', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 147, 'avg_line_length': 33.46153846153846, 'alnum_prop': 0.6704980842911877, 'repo_name': 'cfagiani/geocoder', 'id': 'ad835307bf1e2aed5b7e2eb90fc9cb7ddf3c74c4', 'size': '1305', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '9252'}]}
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isWindows = require('is-windows'); var _isWindows2 = _interopRequireDefault(_isWindows); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = commandConvert; /** * Converts an environment variable usage to be appropriate for the current OS * @param {String} command Command to convert * @returns {String} Converted command */ function commandConvert(command) { if (!(0, _isWindows2.default)()) { return command; } var envUnixRegex = /\$(\w+)|\${(\w+)}/g; // $my_var or ${my_var} return command.replace(envUnixRegex, '%$1$2%'); }
{'content_hash': '859f6f052de398d77668460f8447fa1d', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 95, 'avg_line_length': 25.77777777777778, 'alnum_prop': 0.6752873563218391, 'repo_name': 'Oritechnology/pubApp', 'id': 'f0d808a3914ad60b465ecb639898244afd1091d8', 'size': '696', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'node_modules/cross-env/dist/command.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '781'}, {'name': 'HTML', 'bytes': '1629'}, {'name': 'JavaScript', 'bytes': '86639'}, {'name': 'Shell', 'bytes': '1794'}]}
var expect = require("chai").expect; var sinon = require("sinon"); var ReadlineStub = require("../../helpers/readline"); var Base = require("../../../lib/prompts/base"); // Prevent prompt from writing to screen // Confirm.prototype.write = function() { return this; }; describe("`base` prompt (e.g. prompt helpers)", function() { beforeEach(function() { this.rl = new ReadlineStub(); this.base = new Base({ message: "foo bar", name: "name" }, this.rl ); }); it("`suffix` method should only add ':' if last char is a letter", function() { expect(this.base.suffix("m:")).to.equal("m: "); expect(this.base.suffix("m?")).to.equal("m? "); expect(this.base.suffix("m")).to.equal("m: "); expect(this.base.suffix("m ")).to.equal("m "); expect(this.base.suffix()).to.equal(": "); }); });
{'content_hash': '7b46ad1d199c6c5a839c95b9d779b539', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 81, 'avg_line_length': 29.892857142857142, 'alnum_prop': 0.5985663082437276, 'repo_name': 'ricklon/AngBootExpress', 'id': 'e993b9831a69ec92f6207ea4a6c8286ba1d9a88a', 'size': '837', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'node_modules/bower/node_modules/inquirer/test/node_modules/inquirer/test/specs/prompts/base.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '233569'}, {'name': 'JavaScript', 'bytes': '558815'}]}
#if !defined(_TOOLEVENT_H_) #define _TOOLEVENT_H_ namespace Executor { typedef struct PACKED { INTEGER version; INTEGER tableno[256]; INTEGER ntables; Byte table[1][128]; /* who knows how many */ } keymap; extern void dofloppymount (void); extern BOOLEAN ROMlib_beepedonce; extern void ROMlib_send_quit (void); } extern "C" int ROMlib_right_button_modifier; #endif /* !_TOOLEVENT_H_ */
{'content_hash': '930fc3b3f56e8bee712dbc44853c6861', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 48, 'avg_line_length': 19.428571428571427, 'alnum_prop': 0.696078431372549, 'repo_name': 'MaddTheSane/executor', 'id': '3bf56e4ccaf24bd02277711e08336530e9dbce16', 'size': '550', 'binary': False, 'copies': '1', 'ref': 'refs/heads/CppPort', 'path': 'src/include/rsys/toolevent.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '78587'}, {'name': 'Awk', 'bytes': '5579'}, {'name': 'C', 'bytes': '1598474'}, {'name': 'C++', 'bytes': '4606280'}, {'name': 'GDB', 'bytes': '36'}, {'name': 'Inno Setup', 'bytes': '25291'}, {'name': 'M4', 'bytes': '5802'}, {'name': 'Makefile', 'bytes': '62397'}, {'name': 'Mathematica', 'bytes': '9405'}, {'name': 'NewLisp', 'bytes': '35906'}, {'name': 'Objective-C', 'bytes': '25209'}, {'name': 'Objective-C++', 'bytes': '101300'}, {'name': 'Perl', 'bytes': '33397'}, {'name': 'Perl 6', 'bytes': '2970'}, {'name': 'Roff', 'bytes': '19007'}, {'name': 'Shell', 'bytes': '65013'}, {'name': 'Yacc', 'bytes': '27639'}]}
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.Routing.Configuration { using System; using System.Xml; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Text; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using SR2 = System.ServiceModel.Routing.SR; public class RoutingSection : ConfigurationSection { [ConfigurationProperty(ConfigurationStrings.Filters, Options = ConfigurationPropertyOptions.None)] public FilterElementCollection Filters { get { return (FilterElementCollection)base[ConfigurationStrings.Filters]; } } [ConfigurationProperty(ConfigurationStrings.FilterTables, Options = ConfigurationPropertyOptions.None)] public FilterTableCollection FilterTables { get { return (FilterTableCollection)base[ConfigurationStrings.FilterTables]; } } [ConfigurationProperty(ConfigurationStrings.BackupLists, Options = ConfigurationPropertyOptions.None)] public BackupListCollection BackupLists { get { return (BackupListCollection)base[ConfigurationStrings.BackupLists]; } } [ConfigurationProperty(ConfigurationStrings.NamespaceTable, Options = ConfigurationPropertyOptions.None)] public NamespaceElementCollection NamespaceTable { get { return (NamespaceElementCollection)base[ConfigurationStrings.NamespaceTable]; } } public static MessageFilterTable<IEnumerable<ServiceEndpoint>> CreateFilterTable(string name) { if (string.IsNullOrEmpty(name)) { throw FxTrace.Exception.ArgumentNullOrEmpty("name"); } RoutingSection routingSection = (RoutingSection)ConfigurationManager.GetSection("system.serviceModel/routing"); if (routingSection == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.RoutingSectionNotFound)); } FilterTableEntryCollection routingTableElement = routingSection.FilterTables[name]; if (routingTableElement == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.RoutingTableNotFound(name))); } XmlNamespaceManager xmlNamespaces = new XPathMessageContext(); foreach (NamespaceElement nsElement in routingSection.NamespaceTable) { xmlNamespaces.AddNamespace(nsElement.Prefix, nsElement.Namespace); } FilterElementCollection filterElements = routingSection.Filters; MessageFilterTable<IEnumerable<ServiceEndpoint>> routingTable = new MessageFilterTable<IEnumerable<ServiceEndpoint>>(); foreach (FilterTableEntryElement entry in routingTableElement) { FilterElement filterElement = filterElements[entry.FilterName]; if (filterElement == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.FilterElementNotFound(entry.FilterName))); } MessageFilter filter = filterElement.CreateFilter(xmlNamespaces, filterElements); //retreive alternate service endpoints IList<ServiceEndpoint> endpoints = new List<ServiceEndpoint>(); if (!string.IsNullOrEmpty(entry.BackupList)) { BackupEndpointCollection alternateEndpointListElement = routingSection.BackupLists[entry.BackupList]; if (alternateEndpointListElement == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR2.BackupListNotFound(entry.BackupList))); } endpoints = alternateEndpointListElement.CreateAlternateEndpoints(); } //add first endpoint to beginning of list endpoints.Insert(0, ClientEndpointLoader.LoadEndpoint(entry.EndpointName)); routingTable.Add(filter, endpoints, entry.Priority); } return routingTable; } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")] [ConfigurationCollection(typeof(FilterTableEntryCollection), AddItemName = ConfigurationStrings.FilterTable)] public class FilterTableCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new FilterTableEntryCollection(); } protected override object GetElementKey(ConfigurationElement element) { return ((FilterTableEntryCollection)element).Name; } public void Add(FilterTableEntryCollection element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseAdd(element); } public void Clear() { BaseClear(); } public void Remove(FilterTableEntryCollection element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseRemove(this.GetElementKey(element)); } new public FilterTableEntryCollection this[string name] { get { return (FilterTableEntryCollection)BaseGet(name); } } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")] [ConfigurationCollection(typeof(FilterTableEntryElement))] public class FilterTableEntryCollection : ConfigurationElementCollection { [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Name, DefaultValue = null, Options = ConfigurationPropertyOptions.IsKey | ConfigurationPropertyOptions.IsRequired)] public string Name { get { return (string)this[ConfigurationStrings.Name]; } set { this[ConfigurationStrings.Name] = value; } } protected override ConfigurationElement CreateNewElement() { return new FilterTableEntryElement(); } protected override object GetElementKey(ConfigurationElement element) { FilterTableEntryElement entry = (FilterTableEntryElement)element; return entry.FilterName + ":" + entry.EndpointName; } public void Add(FilterTableEntryElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseAdd(element); } public void Clear() { BaseClear(); } public void Remove(FilterTableEntryElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseRemove(this.GetElementKey(element)); } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")] [ConfigurationCollection(typeof(BackupEndpointCollection), AddItemName = ConfigurationStrings.BackupList)] public class BackupListCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new BackupEndpointCollection(); } protected override object GetElementKey(ConfigurationElement element) { return ((BackupEndpointCollection)element).Name; } public void Add(BackupEndpointCollection element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseAdd(element); } public void Clear() { BaseClear(); } public void Remove(BackupEndpointCollection element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseRemove(this.GetElementKey(element)); } new public BackupEndpointCollection this[string name] { get { return (BackupEndpointCollection)BaseGet(name); } } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")] [ConfigurationCollection(typeof(BackupEndpointElement))] public class BackupEndpointCollection : ConfigurationElementCollection { [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Name, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)] public string Name { get { return (string)this[ConfigurationStrings.Name]; } set { this[ConfigurationStrings.Name] = value; } } protected override ConfigurationElement CreateNewElement() { return new BackupEndpointElement(); } protected override object GetElementKey(ConfigurationElement element) { BackupEndpointElement entry = (BackupEndpointElement)element; return entry.Key; } public void Add(BackupEndpointElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseAdd(element); } public void Clear() { BaseClear(); } public void Remove(BackupEndpointElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseRemove(this.GetElementKey(element)); } internal IList<ServiceEndpoint> CreateAlternateEndpoints() { IList<ServiceEndpoint> toReturn = new List<ServiceEndpoint>(); foreach (BackupEndpointElement entryElement in this) { ServiceEndpoint serviceEnpoint = ClientEndpointLoader.LoadEndpoint(entryElement.EndpointName); toReturn.Add(serviceEnpoint); } return toReturn; } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")] [ConfigurationCollection(typeof(FilterElement), AddItemName = ConfigurationStrings.Filter)] public class FilterElementCollection : ConfigurationElementCollection { public override bool IsReadOnly() { return false; } protected override bool IsElementRemovable(ConfigurationElement element) { return true; } protected override ConfigurationElement CreateNewElement() { return new FilterElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((FilterElement)element).Name; } public void Add(FilterElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseAdd(element); } public void Clear() { BaseClear(); } public void Remove(FilterElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseRemove(this.GetElementKey(element)); } public FilterElement this[int index] { get { return (FilterElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } new public FilterElement this[string name] { get { return (FilterElement)BaseGet(name); } } } [SuppressMessage(FxCop.Category.Design, FxCop.Rule.CollectionsShouldImplementGenericInterface, Justification = "generic interface not needed for config")] [ConfigurationCollection(typeof(NamespaceElement))] public class NamespaceElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new NamespaceElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((NamespaceElement)element).Prefix; } public void Add(NamespaceElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseAdd(element); } public void Clear() { BaseClear(); } public void Remove(NamespaceElement element) { if (!this.IsReadOnly()) { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } } BaseRemove(this.GetElementKey(element)); } public NamespaceElement this[int index] { get { return (NamespaceElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } new public NamespaceElement this[string name] { get { return (NamespaceElement)BaseGet(name); } } } public class FilterElement : ConfigurationElement { [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Name, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)] public string Name { get { return (string)this[ConfigurationStrings.Name]; } set { this[ConfigurationStrings.Name] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like validator")] [ConfigurationProperty(ConfigurationStrings.FilterType, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired)] public FilterType FilterType { get { return (FilterType)this[ConfigurationStrings.FilterType]; } set { if (value < FilterType.Action || value > FilterType.XPath) { throw FxTrace.Exception.AsError(new ArgumentOutOfRangeException("value")); } this[ConfigurationStrings.FilterType] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.FilterData, DefaultValue = null, Options = ConfigurationPropertyOptions.None)] public string FilterData { get { return (string)this[ConfigurationStrings.FilterData]; } set { this[ConfigurationStrings.FilterData] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Filter1, DefaultValue = null, Options = ConfigurationPropertyOptions.None)] public string Filter1 { get { return (string)this[ConfigurationStrings.Filter1]; } set { this[ConfigurationStrings.Filter1] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Filter2, DefaultValue = null, Options = ConfigurationPropertyOptions.None)] public string Filter2 { get { return (string)this[ConfigurationStrings.Filter2]; } set { this[ConfigurationStrings.Filter2] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.CustomType, DefaultValue = null, Options = ConfigurationPropertyOptions.None)] public string CustomType { get { return (string)this[ConfigurationStrings.CustomType]; } set { this[ConfigurationStrings.CustomType] = value; } } internal MessageFilter CreateFilter(XmlNamespaceManager xmlNamespaces, FilterElementCollection filters) { MessageFilter filter; switch (this.FilterType) { case FilterType.Action: filter = new ActionMessageFilter(this.FilterData); break; case FilterType.EndpointAddress: filter = new EndpointAddressMessageFilter(new EndpointAddress(this.FilterData), false); break; case FilterType.PrefixEndpointAddress: filter = new PrefixEndpointAddressMessageFilter(new EndpointAddress(this.FilterData), false); break; case FilterType.And: MessageFilter filter1 = filters[this.Filter1].CreateFilter(xmlNamespaces, filters); MessageFilter filter2 = filters[this.Filter2].CreateFilter(xmlNamespaces, filters); filter = new StrictAndMessageFilter(filter1, filter2); break; case FilterType.EndpointName: filter = new EndpointNameMessageFilter(this.FilterData); break; case FilterType.MatchAll: filter = new MatchAllMessageFilter(); break; case FilterType.Custom: filter = CreateCustomFilter(this.CustomType, this.FilterData); break; case FilterType.XPath: filter = new XPathMessageFilter(this.FilterData, xmlNamespaces); break; default: // We can't really ever get here because set_FilterType performs validation. throw FxTrace.Exception.AsError(new InvalidOperationException()); } return filter; } static MessageFilter CreateCustomFilter(string customType, string filterData) { if (string.IsNullOrEmpty(customType)) { throw FxTrace.Exception.ArgumentNullOrEmpty("customType"); } Type customFilterType = Type.GetType(customType, true); return (MessageFilter)Activator.CreateInstance(customFilterType, filterData); } } public class NamespaceElement : ConfigurationElement { [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Prefix, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)] public string Prefix { get { return (string)this[ConfigurationStrings.Prefix]; } set { this[ConfigurationStrings.Prefix] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.Namespace, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired)] public string Namespace { get { return (string)this[ConfigurationStrings.Namespace]; } set { this[ConfigurationStrings.Namespace] = value; } } } public class FilterTableEntryElement : ConfigurationElement { [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.FilterName, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)] public string FilterName { get { return (string)this[ConfigurationStrings.FilterName]; } set { this[ConfigurationStrings.FilterName] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationPropertyNameRule, Justification = "fxcop rule throws null ref if fixed")] [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.EndpointName, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)] public string EndpointName { get { return (string)this[ConfigurationStrings.EndpointName]; } set { this[ConfigurationStrings.EndpointName] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like IntegerValidator")] [ConfigurationProperty(ConfigurationStrings.Priority, DefaultValue = 0, Options = ConfigurationPropertyOptions.None)] public int Priority { get { return (int)this[ConfigurationStrings.Priority]; } set { this[ConfigurationStrings.Priority] = value; } } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.BackupList, DefaultValue = null, Options = ConfigurationPropertyOptions.None)] public string BackupList { get { return (string)this[ConfigurationStrings.BackupList]; } set { this[ConfigurationStrings.BackupList] = value; } } } public class BackupEndpointElement : ConfigurationElement { public BackupEndpointElement() { this.Key = new object(); } //needed to allow duplicate alternate endpoints internal object Key { get; private set; } [SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "fxcop didn't like [StringValidator(MinLength = 0)]")] [ConfigurationProperty(ConfigurationStrings.EndpointName, DefaultValue = null, Options = ConfigurationPropertyOptions.IsRequired)] public string EndpointName { get { return (string)this[ConfigurationStrings.EndpointName]; } set { this[ConfigurationStrings.EndpointName] = value; } } } }
{'content_hash': '75fea1fa9a6f382a5d8a81e1819b03b3', 'timestamp': '', 'source': 'github', 'line_count': 742, 'max_line_length': 175, 'avg_line_length': 36.32749326145552, 'alnum_prop': 0.5856798367649787, 'repo_name': 'mono/referencesource', 'id': '49f888f0e29168ee724ed5f5aa50c995abd22620', 'size': '26957', 'binary': False, 'copies': '17', 'ref': 'refs/heads/mono', 'path': 'System.ServiceModel.Routing/System/ServiceModel/Routing/Configuration/RoutingSection.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '155045910'}]}
package org.pocketcampus.platform.android.ui.layout; import org.pocketcampus.platform.android.R; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; /** * A <code>RelativeLayout</code> with a centered message and a title at the top. * You can add two inner layouts in the outer <code>RelativeLayout</code>. * * @author Oriane <[email protected]> */ public class StandardTitledDoubleSeparatedLayout extends RelativeLayout { /** The main layout containing both titles and the centered text. */ private RelativeLayout mLayout; /** The first inner layout, below the title. */ private RelativeLayout mFillerLayout1; /** The second inner layout, below the first one. */ private RelativeLayout mFillerLayout2; /** The first title of the Layout. */ private TextView mTitle1TextView; /** The second title of the Layout. */ private TextView mTitle2TextView; /** The <code>TextView</code> displayed at the center of the main layout. */ private TextView mMessageTextView; /** * Class constructor initializing the context and the attributes. * * @param context * The application context. * @param attrs * The attributes to set for this layout. */ public StandardTitledDoubleSeparatedLayout(Context context, AttributeSet attrs) { super(context, attrs); initialize(context); } /** * Class constructor initializing the context. * * @param context * The application context. */ public StandardTitledDoubleSeparatedLayout(Context context) { super(context); initialize(context); } /** * Initializes the layout. * * @param context * The application context. */ private void initialize(Context context) { LayoutInflater inflater = LayoutInflater.from(context); mLayout = (RelativeLayout) inflater.inflate( R.layout.sdk_standard_titled_double_separated_layout, null); super.addView(mLayout); mTitle1TextView = (TextView) findViewById(R.id.sdk_standard_titled_double_separated_layout_title1); mTitle2TextView = (TextView) findViewById(R.id.sdk_standard_titled_double_separated_layout_title2); mMessageTextView = (TextView) findViewById(R.id.sdk_standard_titled_double_separated_layout_msg); mFillerLayout1 = (RelativeLayout) findViewById(R.id.sdk_standard_titled_double_separated_layout_filler1); mFillerLayout2 = (RelativeLayout) findViewById(R.id.sdk_standard_titled_double_separated_layout_filler2); } /** * Displays a centered message. * * @param text * The text to display. */ public void setText(String text) { mMessageTextView.setText(text); mMessageTextView.setVisibility(View.VISIBLE); } /** * Displays a message in the first title. * * @param text * The text of the title to display */ public void setFirstTitle(String text) { mTitle1TextView.setText(text); mTitle1TextView.setVisibility(View.VISIBLE); } /** * Displays a message in the second title. * * @param text * The text of the title to display */ public void setSecondTitle(String text) { mTitle2TextView.setText(text); mTitle2TextView.setVisibility(View.VISIBLE); } /** * Hides the centered message. */ public void hideText() { mMessageTextView.setVisibility(View.GONE); } /** * Hides the first title. */ public void hideFirstTitle() { mTitle1TextView.setVisibility(View.GONE); } /** * Hides the second title. */ public void hideSecondTitle() { mTitle2TextView.setVisibility(View.GONE); } /** * Adds a view to the layout. * * @param child * The view to add to the layout. */ @Override public void addView(View child) { mLayout.addView(child); } /** * Adds a view to the first inner layout, below the title. * * @param child * The view to add to the first inner layout. */ public void addFirstLayoutFillerView(View child) { mFillerLayout1.addView(child); } /** * Removes all views from the first inner layout, below the title. */ public void removeFirstLayoutFillerView() { mFillerLayout1.removeAllViews(); } /** * Adds a view to the second inner layout, below the first inner layout. * * @param child * The view to add to the second inner layout. */ public void addSecondLayoutFillerView(View child) { mFillerLayout2.addView(child); } /** * Removes all views from the second inner layout, below the first inner * layout. */ public void removeSecondLayoutFillerView() { mFillerLayout2.removeAllViews(); } }
{'content_hash': '32a5a41f8ef09f5e43b64fa04ab4e2a7', 'timestamp': '', 'source': 'github', 'line_count': 175, 'max_line_length': 107, 'avg_line_length': 26.731428571428573, 'alnum_prop': 0.7073535699016674, 'repo_name': 'ValentinMinder/pocketcampus', 'id': '00550bb84b4d1b03ad183d3146f978410d982cca', 'size': '4678', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'platform/android/src/main/java/org/pocketcampus/platform/android/ui/layout/StandardTitledDoubleSeparatedLayout.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '876'}, {'name': 'C', 'bytes': '24548'}, {'name': 'C#', 'bytes': '934103'}, {'name': 'CSS', 'bytes': '33788'}, {'name': 'HTML', 'bytes': '393132'}, {'name': 'Java', 'bytes': '1971771'}, {'name': 'JavaScript', 'bytes': '120550'}, {'name': 'Objective-C', 'bytes': '3611367'}, {'name': 'PHP', 'bytes': '363528'}, {'name': 'Python', 'bytes': '52585'}, {'name': 'Ruby', 'bytes': '6419'}, {'name': 'Shell', 'bytes': '11498'}, {'name': 'Thrift', 'bytes': '37896'}]}
package storage import ( "sync" "testing" "time" "github.com/cockroachdb/cockroach/roachpb" "github.com/cockroachdb/cockroach/util/leaktest" ) func getWait(cq *CommandQueue, from, to roachpb.Key, readOnly bool, wg *sync.WaitGroup) { cq.GetWait(readOnly, wg, roachpb.Span{Key: from, EndKey: to}) } func add(cq *CommandQueue, from, to roachpb.Key, readOnly bool) interface{} { return cq.Add(readOnly, roachpb.Span{Key: from, EndKey: to})[0] } // waitForCmd launches a goroutine to wait on the supplied // WaitGroup. A channel is returned which signals the completion of // the wait. func waitForCmd(wg *sync.WaitGroup) <-chan struct{} { cmdDone := make(chan struct{}) go func() { wg.Wait() close(cmdDone) }() return cmdDone } // testCmdDone waits for the cmdDone channel to be closed for at most // the specified wait duration. Returns true if the command finished in // the allotted time, false otherwise. func testCmdDone(cmdDone <-chan struct{}, wait time.Duration) bool { select { case <-cmdDone: return true case <-time.After(wait): return false } } func TestCommandQueue(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() wg := sync.WaitGroup{} // Try a command with no overlapping already-running commands. getWait(cq, roachpb.Key("a"), nil, false, &wg) wg.Wait() getWait(cq, roachpb.Key("a"), roachpb.Key("b"), false, &wg) wg.Wait() // Add a command and verify wait group is returned. wk := add(cq, roachpb.Key("a"), nil, false) getWait(cq, roachpb.Key("a"), nil, false, &wg) cmdDone := waitForCmd(&wg) if testCmdDone(cmdDone, 1*time.Millisecond) { t.Fatal("command should not finish with command outstanding") } cq.Remove([]interface{}{wk}) if !testCmdDone(cmdDone, 5*time.Millisecond) { t.Fatal("command should finish with no commands outstanding") } } func TestCommandQueueNoWaitOnReadOnly(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() wg := sync.WaitGroup{} // Add a read-only command. wk := add(cq, roachpb.Key("a"), nil, true) // Verify no wait on another read-only command. getWait(cq, roachpb.Key("a"), nil, true, &wg) wg.Wait() // Verify wait with a read-write command. getWait(cq, roachpb.Key("a"), nil, false, &wg) cmdDone := waitForCmd(&wg) if testCmdDone(cmdDone, 1*time.Millisecond) { t.Fatal("command should not finish with command outstanding") } cq.Remove([]interface{}{wk}) if !testCmdDone(cmdDone, 5*time.Millisecond) { t.Fatal("command should finish with no commands outstanding") } } func TestCommandQueueMultipleExecutingCommands(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() wg := sync.WaitGroup{} // Add multiple commands and add a command which overlaps them all. wk1 := add(cq, roachpb.Key("a"), nil, false) wk2 := add(cq, roachpb.Key("b"), roachpb.Key("c"), false) wk3 := add(cq, roachpb.Key("0"), roachpb.Key("d"), false) getWait(cq, roachpb.Key("a"), roachpb.Key("cc"), false, &wg) cmdDone := waitForCmd(&wg) cq.Remove([]interface{}{wk1}) if testCmdDone(cmdDone, 1*time.Millisecond) { t.Fatal("command should not finish with two commands outstanding") } cq.Remove([]interface{}{wk2}) if testCmdDone(cmdDone, 1*time.Millisecond) { t.Fatal("command should not finish with one command outstanding") } cq.Remove([]interface{}{wk3}) if !testCmdDone(cmdDone, 5*time.Millisecond) { t.Fatal("command should finish with no commands outstanding") } } func TestCommandQueueMultiplePendingCommands(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() wg1 := sync.WaitGroup{} wg2 := sync.WaitGroup{} wg3 := sync.WaitGroup{} // Add a command which will overlap all commands. wk := add(cq, roachpb.Key("a"), roachpb.Key("d"), false) getWait(cq, roachpb.Key("a"), nil, false, &wg1) getWait(cq, roachpb.Key("b"), nil, false, &wg2) getWait(cq, roachpb.Key("c"), nil, false, &wg3) cmdDone1 := waitForCmd(&wg1) cmdDone2 := waitForCmd(&wg2) cmdDone3 := waitForCmd(&wg3) if testCmdDone(cmdDone1, 1*time.Millisecond) || testCmdDone(cmdDone2, 1*time.Millisecond) || testCmdDone(cmdDone3, 1*time.Millisecond) { t.Fatal("no commands should finish with command outstanding") } cq.Remove([]interface{}{wk}) if !testCmdDone(cmdDone1, 5*time.Millisecond) || !testCmdDone(cmdDone2, 5*time.Millisecond) || !testCmdDone(cmdDone3, 5*time.Millisecond) { t.Fatal("commands should finish with no commands outstanding") } } func TestCommandQueueClear(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() wg1 := sync.WaitGroup{} wg2 := sync.WaitGroup{} // Add multiple commands and commands which access each. add(cq, roachpb.Key("a"), nil, false) add(cq, roachpb.Key("b"), nil, false) getWait(cq, roachpb.Key("a"), nil, false, &wg1) getWait(cq, roachpb.Key("b"), nil, false, &wg2) cmdDone1 := waitForCmd(&wg1) cmdDone2 := waitForCmd(&wg2) // Clear the queue and verify both commands are signaled. cq.Clear() if !testCmdDone(cmdDone1, 100*time.Millisecond) || !testCmdDone(cmdDone2, 100*time.Millisecond) { t.Fatal("commands should finish when clearing queue") } } // TestCommandQueueExclusiveEnd verifies that an end key is treated as // an exclusive end when GetWait calculates overlapping commands. Test // it by calling GetWait with a command whose start key is equal to // the end key of a previous command. func TestCommandQueueExclusiveEnd(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() add(cq, roachpb.Key("a"), roachpb.Key("b"), false) wg := sync.WaitGroup{} getWait(cq, roachpb.Key("b"), nil, false, &wg) // Verify no wait on the second writer command on "b" since // it does not overlap with the first command on ["a", "b"). wg.Wait() } // TestCommandQueueSelfOverlap makes sure that GetWait adds all of the // key ranges simultaneously. If that weren't the case, all but the first // span would wind up waiting on overlapping previous spans, resulting // in deadlock. func TestCommandQueueSelfOverlap(t *testing.T) { defer leaktest.AfterTest(t) cq := NewCommandQueue() a := roachpb.Key("a") k := add(cq, a, roachpb.Key("b"), false) var wg sync.WaitGroup cq.GetWait(false, &wg, []roachpb.Span{{Key: a}, {Key: a}, {Key: a}}...) cq.Remove([]interface{}{k}) wg.Wait() }
{'content_hash': 'd40e7dd1e0bf06d3eb73bb68dc114e06', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 89, 'avg_line_length': 32.10769230769231, 'alnum_prop': 0.7069158281424692, 'repo_name': 'jmank88/cockroach', 'id': 'cb38685551ce636c7214a458e969c7e0ccbbea10', 'size': '6970', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'storage/command_queue_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '1016'}, {'name': 'C', 'bytes': '6708'}, {'name': 'C++', 'bytes': '43530'}, {'name': 'CSS', 'bytes': '15025'}, {'name': 'Go', 'bytes': '3431402'}, {'name': 'HTML', 'bytes': '4293'}, {'name': 'JavaScript', 'bytes': '1304'}, {'name': 'Makefile', 'bytes': '15714'}, {'name': 'Protocol Buffer', 'bytes': '108526'}, {'name': 'Shell', 'bytes': '19159'}, {'name': 'TypeScript', 'bytes': '128902'}, {'name': 'Yacc', 'bytes': '86190'}]}
module Faq class Initializer Cms::Node.plugin "faq/page" Cms::Node.plugin "faq/search" Cms::Part.plugin "faq/search" Cms::Role.permission :read_other_faq_pages Cms::Role.permission :read_private_faq_pages Cms::Role.permission :edit_other_faq_pages Cms::Role.permission :edit_private_faq_pages Cms::Role.permission :delete_other_faq_pages Cms::Role.permission :delete_private_faq_pages Cms::Role.permission :release_other_faq_pages Cms::Role.permission :release_private_faq_pages Cms::Role.permission :approve_other_faq_pages Cms::Role.permission :approve_private_faq_pages Cms::Role.permission :reroute_other_faq_pages Cms::Role.permission :reroute_private_faq_pages Cms::Role.permission :revoke_other_faq_pages Cms::Role.permission :revoke_private_faq_pages Cms::Role.permission :move_private_faq_pages Cms::Role.permission :move_other_faq_pages Cms::Role.permission :import_private_faq_pages Cms::Role.permission :import_other_faq_pages Cms::Role.permission :unlock_other_faq_pages end end
{'content_hash': '6802d6b5422e68b8f77014125ede361c', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 51, 'avg_line_length': 40.18518518518518, 'alnum_prop': 0.7290322580645161, 'repo_name': 'mizoki/shirasagi', 'id': 'aee313843de34c1645048baeab5514db5609cfd1', 'size': '1085', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'app/models/faq/initializer.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '501934'}, {'name': 'HTML', 'bytes': '2677091'}, {'name': 'JavaScript', 'bytes': '4925987'}, {'name': 'Ruby', 'bytes': '6394316'}, {'name': 'Shell', 'bytes': '20799'}]}
/*************************************************************************/ /* animation.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "animation.h" #include "geometry.h" bool Animation::_set(const StringName &p_name, const Variant &p_value) { String name = p_name; if (name == "length") set_length(p_value); else if (name == "loop") set_loop(p_value); else if (name == "step") set_step(p_value); else if (name.begins_with("tracks/")) { int track = name.get_slicec('/', 1).to_int(); String what = name.get_slicec('/', 2); if (tracks.size() == track && what == "type") { String type = p_value; if (type == "transform") { add_track(TYPE_TRANSFORM); } else if (type == "value") { add_track(TYPE_VALUE); } else if (type == "method") { add_track(TYPE_METHOD); } else { return false; } return true; } ERR_FAIL_INDEX_V(track, tracks.size(), false); if (what == "path") track_set_path(track, p_value); else if (what == "interp") track_set_interpolation_type(track, InterpolationType(p_value.operator int())); else if (what == "loop_wrap") track_set_interpolation_loop_wrap(track, p_value); else if (what == "imported") track_set_imported(track, p_value); else if (what == "keys" || what == "key_values") { if (track_get_type(track) == TYPE_TRANSFORM) { TransformTrack *tt = static_cast<TransformTrack *>(tracks[track]); PoolVector<float> values = p_value; int vcount = values.size(); ERR_FAIL_COND_V(vcount % 12, false); // shuld be multiple of 11 PoolVector<float>::Read r = values.read(); tt->transforms.resize(vcount / 12); for (int i = 0; i < (vcount / 12); i++) { TKey<TransformKey> &tk = tt->transforms[i]; const float *ofs = &r[i * 12]; tk.time = ofs[0]; tk.transition = ofs[1]; tk.value.loc.x = ofs[2]; tk.value.loc.y = ofs[3]; tk.value.loc.z = ofs[4]; tk.value.rot.x = ofs[5]; tk.value.rot.y = ofs[6]; tk.value.rot.z = ofs[7]; tk.value.rot.w = ofs[8]; tk.value.scale.x = ofs[9]; tk.value.scale.y = ofs[10]; tk.value.scale.z = ofs[11]; } } else if (track_get_type(track) == TYPE_VALUE) { ValueTrack *vt = static_cast<ValueTrack *>(tracks[track]); Dictionary d = p_value; ERR_FAIL_COND_V(!d.has("times"), false); ERR_FAIL_COND_V(!d.has("values"), false); if (d.has("cont")) { bool v = d["cont"]; vt->update_mode = v ? UPDATE_CONTINUOUS : UPDATE_DISCRETE; } if (d.has("update")) { int um = d["update"]; if (um < 0) um = 0; else if (um > 2) um = 2; vt->update_mode = UpdateMode(um); } PoolVector<float> times = d["times"]; Array values = d["values"]; ERR_FAIL_COND_V(times.size() != values.size(), false); if (times.size()) { int valcount = times.size(); PoolVector<float>::Read rt = times.read(); vt->values.resize(valcount); for (int i = 0; i < valcount; i++) { vt->values[i].time = rt[i]; vt->values[i].value = values[i]; } if (d.has("transitions")) { PoolVector<float> transitions = d["transitions"]; ERR_FAIL_COND_V(transitions.size() != valcount, false); PoolVector<float>::Read rtr = transitions.read(); for (int i = 0; i < valcount; i++) { vt->values[i].transition = rtr[i]; } } } return true; } else { while (track_get_key_count(track)) track_remove_key(track, 0); //well shouldn't be set anyway Dictionary d = p_value; ERR_FAIL_COND_V(!d.has("times"), false); ERR_FAIL_COND_V(!d.has("values"), false); PoolVector<float> times = d["times"]; Array values = d["values"]; ERR_FAIL_COND_V(times.size() != values.size(), false); if (times.size()) { int valcount = times.size(); PoolVector<float>::Read rt = times.read(); for (int i = 0; i < valcount; i++) { track_insert_key(track, rt[i], values[i]); } if (d.has("transitions")) { PoolVector<float> transitions = d["transitions"]; ERR_FAIL_COND_V(transitions.size() != valcount, false); PoolVector<float>::Read rtr = transitions.read(); for (int i = 0; i < valcount; i++) { track_set_key_transition(track, i, rtr[i]); } } } } } else return false; } else return false; return true; } bool Animation::_get(const StringName &p_name, Variant &r_ret) const { String name = p_name; if (name == "length") r_ret = length; else if (name == "loop") r_ret = loop; else if (name == "step") r_ret = step; else if (name.begins_with("tracks/")) { int track = name.get_slicec('/', 1).to_int(); String what = name.get_slicec('/', 2); ERR_FAIL_INDEX_V(track, tracks.size(), false); if (what == "type") { switch (track_get_type(track)) { case TYPE_TRANSFORM: r_ret = "transform"; break; case TYPE_VALUE: r_ret = "value"; break; case TYPE_METHOD: r_ret = "method"; break; } return true; } else if (what == "path") r_ret = track_get_path(track); else if (what == "interp") r_ret = track_get_interpolation_type(track); else if (what == "loop_wrap") r_ret = track_get_interpolation_loop_wrap(track); else if (what == "imported") r_ret = track_is_imported(track); else if (what == "keys") { if (track_get_type(track) == TYPE_TRANSFORM) { PoolVector<real_t> keys; int kk = track_get_key_count(track); keys.resize(kk * 12); PoolVector<real_t>::Write w = keys.write(); int idx = 0; for (int i = 0; i < track_get_key_count(track); i++) { Vector3 loc; Quat rot; Vector3 scale; transform_track_get_key(track, i, &loc, &rot, &scale); w[idx++] = track_get_key_time(track, i); w[idx++] = track_get_key_transition(track, i); w[idx++] = loc.x; w[idx++] = loc.y; w[idx++] = loc.z; w[idx++] = rot.x; w[idx++] = rot.y; w[idx++] = rot.z; w[idx++] = rot.w; w[idx++] = scale.x; w[idx++] = scale.y; w[idx++] = scale.z; } w = PoolVector<real_t>::Write(); r_ret = keys; return true; } else if (track_get_type(track) == TYPE_VALUE) { const ValueTrack *vt = static_cast<const ValueTrack *>(tracks[track]); Dictionary d; PoolVector<float> key_times; PoolVector<float> key_transitions; Array key_values; int kk = vt->values.size(); key_times.resize(kk); key_transitions.resize(kk); key_values.resize(kk); PoolVector<float>::Write wti = key_times.write(); PoolVector<float>::Write wtr = key_transitions.write(); int idx = 0; const TKey<Variant> *vls = vt->values.ptr(); for (int i = 0; i < kk; i++) { wti[idx] = vls[i].time; wtr[idx] = vls[i].transition; key_values[idx] = vls[i].value; idx++; } wti = PoolVector<float>::Write(); wtr = PoolVector<float>::Write(); d["times"] = key_times; d["transitions"] = key_transitions; d["values"] = key_values; if (track_get_type(track) == TYPE_VALUE) { d["update"] = value_track_get_update_mode(track); } r_ret = d; return true; } else { Dictionary d; PoolVector<float> key_times; PoolVector<float> key_transitions; Array key_values; int kk = track_get_key_count(track); key_times.resize(kk); key_transitions.resize(kk); key_values.resize(kk); PoolVector<float>::Write wti = key_times.write(); PoolVector<float>::Write wtr = key_transitions.write(); int idx = 0; for (int i = 0; i < track_get_key_count(track); i++) { wti[idx] = track_get_key_time(track, i); wtr[idx] = track_get_key_transition(track, i); key_values[idx] = track_get_key_value(track, i); idx++; } wti = PoolVector<float>::Write(); wtr = PoolVector<float>::Write(); d["times"] = key_times; d["transitions"] = key_transitions; d["values"] = key_values; if (track_get_type(track) == TYPE_VALUE) { d["update"] = value_track_get_update_mode(track); } r_ret = d; return true; } } else return false; } else return false; return true; } void Animation::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::REAL, "length", PROPERTY_HINT_RANGE, "0.001,99999,0.001")); p_list->push_back(PropertyInfo(Variant::BOOL, "loop")); p_list->push_back(PropertyInfo(Variant::REAL, "step", PROPERTY_HINT_RANGE, "0,4096,0.001")); for (int i = 0; i < tracks.size(); i++) { p_list->push_back(PropertyInfo(Variant::STRING, "tracks/" + itos(i) + "/type", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::NODE_PATH, "tracks/" + itos(i) + "/path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::INT, "tracks/" + itos(i) + "/interp", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/loop_wrap", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::BOOL, "tracks/" + itos(i) + "/imported", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::ARRAY, "tracks/" + itos(i) + "/keys", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR)); } } int Animation::add_track(TrackType p_type, int p_at_pos) { if (p_at_pos < 0 || p_at_pos >= tracks.size()) p_at_pos = tracks.size(); switch (p_type) { case TYPE_TRANSFORM: { TransformTrack *tt = memnew(TransformTrack); tracks.insert(p_at_pos, tt); } break; case TYPE_VALUE: { tracks.insert(p_at_pos, memnew(ValueTrack)); } break; case TYPE_METHOD: { tracks.insert(p_at_pos, memnew(MethodTrack)); } break; default: { ERR_PRINT("Unknown track type"); } } emit_changed(); return p_at_pos; } void Animation::remove_track(int p_track) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); _clear(tt->transforms); } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); _clear(vt->values); } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); _clear(mt->methods); } break; } memdelete(t); tracks.remove(p_track); emit_changed(); } int Animation::get_track_count() const { return tracks.size(); } Animation::TrackType Animation::track_get_type(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), TYPE_TRANSFORM); return tracks[p_track]->type; } void Animation::track_set_path(int p_track, const NodePath &p_path) { ERR_FAIL_INDEX(p_track, tracks.size()); tracks[p_track]->path = p_path; emit_changed(); } NodePath Animation::track_get_path(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), NodePath()); return tracks[p_track]->path; } int Animation::find_track(const NodePath &p_path) const { for (int i = 0; i < tracks.size(); i++) { if (tracks[i]->path == p_path) return i; }; return -1; }; void Animation::track_set_interpolation_type(int p_track, InterpolationType p_interp) { ERR_FAIL_INDEX(p_track, tracks.size()); ERR_FAIL_INDEX(p_interp, 3); tracks[p_track]->interpolation = p_interp; emit_changed(); } Animation::InterpolationType Animation::track_get_interpolation_type(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), INTERPOLATION_NEAREST); return tracks[p_track]->interpolation; } void Animation::track_set_interpolation_loop_wrap(int p_track, bool p_enable) { ERR_FAIL_INDEX(p_track, tracks.size()); tracks[p_track]->loop_wrap = p_enable; emit_changed(); } bool Animation::track_get_interpolation_loop_wrap(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), INTERPOLATION_NEAREST); return tracks[p_track]->loop_wrap; } // transform /* template<class T> int Animation::_insert_pos(float p_time, T& p_keys) { // simple, linear time inset that should be fast enough in reality. int idx=p_keys.size(); while(true) { if (idx==0 || p_keys[idx-1].time < p_time) { //condition for insertion. p_keys.insert(idx,T()); return idx; } else if (p_keys[idx-1].time == p_time) { // condition for replacing. return idx-1; } idx--; } } */ template <class T, class V> int Animation::_insert(float p_time, T &p_keys, const V &p_value) { int idx = p_keys.size(); while (true) { if (idx == 0 || p_keys[idx - 1].time < p_time) { //condition for insertion. p_keys.insert(idx, p_value); return idx; } else if (p_keys[idx - 1].time == p_time) { // condition for replacing. p_keys[idx - 1] = p_value; return idx - 1; } idx--; } return -1; } template <class T> void Animation::_clear(T &p_keys) { p_keys.clear(); } Error Animation::transform_track_get_key(int p_track, int p_key, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), ERR_INVALID_PARAMETER); Track *t = tracks[p_track]; TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, ERR_INVALID_PARAMETER); ERR_FAIL_INDEX_V(p_key, tt->transforms.size(), ERR_INVALID_PARAMETER); if (r_loc) *r_loc = tt->transforms[p_key].value.loc; if (r_rot) *r_rot = tt->transforms[p_key].value.rot; if (r_scale) *r_scale = tt->transforms[p_key].value.scale; return OK; } int Animation::transform_track_insert_key(int p_track, float p_time, const Vector3 p_loc, const Quat &p_rot, const Vector3 &p_scale) { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); Track *t = tracks[p_track]; ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, -1); TransformTrack *tt = static_cast<TransformTrack *>(t); TKey<TransformKey> tkey; tkey.time = p_time; tkey.value.loc = p_loc; tkey.value.rot = p_rot; tkey.value.scale = p_scale; int ret = _insert(p_time, tt->transforms, tkey); emit_changed(); return ret; } void Animation::track_remove_key_at_position(int p_track, float p_pos) { int idx = track_find_key(p_track, p_pos, true); ERR_FAIL_COND(idx < 0); track_remove_key(p_track, idx); } void Animation::track_remove_key(int p_track, int p_idx) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_INDEX(p_idx, tt->transforms.size()); tt->transforms.remove(p_idx); } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); ERR_FAIL_INDEX(p_idx, vt->values.size()); vt->values.remove(p_idx); } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX(p_idx, mt->methods.size()); mt->methods.remove(p_idx); } break; } emit_changed(); } int Animation::track_find_key(int p_track, float p_time, bool p_exact) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); int k = _find(tt->transforms, p_time); if (k < 0 || k >= tt->transforms.size()) return -1; if (tt->transforms[k].time != p_time && p_exact) return -1; return k; } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); int k = _find(vt->values, p_time); if (k < 0 || k >= vt->values.size()) return -1; if (vt->values[k].time != p_time && p_exact) return -1; return k; } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); int k = _find(mt->methods, p_time); if (k < 0 || k >= mt->methods.size()) return -1; if (mt->methods[k].time != p_time && p_exact) return -1; return k; } break; } return -1; } void Animation::track_insert_key(int p_track, float p_time, const Variant &p_key, float p_transition) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { Dictionary d = p_key; Vector3 loc; if (d.has("location")) loc = d["location"]; Quat rot; if (d.has("rotation")) rot = d["rotation"]; Vector3 scale; if (d.has("scale")) scale = d["scale"]; int idx = transform_track_insert_key(p_track, p_time, loc, rot, scale); track_set_key_transition(p_track, idx, p_transition); } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); TKey<Variant> k; k.time = p_time; k.transition = p_transition; k.value = p_key; _insert(p_time, vt->values, k); } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_COND(p_key.get_type() != Variant::DICTIONARY); Dictionary d = p_key; ERR_FAIL_COND(!d.has("method") || d["method"].get_type() != Variant::STRING); ERR_FAIL_COND(!d.has("args") || !d["args"].is_array()); MethodKey k; k.time = p_time; k.transition = p_transition; k.method = d["method"]; k.params = d["args"]; _insert(p_time, mt->methods, k); } break; } emit_changed(); } int Animation::track_get_key_count(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); return tt->transforms.size(); } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); return vt->values.size(); } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); return mt->methods.size(); } break; } ERR_FAIL_V(-1); } Variant Animation::track_get_key_value(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), Variant()); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), Variant()); Dictionary d; d["location"] = tt->transforms[p_key_idx].value.loc; d["rotation"] = tt->transforms[p_key_idx].value.rot; d["scale"] = tt->transforms[p_key_idx].value.scale; return d; } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), Variant()); return vt->values[p_key_idx].value; } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), Variant()); Dictionary d; d["method"] = mt->methods[p_key_idx].method; d["args"] = mt->methods[p_key_idx].params; return d; } break; } ERR_FAIL_V(Variant()); } float Animation::track_get_key_time(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), -1); return tt->transforms[p_key_idx].time; } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), -1); return vt->values[p_key_idx].time; } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), -1); return mt->methods[p_key_idx].time; } break; } ERR_FAIL_V(-1); } float Animation::track_get_key_transition(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), -1); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, tt->transforms.size(), -1); return tt->transforms[p_key_idx].transition; } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, vt->values.size(), -1); return vt->values[p_key_idx].transition; } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, mt->methods.size(), -1); return mt->methods[p_key_idx].transition; } break; } ERR_FAIL_V(0); } void Animation::track_set_key_value(int p_track, int p_key_idx, const Variant &p_value) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_INDEX(p_key_idx, tt->transforms.size()); Dictionary d = p_value; if (d.has("location")) tt->transforms[p_key_idx].value.loc = d["location"]; if (d.has("rotation")) tt->transforms[p_key_idx].value.rot = d["rotation"]; if (d.has("scale")) tt->transforms[p_key_idx].value.scale = d["scale"]; } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); ERR_FAIL_INDEX(p_key_idx, vt->values.size()); vt->values[p_key_idx].value = p_value; } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX(p_key_idx, mt->methods.size()); Dictionary d = p_value; if (d.has("method")) mt->methods[p_key_idx].method = d["method"]; if (d.has("args")) mt->methods[p_key_idx].params = d["args"]; } break; } } void Animation::track_set_key_transition(int p_track, int p_key_idx, float p_transition) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; switch (t->type) { case TYPE_TRANSFORM: { TransformTrack *tt = static_cast<TransformTrack *>(t); ERR_FAIL_INDEX(p_key_idx, tt->transforms.size()); tt->transforms[p_key_idx].transition = p_transition; } break; case TYPE_VALUE: { ValueTrack *vt = static_cast<ValueTrack *>(t); ERR_FAIL_INDEX(p_key_idx, vt->values.size()); vt->values[p_key_idx].transition = p_transition; } break; case TYPE_METHOD: { MethodTrack *mt = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX(p_key_idx, mt->methods.size()); mt->methods[p_key_idx].transition = p_transition; } break; } } template <class K> int Animation::_find(const Vector<K> &p_keys, float p_time) const { int len = p_keys.size(); if (len == 0) return -2; int low = 0; int high = len - 1; int middle = 0; #if DEBUG_ENABLED if (low > high) ERR_PRINT("low > high, this may be a bug"); #endif const K *keys = &p_keys[0]; while (low <= high) { middle = (low + high) / 2; if (p_time == keys[middle].time) { //match return middle; } else if (p_time < keys[middle].time) high = middle - 1; //search low end of array else low = middle + 1; //search high end of array } if (keys[middle].time > p_time) middle--; return middle; } Animation::TransformKey Animation::_interpolate(const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, float p_c) const { TransformKey ret; ret.loc = _interpolate(p_a.loc, p_b.loc, p_c); ret.rot = _interpolate(p_a.rot, p_b.rot, p_c); ret.scale = _interpolate(p_a.scale, p_b.scale, p_c); return ret; } Vector3 Animation::_interpolate(const Vector3 &p_a, const Vector3 &p_b, float p_c) const { return p_a.linear_interpolate(p_b, p_c); } Quat Animation::_interpolate(const Quat &p_a, const Quat &p_b, float p_c) const { return p_a.slerp(p_b, p_c); } Variant Animation::_interpolate(const Variant &p_a, const Variant &p_b, float p_c) const { Variant dst; Variant::interpolate(p_a, p_b, p_c, dst); return dst; } float Animation::_interpolate(const float &p_a, const float &p_b, float p_c) const { return p_a * (1.0 - p_c) + p_b * p_c; } Animation::TransformKey Animation::_cubic_interpolate(const Animation::TransformKey &p_pre_a, const Animation::TransformKey &p_a, const Animation::TransformKey &p_b, const Animation::TransformKey &p_post_b, float p_c) const { Animation::TransformKey tk; tk.loc = p_a.loc.cubic_interpolate(p_b.loc, p_pre_a.loc, p_post_b.loc, p_c); tk.scale = p_a.scale.cubic_interpolate(p_b.scale, p_pre_a.scale, p_post_b.scale, p_c); tk.rot = p_a.rot.cubic_slerp(p_b.rot, p_pre_a.rot, p_post_b.rot, p_c); return tk; } Vector3 Animation::_cubic_interpolate(const Vector3 &p_pre_a, const Vector3 &p_a, const Vector3 &p_b, const Vector3 &p_post_b, float p_c) const { return p_a.cubic_interpolate(p_b, p_pre_a, p_post_b, p_c); } Quat Animation::_cubic_interpolate(const Quat &p_pre_a, const Quat &p_a, const Quat &p_b, const Quat &p_post_b, float p_c) const { return p_a.cubic_slerp(p_b, p_pre_a, p_post_b, p_c); } Variant Animation::_cubic_interpolate(const Variant &p_pre_a, const Variant &p_a, const Variant &p_b, const Variant &p_post_b, float p_c) const { Variant::Type type_a = p_a.get_type(); Variant::Type type_b = p_b.get_type(); Variant::Type type_pa = p_pre_a.get_type(); Variant::Type type_pb = p_post_b.get_type(); //make int and real play along uint32_t vformat = 1 << type_a; vformat |= 1 << type_b; vformat |= 1 << type_pa; vformat |= 1 << type_pb; if (vformat == ((1 << Variant::INT) | (1 << Variant::REAL)) || vformat == (1 << Variant::REAL)) { //mix of real and int real_t p0 = p_pre_a; real_t p1 = p_a; real_t p2 = p_b; real_t p3 = p_post_b; float t = p_c; float t2 = t * t; float t3 = t2 * t; return 0.5f * ((p1 * 2.0f) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); } else if ((vformat & (vformat - 1))) { return p_a; //can't interpolate, mix of types } switch (type_a) { case Variant::VECTOR2: { Vector2 a = p_a; Vector2 b = p_b; Vector2 pa = p_pre_a; Vector2 pb = p_post_b; return a.cubic_interpolate(b, pa, pb, p_c); } break; case Variant::RECT2: { Rect2 a = p_a; Rect2 b = p_b; Rect2 pa = p_pre_a; Rect2 pb = p_post_b; return Rect2( a.position.cubic_interpolate(b.position, pa.position, pb.position, p_c), a.size.cubic_interpolate(b.size, pa.size, pb.size, p_c)); } break; case Variant::VECTOR3: { Vector3 a = p_a; Vector3 b = p_b; Vector3 pa = p_pre_a; Vector3 pb = p_post_b; return a.cubic_interpolate(b, pa, pb, p_c); } break; case Variant::QUAT: { Quat a = p_a; Quat b = p_b; Quat pa = p_pre_a; Quat pb = p_post_b; return a.cubic_slerp(b, pa, pb, p_c); } break; case Variant::RECT3: { Rect3 a = p_a; Rect3 b = p_b; Rect3 pa = p_pre_a; Rect3 pb = p_post_b; return Rect3( a.position.cubic_interpolate(b.position, pa.position, pb.position, p_c), a.size.cubic_interpolate(b.size, pa.size, pb.size, p_c)); } break; default: { return _interpolate(p_a, p_b, p_c); } } return Variant(); } float Animation::_cubic_interpolate(const float &p_pre_a, const float &p_a, const float &p_b, const float &p_post_b, float p_c) const { return _interpolate(p_a, p_b, p_c); } template <class T> T Animation::_interpolate(const Vector<TKey<T> > &p_keys, float p_time, InterpolationType p_interp, bool p_loop_wrap, bool *p_ok) const { int len = _find(p_keys, length) + 1; // try to find last key (there may be more past the end) if (len <= 0) { // (-1 or -2 returned originally) (plus one above) // meaning no keys, or only key time is larger than length if (p_ok) *p_ok = false; return T(); } else if (len == 1) { // one key found (0+1), return it if (p_ok) *p_ok = true; return p_keys[0].value; } int idx = _find(p_keys, p_time); ERR_FAIL_COND_V(idx == -2, T()); bool result = true; int next = 0; float c = 0; // prepare for all cases of interpolation if (loop && p_loop_wrap) { // loop if (idx >= 0) { if ((idx + 1) < len) { next = idx + 1; float delta = p_keys[next].time - p_keys[idx].time; float from = p_time - p_keys[idx].time; if (Math::absf(delta) > CMP_EPSILON) c = from / delta; else c = 0; } else { next = 0; float delta = (length - p_keys[idx].time) + p_keys[next].time; float from = p_time - p_keys[idx].time; if (Math::absf(delta) > CMP_EPSILON) c = from / delta; else c = 0; } } else { // on loop, behind first key idx = len - 1; next = 0; float endtime = (length - p_keys[idx].time); if (endtime < 0) // may be keys past the end endtime = 0; float delta = endtime + p_keys[next].time; float from = endtime + p_time; if (Math::absf(delta) > CMP_EPSILON) c = from / delta; else c = 0; } } else { // no loop if (idx >= 0) { if ((idx + 1) < len) { next = idx + 1; float delta = p_keys[next].time - p_keys[idx].time; float from = p_time - p_keys[idx].time; if (Math::absf(delta) > CMP_EPSILON) c = from / delta; else c = 0; } else { next = idx; } } else if (idx < 0) { // only allow extending first key to anim start if looping if (loop) idx = next = 0; else result = false; } } if (p_ok) *p_ok = result; if (!result) return T(); float tr = p_keys[idx].transition; if (tr == 0 || idx == next) { // don't interpolate if not needed return p_keys[idx].value; } if (tr != 1.0) { c = Math::ease(c, tr); } switch (p_interp) { case INTERPOLATION_NEAREST: { return p_keys[idx].value; } break; case INTERPOLATION_LINEAR: { return _interpolate(p_keys[idx].value, p_keys[next].value, c); } break; case INTERPOLATION_CUBIC: { int pre = idx - 1; if (pre < 0) pre = 0; int post = next + 1; if (post >= len) post = next; return _cubic_interpolate(p_keys[pre].value, p_keys[idx].value, p_keys[next].value, p_keys[post].value, c); } break; default: return p_keys[idx].value; } // do a barrel roll } Error Animation::transform_track_interpolate(int p_track, float p_time, Vector3 *r_loc, Quat *r_rot, Vector3 *r_scale) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), ERR_INVALID_PARAMETER); Track *t = tracks[p_track]; ERR_FAIL_COND_V(t->type != TYPE_TRANSFORM, ERR_INVALID_PARAMETER); TransformTrack *tt = static_cast<TransformTrack *>(t); bool ok = false; TransformKey tk = _interpolate(tt->transforms, p_time, tt->interpolation, tt->loop_wrap, &ok); if (!ok) return ERR_UNAVAILABLE; if (r_loc) *r_loc = tk.loc; if (r_rot) *r_rot = tk.rot; if (r_scale) *r_scale = tk.scale; return OK; } Variant Animation::value_track_interpolate(int p_track, float p_time) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), 0); Track *t = tracks[p_track]; ERR_FAIL_COND_V(t->type != TYPE_VALUE, Variant()); ValueTrack *vt = static_cast<ValueTrack *>(t); bool ok = false; Variant res = _interpolate(vt->values, p_time, vt->update_mode == UPDATE_CONTINUOUS ? vt->interpolation : INTERPOLATION_NEAREST, vt->loop_wrap, &ok); if (ok) { return res; } return Variant(); } void Animation::_value_track_get_key_indices_in_range(const ValueTrack *vt, float from_time, float to_time, List<int> *p_indices) const { if (from_time != length && to_time == length) to_time = length * 1.01; //include a little more if at the end int to = _find(vt->values, to_time); // can't really send the events == time, will be sent in the next frame. // if event>=len then it will probably never be requested by the anim player. if (to >= 0 && vt->values[to].time >= to_time) to--; if (to < 0) return; // not bother int from = _find(vt->values, from_time); // position in the right first event.+ if (from < 0 || vt->values[from].time < from_time) from++; int max = vt->values.size(); for (int i = from; i <= to; i++) { ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen p_indices->push_back(i); } } void Animation::value_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; ERR_FAIL_COND(t->type != TYPE_VALUE); ValueTrack *vt = static_cast<ValueTrack *>(t); float from_time = p_time - p_delta; float to_time = p_time; if (from_time > to_time) SWAP(from_time, to_time); if (loop) { from_time = Math::fposmod(from_time, length); to_time = Math::fposmod(to_time, length); if (from_time > to_time) { // handle loop by splitting _value_track_get_key_indices_in_range(vt, length - from_time, length, p_indices); _value_track_get_key_indices_in_range(vt, 0, to_time, p_indices); return; } } else { if (from_time < 0) from_time = 0; if (from_time > length) from_time = length; if (to_time < 0) to_time = 0; if (to_time > length) to_time = length; } _value_track_get_key_indices_in_range(vt, from_time, to_time, p_indices); } void Animation::value_track_set_update_mode(int p_track, UpdateMode p_mode) { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; ERR_FAIL_COND(t->type != TYPE_VALUE); ERR_FAIL_INDEX(p_mode, 3); ValueTrack *vt = static_cast<ValueTrack *>(t); vt->update_mode = p_mode; } Animation::UpdateMode Animation::value_track_get_update_mode(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), UPDATE_CONTINUOUS); Track *t = tracks[p_track]; ERR_FAIL_COND_V(t->type != TYPE_VALUE, UPDATE_CONTINUOUS); ValueTrack *vt = static_cast<ValueTrack *>(t); return vt->update_mode; } void Animation::_method_track_get_key_indices_in_range(const MethodTrack *mt, float from_time, float to_time, List<int> *p_indices) const { if (from_time != length && to_time == length) to_time = length * 1.01; //include a little more if at the end int to = _find(mt->methods, to_time); // can't really send the events == time, will be sent in the next frame. // if event>=len then it will probably never be requested by the anim player. if (to >= 0 && mt->methods[to].time >= to_time) to--; if (to < 0) return; // not bother int from = _find(mt->methods, from_time); // position in the right first event.+ if (from < 0 || mt->methods[from].time < from_time) from++; int max = mt->methods.size(); for (int i = from; i <= to; i++) { ERR_CONTINUE(i < 0 || i >= max); // shouldn't happen p_indices->push_back(i); } } void Animation::method_track_get_key_indices(int p_track, float p_time, float p_delta, List<int> *p_indices) const { ERR_FAIL_INDEX(p_track, tracks.size()); Track *t = tracks[p_track]; ERR_FAIL_COND(t->type != TYPE_METHOD); MethodTrack *mt = static_cast<MethodTrack *>(t); float from_time = p_time - p_delta; float to_time = p_time; if (from_time > to_time) SWAP(from_time, to_time); if (loop) { if (from_time > length || from_time < 0) from_time = Math::fposmod(from_time, length); if (to_time > length || to_time < 0) to_time = Math::fposmod(to_time, length); if (from_time > to_time) { // handle loop by splitting _method_track_get_key_indices_in_range(mt, from_time, length, p_indices); _method_track_get_key_indices_in_range(mt, 0, to_time, p_indices); return; } } else { if (from_time < 0) from_time = 0; if (from_time > length) from_time = length; if (to_time < 0) to_time = 0; if (to_time > length) to_time = length; } _method_track_get_key_indices_in_range(mt, from_time, to_time, p_indices); } Vector<Variant> Animation::method_track_get_params(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), Vector<Variant>()); Track *t = tracks[p_track]; ERR_FAIL_COND_V(t->type != TYPE_METHOD, Vector<Variant>()); MethodTrack *pm = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, pm->methods.size(), Vector<Variant>()); const MethodKey &mk = pm->methods[p_key_idx]; return mk.params; } StringName Animation::method_track_get_name(int p_track, int p_key_idx) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), StringName()); Track *t = tracks[p_track]; ERR_FAIL_COND_V(t->type != TYPE_METHOD, StringName()); MethodTrack *pm = static_cast<MethodTrack *>(t); ERR_FAIL_INDEX_V(p_key_idx, pm->methods.size(), StringName()); return pm->methods[p_key_idx].method; } void Animation::set_length(float p_length) { ERR_FAIL_COND(length < 0); length = p_length; emit_changed(); } float Animation::get_length() const { return length; } void Animation::set_loop(bool p_enabled) { loop = p_enabled; emit_changed(); } bool Animation::has_loop() const { return loop; } void Animation::track_move_up(int p_track) { if (p_track >= 0 && p_track < (tracks.size() - 1)) { SWAP(tracks[p_track], tracks[p_track + 1]); } emit_changed(); } void Animation::track_set_imported(int p_track, bool p_imported) { ERR_FAIL_INDEX(p_track, tracks.size()); tracks[p_track]->imported = p_imported; } bool Animation::track_is_imported(int p_track) const { ERR_FAIL_INDEX_V(p_track, tracks.size(), false); return tracks[p_track]->imported; } void Animation::track_move_down(int p_track) { if (p_track > 0 && p_track < tracks.size()) { SWAP(tracks[p_track], tracks[p_track - 1]); } emit_changed(); } void Animation::set_step(float p_step) { step = p_step; emit_changed(); } float Animation::get_step() const { return step; } void Animation::_bind_methods() { ClassDB::bind_method(D_METHOD("add_track", "type", "at_position"), &Animation::add_track, DEFVAL(-1)); ClassDB::bind_method(D_METHOD("remove_track", "idx"), &Animation::remove_track); ClassDB::bind_method(D_METHOD("get_track_count"), &Animation::get_track_count); ClassDB::bind_method(D_METHOD("track_get_type", "idx"), &Animation::track_get_type); ClassDB::bind_method(D_METHOD("track_get_path", "idx"), &Animation::track_get_path); ClassDB::bind_method(D_METHOD("track_set_path", "idx", "path"), &Animation::track_set_path); ClassDB::bind_method(D_METHOD("find_track", "path"), &Animation::find_track); ClassDB::bind_method(D_METHOD("track_move_up", "idx"), &Animation::track_move_up); ClassDB::bind_method(D_METHOD("track_move_down", "idx"), &Animation::track_move_down); ClassDB::bind_method(D_METHOD("track_set_imported", "idx", "imported"), &Animation::track_set_imported); ClassDB::bind_method(D_METHOD("track_is_imported", "idx"), &Animation::track_is_imported); ClassDB::bind_method(D_METHOD("transform_track_insert_key", "idx", "time", "location", "rotation", "scale"), &Animation::transform_track_insert_key); ClassDB::bind_method(D_METHOD("track_insert_key", "idx", "time", "key", "transition"), &Animation::track_insert_key, DEFVAL(1)); ClassDB::bind_method(D_METHOD("track_remove_key", "idx", "key_idx"), &Animation::track_remove_key); ClassDB::bind_method(D_METHOD("track_remove_key_at_position", "idx", "position"), &Animation::track_remove_key_at_position); ClassDB::bind_method(D_METHOD("track_set_key_value", "idx", "key", "value"), &Animation::track_set_key_value); ClassDB::bind_method(D_METHOD("track_set_key_transition", "idx", "key_idx", "transition"), &Animation::track_set_key_transition); ClassDB::bind_method(D_METHOD("track_get_key_transition", "idx", "key_idx"), &Animation::track_get_key_transition); ClassDB::bind_method(D_METHOD("track_get_key_count", "idx"), &Animation::track_get_key_count); ClassDB::bind_method(D_METHOD("track_get_key_value", "idx", "key_idx"), &Animation::track_get_key_value); ClassDB::bind_method(D_METHOD("track_get_key_time", "idx", "key_idx"), &Animation::track_get_key_time); ClassDB::bind_method(D_METHOD("track_find_key", "idx", "time", "exact"), &Animation::track_find_key, DEFVAL(false)); ClassDB::bind_method(D_METHOD("track_set_interpolation_type", "idx", "interpolation"), &Animation::track_set_interpolation_type); ClassDB::bind_method(D_METHOD("track_get_interpolation_type", "idx"), &Animation::track_get_interpolation_type); ClassDB::bind_method(D_METHOD("track_set_interpolation_loop_wrap", "idx", "interpolation"), &Animation::track_set_interpolation_loop_wrap); ClassDB::bind_method(D_METHOD("track_get_interpolation_loop_wrap", "idx"), &Animation::track_get_interpolation_loop_wrap); ClassDB::bind_method(D_METHOD("transform_track_interpolate", "idx", "time_sec"), &Animation::_transform_track_interpolate); ClassDB::bind_method(D_METHOD("value_track_set_update_mode", "idx", "mode"), &Animation::value_track_set_update_mode); ClassDB::bind_method(D_METHOD("value_track_get_update_mode", "idx"), &Animation::value_track_get_update_mode); ClassDB::bind_method(D_METHOD("value_track_get_key_indices", "idx", "time_sec", "delta"), &Animation::_value_track_get_key_indices); ClassDB::bind_method(D_METHOD("method_track_get_key_indices", "idx", "time_sec", "delta"), &Animation::_method_track_get_key_indices); ClassDB::bind_method(D_METHOD("method_track_get_name", "idx", "key_idx"), &Animation::method_track_get_name); ClassDB::bind_method(D_METHOD("method_track_get_params", "idx", "key_idx"), &Animation::method_track_get_params); ClassDB::bind_method(D_METHOD("set_length", "time_sec"), &Animation::set_length); ClassDB::bind_method(D_METHOD("get_length"), &Animation::get_length); ClassDB::bind_method(D_METHOD("set_loop", "enabled"), &Animation::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &Animation::has_loop); ClassDB::bind_method(D_METHOD("set_step", "size_sec"), &Animation::set_step); ClassDB::bind_method(D_METHOD("get_step"), &Animation::get_step); ClassDB::bind_method(D_METHOD("clear"), &Animation::clear); BIND_ENUM_CONSTANT(TYPE_VALUE); BIND_ENUM_CONSTANT(TYPE_TRANSFORM); BIND_ENUM_CONSTANT(TYPE_METHOD); BIND_ENUM_CONSTANT(INTERPOLATION_NEAREST); BIND_ENUM_CONSTANT(INTERPOLATION_LINEAR); BIND_ENUM_CONSTANT(INTERPOLATION_CUBIC); BIND_ENUM_CONSTANT(UPDATE_CONTINUOUS); BIND_ENUM_CONSTANT(UPDATE_DISCRETE); BIND_ENUM_CONSTANT(UPDATE_TRIGGER); } void Animation::clear() { for (int i = 0; i < tracks.size(); i++) memdelete(tracks[i]); tracks.clear(); loop = false; length = 1; } bool Animation::_transform_track_optimize_key(const TKey<TransformKey> &t0, const TKey<TransformKey> &t1, const TKey<TransformKey> &t2, float p_alowed_linear_err, float p_alowed_angular_err, float p_max_optimizable_angle, const Vector3 &p_norm) { real_t c = (t1.time - t0.time) / (t2.time - t0.time); real_t t[3] = { -1, -1, -1 }; { //translation const Vector3 &v0 = t0.value.loc; const Vector3 &v1 = t1.value.loc; const Vector3 &v2 = t2.value.loc; if (v0.distance_to(v2) < CMP_EPSILON) { //0 and 2 are close, let's see if 1 is close if (v0.distance_to(v1) > CMP_EPSILON) { //not close, not optimizable return false; } } else { Vector3 pd = (v2 - v0); float d0 = pd.dot(v0); float d1 = pd.dot(v1); float d2 = pd.dot(v2); if (d1 < d0 || d1 > d2) { return false; } Vector3 s[2] = { v0, v2 }; real_t d = Geometry::get_closest_point_to_segment(v1, s).distance_to(v1); if (d > pd.length() * p_alowed_linear_err) { return false; //beyond allowed error for colinearity } if (p_norm != Vector3() && Math::acos(pd.normalized().dot(p_norm)) > p_alowed_angular_err) return false; t[0] = (d1 - d0) / (d2 - d0); } } { //rotation const Quat &q0 = t0.value.rot; const Quat &q1 = t1.value.rot; const Quat &q2 = t2.value.rot; //localize both to rotation from q0 if ((q0 - q2).length() < CMP_EPSILON) { if ((q0 - q1).length() > CMP_EPSILON) return false; } else { Quat r02 = (q0.inverse() * q2).normalized(); Quat r01 = (q0.inverse() * q1).normalized(); Vector3 v02, v01; real_t a02, a01; r02.get_axis_angle(v02, a02); r01.get_axis_angle(v01, a01); if (Math::abs(a02) > p_max_optimizable_angle) return false; if (v01.dot(v02) < 0) { //make sure both rotations go the same way to compare v02 = -v02; a02 = -a02; } real_t err_01 = Math::acos(v01.normalized().dot(v02.normalized())) / Math_PI; if (err_01 > p_alowed_angular_err) { //not rotating in the same axis return false; } if (a01 * a02 < 0) { //not rotating in the same direction return false; } real_t tr = a01 / a02; if (tr < 0 || tr > 1) return false; //rotating too much or too less t[1] = tr; } } { //scale const Vector3 &v0 = t0.value.scale; const Vector3 &v1 = t1.value.scale; const Vector3 &v2 = t2.value.scale; if (v0.distance_to(v2) < CMP_EPSILON) { //0 and 2 are close, let's see if 1 is close if (v0.distance_to(v1) > CMP_EPSILON) { //not close, not optimizable return false; } } else { Vector3 pd = (v2 - v0); float d0 = pd.dot(v0); float d1 = pd.dot(v1); float d2 = pd.dot(v2); if (d1 < d0 || d1 > d2) { return false; //beyond segment range } Vector3 s[2] = { v0, v2 }; real_t d = Geometry::get_closest_point_to_segment(v1, s).distance_to(v1); if (d > pd.length() * p_alowed_linear_err) { return false; //beyond allowed error for colinearity } t[2] = (d1 - d0) / (d2 - d0); } } bool erase = false; if (t[0] == -1 && t[1] == -1 && t[2] == -1) { erase = true; } else { erase = true; real_t lt = -1; for (int j = 0; j < 3; j++) { //search for t on first, one must be it if (t[j] != -1) { lt = t[j]; //official t //validate rest for (int k = j + 1; k < 3; k++) { if (t[k] == -1) continue; if (Math::abs(lt - t[k]) > p_alowed_linear_err) { erase = false; break; } } break; } } ERR_FAIL_COND_V(lt == -1, false); if (erase) { if (Math::abs(lt - c) > p_alowed_linear_err) { //todo, evaluate changing the transition if this fails? //this could be done as a second pass and would be //able to optimize more erase = false; } else { //print_line(itos(i)+"because of interp"); } } } return erase; } void Animation::_transform_track_optimize(int p_idx, float p_allowed_linear_err, float p_allowed_angular_err, float p_max_optimizable_angle) { ERR_FAIL_INDEX(p_idx, tracks.size()); ERR_FAIL_COND(tracks[p_idx]->type != TYPE_TRANSFORM); TransformTrack *tt = static_cast<TransformTrack *>(tracks[p_idx]); bool prev_erased = false; TKey<TransformKey> first_erased; Vector3 norm; for (int i = 1; i < tt->transforms.size() - 1; i++) { TKey<TransformKey> &t0 = tt->transforms[i - 1]; TKey<TransformKey> &t1 = tt->transforms[i]; TKey<TransformKey> &t2 = tt->transforms[i + 1]; bool erase = _transform_track_optimize_key(t0, t1, t2, p_allowed_linear_err, p_allowed_angular_err, p_max_optimizable_angle, norm); if (erase && !prev_erased) { norm = (t2.value.loc - t1.value.loc).normalized(); } if (prev_erased && !_transform_track_optimize_key(t0, first_erased, t2, p_allowed_linear_err, p_allowed_angular_err, p_max_optimizable_angle, norm)) { //avoid error to go beyond first erased key erase = false; } if (erase) { if (!prev_erased) { first_erased = t1; prev_erased = true; } tt->transforms.remove(i); i--; } else { prev_erased = false; norm = Vector3(); } } } void Animation::optimize(float p_allowed_linear_err, float p_allowed_angular_err, float p_max_optimizable_angle) { for (int i = 0; i < tracks.size(); i++) { if (tracks[i]->type == TYPE_TRANSFORM) _transform_track_optimize(i, p_allowed_linear_err, p_allowed_angular_err, p_max_optimizable_angle); } } Animation::Animation() { step = 0.1; loop = false; length = 1; } Animation::~Animation() { for (int i = 0; i < tracks.size(); i++) memdelete(tracks[i]); }
{'content_hash': '2c5f602259d8413e03a309fcb096952d', 'timestamp': '', 'source': 'github', 'line_count': 1912, 'max_line_length': 246, 'avg_line_length': 25.80857740585774, 'alnum_prop': 0.6153284967373241, 'repo_name': 'Brickcaster/godot', 'id': '21e4a85cd1ebcea38d17e41277812752ab6cae20', 'size': '49346', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'scene/resources/animation.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '50004'}, {'name': 'C#', 'bytes': '175588'}, {'name': 'C++', 'bytes': '17917130'}, {'name': 'GLSL', 'bytes': '1271'}, {'name': 'Java', 'bytes': '499031'}, {'name': 'JavaScript', 'bytes': '9580'}, {'name': 'Makefile', 'bytes': '451'}, {'name': 'Objective-C', 'bytes': '2644'}, {'name': 'Objective-C++', 'bytes': '169356'}, {'name': 'Python', 'bytes': '313311'}, {'name': 'Shell', 'bytes': '11043'}]}
<?php /** * @file * Contains \Drupal\Console\Core\Command\Settings\DebugCommand. */ namespace Drupal\Console\Core\Command\Settings; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Command\Command; use Drupal\Console\Core\Command\Shared\CommandTrait; use Drupal\Console\Core\Utils\ConfigurationManager; use Drupal\Console\Core\Utils\NestedArray; use Drupal\Console\Core\Style\DrupalStyle; /** * Class DebugCommand * @package Drupal\Console\Core\Command\Settings */ class DebugCommand extends Command { use CommandTrait; /** * @var ConfigurationManager */ protected $configurationManager; /** * @var NestedArray */ protected $nestedArray; /** * CheckCommand constructor. * @param ConfigurationManager $configurationManager * @param NestedArray $nestedArray */ public function __construct( ConfigurationManager $configurationManager, NestedArray $nestedArray ) { $this->configurationManager = $configurationManager; $this->nestedArray = $nestedArray; parent::__construct(); } /** * {@inheritdoc} */ protected function configure() { $this ->setName('settings:debug') ->setDescription($this->trans('commands.settings.debug.description')); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $configuration = $this->configurationManager->getConfiguration(); $configApplication = $configuration->get('application'); unset($configApplication['autowire']); unset($configApplication['languages']); unset($configApplication['aliases']); unset($configApplication['composer']); unset($configApplication['default']['commands']); $configApplicationFlatten = []; $keyFlatten = ''; $this->nestedArray->yamlFlattenArray( $configApplication, $configApplicationFlatten, $keyFlatten ); $tableHeader = [ $this->trans('commands.settings.debug.messages.config-key'), $this->trans('commands.settings.debug.messages.config-value'), ]; $tableRows = []; foreach ($configApplicationFlatten as $ymlKey => $ymlValue) { $tableRows[] = [ $ymlKey, $ymlValue ]; } $io->newLine(); $io->info( sprintf( '%s :', $this->trans('commands.settings.debug.messages.config-file') ), false ); $io->comment( sprintf( '%s/.console/config.yml', $this->configurationManager->getHomeDirectory() ), true ); $io->newLine(); $io->table($tableHeader, $tableRows, 'compact'); return 0; } }
{'content_hash': '79c409ec97ef52325492091d13db2658', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 82, 'avg_line_length': 25.60330578512397, 'alnum_prop': 0.5881213686249193, 'repo_name': 'sukottokun/jenkins-002-001', 'id': '50f62f4fce47512adf3e0f608f5bea826d40a550', 'size': '3098', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'vendor/drupal/console-core/src/Command/Settings/DebugCommand.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '673'}, {'name': 'CSS', 'bytes': '481085'}, {'name': 'Gherkin', 'bytes': '3374'}, {'name': 'HTML', 'bytes': '525716'}, {'name': 'JavaScript', 'bytes': '911696'}, {'name': 'PHP', 'bytes': '32448348'}, {'name': 'Shell', 'bytes': '54634'}]}
from django.conf.urls import url, include urlpatterns = [ url(r'^excluded/', include('cms.test_utils.project.sampleapp.urls_example', namespace="excluded", app_name='some_app')), url(r'^not_excluded/', include('cms.test_utils.project.sampleapp.urls_example', namespace="not_excluded", app_name='some_app')), ]
{'content_hash': '25ac6e3dcdf4b85fb9848fe92a9c78e9', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 113, 'avg_line_length': 41.875, 'alnum_prop': 0.6835820895522388, 'repo_name': 'kk9599/django-cms', 'id': 'cfa53f1bfd251805c70e19b1f5b0942a4078d726', 'size': '335', 'binary': False, 'copies': '58', 'ref': 'refs/heads/develop', 'path': 'cms/test_utils/project/sampleapp/urls_excluded.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '114206'}, {'name': 'HTML', 'bytes': '93242'}, {'name': 'JavaScript', 'bytes': '510815'}, {'name': 'Logos', 'bytes': '10461'}, {'name': 'Python', 'bytes': '3516533'}, {'name': 'XSLT', 'bytes': '5917'}]}
QUnit.module('FaBoProfileNormalTest', { before: function() { init(); } }); /** * FaBoプロファイルの正常系テストを行うクラス。 * @class */ let FaBoProfileNormalTest = {}; /** * 仮想サービス一覧取得するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method: GET<br/> * Path: /gpio/fabo/service?serviceId=xxxx&accessToken=xxx<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・サービス一覧が取得できること。<br/> * </p> */ FaBoProfileNormalTest.getFaBoServiceNormalTest001 = function(assert) { let done = assert.async(); sdk.get({ profile: 'fabo', attribute: 'service', params: { serviceId: getCurrentServiceId() } }).then(json => { assert.ok(true, 'result=' + json.result); assert.ok(json.services != undefined, 'services=' + JSON.stringify(json.services)); done(); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('getFaBoServiceNormalTest001', FaBoProfileNormalTest.getFaBoServiceNormalTest001); /** * 新規仮想サービス作成するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method:POST<br/> * Path: /gpio/fabo/service?serviceId=xxxx&accessToken=xxx&name=TEST<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・新規のサービスが作成できること。<br/> * </p> */ FaBoProfileNormalTest.postFaBoServiceNormalTest001 = function(assert) { let done = assert.async(); sdk.post({ profile: 'fabo', attribute: 'service', params: { serviceId: getCurrentServiceId(), name: 'TEST' } }).then(json => { assert.ok(true, 'result=' + json.result); done(); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('postFaBoServiceNormalTest001', FaBoProfileNormalTest.postFaBoServiceNormalTest001); /** * 仮想サービス更新するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method:PUT<br/> * Path: /gpio/fabo/service?serviceId=xxxx&accessToken=xxx&name=TEST<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・サービス名が更新できること。<br/> * </p> */ FaBoProfileNormalTest.putFaBoServiceNormalTest001 = function(assert) { let done = assert.async(); createFaBoService().then(vid => { sdk.post({ profile: 'fabo', attribute: 'service', params: { serviceId: getCurrentServiceId(), vid: vid, name: 'TEST UPDATE' } }).then(json => { assert.ok(true, 'result=' + json.result); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); }).finally(() => { FaBoProfileAbnormalTest.deleteFaBoService(vid); done(); }); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('putFaBoServiceNormalTest001', FaBoProfileNormalTest.putFaBoServiceNormalTest001); /** * 仮想サービス削除するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method:DELETE<br/> * Path: /gpio/fabo/service?serviceId=xxxx&accessToken=xxx&vid=xxxx<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・サービスが削除できること。<br/> * </p> */ FaBoProfileNormalTest.deleteFaBoServiceNormalTest001 = function(assert) { let done = assert.async(); createFaBoService().then(vid => { sdk.delete({ profile: 'fabo', attribute: 'service', params: { serviceId: getCurrentServiceId(), vid: vid } }).then(json => { assert.ok(true, 'result=' + json.result); done(); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('deleteFaBoServiceNormalTest001', FaBoProfileNormalTest.deleteFaBoServiceNormalTest001); /** * プロファイル一覧取得するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method: GET<br/> * Path: /gpio/fabo/profile?serviceId=xxxx&accessToken=xxx&name=TEST<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・新規のサービスが作成できること。<br/> * </p> */ FaBoProfileNormalTest.getFaBoProfileNormalTest001 = function(assert) { let done = assert.async(); createFaBoService().then(vid => { sdk.get({ profile: 'fabo', attribute: 'service', params: { serviceId: getCurrentServiceId(), vid: vid } }).then(json => { assert.ok(true, 'result=' + json.result); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); }).finally(() => { deleteFaBoService(vid); done(); }); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('getFaBoProfileNormalTest001', FaBoProfileNormalTest.getFaBoProfileNormalTest001); /** * プロファイル作成するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method: POST<br/> * Path: /gpio/fabo/profile?serviceId=xxxx&accessToken=xxx&vid=xxx&type=1&pins=D2<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・新規のサービスが作成できること。<br/> * </p> */ FaBoProfileNormalTest.postFaBoServiceNormalTest001 = function(assert) { let done = assert.async(); createFaBoService().then(vid => { sdk.post({ profile: 'fabo', attribute: 'service', params: { serviceId: getCurrentServiceId(), vid: vid, type: 1, pins: 'D2' } }).then(json => { assert.ok(true, 'result=' + json.result); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); }).finally(() => { deleteFaBoService(vid); done(); }); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('postFaBoServiceNormalTest001', FaBoProfileNormalTest.postFaBoServiceNormalTest001); /** * プロファイルを更新するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method: PUT<br/> * Path: /gpio/fabo/profile?serviceId=xxxx&accessToken=xxx&vid=xxx&type=1&pins=D2,D3<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・プロファイルを更新できること。<br/> * </p> */ FaBoProfileNormalTest.putFaBoProfileNormalTest001 = function(assert) { let done = assert.async(); createFaBoProfile().then(vid => { sdk.post({ profile: 'fabo', attribute: 'profile', params: { serviceId: getCurrentServiceId(), vid: vid, type: 1, pins: 'D2,D3' } }).then(json => { assert.ok(true, 'result=' + json.result); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); }).finally(() => { deleteFaBoService(vid); done(); }); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('putFaBoProfileNormalTest001', FaBoProfileNormalTest.putFaBoProfileNormalTest001); /** * プロファイルを削除するテストを行う。 * <h3>【HTTP通信】</h3> * <p id='test'> * Method: PUT<br/> * Path: /gpio/fabo/profile?serviceId=xxxx&accessToken=xxx&vid=xxx&type=1&pins=D2,D3<br/> * </p> * <h3>【期待する動作】</h3> * <p id='expected'> * ・新規のサービスが作成できること。<br/> * </p> */ FaBoProfileNormalTest.deleteFaBoServiceNormalTest001 = function(assert) { let done = assert.async(); createFaBoProfile().then(vid => { sdk.delete({ profile: 'fabo', attribute: 'profile', params: { serviceId: getCurrentServiceId(), vid: vid, type: 1 } }).then(json => { assert.ok(true, 'result=' + json.result); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); }).finally(() => { deleteFaBoService(vid); done(); }); }).catch(e => { assert.ok(false, 'errorCode=' + e.errorCode + ', errorMessage=' + e.errorMessage); done(); }); }; QUnit.test('deleteFaBoServiceNormalTest001', FaBoProfileNormalTest.deleteFaBoServiceNormalTest001);
{'content_hash': '578e0c7da962a3e4f97ded9cbc3c98fc', 'timestamp': '', 'source': 'github', 'line_count': 308, 'max_line_length': 99, 'avg_line_length': 26.07792207792208, 'alnum_prop': 0.6002241035856574, 'repo_name': 'DeviceConnect/DeviceConnect-JS', 'id': '25e9cb2e307eb4a91d562d119babc804b931f774', 'size': '8810', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'dConnectSDKForJavascriptTest/tests/extra_profiles/fabo_normal.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '664418'}, {'name': 'HTML', 'bytes': '111471'}, {'name': 'JavaScript', 'bytes': '3679073'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <!--basic styles--> <link href="asset/css/bootstrap.css" rel="stylesheet" /> <link rel="stylesheet" href="asset/css/dexter.min.css" /> <link rel="stylesheet" href="asset/css/font-awesome.min.css" /> <!--[if IE 7]> <link rel="stylesheet" href="asset/css/font-awesome-ie7.min.css"> <![endif]--> <link rel="stylesheet" href="asset/css/prettify.css" /> <script src="asset/js/jquery-2.0.3.min.js"></script> <!--[if IE]> <script src="asset/js/jquery.min.js"></script> <![endif]--> <script src="asset/js/prettify.js"></script> <script type="text/javascript"> $(function() { window.prettyPrint && prettyPrint(); $('#id-check-horizontal').removeAttr('checked').on('click', function(){ $('#dt-list-1').toggleClass('dl-horizontal').prev().html(this.checked ? '&lt;dl class="dl-horizontal"&gt;' : '&lt;dl&gt;'); }); }) </script> </head> <body> <div class="space-12"></div> <div class="table-grid-info table-grid-info-striped"> <div class="table-grid-row"> <div class="table-grid-label"> Checker Code</div> <div class="table-grid-value"><h5 class="header blue"><i class="fa fa-bug"></i>&nbsp; SA_LOCAL_SELF_ASSIGNMENT </h5> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Description </div> <div class="table-grid-value-highlight"><i class="fa fa-th"></i>&nbsp; Self assignment of local variable </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Severity </div> <div class="table-grid-value"> Critical </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Detector / Bug Pattern </div> <div class="table-grid-value"> FindLocalSelfAssignment2 / SA </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> More Information </div> <div class="table-grid-value"> <p> This method contains a self assignment of a local variable; e.g.</p> <pre> public void foo() { int x = 3; x = x; } </pre> <p> Such assignments are useless, and may indicate a logic error or typo. </p> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Bad Code </div> <div class="table-grid-value"> <pre class="prettyprint linenums warning"> </pre> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Good Code </div> <div class="table-grid-value"> <pre class="prettyprint linenums correct"> </pre> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> CWE ID </div> <div class="table-grid-value"> <a href="http://cwe.mitre.org/data/definitions/1001.html">CWE-586</a> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Code Review Asset </div> <div class="table-grid-value"> N/A </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> URLs </div> <div class="table-grid-value"> <i class="fa fa-link"></i>&nbsp; FINDBUGS SITE : <p> <i class="fa fa-link"></i>&nbsp; STACKOVERFLOW SITE : </div> </div> </div> <div class="space-20"></div> </body> <html>
{'content_hash': 'b1077e69504dd01f5584357506391eb4', 'timestamp': '', 'source': 'github', 'line_count': 145, 'max_line_length': 128, 'avg_line_length': 23.06206896551724, 'alnum_prop': 0.5941985645933014, 'repo_name': 'Minjung-Baek/Dexter', 'id': '3451074167961b88c887d0ccb1f741faef4b6423', 'size': '3344', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'project/dexter-server/public/tool/findbugs/JAVA/help/SA_LOCAL_SELF_ASSIGNMENT.html', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '230'}, {'name': 'C', 'bytes': '160649'}, {'name': 'C#', 'bytes': '368383'}, {'name': 'C++', 'bytes': '934804'}, {'name': 'CSS', 'bytes': '140317'}, {'name': 'EmberScript', 'bytes': '96193'}, {'name': 'HTML', 'bytes': '2858148'}, {'name': 'Java', 'bytes': '1760529'}, {'name': 'JavaScript', 'bytes': '2287560'}, {'name': 'Perl', 'bytes': '4890'}, {'name': 'Python', 'bytes': '9200'}, {'name': 'Ruby', 'bytes': '565'}, {'name': 'Shell', 'bytes': '10474'}]}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:cardBackgroundColor="@android:color/white" android:padding="@dimen/padding_small"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="@dimen/margin_small" android:orientation="vertical" android:padding="@dimen/margin_small" app:cardBackgroundColor="@android:color/white" app:cardCornerRadius="@dimen/card_radius" app:cardElevation="@dimen/cardview_default_elevation" app:cardPreventCornerOverlap="false"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="@dimen/padding_large"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/card_expiry" /> <EditText android:id="@+id/card_expiry" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/margin_small" android:hint="@string/card_mm_yy" android:inputType="number" android:maxLength="5" android:text="" /> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout>
{'content_hash': '8d39be3d9f1c6f0fe0a1097b348464a4', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 72, 'avg_line_length': 36.666666666666664, 'alnum_prop': 0.6153409090909091, 'repo_name': 'kpamansoor/Cardless', 'id': '9212ba9e2eba9e781101f87a3f9af401fc01b178', 'size': '1760', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'creditcarddesign/src/main/res/layout/lyt_card_expiry.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '82093'}]}
package org.bouncycastle.jcajce.provider.symmetric.util; import javax.crypto.interfaces.PBEKey; import javax.crypto.spec.PBEKeySpec; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.PBEParametersGenerator; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; public class BCPBEKey implements PBEKey { String algorithm; ASN1ObjectIdentifier oid; int type; int digest; int keySize; int ivSize; CipherParameters param; PBEKeySpec pbeKeySpec; boolean tryWrong = false; /** * @param param */ public BCPBEKey( String algorithm, ASN1ObjectIdentifier oid, int type, int digest, int keySize, int ivSize, PBEKeySpec pbeKeySpec, CipherParameters param) { this.algorithm = algorithm; this.oid = oid; this.type = type; this.digest = digest; this.keySize = keySize; this.ivSize = ivSize; this.pbeKeySpec = pbeKeySpec; this.param = param; } public String getAlgorithm() { return algorithm; } public String getFormat() { return "RAW"; } public byte[] getEncoded() { if (param != null) { KeyParameter kParam; if (param instanceof ParametersWithIV) { kParam = (KeyParameter)((ParametersWithIV)param).getParameters(); } else { kParam = (KeyParameter)param; } return kParam.getKey(); } else { if (type == PBE.PKCS12) { return PBEParametersGenerator.PKCS12PasswordToBytes(pbeKeySpec.getPassword()); } else if (type == PBE.PKCS5S2_UTF8) { return PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(pbeKeySpec.getPassword()); } else { return PBEParametersGenerator.PKCS5PasswordToBytes(pbeKeySpec.getPassword()); } } } int getType() { return type; } int getDigest() { return digest; } int getKeySize() { return keySize; } public int getIvSize() { return ivSize; } public CipherParameters getParam() { return param; } /* (non-Javadoc) * @see javax.crypto.interfaces.PBEKey#getPassword() */ public char[] getPassword() { return pbeKeySpec.getPassword(); } /* (non-Javadoc) * @see javax.crypto.interfaces.PBEKey#getSalt() */ public byte[] getSalt() { return pbeKeySpec.getSalt(); } /* (non-Javadoc) * @see javax.crypto.interfaces.PBEKey#getIterationCount() */ public int getIterationCount() { return pbeKeySpec.getIterationCount(); } public ASN1ObjectIdentifier getOID() { return oid; } public void setTryWrongPKCS12Zero(boolean tryWrong) { this.tryWrong = tryWrong; } boolean shouldTryWrongPKCS12() { return tryWrong; } }
{'content_hash': '26e451b41480fdcab41130b4738fe6b7', 'timestamp': '', 'source': 'github', 'line_count': 155, 'max_line_length': 97, 'avg_line_length': 22.283870967741937, 'alnum_prop': 0.5445859872611465, 'repo_name': 'sake/bouncycastle-java', 'id': 'a4719729f2f81156a464100e307970e5cdb63a95', 'size': '3454', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'src/org/bouncycastle/jcajce/provider/symmetric/util/BCPBEKey.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '21610104'}, {'name': 'Standard ML', 'bytes': '20502'}]}
BEGIN { require 'pathname' basedir = Pathname.new( __FILE__ ).dirname.parent.parent libdir = basedir + "lib" $LOAD_PATH.unshift( libdir ) unless $LOAD_PATH.include?( libdir ) } require 'spec' require 'spec/lib/helpers' require 'apache/fakerequest' require 'arrow' require 'arrow/dispatcherloader' ##################################################################### ### C O N T E X T S ##################################################################### describe Arrow::DispatcherLoader do include Arrow::SpecHelpers before( :all ) do setup_logging( :crit ) end after( :all ) do reset_logging() end it "creates Arrow::Dispatchers from a registered configfile on child_init" do req = Apache::Request.new Arrow::Dispatcher.should_receive( :create_from_hosts_file ).with( 'hosts.yml' ) Arrow::DispatcherLoader.new( 'hosts.yml' ).child_init( req ).should == Apache::OK end it "handles errors while loading dispachers by logging to a tempfile and to Apache's log" do req = Apache::Request.new Arrow::Dispatcher.should_receive( :create_from_hosts_file ).with( 'hosts.yml' ). and_raise( RuntimeError.new("something bad happened") ) logpath = mock( "error logfile Pathname" ) io = mock( "error logfile IO" ) Pathname.should_receive( :new ).with( instance_of(String) ). and_return( logpath ) logpath.should_receive( :+ ).with( 'arrow-dispatcher-failure.log' ).and_return( logpath ) logpath.should_receive( :open ).with( IO::WRONLY|IO::TRUNC|IO::CREAT ).and_yield( io ) io.should_receive( :puts ).with( /something bad happened/ ) io.should_receive( :flush ) expect { Arrow::DispatcherLoader.new( 'hosts.yml' ).child_init( req ) }.to raise_error( RuntimeError, /something bad happened/ ) end end
{'content_hash': '834f02bf96f411ce6bdb9f145cfe1c5c', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 93, 'avg_line_length': 27.952380952380953, 'alnum_prop': 0.6439522998296422, 'repo_name': 'ged/arrow', 'id': '67872986af609219c93e3a8ceddd1e8a39d28d27', 'size': '1782', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/arrow/dispatcherloader_spec.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '34720'}, {'name': 'Ruby', 'bytes': '715754'}]}
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInitbe3bcf261f233d43ba788e7f1fc83f33 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInitbe3bcf261f233d43ba788e7f1fc83f33', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInitbe3bcf261f233d43ba788e7f1fc83f33', 'loadClassLoader')); $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } $loader->register(true); $includeFiles = require __DIR__ . '/autoload_files.php'; foreach ($includeFiles as $fileIdentifier => $file) { composerRequirebe3bcf261f233d43ba788e7f1fc83f33($fileIdentifier, $file); } return $loader; } } function composerRequirebe3bcf261f233d43ba788e7f1fc83f33($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { require $file; $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; } }
{'content_hash': '0e6ef88ee54aa3b02448b6a96c5f1749', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 126, 'avg_line_length': 30.389830508474578, 'alnum_prop': 0.6129392080312326, 'repo_name': 'starspire/payu', 'id': 'c8f79680bad5f605ae1f884da70fa425e450a7f7', 'size': '1793', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/composer/autoload_real.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '208'}, {'name': 'PHP', 'bytes': '37885'}]}
import { ReactElement } from 'react' import { NgPartyNewIcon } from '../../components' import { styles, sidebarStyles } from './header.styles' import { navigation as DATA, LinkModel, config } from './data' import { A } from './shared' export const Header = () => { const sidebarId = 'header-sidebar' return ( <> <header className="headerbar fixed flex justify-start items-center"> <style jsx global> {styles} </style> <style jsx global> {sidebarStyles} </style> <SidebarToggle id={sidebarId} /> <a href="big-party-v" className="text-decoration-none inline-block mx-auto headerbar-home-link " > <div className="headerbar-title mx-auto"> <NgPartyNewIcon className="headerbar-title-logo" /> <span>BigParty V</span> </div> </a> <MainNav data={DATA.main} /> <div className="headerbar-action center m0 p0 flex justify-center nowrap"> <SecondaryNavItemAction {...DATA.secondary[config.enableTickets ? 0 : 1]} /> </div> </header> <Sidebar id={sidebarId}> <SibebarNav data={DATA.main} /> </Sidebar> </> ) } const MainNav = (props: { data: LinkModel[] }) => { const { data } = props return ( <nav className="headerbar-nav nav"> <ul className="nav-item__list list-reset center m0 p0 flex justify-center nowrap"> {data.map((item) => { return ( <li className="nav-item" key={item.label}> <a href={item.link} className="text-decoration-none block"> {item.label} </a> </li> ) })} </ul> </nav> ) } const SidebarToggle = (props: { id: string }) => { const { id } = props const handleToggleRef = `tap:${id}.toggle` return ( <div role="button" aria-label="open sidebar" on={handleToggleRef} tabIndex={0} className="navbar-trigger md-hide lg-hide pr2" > ☰ </div> ) } const Sidebar = (props: { id: string; children: ReactElement }) => { const { children, id } = props const handleToggleRef = `tap:${id}.toggle` return ( <amp-sidebar id={id} className="sidebar" layout="nodisplay" side="left"> <div className="flex justify-start items-center sidebar-header"> <div role="button" aria-label="close sidebar" on={handleToggleRef} tabIndex={0} className="navbar-trigger items-start" > ✕ </div> </div> {children} </amp-sidebar> ) } const SibebarNav = (props: { data: LinkModel[] }) => { const { data } = props return ( <nav className="sidebar-nav nav"> <ul className="list-reset m0 p0 label"> {data.map((item) => { return ( <li className="nav-item land-see-sidebar-nav-item title-sm sidebar-link" key={item.label} > <a className="nav-link" href={item.link}> {item.label} </a> </li> ) })} </ul> </nav> ) } const SecondaryNavItemAction = (props: LinkModel) => { const { link, label } = props return ( <A href={link} className="text-decoration-none headerbar-action-link"> {label} </A> ) }
{'content_hash': '06d6718c0fb220fb6f1fa82cc0ce990e', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 88, 'avg_line_length': 25.139705882352942, 'alnum_prop': 0.5349517402749342, 'repo_name': 'ngParty/web', 'id': '80de0b62fca6bbfab5cca2aa251151e12062dd45', 'size': '3423', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'conferences/big-party-v/header.tsx', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '782'}, {'name': 'JavaScript', 'bytes': '670'}, {'name': 'TypeScript', 'bytes': '195232'}]}
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <display-name>Deciservice Web Application</display-name> <filter> <filter-name>filter</filter-name> <filter-class>com.redsaz.deciservice.view.StaticContentFilter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>Resteasy</servlet-name> <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher </servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.redsaz.deciservice.view.DeciserviceApplication</param-value> </init-param> </servlet> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/</param-value> </context-param> <servlet-mapping> <servlet-name>Resteasy</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
{'content_hash': '4b4d7d706a99dea348f71ee98cb09ff4', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 227, 'avg_line_length': 42.733333333333334, 'alnum_prop': 0.6505460218408736, 'repo_name': 'redsaz/deciservice', 'id': '95bd3dc7b450543a8bd59997653efdcf6fe8b481', 'size': '1282', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'deciservice/src/main/webapp/WEB-INF/web.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1651'}, {'name': 'FreeMarker', 'bytes': '9282'}, {'name': 'Java', 'bytes': '61429'}, {'name': 'JavaScript', 'bytes': '715'}]}
npm install -g serverless serverless deploy --stage $env --region us-east-1 --verbose
{'content_hash': 'e78c51e73367ab2035df82d761a75e7a', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 59, 'avg_line_length': 28.666666666666668, 'alnum_prop': 0.7558139534883721, 'repo_name': 'maingi4/Serverless_Getting_Started', 'id': '406b4f0f83cb38255eebc661caa8ff0b34a5794c', 'size': '86', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'promotion.sh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '296'}, {'name': 'C#', 'bytes': '1397'}, {'name': 'Shell', 'bytes': '86'}]}
package de.katzenpapst.amunra.entity; import de.katzenpapst.amunra.AmunRa; import de.katzenpapst.amunra.mob.DamageSourceAR; import de.katzenpapst.amunra.world.WorldHelper; import micdoodle8.mods.galacticraft.api.vector.Vector3; import micdoodle8.mods.galacticraft.core.util.OxygenUtil; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityBlaze; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; public class EntityLaserArrow extends EntityBaseLaserArrow { protected float damage = 2.0F; protected boolean doesFireDamage = true; private static final ResourceLocation arrowTextures = new ResourceLocation(AmunRa.ASSETPREFIX, "textures/entity/laserarrow.png"); public EntityLaserArrow(World world, EntityLivingBase shooter, Vector3 startVec, EntityLivingBase target) { super(world, shooter, startVec, target); } public EntityLaserArrow(World world) { super(world); // TODO Auto-generated constructor stub } public EntityLaserArrow(World world, EntityLivingBase shooter, double startX, double startY, double startZ) { super(world, shooter, startX, startY, startZ); } public EntityLaserArrow(World world, double x, double y, double z) { super(world, x, y, z); } public EntityLaserArrow(World world, EntityLivingBase shootingEntity, EntityLivingBase target, float randMod) { super(world, shootingEntity, target, randMod); } public EntityLaserArrow(World par1World, EntityLivingBase par2EntityLivingBase) { super(par1World, par2EntityLivingBase); } @Override protected float getSpeed() { return 3.0F; } @Override protected float getDamage() { return damage; } public void setDoesFireDamage(boolean set) { this.doesFireDamage = set; } public void setDamage(float newDmg) { damage = newDmg; } @Override protected boolean doesFireDamage() { return doesFireDamage; } @Override public ResourceLocation getTexture() { return arrowTextures; } @Override protected int getEntityDependentDamage(Entity ent, int regularDamage) { if(ent instanceof EntityBlaze) { return Math.max(regularDamage / 2, 1); } return regularDamage; } @Override protected void onImpactBlock(World worldObj, int x, int y, int z) { Block block = worldObj.getBlock(x, y, z); int meta = worldObj.getBlockMetadata(x, y, z); // first tests first if(block == Blocks.ice) { worldObj.setBlock(x, y, z, Blocks.water, 0, 3); return; } if(block == Blocks.snow || block == Blocks.snow_layer) { worldObj.setBlock(x, y, z, Blocks.air, 0, 3); return; } ItemStack smeltResult = FurnaceRecipes.smelting().getSmeltingResult(new ItemStack(block, 1, meta)); if(smeltResult != null) { int blockId = Item.getIdFromItem(smeltResult.getItem()); if(blockId > 0) { Block b = Block.getBlockById(blockId); if(b != Blocks.air) { /** * Sets the block ID and metadata at a given location. Args: X, Y, Z, new block ID, new metadata, flags. Flag 1 will * cause a block update. Flag 2 will send the change to clients (you almost always want this). Flag 4 prevents the * block from being re-rendered, if this is a client world. Flags can be added together. */ worldObj.setBlock(x, y, z, b, smeltResult.getItemDamage(), 3); return; } } } if(OxygenUtil.noAtmosphericCombustion(worldObj.provider)) { if(OxygenUtil.isAABBInBreathableAirBlock(worldObj, AxisAlignedBB.getBoundingBox(x, y, z, x+1, y+1, z+1))) { WorldHelper.setFireToBlock(worldObj, x, y, z, posX, posY, posZ); } } else { WorldHelper.setFireToBlock(worldObj, x, y, z, posX, posY, posZ); } //OxygenUtil.isInOxygenBlock(world, bb) //if(Blocks.fire.getFlammability(world, x, y, z, face)) //if(block.isFlammable(world, x, y, z, face)) /*if(worldObj.getBlock(x, y+1, z) == Blocks.air) { //OxygenUtil.isAABBInBreathableAirBlock(world, bb) // no oxygen check for now worldObj.setBlock(x, y+1, z, Blocks.fire, 0, 3); }*/ } protected void setFireToBlock(World worldObj, int x, int y, int z) { // omg double deltaX = x+0.5 - posX; double deltaY = y+0.5 - posY; double deltaZ = z+0.5 - posZ; double deltaXabs = Math.abs(deltaX); double deltaYabs = Math.abs(deltaY); double deltaZabs = Math.abs(deltaZ); if(deltaXabs > deltaYabs) { if(deltaXabs > deltaZabs) { if(deltaX < 0) { worldObj.setBlock(x+1, y, z, Blocks.fire); } else { worldObj.setBlock(x-1, y, z, Blocks.fire); } } else { if(deltaZ < 0) { worldObj.setBlock(x, y, z+1, Blocks.fire); } else { worldObj.setBlock(x, y, z-1, Blocks.fire); } } } else { if(deltaYabs > deltaZabs) { if(deltaY < 0) { worldObj.setBlock(x, y+1, z, Blocks.fire); } else { // is there even fire from below? worldObj.setBlock(x, y-1, z, Blocks.fire); } } else { if(deltaZ < 0) { worldObj.setBlock(x, y, z+1, Blocks.fire); } else { worldObj.setBlock(x, y, z-1, Blocks.fire); } } } } @Override protected void onPassThrough(int x, int y, int z) { Block b = worldObj.getBlock(x, y, z); if(b == Blocks.water) { this.worldObj.setBlock(x, y, z, Blocks.air); this.playSound("random.fizz", 0.7F, 1.6F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.4F); inWater = false; } } @Override protected DamageSource getDamageSource() { if (this.shootingEntity == null) { return DamageSourceAR.causeLaserDamage("ar_heatray", this, this);// ("laserArrow", this, this).setProjectile(); } return DamageSourceAR.causeLaserDamage("ar_heatray", this, this.shootingEntity); } @Override protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); damage = nbttagcompound.getFloat("damage"); doesFireDamage = nbttagcompound.getBoolean("fireDmg"); } @Override protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); nbttagcompound.setFloat("damage", damage); nbttagcompound.setBoolean("fireDmg", doesFireDamage); } }
{'content_hash': 'db439c395193ebc16f37da27428663d1', 'timestamp': '', 'source': 'github', 'line_count': 231, 'max_line_length': 136, 'avg_line_length': 32.84415584415584, 'alnum_prop': 0.5979965730855411, 'repo_name': 'katzenpapst/amunra', 'id': 'e5a8590ab53635e0075815756f22f5ad36eb52cb', 'size': '7587', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/de/katzenpapst/amunra/entity/EntityLaserArrow.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '1737273'}]}
Your blind folded in Mexico, you've just been given a toasted bagel. Now the question is do you eat it? If so what kind is it? Was it good?
{'content_hash': '94d1315eed0c8c212f136fe431d74a2a', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 50, 'avg_line_length': 46.333333333333336, 'alnum_prop': 0.7553956834532374, 'repo_name': 'deltaworld/create-your-own-adventure', 'id': '5f043a8b82f7266deafa40c0d9203671b4f24483', 'size': '139', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'english/coffee/bagel/eat-a-bagel.md', 'mode': '33188', 'license': 'mit', 'language': []}
package de.cosmocode.palava.ipc; import junit.framework.Assert; import org.junit.Test; import de.cosmocode.collections.utility.map.MapTest; /** * Tests {@link IpcArguments} implementations. * * @author Willi Schoenborn */ public abstract class AbstractIpcArgumentsTest extends MapTest { @Override protected abstract IpcArguments unit(); /** * Tests {@link IpcArguments#require(String...)} with a present key. */ @Test public void require() { final IpcArguments unit = unit(); unit.put("key", "value"); Assert.assertTrue("'key' should be present", unit.containsKey("key")); unit.require("key"); } /** * Tests {@link IpcArguments#require(String...)} with a missing key. */ @Test(expected = IpcArgumentsMissingException.class) public void requireFail() { unit().require("no-such-key"); } }
{'content_hash': 'd19593c3cc9d33ae33afb63f23086d03', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 78, 'avg_line_length': 22.75, 'alnum_prop': 0.6395604395604395, 'repo_name': 'palava/palava-ipc', 'id': '6d913e4583e82a4ddca89816fc497176e2e20760', 'size': '1508', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/de/cosmocode/palava/ipc/AbstractIpcArgumentsTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '168172'}]}
/* ** If you embed Lua in your program and need to open the standard ** libraries, call luaL_openlibs in your program. If you need a ** different set of libraries, copy this file to your project and edit ** it to suit your needs. */ #define linit_c #define LUA_LIB #include "lua.h" #include "lualib.h" #include "lauxlib.h" /* ** these libs are loaded by lua.c and are readily available to any Lua ** program */ static const luaL_Reg loadedlibs[] = { {"_G", luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, {LUA_IOLIBNAME, luaopen_io}, {LUA_OSLIBNAME, luaopen_os}, {LUA_STRLIBNAME, luaopen_string}, {LUA_BITLIBNAME, luaopen_bit32}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_DBLIBNAME, luaopen_debug}, {LUA_ERISLIBNAME, luaopen_eris}, {NULL, NULL} }; /* ** these libs are preloaded and must be required before used */ static const luaL_Reg preloadedlibs[] = { {NULL, NULL} }; LUALIB_API void luaL_openlibs (lua_State *L) { const luaL_Reg *lib; /* call open functions from 'loadedlibs' and set results to global table */ for (lib = loadedlibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } /* add open functions from 'preloadedlibs' into 'package.preload' table */ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); for (lib = preloadedlibs; lib->func; lib++) { lua_pushcfunction(L, lib->func); lua_setfield(L, -2, lib->name); } lua_pop(L, 1); /* remove _PRELOAD table */ }
{'content_hash': '131ebfeaa889c050366683dfaf202def', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 77, 'avg_line_length': 24.46875, 'alnum_prop': 0.6698595146871009, 'repo_name': 'cbeck88/wes-kernel', 'id': '0903f689efa68b459fb6bb3222b5264fed173c0d', 'size': '1724', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/eris/linit.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '102767'}, {'name': 'C++', 'bytes': '668620'}, {'name': 'Lua', 'bytes': '16889'}, {'name': 'Makefile', 'bytes': '7045'}, {'name': 'Python', 'bytes': '18274'}, {'name': 'Shell', 'bytes': '310'}]}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Customizing the module's entry point</title> <link rel="stylesheet" href="../../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="Boost.Test"> <link rel="up" href="../static_lib_customizations.html" title="Static-library variant customizations"> <link rel="prev" href="../static_lib_customizations.html" title="Static-library variant customizations"> <link rel="next" href="init_func.html" title="Customizing the module's initialization function"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../static_lib_customizations.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../static_lib_customizations.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="init_func.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_test.adv_scenarios.static_lib_customizations.entry_point"></a><a class="link" href="entry_point.html" title="Customizing the module's entry point">Customizing the module's entry point</a> </h4></div></div></div> <p> In the static library variant, customizing the main entry point is quite troublesome, because the definition of function <code class="computeroutput"><span class="identifier">main</span></code> is already compiled into the static library. This requires you to rebuild the <span class="emphasis"><em>Unit Test Framework</em></span> static library with the defined symbol <a class="link" href="../../utf_reference/link_references/link_boost_test_no_main.html" title="BOOST_TEST_NO_MAIN"><code class="computeroutput"><span class="identifier">BOOST_TEST_NO_MAIN</span></code></a>. In the Boost root directory you need to invoke command </p> <pre class="programlisting"><span class="special">&gt;</span> <span class="identifier">b2</span> <span class="special">--</span><span class="identifier">with</span><span class="special">-</span><span class="identifier">test</span> <span class="identifier">link</span><span class="special">=</span><span class="keyword">static</span> <span class="identifier">define</span><span class="special">=</span><a class="link" href="../../utf_reference/link_references/link_boost_test_no_main.html" title="BOOST_TEST_NO_MAIN"><code class="computeroutput"><span class="identifier">BOOST_TEST_NO_MAIN</span></code></a> <span class="identifier">define</span><span class="special">=</span><a class="link" href="../../utf_reference/link_references/link_boost_test_alternative_init_macro.html" title="BOOST_TEST_ALTERNATIVE_INIT_API"><code class="computeroutput"><span class="identifier">BOOST_TEST_ALTERNATIVE_INIT_API</span></code></a> <span class="identifier">install</span> </pre> <div class="warning"><table border="0" summary="Warning"> <tr> <td rowspan="2" align="center" valign="top" width="25"><img alt="[Warning]" src="../../../../../../../doc/src/images/warning.png"></td> <th align="left">Warning</th> </tr> <tr><td align="left" valign="top"><p> This removal of entry point definition from the static library will affect everybody else who is linking against the library. It may be less intrusive to switch to the <a class="link" href="../shared_lib_customizations.html" title="Shared-library variant customizations">shared library usage variant</a> instead. </p></td></tr> </table></div> <p> In one of the source files, you now have to define your custom entry point, and invoke the default <a class="link" href="../test_module_runner_overview.html" title="Test module runner">test runner</a> <code class="computeroutput"><span class="identifier">unit_test_main</span></code> manually with the default <a class="link" href="../test_module_init_overview.html" title="Test module's initialization">initialization function</a> <code class="computeroutput"><span class="identifier">init_unit_test</span></code> as the first argument. There is no need to define <a class="link" href="../../utf_reference/link_references/link_boost_test_no_main.html" title="BOOST_TEST_NO_MAIN"><code class="computeroutput"><span class="identifier">BOOST_TEST_NO_MAIN</span></code></a> in your source code, but you need to define <a class="link" href="../../utf_reference/link_references/link_boost_test_alternative_init_macro.html" title="BOOST_TEST_ALTERNATIVE_INIT_API"><code class="computeroutput"><span class="identifier">BOOST_TEST_ALTERNATIVE_INIT_API</span></code></a> in the main file: </p> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> In <span class="bold"><strong>exactly one</strong></span> file </p> </th> <th> <p> In all other files </p> </th> </tr></thead> <tbody><tr> <td> <pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="preprocessor">#define</span> <span class="identifier">BOOST_TEST_MODULE</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="identifier">name</span> <span class="preprocessor">#define</span> <span class="identifier">BOOST_TEST_ALTERNATIVE_INIT_API</span> <span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="comment">// entry point:</span> <span class="keyword">int</span> <span class="identifier">main</span><span class="special">(</span><span class="keyword">int</span> <span class="identifier">argc</span><span class="special">,</span> <span class="keyword">char</span><span class="special">*</span> <span class="identifier">argv</span><span class="special">[],</span> <span class="keyword">char</span><span class="special">*</span> <span class="identifier">envp</span><span class="special">[])</span> <span class="special">{</span> <span class="keyword">return</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">unit_test_main</span><span class="special">(</span><span class="identifier">init_unit_test</span><span class="special">,</span> <span class="identifier">argc</span><span class="special">,</span> <span class="identifier">argv</span><span class="special">);</span> <span class="special">}</span> </pre> </td> <td> <pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="comment">//</span> <span class="comment">// test cases</span> <span class="comment">//</span> <span class="comment">//</span> <span class="comment">// test cases</span> <span class="comment">//</span> </pre> </td> </tr></tbody> </table></div> <div class="note"><table border="0" summary="Note"> <tr> <td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../../doc/src/images/note.png"></td> <th align="left">Note</th> </tr> <tr><td align="left" valign="top"><p> The reason for defining <a class="link" href="../../utf_reference/link_references/link_boost_test_alternative_init_macro.html" title="BOOST_TEST_ALTERNATIVE_INIT_API"><code class="computeroutput"><span class="identifier">BOOST_TEST_ALTERNATIVE_INIT_API</span></code></a> is described <a class="link" href="../obsolete_init_func.html" title="The obsolete initialization function">here</a>. </p></td></tr> </table></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2001-2016 Boost.Test contributors<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../static_lib_customizations.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../static_lib_customizations.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="init_func.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': '531102464c23dd00f6bb33f0ca3ede7a', 'timestamp': '', 'source': 'github', 'line_count': 130, 'max_line_length': 961, 'avg_line_length': 79.01538461538462, 'alnum_prop': 0.6557632398753894, 'repo_name': 'keichan100yen/ode-ext', 'id': '3701c9a12f0eb2b06551cf1716ff55e3a10b5570', 'size': '10272', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'boost/libs/test/doc/html/boost_test/adv_scenarios/static_lib_customizations/entry_point.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '309067'}, {'name': 'Batchfile', 'bytes': '37875'}, {'name': 'C', 'bytes': '2967570'}, {'name': 'C#', 'bytes': '40804'}, {'name': 'C++', 'bytes': '189322982'}, {'name': 'CMake', 'bytes': '119251'}, {'name': 'CSS', 'bytes': '456744'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '6246'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'Groff', 'bytes': '5189'}, {'name': 'HTML', 'bytes': '181460055'}, {'name': 'IDL', 'bytes': '28'}, {'name': 'JavaScript', 'bytes': '419776'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '29689'}, {'name': 'Makefile', 'bytes': '1088024'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Objective-C', 'bytes': '11406'}, {'name': 'Objective-C++', 'bytes': '630'}, {'name': 'PHP', 'bytes': '68641'}, {'name': 'Perl', 'bytes': '36491'}, {'name': 'Perl6', 'bytes': '2053'}, {'name': 'Python', 'bytes': '1612978'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Ruby', 'bytes': '5532'}, {'name': 'Shell', 'bytes': '354720'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '32117'}, {'name': 'XSLT', 'bytes': '553585'}, {'name': 'Yacc', 'bytes': '19623'}]}
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.flags; /** * @author hakonhall */ public class UnboundJacksonFlag<T> extends UnboundFlagImpl<T, JacksonFlag<T>, UnboundJacksonFlag<T>> { public UnboundJacksonFlag(FlagId id, T defaultValue, Class<T> jacksonClass) { this(id, defaultValue, new FetchVector(), jacksonClass); } public UnboundJacksonFlag(FlagId id, T defaultValue, FetchVector defaultFetchVector, Class<T> jacksonClass) { super(id, defaultValue, defaultFetchVector, new JacksonSerializer<>(jacksonClass), (id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), JacksonFlag::new); } }
{'content_hash': '571f026363db4f9cf56e8a07ed51f371', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 117, 'avg_line_length': 44.72222222222222, 'alnum_prop': 0.7031055900621118, 'repo_name': 'vespa-engine/vespa', 'id': 'bef152707875b236a65a214b630909da8c028668', 'size': '805', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'flags/src/main/java/com/yahoo/vespa/flags/UnboundJacksonFlag.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '8130'}, {'name': 'C', 'bytes': '60315'}, {'name': 'C++', 'bytes': '29580035'}, {'name': 'CMake', 'bytes': '593981'}, {'name': 'Emacs Lisp', 'bytes': '91'}, {'name': 'GAP', 'bytes': '3312'}, {'name': 'Go', 'bytes': '560664'}, {'name': 'HTML', 'bytes': '54520'}, {'name': 'Java', 'bytes': '40814190'}, {'name': 'JavaScript', 'bytes': '73436'}, {'name': 'LLVM', 'bytes': '6152'}, {'name': 'Lex', 'bytes': '11499'}, {'name': 'Makefile', 'bytes': '5553'}, {'name': 'Objective-C', 'bytes': '12369'}, {'name': 'Perl', 'bytes': '23134'}, {'name': 'Python', 'bytes': '52392'}, {'name': 'Roff', 'bytes': '17506'}, {'name': 'Ruby', 'bytes': '10690'}, {'name': 'Shell', 'bytes': '268737'}, {'name': 'Yacc', 'bytes': '14735'}]}
namespace { bool IsMainThread() { return pp::Module::Get()->core()->IsMainThread(); } // Posts a task to run |cb| on the main thread. The task is posted even if the // current thread is the main thread. void PostOnMain(pp::CompletionCallback cb) { pp::Module::Get()->core()->CallOnMainThread(0, cb, PP_OK); } // Ensures |cb| is called on the main thread, either because the current thread // is the main thread or by posting it to the main thread. void CallOnMain(pp::CompletionCallback cb) { // TODO(tomfinegan): This is only necessary because PPAPI doesn't allow calls // off the main thread yet. Remove this once the change lands. if (IsMainThread()) cb.Run(PP_OK); else PostOnMain(cb); } // Configures a cdm::InputBuffer. |subsamples| must exist as long as // |input_buffer| is in use. void ConfigureInputBuffer( const pp::Buffer_Dev& encrypted_buffer, const PP_EncryptedBlockInfo& encrypted_block_info, std::vector<cdm::SubsampleEntry>* subsamples, cdm::InputBuffer* input_buffer) { PP_DCHECK(subsamples); PP_DCHECK(!encrypted_buffer.is_null()); input_buffer->data = static_cast<uint8_t*>(encrypted_buffer.data()); input_buffer->data_size = encrypted_block_info.data_size; PP_DCHECK(encrypted_buffer.size() >= input_buffer->data_size); input_buffer->data_offset = encrypted_block_info.data_offset; PP_DCHECK(encrypted_block_info.key_id_size <= arraysize(encrypted_block_info.key_id)); input_buffer->key_id_size = encrypted_block_info.key_id_size; input_buffer->key_id = input_buffer->key_id_size > 0 ? encrypted_block_info.key_id : NULL; PP_DCHECK(encrypted_block_info.iv_size <= arraysize(encrypted_block_info.iv)); input_buffer->iv_size = encrypted_block_info.iv_size; input_buffer->iv = encrypted_block_info.iv_size > 0 ? encrypted_block_info.iv : NULL; input_buffer->num_subsamples = encrypted_block_info.num_subsamples; if (encrypted_block_info.num_subsamples > 0) { subsamples->reserve(encrypted_block_info.num_subsamples); for (uint32_t i = 0; i < encrypted_block_info.num_subsamples; ++i) { subsamples->push_back(cdm::SubsampleEntry( encrypted_block_info.subsamples[i].clear_bytes, encrypted_block_info.subsamples[i].cipher_bytes)); } input_buffer->subsamples = &(*subsamples)[0]; } input_buffer->timestamp = encrypted_block_info.tracking_info.timestamp; } PP_DecryptResult CdmStatusToPpDecryptResult(cdm::Status status) { switch (status) { case cdm::kSuccess: return PP_DECRYPTRESULT_SUCCESS; case cdm::kNoKey: return PP_DECRYPTRESULT_DECRYPT_NOKEY; case cdm::kNeedMoreData: return PP_DECRYPTRESULT_NEEDMOREDATA; case cdm::kDecryptError: return PP_DECRYPTRESULT_DECRYPT_ERROR; case cdm::kDecodeError: return PP_DECRYPTRESULT_DECODE_ERROR; default: PP_NOTREACHED(); return PP_DECRYPTRESULT_DECODE_ERROR; } } PP_DecryptedFrameFormat CdmVideoFormatToPpDecryptedFrameFormat( cdm::VideoFormat format) { switch (format) { case cdm::kYv12: return PP_DECRYPTEDFRAMEFORMAT_YV12; case cdm::kI420: return PP_DECRYPTEDFRAMEFORMAT_I420; default: return PP_DECRYPTEDFRAMEFORMAT_UNKNOWN; } } PP_DecryptedSampleFormat CdmAudioFormatToPpDecryptedSampleFormat( cdm::AudioFormat format) { switch (format) { case cdm::kAudioFormatU8: return PP_DECRYPTEDSAMPLEFORMAT_U8; case cdm::kAudioFormatS16: return PP_DECRYPTEDSAMPLEFORMAT_S16; case cdm::kAudioFormatS32: return PP_DECRYPTEDSAMPLEFORMAT_S32; case cdm::kAudioFormatF32: return PP_DECRYPTEDSAMPLEFORMAT_F32; case cdm::kAudioFormatPlanarS16: return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_S16; case cdm::kAudioFormatPlanarF32: return PP_DECRYPTEDSAMPLEFORMAT_PLANAR_F32; default: return PP_DECRYPTEDSAMPLEFORMAT_UNKNOWN; } } cdm::AudioDecoderConfig::AudioCodec PpAudioCodecToCdmAudioCodec( PP_AudioCodec codec) { switch (codec) { case PP_AUDIOCODEC_VORBIS: return cdm::AudioDecoderConfig::kCodecVorbis; case PP_AUDIOCODEC_AAC: return cdm::AudioDecoderConfig::kCodecAac; default: return cdm::AudioDecoderConfig::kUnknownAudioCodec; } } cdm::VideoDecoderConfig::VideoCodec PpVideoCodecToCdmVideoCodec( PP_VideoCodec codec) { switch (codec) { case PP_VIDEOCODEC_VP8: return cdm::VideoDecoderConfig::kCodecVp8; case PP_VIDEOCODEC_H264: return cdm::VideoDecoderConfig::kCodecH264; default: return cdm::VideoDecoderConfig::kUnknownVideoCodec; } } cdm::VideoDecoderConfig::VideoCodecProfile PpVCProfileToCdmVCProfile( PP_VideoCodecProfile profile) { switch (profile) { case PP_VIDEOCODECPROFILE_VP8_MAIN: return cdm::VideoDecoderConfig::kVp8ProfileMain; case PP_VIDEOCODECPROFILE_H264_BASELINE: return cdm::VideoDecoderConfig::kH264ProfileBaseline; case PP_VIDEOCODECPROFILE_H264_MAIN: return cdm::VideoDecoderConfig::kH264ProfileMain; case PP_VIDEOCODECPROFILE_H264_EXTENDED: return cdm::VideoDecoderConfig::kH264ProfileExtended; case PP_VIDEOCODECPROFILE_H264_HIGH: return cdm::VideoDecoderConfig::kH264ProfileHigh; case PP_VIDEOCODECPROFILE_H264_HIGH_10: return cdm::VideoDecoderConfig::kH264ProfileHigh10; case PP_VIDEOCODECPROFILE_H264_HIGH_422: return cdm::VideoDecoderConfig::kH264ProfileHigh422; case PP_VIDEOCODECPROFILE_H264_HIGH_444_PREDICTIVE: return cdm::VideoDecoderConfig::kH264ProfileHigh444Predictive; default: return cdm::VideoDecoderConfig::kUnknownVideoCodecProfile; } } cdm::VideoFormat PpDecryptedFrameFormatToCdmVideoFormat( PP_DecryptedFrameFormat format) { switch (format) { case PP_DECRYPTEDFRAMEFORMAT_YV12: return cdm::kYv12; case PP_DECRYPTEDFRAMEFORMAT_I420: return cdm::kI420; default: return cdm::kUnknownVideoFormat; } } cdm::StreamType PpDecryptorStreamTypeToCdmStreamType( PP_DecryptorStreamType stream_type) { switch (stream_type) { case PP_DECRYPTORSTREAMTYPE_AUDIO: return cdm::kStreamTypeAudio; case PP_DECRYPTORSTREAMTYPE_VIDEO: return cdm::kStreamTypeVideo; } PP_NOTREACHED(); return cdm::kStreamTypeVideo; } } // namespace namespace media { CdmAdapter::CdmAdapter(PP_Instance instance, pp::Module* module) : pp::Instance(instance), pp::ContentDecryptor_Private(this), #if defined(OS_CHROMEOS) output_protection_(this), platform_verification_(this), challenge_in_progress_(false), output_link_mask_(0), output_protection_mask_(0), query_output_protection_in_progress_(false), #endif allocator_(this), cdm_(NULL), deferred_initialize_audio_decoder_(false), deferred_audio_decoder_config_id_(0), deferred_initialize_video_decoder_(false), deferred_video_decoder_config_id_(0) { callback_factory_.Initialize(this); } CdmAdapter::~CdmAdapter() {} bool CdmAdapter::CreateCdmInstance(const std::string& key_system) { PP_DCHECK(!cdm_); cdm_ = make_linked_ptr(CdmWrapper::Create( key_system.data(), key_system.size(), GetCdmHost, this)); return (cdm_ != NULL); } // No KeyErrors should be reported in this function because they cannot be // bubbled up in the WD EME API. Those errors will be reported during session // creation (aka GenerateKeyRequest). void CdmAdapter::Initialize(const std::string& key_system, bool can_challenge_platform) { PP_DCHECK(!key_system.empty()); PP_DCHECK(key_system_.empty() || (key_system_ == key_system && cdm_)); if (!cdm_ && !CreateCdmInstance(key_system)) return; PP_DCHECK(cdm_); key_system_ = key_system; } void CdmAdapter::GenerateKeyRequest(const std::string& type, pp::VarArrayBuffer init_data) { // Initialize() doesn't report an error, so GenerateKeyRequest() can be called // even if Initialize() failed. if (!cdm_) { SendUnknownKeyError(key_system_, std::string()); return; } #if defined(CHECK_DOCUMENT_URL) PP_URLComponents_Dev url_components = {}; pp::Var href = pp::URLUtil_Dev::Get()->GetDocumentURL( pp::InstanceHandle(pp_instance()), &url_components); PP_DCHECK(href.is_string()); PP_DCHECK(!href.AsString().empty()); PP_DCHECK(url_components.host.begin); PP_DCHECK(0 < url_components.host.len); #endif // defined(CHECK_DOCUMENT_URL) cdm::Status status = cdm_->GenerateKeyRequest( type.data(), type.size(), static_cast<const uint8_t*>(init_data.Map()), init_data.ByteLength()); PP_DCHECK(status == cdm::kSuccess || status == cdm::kSessionError); if (status != cdm::kSuccess) SendUnknownKeyError(key_system_, std::string()); } void CdmAdapter::AddKey(const std::string& session_id, pp::VarArrayBuffer key, pp::VarArrayBuffer init_data) { // TODO(jrummell): In EME WD, AddKey() can only be called on valid sessions. // We should be able to DCHECK(cdm_) when addressing http://crbug.com/249976. if (!cdm_) { SendUnknownKeyError(key_system_, session_id); return; } const uint8_t* key_ptr = static_cast<const uint8_t*>(key.Map()); const uint32_t key_size = key.ByteLength(); const uint8_t* init_data_ptr = static_cast<const uint8_t*>(init_data.Map()); const uint32_t init_data_size = init_data.ByteLength(); PP_DCHECK(!init_data_ptr == !init_data_size); if (!key_ptr || !key_size) { SendUnknownKeyError(key_system_, session_id); return; } cdm::Status status = cdm_->AddKey(session_id.data(), session_id.size(), key_ptr, key_size, init_data_ptr, init_data_size); PP_DCHECK(status == cdm::kSuccess || status == cdm::kSessionError); if (status != cdm::kSuccess) { SendUnknownKeyError(key_system_, session_id); return; } SendKeyAdded(key_system_, session_id); } void CdmAdapter::CancelKeyRequest(const std::string& session_id) { // TODO(jrummell): In EME WD, AddKey() can only be called on valid sessions. // We should be able to DCHECK(cdm_) when addressing http://crbug.com/249976. if (!cdm_) { SendUnknownKeyError(key_system_, session_id); return; } cdm::Status status = cdm_->CancelKeyRequest(session_id.data(), session_id.size()); PP_DCHECK(status == cdm::kSuccess || status == cdm::kSessionError); if (status != cdm::kSuccess) SendUnknownKeyError(key_system_, session_id); } // Note: In the following decryption/decoding related functions, errors are NOT // reported via KeyError, but are reported via corresponding PPB calls. void CdmAdapter::Decrypt(pp::Buffer_Dev encrypted_buffer, const PP_EncryptedBlockInfo& encrypted_block_info) { PP_DCHECK(!encrypted_buffer.is_null()); // Release a buffer that the caller indicated it is finished with. allocator_.Release(encrypted_block_info.tracking_info.buffer_id); cdm::Status status = cdm::kDecryptError; LinkedDecryptedBlock decrypted_block(new DecryptedBlockImpl()); if (cdm_) { cdm::InputBuffer input_buffer; std::vector<cdm::SubsampleEntry> subsamples; ConfigureInputBuffer(encrypted_buffer, encrypted_block_info, &subsamples, &input_buffer); status = cdm_->Decrypt(input_buffer, decrypted_block.get()); PP_DCHECK(status != cdm::kSuccess || (decrypted_block->DecryptedBuffer() && decrypted_block->DecryptedBuffer()->Size())); } CallOnMain(callback_factory_.NewCallback( &CdmAdapter::DeliverBlock, status, decrypted_block, encrypted_block_info.tracking_info)); } void CdmAdapter::InitializeAudioDecoder( const PP_AudioDecoderConfig& decoder_config, pp::Buffer_Dev extra_data_buffer) { PP_DCHECK(!deferred_initialize_audio_decoder_); PP_DCHECK(deferred_audio_decoder_config_id_ == 0); cdm::Status status = cdm::kSessionError; if (cdm_) { cdm::AudioDecoderConfig cdm_decoder_config; cdm_decoder_config.codec = PpAudioCodecToCdmAudioCodec(decoder_config.codec); cdm_decoder_config.channel_count = decoder_config.channel_count; cdm_decoder_config.bits_per_channel = decoder_config.bits_per_channel; cdm_decoder_config.samples_per_second = decoder_config.samples_per_second; cdm_decoder_config.extra_data = static_cast<uint8_t*>(extra_data_buffer.data()); cdm_decoder_config.extra_data_size = extra_data_buffer.size(); status = cdm_->InitializeAudioDecoder(cdm_decoder_config); } if (status == cdm::kDeferredInitialization) { deferred_initialize_audio_decoder_ = true; deferred_audio_decoder_config_id_ = decoder_config.request_id; return; } CallOnMain(callback_factory_.NewCallback( &CdmAdapter::DecoderInitializeDone, PP_DECRYPTORSTREAMTYPE_AUDIO, decoder_config.request_id, status == cdm::kSuccess)); } void CdmAdapter::InitializeVideoDecoder( const PP_VideoDecoderConfig& decoder_config, pp::Buffer_Dev extra_data_buffer) { PP_DCHECK(!deferred_initialize_video_decoder_); PP_DCHECK(deferred_video_decoder_config_id_ == 0); cdm::Status status = cdm::kSessionError; if (cdm_) { cdm::VideoDecoderConfig cdm_decoder_config; cdm_decoder_config.codec = PpVideoCodecToCdmVideoCodec(decoder_config.codec); cdm_decoder_config.profile = PpVCProfileToCdmVCProfile(decoder_config.profile); cdm_decoder_config.format = PpDecryptedFrameFormatToCdmVideoFormat(decoder_config.format); cdm_decoder_config.coded_size.width = decoder_config.width; cdm_decoder_config.coded_size.height = decoder_config.height; cdm_decoder_config.extra_data = static_cast<uint8_t*>(extra_data_buffer.data()); cdm_decoder_config.extra_data_size = extra_data_buffer.size(); status = cdm_->InitializeVideoDecoder(cdm_decoder_config); } if (status == cdm::kDeferredInitialization) { deferred_initialize_video_decoder_ = true; deferred_video_decoder_config_id_ = decoder_config.request_id; return; } CallOnMain(callback_factory_.NewCallback( &CdmAdapter::DecoderInitializeDone, PP_DECRYPTORSTREAMTYPE_VIDEO, decoder_config.request_id, status == cdm::kSuccess)); } void CdmAdapter::DeinitializeDecoder(PP_DecryptorStreamType decoder_type, uint32_t request_id) { PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded. if (cdm_) { cdm_->DeinitializeDecoder( PpDecryptorStreamTypeToCdmStreamType(decoder_type)); } CallOnMain(callback_factory_.NewCallback( &CdmAdapter::DecoderDeinitializeDone, decoder_type, request_id)); } void CdmAdapter::ResetDecoder(PP_DecryptorStreamType decoder_type, uint32_t request_id) { PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded. if (cdm_) cdm_->ResetDecoder(PpDecryptorStreamTypeToCdmStreamType(decoder_type)); CallOnMain(callback_factory_.NewCallback(&CdmAdapter::DecoderResetDone, decoder_type, request_id)); } void CdmAdapter::DecryptAndDecode( PP_DecryptorStreamType decoder_type, pp::Buffer_Dev encrypted_buffer, const PP_EncryptedBlockInfo& encrypted_block_info) { PP_DCHECK(cdm_); // InitializeXxxxxDecoder should have succeeded. // Release a buffer that the caller indicated it is finished with. allocator_.Release(encrypted_block_info.tracking_info.buffer_id); cdm::InputBuffer input_buffer; std::vector<cdm::SubsampleEntry> subsamples; if (cdm_ && !encrypted_buffer.is_null()) { ConfigureInputBuffer(encrypted_buffer, encrypted_block_info, &subsamples, &input_buffer); } cdm::Status status = cdm::kDecodeError; switch (decoder_type) { case PP_DECRYPTORSTREAMTYPE_VIDEO: { LinkedVideoFrame video_frame(new VideoFrameImpl()); if (cdm_) status = cdm_->DecryptAndDecodeFrame(input_buffer, video_frame.get()); CallOnMain(callback_factory_.NewCallback( &CdmAdapter::DeliverFrame, status, video_frame, encrypted_block_info.tracking_info)); return; } case PP_DECRYPTORSTREAMTYPE_AUDIO: { LinkedAudioFrames audio_frames(new AudioFramesImpl()); if (cdm_) { status = cdm_->DecryptAndDecodeSamples(input_buffer, audio_frames.get()); } CallOnMain(callback_factory_.NewCallback( &CdmAdapter::DeliverSamples, status, audio_frames, encrypted_block_info.tracking_info)); return; } default: PP_NOTREACHED(); return; } } cdm::Buffer* CdmAdapter::Allocate(uint32_t capacity) { return allocator_.Allocate(capacity); } void CdmAdapter::SetTimer(int64_t delay_ms, void* context) { // NOTE: doesn't really need to run on the main thread; could just as well run // on a helper thread if |cdm_| were thread-friendly and care was taken. We // only use CallOnMainThread() here to get delayed-execution behavior. pp::Module::Get()->core()->CallOnMainThread( delay_ms, callback_factory_.NewCallback(&CdmAdapter::TimerExpired, context), PP_OK); } void CdmAdapter::TimerExpired(int32_t result, void* context) { PP_DCHECK(result == PP_OK); cdm_->TimerExpired(context); } double CdmAdapter::GetCurrentWallTimeInSeconds() { return pp::Module::Get()->core()->GetTime(); } void CdmAdapter::SendKeyMessage( const char* session_id, uint32_t session_id_length, const char* message, uint32_t message_length, const char* default_url, uint32_t default_url_length) { PP_DCHECK(!key_system_.empty()); PostOnMain(callback_factory_.NewCallback( &CdmAdapter::KeyMessage, SessionInfo(key_system_, std::string(session_id, session_id_length)), std::vector<uint8>(message, message + message_length), std::string(default_url, default_url_length))); } void CdmAdapter::SendKeyError(const char* session_id, uint32_t session_id_length, cdm::MediaKeyError error_code, uint32_t system_code) { SendKeyErrorInternal(key_system_, std::string(session_id, session_id_length), error_code, system_code); } void CdmAdapter::GetPrivateData(int32_t* instance, GetPrivateInterface* get_interface) { *instance = pp_instance(); *get_interface = pp::Module::Get()->get_browser_interface(); } void CdmAdapter::SendUnknownKeyError(const std::string& key_system, const std::string& session_id) { SendKeyErrorInternal(key_system, session_id, cdm::kUnknownError, 0); } void CdmAdapter::SendKeyAdded(const std::string& key_system, const std::string& session_id) { PostOnMain(callback_factory_.NewCallback( &CdmAdapter::KeyAdded, SessionInfo(key_system_, session_id))); } void CdmAdapter::SendKeyErrorInternal(const std::string& key_system, const std::string& session_id, cdm::MediaKeyError error_code, uint32_t system_code) { PostOnMain(callback_factory_.NewCallback(&CdmAdapter::KeyError, SessionInfo(key_system_, session_id), error_code, system_code)); } void CdmAdapter::KeyAdded(int32_t result, const SessionInfo& session_info) { PP_DCHECK(result == PP_OK); PP_DCHECK(!session_info.key_system.empty()); pp::ContentDecryptor_Private::KeyAdded(session_info.key_system, session_info.session_id); } void CdmAdapter::KeyMessage(int32_t result, const SessionInfo& session_info, const std::vector<uint8>& message, const std::string& default_url) { PP_DCHECK(result == PP_OK); PP_DCHECK(!session_info.key_system.empty()); pp::VarArrayBuffer message_array_buffer(message.size()); if (message.size() > 0) { memcpy(message_array_buffer.Map(), message.data(), message.size()); } pp::ContentDecryptor_Private::KeyMessage( session_info.key_system, session_info.session_id, message_array_buffer, default_url); } void CdmAdapter::KeyError(int32_t result, const SessionInfo& session_info, cdm::MediaKeyError error_code, uint32_t system_code) { PP_DCHECK(result == PP_OK); pp::ContentDecryptor_Private::KeyError( session_info.key_system, session_info.session_id, error_code, system_code); } void CdmAdapter::DeliverBlock(int32_t result, const cdm::Status& status, const LinkedDecryptedBlock& decrypted_block, const PP_DecryptTrackingInfo& tracking_info) { PP_DCHECK(result == PP_OK); PP_DecryptedBlockInfo decrypted_block_info; decrypted_block_info.tracking_info = tracking_info; decrypted_block_info.tracking_info.timestamp = decrypted_block->Timestamp(); decrypted_block_info.tracking_info.buffer_id = 0; decrypted_block_info.data_size = 0; decrypted_block_info.result = CdmStatusToPpDecryptResult(status); pp::Buffer_Dev buffer; if (decrypted_block_info.result == PP_DECRYPTRESULT_SUCCESS) { PP_DCHECK(decrypted_block.get() && decrypted_block->DecryptedBuffer()); if (!decrypted_block.get() || !decrypted_block->DecryptedBuffer()) { PP_NOTREACHED(); decrypted_block_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR; } else { PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(decrypted_block->DecryptedBuffer()); buffer = ppb_buffer->buffer_dev(); decrypted_block_info.tracking_info.buffer_id = ppb_buffer->buffer_id(); decrypted_block_info.data_size = ppb_buffer->Size(); } } pp::ContentDecryptor_Private::DeliverBlock(buffer, decrypted_block_info); } void CdmAdapter::DecoderInitializeDone(int32_t result, PP_DecryptorStreamType decoder_type, uint32_t request_id, bool success) { PP_DCHECK(result == PP_OK); pp::ContentDecryptor_Private::DecoderInitializeDone(decoder_type, request_id, success); } void CdmAdapter::DecoderDeinitializeDone(int32_t result, PP_DecryptorStreamType decoder_type, uint32_t request_id) { pp::ContentDecryptor_Private::DecoderDeinitializeDone(decoder_type, request_id); } void CdmAdapter::DecoderResetDone(int32_t result, PP_DecryptorStreamType decoder_type, uint32_t request_id) { pp::ContentDecryptor_Private::DecoderResetDone(decoder_type, request_id); } void CdmAdapter::DeliverFrame( int32_t result, const cdm::Status& status, const LinkedVideoFrame& video_frame, const PP_DecryptTrackingInfo& tracking_info) { PP_DCHECK(result == PP_OK); PP_DecryptedFrameInfo decrypted_frame_info; decrypted_frame_info.tracking_info.request_id = tracking_info.request_id; decrypted_frame_info.tracking_info.buffer_id = 0; decrypted_frame_info.result = CdmStatusToPpDecryptResult(status); pp::Buffer_Dev buffer; if (decrypted_frame_info.result == PP_DECRYPTRESULT_SUCCESS) { if (!IsValidVideoFrame(video_frame)) { PP_NOTREACHED(); decrypted_frame_info.result = PP_DECRYPTRESULT_DECODE_ERROR; } else { PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(video_frame->FrameBuffer()); buffer = ppb_buffer->buffer_dev(); decrypted_frame_info.tracking_info.timestamp = video_frame->Timestamp(); decrypted_frame_info.tracking_info.buffer_id = ppb_buffer->buffer_id(); decrypted_frame_info.format = CdmVideoFormatToPpDecryptedFrameFormat(video_frame->Format()); decrypted_frame_info.width = video_frame->Size().width; decrypted_frame_info.height = video_frame->Size().height; decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_Y] = video_frame->PlaneOffset(cdm::VideoFrame::kYPlane); decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_U] = video_frame->PlaneOffset(cdm::VideoFrame::kUPlane); decrypted_frame_info.plane_offsets[PP_DECRYPTEDFRAMEPLANES_V] = video_frame->PlaneOffset(cdm::VideoFrame::kVPlane); decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_Y] = video_frame->Stride(cdm::VideoFrame::kYPlane); decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_U] = video_frame->Stride(cdm::VideoFrame::kUPlane); decrypted_frame_info.strides[PP_DECRYPTEDFRAMEPLANES_V] = video_frame->Stride(cdm::VideoFrame::kVPlane); } } pp::ContentDecryptor_Private::DeliverFrame(buffer, decrypted_frame_info); } void CdmAdapter::DeliverSamples(int32_t result, const cdm::Status& status, const LinkedAudioFrames& audio_frames, const PP_DecryptTrackingInfo& tracking_info) { PP_DCHECK(result == PP_OK); PP_DecryptedSampleInfo decrypted_sample_info; decrypted_sample_info.tracking_info = tracking_info; decrypted_sample_info.tracking_info.timestamp = 0; decrypted_sample_info.tracking_info.buffer_id = 0; decrypted_sample_info.data_size = 0; decrypted_sample_info.result = CdmStatusToPpDecryptResult(status); pp::Buffer_Dev buffer; if (decrypted_sample_info.result == PP_DECRYPTRESULT_SUCCESS) { PP_DCHECK(audio_frames.get() && audio_frames->FrameBuffer()); if (!audio_frames.get() || !audio_frames->FrameBuffer()) { PP_NOTREACHED(); decrypted_sample_info.result = PP_DECRYPTRESULT_DECRYPT_ERROR; } else { PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(audio_frames->FrameBuffer()); buffer = ppb_buffer->buffer_dev(); decrypted_sample_info.tracking_info.buffer_id = ppb_buffer->buffer_id(); decrypted_sample_info.data_size = ppb_buffer->Size(); decrypted_sample_info.format = CdmAudioFormatToPpDecryptedSampleFormat(audio_frames->Format()); } } pp::ContentDecryptor_Private::DeliverSamples(buffer, decrypted_sample_info); } bool CdmAdapter::IsValidVideoFrame(const LinkedVideoFrame& video_frame) { if (!video_frame.get() || !video_frame->FrameBuffer() || (video_frame->Format() != cdm::kI420 && video_frame->Format() != cdm::kYv12)) { return false; } PpbBuffer* ppb_buffer = static_cast<PpbBuffer*>(video_frame->FrameBuffer()); for (uint32_t i = 0; i < cdm::VideoFrame::kMaxPlanes; ++i) { int plane_height = (i == cdm::VideoFrame::kYPlane) ? video_frame->Size().height : (video_frame->Size().height + 1) / 2; cdm::VideoFrame::VideoPlane plane = static_cast<cdm::VideoFrame::VideoPlane>(i); if (ppb_buffer->Size() < video_frame->PlaneOffset(plane) + plane_height * video_frame->Stride(plane)) { return false; } } return true; } void CdmAdapter::SendPlatformChallenge( const char* service_id, uint32_t service_id_length, const char* challenge, uint32_t challenge_length) { #if defined(OS_CHROMEOS) PP_DCHECK(!challenge_in_progress_); // Ensure member variables set by the callback are in a clean state. signed_data_output_ = pp::Var(); signed_data_signature_output_ = pp::Var(); platform_key_certificate_output_ = pp::Var(); pp::VarArrayBuffer challenge_var(challenge_length); uint8_t* var_data = static_cast<uint8_t*>(challenge_var.Map()); memcpy(var_data, challenge, challenge_length); std::string service_id_str(service_id, service_id_length); int32_t result = platform_verification_.ChallengePlatform( pp::Var(service_id_str), challenge_var, &signed_data_output_, &signed_data_signature_output_, &platform_key_certificate_output_, callback_factory_.NewCallback(&CdmAdapter::SendPlatformChallengeDone)); challenge_var.Unmap(); if (result == PP_OK_COMPLETIONPENDING) { challenge_in_progress_ = true; return; } // Fall through on error and issue an empty OnPlatformChallengeResponse(). PP_DCHECK(result != PP_OK); #endif cdm::PlatformChallengeResponse response = {}; cdm_->OnPlatformChallengeResponse(response); } void CdmAdapter::EnableOutputProtection(uint32_t desired_protection_mask) { #if defined(OS_CHROMEOS) output_protection_.EnableProtection( desired_protection_mask, callback_factory_.NewCallback( &CdmAdapter::EnableProtectionDone)); // Errors are ignored since clients must call QueryOutputProtectionStatus() to // inspect the protection status on a regular basis. // TODO(dalecurtis): It'd be nice to log a message or non-fatal error here... #endif } void CdmAdapter::QueryOutputProtectionStatus() { #if defined(OS_CHROMEOS) PP_DCHECK(!query_output_protection_in_progress_); output_link_mask_ = output_protection_mask_ = 0; const int32_t result = output_protection_.QueryStatus( &output_link_mask_, &output_protection_mask_, callback_factory_.NewCallback( &CdmAdapter::QueryOutputProtectionStatusDone)); if (result == PP_OK_COMPLETIONPENDING) { query_output_protection_in_progress_ = true; return; } // Fall through on error and issue an empty OnQueryOutputProtectionStatus(). PP_DCHECK(result != PP_OK); #endif cdm_->OnQueryOutputProtectionStatus(0, 0); } void CdmAdapter::OnDeferredInitializationDone(cdm::StreamType stream_type, cdm::Status decoder_status) { switch (stream_type) { case cdm::kStreamTypeAudio: PP_DCHECK(deferred_initialize_audio_decoder_); CallOnMain( callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone, PP_DECRYPTORSTREAMTYPE_AUDIO, deferred_audio_decoder_config_id_, decoder_status == cdm::kSuccess)); deferred_initialize_audio_decoder_ = false; deferred_audio_decoder_config_id_ = 0; break; case cdm::kStreamTypeVideo: PP_DCHECK(deferred_initialize_video_decoder_); CallOnMain( callback_factory_.NewCallback(&CdmAdapter::DecoderInitializeDone, PP_DECRYPTORSTREAMTYPE_VIDEO, deferred_video_decoder_config_id_, decoder_status == cdm::kSuccess)); deferred_initialize_video_decoder_ = false; deferred_video_decoder_config_id_ = 0; break; } } #if defined(OS_CHROMEOS) void CdmAdapter::SendPlatformChallengeDone(int32_t result) { challenge_in_progress_ = false; if (result != PP_OK) { cdm::PlatformChallengeResponse response = {}; cdm_->OnPlatformChallengeResponse(response); return; } pp::VarArrayBuffer signed_data_var(signed_data_output_); pp::VarArrayBuffer signed_data_signature_var(signed_data_signature_output_); std::string platform_key_certificate_string = platform_key_certificate_output_.AsString(); cdm::PlatformChallengeResponse response = { static_cast<uint8_t*>(signed_data_var.Map()), signed_data_var.ByteLength(), static_cast<uint8_t*>(signed_data_signature_var.Map()), signed_data_signature_var.ByteLength(), reinterpret_cast<const uint8_t*>(platform_key_certificate_string.c_str()), static_cast<uint32_t>(platform_key_certificate_string.length()) }; cdm_->OnPlatformChallengeResponse(response); signed_data_var.Unmap(); signed_data_signature_var.Unmap(); } void CdmAdapter::EnableProtectionDone(int32_t result) { // Does nothing since clients must call QueryOutputProtectionStatus() to // inspect the protection status on a regular basis. // TODO(dalecurtis): It'd be nice to log a message or non-fatal error here... } void CdmAdapter::QueryOutputProtectionStatusDone(int32_t result) { PP_DCHECK(query_output_protection_in_progress_); query_output_protection_in_progress_ = false; // Return a protection status of none on error. if (result != PP_OK) output_link_mask_ = output_protection_mask_ = 0; cdm_->OnQueryOutputProtectionStatus(output_link_mask_, output_protection_mask_); } #endif void* GetCdmHost(int host_interface_version, void* user_data) { if (!host_interface_version || !user_data) return NULL; COMPILE_ASSERT(cdm::ContentDecryptionModule::Host::kVersion == cdm::ContentDecryptionModule_2::Host::kVersion, update_code_below); // Ensure IsSupportedCdmHostVersion matches implementation of this function. // Always update this DCHECK when updating this function. // If this check fails, update this function and DCHECK or update // IsSupportedCdmHostVersion. PP_DCHECK( // Future version is not supported. !IsSupportedCdmHostVersion( cdm::ContentDecryptionModule::Host::kVersion + 1) && // Current version is supported. IsSupportedCdmHostVersion(cdm::ContentDecryptionModule::Host::kVersion) && // Include all previous supported versions here. IsSupportedCdmHostVersion(cdm::Host_1::kVersion) && // One older than the oldest supported version is not supported. !IsSupportedCdmHostVersion(cdm::Host_1::kVersion - 1)); PP_DCHECK(IsSupportedCdmHostVersion(host_interface_version)); CdmAdapter* cdm_adapter = static_cast<CdmAdapter*>(user_data); switch (host_interface_version) { // The latest CDM host version. case cdm::ContentDecryptionModule::Host::kVersion: return static_cast<cdm::ContentDecryptionModule::Host*>(cdm_adapter); // Older supported version(s) of the CDM host. case cdm::Host_1::kVersion: return static_cast<cdm::Host_1*>(cdm_adapter); default: PP_NOTREACHED(); return NULL; } } // This object is the global object representing this plugin library as long // as it is loaded. class CdmAdapterModule : public pp::Module { public: CdmAdapterModule() : pp::Module() { // This function blocks the renderer thread (PluginInstance::Initialize()). // Move this call to other places if this may be a concern in the future. INITIALIZE_CDM_MODULE(); } virtual ~CdmAdapterModule() { DeinitializeCdmModule(); } virtual pp::Instance* CreateInstance(PP_Instance instance) { return new CdmAdapter(instance, this); } }; } // namespace media namespace pp { // Factory function for your specialization of the Module object. Module* CreateModule() { return new media::CdmAdapterModule(); } } // namespace pp
{'content_hash': '06e0be8e1bc9ecfebd0ee08f71c389b2', 'timestamp': '', 'source': 'github', 'line_count': 963, 'max_line_length': 80, 'avg_line_length': 36.781931464174455, 'alnum_prop': 0.6659608706699416, 'repo_name': 'cvsuser-chromium/chromium', 'id': 'f8adb03ba5199ae2e6c88ee7259d095eb724b9d9', 'size': '35874', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'media/cdm/ppapi/cdm_adapter.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Assembly', 'bytes': '36421'}, {'name': 'C', 'bytes': '6924841'}, {'name': 'C++', 'bytes': '179649999'}, {'name': 'CSS', 'bytes': '812951'}, {'name': 'Java', 'bytes': '3768838'}, {'name': 'JavaScript', 'bytes': '8338074'}, {'name': 'Makefile', 'bytes': '52980'}, {'name': 'Objective-C', 'bytes': '819293'}, {'name': 'Objective-C++', 'bytes': '6453781'}, {'name': 'PHP', 'bytes': '61320'}, {'name': 'Perl', 'bytes': '17897'}, {'name': 'Python', 'bytes': '5640877'}, {'name': 'Rebol', 'bytes': '262'}, {'name': 'Shell', 'bytes': '648699'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '15926'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- weighted social network of known and suspected terrorists --> <!-- involved in the September 11, 2001 attacks --> <graphml xmlns="http://graphml.graphdrawing.org/xmlns"> <graph edgedefault="undirected"> <!-- data schema --> <key id="name" for="node" attr.name="name" attr.type="string"/> <key id="flight" for="node" attr.name="flight" attr.type="string"> <default></default> </key> <key id="pilot" for="node" attr.name="pilot" attr.type="boolean"> <default>false</default> </key> <key id="weight" for="edge" attr.name="weight" attr.type="int"/> <!-- nodes --> <node id="al-shehhi"> <data key="name">Marwan Al-Shehhi</data> <data key="flight">United Airlines Flight 175 (WTC2)</data> <data key="pilot">true</data> </node> <node id="alshehri"> <data key="name">Waleed M. Alshehri</data> <data key="flight">American Airlines Flight 11 (WTC1)</data> </node> <node id="halghamdi"> <data key="name">Hamza Alghamdi</data> <data key="flight">United Airlines Flight 175 (WTC2)</data> </node> <node id="alsuqami"> <data key="name">Satam M. A. Al Suqami</data> <data key="flight">American Airlines Flight 11 (WTC1)</data> </node> <node id="omar"> <data key="name">Ramzi Omar</data> </node> <node id="abdullah"> <data key="name">Rayed Mohammed Abdullah</data> </node> <node id="essabar"> <data key="name">Zakariya Essabar</data> </node> <node id="moqed"> <data key="name">Majed Moqed</data> <data key="flight">American Airlines Flight 77 (Pentagon)</data> </node> <node id="nalhazmi"> <data key="name">Nawaf Alhazmi</data> <data key="flight">American Airlines Flight 77 (Pentagon)</data> </node> <node id="salim"> <data key="name">Mamduh Mahmud Salim</data> </node> <node id="atta"> <data key="name">Mohamed Atta</data> <data key="flight">American Airlines Flight 11 (WTC1)</data> <data key="pilot">true</data> </node> <node id="moussaoui"> <data key="name">Habib Zacarias Moussaoui</data> </node> <node id="raissi"> <data key="name">Lotfi Raissi</data> </node> <node id="bahaji"> <data key="name">Said Bahaji</data> </node> <node id="al-marabh"> <data key="name">Nabil al-Marabh</data> </node> <node id="salhazmi"> <data key="name">Salem Alhazmi</data> <data key="flight">American Airlines Flight 77 (Pentagon)</data> </node> <node id="aalghamdi"> <data key="name">Ahmed Alghamdi</data> <data key="flight">United Airlines Flight 175 (WTC2)</data> </node> <node id="abdi"> <data key="name">Mohamed Abdi</data> </node> <node id="saiid"> <data key="name">Shaykh Saiid</data> </node> <node id="alhaznawi"> <data key="name">Ahmed Ibrahim A. Al Haznawi</data> <data key="flight">United Airlines Flight 93 (Pennsylvania)</data> </node> <node id="alomari"> <data key="name">Abdulaziz Alomari</data> <data key="flight">American Airlines Flight 11 (WTC1)</data> </node> <node id="darkazanli"> <data key="name">Mamoun Darkazanli</data> </node> <node id="alnami"> <data key="name">Ahmed Alnami</data> <data key="flight">United Airlines Flight 93 (Pennsylvania)</data> </node> <node id="salghamdi"> <data key="name">Saeed Alghamdi</data> <data key="flight">United Airlines Flight 93 (Pennsylvania)</data> </node> <node id="hijazi"> <data key="name">Raed Hijazi</data> </node> <node id="malshehri"> <data key="name">Mohand Alshehri</data> <data key="flight">United Airlines Flight 175 (WTC2)</data> </node> <node id="almihdhar"> <data key="name">Khalid Almihdhar</data> <data key="flight">American Airlines Flight 77 (Pentagon)</data> </node> <node id="shaikh"> <data key="name">Abdussattar Shaikh</data> </node> <node id="jarrah"> <data key="name">Ziad Samir Jarrah</data> <data key="flight">United Airlines Flight 93 (Pennsylvania)</data> <data key="pilot">true</data> </node> <node id="walshehri"> <data key="name">Wail M. Alshehri</data> <data key="flight">American Airlines Flight 11 (WTC1)</data> </node> <node id="banihammad"> <data key="name">Fayez Rashid Ahmed Hassan Al Qadi Banihammad</data> <data key="flight">United Airlines Flight 175 (WTC2)</data> </node> <node id="alsalmi"> <data key="name">Faisal Al Salmi</data> </node> <node id="al-ani"> <data key="name">Ahmed Khalil Ibrahim Samir Al-Ani</data> </node> <node id="hanjour"> <data key="name">Hani Hanjour</data> <data key="flight">American Airlines Flight 77 (Pentagon)</data> <data key="pilot">true</data> </node> <!-- edges --> <edge source="al-shehhi" target="halghamdi"><data key="weight">1</data></edge> <edge source="al-shehhi" target="raissi"><data key="weight">2</data></edge> <edge source="al-shehhi" target="essabar"><data key="weight">3</data></edge> <edge source="al-shehhi" target="atta"><data key="weight">3</data></edge> <edge source="al-shehhi" target="omar"><data key="weight">3</data></edge> <edge source="al-shehhi" target="bahaji"><data key="weight">3</data></edge> <edge source="al-shehhi" target="jarrah"><data key="weight">3</data></edge> <edge source="al-shehhi" target="darkazanli"><data key="weight">2</data></edge> <edge source="al-shehhi" target="saiid"><data key="weight">1</data></edge> <edge source="al-shehhi" target="alshehri"><data key="weight">1</data></edge> <edge source="al-shehhi" target="walshehri"><data key="weight">1</data></edge> <edge source="al-shehhi" target="alsuqami"><data key="weight">1</data></edge> <edge source="alshehri" target="saiid"><data key="weight">1</data></edge> <edge source="alshehri" target="walshehri"><data key="weight">3</data></edge> <edge source="alshehri" target="alomari"><data key="weight">1</data></edge> <edge source="alshehri" target="alsuqami"><data key="weight">3</data></edge> <edge source="alshehri" target="banihammad"><data key="weight">1</data></edge> <edge source="halghamdi" target="nalhazmi"><data key="weight">2</data></edge> <edge source="halghamdi" target="alnami"><data key="weight">3</data></edge> <edge source="halghamdi" target="salghamdi"><data key="weight">2</data></edge> <edge source="halghamdi" target="aalghamdi"><data key="weight">2</data></edge> <edge source="halghamdi" target="alhaznawi"><data key="weight">3</data></edge> <edge source="halghamdi" target="malshehri"><data key="weight">2</data></edge> <edge source="alsuqami" target="hijazi"><data key="weight">2</data></edge> <edge source="alsuqami" target="al-marabh"><data key="weight">2</data></edge> <edge source="alsuqami" target="banihammad"><data key="weight">1</data></edge> <edge source="alsuqami" target="walshehri"><data key="weight">3</data></edge> <edge source="alsuqami" target="alomari"><data key="weight">1</data></edge> <edge source="alsuqami" target="atta"><data key="weight">1</data></edge> <edge source="omar" target="bahaji"><data key="weight">3</data></edge> <edge source="omar" target="essabar"><data key="weight">3</data></edge> <edge source="omar" target="atta"><data key="weight">3</data></edge> <edge source="omar" target="jarrah"><data key="weight">3</data></edge> <edge source="abdullah" target="alsalmi"><data key="weight">1</data></edge> <edge source="abdullah" target="hanjour"><data key="weight">3</data></edge> <edge source="abdullah" target="raissi"><data key="weight">2</data></edge> <edge source="essabar" target="atta"><data key="weight">3</data></edge> <edge source="essabar" target="bahaji"><data key="weight">3</data></edge> <edge source="essabar" target="jarrah"><data key="weight">3</data></edge> <edge source="moqed" target="almihdhar"><data key="weight">1</data></edge> <edge source="moqed" target="nalhazmi"><data key="weight">1</data></edge> <edge source="moqed" target="salhazmi"><data key="weight">1</data></edge> <edge source="moqed" target="hanjour"><data key="weight">3</data></edge> <edge source="nalhazmi" target="shaikh"><data key="weight">2</data></edge> <edge source="nalhazmi" target="almihdhar"><data key="weight">3</data></edge> <edge source="nalhazmi" target="abdi"><data key="weight">2</data></edge> <edge source="nalhazmi" target="alnami"><data key="weight">3</data></edge> <edge source="nalhazmi" target="salghamdi"><data key="weight">3</data></edge> <edge source="nalhazmi" target="hanjour"><data key="weight">3</data></edge> <edge source="nalhazmi" target="salhazmi"><data key="weight">3</data></edge> <edge source="salim" target="darkazanli"><data key="weight">2</data></edge> <edge source="atta" target="hanjour"><data key="weight">2</data></edge> <edge source="atta" target="moussaoui"><data key="weight">1</data></edge> <edge source="atta" target="raissi"><data key="weight">2</data></edge> <edge source="atta" target="al-ani"><data key="weight">2</data></edge> <edge source="atta" target="jarrah"><data key="weight">3</data></edge> <edge source="atta" target="bahaji"><data key="weight">3</data></edge> <edge source="atta" target="darkazanli"><data key="weight">2</data></edge> <edge source="atta" target="saiid"><data key="weight">1</data></edge> <edge source="atta" target="walshehri"><data key="weight">1</data></edge> <edge source="atta" target="banihammad"><data key="weight">1</data></edge> <edge source="raissi" target="hanjour"><data key="weight">2</data></edge> <edge source="raissi" target="jarrah"><data key="weight">2</data></edge> <edge source="bahaji" target="jarrah"><data key="weight">3</data></edge> <edge source="al-marabh" target="aalghamdi"><data key="weight">2</data></edge> <edge source="al-marabh" target="hijazi"><data key="weight">2</data></edge> <edge source="al-marabh" target="salghamdi"><data key="weight">2</data></edge> <edge source="salhazmi" target="almihdhar"><data key="weight">1</data></edge> <edge source="salhazmi" target="hanjour"><data key="weight">2</data></edge> <edge source="salhazmi" target="aalghamdi"><data key="weight">1</data></edge> <edge source="salhazmi" target="alomari"><data key="weight">1</data></edge> <edge source="salghamdi" target="alhaznawi"><data key="weight">3</data></edge> <edge source="aalghamdi" target="hanjour"><data key="weight">1</data></edge> <edge source="aalghamdi" target="alomari"><data key="weight">1</data></edge> <edge source="alhaznawi" target="jarrah"><data key="weight">3</data></edge> <edge source="alomari" target="banihammad"><data key="weight">1</data></edge> <edge source="alomari" target="walshehri"><data key="weight">1</data></edge> <edge source="alomari" target="hanjour"><data key="weight">1</data></edge> <edge source="alnami" target="salghamdi"><data key="weight">3</data></edge> <edge source="salghamdi" target="hijazi"><data key="weight">2</data></edge> <edge source="malshehri" target="banihammad"><data key="weight">2</data></edge> <edge source="almihdhar" target="shaikh"><data key="weight">3</data></edge> <edge source="almihdhar" target="hanjour"><data key="weight">3</data></edge> <edge source="walshehri" target="banihammad"><data key="weight">1</data></edge> <edge source="alsalmi" target="hanjour"><data key="weight">1</data></edge> </graph> </graphml>
{'content_hash': '303641eadd4388ebea322ee1d8193a1d', 'timestamp': '', 'source': 'github', 'line_count': 234, 'max_line_length': 81, 'avg_line_length': 49.82051282051282, 'alnum_prop': 0.6400754846457368, 'repo_name': 'luizvarela/grafos_java', 'id': '2730137b34f849e6e09e7088d4bf02e64d2ed96e', 'size': '11658', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'build/terror.xml', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '2698909'}, {'name': 'Shell', 'bytes': '587'}]}
@interface PACreateSubscriptionRequest : NSObject @property (nonatomic, strong) NSString *userIdentifier; @property (nonatomic, strong) NSString *planIdentifier; @property (nonatomic, strong) NSString *orderIdentifier; @property (nonatomic, strong) NSString *orderDescription; @property (nonatomic, assign) NSInteger amount; @property (nonatomic, strong) NSString *currency; @end
{'content_hash': '3fac6d1e2a389fe2b462e48525e70d47', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 57, 'avg_line_length': 38.2, 'alnum_prop': 0.8036649214659686, 'repo_name': 'gimenete/pagantis-ios', 'id': 'c2d0aa3a164953a120d6934847c5066e5af40875', 'size': '583', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Pagantis/Pagantis/PagantisSDK/PACreateSubscriptionRequest.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '91331'}, {'name': 'Ruby', 'bytes': '722'}]}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v11/services/extension_feed_item_service.proto package com.google.ads.googleads.v11.services; public interface MutateExtensionFeedItemsResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v11.services.MutateExtensionFeedItemsResponse) com.google.protobuf.MessageOrBuilder { /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (for example, auth * errors), we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return Whether the partialFailureError field is set. */ boolean hasPartialFailureError(); /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (for example, auth * errors), we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> * @return The partialFailureError. */ com.google.rpc.Status getPartialFailureError(); /** * <pre> * Errors that pertain to operation failures in the partial failure mode. * Returned only when partial_failure = true and all errors occur inside the * operations. If any errors occur outside the operations (for example, auth * errors), we return an RPC level error. * </pre> * * <code>.google.rpc.Status partial_failure_error = 3;</code> */ com.google.rpc.StatusOrBuilder getPartialFailureErrorOrBuilder(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v11.services.MutateExtensionFeedItemResult results = 2;</code> */ java.util.List<com.google.ads.googleads.v11.services.MutateExtensionFeedItemResult> getResultsList(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v11.services.MutateExtensionFeedItemResult results = 2;</code> */ com.google.ads.googleads.v11.services.MutateExtensionFeedItemResult getResults(int index); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v11.services.MutateExtensionFeedItemResult results = 2;</code> */ int getResultsCount(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v11.services.MutateExtensionFeedItemResult results = 2;</code> */ java.util.List<? extends com.google.ads.googleads.v11.services.MutateExtensionFeedItemResultOrBuilder> getResultsOrBuilderList(); /** * <pre> * All results for the mutate. * </pre> * * <code>repeated .google.ads.googleads.v11.services.MutateExtensionFeedItemResult results = 2;</code> */ com.google.ads.googleads.v11.services.MutateExtensionFeedItemResultOrBuilder getResultsOrBuilder( int index); }
{'content_hash': '4ff5da7c3224e8154e95f310792a97e3', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 117, 'avg_line_length': 35.87640449438202, 'alnum_prop': 0.7062323833385531, 'repo_name': 'googleads/google-ads-java', 'id': '8fd13f117dd4ab4eab30633041759cd62ba2d2c2', 'size': '3193', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'google-ads-stubs-v11/src/main/java/com/google/ads/googleads/v11/services/MutateExtensionFeedItemsResponseOrBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '28701198'}]}
require 'spec_helper' require 'liberty_buildpack/util/constantize' describe 'constantize' do it 'should constantize string' do expect('Test::StubClass'.constantize).to eq(Test::StubClass) end it 'should raise error if constant does not exist' do expect { 'Test::StubClass2'.constantize }.to raise_error(NameError) end end module Test class StubClass end end
{'content_hash': 'c6485ae156d8eaa9fedc2a8de265a063', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 71, 'avg_line_length': 20.157894736842106, 'alnum_prop': 0.7389033942558747, 'repo_name': 'barthy1/ibm-websphere-liberty-buildpack', 'id': 'd5604fc7613a91d4928ababab7fe172450c04b11', 'size': '1051', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'spec/liberty_buildpack/util/constantize_spec.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '46'}, {'name': 'Ruby', 'bytes': '766963'}, {'name': 'Shell', 'bytes': '4353'}]}
<?php namespace Deplink\Downloaders\Fixtures; use Deplink\Downloaders\DownloadingProgress; class DummyDownloadingProgress implements DownloadingProgress { public function downloadingStarted() { // Should do nothing } /** * @param int $percentage In range 0-100, not guarantees that all percentages will be reported. */ public function downloadingProgress($percentage) { // Should do nothing } public function downloadingSucceed() { // Should do nothing } /** * @param \Exception $e Exception which stopped the downloading process. */ public function downloadingFailed(\Exception $e) { // Should do nothing } }
{'content_hash': '87de9a968a073eb9186559191ebe12bf', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 99, 'avg_line_length': 21.294117647058822, 'alnum_prop': 0.6560773480662984, 'repo_name': 'deplink/deplink', 'id': '5f3c18fe9908c39fae5ffe620db2ec3eacb704b0', 'size': '724', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Downloaders/Fixtures/DummyDownloadingProgress.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '1042'}, {'name': 'Dockerfile', 'bytes': '830'}, {'name': 'Gherkin', 'bytes': '30069'}, {'name': 'PHP', 'bytes': '253299'}]}
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ReplicationMigrationItemsOperations operations. /// </summary> internal partial class ReplicationMigrationItemsOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationMigrationItemsOperations { /// <summary> /// Initializes a new instance of the ReplicationMigrationItemsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ReplicationMigrationItemsOperations(SiteRecoveryManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SiteRecoveryManagementClient /// </summary> public SiteRecoveryManagementClient Client { get; private set; } /// <summary> /// Gets the list of migration items in the protection container. /// </summary> /// <remarks> /// Gets the list of ASR migration items in the protection container. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// The pagination token. /// </param> /// <param name='takeToken'> /// The page size. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<MigrationItem>>> ListByReplicationProtectionContainersWithHttpMessagesAsync(string fabricName, string protectionContainerName, ODataQuery<MigrationItemsQueryParameter> odataQuery = default(ODataQuery<MigrationItemsQueryParameter>), string skipToken = default(string), string takeToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("takeToken", takeToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationProtectionContainers", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (takeToken != null) { _queryParameters.Add(string.Format("takeToken={0}", System.Uri.EscapeDataString(takeToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<MigrationItem>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MigrationItem>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the details of a migration item. /// </summary> /// <param name='fabricName'> /// Fabric unique name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> GetWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Enables migration. /// </summary> /// <remarks> /// The operation to create an ASR migration item (enable migration). /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='input'> /// Enable migration input. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<MigrationItem>> CreateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, EnableMigrationInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<MigrationItem> _response = await BeginCreateWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, input, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Delete the migration item. /// </summary> /// <remarks> /// The operation to delete an ASR migration item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='deleteOption'> /// The delete option. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, string deleteOption = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, deleteOption, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Updates migration item. /// </summary> /// <remarks> /// The operation to update the recovery settings of an ASR migration item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='input'> /// Update migration item input. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<MigrationItem>> UpdateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, UpdateMigrationItemInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<MigrationItem> _response = await BeginUpdateWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, input, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Migrate item. /// </summary> /// <remarks> /// The operation to initiate migration of the item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='migrateInput'> /// Migrate input. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<MigrationItem>> MigrateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, MigrateInput migrateInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<MigrationItem> _response = await BeginMigrateWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, migrateInput, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Resynchronizes replication. /// </summary> /// <remarks> /// The operation to resynchronize replication of an ASR migration item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='input'> /// Resync input. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<MigrationItem>> ResyncWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, ResyncInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<MigrationItem> _response = await BeginResyncWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, input, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test migrate item. /// </summary> /// <remarks> /// The operation to initiate test migration of the item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='testMigrateInput'> /// Test migrate input. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<MigrationItem>> TestMigrateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, TestMigrateInput testMigrateInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<MigrationItem> _response = await BeginTestMigrateWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, testMigrateInput, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test migrate cleanup. /// </summary> /// <remarks> /// The operation to initiate test migrate cleanup. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='testMigrateCleanupInput'> /// Test migrate cleanup input. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<MigrationItem>> TestMigrateCleanupWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, TestMigrateCleanupInput testMigrateCleanupInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<MigrationItem> _response = await BeginTestMigrateCleanupWithHttpMessagesAsync(fabricName, protectionContainerName, migrationItemName, testMigrateCleanupInput, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the list of migration items in the vault. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// The pagination token. /// </param> /// <param name='takeToken'> /// The page size. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<MigrationItem>>> ListWithHttpMessagesAsync(ODataQuery<MigrationItemsQueryParameter> odataQuery = default(ODataQuery<MigrationItemsQueryParameter>), string skipToken = default(string), string takeToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("takeToken", takeToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationMigrationItems").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (takeToken != null) { _queryParameters.Add(string.Format("takeToken={0}", System.Uri.EscapeDataString(takeToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<MigrationItem>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MigrationItem>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Enables migration. /// </summary> /// <remarks> /// The operation to create an ASR migration item (enable migration). /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='input'> /// Enable migration input. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> BeginCreateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, EnableMigrationInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } if (input == null) { throw new ValidationException(ValidationRules.CannotBeNull, "input"); } if (input != null) { input.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("input", input); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(input != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(input, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete the migration item. /// </summary> /// <remarks> /// The operation to delete an ASR migration item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='deleteOption'> /// The delete option. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, string deleteOption = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("deleteOption", deleteOption); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (deleteOption != null) { _queryParameters.Add(string.Format("deleteOption={0}", System.Uri.EscapeDataString(deleteOption))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates migration item. /// </summary> /// <remarks> /// The operation to update the recovery settings of an ASR migration item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='input'> /// Update migration item input. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> BeginUpdateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, UpdateMigrationItemInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } if (input == null) { throw new ValidationException(ValidationRules.CannotBeNull, "input"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("input", input); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(input != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(input, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Migrate item. /// </summary> /// <remarks> /// The operation to initiate migration of the item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='migrateInput'> /// Migrate input. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> BeginMigrateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, MigrateInput migrateInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } if (migrateInput == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrateInput"); } if (migrateInput != null) { migrateInput.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("migrateInput", migrateInput); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginMigrate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/migrate").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(migrateInput != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(migrateInput, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Resynchronizes replication. /// </summary> /// <remarks> /// The operation to resynchronize replication of an ASR migration item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='input'> /// Resync input. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> BeginResyncWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, ResyncInput input, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } if (input == null) { throw new ValidationException(ValidationRules.CannotBeNull, "input"); } if (input != null) { input.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("input", input); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginResync", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/resync").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(input != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(input, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test migrate item. /// </summary> /// <remarks> /// The operation to initiate test migration of the item. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='testMigrateInput'> /// Test migrate input. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> BeginTestMigrateWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, TestMigrateInput testMigrateInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } if (testMigrateInput == null) { throw new ValidationException(ValidationRules.CannotBeNull, "testMigrateInput"); } if (testMigrateInput != null) { testMigrateInput.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("testMigrateInput", testMigrateInput); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginTestMigrate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/testMigrate").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(testMigrateInput != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(testMigrateInput, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Test migrate cleanup. /// </summary> /// <remarks> /// The operation to initiate test migrate cleanup. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='migrationItemName'> /// Migration item name. /// </param> /// <param name='testMigrateCleanupInput'> /// Test migrate cleanup input. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<MigrationItem>> BeginTestMigrateCleanupWithHttpMessagesAsync(string fabricName, string protectionContainerName, string migrationItemName, TestMigrateCleanupInput testMigrateCleanupInput, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (protectionContainerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectionContainerName"); } if (migrationItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "migrationItemName"); } if (testMigrateCleanupInput == null) { throw new ValidationException(ValidationRules.CannotBeNull, "testMigrateCleanupInput"); } if (testMigrateCleanupInput != null) { testMigrateCleanupInput.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("protectionContainerName", protectionContainerName); tracingParameters.Add("migrationItemName", migrationItemName); tracingParameters.Add("testMigrateCleanupInput", testMigrateCleanupInput); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginTestMigrateCleanup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationProtectionContainers/{protectionContainerName}/replicationMigrationItems/{migrationItemName}/testMigrateCleanup").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{protectionContainerName}", System.Uri.EscapeDataString(protectionContainerName)); _url = _url.Replace("{migrationItemName}", System.Uri.EscapeDataString(migrationItemName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(testMigrateCleanupInput != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(testMigrateCleanupInput, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<MigrationItem>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<MigrationItem>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of migration items in the protection container. /// </summary> /// <remarks> /// Gets the list of ASR migration items in the protection container. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<MigrationItem>>> ListByReplicationProtectionContainersNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationProtectionContainersNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<MigrationItem>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MigrationItem>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of migration items in the vault. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<MigrationItem>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<MigrationItem>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MigrationItem>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
{'content_hash': 'c913b9aeaeb307cf343ef48f6b73c1e3', 'timestamp': '', 'source': 'github', 'line_count': 2896, 'max_line_length': 479, 'avg_line_length': 47.70303867403315, 'alnum_prop': 0.5657338506529229, 'repo_name': 'AsrOneSdk/azure-sdk-for-net', 'id': '62943495cf9a71a0ef64e6a6ca899cdbaaa4156f', 'size': '138501', 'binary': False, 'copies': '3', 'ref': 'refs/heads/psSdkJson6Current', 'path': 'sdk/recoveryservices-siterecovery/Microsoft.Azure.Management.RecoveryServices.SiteRecovery/src/Generated/ReplicationMigrationItemsOperations.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '15473'}, {'name': 'Bicep', 'bytes': '13438'}, {'name': 'C#', 'bytes': '72203239'}, {'name': 'CSS', 'bytes': '6089'}, {'name': 'Dockerfile', 'bytes': '5652'}, {'name': 'HTML', 'bytes': '6169271'}, {'name': 'JavaScript', 'bytes': '16012'}, {'name': 'PowerShell', 'bytes': '649218'}, {'name': 'Shell', 'bytes': '31287'}, {'name': 'Smarty', 'bytes': '11135'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_77) on Mon May 23 19:36:30 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Class Hierarchy (Lucene 6.0.1 API)</title> <meta name="date" content="2016-05-23"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Class Hierarchy (Lucene 6.0.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li> <li><a href="overview-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For All Packages</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="org/apache/lucene/analysis/cn/smart/package-tree.html">org.apache.lucene.analysis.cn.smart</a>, </li> <li><a href="org/apache/lucene/analysis/cn/smart/hhmm/package-tree.html">org.apache.lucene.analysis.cn.smart.hhmm</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://download.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.apache.lucene.analysis.util.<a href="../analyzers-common/org/apache/lucene/analysis/util/AbstractAnalysisFactory.html?is-external=true" title="class or interface in org.apache.lucene.analysis.util"><span class="typeNameLink">AbstractAnalysisFactory</span></a> <ul> <li type="circle">org.apache.lucene.analysis.util.<a href="../analyzers-common/org/apache/lucene/analysis/util/TokenizerFactory.html?is-external=true" title="class or interface in org.apache.lucene.analysis.util"><span class="typeNameLink">TokenizerFactory</span></a> <ul> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/HMMChineseTokenizerFactory.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">HMMChineseTokenizerFactory</span></a></li> </ul> </li> </ul> </li> <li type="circle">org.apache.lucene.analysis.<a href="../core/org/apache/lucene/analysis/Analyzer.html?is-external=true" title="class or interface in org.apache.lucene.analysis"><span class="typeNameLink">Analyzer</span></a> (implements java.io.<a href="http://download.oracle.com/javase/8/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</a>) <ul> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/SmartChineseAnalyzer.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">SmartChineseAnalyzer</span></a></li> </ul> </li> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/AnalyzerProfile.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">AnalyzerProfile</span></a></li> <li type="circle">org.apache.lucene.util.<a href="../core/org/apache/lucene/util/AttributeSource.html?is-external=true" title="class or interface in org.apache.lucene.util"><span class="typeNameLink">AttributeSource</span></a> <ul> <li type="circle">org.apache.lucene.analysis.<a href="../core/org/apache/lucene/analysis/TokenStream.html?is-external=true" title="class or interface in org.apache.lucene.analysis"><span class="typeNameLink">TokenStream</span></a> (implements java.io.<a href="http://download.oracle.com/javase/8/docs/api/java/io/Closeable.html?is-external=true" title="class or interface in java.io">Closeable</a>) <ul> <li type="circle">org.apache.lucene.analysis.<a href="../core/org/apache/lucene/analysis/Tokenizer.html?is-external=true" title="class or interface in org.apache.lucene.analysis"><span class="typeNameLink">Tokenizer</span></a> <ul> <li type="circle">org.apache.lucene.analysis.util.<a href="../analyzers-common/org/apache/lucene/analysis/util/SegmentingTokenizerBase.html?is-external=true" title="class or interface in org.apache.lucene.analysis.util"><span class="typeNameLink">SegmentingTokenizerBase</span></a> <ul> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/HMMChineseTokenizer.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">HMMChineseTokenizer</span></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/CharType.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">CharType</span></a></li> <li type="circle">org.apache.lucene.analysis.cn.smart.hhmm.<a href="org/apache/lucene/analysis/cn/smart/hhmm/HHMMSegmenter.html" title="class in org.apache.lucene.analysis.cn.smart.hhmm"><span class="typeNameLink">HHMMSegmenter</span></a></li> <li type="circle">org.apache.lucene.analysis.cn.smart.hhmm.<a href="org/apache/lucene/analysis/cn/smart/hhmm/SegToken.html" title="class in org.apache.lucene.analysis.cn.smart.hhmm"><span class="typeNameLink">SegToken</span></a></li> <li type="circle">org.apache.lucene.analysis.cn.smart.hhmm.<a href="org/apache/lucene/analysis/cn/smart/hhmm/SegTokenFilter.html" title="class in org.apache.lucene.analysis.cn.smart.hhmm"><span class="typeNameLink">SegTokenFilter</span></a></li> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/Utility.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">Utility</span></a></li> <li type="circle">org.apache.lucene.analysis.cn.smart.<a href="org/apache/lucene/analysis/cn/smart/WordType.html" title="class in org.apache.lucene.analysis.cn.smart"><span class="typeNameLink">WordType</span></a></li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?overview-tree.html" target="_top">Frames</a></li> <li><a href="overview-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='./prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
{'content_hash': '03ef20ec9138f971c13e4d389f1d973f', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 398, 'avg_line_length': 48.78534031413613, 'alnum_prop': 0.6902768834513844, 'repo_name': 'YorkUIRLab/irlab', 'id': '1bec2c36c060d67c5abb5f7167541bdfb3ebd777', 'size': '9318', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/lucene-6.0.1/docs/analyzers-smartcn/overview-tree.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '433499'}, {'name': 'Gnuplot', 'bytes': '2444'}, {'name': 'HTML', 'bytes': '95820812'}, {'name': 'Java', 'bytes': '303195'}, {'name': 'JavaScript', 'bytes': '33538'}]}
 #include <aws/organizations/model/AcceptHandshakeResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Organizations::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; AcceptHandshakeResult::AcceptHandshakeResult() { } AcceptHandshakeResult::AcceptHandshakeResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } AcceptHandshakeResult& AcceptHandshakeResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("Handshake")) { m_handshake = jsonValue.GetObject("Handshake"); } return *this; }
{'content_hash': '590f015c17801ccdd2a865597a8f7979', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 110, 'avg_line_length': 22.972972972972972, 'alnum_prop': 0.7717647058823529, 'repo_name': 'cedral/aws-sdk-cpp', 'id': '63d5a10be6151b6b68e809ab1912b1aaf25ee5c8', 'size': '969', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-organizations/source/model/AcceptHandshakeResult.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '294220'}, {'name': 'C++', 'bytes': '428637022'}, {'name': 'CMake', 'bytes': '862025'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '7904'}, {'name': 'Java', 'bytes': '352201'}, {'name': 'Python', 'bytes': '106761'}, {'name': 'Shell', 'bytes': '10891'}]}
<!DOCTYPE html> <html lang="en" manifest="cache.appcache"> <head> <meta charset="utf-8"> <title>Play 2048 with 12B!</title> <link href="style/main.css" rel="stylesheet" type="text/css"> <link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:400,600,700' rel='stylesheet' type='text/css'> <link rel="shortcut icon" href="favicon.ico"> <link rel="apple-touch-icon" href="meta/apple-touch-icon.png"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="keywords" content="HTML,CSS,Javascript,Make your own 2048,Play 2048"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui"> <meta name="format-detection" content="telephone=no" /> <meta property="og:title" content="2048 game"/> <meta property="og:site_name" content="2048 game"/> <meta property="og:description" content="Play Udacity 2048. Then, make your own 2048 game in Udacity's 2 hour mini course for programming beginners!"/> <meta property="og:image" content="http://gabrielecirulli.github.io/2048/meta/og_image.png"/> </head> <body> <div class="container"> <div class="heading"> <h1 class="title">Make 2048</h1> <div class="scores-container"> <div class="score-container">0</div> <div class="best-container">0</div> </div> </div> <div class="above-game"> <p class="game-intro"> <a class="restart-button">New Game</a> Use the arrow keys to slide tiles. Combine similar tiles to create new ones.</p> </div> <div class="pre-game"> <p class="learn">Learn to make your own version of 2048 in 30 minutes in Udacity's mini online class for beginners.</p><a class="learn" href="https://www.udacity.com/course/ud248">Take the Class!</a> </div> <div class="game-container"> <div class="game-message"> <p></p> <div class="lower"> <a href="http://www.udacity.com/course/ud248/"class="learn learn-low">Take the Class!</a> <a class="retry-button">Play Again</a> <div class="score-sharing"></div> </div> </div> <div class="grid-container"> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> </div> <div class="tile-container"> </div> </div> <p class="game-explanation"> <strong class="important">Make your own version:</strong> If you'd like to make your own version of this game, check out Udacity's newest course for beginners <a href="https://www.udacity.com/course/ud248" target="_blank">Make your own 2048</a>. No programming experience is required and in less than half an hour you'll dig into the source code, make some changes, and have your own version of the game to share. </p> <hr> <p class="game-explanation"> <strong class="important">How to play:</strong> Use your <strong>arrow keys</strong> to move the tiles. When two tiles with the same image touch, they <strong>merge into one!</strong> </p> <hr> <p> This is a modified version of the <a href="http://gabrielecirulli.github.io/2048/" target="_blank">original game</a> created by Gabriele Cirulli. </p> </div> <script src="js/bind_polyfill.js"></script> <script src="js/classlist_polyfill.js"></script> <script src="js/animframe_polyfill.js"></script> <script src="js/keyboard_input_manager.js"></script> <script src="js/html_actuator.js"></script> <script src="js/grid.js"></script> <script src="js/tile.js"></script> <script src="js/local_storage_manager.js"></script> <script src="js/game_manager.js"></script> <script src="js/application.js"></script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> </body> </html>
{'content_hash': '672042d65b27cc17c343217a61969f76', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 419, 'avg_line_length': 42.206896551724135, 'alnum_prop': 0.6325571895424836, 'repo_name': 'matiancai74/matiancai74.github.io', 'id': 'd3550c731c5923627f59dbe9a3a813f4c46c3f17', 'size': '4896', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '44070'}, {'name': 'JavaScript', 'bytes': '25321'}, {'name': 'Ruby', 'bytes': '300'}]}
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-182.js * @description Object.create - 'writable' property of one property in 'Properties' is own data property that overrides an inherited data property (8.10.5 step 6.a) */ function testcase() { var proto = { writable: false }; var ConstructFun = function () { }; ConstructFun.prototype = proto; var descObj = new ConstructFun(); descObj.writable = true; var newObj = Object.create({}, { prop: descObj }); var beforeWrite = (newObj.hasOwnProperty("prop") && typeof (newObj.prop) === "undefined"); newObj.prop = "isWritable"; var afterWrite = (newObj.prop === "isWritable"); return beforeWrite === true && afterWrite === true; } runTestCase(testcase);
{'content_hash': '66bf48d3564bd08555a148c111b44312', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 164, 'avg_line_length': 33.810810810810814, 'alnum_prop': 0.6171063149480416, 'repo_name': 'mbebenita/shumway.ts', 'id': '86c16dc28f8e60592162a190acec4ea7cda3a1b5', 'size': '1251', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'tests/Fidelity/test262/suite/ch15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-182.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Elixir', 'bytes': '3294'}, {'name': 'JavaScript', 'bytes': '24658966'}, {'name': 'Shell', 'bytes': '386'}, {'name': 'TypeScript', 'bytes': '18287003'}]}
A `variant` type is on planned for inclusion in the C++ Standard, probably in C++17. Current working papers are (list extracted from [2015 working group papers](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/)): * 2015-09-28: Variant design review. [P0086R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0086r0.pdf) * 2015-09-28: Variant: a type-safe union without undefined behavior (v2) [P0087R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0087r0.pdf) * 2015-09-27: Variant: a type-safe union that is rarely invalid (v5) [P0088R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0088r0.pdf) * 2015-09-24: Simply a Strong Variant [P0093R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0093r0.html) * 2015-09-24: Simply a Basic Variant [P0094R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0094r0.html) * 2015-09-24: The Case for a Language Based Variant [P0096R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0095r0.html) * 2015-09-25: Implementing the strong guarantee for variant<> assignment [P0110R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0110r0.html) * 2015-09-24: Homogeneous interface for variant, any and optional (Revision 1) [P0032R1](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0032r1.pdf) Last state can be seen from [The Variant Saga: A happy ending?](https://isocpp.org/blog/2015/11/the-variant-saga-a-happy-ending). The `optional` type is also on the way into the standard. The papers are: * 2013-10-03: A proposal to add a utility class to represent optional objects (Revision 5) [N3793](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3793.html) * 2014-01-18: Working Draft, Technical Specification on C++ Extensions for Library Fundamentals [N3848](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3848.html) ## Older Papers * Older working drafts are: N4218 (rev 1), N4516 (rev 2), N4450 (rev 3), and [N4542](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4542.pdf) (rev 4). They have been split into P0086 (general design discussions) and P0087 and P0088 (containing two competing? specs). * 2015-07-28: Variant: Discriminated Union with Value Semantics [P0080R0](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0080r0.pdf) An alternative proposal to N4542.
{'content_hash': '62cdb0ed3253cd36abb4a6b0a0be9cb4', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 276, 'avg_line_length': 93.4, 'alnum_prop': 0.7558886509635975, 'repo_name': 'evanbowman/FLIGHT', 'id': 'd2df488f002f539dc386b425353614575693fac0', 'size': '2357', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'deps/header-only/variant/doc/standards_effort.md', 'mode': '33261', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '216673'}, {'name': 'CMake', 'bytes': '2719'}, {'name': 'GLSL', 'bytes': '10021'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>dblib: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.2 / dblib - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> dblib <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-03 22:58:34 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-03 22:58:34 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/dblib&quot; license: &quot;GPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Dblib&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: abstract syntax&quot; &quot;keyword: binders&quot; &quot;keyword: de Bruijn indices&quot; &quot;keyword: shift&quot; &quot;keyword: lift&quot; &quot;keyword: substitution&quot; &quot;category: Computer Science/Lambda Calculi&quot; ] authors: [ &quot;Francois Pottier &lt;[email protected]&gt; [http://gallium.inria.fr/~fpottier/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/dblib/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/dblib.git&quot; synopsis: &quot;Dblib&quot; description: &quot;&quot;&quot; http://gallium.inria.fr/~fpottier/dblib/README The dblib library offers facilities for working with de Bruijn indices.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/dblib/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=f3801acc5eccb14676c5c27315c30ee2&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-dblib.8.8.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-dblib -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-dblib.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{'content_hash': 'ca6dd462a11c65808d6a92ce0a4bcebd', 'timestamp': '', 'source': 'github', 'line_count': 164, 'max_line_length': 255, 'avg_line_length': 42.09146341463415, 'alnum_prop': 0.5430972041141533, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '6bd6880a5075a59d041a13c34d72ce4930a842f1', 'size': '6928', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.09.1-2.0.6/released/8.11.2/dblib/8.8.0.html', 'mode': '33188', 'license': 'mit', 'language': []}
<!DOCTYPE html> <html> <head> <script> function performTest() { var br = document.getElementsByTagName("BR")[0]; Selection_setEmptySelectionAt(br,0); Cursor_insertCharacter("X"); showSelection(); } </script> </head> <body> <p><br></p> </body> </html>
{'content_hash': '406c3bf02596ee2c911ffbdc8cc7e611', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 52, 'avg_line_length': 15.705882352941176, 'alnum_prop': 0.6441947565543071, 'repo_name': 'apache/incubator-corinthia', 'id': 'b90ca347e2454b11df93907dcce9ad0128596841', 'size': '267', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'experiments/editorFramework/test/Layer0/cursor/insertCharacter-empty10-input.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1472597'}, {'name': 'C++', 'bytes': '192881'}, {'name': 'CMake', 'bytes': '37626'}, {'name': 'CSS', 'bytes': '66484'}, {'name': 'HTML', 'bytes': '2330985'}, {'name': 'JavaScript', 'bytes': '846018'}, {'name': 'Makefile', 'bytes': '1393'}, {'name': 'Objective-C', 'bytes': '424956'}, {'name': 'Perl', 'bytes': '677'}, {'name': 'Python', 'bytes': '5255'}, {'name': 'Shell', 'bytes': '8992'}]}
namespace media { namespace mp4 { static const uint8 kNALU1[] = { 0x01, 0x02, 0x03 }; static const uint8 kNALU2[] = { 0x04, 0x05, 0x06, 0x07 }; static const uint8 kExpected[] = { 0x00, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07 }; static const uint8 kExpectedParamSets[] = { 0x00, 0x00, 0x00, 0x01, 0x67, 0x12, 0x00, 0x00, 0x00, 0x01, 0x67, 0x34, 0x00, 0x00, 0x00, 0x01, 0x68, 0x56, 0x78}; static H264NALU::Type StringToNALUType(const std::string& name) { if (name == "P") return H264NALU::kNonIDRSlice; if (name == "I") return H264NALU::kIDRSlice; if (name == "SEI") return H264NALU::kSEIMessage; if (name == "SPS") return H264NALU::kSPS; if (name == "SPSExt") return H264NALU::kSPSExt; if (name == "PPS") return H264NALU::kPPS; if (name == "AUD") return H264NALU::kAUD; if (name == "EOSeq") return H264NALU::kEOSeq; if (name == "EOStr") return H264NALU::kEOStream; if (name == "FILL") return H264NALU::kFiller; if (name == "R14") return H264NALU::kReserved14; CHECK(false) << "Unexpected name: " << name; return H264NALU::kUnspecified; } static std::string NALUTypeToString(int type) { switch (type) { case H264NALU::kNonIDRSlice: return "P"; case H264NALU::kSliceDataA: return "SDA"; case H264NALU::kSliceDataB: return "SDB"; case H264NALU::kSliceDataC: return "SDC"; case H264NALU::kIDRSlice: return "I"; case H264NALU::kSEIMessage: return "SEI"; case H264NALU::kSPS: return "SPS"; case H264NALU::kSPSExt: return "SPSExt"; case H264NALU::kPPS: return "PPS"; case H264NALU::kAUD: return "AUD"; case H264NALU::kEOSeq: return "EOSeq"; case H264NALU::kEOStream: return "EOStr"; case H264NALU::kFiller: return "FILL"; case H264NALU::kReserved14: return "R14"; case H264NALU::kUnspecified: case H264NALU::kReserved15: case H264NALU::kReserved16: case H264NALU::kReserved17: case H264NALU::kReserved18: case H264NALU::kCodedSliceAux: case H264NALU::kCodedSliceExtension: CHECK(false) << "Unexpected type: " << type; break; }; return "UnsupportedType"; } static void WriteStartCodeAndNALUType(std::vector<uint8>* buffer, const std::string& nal_unit_type) { buffer->push_back(0x00); buffer->push_back(0x00); buffer->push_back(0x00); buffer->push_back(0x01); buffer->push_back(StringToNALUType(nal_unit_type)); } // Input string should be one or more NALU types separated with spaces or // commas. NALU grouped together and separated by commas are placed into the // same subsample, NALU groups separated by spaces are placed into separate // subsamples. // For example: input string "SPS PPS I" produces Annex B buffer containing // SPS, PPS and I NALUs, each in a separate subsample. While input string // "SPS,PPS I" produces Annex B buffer where the first subsample contains SPS // and PPS NALUs and the second subsample contains the I-slice NALU. // The output buffer will contain a valid-looking Annex B (it's valid-looking in // the sense that it has start codes and correct NALU types, but the actual NALU // payload is junk). void StringToAnnexB(const std::string& str, std::vector<uint8>* buffer, std::vector<SubsampleEntry>* subsamples) { DCHECK(!str.empty()); std::vector<std::string> subsample_specs = base::SplitString( str, " ", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); EXPECT_GT(subsample_specs.size(), 0u); buffer->clear(); for (size_t i = 0; i < subsample_specs.size(); ++i) { SubsampleEntry entry; size_t start = buffer->size(); std::vector<std::string> subsample_nalus = base::SplitString( subsample_specs[i], ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); EXPECT_GT(subsample_nalus.size(), 0u); for (size_t j = 0; j < subsample_nalus.size(); ++j) { WriteStartCodeAndNALUType(buffer, subsample_nalus[j]); // Write junk for the payload since the current code doesn't // actually look at it. buffer->push_back(0x32); buffer->push_back(0x12); buffer->push_back(0x67); } entry.clear_bytes = buffer->size() - start; if (subsamples) { // Simulate the encrypted bits containing something that looks // like a SPS NALU. WriteStartCodeAndNALUType(buffer, "SPS"); } entry.cypher_bytes = buffer->size() - start - entry.clear_bytes; if (subsamples) { subsamples->push_back(entry); } } } std::string AnnexBToString(const std::vector<uint8>& buffer, const std::vector<SubsampleEntry>& subsamples) { std::stringstream ss; H264Parser parser; parser.SetEncryptedStream(&buffer[0], buffer.size(), subsamples); H264NALU nalu; bool first = true; size_t current_subsample_index = 0; while (parser.AdvanceToNextNALU(&nalu) == H264Parser::kOk) { size_t subsample_index = AVC::FindSubsampleIndex(buffer, &subsamples, nalu.data); if (!first) { ss << (subsample_index == current_subsample_index ? "," : " "); } else { DCHECK_EQ(subsample_index, current_subsample_index); first = false; } ss << NALUTypeToString(nalu.nal_unit_type); current_subsample_index = subsample_index; } return ss.str(); } class AVCConversionTest : public testing::TestWithParam<int> { protected: void WriteLength(int length_size, int length, std::vector<uint8>* buf) { DCHECK_GE(length, 0); DCHECK_LE(length, 255); for (int i = 1; i < length_size; i++) buf->push_back(0); buf->push_back(length); } void MakeInputForLength(int length_size, std::vector<uint8>* buf) { buf->clear(); WriteLength(length_size, sizeof(kNALU1), buf); buf->insert(buf->end(), kNALU1, kNALU1 + sizeof(kNALU1)); WriteLength(length_size, sizeof(kNALU2), buf); buf->insert(buf->end(), kNALU2, kNALU2 + sizeof(kNALU2)); } }; TEST_P(AVCConversionTest, ParseCorrectly) { std::vector<uint8> buf; std::vector<SubsampleEntry> subsamples; MakeInputForLength(GetParam(), &buf); EXPECT_TRUE(AVC::ConvertFrameToAnnexB(GetParam(), &buf)); EXPECT_TRUE(AVC::IsValidAnnexB(buf, subsamples)); EXPECT_EQ(buf.size(), sizeof(kExpected)); EXPECT_EQ(0, memcmp(kExpected, &buf[0], sizeof(kExpected))); EXPECT_EQ("P,SDC", AnnexBToString(buf, subsamples)); } // Intentionally write NALU sizes that are larger than the buffer. TEST_P(AVCConversionTest, NALUSizeTooLarge) { std::vector<uint8> buf; WriteLength(GetParam(), 10 * sizeof(kNALU1), &buf); buf.insert(buf.end(), kNALU1, kNALU1 + sizeof(kNALU1)); EXPECT_FALSE(AVC::ConvertFrameToAnnexB(GetParam(), &buf)); } TEST_P(AVCConversionTest, NALUSizeIsZero) { std::vector<uint8> buf; WriteLength(GetParam(), 0, &buf); WriteLength(GetParam(), sizeof(kNALU1), &buf); buf.insert(buf.end(), kNALU1, kNALU1 + sizeof(kNALU1)); WriteLength(GetParam(), 0, &buf); WriteLength(GetParam(), sizeof(kNALU2), &buf); buf.insert(buf.end(), kNALU2, kNALU2 + sizeof(kNALU2)); EXPECT_FALSE(AVC::ConvertFrameToAnnexB(GetParam(), &buf)); } TEST_P(AVCConversionTest, ParsePartial) { std::vector<uint8> buf; MakeInputForLength(GetParam(), &buf); buf.pop_back(); EXPECT_FALSE(AVC::ConvertFrameToAnnexB(GetParam(), &buf)); // This tests a buffer ending in the middle of a NAL length. For length size // of one, this can't happen, so we skip that case. if (GetParam() != 1) { MakeInputForLength(GetParam(), &buf); buf.erase(buf.end() - (sizeof(kNALU2) + 1), buf.end()); EXPECT_FALSE(AVC::ConvertFrameToAnnexB(GetParam(), &buf)); } } TEST_P(AVCConversionTest, ParseEmpty) { std::vector<uint8> buf; EXPECT_TRUE(AVC::ConvertFrameToAnnexB(GetParam(), &buf)); EXPECT_EQ(0u, buf.size()); } INSTANTIATE_TEST_CASE_P(AVCConversionTestValues, AVCConversionTest, ::testing::Values(1, 2, 4)); TEST_F(AVCConversionTest, ConvertConfigToAnnexB) { AVCDecoderConfigurationRecord avc_config; avc_config.sps_list.resize(2); avc_config.sps_list[0].push_back(0x67); avc_config.sps_list[0].push_back(0x12); avc_config.sps_list[1].push_back(0x67); avc_config.sps_list[1].push_back(0x34); avc_config.pps_list.resize(1); avc_config.pps_list[0].push_back(0x68); avc_config.pps_list[0].push_back(0x56); avc_config.pps_list[0].push_back(0x78); std::vector<uint8> buf; std::vector<SubsampleEntry> subsamples; EXPECT_TRUE(AVC::ConvertConfigToAnnexB(avc_config, &buf)); EXPECT_EQ(0, memcmp(kExpectedParamSets, &buf[0], sizeof(kExpectedParamSets))); EXPECT_EQ("SPS,SPS,PPS", AnnexBToString(buf, subsamples)); } // Verify that we can round trip string -> Annex B -> string. TEST_F(AVCConversionTest, StringConversionFunctions) { std::string str = "AUD SPS SPSExt SPS PPS SEI SEI R14 I P FILL EOSeq EOStr"; std::vector<uint8> buf; std::vector<SubsampleEntry> subsamples; StringToAnnexB(str, &buf, &subsamples); EXPECT_TRUE(AVC::IsValidAnnexB(buf, subsamples)); EXPECT_EQ(str, AnnexBToString(buf, subsamples)); } TEST_F(AVCConversionTest, ValidAnnexBConstructs) { const char* test_cases[] = { "I", "I I I I", "AUD I", "AUD SPS PPS I", "I EOSeq", "I EOSeq EOStr", "I EOStr", "P", "P P P P", "AUD SPS PPS P", "SEI SEI I", "SEI SEI R14 I", "SPS SPSExt SPS PPS I P", "R14 SEI I", "AUD,I", "AUD,SEI I", "AUD,SEI,SPS,PPS,I" }; for (size_t i = 0; i < arraysize(test_cases); ++i) { std::vector<uint8> buf; std::vector<SubsampleEntry> subsamples; StringToAnnexB(test_cases[i], &buf, NULL); EXPECT_TRUE(AVC::IsValidAnnexB(buf, subsamples)) << "'" << test_cases[i] << "' failed"; } } TEST_F(AVCConversionTest, InvalidAnnexBConstructs) { static const char* test_cases[] = { "AUD", // No VCL present. "AUD,SEI", // No VCL present. "SPS PPS", // No VCL present. "SPS PPS AUD I", // Parameter sets must come after AUD. "SPSExt SPS P", // SPS must come before SPSExt. "SPS PPS SPSExt P", // SPSExt must follow an SPS. "EOSeq", // EOSeq must come after a VCL. "EOStr", // EOStr must come after a VCL. "I EOStr EOSeq", // EOSeq must come before EOStr. "I R14", // Reserved14-18 must come before first VCL. "I SEI", // SEI must come before first VCL. "P SPS P", // SPS after first VCL would indicate a new access unit. }; for (size_t i = 0; i < arraysize(test_cases); ++i) { std::vector<uint8> buf; std::vector<SubsampleEntry> subsamples; StringToAnnexB(test_cases[i], &buf, NULL); EXPECT_FALSE(AVC::IsValidAnnexB(buf, subsamples)) << "'" << test_cases[i] << "' failed"; } } typedef struct { const char* input; const char* expected; } InsertTestCases; TEST_F(AVCConversionTest, InsertParamSetsAnnexB) { static const InsertTestCases test_cases[] = { { "I", "SPS,SPS,PPS,I" }, { "AUD I", "AUD SPS,SPS,PPS,I" }, // Cases where param sets in |avc_config| are placed before // the existing ones. { "SPS,PPS,I", "SPS,SPS,PPS,SPS,PPS,I" }, { "AUD,SPS,PPS,I", "AUD,SPS,SPS,PPS,SPS,PPS,I" }, // Note: params placed // after AUD. // One or more NALUs might follow AUD in the first subsample, we need to // handle this correctly. Params should be inserted right after AUD. { "AUD,SEI I", "AUD,SPS,SPS,PPS,SEI I" }, }; AVCDecoderConfigurationRecord avc_config; avc_config.sps_list.resize(2); avc_config.sps_list[0].push_back(0x67); avc_config.sps_list[0].push_back(0x12); avc_config.sps_list[1].push_back(0x67); avc_config.sps_list[1].push_back(0x34); avc_config.pps_list.resize(1); avc_config.pps_list[0].push_back(0x68); avc_config.pps_list[0].push_back(0x56); avc_config.pps_list[0].push_back(0x78); for (size_t i = 0; i < arraysize(test_cases); ++i) { std::vector<uint8> buf; std::vector<SubsampleEntry> subsamples; StringToAnnexB(test_cases[i].input, &buf, &subsamples); EXPECT_TRUE(AVC::InsertParamSetsAnnexB(avc_config, &buf, &subsamples)) << "'" << test_cases[i].input << "' insert failed."; EXPECT_TRUE(AVC::IsValidAnnexB(buf, subsamples)) << "'" << test_cases[i].input << "' created invalid AnnexB."; EXPECT_EQ(test_cases[i].expected, AnnexBToString(buf, subsamples)) << "'" << test_cases[i].input << "' generated unexpected output."; } } } // namespace mp4 } // namespace media
{'content_hash': 'c8a3922b0ea2e74d859394c7f4d04124', 'timestamp': '', 'source': 'github', 'line_count': 403, 'max_line_length': 80, 'avg_line_length': 31.734491315136477, 'alnum_prop': 0.6404722808663695, 'repo_name': 'lihui7115/ChromiumGStreamerBackend', 'id': 'e9ec17b8bd8db40ba56a741d2ac25f59487ae487', 'size': '13335', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'media/formats/mp4/avc_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '37073'}, {'name': 'Batchfile', 'bytes': '8451'}, {'name': 'C', 'bytes': '9508834'}, {'name': 'C++', 'bytes': '242598549'}, {'name': 'CSS', 'bytes': '943747'}, {'name': 'DM', 'bytes': '60'}, {'name': 'Groff', 'bytes': '2494'}, {'name': 'HTML', 'bytes': '27281878'}, {'name': 'Java', 'bytes': '14561064'}, {'name': 'JavaScript', 'bytes': '20540839'}, {'name': 'Makefile', 'bytes': '70864'}, {'name': 'Objective-C', 'bytes': '1745880'}, {'name': 'Objective-C++', 'bytes': '10008668'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'PLpgSQL', 'bytes': '178732'}, {'name': 'Perl', 'bytes': '63937'}, {'name': 'Protocol Buffer', 'bytes': '482954'}, {'name': 'Python', 'bytes': '8626890'}, {'name': 'Shell', 'bytes': '481888'}, {'name': 'Standard ML', 'bytes': '5106'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '18347'}]}
title: Istio 1.2 Upgrade Notes description: Important changes operators must understand before upgrading to Istio 1.2. publishdate: 2019-06-18 release: 1.2 subtitle: Minor Release linktitle: 1.2 Upgrade Notes weight: 20 --- This page describes changes you need to be aware of when upgrading from Istio 1.1.x to 1.2.x. Here, we detail cases where we intentionally broke backwards compatibility. We also mention cases where backwards compatibility was preserved but new behavior was introduced that would be surprising to someone familiar with the use and operation of Istio 1.1. ## Installation and upgrade {{< tip >}} The configuration model for Mixer has been simplified. Support for adapter-specific and template-specific Custom Resources has been removed by default in 1.2 and will be removed entirely in 1.3. Please move to the new configuration model. {{< /tip >}} Most Mixer CRDs were removed from the system to simplify the configuration model, improve performance of Mixer when used with Kubernetes, and improve reliability in a variety of Kubernetes environments. The following CRDs remain: | Custom Resource Definition name | Purpose | | --- | --- | | `adapter` | Specification of Istio extension declarations | | `attributemanifest` | Specification of Istio extension declarations | | `template` | Specification of Istio extension declarations | | `handler` | Specification of extension invocations | | `rule` | Specification of extension invocations | | `instance` | Specification of extension invocations | In the event you are using the removed mixer configuration schemas, set the following Helm flags during upgrade of the main Helm chart: `--set mixer.templates.useTemplateCRDs=true --set mixer.adapters.useAdapterCRDs=true`
{'content_hash': 'd3f652a3b2b0cc2ce2c010de2c733f3f', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 87, 'avg_line_length': 41.69047619047619, 'alnum_prop': 0.7864077669902912, 'repo_name': 'istio/istio.io', 'id': '000f0b8404b612601c8c4d97393a0290a7477e02', 'size': '1755', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'content/en/news/releases/1.2.x/announcing-1.2/upgrade-notes/index.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '70128'}, {'name': 'Go', 'bytes': '39192'}, {'name': 'HTML', 'bytes': '866919838'}, {'name': 'JavaScript', 'bytes': '372035'}, {'name': 'Makefile', 'bytes': '18567'}, {'name': 'Python', 'bytes': '8488'}, {'name': 'Ruby', 'bytes': '634'}, {'name': 'SCSS', 'bytes': '117075'}, {'name': 'Shell', 'bytes': '8934097'}, {'name': 'TypeScript', 'bytes': '75683'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <feed description="Customer data" name="CustomerFeed" xmlns="uri:falcon:feed:0.1"> <tags>[email protected], [email protected], _department_type=forecasting</tags> <partitions> <partition name="fraud"/> <partition name="good"/> </partitions> <groups>online,bi</groups> <availabilityFlag>_SUCCESS</availabilityFlag> <frequency>hours(1)</frequency> <sla slaLow="hours(2)" slaHigh="hours(3)"/> <timezone>UTC</timezone> <late-arrival cut-off="hours(6)"/> <clusters> <cluster name="testCluster" type="source"> <validity start="2011-11-01T00:00Z" end="2011-12-31T00:00Z"/> <retention limit="hours(48)" action="delete"/> <!-- Limit can be in Time or Instances 100, Action ENUM DELETE,ARCHIVE --> <sla slaLow="hours(3)" slaHigh="hours(4)"/> <export> <target name="test-hsql-db" tableName="customer"> <load type="updateonly"/> <fields> <includes> <field>id</field> <field>name</field> </includes> </fields> </target> <arguments> <argument name="--update-key" value="id"/> </arguments> </export> </cluster> </clusters> <locations> <location type="data" path="/projects/falcon/clicks"/> <location type="stats" path="/projects/falcon/clicksStats"/> <location type="meta" path="/projects/falcon/clicksMetaData"/> </locations> <ACL owner="testuser" group="group" permission="0x755"/> <schema location="/schema/clicks" provider="protobuf"/> </feed>
{'content_hash': '5f5c06298c5cebc5c2f795f1acb0f7a6', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 96, 'avg_line_length': 39.696969696969695, 'alnum_prop': 0.6110687022900764, 'repo_name': 'sriksun/falcon', 'id': '8fda43d7c152d13cfa562a356cfdb2b473d0c37a', 'size': '2620', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'common/src/test/resources/config/feed/feed-export-fields-0.1.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '119841'}, {'name': 'HTML', 'bytes': '224589'}, {'name': 'Java', 'bytes': '7480382'}, {'name': 'JavaScript', 'bytes': '743100'}, {'name': 'Perl', 'bytes': '19690'}, {'name': 'PigLatin', 'bytes': '4826'}, {'name': 'Python', 'bytes': '20124'}, {'name': 'Shell', 'bytes': '29149'}, {'name': 'XSLT', 'bytes': '16792'}]}
'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var last = function last(array) { return array[array.length - 1]; }; var brackets = { /** * Parse string to nodes tree */ parse: function parse(str) { var current = ['']; var stack = [current]; for (var i = 0; i < str.length; i++) { var sym = str[i]; if (sym === '(') { current = ['']; last(stack).push(current); stack.push(current); } else if (sym === ')') { stack.pop(); current = last(stack); current.push(''); } else { current[current.length - 1] += sym; } } return stack[0]; }, /** * Generate output string by nodes tree */ stringify: function stringify(ast) { var result = ''; for (var _iterator = ast, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var i = _ref; if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object') { result += '(' + brackets.stringify(i) + ')'; } else { result += i; } } return result; } }; module.exports = brackets;
{'content_hash': '2560e4d542247b5d28ae2029d2c8bf8b', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 269, 'avg_line_length': 28.484848484848484, 'alnum_prop': 0.4425531914893617, 'repo_name': 'ge6285790/test', 'id': '4e56cea07d9334e1cfb64da859dcbba17ea95ca1', 'size': '1880', 'binary': False, 'copies': '62', 'ref': 'refs/heads/master', 'path': 'node_modules/autoprefixer/lib/brackets.js', 'mode': '33188', 'license': 'mit', 'language': []}
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #ifndef WIN32 #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #endif #include "serialize.h" #include "tinyformat.h" #include <map> #include <list> #include <utility> #include <vector> #include <string> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <stdint.h> class uint256; static const int64_t COIN = 100000000; static const int64_t CENT = 1000000; #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) #define UVOIDBEGIN(a) ((void*)&(a)) #define CVOIDBEGIN(a) ((const void*)&(a)) #define UINTBEGIN(a) ((uint32_t*)&(a)) #define CUINTBEGIN(a) ((const uint32_t*)&(a)) // This is needed because the foreach macro can't get over the comma in pair<t1, t2> #define PAIRTYPE(t1, t2) std::pair<t1, t2> // Align by increasing pointer, must have extra space at end of buffer template <size_t nBytes, typename T> T* alignup(T* p) { union { T* ptr; size_t n; } u; u.ptr = p; u.n = (u.n + (nBytes-1)) & ~(nBytes-1); return u.ptr; } #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif inline void MilliSleep(int64_t n) { #if BOOST_VERSION >= 105000 boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #else boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #endif } extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fPrintToConsole; extern bool fPrintToDebugLog; extern bool fDaemon; extern bool fServer; extern bool fCommandLine; extern std::string strMiscWarning; extern bool fNoListen; extern bool fLogTimestamps; extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); /* Return true if log accepts specified category */ bool LogAcceptCategory(const char* category); /* Send a string to the log output */ int LogPrintStr(const std::string &str); #define LogPrintf(...) LogPrint(NULL, __VA_ARGS__) /* When we switch to C++11, this can be switched to variadic templates instead * of this macro-based construction (see tinyformat.h). */ #define MAKE_ERROR_AND_LOG_FUNC(n) \ /* Print to debug.log if -debug=category switch is given OR category is NULL. */ \ template<TINYFORMAT_ARGTYPES(n)> \ static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \ { \ if(!LogAcceptCategory(category)) return 0; \ return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \ } \ /* Log error and return false */ \ template<TINYFORMAT_ARGTYPES(n)> \ static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \ { \ LogPrintStr("ERROR: " + tfm::format(format, TINYFORMAT_PASSARGS(n)) + "\n"); \ return false; \ } TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC) /* Zero-arg versions of logging and error, these are not covered by * TINYFORMAT_FOREACH_ARGNUM */ static inline int LogPrint(const char* category, const char* format) { if(!LogAcceptCategory(category)) return 0; return LogPrintStr(format); } static inline bool error(const char* format) { LogPrintStr(std::string("ERROR: ") + format + "\n"); return false; } void PrintException(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseString(const std::string& str, char c, std::vector<std::string>& v); std::string FormatMoney(int64_t n, bool fPlus=false); bool ParseMoney(const std::string& str, int64_t& nRet); bool ParseMoney(const char* pszIn, int64_t& nRet); std::string SanitizeString(const std::string& str); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); void ParseParameters(int argc, const char*const argv[]); bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const std::string& str, const std::string& mask); void FileCommit(FILE *fileout); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path &GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); #ifndef WIN32 void CreatePidFile(const boost::filesystem::path &path, pid_t pid); #endif void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif void ShrinkDebugFile(); int GetRandInt(int nMax); uint64_t GetRand(uint64_t nMax); uint256 GetRandHash(); int64_t GetTime(); void SetMockTime(int64_t nMockTimeIn); std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); void runCommand(std::string strCommand); inline std::string i64tostr(int64_t n) { return strprintf("%d", n); } inline std::string itostr(int n) { return strprintf("%d", n); } inline int64_t atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, NULL, 10); #endif } inline int64_t atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), NULL, 10); #endif } inline int atoi(const std::string& str) { return atoi(str.c_str()); } inline int roundint(double d) { return (int)(d > 0 ? d + 0.5 : d - 0.5); } inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } inline int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } inline std::string leftTrim(std::string src, char chr) { std::string::size_type pos = src.find_first_not_of(chr, 0); if(pos > 0) src.erase(0, pos); return src; } template<typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { std::string rv; static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; rv.reserve((itend-itbegin)*3); for(T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if(fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val>>4]); rv.push_back(hexmap[val&15]); } return rv; } template<typename T> inline std::string HexStr(const T& vch, bool fSpaces=false) { return HexStr(vch.begin(), vch.end(), fSpaces); } inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t) t.tv_sec * 1000000 + t.tv_usec; #endif return nCounter; } inline int64_t GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } inline int64_t GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC"; inline std::string DateTimeStrFormat(int64_t nTime) { return DateTimeStrFormat(strTimestampFormat.c_str(), nTime); } template<typename T> void skipspaces(T& it) { while (isspace(*it)) ++it; } inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * MWC RNG of George Marsaglia * This is intended to be fast. It has a period of 2^59.3, though the * least significant 16 bits only have a period of about 2^30.1. * * @return random value */ extern uint32_t insecure_rand_Rz; extern uint32_t insecure_rand_Rw; static inline uint32_t insecure_rand(void) { insecure_rand_Rz=36969*(insecure_rand_Rz&65535)+(insecure_rand_Rz>>16); insecure_rand_Rw=18000*(insecure_rand_Rw&65535)+(insecure_rand_Rw>>16); return (insecure_rand_Rw<<16)+insecure_rand_Rz; } /** * Seed insecure_rand using the random pool. * @param Deterministic Use a determinstic seed */ void seed_insecure_rand(bool fDeterministic=false); /** * Timing-attack-resistant comparison. * Takes time proportional to length * of first argument. */ template <typename T> bool TimingResistantEqual(const T& a, const T& b) { if (b.size() == 0) return a.size() == 0; size_t accumulator = a.size() ^ b.size(); for (size_t i = 0; i < a.size(); i++) accumulator |= a[i] ^ b[i%b.size()]; return accumulator == 0; } /** Median filter over a stream of values. * Returns the median of the last N numbers */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int size, T initial_value): nSize(size) { vValues.reserve(size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if(vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int size = vSorted.size(); assert(size>0); if(size & 1) // Odd number of elements { return vSorted[size/2]; } else // Even number of elements { return (vSorted[size/2-1] + vSorted[size/2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted () const { return vSorted; } }; #ifdef WIN32 inline void SetThreadPriority(int nPriority) { SetThreadPriority(GetCurrentThread(), nPriority); } #else #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL 0 inline void SetThreadPriority(int nPriority) { // It's unclear if it's even possible to change thread priorities on Linux, // but we really and truly need it for the generation threads. #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else setpriority(PRIO_PROCESS, 0, nPriority); #endif } #endif void RenameThread(const char* name); inline uint32_t ByteReverse(uint32_t value) { value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); return (value<<16) | (value>>16); } // Standard wrapper for do-something-forever thread functions. // "Forever" really means until the thread is interrupted. // Use it like: // new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000)); // or maybe: // boost::function<void()> f = boost::bind(&FunctionWithArg, argument); // threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); template <typename Callable> void LoopForever(const char* name, Callable func, int64_t msecs) { std::string s = strprintf("demonic-%s", name); RenameThread(s.c_str()); LogPrintf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { LogPrintf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } // .. and a wrapper that just calls func once template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("demonic-%s", name); RenameThread(s.c_str()); try { LogPrintf("%s thread start\n", name); func(); LogPrintf("%s thread exit\n", name); } catch (boost::thread_interrupted) { LogPrintf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } #endif
{'content_hash': 'db57541e5bf28fb958c846ea8dda8c70', 'timestamp': '', 'source': 'github', 'line_count': 558, 'max_line_length': 143, 'avg_line_length': 28.03584229390681, 'alnum_prop': 0.6366658143697264, 'repo_name': 'CryptoDemonic/demonic', 'id': '0e5a05c54fe837eab7327bc4a0124e7828015f96', 'size': '15644', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/util.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '51312'}, {'name': 'C', 'bytes': '465529'}, {'name': 'C++', 'bytes': '2533501'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'HTML', 'bytes': '50620'}, {'name': 'Makefile', 'bytes': '12088'}, {'name': 'NSIS', 'bytes': '5914'}, {'name': 'Objective-C', 'bytes': '858'}, {'name': 'Objective-C++', 'bytes': '6899'}, {'name': 'Python', 'bytes': '54355'}, {'name': 'QMake', 'bytes': '14146'}, {'name': 'Shell', 'bytes': '8509'}]}
package org.apache.qpid.jms.selector.filter; /** * An expression which performs an operation on two expression values. * */ public abstract class BinaryExpression implements Expression { protected Expression left; protected Expression right; public BinaryExpression(Expression left, Expression right) { this.left = left; this.right = right; } public Expression getLeft() { return left; } public Expression getRight() { return right; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; } /** * TODO: more efficient hashCode() * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return toString().hashCode(); } /** * TODO: more efficient hashCode() * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (o == null || !this.getClass().equals(o.getClass())) { return false; } return toString().equals(o.toString()); } /** * Returns the symbol that represents this binary expression. For example, addition is * represented by "+" * * @return the symbol String */ public abstract String getExpressionSymbol(); /** * @param expression the RHS. */ public void setRight(Expression expression) { right = expression; } /** * @param expression the LHS */ public void setLeft(Expression expression) { left = expression; } }
{'content_hash': '97b2eb54bd7cc37d8af53c154cb6a765', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 98, 'avg_line_length': 22.08974358974359, 'alnum_prop': 0.5803830528148578, 'repo_name': 'gemmellr/qpid-jms', 'id': '2f5dc73b2f56cd7bf3237bc7bdb7b6dd82f8c557', 'size': '2525', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'qpid-jms-client/src/main/java/org/apache/qpid/jms/selector/filter/BinaryExpression.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1815'}, {'name': 'Java', 'bytes': '6414869'}, {'name': 'XSLT', 'bytes': '50129'}]}
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } require('nanoid/non-secure'); require('./Debug-bbad1094.js'); require('redux'); require('./turn-order-9099d084.js'); require('immer'); require('lodash.isplainobject'); require('./reducer-4d6573e0.js'); require('rfc6902'); require('./initialize-c5af9678.js'); require('./transport-b1874dfa.js'); var client = require('./client-be861238.js'); require('flatted'); require('setimmediate'); var ai = require('./ai-3736f26d.js'); var client$1 = require('./client-76dec77b.js'); var React = _interopDefault(require('react')); var PropTypes = _interopDefault(require('prop-types')); var Cookies = _interopDefault(require('react-cookies')); require('./util-26588169.js'); var socketio = require('./socketio-a795a800.js'); require('./master-4729db75.js'); require('./filter-player-view-ba976da7.js'); require('socket.io-client'); /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client(opts) { var _a; const { game, numPlayers, board, multiplayer, enhancer } = opts; let { loading, debug } = opts; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting..."); loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _a = class WrappedBoard extends React.Component { constructor(props) { super(props); if (debug === undefined) { debug = props.debug; } this.client = client.Client({ game, debug, numPlayers, multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, enhancer, }); } componentDidMount() { this.unsubscribe = this.client.subscribe(() => this.forceUpdate()); this.client.start(); } componentWillUnmount() { this.client.stop(); this.unsubscribe(); } componentDidUpdate(prevProps) { if (this.props.matchID != prevProps.matchID) { this.client.updateMatchID(this.props.matchID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } render() { const state = this.client.getState(); if (state === null) { return React.createElement(loading); } let _board = null; if (board) { _board = React.createElement(board, { ...state, ...this.props, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, matchID: this.client.matchID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, log: this.client.log, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages, }); } return React.createElement("div", { className: "bgio-client" }, _board); } }, _a.propTypes = { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any, }, _a.defaultProps = { matchID: 'default', playerID: null, credentials: null, debug: true, }, _a; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class _LobbyConnectionImpl { constructor({ server, gameComponents, playerName, playerCredentials, }) { this.client = new client$1.LobbyClient({ server }); this.gameComponents = gameComponents; this.playerName = playerName || 'Visitor'; this.playerCredentials = playerCredentials; this.matches = []; } async refresh() { try { this.matches = []; const games = await this.client.listGames(); for (const game of games) { if (!this._getGameComponents(game)) continue; const { matches } = await this.client.listMatches(game); this.matches.push(...matches); } } catch (error) { throw new Error('failed to retrieve list of matches (' + error + ')'); } } _getMatchInstance(matchID) { for (const inst of this.matches) { if (inst['matchID'] === matchID) return inst; } } _getGameComponents(gameName) { for (const comp of this.gameComponents) { if (comp.game.name === gameName) return comp; } } _findPlayer(playerName) { for (const inst of this.matches) { if (inst.players.some((player) => player.name === playerName)) return inst; } } async join(gameName, matchID, playerID) { try { let inst = this._findPlayer(this.playerName); if (inst) { throw new Error('player has already joined ' + inst.matchID); } inst = this._getMatchInstance(matchID); if (!inst) { throw new Error('game instance ' + matchID + ' not found'); } const json = await this.client.joinMatch(gameName, matchID, { playerID, playerName: this.playerName, }); inst.players[Number.parseInt(playerID)].name = this.playerName; this.playerCredentials = json.playerCredentials; } catch (error) { throw new Error('failed to join match ' + matchID + ' (' + error + ')'); } } async leave(gameName, matchID) { try { const inst = this._getMatchInstance(matchID); if (!inst) throw new Error('match instance not found'); for (const player of inst.players) { if (player.name === this.playerName) { await this.client.leaveMatch(gameName, matchID, { playerID: player.id.toString(), credentials: this.playerCredentials, }); delete player.name; delete this.playerCredentials; return; } } throw new Error('player not found in match'); } catch (error) { throw new Error('failed to leave match ' + matchID + ' (' + error + ')'); } } async disconnect() { const inst = this._findPlayer(this.playerName); if (inst) { await this.leave(inst.gameName, inst.matchID); } this.matches = []; this.playerName = 'Visitor'; } async create(gameName, numPlayers) { try { const comp = this._getGameComponents(gameName); if (!comp) throw new Error('game not found'); if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers); await this.client.createMatch(gameName, { numPlayers }); } catch (error) { throw new Error('failed to create match for ' + gameName + ' (' + error + ')'); } } } /** * LobbyConnection * * Lobby model. * * @param {string} server - '<host>:<port>' of the server. * @param {Array} gameComponents - A map of Board and Game objects for the supported games. * @param {string} playerName - The name of the player. * @param {string} playerCredentials - The credentials currently used by the player, if any. * * Returns: * A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances. */ function LobbyConnection(opts) { return new _LobbyConnectionImpl(opts); } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyLoginForm extends React.Component { constructor() { super(...arguments); this.state = { playerName: this.props.playerName, nameErrorMsg: '', }; this.onClickEnter = () => { if (this.state.playerName === '') return; this.props.onEnter(this.state.playerName); }; this.onKeyPress = (event) => { if (event.key === 'Enter') { this.onClickEnter(); } }; this.onChangePlayerName = (event) => { const name = event.target.value.trim(); this.setState({ playerName: name, nameErrorMsg: name.length > 0 ? '' : 'empty player name', }); }; } render() { return (React.createElement("div", null, React.createElement("p", { className: "phase-title" }, "Choose a player name:"), React.createElement("input", { type: "text", value: this.state.playerName, onChange: this.onChangePlayerName, onKeyPress: this.onKeyPress }), React.createElement("span", { className: "buttons" }, React.createElement("button", { className: "buttons", onClick: this.onClickEnter }, "Enter")), React.createElement("br", null), React.createElement("span", { className: "error-msg" }, this.state.nameErrorMsg, React.createElement("br", null)))); } } LobbyLoginForm.defaultProps = { playerName: '', }; /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyMatchInstance extends React.Component { constructor() { super(...arguments); this._createSeat = (player) => { return player.name || '[free]'; }; this._createButtonJoin = (inst, seatId) => (React.createElement("button", { key: 'button-join-' + inst.matchID, onClick: () => this.props.onClickJoin(inst.gameName, inst.matchID, '' + seatId) }, "Join")); this._createButtonLeave = (inst) => (React.createElement("button", { key: 'button-leave-' + inst.matchID, onClick: () => this.props.onClickLeave(inst.gameName, inst.matchID) }, "Leave")); this._createButtonPlay = (inst, seatId) => (React.createElement("button", { key: 'button-play-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, playerID: '' + seatId, numPlayers: inst.players.length, }) }, "Play")); this._createButtonSpectate = (inst) => (React.createElement("button", { key: 'button-spectate-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, numPlayers: inst.players.length, }) }, "Spectate")); this._createInstanceButtons = (inst) => { const playerSeat = inst.players.find((player) => player.name === this.props.playerName); const freeSeat = inst.players.find((player) => !player.name); if (playerSeat && freeSeat) { // already seated: waiting for match to start return this._createButtonLeave(inst); } if (freeSeat) { // at least 1 seat is available return this._createButtonJoin(inst, freeSeat.id); } // match is full if (playerSeat) { return (React.createElement("div", null, [ this._createButtonPlay(inst, playerSeat.id), this._createButtonLeave(inst), ])); } // allow spectating return this._createButtonSpectate(inst); }; } render() { const match = this.props.match; let status = 'OPEN'; if (!match.players.some((player) => !player.name)) { status = 'RUNNING'; } return (React.createElement("tr", { key: 'line-' + match.matchID }, React.createElement("td", { key: 'cell-name-' + match.matchID }, match.gameName), React.createElement("td", { key: 'cell-status-' + match.matchID }, status), React.createElement("td", { key: 'cell-seats-' + match.matchID }, match.players.map((player) => this._createSeat(player)).join(', ')), React.createElement("td", { key: 'cell-buttons-' + match.matchID }, this._createInstanceButtons(match)))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyCreateMatchForm extends React.Component { constructor(props) { super(props); this.state = { selectedGame: 0, numPlayers: 2, }; this._createGameNameOption = (game, idx) => { return (React.createElement("option", { key: 'name-option-' + idx, value: idx }, game.game.name)); }; this._createNumPlayersOption = (idx) => { return (React.createElement("option", { key: 'num-option-' + idx, value: idx }, idx)); }; this._createNumPlayersRange = (game) => { return Array.from({ length: game.maxPlayers + 1 }) .map((_, i) => i) .slice(game.minPlayers); }; this.onChangeNumPlayers = (event) => { this.setState({ numPlayers: Number.parseInt(event.target.value), }); }; this.onChangeSelectedGame = (event) => { const idx = Number.parseInt(event.target.value); this.setState({ selectedGame: idx, numPlayers: this.props.games[idx].game.minPlayers, }); }; this.onClickCreate = () => { this.props.createMatch(this.props.games[this.state.selectedGame].game.name, this.state.numPlayers); }; /* fix min and max number of players */ for (const game of props.games) { const matchDetails = game.game; if (!matchDetails.minPlayers) { matchDetails.minPlayers = 1; } if (!matchDetails.maxPlayers) { matchDetails.maxPlayers = 4; } console.assert(matchDetails.maxPlayers >= matchDetails.minPlayers); } this.state = { selectedGame: 0, numPlayers: props.games[0].game.minPlayers, }; } render() { return (React.createElement("div", null, React.createElement("select", { value: this.state.selectedGame, onChange: (evt) => this.onChangeSelectedGame(evt) }, this.props.games.map((game, index) => this._createGameNameOption(game, index))), React.createElement("span", null, "Players:"), React.createElement("select", { value: this.state.numPlayers, onChange: this.onChangeNumPlayers }, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map((number) => this._createNumPlayersOption(number))), React.createElement("span", { className: "buttons" }, React.createElement("button", { onClick: this.onClickCreate }, "Create")))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ var LobbyPhases; (function (LobbyPhases) { LobbyPhases["ENTER"] = "enter"; LobbyPhases["PLAY"] = "play"; LobbyPhases["LIST"] = "list"; })(LobbyPhases || (LobbyPhases = {})); /** * Lobby * * React lobby component. * * @param {Array} gameComponents - An array of Board and Game objects for the supported games. * @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000'). * If not set, defaults to the server that served the page. * @param {string} gameServer - Address of the game server (for example 'localhost:8001'). * If not set, defaults to the server that served the page. * @param {function} clientFactory - Function that is used to create the game clients. * @param {number} refreshInterval - Interval between server updates (default: 2000ms). * @param {bool} debug - Enable debug information (default: false). * * Returns: * A React component that provides a UI to create, list, join, leave, play or * spectate matches (game instances). */ class Lobby extends React.Component { constructor(props) { super(props); this.state = { phase: LobbyPhases.ENTER, playerName: 'Visitor', runningMatch: null, errorMsg: '', credentialStore: {}, }; this._createConnection = (props) => { const name = this.state.playerName; this.connection = LobbyConnection({ server: props.lobbyServer, gameComponents: props.gameComponents, playerName: name, playerCredentials: this.state.credentialStore[name], }); }; this._updateCredentials = (playerName, credentials) => { this.setState((prevState) => { // clone store or componentDidUpdate will not be triggered const store = Object.assign({}, prevState.credentialStore); store[playerName] = credentials; return { credentialStore: store }; }); }; this._updateConnection = async () => { await this.connection.refresh(); this.forceUpdate(); }; this._enterLobby = (playerName) => { this.setState({ playerName, phase: LobbyPhases.LIST }); }; this._exitLobby = async () => { await this.connection.disconnect(); this.setState({ phase: LobbyPhases.ENTER, errorMsg: '' }); }; this._createMatch = async (gameName, numPlayers) => { try { await this.connection.create(gameName, numPlayers); await this.connection.refresh(); // rerender this.setState({}); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._joinMatch = async (gameName, matchID, playerID) => { try { await this.connection.join(gameName, matchID, playerID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._leaveMatch = async (gameName, matchID) => { try { await this.connection.leave(gameName, matchID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._startMatch = (gameName, matchOpts) => { const gameCode = this.connection._getGameComponents(gameName); if (!gameCode) { this.setState({ errorMsg: 'game ' + gameName + ' not supported', }); return; } let multiplayer = undefined; if (matchOpts.numPlayers > 1) { multiplayer = this.props.gameServer ? socketio.SocketIO({ server: this.props.gameServer }) : socketio.SocketIO(); } if (matchOpts.numPlayers == 1) { const maxPlayers = gameCode.game.maxPlayers; const bots = {}; for (let i = 1; i < maxPlayers; i++) { bots[i + ''] = ai.MCTSBot; } multiplayer = socketio.Local({ bots }); } const app = this.props.clientFactory({ game: gameCode.game, board: gameCode.board, debug: this.props.debug, multiplayer, }); const match = { app: app, matchID: matchOpts.matchID, playerID: matchOpts.numPlayers > 1 ? matchOpts.playerID : '0', credentials: this.connection.playerCredentials, }; this.setState({ phase: LobbyPhases.PLAY, runningMatch: match }); }; this._exitMatch = () => { this.setState({ phase: LobbyPhases.LIST, runningMatch: null }); }; this._getPhaseVisibility = (phase) => { return this.state.phase !== phase ? 'hidden' : 'phase'; }; this.renderMatches = (matches, playerName) => { return matches.map((match) => { const { matchID, gameName, players } = match; return (React.createElement(LobbyMatchInstance, { key: 'instance-' + matchID, match: { matchID, gameName, players: Object.values(players) }, playerName: playerName, onClickJoin: this._joinMatch, onClickLeave: this._leaveMatch, onClickPlay: this._startMatch })); }); }; this._createConnection(this.props); } componentDidMount() { const cookie = Cookies.load('lobbyState') || {}; if (cookie.phase && cookie.phase === LobbyPhases.PLAY) { cookie.phase = LobbyPhases.LIST; } this.setState({ phase: cookie.phase || LobbyPhases.ENTER, playerName: cookie.playerName || 'Visitor', credentialStore: cookie.credentialStore || {}, }); this._startRefreshInterval(); } componentDidUpdate(prevProps, prevState) { const name = this.state.playerName; const creds = this.state.credentialStore[name]; if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) { this._createConnection(this.props); this._updateConnection(); const cookie = { phase: this.state.phase, playerName: name, credentialStore: this.state.credentialStore, }; Cookies.save('lobbyState', cookie, { path: '/' }); } if (prevProps.refreshInterval !== this.props.refreshInterval) { this._startRefreshInterval(); } } componentWillUnmount() { this._clearRefreshInterval(); } _startRefreshInterval() { this._clearRefreshInterval(); this._currentInterval = setInterval(this._updateConnection, this.props.refreshInterval); } _clearRefreshInterval() { clearInterval(this._currentInterval); } render() { const { gameComponents, renderer } = this.props; const { errorMsg, playerName, phase, runningMatch } = this.state; if (renderer) { return renderer({ errorMsg, gameComponents, matches: this.connection.matches, phase, playerName, runningMatch, handleEnterLobby: this._enterLobby, handleExitLobby: this._exitLobby, handleCreateMatch: this._createMatch, handleJoinMatch: this._joinMatch, handleLeaveMatch: this._leaveMatch, handleExitMatch: this._exitMatch, handleRefreshMatches: this._updateConnection, handleStartMatch: this._startMatch, }); } return (React.createElement("div", { id: "lobby-view", style: { padding: 50 } }, React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.ENTER) }, React.createElement(LobbyLoginForm, { key: playerName, playerName: playerName, onEnter: this._enterLobby })), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.LIST) }, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", { className: "phase-title", id: "match-creation" }, React.createElement("span", null, "Create a match:"), React.createElement(LobbyCreateMatchForm, { games: gameComponents, createMatch: this._createMatch })), React.createElement("p", { className: "phase-title" }, "Join a match:"), React.createElement("div", { id: "instances" }, React.createElement("table", null, React.createElement("tbody", null, this.renderMatches(this.connection.matches, playerName))), React.createElement("span", { className: "error-msg" }, errorMsg, React.createElement("br", null))), React.createElement("p", { className: "phase-title" }, "Matches that become empty are automatically deleted.")), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.PLAY) }, runningMatch && (React.createElement(runningMatch.app, { matchID: runningMatch.matchID, playerID: runningMatch.playerID, credentials: runningMatch.credentials })), React.createElement("div", { className: "buttons", id: "match-exit" }, React.createElement("button", { onClick: this._exitMatch }, "Exit match"))), React.createElement("div", { className: "buttons", id: "lobby-exit" }, React.createElement("button", { onClick: this._exitLobby }, "Exit lobby")))); } } Lobby.propTypes = { gameComponents: PropTypes.array.isRequired, lobbyServer: PropTypes.string, gameServer: PropTypes.string, debug: PropTypes.bool, clientFactory: PropTypes.func, refreshInterval: PropTypes.number, }; Lobby.defaultProps = { debug: false, clientFactory: Client, refreshInterval: 2000, }; exports.Client = Client; exports.Lobby = Lobby;
{'content_hash': 'f4e95b394871ea13d3be7247ebfffd32', 'timestamp': '', 'source': 'github', 'line_count': 710, 'max_line_length': 277, 'avg_line_length': 41.89859154929577, 'alnum_prop': 0.5397673793196182, 'repo_name': 'cdnjs/cdnjs', 'id': '12a55b05ce02e9fff37b7943897bdfe6eb00ea65', 'size': '29955', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'ajax/libs/boardgame-io/0.49.7/cjs/react.js', 'mode': '33188', 'license': 'mit', 'language': []}
<?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> <extension id="application" point="org.eclipse.core.runtime.applications"> <application> <run class="oncecenter.Application"> </run> </application> </extension> <extension point="org.eclipse.ui.perspectives"> <perspective name="RCP Perspective" class="oncecenter.Perspective" id="oncecenter.perspective"> </perspective> </extension> <extension point="org.eclipse.ui.views"> <view allowMultiple="true" class="oncecenter.views.MainView" id="oncecenter.views.MainView" relationship="fast" name="清单信息"> </view> <view class="oncecenter.views.xenconnectiontreeview.VMTreeView" id="oncecenter.tree.VMTreeView" name="清单列表"> </view> <view class="oncecenter.views.detailview.VMTreePageBookView" id="oncecenter.views.VMTreePageBookView" name="清单信息" restorable="true"> </view> <view class="oncecenter.views.ExampleView" id="oncecenter.views.ExampleView" name="ExampleView" restorable="true"> </view> <view class="oncecenter.views.logview.LogView" id="oncecenter.views.LogView" name="日志" restorable="true"> </view> <view class="oncecenter.views.grouptreeview.VMTreeVMGroupView" id="oncecenter.tree.VMTreeVMGroupView" name="虚拟机组" restorable="true"> </view> </extension> <extension id="product" point="org.eclipse.core.runtime.products"> <product application="OnceCenter.application" name="OnceVM"> <property name="appName" value="OnceVM"> </property> <property name="windowImages" value="icons/console/logo/logo16.png,icons/console/logo/logo32.png,icons/console/logo/logo48.png"> </property> <property name="startupProgressRect" value="0,235,539,15"> </property> <property name="preferenceCustomization" value="plugin_customization.ini"> </property> <property name="startupForegroundColor" value="000000"> </property> <property name="startupMessageRect" value="7,252,445,20"> </property> </product> </extension> </plugin>
{'content_hash': '9151e657d9358a5d8aa8c589bbef5fec', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 110, 'avg_line_length': 28.301075268817204, 'alnum_prop': 0.550531914893617, 'repo_name': 'guzy/OnceCenter', 'id': '8866fb48a8eb157b16b7142fb594a7bca9615f88', 'size': '2668', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugin.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1157'}, {'name': 'Java', 'bytes': '3468368'}]}
class AddPurgedAtColumnToFeeds < ActiveRecord::Migration def up Feed.connection.execute(%{ ALTER TABLE feeds ADD COLUMN purged_at timestamp; }) end def down Feed.connection.execute(%{ ALTER TABLE feeds DROP COLUMN purged_at; }) end end
{'content_hash': '0627eb4a9d9c240871dc91179b87c46e', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 56, 'avg_line_length': 21.0, 'alnum_prop': 0.684981684981685, 'repo_name': 'ptrckbrwn/idoru', 'id': '7a7ff514fc1d626250e2dc45e7d1009c8de91a02', 'size': '273', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/migrate/20141013025022_add_purged_at_column_to_feeds.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '43'}, {'name': 'HTML', 'bytes': '33161'}, {'name': 'JavaScript', 'bytes': '730'}, {'name': 'Ruby', 'bytes': '62203'}]}
package bai.kang.yun.zxd.mvp.ui.adapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Paint; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.jess.arms.utils.UiUtils; import com.jess.arms.widget.imageloader.ImageLoader; import com.jess.arms.widget.imageloader.glide.GlideImageConfig; import java.util.ArrayList; import java.util.List; import bai.kang.yun.zxd.R; import bai.kang.yun.zxd.app.utils.OnShoppingCartChangeListener; import bai.kang.yun.zxd.app.utils.ShoppingCartBiz; import bai.kang.yun.zxd.mvp.model.entity.CarGoods; import bai.kang.yun.zxd.mvp.model.entity.CarShop; import bai.kang.yun.zxd.mvp.ui.activity.AddressListActivity; import bai.kang.yun.zxd.mvp.ui.activity.LoginActivity; import bai.kang.yun.zxd.mvp.ui.activity.MakeOrderActivity; import bai.kang.yun.zxd.mvp.ui.view.UIAlertView; import common.WEApplication; import io.realm.Realm; public class MyExpandableListAdapter extends BaseExpandableListAdapter { private Context mContext; private List<CarShop> mListGoods = new ArrayList(); private OnShoppingCartChangeListener mChangeListener; private boolean isSelectAll = false; Realm realm=Realm.getDefaultInstance(); private ImageLoader imageLoader; private SharedPreferences config; public MyExpandableListAdapter(Context context) { mContext = context; config=context.getSharedPreferences("config", Context.MODE_PRIVATE); imageLoader=((WEApplication)context.getApplicationContext()).getAppComponent().imageLoader(); } public void setList(List<CarShop> mListGoods) { this.mListGoods = mListGoods; setSettleInfo(); } public void setOnShoppingCartChangeListener(OnShoppingCartChangeListener changeListener) { this.mChangeListener = changeListener; } public View.OnClickListener getAdapterListener() { return listener; } public int getGroupCount() { return mListGoods.size(); } public int getChildrenCount(int groupPosition) { return mListGoods.get(groupPosition).getGoods().size(); } public Object getGroup(int groupPosition) { return mListGoods.get(groupPosition); } public Object getChild(int groupPosition, int childPosition) { return mListGoods.get(groupPosition).getGoods().get(childPosition); } public long getGroupId(int groupPosition) { return groupPosition; } public long getChildId(int groupPosition, int childPosition) { return childPosition; } public boolean hasStableIds() { return false; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { GroupViewHolder holder = null; if (convertView == null) { holder = new GroupViewHolder(); convertView = LayoutInflater.from(mContext).inflate(R.layout.item_elv_group_test, parent, false); holder.tvGroup = (TextView) convertView.findViewById(R.id.tvShopNameGroup); holder.tvEdit = (TextView) convertView.findViewById(R.id.tvEdit); holder.ivCheckGroup = (ImageView) convertView.findViewById(R.id.ivCheckGroup); convertView.setTag(holder); } else { holder = (GroupViewHolder) convertView.getTag(); } holder.tvGroup.setText(mListGoods.get(groupPosition).getMerchantName()); ShoppingCartBiz.checkItem(mListGoods.get(groupPosition).isGroupSelected(), holder.ivCheckGroup); boolean isEditing = mListGoods.get(groupPosition).isEditing(); if (isEditing) { holder.tvEdit.setText("完成"); } else { holder.tvEdit.setText("编辑"); } holder.ivCheckGroup.setTag(groupPosition); holder.ivCheckGroup.setOnClickListener(listener); holder.tvEdit.setTag(groupPosition); holder.tvEdit.setOnClickListener(listener); holder.tvGroup.setOnClickListener(listener); return convertView; } /** * child view */ public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ChildViewHolder holder = null; if (convertView == null) { holder = new ChildViewHolder(); convertView = LayoutInflater.from(mContext).inflate(R.layout.item_elv_child_test, parent, false); holder.tvChild = (TextView) convertView.findViewById(R.id.tvItemChild); holder.tvDel = (TextView) convertView.findViewById(R.id.tvDel); holder.ivCheckGood = (ImageView) convertView.findViewById(R.id.ivCheckGood); holder.rlEditStatus = (RelativeLayout) convertView.findViewById(R.id.rlEditStatus); holder.llGoodInfo = (LinearLayout) convertView.findViewById(R.id.llGoodInfo); holder.ivAdd = (ImageView) convertView.findViewById(R.id.ivAdd); holder.ivReduce = (ImageView) convertView.findViewById(R.id.ivReduce); holder.iv_goodslogo = (ImageView) convertView.findViewById(R.id.ivGoods); holder.tvGoodsParam = (TextView) convertView.findViewById(R.id.tvGoodsParam); holder.tvPriceNew = (TextView) convertView.findViewById(R.id.tvPriceNew); holder.tvPriceOld = (TextView) convertView.findViewById(R.id.tvPriceOld); holder.tvPriceOld.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//数字被划掉效果 holder.tvNum = (TextView) convertView.findViewById(R.id.tvNum); holder.tvNum2 = (TextView) convertView.findViewById(R.id.tvNum2); convertView.setTag(holder); } else { holder = (ChildViewHolder) convertView.getTag(); } CarGoods goods = mListGoods.get(groupPosition).getGoods().get(childPosition); boolean isChildSelected = mListGoods.get(groupPosition).getGoods().get(childPosition).isChildSelected(); boolean isEditing = goods.isEditing(); String priceNew = "¥" + goods.getPrice(); String priceOld = "¥" + goods.getMkPrice(); String num = goods.getNumber(); String pdtDesc = goods.getPdtDesc(); String goodName = mListGoods.get(groupPosition).getGoods().get(childPosition).getGoodsName(); holder.ivCheckGood.setTag(groupPosition + "," + childPosition); holder.tvChild.setText(goodName); holder.tvPriceNew.setText(priceNew); holder.tvPriceOld.setText(priceOld); holder.tvNum.setText("X " + num); holder.tvNum2.setText(num); holder.tvGoodsParam.setText(pdtDesc); imageLoader.loadImage(mContext, GlideImageConfig .builder() .url(goods.getGoodsLogo()) .errorPic(R.mipmap.imgerror) .imageView(holder.iv_goodslogo) .build()); holder.ivAdd.setTag(goods); holder.ivReduce.setTag(goods); holder.tvDel.setTag(groupPosition + "," + childPosition); holder.tvDel.setTag(groupPosition + "," + childPosition); ShoppingCartBiz.checkItem(isChildSelected, holder.ivCheckGood); if (isEditing) { holder.llGoodInfo.setVisibility(View.GONE); holder.rlEditStatus.setVisibility(View.VISIBLE); } else { holder.llGoodInfo.setVisibility(View.VISIBLE); holder.rlEditStatus.setVisibility(View.GONE); } holder.ivCheckGood.setOnClickListener(listener); holder.tvDel.setOnClickListener(listener); holder.ivAdd.setOnClickListener(listener); holder.ivReduce.setOnClickListener(listener); holder.llGoodInfo.setOnClickListener(listener); return convertView; } public boolean isChildSelectable(int i, int i1) { return false; } View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) { switch (v.getId()) { //main case R.id.ivSelectAll: isSelectAll = ShoppingCartBiz.selectAll(mListGoods, isSelectAll, (ImageView) v); setSettleInfo(); notifyDataSetChanged(); break; case R.id.btnSettle: if (ShoppingCartBiz.hasSelectedGoods(mListGoods)) { if(config.getBoolean("isLog",false)) if(config.getBoolean("isAdd",false)) mContext.startActivity(new Intent(mContext, MakeOrderActivity.class)); else mContext.startActivity(new Intent(mContext, AddressListActivity.class)); else mContext.startActivity(new Intent(mContext, LoginActivity.class)); } else { UiUtils.makeText("亲,先选择商品!"); } //group break; case R.id.tvEdit://切换界面,属于特殊处理,假如没打算切换界面,则不需要这块代码 int groupPosition2 = Integer.parseInt(String.valueOf(v.getTag())); boolean isEditing = !(mListGoods.get(groupPosition2).isEditing()); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { //先查找后得到User对象 mListGoods.get(groupPosition2).setEditing(isEditing); } }); for (int i = 0; i < mListGoods.get(groupPosition2).getGoods().size(); i++) { int finalI = i; realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { //先查找后得到User对象 mListGoods.get(groupPosition2).getGoods().get(finalI).setEditing(isEditing); } }); } notifyDataSetChanged(); break; case R.id.ivCheckGroup: int groupPosition3 = Integer.parseInt(String.valueOf(v.getTag())); isSelectAll = ShoppingCartBiz.selectGroup(mListGoods, groupPosition3); selectAll(); setSettleInfo(); notifyDataSetChanged(); break; //child case R.id.ivCheckGood: String tag = String.valueOf(v.getTag()); if (tag.contains(",")) { String s[] = tag.split(","); int groupPosition = Integer.parseInt(s[0]); int childPosition = Integer.parseInt(s[1]); isSelectAll = ShoppingCartBiz.selectOne(mListGoods, groupPosition, childPosition); selectAll(); setSettleInfo(); notifyDataSetChanged(); } break; case R.id.tvDel: String tagPos = String.valueOf(v.getTag()); if (tagPos.contains(",")) { String s[] = tagPos.split(","); int groupPosition = Integer.parseInt(s[0]); int childPosition = Integer.parseInt(s[1]); showDelDialog(groupPosition, childPosition); } break; case R.id.ivAdd: ShoppingCartBiz.addOrReduceGoodsNum(true, (CarGoods) v.getTag(), ((TextView) (((View) (v.getParent())).findViewById(R.id.tvNum2)))); setSettleInfo(); break; case R.id.ivReduce: ShoppingCartBiz.addOrReduceGoodsNum(false, (CarGoods) v.getTag(), ((TextView) (((View) (v.getParent())).findViewById(R.id.tvNum2)))); setSettleInfo(); break; case R.id.llGoodInfo: UiUtils.makeText("商品详情,暂未实现"); break; case R.id.tvShopNameGroup: UiUtils.makeText("商铺详情,暂未实现"); break; } } }; private void selectAll() { if (mChangeListener != null) { mChangeListener.onSelectItem(isSelectAll); } } private void setSettleInfo() { String[] infos = ShoppingCartBiz.getShoppingCount(mListGoods); //删除或者选择商品之后,需要通知结算按钮,更新自己的数据; if (mChangeListener != null && infos != null) { mChangeListener.onDataChange(infos[0], infos[1]); } } private void showDelDialog(final int groupPosition, final int childPosition) { final UIAlertView delDialog = new UIAlertView(mContext, "温馨提示", "确认删除该商品吗?", "取消", "确定"); delDialog.show(); delDialog.setClicklistener(new UIAlertView.ClickListenerInterface() { public void doLeft() { delDialog.dismiss(); } public void doRight() { String productID = mListGoods.get(groupPosition).getGoods().get(childPosition).getGoodsID(); delGoods(groupPosition, childPosition,productID); setSettleInfo(); notifyDataSetChanged(); delDialog.dismiss(); } } ); } private void delGoods(int groupPosition, int childPosition,String productID) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { //先查找后得到User对象 boolean is=false; mListGoods.get(groupPosition).getGoods().remove(childPosition); if (mListGoods.get(groupPosition).getGoods().size() == 0) { mListGoods.remove(groupPosition); is=true; } ShoppingCartBiz.delGood(productID,is); } }); notifyDataSetChanged(); } class GroupViewHolder { TextView tvGroup; TextView tvEdit; ImageView ivCheckGroup; } class ChildViewHolder { /** 商品名称 */ TextView tvChild; /** 商品规格 */ TextView tvGoodsParam; /** 选中 */ ImageView ivCheckGood; /** 商品图片 */ ImageView iv_goodslogo; /** 非编辑状态 */ LinearLayout llGoodInfo; /** 编辑状态 */ RelativeLayout rlEditStatus; /** +1 */ ImageView ivAdd; /** -1 */ ImageView ivReduce; /** 删除 */ TextView tvDel; /** 新价格 */ TextView tvPriceNew; /** 旧价格 */ TextView tvPriceOld; /** 商品状态的数量 */ TextView tvNum; /** 编辑状态的数量 */ TextView tvNum2; } }
{'content_hash': 'daffcfbde1d34f64bcc04a9ba1129961', 'timestamp': '', 'source': 'github', 'line_count': 393, 'max_line_length': 153, 'avg_line_length': 39.98727735368957, 'alnum_prop': 0.5739739102768056, 'repo_name': 'appsw/NewShopBKY', 'id': '580812a581d36b9caea5e46745ccd4113c4f31ab', 'size': '16077', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/bai/kang/yun/zxd/mvp/ui/adapter/MyExpandableListAdapter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1095917'}]}
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamp('created_at') ->default(DB::raw('CURRENT_TIMESTAMP')); $table->timestamp('updated_at') ->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
{'content_hash': '2b5a99ca198d07a2996e6d630b0fda89', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 84, 'avg_line_length': 23.6, 'alnum_prop': 0.548728813559322, 'repo_name': 'REZ1DENT3/Notes', 'id': '16f0d3a1dd62d6cfa877d82ae296e9c2d61f429d', 'size': '944', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'database/migrations/2014_10_12_000000_create_users_table.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '553'}, {'name': 'HTML', 'bytes': '45939'}, {'name': 'JavaScript', 'bytes': '1132'}, {'name': 'PHP', 'bytes': '84409'}, {'name': 'Vue', 'bytes': '563'}]}
using namespace std; namespace extractor { typedef unordered_map<int, int> Indexes; class MockRuleExtractorHelper : public RuleExtractorHelper { public: MOCK_CONST_METHOD5(GetLinksSpans, void(vector<int>&, vector<int>&, vector<int>&, vector<int>&, int)); MOCK_CONST_METHOD4(CheckAlignedTerminals, bool(const vector<int>&, const vector<int>&, const vector<int>&, int)); MOCK_CONST_METHOD4(CheckTightPhrases, bool(const vector<int>&, const vector<int>&, const vector<int>&, int)); MOCK_CONST_METHOD1(GetGapOrder, vector<int>(const vector<pair<int, int>>&)); MOCK_CONST_METHOD4(GetSourceIndexes, Indexes(const vector<int>&, const vector<int>&, int, int)); // We need to implement these methods, because Google Mock doesn't support // methods with more than 10 arguments. bool FindFixPoint( int, int, const vector<int>&, const vector<int>&, int& target_phrase_low, int& target_phrase_high, const vector<int>&, const vector<int>&, int& source_back_low, int& source_back_high, int, int, int, int, bool, bool, bool) const { target_phrase_low = this->target_phrase_low; target_phrase_high = this->target_phrase_high; source_back_low = this->source_back_low; source_back_high = this->source_back_high; return find_fix_point; } bool GetGaps(vector<pair<int, int>>& source_gaps, vector<pair<int, int>>& target_gaps, const vector<int>&, const vector<int>&, const vector<int>&, const vector<int>&, const vector<int>&, const vector<int>&, int, int, int, int, int, int, int& num_symbols, bool& met_constraints) const { source_gaps = this->source_gaps; target_gaps = this->target_gaps; num_symbols = this->num_symbols; met_constraints = this->met_constraints; return get_gaps; } void SetUp( int target_phrase_low, int target_phrase_high, int source_back_low, int source_back_high, bool find_fix_point, vector<pair<int, int>> source_gaps, vector<pair<int, int>> target_gaps, int num_symbols, bool met_constraints, bool get_gaps) { this->target_phrase_low = target_phrase_low; this->target_phrase_high = target_phrase_high; this->source_back_low = source_back_low; this->source_back_high = source_back_high; this->find_fix_point = find_fix_point; this->source_gaps = source_gaps; this->target_gaps = target_gaps; this->num_symbols = num_symbols; this->met_constraints = met_constraints; this->get_gaps = get_gaps; } private: int target_phrase_low; int target_phrase_high; int source_back_low; int source_back_high; bool find_fix_point; vector<pair<int, int>> source_gaps; vector<pair<int, int>> target_gaps; int num_symbols; bool met_constraints; bool get_gaps; }; } // namespace extractor
{'content_hash': 'c01810e8817f5d63bba773c2617b6a18', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 79, 'avg_line_length': 37.56578947368421, 'alnum_prop': 0.667600700525394, 'repo_name': 'pks/cdec-dtrain', 'id': 'b5ab323fcf2b1324224b942b901d1992fd8e52e0', 'size': '2936', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'extractor/mocks/mock_rule_extractor_helper.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '100229'}, {'name': 'C++', 'bytes': '2878347'}, {'name': 'CMake', 'bytes': '45871'}, {'name': 'Groff', 'bytes': '5461'}, {'name': 'LLVM', 'bytes': '11021'}, {'name': 'Perl', 'bytes': '206321'}, {'name': 'Python', 'bytes': '428788'}, {'name': 'Ruby', 'bytes': '9707'}, {'name': 'Shell', 'bytes': '3915'}]}
<?php /** * Skeleton subclass for representing a row from the 'speed' table. * * * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. * * @package propel.generator.fbapp */ class Speed extends BaseSpeed { }
{'content_hash': '60c314e47f5ac45102c1e5d706f53fe8', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 67, 'avg_line_length': 20.055555555555557, 'alnum_prop': 0.7119113573407202, 'repo_name': 'royrusso/fishbase', 'id': '21aa470ed3c610bad2a03b8d14a3e5463ad927c8', 'size': '361', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'classes/fbapp/Speed.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '54469'}, {'name': 'JavaScript', 'bytes': '257574'}, {'name': 'PHP', 'bytes': '43155398'}]}
package io.pivotal.arca.provider; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DatasetName { String value(); }
{'content_hash': 'e512c34ea89e889f5bf61420852bd307', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 44, 'avg_line_length': 22.285714285714285, 'alnum_prop': 0.8141025641025641, 'repo_name': 'cfmobile/arca-android', 'id': 'dda92ac66cf6ebb83ae9742054a992a5e4c20327', 'size': '312', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'arca-core/arca-provider/src/main/java/io/pivotal/arca/provider/DatasetName.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '508948'}, {'name': 'Shell', 'bytes': '501'}]}
eecs560_lab12 ============= Lab 12: Tarjan's Algorithm for finding strongly connected vertices Objective: Find the articulation points in an undirected graph. Nota Bene: There seems to be a mistake with the first input file because it is not a connected graph. BUILD ===== "make" Nota Bene: You will need a c++11 compiler because the code uses lambdas RUN === (after running make successfully) "./lab12 [FILE]" The output was verified with the Boost.Graph library. That code is in "./Verification/". CMake, and the Boost libraries are required to build that code. To build: "cd Verification" "mkdir build && cd build && cmake .." "make" The output from the verification program can be redirected to a file, which can be visualized using GraphViz. Testing was done with both Thursday and Tuesday lab's test data, which is in input.txt and input2.txt, respectively.
{'content_hash': '69afb170962c9c62772bffc790b790c8', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 71, 'avg_line_length': 27.3125, 'alnum_prop': 0.7494279176201373, 'repo_name': 'selavy/eecs560_lab12', 'id': 'eb58b68376319ecec05fce597de375bdf36bd872', 'size': '874', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '2070'}]}
module ChefCompat module DelegatingClass def method_missing(name, *args, &block) @delegates_to.send(name, *args, &block) end def const_missing(name) @delegates_to.const_get(name) end end end
{'content_hash': '7b8e7e155fbfc1a47f2a2d0ddf4f84a4', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 45, 'avg_line_length': 22.3, 'alnum_prop': 0.6636771300448431, 'repo_name': 'pmigrala/chef-repo', 'id': '123f4189c0cde9c8374b8df35d58e4705dc67c9c', 'size': '223', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'cookbooks/compat_resource/files/lib/chef_compat/delegating_class.rb', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '519983'}, {'name': 'Perl', 'bytes': '105144'}, {'name': 'Python', 'bytes': '1654898'}, {'name': 'Ruby', 'bytes': '912820'}, {'name': 'Shell', 'bytes': '54576'}]}
package com.clicktravel.cheddar.infrastructure.persistence.document.search.query; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class OrQuery extends StructuredQuery { private final Set<StructuredQuery> queries = new HashSet<>(); public OrQuery(final Collection<StructuredQuery> queries) { this.queries.addAll(queries); } public void addQuery(final StructuredQuery query) { queries.add(query); } public Set<StructuredQuery> getQueries() { return queries; } @Override public void accept(final QueryVisitor visitor) { visitor.visit(this); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((queries == null) ? 0 : queries.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final OrQuery other = (OrQuery) obj; if (queries == null) { if (other.queries != null) { return false; } } else if (!queries.equals(other.queries)) { return false; } return true; } }
{'content_hash': '8144fa4ba7398b5af79567e74558bea3', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 81, 'avg_line_length': 23.88135593220339, 'alnum_prop': 0.5699077359829666, 'repo_name': 'clicktravel-basharat/Cheddar', 'id': '84beba8d1a2837dfafb29e40490cc943421cb966', 'size': '2009', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'cheddar/cheddar-persistence/src/main/java/com/clicktravel/cheddar/infrastructure/persistence/document/search/query/OrQuery.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1926777'}, {'name': 'XSLT', 'bytes': '7641'}]}
from django.db.models import Q from django.contrib.auth import get_user_model from .utils import get_action_model def fetch_stream(self, include_secondary=True, **kwargs): kwargs['item'] = self if include_secondary: kwargs['target'] = self return get_action_model().objects.activity_stream(**kwargs) def register_model(fetch_method='activity_stream'): def register(model): setattr(model, fetch_method, fetch_stream) return model return register
{'content_hash': '073a456e41a7dac2050c0e7995e07c04', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 63, 'avg_line_length': 27.444444444444443, 'alnum_prop': 0.7044534412955465, 'repo_name': 'owais/django-simple-activity', 'id': '84bb96f612893f7f902d4eb252214ef84dcfd1d0', 'size': '494', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'simple_activity/decorators.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Python', 'bytes': '9574'}]}
class DeviseInvitableAddToUsers < ActiveRecord::Migration def up change_table :users do |t| t.string :invitation_token t.datetime :invitation_created_at t.datetime :invitation_sent_at t.datetime :invitation_accepted_at t.integer :invitation_limit t.references :invited_by, polymorphic: true t.integer :invitations_count, default: 0 t.index :invitations_count t.index :invitation_token, unique: true # for invitable t.index :invited_by_id end end def down change_table :users do |t| t.remove_references :invited_by, polymorphic: true t.remove :invitations_count, :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token, :invitation_created_at end end end
{'content_hash': 'e1a15e5aba7371dd50d528238d99a924', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 141, 'avg_line_length': 35.17391304347826, 'alnum_prop': 0.6687268232385661, 'repo_name': 'samtgarson/fulli', 'id': '788529ab33a5c8f968e9ae49ad550b4fb928ae9c', 'size': '809', 'binary': False, 'copies': '43', 'ref': 'refs/heads/master', 'path': 'db/migrate/20160416164900_devise_invitable_add_to_users.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '18734'}, {'name': 'CoffeeScript', 'bytes': '8838'}, {'name': 'HTML', 'bytes': '23315'}, {'name': 'Ruby', 'bytes': '101419'}]}
cuckoo ====== Cuckoo Cycle is the first graph-theoretic proof-of-work. Keyed hash functions define arbitrarily large random graphs, in which certain fixed-size subgraphs occur with suitably small probability. Asking for a cycle, or a clique, is a close analogue of asking for a chain or cluster of primes numbers, which were adopted as the number-theoretic proof-of-work in Primecoin and Riecoin, respectively. The latest implementaton incorporates a huge memory savings proposed by Dave Andersen in http://da-data.blogspot.com/2014/03/a-public-review-of-cuckoo-cycle.html Cuckoo Cycle represents a breakthrough in three important ways: 1) it performs only one very cheap siphash computation for each random access to memory, 2) (intended) memory usage grows linearly with graph size, which can be set arbitrarily. there may be very limited opportunity to reduce memory usage without undue slowdown. 3) verification of the proof of work is instant, requiring 2 sha256 and 42x2 siphash computations. Runtime in Cuckoo Cycle is dominated by memory latency (67%). Any ASIC developed for Cuckoo Cycle will need to rely on commodity DRAM chips (SRAM, while an order of magnitude faster, is also 2 orders of magnitude more expensive, and thus not competitive). Such an ASIC would be focussed on orchestrating all the memory accesses which form the bottleneck, and thus replacable by a programmable part (or FPGA) without much loss in efficiency. In this way Cuckoo Cycle limits the advantage of custom designed single-purpose hardware over commodity general-purpose hardware. Other features: 4) proofs take the form of a length 42 cycle in the Cuckoo graph. 5) it has a natural notion of (base) difficulty, namely the number of edges in the graph; above about 60% of size, a 42-cycle is almost guaranteed, but below 50% the probability starts to fall sharply. 6) running time on high end x86 is 9min/GB single-threaded, and 1min/GB for 20 threads. Please read the latest version of the whitepaper for more details: https://github.com/tromp/cuckoo/blob/master/cuckoo.pdf?raw=true On July 23 2014, I posted the following message on https://bitcointalk.org/index.php?topic=707879.0 Cuckoo Cycle Speed Challenge; $2500 in bounties =============================================== Cuckoo Cycle is the first graph-theoretic proof-of-work. Proofs take the form of a length 42-cycle in a bipartite graph with N nodes and N/2 edges, with N scalable from millions to billions and beyond. This makes verification trivial: compute the 42x2 edge endpoints with one initialising sha256 and 84 siphash24 computations, check that each endpoint occurs twice, and that you come back to the starting point only after traversing 42 edges. A final sha256 can check whether the 42-cycle meets a difficulty target. With siphash24 being a very lightweight hash function, this makes for practically instant verification. This is implemented in just 157 lines of C code (files cuckoo.h and cuckoo.c) at https://github.com/tromp/cuckoo, where you can also find a whitepaper. From this point of view, Cuckoo Cycle is a rather simple PoW. Finding a 42-cycle, on the other hand, is far from trivial, requiring considerable resources, and some luck (for a given header, the odds of its graph having a 42-cycle are about 2.5%). The algorithm implemented in cuckoo_miner.h runs in time linear in N. (Note that running in sub-linear time is out of the question, as you could only compute a fraction of all edges, and the odds of all 42 edges of a cycle occurring in this fraction are astronomically small). Memory-wise, it uses N/2 bits to maintain a subset of all edges (potential cycle edges) and N additional bits (or N/2^k bits with corresponding slowdown) to trim the subset in a series of edge trimming rounds. Once the subset is small enough, an algorithm inspired by Cuckoo Hashing is used to recognise all cycles, and recover those of the right length. I'd like to claim that this implementation is a reasonably optimal Cuckoo miner, and that trading off memory for running time, as implemented in tomato_miner.h, incurs at least one order of magnitude extra slowdown. I'd further like to claim that GPUs cannot achieve speed parity with server CPUs. To that end, I offer the following bounties: Speedup Bounty -------------- $500 for an open source implementation that finds 42-cycles twice as fast (disregarding memory use). Linear Time-Memory Trade-Off Bounty ----------------------------------- $500 for an open source implementation that uses at most N/k bits while running up to 15 k times slower, for any k>=2. Both of these bounties require N ranging over {2^28,2^30,2^32} and #threads ranging over {1,2,4,8}, and further assume a high-end Intel Core i7 or Xeon and recent gcc compiler with regular flags as in my Makefile. GPU Speed Parity Bounty ----------------------- $1000 for an open source implementation for an AMD R9 280X or nVidia GeForce GTX 770 (or similar high-end GPU) that is as fast as a high-end Intel Xeon running 16 threads. Again with N ranging over {2^28,2^30,2^32}. Note that there is already a cuda_miner.cu, my attempted port of the edge trimming part of cuckoo_miner.c to CUDA, but while it seems to run ok for medium graph sizes, it crashes my computer at larger sizes, and I haven't had the chance to debug the issue yet (I prefer to let my computer work on solving 8x8 connect-4:-) Anyway, this could make a good starting point. These bounties are to expire at the end of this year. They are admittedly modest in size, but then claiming them might only require one or two insightful tweaks to my existing implementations. I invite anyone who'd like to see my claims refuted to extend any of these bounties with amounts of your crypto-currency of choice. (I don't have any crypto-currencies to offer myself, but if need be, I might be able to convert a bounty through a trusted 3rd party) Happy bounty hunting! -John
{'content_hash': 'a896a0c1350a6bd73f7b54f3d0dc5e4b', 'timestamp': '', 'source': 'github', 'line_count': 126, 'max_line_length': 113, 'avg_line_length': 47.34920634920635, 'alnum_prop': 0.7723768018773047, 'repo_name': 'Electric-Coin-Company/cuckoo', 'id': '566fa7e64ee4ff63032caa4e764c8e1b04f98c47', 'size': '5966', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '19109'}, {'name': 'C++', 'bytes': '47999'}, {'name': 'Cuda', 'bytes': '12827'}, {'name': 'Java', 'bytes': '10924'}, {'name': 'Perl', 'bytes': '2528'}, {'name': 'TeX', 'bytes': '45515'}]}
package io.trivium.dep.com.google.common.collect; import static io.trivium.dep.com.google.common.base.Preconditions.checkNotNull; import io.trivium.dep.com.google.common.annotations.GwtCompatible; import io.trivium.dep.com.google.common.base.Equivalence; import io.trivium.dep.com.google.common.base.Function; import io.trivium.dep.com.google.common.base.Predicate; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedSet; import javax.annotation.Nullable; /** * A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some * {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not * possible to <i>iterate</i> over these contained values. To do so, pass this range instance and * an appropriate {@link DiscreteDomain} to {@link ContiguousSet#create}. * * <h3>Types of ranges</h3> * * <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated * <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the * endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each * side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket * ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means * it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all * <i>x</i> such that <i>statement</i>.") * * <blockquote><table> * <tr><td><b>Notation</b> <td><b>Definition</b> <td><b>Factory method</b> * <tr><td>{@code (a..b)} <td>{@code {x | a < x < b}} <td>{@link Range#open open} * <tr><td>{@code [a..b]} <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed} * <tr><td>{@code (a..b]} <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed} * <tr><td>{@code [a..b)} <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen} * <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}} <td>{@link Range#greaterThan greaterThan} * <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}} <td>{@link Range#atLeast atLeast} * <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}} <td>{@link Range#lessThan lessThan} * <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}} <td>{@link Range#atMost atMost} * <tr><td>{@code (-∞..+∞)}<td>{@code {x}} <td>{@link Range#all all} * </table></blockquote> * * <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints * may be equal only if at least one of the bounds is closed: * * <ul> * <li>{@code [a..a]} : a singleton range * <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid * <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown * </ul> * * <h3>Warnings</h3> * * <ul> * <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do * not</b> allow the endpoint instances to mutate after the range is created! * <li>Your value type's comparison method should be {@linkplain Comparable consistent with equals} * if at all possible. Otherwise, be aware that concepts used throughout this documentation such * as "equal", "same", "unique" and so on actually refer to whether {@link Comparable#compareTo * compareTo} returns zero, not whether {@link Object#equals equals} returns {@code true}. * <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause * undefined horrible things to happen in {@code Range}. For now, the Range API does not prevent * its use, because this would also rule out all ungenerified (pre-JDK1.5) data types. <b>This * may change in the future.</b> * </ul> * * <h3>Other notes</h3> * * <ul> * <li>Instances of this type are obtained using the static factory methods in this class. * <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them must * also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C}, {@code * r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a {@code * Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from 1 to * 100." * <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link * #contains}. * <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property * <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}. * Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having * property <i>P</i>. See, for example, the definition of {@link #intersection intersection}. * </ul> * * <h3>Further reading</h3> * * <p>See the Guava User Guide article on * <a href="https://github.com/google/guava/wiki/RangesExplained">{@code Range}</a>. * * @author Kevin Bourrillion * @author Gregory Kick * @since 10.0 */ @GwtCompatible @SuppressWarnings("rawtypes") public final class Range<C extends Comparable> implements Predicate<C>, Serializable { private static final Function<Range, Cut> LOWER_BOUND_FN = new Function<Range, Cut>() { @Override public Cut apply(Range range) { return range.lowerBound; } }; @SuppressWarnings("unchecked") static <C extends Comparable<?>> Function<Range<C>, Cut<C>> lowerBoundFn() { return (Function) LOWER_BOUND_FN; } private static final Function<Range, Cut> UPPER_BOUND_FN = new Function<Range, Cut>() { @Override public Cut apply(Range range) { return range.upperBound; } }; @SuppressWarnings("unchecked") static <C extends Comparable<?>> Function<Range<C>, Cut<C>> upperBoundFn() { return (Function) UPPER_BOUND_FN; } static final Ordering<Range<?>> RANGE_LEX_ORDERING = new RangeLexOrdering(); static <C extends Comparable<?>> Range<C> create(Cut<C> lowerBound, Cut<C> upperBound) { return new Range<C>(lowerBound, upperBound); } /** * Returns a range that contains all values strictly greater than {@code * lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than <i>or * equal to</i> {@code upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> open(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) { return create(Cut.belowValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains all values greater than or equal to * {@code lower} and strictly less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) { return create(Cut.belowValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values strictly greater than {@code * lower} and less than or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains any value from {@code lower} to {@code * upper}, where each endpoint may be either inclusive (closed) or exclusive * (open). * * @throws IllegalArgumentException if {@code lower} is greater than {@code * upper} * @since 14.0 */ public static <C extends Comparable<?>> Range<C> range( C lower, BoundType lowerType, C upper, BoundType upperType) { checkNotNull(lowerType); checkNotNull(upperType); Cut<C> lowerBound = (lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower); Cut<C> upperBound = (upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper); return create(lowerBound, upperBound); } /** * Returns a range that contains all values strictly less than {@code * endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) { return create(Cut.<C>belowAll(), Cut.belowValue(endpoint)); } /** * Returns a range that contains all values less than or equal to * {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atMost(C endpoint) { return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint)); } /** * Returns a range with no lower bound up to the given endpoint, which may be * either inclusive (closed) or exclusive (open). * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return lessThan(endpoint); case CLOSED: return atMost(endpoint); default: throw new AssertionError(); } } /** * Returns a range that contains all values strictly greater than {@code * endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) { return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range that contains all values greater than or equal to * {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) { return create(Cut.belowValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range from the given endpoint, which may be either inclusive * (closed) or exclusive (open), with no upper bound. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return greaterThan(endpoint); case CLOSED: return atLeast(endpoint); default: throw new AssertionError(); } } private static final Range<Comparable> ALL = new Range<Comparable>(Cut.belowAll(), Cut.aboveAll()); /** * Returns a range that contains every value of type {@code C}. * * @since 14.0 */ @SuppressWarnings("unchecked") public static <C extends Comparable<?>> Range<C> all() { return (Range) ALL; } /** * Returns a range that {@linkplain Range#contains(Comparable) contains} only * the given value. The returned range is {@linkplain BoundType#CLOSED closed} * on both ends. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> singleton(C value) { return closed(value, value); } /** * Returns the minimal range that * {@linkplain Range#contains(Comparable) contains} all of the given values. * The returned range is {@linkplain BoundType#CLOSED closed} on both ends. * * @throws ClassCastException if the parameters are not <i>mutually * comparable</i> * @throws NoSuchElementException if {@code values} is empty * @throws NullPointerException if any of {@code values} is null * @since 14.0 */ public static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values) { checkNotNull(values); if (values instanceof ContiguousSet) { return ((ContiguousSet<C>) values).range(); } Iterator<C> valueIterator = values.iterator(); C min = checkNotNull(valueIterator.next()); C max = min; while (valueIterator.hasNext()) { C value = checkNotNull(valueIterator.next()); min = Ordering.natural().min(min, value); max = Ordering.natural().max(max, value); } return closed(min, max); } final Cut<C> lowerBound; final Cut<C> upperBound; private Range(Cut<C> lowerBound, Cut<C> upperBound) { this.lowerBound = checkNotNull(lowerBound); this.upperBound = checkNotNull(upperBound); if (lowerBound.compareTo(upperBound) > 0 || lowerBound == Cut.<C>aboveAll() || upperBound == Cut.<C>belowAll()) { throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound)); } } /** * Returns {@code true} if this range has a lower endpoint. */ public boolean hasLowerBound() { return lowerBound != Cut.belowAll(); } /** * Returns the lower endpoint of this range. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public C lowerEndpoint() { return lowerBound.endpoint(); } /** * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes * its lower endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public BoundType lowerBoundType() { return lowerBound.typeAsLowerBound(); } /** * Returns {@code true} if this range has an upper endpoint. */ public boolean hasUpperBound() { return upperBound != Cut.aboveAll(); } /** * Returns the upper endpoint of this range. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public C upperEndpoint() { return upperBound.endpoint(); } /** * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes * its upper endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public BoundType upperBoundType() { return upperBound.typeAsUpperBound(); } /** * Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does * not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and * can't be constructed at all.) * * <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b> * considered empty, even though they contain no actual values. In these cases, it may be * helpful to preprocess ranges with {@link #canonical(DiscreteDomain)}. */ public boolean isEmpty() { return lowerBound.equals(upperBound); } /** * Returns {@code true} if {@code value} is within the bounds of this range. For example, on the * range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)} * returns {@code false}. */ public boolean contains(C value) { checkNotNull(value); // let this throw CCE if there is some trickery going on return lowerBound.isLessThan(value) && !upperBound.isLessThan(value); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #contains} * instead. */ @Deprecated @Override public boolean apply(C input) { return contains(input); } /** * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in * this range. */ public boolean containsAll(Iterable<? extends C> values) { if (Iterables.isEmpty(values)) { return true; } // this optimizes testing equality of two range-backed sets if (values instanceof SortedSet) { SortedSet<? extends C> set = cast(values); Comparator<?> comparator = set.comparator(); if (Ordering.natural().equals(comparator) || comparator == null) { return contains(set.first()) && contains(set.last()); } } for (C value : values) { if (!contains(value)) { return false; } } return true; } /** * Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this * range. Examples: * * <ul> * <li>{@code [3..6]} encloses {@code [4..5]} * <li>{@code (3..6)} encloses {@code (3..6)} * <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty) * <li>{@code (3..6]} does not enclose {@code [3..6]} * <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value * contained by the latter range) * <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value * contained by the latter range) * </ul> * * <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies * {@code a.contains(v)}, but as the last two examples illustrate, the converse is not always * true. * * <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a * <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range * according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure * also implies {@linkplain #isConnected connectedness}. */ public boolean encloses(Range<C> other) { return lowerBound.compareTo(other.lowerBound) <= 0 && upperBound.compareTo(other.upperBound) >= 0; } /** * Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses * enclosed} by both this range and {@code other}. * * <p>For example, * <ul> * <li>{@code [2, 4)} and {@code [5, 7)} are not connected * <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)} * <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range * {@code [4, 4)} * </ul> * * <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and * {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this * method returns {@code true}. * * <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain * Equivalence equivalence relation} as it is not transitive. * * <p>Note that certain discrete ranges are not considered connected, even though there are no * elements "between them." For example, {@code [3, 5]} is not considered connected to {@code * [6, 10]}. In these cases, it may be desirable for both input ranges to be preprocessed with * {@link #canonical(DiscreteDomain)} before testing for connectedness. */ public boolean isConnected(Range<C> other) { return lowerBound.compareTo(other.upperBound) <= 0 && other.lowerBound.compareTo(upperBound) <= 0; } /** * Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code * connectedRange}, if such a range exists. * * <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The * resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)} * yields the empty range {@code [5..5)}. * * <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected * connected}. * * <p>The intersection operation is commutative, associative and idempotent, and its identity * element is {@link Range#all}). * * @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false} */ public Range<C> intersection(Range<C> connectedRange) { int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound); int upperCmp = upperBound.compareTo(connectedRange.upperBound); if (lowerCmp >= 0 && upperCmp <= 0) { return this; } else if (lowerCmp <= 0 && upperCmp >= 0) { return connectedRange; } else { Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound; Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound; return create(newLower, newUpper); } } /** * Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code * other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}. * * <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can * also be called their <i>union</i>. If they are not, note that the span might contain values * that are not contained in either input range. * * <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative * and idempotent. Unlike it, it is always well-defined for any two input ranges. */ public Range<C> span(Range<C> other) { int lowerCmp = lowerBound.compareTo(other.lowerBound); int upperCmp = upperBound.compareTo(other.upperBound); if (lowerCmp <= 0 && upperCmp >= 0) { return this; } else if (lowerCmp >= 0 && upperCmp <= 0) { return other; } else { Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound; Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound; return create(newLower, newUpper); } } /** * Returns the canonical form of this range in the given domain. The canonical form has the * following properties: * * <ul> * <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in other * words, {@code ContiguousSet.create(a.canonical(domain), domain).equals( * ContiguousSet.create(a, domain))} * <li>uniqueness: unless {@code a.isEmpty()}, * {@code ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))} implies * {@code a.canonical(domain).equals(b.canonical(domain))} * <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))} * </ul> * * <p>Furthermore, this method guarantees that the range returned will be one of the following * canonical forms: * * <ul> * <li>[start..end) * <li>[start..+∞) * <li>(-∞..end) (only if type {@code C} is unbounded below) * <li>(-∞..+∞) (only if type {@code C} is unbounded below) * </ul> */ public Range<C> canonical(DiscreteDomain<C> domain) { checkNotNull(domain); Cut<C> lower = lowerBound.canonical(domain); Cut<C> upper = upperBound.canonical(domain); return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper); } /** * Returns {@code true} if {@code object} is a range having the same endpoints and bound types as * this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b> * equal to one another, despite the fact that they each contain precisely the same set of values. * Similarly, empty ranges are not equal unless they have exactly the same representation, so * {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal. */ @Override public boolean equals(@Nullable Object object) { if (object instanceof Range) { Range<?> other = (Range<?>) object; return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound); } return false; } /** Returns a hash code for this range. */ @Override public int hashCode() { return lowerBound.hashCode() * 31 + upperBound.hashCode(); } /** * Returns a string representation of this range, such as {@code "[3..5)"} (other examples are * listed in the class documentation). */ @Override public String toString() { return toString(lowerBound, upperBound); } private static String toString(Cut<?> lowerBound, Cut<?> upperBound) { StringBuilder sb = new StringBuilder(16); lowerBound.describeAsLowerBound(sb); sb.append('\u2025'); upperBound.describeAsUpperBound(sb); return sb.toString(); } /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ private static <T> SortedSet<T> cast(Iterable<T> iterable) { return (SortedSet<T>) iterable; } Object readResolve() { if (this.equals(ALL)) { return all(); } else { return this; } } @SuppressWarnings("unchecked") // this method may throw CCE static int compareOrThrow(Comparable left, Comparable right) { return left.compareTo(right); } /** * Needed to serialize sorted collections of Ranges. */ private static class RangeLexOrdering extends Ordering<Range<?>> implements Serializable { @Override public int compare(Range<?> left, Range<?> right) { return ComparisonChain.start() .compare(left.lowerBound, right.lowerBound) .compare(left.upperBound, right.upperBound) .result(); } private static final long serialVersionUID = 0; } private static final long serialVersionUID = 0; }
{'content_hash': 'fa4cc1931f2aeca52d3372bd03a5573b', 'timestamp': '', 'source': 'github', 'line_count': 678, 'max_line_length': 100, 'avg_line_length': 37.1622418879056, 'alnum_prop': 0.6505397682171773, 'repo_name': 'trivium-io/trivium', 'id': 'a5c96831c6e48ae83787e2eedf0d58862854d31f', 'size': '25816', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/io/trivium/dep/com/google/common/collect/Range.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '9683'}, {'name': 'HTML', 'bytes': '78864'}, {'name': 'Java', 'bytes': '8440296'}, {'name': 'JavaScript', 'bytes': '1481641'}, {'name': 'Shell', 'bytes': '398'}]}
// // PFRole.h // Parse // // Created by David Poll on 5/17/12. // Copyright (c) 2012 Parse Inc. All rights reserved. // #import <Foundation/Foundation.h> #import "PFObject.h" #import "PFSubclassing.h" /*! Represents a Role on the Parse server. PFRoles represent groupings of PFUsers for the purposes of granting permissions (e.g. specifying a PFACL for a PFObject). Roles are specified by their sets of child users and child roles, all of which are granted any permissions that the parent role has.<br /> <br /> Roles must have a name (which cannot be changed after creation of the role), and must specify an ACL. */ @interface PFRole : PFObject<PFSubclassing> #pragma mark Creating a New Role /** @name Creating a New Role */ /*! Constructs a new PFRole with the given name. If no default ACL has been specified, you must provide an ACL for the role. @param name The name of the Role to create. */ - (instancetype)initWithName:(NSString *)name; /*! Constructs a new PFRole with the given name. @param name The name of the Role to create. @param acl The ACL for this role. Roles must have an ACL. */ - (instancetype)initWithName:(NSString *)name acl:(PFACL *)acl; /*! Constructs a new PFRole with the given name. If no default ACL has been specified, you must provide an ACL for the role. @param name The name of the Role to create. */ + (instancetype)roleWithName:(NSString *)name; /*! Constructs a new PFRole with the given name. @param name The name of the Role to create. @param acl The ACL for this role. Roles must have an ACL. */ + (instancetype)roleWithName:(NSString *)name acl:(PFACL *)acl; #pragma mark - #pragma mark Role-specific Properties /** @name Role-specific Properties */ /*! Gets or sets the name for a role. This value must be set before the role has been saved to the server, and cannot be set once the role has been saved.<br /> <br /> A role's name can only contain alphanumeric characters, _, -, and spaces. */ @property (nonatomic, copy) NSString *name; /*! Gets the PFRelation for the PFUsers that are direct children of this role. These users are granted any privileges that this role has been granted (e.g. read or write access through ACLs). You can add or remove users from the role through this relation. */ @property (nonatomic, strong, readonly) PFRelation *users; /*! Gets the PFRelation for the PFRoles that are direct children of this role. These roles' users are granted any privileges that this role has been granted (e.g. read or write access through ACLs). You can add or remove child roles from this role through this relation. */ @property (nonatomic, strong, readonly) PFRelation *roles; #pragma mark - #pragma mark Querying for Roles /** @name Querying for Roles */ + (PFQuery *)query; @end
{'content_hash': '341c836ed7da9d77ef1916cc0cafaea8', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 78, 'avg_line_length': 28.653061224489797, 'alnum_prop': 0.7264957264957265, 'repo_name': 'jonastomazalves/mysoccerchamp', 'id': 'b875a223156011a96597532ef151923031dbd06e', 'size': '2808', 'binary': False, 'copies': '72', 'ref': 'refs/heads/master', 'path': 'MySoccerChamp/Parse.framework/Versions/A/Headers/PFRole.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '196915'}, {'name': 'Ruby', 'bytes': '324'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- --> <Keyboard xmlns:android="http://schemas.android.com/apk/res-auto" android:keyWidth="9.09%p" android:horizontalGap="0px" android:verticalGap="@dimen/key_bottom_gap" > <Row android:rowEdgeFlags="top" > <Key android:keyLabel="й" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="1" android:keyWidth="8.75%p" android:keyEdgeFlags="left" /> <Key android:keyLabel="ц" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="2" /> <Key android:keyLabel="у" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="3" /> <Key android:keyLabel="к" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="4" /> <Key android:keyLabel="е" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="5" /> <Key android:keyLabel="н" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="6" /> <Key android:keyLabel="г" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="7ґ" /> <Key android:keyLabel="ш" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="8" /> <Key android:keyLabel="щ" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="9" /> <Key android:keyLabel="з" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="0" /> <Key android:keyLabel="х" android:keyWidth="8.75%p" android:keyEdgeFlags="right" /> </Row> <Row> <Key android:keyLabel="ф" android:keyWidth="8.75%p" android:keyEdgeFlags="left" /> <Key android:keyLabel="і" android:popupKeyboard="@xml/kbd_popup_template" android:popupCharacters="ї" /> <Key android:keyLabel="в" /> <Key android:keyLabel="а" /> <Key android:keyLabel="п" /> <Key android:keyLabel="р" /> <Key android:keyLabel="о" /> <Key android:keyLabel="л" /> <Key android:keyLabel="д" /> <Key android:keyLabel="ж" /> <Key android:keyLabel="є" android:keyWidth="8.75%p" android:keyEdgeFlags="right" /> </Row> <Row android:keyWidth="8.5%p" > <Key android:codes="@integer/key_shift" android:keyIcon="@drawable/sym_keyboard_shift" android:iconPreview="@drawable/sym_keyboard_feedback_shift" android:keyWidth="11.75%p" android:isModifier="true" android:isSticky="true" android:keyEdgeFlags="left" /> <Key android:keyLabel="я" /> <Key android:keyLabel="ч" /> <Key android:keyLabel="с" /> <Key android:keyLabel="м" /> <Key android:keyLabel="и" /> <Key android:keyLabel="т" /> <Key android:keyLabel="ь" /> <Key android:keyLabel="б" /> <Key android:keyLabel="ю" /> <Key android:codes="@integer/key_delete" android:keyIcon="@drawable/sym_keyboard_delete" android:iconPreview="@drawable/sym_keyboard_feedback_delete" android:keyWidth="11.75%p" android:isModifier="true" android:isRepeatable="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_normal" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="40%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_url" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="40%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_email" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="40%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_im" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="40%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:keyLabel=":-)" android:keyOutputText=":-) " android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_smileys" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_webentry" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="30%p" android:isModifier="true" /> <Key android:codes="@integer/key_tab" android:keyIcon="@drawable/sym_keyboard_tab" android:iconPreview="@drawable/sym_keyboard_feedback_tab" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="20%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_normal_with_settings_key" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="15%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_settings" android:keyIcon="@drawable/sym_keyboard_settings" android:iconPreview="@drawable/sym_keyboard_feedback_settings" android:isModifier="true" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="30%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="25%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_url_with_settings_key" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="15%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_settings" android:keyIcon="@drawable/sym_keyboard_settings" android:iconPreview="@drawable/sym_keyboard_feedback_settings" android:isModifier="true" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="30%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="25%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_email_with_settings_key" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="15%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_settings" android:keyIcon="@drawable/sym_keyboard_settings" android:iconPreview="@drawable/sym_keyboard_feedback_settings" android:isModifier="true" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="30%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="25%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_im_with_settings_key" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="15%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_settings" android:keyIcon="@drawable/sym_keyboard_settings" android:iconPreview="@drawable/sym_keyboard_feedback_settings" android:isModifier="true" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="30%p" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:keyLabel=":-)" android:keyOutputText=":-) " android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_smileys" android:keyWidth="25%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> <Row android:keyboardMode="@+id/mode_webentry_with_settings_key" android:keyWidth="10%p" android:rowEdgeFlags="bottom" > <Key android:codes="@integer/key_symbol" android:keyLabel="@string/label_symbol_key" android:keyWidth="15%p" android:isModifier="true" android:keyEdgeFlags="left" /> <Key android:codes="@integer/key_settings" android:keyIcon="@drawable/sym_keyboard_settings" android:iconPreview="@drawable/sym_keyboard_feedback_settings" android:isModifier="true" /> <Key android:codes="@integer/key_f1" android:isModifier="true" /> <Key android:codes="@integer/key_space" android:keyIcon="@drawable/sym_keyboard_space" android:iconPreview="@drawable/sym_keyboard_feedback_space" android:keyWidth="30%p" android:isModifier="true" /> <Key android:codes="@integer/key_tab" android:keyIcon="@drawable/sym_keyboard_tab" android:iconPreview="@drawable/sym_keyboard_feedback_tab" android:isModifier="true" /> <Key android:keyLabel="." android:keyIcon="@drawable/hint_popup" android:popupKeyboard="@xml/popup_punctuation" android:isModifier="true" /> <Key android:codes="@integer/key_return" android:keyIcon="@drawable/sym_keyboard_return" android:iconPreview="@drawable/sym_keyboard_feedback_return" android:keyWidth="15%p" android:isModifier="true" android:keyEdgeFlags="right" /> </Row> </Keyboard>
{'content_hash': '75351dd40861bba58ea29d248dbb455b', 'timestamp': '', 'source': 'github', 'line_count': 497, 'max_line_length': 74, 'avg_line_length': 36.796780684104625, 'alnum_prop': 0.55582895888014, 'repo_name': 'klausw/hackerskeyboard', 'id': 'fc895354bffdd37582ba8b2410e5634b7e07a33d', 'size': '18938', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/xml-uk/kbd_qwerty.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '84397'}, {'name': 'CMake', 'bytes': '1844'}, {'name': 'Java', 'bytes': '686810'}, {'name': 'Objective-C', 'bytes': '11582'}, {'name': 'Perl', 'bytes': '4709'}, {'name': 'Shell', 'bytes': '2020'}]}
<?php namespace air\docker; /** * * @author wukezhan<[email protected]> * 2014-10-12 14:28 * */ class misc extends api { public function build($params = array()) { $this->_api_url = 'build'; $this->_method = self::POST; $this->_params = $params; return $this; } public function auth($params = array()) { $this->_api_url = 'auth'; $this->_method = self::POST; $this->_params = $params; return $this; } public function info($params = array()) { $this->_api_url = 'info'; $this->_method = self::GET; $this->_params = $params; return $this; } public function version($params = array()) { $this->_api_url = 'version'; $this->_method = self::GET; $this->_params = $params; return $this; } public function _ping($params = array()) { $this->_api_url = '_ping'; $this->_method = self::GET; $this->_params = $params; return $this; } public function commit($params = array()) { $this->_api_url = 'commit'; $this->_method = self::POST; $this->_params = $params; return $this; } public function events($params = array()) { $this->_api_url = 'events'; $this->_method = self::GET; $this->_params = $params; return $this; } }
{'content_hash': 'fb7eeb8b7c8af82c5a0f628650e95fd8', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 46, 'avg_line_length': 23.0, 'alnum_prop': 0.49298737727910236, 'repo_name': 'wukezhan/docker-ui', 'id': 'df991018db403dad04ef1fd883ffa3915249b893', 'size': '1426', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/air/docker/misc.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19776'}, {'name': 'JavaScript', 'bytes': '6495'}, {'name': 'PHP', 'bytes': '24810'}, {'name': 'Smarty', 'bytes': '4255'}]}
//go:build !ignore_autogenerated // +build !ignore_autogenerated // Code generated by conversion-gen. DO NOT EDIT. package v1 import ( unsafe "unsafe" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" conversion "k8s.io/apimachinery/pkg/conversion" runtime "k8s.io/apimachinery/pkg/runtime" config "k8s.io/apiserver/pkg/apis/config" ) func init() { localSchemeBuilder.Register(RegisterConversions) } // RegisterConversions adds conversion functions to the given scheme. // Public to allow building arbitrary schemes. func RegisterConversions(s *runtime.Scheme) error { if err := s.AddGeneratedConversionFunc((*AESConfiguration)(nil), (*config.AESConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_AESConfiguration_To_config_AESConfiguration(a.(*AESConfiguration), b.(*config.AESConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.AESConfiguration)(nil), (*AESConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_AESConfiguration_To_v1_AESConfiguration(a.(*config.AESConfiguration), b.(*AESConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*EncryptionConfiguration)(nil), (*config.EncryptionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_EncryptionConfiguration_To_config_EncryptionConfiguration(a.(*EncryptionConfiguration), b.(*config.EncryptionConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.EncryptionConfiguration)(nil), (*EncryptionConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_EncryptionConfiguration_To_v1_EncryptionConfiguration(a.(*config.EncryptionConfiguration), b.(*EncryptionConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*IdentityConfiguration)(nil), (*config.IdentityConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_IdentityConfiguration_To_config_IdentityConfiguration(a.(*IdentityConfiguration), b.(*config.IdentityConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.IdentityConfiguration)(nil), (*IdentityConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_IdentityConfiguration_To_v1_IdentityConfiguration(a.(*config.IdentityConfiguration), b.(*IdentityConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*KMSConfiguration)(nil), (*config.KMSConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_KMSConfiguration_To_config_KMSConfiguration(a.(*KMSConfiguration), b.(*config.KMSConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.KMSConfiguration)(nil), (*KMSConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_KMSConfiguration_To_v1_KMSConfiguration(a.(*config.KMSConfiguration), b.(*KMSConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*Key)(nil), (*config.Key)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_Key_To_config_Key(a.(*Key), b.(*config.Key), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.Key)(nil), (*Key)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_Key_To_v1_Key(a.(*config.Key), b.(*Key), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*ProviderConfiguration)(nil), (*config.ProviderConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_ProviderConfiguration_To_config_ProviderConfiguration(a.(*ProviderConfiguration), b.(*config.ProviderConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.ProviderConfiguration)(nil), (*ProviderConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_ProviderConfiguration_To_v1_ProviderConfiguration(a.(*config.ProviderConfiguration), b.(*ProviderConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*ResourceConfiguration)(nil), (*config.ResourceConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_ResourceConfiguration_To_config_ResourceConfiguration(a.(*ResourceConfiguration), b.(*config.ResourceConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.ResourceConfiguration)(nil), (*ResourceConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_ResourceConfiguration_To_v1_ResourceConfiguration(a.(*config.ResourceConfiguration), b.(*ResourceConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*SecretboxConfiguration)(nil), (*config.SecretboxConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_v1_SecretboxConfiguration_To_config_SecretboxConfiguration(a.(*SecretboxConfiguration), b.(*config.SecretboxConfiguration), scope) }); err != nil { return err } if err := s.AddGeneratedConversionFunc((*config.SecretboxConfiguration)(nil), (*SecretboxConfiguration)(nil), func(a, b interface{}, scope conversion.Scope) error { return Convert_config_SecretboxConfiguration_To_v1_SecretboxConfiguration(a.(*config.SecretboxConfiguration), b.(*SecretboxConfiguration), scope) }); err != nil { return err } return nil } func autoConvert_v1_AESConfiguration_To_config_AESConfiguration(in *AESConfiguration, out *config.AESConfiguration, s conversion.Scope) error { out.Keys = *(*[]config.Key)(unsafe.Pointer(&in.Keys)) return nil } // Convert_v1_AESConfiguration_To_config_AESConfiguration is an autogenerated conversion function. func Convert_v1_AESConfiguration_To_config_AESConfiguration(in *AESConfiguration, out *config.AESConfiguration, s conversion.Scope) error { return autoConvert_v1_AESConfiguration_To_config_AESConfiguration(in, out, s) } func autoConvert_config_AESConfiguration_To_v1_AESConfiguration(in *config.AESConfiguration, out *AESConfiguration, s conversion.Scope) error { out.Keys = *(*[]Key)(unsafe.Pointer(&in.Keys)) return nil } // Convert_config_AESConfiguration_To_v1_AESConfiguration is an autogenerated conversion function. func Convert_config_AESConfiguration_To_v1_AESConfiguration(in *config.AESConfiguration, out *AESConfiguration, s conversion.Scope) error { return autoConvert_config_AESConfiguration_To_v1_AESConfiguration(in, out, s) } func autoConvert_v1_EncryptionConfiguration_To_config_EncryptionConfiguration(in *EncryptionConfiguration, out *config.EncryptionConfiguration, s conversion.Scope) error { out.Resources = *(*[]config.ResourceConfiguration)(unsafe.Pointer(&in.Resources)) return nil } // Convert_v1_EncryptionConfiguration_To_config_EncryptionConfiguration is an autogenerated conversion function. func Convert_v1_EncryptionConfiguration_To_config_EncryptionConfiguration(in *EncryptionConfiguration, out *config.EncryptionConfiguration, s conversion.Scope) error { return autoConvert_v1_EncryptionConfiguration_To_config_EncryptionConfiguration(in, out, s) } func autoConvert_config_EncryptionConfiguration_To_v1_EncryptionConfiguration(in *config.EncryptionConfiguration, out *EncryptionConfiguration, s conversion.Scope) error { out.Resources = *(*[]ResourceConfiguration)(unsafe.Pointer(&in.Resources)) return nil } // Convert_config_EncryptionConfiguration_To_v1_EncryptionConfiguration is an autogenerated conversion function. func Convert_config_EncryptionConfiguration_To_v1_EncryptionConfiguration(in *config.EncryptionConfiguration, out *EncryptionConfiguration, s conversion.Scope) error { return autoConvert_config_EncryptionConfiguration_To_v1_EncryptionConfiguration(in, out, s) } func autoConvert_v1_IdentityConfiguration_To_config_IdentityConfiguration(in *IdentityConfiguration, out *config.IdentityConfiguration, s conversion.Scope) error { return nil } // Convert_v1_IdentityConfiguration_To_config_IdentityConfiguration is an autogenerated conversion function. func Convert_v1_IdentityConfiguration_To_config_IdentityConfiguration(in *IdentityConfiguration, out *config.IdentityConfiguration, s conversion.Scope) error { return autoConvert_v1_IdentityConfiguration_To_config_IdentityConfiguration(in, out, s) } func autoConvert_config_IdentityConfiguration_To_v1_IdentityConfiguration(in *config.IdentityConfiguration, out *IdentityConfiguration, s conversion.Scope) error { return nil } // Convert_config_IdentityConfiguration_To_v1_IdentityConfiguration is an autogenerated conversion function. func Convert_config_IdentityConfiguration_To_v1_IdentityConfiguration(in *config.IdentityConfiguration, out *IdentityConfiguration, s conversion.Scope) error { return autoConvert_config_IdentityConfiguration_To_v1_IdentityConfiguration(in, out, s) } func autoConvert_v1_KMSConfiguration_To_config_KMSConfiguration(in *KMSConfiguration, out *config.KMSConfiguration, s conversion.Scope) error { out.APIVersion = in.APIVersion out.Name = in.Name out.CacheSize = (*int32)(unsafe.Pointer(in.CacheSize)) out.Endpoint = in.Endpoint out.Timeout = (*metav1.Duration)(unsafe.Pointer(in.Timeout)) return nil } // Convert_v1_KMSConfiguration_To_config_KMSConfiguration is an autogenerated conversion function. func Convert_v1_KMSConfiguration_To_config_KMSConfiguration(in *KMSConfiguration, out *config.KMSConfiguration, s conversion.Scope) error { return autoConvert_v1_KMSConfiguration_To_config_KMSConfiguration(in, out, s) } func autoConvert_config_KMSConfiguration_To_v1_KMSConfiguration(in *config.KMSConfiguration, out *KMSConfiguration, s conversion.Scope) error { out.APIVersion = in.APIVersion out.Name = in.Name out.CacheSize = (*int32)(unsafe.Pointer(in.CacheSize)) out.Endpoint = in.Endpoint out.Timeout = (*metav1.Duration)(unsafe.Pointer(in.Timeout)) return nil } // Convert_config_KMSConfiguration_To_v1_KMSConfiguration is an autogenerated conversion function. func Convert_config_KMSConfiguration_To_v1_KMSConfiguration(in *config.KMSConfiguration, out *KMSConfiguration, s conversion.Scope) error { return autoConvert_config_KMSConfiguration_To_v1_KMSConfiguration(in, out, s) } func autoConvert_v1_Key_To_config_Key(in *Key, out *config.Key, s conversion.Scope) error { out.Name = in.Name out.Secret = in.Secret return nil } // Convert_v1_Key_To_config_Key is an autogenerated conversion function. func Convert_v1_Key_To_config_Key(in *Key, out *config.Key, s conversion.Scope) error { return autoConvert_v1_Key_To_config_Key(in, out, s) } func autoConvert_config_Key_To_v1_Key(in *config.Key, out *Key, s conversion.Scope) error { out.Name = in.Name out.Secret = in.Secret return nil } // Convert_config_Key_To_v1_Key is an autogenerated conversion function. func Convert_config_Key_To_v1_Key(in *config.Key, out *Key, s conversion.Scope) error { return autoConvert_config_Key_To_v1_Key(in, out, s) } func autoConvert_v1_ProviderConfiguration_To_config_ProviderConfiguration(in *ProviderConfiguration, out *config.ProviderConfiguration, s conversion.Scope) error { out.AESGCM = (*config.AESConfiguration)(unsafe.Pointer(in.AESGCM)) out.AESCBC = (*config.AESConfiguration)(unsafe.Pointer(in.AESCBC)) out.Secretbox = (*config.SecretboxConfiguration)(unsafe.Pointer(in.Secretbox)) out.Identity = (*config.IdentityConfiguration)(unsafe.Pointer(in.Identity)) out.KMS = (*config.KMSConfiguration)(unsafe.Pointer(in.KMS)) return nil } // Convert_v1_ProviderConfiguration_To_config_ProviderConfiguration is an autogenerated conversion function. func Convert_v1_ProviderConfiguration_To_config_ProviderConfiguration(in *ProviderConfiguration, out *config.ProviderConfiguration, s conversion.Scope) error { return autoConvert_v1_ProviderConfiguration_To_config_ProviderConfiguration(in, out, s) } func autoConvert_config_ProviderConfiguration_To_v1_ProviderConfiguration(in *config.ProviderConfiguration, out *ProviderConfiguration, s conversion.Scope) error { out.AESGCM = (*AESConfiguration)(unsafe.Pointer(in.AESGCM)) out.AESCBC = (*AESConfiguration)(unsafe.Pointer(in.AESCBC)) out.Secretbox = (*SecretboxConfiguration)(unsafe.Pointer(in.Secretbox)) out.Identity = (*IdentityConfiguration)(unsafe.Pointer(in.Identity)) out.KMS = (*KMSConfiguration)(unsafe.Pointer(in.KMS)) return nil } // Convert_config_ProviderConfiguration_To_v1_ProviderConfiguration is an autogenerated conversion function. func Convert_config_ProviderConfiguration_To_v1_ProviderConfiguration(in *config.ProviderConfiguration, out *ProviderConfiguration, s conversion.Scope) error { return autoConvert_config_ProviderConfiguration_To_v1_ProviderConfiguration(in, out, s) } func autoConvert_v1_ResourceConfiguration_To_config_ResourceConfiguration(in *ResourceConfiguration, out *config.ResourceConfiguration, s conversion.Scope) error { out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources)) out.Providers = *(*[]config.ProviderConfiguration)(unsafe.Pointer(&in.Providers)) return nil } // Convert_v1_ResourceConfiguration_To_config_ResourceConfiguration is an autogenerated conversion function. func Convert_v1_ResourceConfiguration_To_config_ResourceConfiguration(in *ResourceConfiguration, out *config.ResourceConfiguration, s conversion.Scope) error { return autoConvert_v1_ResourceConfiguration_To_config_ResourceConfiguration(in, out, s) } func autoConvert_config_ResourceConfiguration_To_v1_ResourceConfiguration(in *config.ResourceConfiguration, out *ResourceConfiguration, s conversion.Scope) error { out.Resources = *(*[]string)(unsafe.Pointer(&in.Resources)) out.Providers = *(*[]ProviderConfiguration)(unsafe.Pointer(&in.Providers)) return nil } // Convert_config_ResourceConfiguration_To_v1_ResourceConfiguration is an autogenerated conversion function. func Convert_config_ResourceConfiguration_To_v1_ResourceConfiguration(in *config.ResourceConfiguration, out *ResourceConfiguration, s conversion.Scope) error { return autoConvert_config_ResourceConfiguration_To_v1_ResourceConfiguration(in, out, s) } func autoConvert_v1_SecretboxConfiguration_To_config_SecretboxConfiguration(in *SecretboxConfiguration, out *config.SecretboxConfiguration, s conversion.Scope) error { out.Keys = *(*[]config.Key)(unsafe.Pointer(&in.Keys)) return nil } // Convert_v1_SecretboxConfiguration_To_config_SecretboxConfiguration is an autogenerated conversion function. func Convert_v1_SecretboxConfiguration_To_config_SecretboxConfiguration(in *SecretboxConfiguration, out *config.SecretboxConfiguration, s conversion.Scope) error { return autoConvert_v1_SecretboxConfiguration_To_config_SecretboxConfiguration(in, out, s) } func autoConvert_config_SecretboxConfiguration_To_v1_SecretboxConfiguration(in *config.SecretboxConfiguration, out *SecretboxConfiguration, s conversion.Scope) error { out.Keys = *(*[]Key)(unsafe.Pointer(&in.Keys)) return nil } // Convert_config_SecretboxConfiguration_To_v1_SecretboxConfiguration is an autogenerated conversion function. func Convert_config_SecretboxConfiguration_To_v1_SecretboxConfiguration(in *config.SecretboxConfiguration, out *SecretboxConfiguration, s conversion.Scope) error { return autoConvert_config_SecretboxConfiguration_To_v1_SecretboxConfiguration(in, out, s) }
{'content_hash': 'bd70c779daee23a5508e5e8890757b88', 'timestamp': '', 'source': 'github', 'line_count': 285, 'max_line_length': 171, 'avg_line_length': 54.771929824561404, 'alnum_prop': 0.7912876361306854, 'repo_name': 'liggitt/kubernetes', 'id': '8585428632b8f07d26dedfbc964111c38c372357', 'size': '16174', 'binary': False, 'copies': '52', 'ref': 'refs/heads/master', 'path': 'staging/src/k8s.io/apiserver/pkg/apis/config/v1/zz_generated.conversion.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '833'}, {'name': 'C', 'bytes': '3902'}, {'name': 'Dockerfile', 'bytes': '47376'}, {'name': 'Go', 'bytes': '64172023'}, {'name': 'HTML', 'bytes': '106'}, {'name': 'Makefile', 'bytes': '64194'}, {'name': 'PowerShell', 'bytes': '144474'}, {'name': 'Python', 'bytes': '23655'}, {'name': 'Shell', 'bytes': '1818574'}, {'name': 'sed', 'bytes': '1262'}]}
grunt-niteo-cdbuild (It's FUN!) =================== [![Build status](https://ci.appveyor.com/api/projects/status/2momxn2atsvys1ht/branch/master?svg=true)](https://ci.appveyor.com/project/NiteoBuildBot/grunt-niteo-cdbuild/branch/master) [![Build Status](https://travis-ci.org/VeriShip/grunt-niteo-cdbuild.svg?branch=master)](https://travis-ci.org/VeriShip/grunt-niteo-cdbuild) This is a grunt extension that we use with our continuously deployments/integrations. In order to create a continuous delivery pipeline, we need to be able to plug and play the tasks that need to be run. Those tasks come in many varieties, but can most likely be categorized into two different goals. - Tasks that affect state - or tasks that affect environments Tasks that affect state are tasks that you use to make sure that everything is going smoothly within your build. Making sure that particular properties exist, making sure that dependent packages are installed, or making sure tests pass are some examples. Tasks that affect environments are used to build, alter, or destroy virtual environments that our build artifacts are going to run on. You can further categorize these tasks into five more categories. - Tasks that you need to run at the beginning of a run and don't have any affect on any environments. - Tasks that you need to provision an environment - Tasks that are dependent on an environment - Tasks that clean up the environment - Tasks that you need at the end of a run and don't have any affect on any environments. I've laid out these five in the order they're in on purpose. These five categories directly correlate into the broadest of steps our continuous delivery pipeline runs in. - Pre-Setup Tasks - Setup Tasks - Test Tasks - Teardown Tasks - Post-Teardown Tasks **Pre-Setup Tasks** These tasks are tasks that only affect state, need to be ran at the beginning of the run, and do not affect any environments. A good example of these kinds of tasks are tasks that make sure dependencies exist before any build artifacts are created. For that matter, building application artifacts would also be considered a *Pre-Setup* task. This is a little confusing, I know, but bare with me. Running your build (and by build here, I mean clicking on *build* within an IDE for example.) while you're developing isn't the same thing as performing a full *continuous delivery* pipeline. Although, those builds can be complex in themselves, they are not concerned with building up a *production-like* environment and testing your build artifacts within that environment. The *Continuous Delivery* pipeline is meant to facilitate that. **Setup Tasks** Setup tasks are meant to ready the environment(s) that will be used to test your build artifacts within. Such as calling [vagrant up](). Having a task that would do this would need to be categorized within the Setup Tasks category. **Test Tasks** Once the production-like environment(s) are ready, tasks that need to interact with that environment are run. For example: - Deploying your build artifacts to the production-like environments. - Running tests against those build artifacts. - Reporting on those tests. etc... **Teardown Tasks** Since the environment needs to exist across multiple tasks, we use this step to make sure we clean up any leftovers of that environment. Because of that, this step has special meaning that we'll get into a little later. **Post-Teardown** These tasks are tasks that only affect state, need to be ran at the end of the run and do not affect any environments **Why are teardown tasks so special?** If our *continuous delivery* run provisions [AWS EC2](http://aws.amazon.com/ec2/) and uses those instances to deploy it's artifacts and test those artifacts, we don't want those instances to exist after the run completes. Even if the run was not a success. (Especially if the run was not a success.) Normally, if an error is encountered within a task, the run stops immediately. This makes sure that we [fail fast](http://en.wikipedia.org/wiki/Fail-fast). However, we need our production-like environment to exist across multiple tasks and steps. So we need to make sure that all tasks associated with cleaning up those environments are ran if those environments exist. Because of this, any error encountered within the *Setup* and *Test* steps will not immediately fail the run. Instead, after the failing task, the current task queue is cleared out and the *Teardown* step tasks are queued. Each task within this step is ran regarless of their success or failure as well. So, unless the *Teardown* tasks are poorly written and fail before their goal is accomplished, the environment(s) should be cleaned up no matter the outcome of the run. Installation ------------ ``` npm install grunt-niteo-cdbuild --save-dev ``` Usage ----- ```js // Register the tasks grunt.loadNpmTasks('grunt-niteo-cdbuild'); // Register the default task to run the cdbuild task. grunt.registerTask('default', [ 'cdbuild' ]); // Here we register a task to run in the pre-setup step. grunt.option('preSetupTasks').push('taskNameToRunInSetup'); // Here we register a task to run in the setup step. grunt.option('setupTasks').push('taskNameToRunInPreSetup'); // Here we register a task to run in the test step. grunt.option('testTasks').push('taskNameToRunInTest'); // Here we register a task to run in the teardown step. grunt.option('teardownTasks').push('taskNameToRunInTeardown'); // Here we register a task to run in the setup step. grunt.option('postTeardownTasks').push('taskNameToRunInPostTeardown'); ```
{'content_hash': 'd7494ae45e741703464c9c87e15e9e45', 'timestamp': '', 'source': 'github', 'line_count': 101, 'max_line_length': 521, 'avg_line_length': 55.48514851485149, 'alnum_prop': 0.7749821556031407, 'repo_name': 'NiteoSoftware/grunt-niteo-cdbuild', 'id': 'ebeaacadfca84410283c333ff4e32162cd0e991f', 'size': '5604', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'readme.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CoffeeScript', 'bytes': '22956'}]}
/** * Spring Data Elasticsearch repositories. */ package io.iansoft.blockchain.repository.search;
{'content_hash': '96bf967f3344811c07712394c4158c11', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 48, 'avg_line_length': 25.0, 'alnum_prop': 0.77, 'repo_name': 'iansoftdev/all-blockchain', 'id': 'f54ff8e3b96db274a88fc8c3deed7ecb7227ee59', 'size': '100', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/io/iansoft/blockchain/repository/search/package-info.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '23670'}, {'name': 'Dockerfile', 'bytes': '328'}, {'name': 'Gherkin', 'bytes': '179'}, {'name': 'HTML', 'bytes': '296792'}, {'name': 'Java', 'bytes': '814900'}, {'name': 'JavaScript', 'bytes': '999740'}, {'name': 'Scala', 'bytes': '33739'}, {'name': 'Shell', 'bytes': '280'}, {'name': 'TSQL', 'bytes': '104378'}, {'name': 'TypeScript', 'bytes': '759210'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>OpenISA Dynamic Binary Translator: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="oi.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">OpenISA Dynamic Binary Translator &#160;<span id="projectnumber">0.0.1</span> </div> <div id="projectbrief">This project implements the Dynamic Binary Translator for the OpenISA Instruction Set. Besides, it implement the Region Formation Techniques such as NET, MRET2, NETPLUS, ...</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('structspp___1_1is__floating__point_3_01float_01_4.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="headertitle"> <div class="title">spp_::is_floating_point&lt; float &gt; Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structspp___1_1is__floating__point_3_01float_01_4.html">spp_::is_floating_point&lt; float &gt;</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>value</b> (defined in <a class="el" href="structspp___1_1integral__constant.html">spp_::integral_constant&lt; T, v &gt;</a>)</td><td class="entry"><a class="el" href="structspp___1_1integral__constant.html">spp_::integral_constant&lt; T, v &gt;</a></td><td class="entry"><span class="mlabel">static</span></td></tr> </table></div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li> </ul> </div> </body> </html>
{'content_hash': '45f4b44e0f5f8155330e0d355bb6b35f', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 373, 'avg_line_length': 44.404580152671755, 'alnum_prop': 0.6496475846656352, 'repo_name': 'OpenISA/oi-dbt', 'id': '346ee287408e4bd15bc24b55d370ee3da8ada270', 'size': '5817', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/html/structspp___1_1is__floating__point_3_01float_01_4-members.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '25399'}, {'name': 'C++', 'bytes': '721253'}, {'name': 'CMake', 'bytes': '2737'}]}
var Icon = require('../icon'); var element = require('magic-virtual-element'); var clone = require('../clone'); exports.render = function render(component) { var props = clone(component.props); delete props.children; return element( Icon, props, element('path', { d: 'M8 5v14l11-7z' }) ); };
{'content_hash': '2ca2d2d8ba12aa12b1233a500b94ced1', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 47, 'avg_line_length': 24.0, 'alnum_prop': 0.6442307692307693, 'repo_name': 'goto-bus-stop/deku-material-svg-icons', 'id': 'df255d239c43530eed24093c3b82c888da690198', 'size': '312', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/av/play-arrow.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '481956'}]}
(function (tree) { tree.Anonymous = function (value, index, currentFileInfo, mapLines) { this.value = value; this.index = index; this.mapLines = mapLines; this.currentFileInfo = currentFileInfo; }; tree.Anonymous.prototype = { type: "Anonymous", eval: function () { return new tree.Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; }, genCSS: function (env, output) { output.add(this.value, this.currentFileInfo, this.index, this.mapLines); }, toCSS: tree.toCSS }; })(require('../tree'));
{'content_hash': '60f05043508e635f1e34aaf93a7c32b0', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 95, 'avg_line_length': 25.08823529411765, 'alnum_prop': 0.5451348182883939, 'repo_name': 'dbkaplun/hipshort', 'id': 'd6e5790301e8a23254f12b65f22544342ab2bfe4', 'size': '853', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'node_modules/sails/node_modules/grunt-contrib-less/node_modules/less/lib/less/tree/anonymous.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1227'}, {'name': 'JavaScript', 'bytes': '140888'}]}
// Copyright 2014 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. package com.google.devtools.build.lib.util.io; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; /** * An implementation of {@link OutErr} that captures all out / err output and * makes it available as ISO-8859-1 strings. Useful for implementing test * cases that assert particular output. */ public class RecordingOutErr extends OutErr { public RecordingOutErr() { super(new ByteArrayOutputStream(), new ByteArrayOutputStream()); } public RecordingOutErr(ByteArrayOutputStream out, ByteArrayOutputStream err) { super(out, err); } /** * Reset the captured content; that is, reset the out / err buffers. */ public void reset() { getOutputStream().reset(); getErrorStream().reset(); } /** * Interprets the captured out content as an {@code ISO-8859-1} encoded * string. */ public String outAsLatin1() { try { return getOutputStream().toString("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } /** * Interprets the captured err content as an {@code ISO-8859-1} encoded * string. */ public String errAsLatin1() { try { return getErrorStream().toString("ISO-8859-1"); } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } /** * Returns true if any output was recorded. */ public boolean hasRecordedOutput() { return getOutputStream().size() > 0 || getErrorStream().size() > 0; } @Override public String toString() { String out = outAsLatin1(); String err = errAsLatin1(); return "" + ((out.length() > 0) ? ("stdout: " + out + "\n") : "") + ((err.length() > 0) ? ("stderr: " + err) : ""); } @Override public ByteArrayOutputStream getOutputStream() { return (ByteArrayOutputStream) super.getOutputStream(); } @Override public ByteArrayOutputStream getErrorStream() { return (ByteArrayOutputStream) super.getErrorStream(); } }
{'content_hash': '42d6bce3ab57e63f934392df44a20797', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 80, 'avg_line_length': 28.802197802197803, 'alnum_prop': 0.6798931705455933, 'repo_name': 'manashmndl/bazel', 'id': 'd276afc1a6fa1a4d615ea024b25b6da10b957e14', 'size': '2621', 'binary': False, 'copies': '22', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/google/devtools/build/lib/util/io/RecordingOutErr.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '39919'}, {'name': 'C++', 'bytes': '274763'}, {'name': 'CSS', 'bytes': '2220'}, {'name': 'HTML', 'bytes': '24717'}, {'name': 'Java', 'bytes': '12434409'}, {'name': 'JavaScript', 'bytes': '12819'}, {'name': 'Protocol Buffer', 'bytes': '61680'}, {'name': 'Python', 'bytes': '87109'}, {'name': 'Shell', 'bytes': '303688'}]}
package reexec // import "github.com/docker/docker/pkg/reexec" import ( "os" "os/exec" "testing" "gotest.tools/v3/assert" ) func init() { Register("reexec", func() { panic("Return Error") }) Init() } func TestRegister(t *testing.T) { defer func() { if r := recover(); r != nil { assert.Equal(t, `reexec func already registered under name "reexec"`, r) } }() Register("reexec", func() {}) } func TestCommand(t *testing.T) { cmd := Command("reexec") w, err := cmd.StdinPipe() assert.NilError(t, err, "Error on pipe creation: %v", err) defer w.Close() err = cmd.Start() assert.NilError(t, err, "Error on re-exec cmd: %v", err) err = cmd.Wait() assert.Error(t, err, "exit status 2") } func TestNaiveSelf(t *testing.T) { if os.Getenv("TEST_CHECK") == "1" { os.Exit(2) } cmd := exec.Command(naiveSelf(), "-test.run=TestNaiveSelf") cmd.Env = append(os.Environ(), "TEST_CHECK=1") err := cmd.Start() assert.NilError(t, err, "Unable to start command") err = cmd.Wait() assert.Error(t, err, "exit status 2") os.Args[0] = "mkdir" assert.Check(t, naiveSelf() != os.Args[0]) }
{'content_hash': 'afdae3132129c865fecc0ef2ca60cf56', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 75, 'avg_line_length': 21.346153846153847, 'alnum_prop': 0.6315315315315315, 'repo_name': 'konstruktoid/docker-1', 'id': '8aea0431e31ec352077383d8fbf087ecab12e77e', 'size': '1110', 'binary': False, 'copies': '35', 'ref': 'refs/heads/master', 'path': 'pkg/reexec/reexec_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '3652'}, {'name': 'Go', 'bytes': '4426230'}, {'name': 'Makefile', 'bytes': '6325'}, {'name': 'PowerShell', 'bytes': '5978'}, {'name': 'Shell', 'bytes': '324496'}, {'name': 'VimL', 'bytes': '1332'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- Reviewed: no --> <sect1 id="zend.mobile.push.gcm"> <title>Zend_Mobile_Push_Gcm</title> <para> <classname>Zend_Mobile_Push_Gcm</classname> provides the ability to send push notifications to Android devices that contain Google Services. A message will always be constructed with <classname>Zend_Mobile_Push_Message_Gcm</classname>. </para> <sect2 id="zend.mobile.push.gcm.server"> <title>Pushing Messages</title> <note> <para>Prior to pushing and receiving messages; you will need to create a Google API Project and setup your Android app to listen to GCM messages.. If you have not done this, follow the <ulink url="http://developer.android.com/guide/google/gcm/gs.html"> GCM: Getting Started</ulink> document. </para> </note> <para> When implementing GCM; you have a few components that you will utilize. <classname>Zend_Mobile_Push_Gcm</classname> which contains the server components, <classname>Zend_Mobile_Push_Message_Gcm</classname> which contains the message that you would like to send, and <classname>Zend_Mobile_Push_Response_Gcm</classname> which contains the response from GCM. Each message sent must do an HTTP request; so remember this when sending in large batches. </para> <para> The actual implementation of the code is fairly minimal; however, considerations to error handling must be taken. </para> <programlisting language="php"><![CDATA[ $message = new Zend_Mobile_Push_Message_Gcm(); $message->addToken('ABCDEF0123456789'); $message->setData(array( 'foo' => 'bar', 'bar' => 'foo', )); $gcm = new Zend_Mobile_Push_Gcm(); $gcm->setApiKey('YOUR_API_KEY'); try { $response = $gcm->send($message); } catch (Zend_Mobile_Push_Exception $e) { // exceptions require action or implementation of exponential backoff. die($e->getMessage()); } // handle all errors and registration_id's foreach ($response->getResults() as $k => $v) { if ($v['registration_id']) { printf("%s has a new registration id of: %s\r\n", $k, $v['registration_id']); } if ($v['error']) { printf("%s had an error of: %s\r\n", $k, $v['error']); } if ($v['message_id']) { printf("%s was successfully sent the message, message id is: %s", $k, $v['message_id']); } } ]]></programlisting> <table id="zend.mobile.push.gcm.server.exceptions"> <title>Exceptions and Remediation Techniques</title> <tgroup cols="3" align="left" colsep="1" rowsep="1"> <thead> <row> <entry>Exception</entry> <entry>Meaning</entry> <entry>Handling</entry> </row> </thead> <tbody> <row> <entry>Zend_Mobile_Push_Exception</entry> <entry>These types of exceptions are more generic in nature and are thrown either from gcm when there was an unknown exception or internally on input validation.</entry> <entry>Read the message and determine remediation steps.</entry> </row> <row> <entry>Zend_Mobile_Push_Exception_InvalidAuthToken</entry> <entry>Your API key was likely typed in wrong or does not have rights to the GCM service.</entry> <entry>Check your project on the <ulink url="https://code.google.com/apis/console">Google APIs Console page</ulink>.</entry> </row> <row> <entry>Zend_Mobile_Push_Exception_ServerUnavailable</entry> <entry>This exception means there was either an internal server error OR that the server denied your request and you should look at the Retry-After header.</entry> <entry>Read the exception message and utilize Exponential Backoff</entry> </row> <row> <entry>Zend_Mobile_Push_Exception_InvalidPayload</entry> <entry>Generally the payload will not throw an exception unless the size of the payload is too large or the JSON is too large.</entry> <entry>Check the size of the payload is within the requirements of GCM, currently it is 4K.</entry> </row> </tbody> </tgroup> </table> </sect2> <sect2 id="zend.mobile.push.gcm.message"> <title>Advanced Messages</title> <para> GCM provides the ability for sending more advanced messages; for instance the examples above show the most basic implementation of a message. <classname>Zend_Mobile_Push_Message_Gcm</classname> allows you to do far more advanced messaging outlined below. </para> <sect3 id="zend.mobile.push.gcm.message.delay-while-idle"> <title>Delay While Idle</title> <para> If included, indicates that the message should not be sent immediately if the device is idle. The server will wait for the device to become active, and then only the last message for each collapse_key value will be sent. </para> <programlisting language="php"><![CDATA[ $message = new Zend_Mobile_Push_Message_Gcm(); $message->setDelayWhileIdle(true); ]]></programlisting> </sect3> <sect3 id="zend.mobile.push.gcm.message.ttl"> <title>Time to Live</title> <para> You may set the time to live in seconds, by default GCM will save it for 4 weeks. Additionally if you specify a Time to Live, you must also set an ID (the collapse key). Generally it is best by using the message data so that you know it is a unique message. </para> <programlisting language="php"><![CDATA[ $message = new Zend_Mobile_Push_Message_Gcm(); $message->setTtl(86400); $message->addData('key', 'value'); $message->setId(md5(json_encode($message->getData()))); ]]></programlisting> </sect3> </sect2> <sect2 id="zend.mobile.push.gcm.response"> <title>Response</title> <para> GCM gives a response back that contains detail that needs to be understood. Most of the time you can just send a message but the server may come back telling you any the message id, any errors and potentially new registration ids. </para> <sect3 id="zend.mobile.push.gcm.response.result"> <title>Results</title> <para> The results are most commonly retrieved by calling the getResults() method. However, you may prefer to just get certain results by using the getResult() method. The getResult method utilizes the constants RESULT_* correlating to message id, error or registration id. </para> <para> Several utility methods exist to give you a better idea of what happened during your send. Methods getSuccessCount(), getFailureCount() and getCanonicalCount() let you know how many where successful, how many failures and how many updates to registration ids you have. </para> </sect3> </sect1>
{'content_hash': 'ace1e04baaa1d3802975069ab752704e', 'timestamp': '', 'source': 'github', 'line_count': 204, 'max_line_length': 96, 'avg_line_length': 40.09803921568628, 'alnum_prop': 0.5599022004889975, 'repo_name': 'weierophinney/zf1', 'id': 'a71fe134cc5c4729235a8721cd3dfe2eedc04f84', 'size': '8180', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'documentation/manual/en/module_specs/Zend_Mobile_Push-Gcm.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '40638'}, {'name': 'JavaScript', 'bytes': '30081'}, {'name': 'PHP', 'bytes': '31409780'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Puppet', 'bytes': '770'}, {'name': 'Ruby', 'bytes': '10'}, {'name': 'Shell', 'bytes': '10511'}, {'name': 'TypeScript', 'bytes': '3445'}]}
import {HttpMethod} from './net/HttpMethod'; import {HttpClient} from './net/HttpClient'; export { HttpMethod, HttpClient };
{'content_hash': '20f259f358b70d1f524ac34d11e1d557', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 44, 'avg_line_length': 18.142857142857142, 'alnum_prop': 0.7244094488188977, 'repo_name': 'FabianLauer/unsplash-json', 'id': '32128c83483f7d423378806f92dc22a18733aef3', 'size': '127', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/net.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '96557'}, {'name': 'Shell', 'bytes': '545'}, {'name': 'TypeScript', 'bytes': '64168'}]}
<?xml version="1.0" encoding="UTF-8"?> <database name="default" namespace="Payum\Core\Bridge\Propel\Model" defaultIdMethod="native" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xsd.propelorm.org/1.7/database.xsd"> <table name="Payment"> <behavior name="auto_add_pk"/> <column name="number" type="VARCHAR"/> <column name="description" type="VARCHAR"/> <column name="clientEmail" type="VARCHAR"/> <column name="clientId" type="VARCHAR"/> <column name="totalAmount" phpName="TotalAmount" type="INTEGER"/> <column name="currencyCode" type="VARCHAR"/> <column name="details" type="ARRAY"/> <vendor type="mysql"> <parameter name="Engine" value="InnoDB"/> </vendor> </table> <table name="Token" idMethod="none"> <column name="hash" type="VARCHAR" primaryKey="true"/> <column name="details" type="OBJECT"/> <column name="afterUrl" type="VARCHAR"/> <column name="targetUrl" type="VARCHAR"/> <column name="gatewayName" type="VARCHAR"/> <vendor type="mysql"> <parameter name="Engine" value="InnoDB"/> </vendor> </table> </database>
{'content_hash': '73c175166fb421be23fe86d1cc785887', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 92, 'avg_line_length': 38.0, 'alnum_prop': 0.5952012383900929, 'repo_name': 'Condors/TunisiaMall', 'id': '63a953200539e066f5cfd68c62022b2a5f545045', 'size': '1292', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/payum/core/Payum/Core/Bridge/Propel/Resources/config/schema.xml', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '16927'}, {'name': 'ApacheConf', 'bytes': '3688'}, {'name': 'Batchfile', 'bytes': '690'}, {'name': 'CSS', 'bytes': '836798'}, {'name': 'HTML', 'bytes': '917753'}, {'name': 'JavaScript', 'bytes': '1079135'}, {'name': 'PHP', 'bytes': '196744'}, {'name': 'Shell', 'bytes': '4247'}]}
/* $OpenBSD: pdc.h,v 1.9 1998/12/14 00:57:59 mickey Exp $ */ /* * Copyright (c) 1990 mt Xinu, Inc. All rights reserved. * Copyright (c) 1990,1991,1992,1994 University of Utah. All rights reserved. * * Permission to use, copy, modify and distribute this software is hereby * granted provided that (1) source code retains these copyright, permission, * and disclaimer notices, and (2) redistributions including binaries * reproduce the notices in supporting documentation, and (3) all advertising * materials mentioning features or use of this software display the following * acknowledgement: ``This product includes software developed by the * Computer Systems Laboratory at the University of Utah.'' * * Copyright (c) 1990 mt Xinu, Inc. * This file may be freely distributed in any form as long as * this copyright notice is included. * MTXINU, THE UNIVERSITY OF UTAH, AND CSL PROVIDE THIS SOFTWARE ``AS * IS'' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND * FITNESS FOR A PARTICULAR PURPOSE. * * CSL requests users of this software to return to [email protected] any * improvements that they make and grant CSL redistribution rights. * * Utah $Hdr: pdc.h 1.12 94/12/14$ */ #ifndef _MACHINE_PDC_H_ #define _MACHINE_PDC_H_ /* * Definitions for interaction with "Processor Dependent Code", * which is a set of ROM routines used to provide information to the OS. * Also includes definitions for the layout of "Page Zero" memory when * boot code is invoked. * * Glossary: * PDC: Processor Dependent Code (ROM or copy of ROM). * IODC: I/O Dependent Code (module-type dependent code). * IPL: Boot program (loaded into memory from boot device). * HPA: Hard Physical Address (hardwired address). * SPA: Soft Physical Address (reconfigurable address). * * * * * Definitions for talking to IODC (I/O Dependent Code). * * The PDC is used to load I/O Dependent Code from a particular module. * I/O Dependent Code is module-type dependent software which provides * a uniform way to identify, initialize, and access a module (and in * some cases, their devices). */ /* * Our Initial Memory Module is laid out as follows. * * 0x000 +--------------------+ * | Page Zero (iomod.h)| * 0x800 +--------------------+ * | | * | | * | PDC | * | | * | | * MEM_FREE +--------------------+ * | | * | Console IODC | * | | * MEM_FREE+16k +--------------------+ * | | * | Boot Device IODC | * | | * IPL_START +--------------------+ * | | * | IPL Code or Kernel | * | | * +--------------------+ * * Restrictions: * MEM_FREE (pagezero.mem_free) can be no greater than 32K. * The PDC may use up to MEM_FREE + 32K (for Console & Boot IODC). * IPL_START must be less than or equal to 64K. * * The IPL (boot) Code is immediately relocated to RELOC (check * "../stand/Makefile") to make way for the Kernel. */ #define IODC_MAXSIZE (16 * 1024) /* maximum size of IODC */ #define MINIOSIZ 64 /* minimum buffer size for IODC call */ #define MAXIOSIZ (64 * 1024) /* maximum buffer size for IODC call */ #define PDC_ALIGNMENT __attribute__ ((aligned(8))) /* * The PDC Entry Points and their arguments... */ #define PDC_POW_FAIL 1 /* prepare for power failure */ #define PDC_POW_FAIL_DFLT 0 #define PDC_CHASSIS 2 /* update chassis display (see below) */ #define PDC_CHASSIS_DISP 0 /* update display */ #define PDC_CHASSIS_WARN 1 /* return warnings */ #define PDC_CHASSIS_ALL 2 /* update display & return warnings */ #define PDC_PIM 3 /* access Processor Internal Memory */ #define PDC_PIM_HPMC 0 /* read High Pri Mach Chk data */ #define PDC_PIM_SIZE 1 /* return size */ #define PDC_PIM_LPMC 2 /* read Low Pri Mach Chk data */ #define PDC_PIM_SBD 3 /* read soft boot data */ #define PDC_PIM_TOC 4 /* read TOC data (used to use HPMC) */ #define PDC_MODEL 4 /* processor model number info */ #define PDC_MODEL_INFO 0 /* processor model number info */ #define PDC_MODEL_BOOTID 1 /* set BOOT_ID of processor */ #define PDC_MODEL_COMP 2 /* return component version numbers */ #define PDC_MODEL_MODEL 3 /* return system model information */ #define PDC_MODEL_ENSPEC 4 /* enable product-specific instrs */ #define PDC_MODEL_DISPEC 5 /* disable product-specific instrs */ #define PDC_CACHE 5 /* return cache and TLB params */ #define PDC_CACHE_DFLT 0 #define PDC_HPA 6 /* return HPA of processor */ #define PDC_HPA_DFLT 0 #define PDC_COPROC 7 /* return co-processor configuration */ #define PDC_COPROC_DFLT 0 #define PDC_IODC 8 /* talk to IODC */ #define PDC_IODC_READ 0 /* read IODC entry point */ #define IODC_DATA 0 /* get first 16 bytes from mod IODC */ #define IODC_INIT 3 /* initialize (see options below) */ #define IODC_INIT_FIRST 2 /* find first device on module */ #define IODC_INIT_NEXT 3 /* find subsequent devices on module */ #define IODC_INIT_ALL 4 /* initialize module and device */ #define IODC_INIT_DEV 5 /* initialize device */ #define IODC_INIT_MOD 6 /* initialize module */ #define IODC_INIT_MSG 9 /* return error message(s) */ #define IODC_INIT_STR 20 /* find device w/ spec in string */ #define IODC_IO 4 /* perform I/O (see options below) */ #define IODC_IO_READ 0 /* read from boot device */ #define IODC_IO_WRITE 1 /* write to boot device */ #define IODC_IO_CONSIN 2 /* read from console */ #define IODC_IO_CONSOUT 3 /* write to conosle */ #define IODC_IO_CLOSE 4 /* close device */ #define IODC_IO_MSG 9 /* return error message(s) */ #define IODC_SPA 5 /* get extended SPA information */ #define IODC_SPA_DFLT 0 /* return SPA information */ #define IODC_TEST 8 /* perform self tests */ #define IODC_TEST_INFO 0 /* return test information */ #define IODC_TEST_STEP 1 /* execute a particular test */ #define IODC_TEST_TEST 2 /* describe a test section */ #define IODC_TEST_MSG 9 /* return error message(s) */ #define PDC_IODC_NINIT 2 /* non-destructive init */ #define PDC_IODC_DINIT 3 /* destructive init */ #define PDC_IODC_MEMERR 4 /* check for memory errors */ #define PDC_IODC_IMEMMASTER 5 /* interlieved memory master ID */ #define PDC_TOD 9 /* access time-of-day clock */ #define PDC_TOD_READ 0 /* read TOD clock */ #define PDC_TOD_WRITE 1 /* write TOD clock */ #define PDC_TOD_ITIMER 2 /* calibrate Interval Timer (CR16) */ #define PDC_STABLE 10 /* access Stable Storage (SS) */ #define PDC_STABLE_READ 0 /* read SS */ #define PDC_STABLE_WRITE 1 /* write SS */ #define PDC_STABLE_SIZE 2 /* return size of SS */ #define PDC_STABLE_VRFY 3 /* verify contents of SS */ #define PDC_STABLE_INIT 4 /* initialize SS */ #define PDC_NVM 11 /* access Non-Volatile Memory (NVM) */ #define PDC_NVM_READ 0 /* read NVM */ #define PDC_NVM_WRITE 1 /* write NVM */ #define PDC_NVM_SIZE 2 /* return size of NVM */ #define PDC_NVM_VRFY 3 /* verify contents of NVM */ #define PDC_NVM_INIT 4 /* initialize NVM */ #define PDC_ADD_VALID 12 /* check address for validity */ #define PDC_ADD_VALID_DFLT 0 #define PDC_BUS_BAD 13 /* verify Error Detection Circuitry (EDC) */ #define PDC_BUS_BAD_DLFT 0 #define PDC_DEBUG 14 /* return address of PDC debugger */ #define PDC_DEBUG_DFLT 0 #define PDC_INSTR 15 /* return instr that invokes PDCE_CHECK */ #define PDC_INSTR_DFLT 0 #define PDC_PROC 16 /* stop currently executing processor */ #define PDC_PROC_DFLT 0 #define PDC_CONF 17 /* (de)configure a module */ #define PDC_CONF_DECONF 0 /* deconfigure module */ #define PDC_CONF_RECONF 1 /* reconfigure module */ #define PDC_CONF_INFO 2 /* get config informaion */ #define PDC_BLOCK_TLB 18 /* Manage Block TLB entries (BTLB) */ #define PDC_BTLB_DEFAULT 0 /* Return BTLB configuration info */ #define PDC_BTLB_INSERT 1 /* Insert a BTLB entry */ #define PDC_BTLB_PURGE 2 /* Purge a BTLB entry */ #define PDC_BTLB_PURGE_ALL 3 /* Purge all BTLB entries */ #define PDC_TLB 19 /* Manage Hardware TLB handling */ #define PDC_TLB_INFO 0 /* Return HW-TLB configuration info */ #define PDC_TLB_CONFIG 1 /* Set HW-TLB pdir base and size */ #define PDC_TLB_CURRPDE 1 /* cr28 points to current pde on miss */ #define PDC_TLB_RESERVD 3 /* reserved */ #define PDC_TLB_NEXTPDE 5 /* cr28 points to next pde on miss */ #define PDC_TLB_WORD3 7 /* cr28 is word 3 of 16 byte pde */ #define PDC_SOFT_POWER 23 /* support for soft power switch */ #define PDC_SOFT_POWER_INFO 0 /* get info about soft power switch */ #define PDC_SOFT_POWER_ENABLE 1 /* enable/disable soft power switch */ #define PDC_MEMMAP 128 /* hp700: return page information */ #define PDC_MEMMAP_HPA 0 /* map module # to HPA */ #define PDC_EEPROM 129 /* Hversion dependent */ #define PDC_EEPROM_READ_WORD 0 #define PDC_EEPROM_WRITE_WORD 1 #define PDC_EEPROM_READ_BYTE 2 #define PDC_EEPROM_WRITE_BYTE 3 #define PDC_LAN_STATION_ID 138 /* Hversion dependent mechanism for */ #define PDC_LAN_STATION_ID_READ 0 /* getting the lan station address */ #define PDC_ERR_OK 0 /* operation complete */ #define PDC_ERR_WARNING 3 /* OK, but warning */ #define PDC_ERR_NOPROC -1 /* no such procedure */ #define PDC_ERR_NOPT -2 /* no such option */ #define PDC_ERR_COMPL -3 /* unable to complete w/o error */ #define PDC_ERR_EOD -9 /* end of device list */ #define PDC_ERR_INVAL -10 /* invalid argument */ #define PDC_ERR_PFAIL -12 /* aborted by powerfail */ #if !defined(_LOCORE) struct iomod; typedef int (*pdcio_t) __P((int, int, ...)); typedef int (*iodcio_t) __P((struct iomod *, int, ...)); /* * Commonly used PDC calls and the structures they return. */ struct pdc_pim { /* PDC_PIM */ u_int count; /* actual (HPMC, LPMC) or total (SIZE) count */ u_int archsize; /* size of architected regions (see "pim.h") */ u_int filler[30]; }; struct pdc_model { /* PDC_MODEL */ u_int hvers; /* hardware version */ u_int svers; /* software version */ u_int hw_id; /* unique processor hardware identifier */ u_int boot_id; /* same as hw_id */ u_int sw_id; /* software security and licensing */ u_int sw_cap; /* OS capabilities of processor */ u_int arch_rev; /* architecture revision */ u_int pot_key; /* potential key */ u_int curr_key; /* current key */ int filler1; u_int filler2[22]; }; struct cache_cf { /* PDC_CACHE (for "struct pdc_cache") */ u_int cc_resv0: 4, cc_block: 4, /* used to determine most efficient stride */ cc_line : 3, /* max data written by store (16-byte mults) */ cc_resv1: 2, /* (reserved) */ cc_wt : 1, /* D-cache: write-to = 0, write-through = 1 */ cc_sh : 2, /* separate I and D = 0, shared I and D = 1 */ cc_cst : 3, /* D-cache: incoherent = 0, coherent = 1 */ cc_resv2: 5, /* (reserved) */ cc_assoc: 8; /* D-cache: associativity of cache */ }; struct tlb_cf { /* PDC_CACHE (for "struct pdc_cache") */ u_int tc_resv1:12, /* (reserved) */ tc_sh : 2, /* separate I and D = 0, shared I and D = 1 */ tc_hvers: 1, /* H-VERSION dependent */ tc_page : 1, /* 2K page size = 0, 4k page size = 1 */ tc_cst : 3, /* incoherent = 0, coherent = 1 */ tc_resv2: 5, /* (reserved) */ tc_assoc: 8; /* associativity of TLB */ }; struct pdc_cache { /* PDC_CACHE */ /* Instruction cache */ u_int ic_size; /* size of I-cache (in bytes) */ struct cache_cf ic_conf;/* cache configuration (see above) */ u_int ic_base; /* start addr of I-cache (for FICE flush) */ u_int ic_stride; /* addr incr per i_count iteration (flush) */ u_int ic_count; /* number of i_loop iterations (flush) */ u_int ic_loop; /* number of FICE's per addr stride (flush) */ /* Data cache */ u_int dc_size; /* size of D-cache (in bytes) */ struct cache_cf dc_conf;/* cache configuration (see above) */ u_int dc_base; /* start addr of D-cache (for FDCE flush) */ u_int dc_stride; /* addr incr per d_count iteration (flush) */ u_int dc_count; /* number of d_loop iterations (flush) */ u_int dc_loop; /* number of FDCE's per addr stride (flush) */ /* Instruction TLB */ u_int it_size; /* number of entries in I-TLB */ struct tlb_cf it_conf; /* I-TLB configuration (see above) */ u_int it_sp_base; /* start space of I-TLB (for PITLBE flush) */ u_int it_sp_stride; /* space incr per sp_count iteration (flush) */ u_int it_sp_count; /* number of off_count iterations (flush) */ u_int it_off_base; /* start offset of I-TLB (for PITLBE flush) */ u_int it_off_stride; /* offset incr per off_count iteration (flush)*/ u_int it_off_count; /* number of it_loop iterations/space (flush) */ u_int it_loop; /* number of PITLBE's per off_stride (flush) */ /* Data TLB */ u_int dt_size; /* number of entries in D-TLB */ struct tlb_cf dt_conf; /* D-TLB configuration (see above) */ u_int dt_sp_base; /* start space of D-TLB (for PDTLBE flush) */ u_int dt_sp_stride; /* space incr per sp_count iteration (flush) */ u_int dt_sp_count; /* number of off_count iterations (flush) */ u_int dt_off_base; /* start offset of D-TLB (for PDTLBE flush) */ u_int dt_off_stride; /* offset incr per off_count iteration (flush)*/ u_int dt_off_count; /* number of dt_loop iterations/space (flush) */ u_int dt_loop; /* number of PDTLBE's per off_stride (flush) */ u_int filler[2]; }; struct pdc_hpa { /* PDC_HPA */ hppa_hpa_t hpa; /* HPA of processor */ int filler1; u_int filler2[30]; }; struct pdc_coproc { /* PDC_COPROC */ u_int ccr_enable; /* same format as CCR (CR 10) */ u_int ccr_present; /* which co-proc's are present (bitset) */ u_int filler2[30]; }; struct pdc_tod { /* PDC_TOD, PDC_TOD_READ */ u_int sec; /* elapsed time since 00:00:00 GMT, 1/1/70 */ u_int usec; /* accurate to microseconds */ u_int filler2[30]; }; struct pdc_instr { /* PDC_INSTR */ u_int instr; /* instruction that invokes PDC mchk entry pt */ int filler1; u_int filler2[30]; }; struct pdc_iodc_read { /* PDC_IODC, PDC_IODC_READ */ int size; /* number of bytes in selected entry point */ int filler1; u_int filler2[30]; }; struct pdc_iodc_minit { /* PDC_IODC, PDC_IODC_NINIT or PDC_IODC_DINIT */ u_int stat; /* HPA.io_status style error returns */ u_int max_spa; /* size of SPA (in bytes) > max_mem+map_mem */ u_int max_mem; /* size of "implemented" memory (in bytes) */ u_int map_mem; /* size of "mapable-only" memory (in bytes) */ u_int filler[28]; }; struct btlb_info { /* for "struct pdc_btlb" (PDC_BTLB) */ u_int resv0: 8, /* (reserved) */ num_i: 8, /* Number of instruction slots */ num_d: 8, /* Number of data slots */ num_c: 8; /* Number of combined slots */ }; struct pdc_btlb { /* PDC_BLOCK_TLB */ u_int min_size; /* Min size in pages */ u_int max_size; /* Max size in pages */ struct btlb_info finfo; /* Fixed range info */ struct btlb_info vinfo; /* Variable range info */ u_int filler[28]; }; struct pdc_hwtlb { /* PDC_TLB */ u_int min_size; /* What do these mean? */ u_int max_size; u_int filler[30]; }; struct pdc_memmap { /* PDC_MEMMAP */ u_int hpa; /* HPA for module */ u_int morepages; /* additional IO pages */ u_int filler[30]; }; struct pdc_lan_station_id { /* PDC_LAN_STATION_ID */ u_int8_t addr[6]; u_int8_t filler1[2]; u_int filler2[30]; }; /* * The PDC_CHASSIS is a strange bird. The format for updating the display * is as follows: * * 0 11 12 14 15 16 19 20 23 24 27 28 31 * +-------+----------+-------+--------+--------+--------+--------+ * | R | OS State | Blank | Hex1 | Hex2 | Hex3 | Hex4 | * +-------+----------+-------+--------+--------+--------+--------+ * * Unfortunately, someone forgot to tell the hardware designers that * there was supposed to be a hex display somewhere. The result is, * you can only toggle 5 LED's and the fault light. * * Interesting values for Hex1-Hex4 and the resulting LED displays: * * FnFF CnFF: * 0 - - - - - Counts in binary from 0x0 - 0xF * 2 o - - - - for corresponding values of `n'. * 4 o o - - - * 6 o o o - - * 8 o o o o - * A o o o o o * * If the "Blank" bit is set, the display should be made blank. * The values for "OS State" are defined below. */ #define PDC_CHASSIS_BAR 0xF0FF /* create a bar graph with LEDs */ #define PDC_CHASSIS_CNT 0xC0FF /* count with LEDs */ #define PDC_OSTAT(os) (((os) & 0x7) << 17) #define PDC_OSTAT_OFF 0x0 /* all off */ #define PDC_OSTAT_FAULT 0x1 /* the red LED of death */ #define PDC_OSTAT_TEST 0x2 /* self test */ #define PDC_OSTAT_BOOT 0x3 /* boot program running */ #define PDC_OSTAT_SHUT 0x4 /* shutdown in progress */ #define PDC_OSTAT_WARN 0x5 /* battery dying, etc */ #define PDC_OSTAT_RUN 0x6 /* OS running */ #define PDC_OSTAT_ON 0x7 /* all on */ /* * Device path specifications used by PDC. */ struct device_path { u_char dp_flags; /* see bit definitions below */ char dp_bc[6]; /* Bus Converter routing info to a specific */ /* I/O adaptor (< 0 means none, > 63 resvd) */ u_char dp_mod; /* fixed field of specified module */ int dp_layers[6]; /* device-specific info (ctlr #, unit # ...) */ }; /* dp_flags */ #define PF_AUTOBOOT 0x80 /* These two are PDC flags for how to locate */ #define PF_AUTOSEARCH 0x40 /* the "boot device" */ #define PF_TIMER 0x0f /* power of 2 # secs "boot timer" (0 == dflt) */ /* * A processors Stable Storage is accessed through the PDC. There are * at least 96 bytes of stable storage (the device path information may * or may not exist). However, as far as I know, processors provide at * least 192 bytes of stable storage. */ struct stable_storage { struct device_path ss_pri_boot; /* (see above) */ char ss_filenames[32]; u_short ss_os_version; /* 0 == none, 1 == HP-UX, 2 == MPE-XL */ char ss_os[22]; /* OS-dependant information */ char ss_pdc[7]; /* reserved */ char ss_fast_size; /* how much memory to test. 0xf == all, or */ /* else it's (256KB << ss_fast_size) */ struct device_path ss_console; struct device_path ss_alt_boot; struct device_path ss_keyboard; }; /* * Recoverable error indications provided to boot code by the PDC. * Any non-zero value indicates error. */ struct boot_err { u_int be_resv : 10, /* (reserved) */ be_fixed : 6, /* module that produced error */ be_chas : 16; /* error code (interpret as 4 hex digits) */ }; /* * The PDC uses the following structure to completely define an I/O * module and the interface to its IODC. */ typedef struct pz_device { struct device_path pz_dp; #define pz_flags pz_dp.dp_flags #define pz_bc pz_dp.dp_bc #define pz_mod pz_dp.dp_mod #define pz_layers pz_dp.dp_layers struct iomod *pz_hpa; /* HPA base address of device */ caddr_t pz_spa; /* SPA base address (zero if no SPA exists) */ iodcio_t pz_iodc_io; /* entry point of device's driver routines */ short pz_resv; /* (reserved) */ u_short pz_class; /* (see below) */ } pz_device_t; /* pz_class */ #define PCL_NULL 0 /* illegal */ #define PCL_RANDOM 1 /* random access (disk) */ #define PCL_SEQU 2 /* sequential access (tape) */ #define PCL_DUPLEX 7 /* full-duplex point-to-point (RS-232, Net) */ #define PCL_KEYBD 8 /* half-duplex input (HIL Keyboard) */ #define PCL_DISPL 9 /* half-duplex ouptput (display) */ #define PCL_CLASS_MASK 0xf /* XXX class mask */ #define PCL_NET_MASK 0x1000 /* mask for bootp/tftp device */ /* * The following structure defines what a particular IODC returns when * given the IODC_DATA argument. */ struct iodc_data { u_int iodc_model: 8, /* hardware model number */ iodc_revision:8, /* software revision */ iodc_spa_io: 1, /* 0:memory, 1:device */ iodc_spa_pack:1, /* 1:packed multiplexor */ iodc_spa_enb:1, /* 1:has an spa */ iodc_spa_shift:5, /* power of two # bytes in SPA space */ iodc_more: 1, /* iodc_data is: 0:8-byte, 1:16-byte */ iodc_word: 1, /* iodc_data is: 0:byte, 1:word */ iodc_pf: 1, /* 1:supports powerfail */ iodc_type: 5; /* see below */ u_int iodc_sv_rev: 4, /* software version revision number */ iodc_sv_model:20, /* software interface model # */ iodc_sv_opt: 8; /* type-specific options */ u_char iodc_rev; /* revision number of IODC code */ u_char iodc_dep; /* module-dependent information */ u_char iodc_rsv[2]; /* reserved */ u_short iodc_cksum; /* 16-bit checksum of whole IODC */ u_short iodc_length; /* number of entry points in IODC */ /* IODC entry points follow... */ }; extern pdcio_t pdc; #ifdef _KERNEL struct consdev; extern int kernelmapped; void pdc_init __P((void)); int pdc_call __P((iodcio_t, int, ...)); void pdccnprobe __P((struct consdev *)); void pdccninit __P((struct consdev *)); int pdccngetc __P((dev_t)); void pdccnputc __P((dev_t, int)); void pdccnpollc __P((dev_t, int)); #endif #endif /* !(_LOCORE) */ #endif /* _MACHINE_PDC_H_ */
{'content_hash': 'ca415467495a7d84ada29b23dfc27e62', 'timestamp': '', 'source': 'github', 'line_count': 562, 'max_line_length': 78, 'avg_line_length': 37.05338078291815, 'alnum_prop': 0.6456012293507492, 'repo_name': 'MarginC/kame', 'id': '530e9d2a84a33e78d4891af3fbcd3d935be3a27b', 'size': '20824', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'openbsd/sys/arch/hppa/include/pdc.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Arc', 'bytes': '7491'}, {'name': 'Assembly', 'bytes': '14375563'}, {'name': 'Awk', 'bytes': '313712'}, {'name': 'Batchfile', 'bytes': '6819'}, {'name': 'C', 'bytes': '356715789'}, {'name': 'C++', 'bytes': '4231647'}, {'name': 'DIGITAL Command Language', 'bytes': '11155'}, {'name': 'Emacs Lisp', 'bytes': '790'}, {'name': 'Forth', 'bytes': '253695'}, {'name': 'GAP', 'bytes': '9964'}, {'name': 'Groff', 'bytes': '2220485'}, {'name': 'Lex', 'bytes': '168376'}, {'name': 'Logos', 'bytes': '570213'}, {'name': 'Makefile', 'bytes': '1778847'}, {'name': 'Mathematica', 'bytes': '16549'}, {'name': 'Objective-C', 'bytes': '529629'}, {'name': 'PHP', 'bytes': '11283'}, {'name': 'Perl', 'bytes': '151251'}, {'name': 'Perl6', 'bytes': '2572'}, {'name': 'Ruby', 'bytes': '7283'}, {'name': 'Scheme', 'bytes': '76872'}, {'name': 'Shell', 'bytes': '583253'}, {'name': 'Stata', 'bytes': '408'}, {'name': 'Yacc', 'bytes': '606054'}]}
<?php namespace Negotiation; final class AcceptLanguage extends BaseAccept implements AcceptHeader { private $basePart; private $subPart; public function __construct($value) { parent::__construct($value); $parts = explode('-', $this->type); if (2 === count($parts)) { $this->basePart = $parts[0]; $this->subPart = $parts[1]; } elseif (1 === count($parts)) { $this->basePart = $parts[0]; } else { // TODO: this part is never reached... throw new InvalidLanguage(); } } /** * @return string */ public function getSubPart() { return $this->subPart; } /** * @return string */ public function getBasePart() { return $this->basePart; } }
{'content_hash': '561deff618d160acd47d936d7cb1b08e', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 69, 'avg_line_length': 19.6046511627907, 'alnum_prop': 0.5065243179122183, 'repo_name': 'sjndhkl/Negotiation', 'id': 'f0790fe8a5da232ea11e497c93f632fe02559d2f', 'size': '843', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Negotiation/AcceptLanguage.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '37779'}]}
from itertools import compress import numpy as np class QuestionScale(): @staticmethod def create_scale(type, choices, exclude_from_analysis, values=None, midpoint=None): if type=='nominal': return(NominalScale(choices, exclude_from_analysis)) elif type =='ordinal': return(OrdinalScale(choices, exclude_from_analysis, values)) elif type =='likert': return(LikertScale(choices, exclude_from_analysis, values, midpoint)) else: raise(Exception("Invalid scale type: {}".format(type))) def __init__(self, choices, exclude_from_analysis): self.choices = choices self.exclude_from_analysis = exclude_from_analysis def __eq__(self, other): return (self.choices == other.choices and self.exclude_from_analysis == other.exclude_from_analysis) @staticmethod def change_scale(oldscale, new_type, new_values=None, new_midpoint=None): if hasattr(oldscale, 'values') and new_values==None: new_values = oldscale.values if hasattr(oldscale, 'midpoint') and new_midpoint==None: new_midpoint = oldscale.midpoint return(QuestionScale.create_scale(new_type, oldscale.choices, oldscale.exclude_from_analysis, new_values, new_midpoint)) def reverse_choices(self): self.choices.reverse() self.exclude_from_analysis.reverse() def get_choices(self, remove_exclusions=True): choices = self.choices if remove_exclusions: choices = list(compress(choices, [not x for x in self.exclude_from_analysis])) return(choices) def exclude_choices_from_analysis(self, choices): new_excl = [] for c, e in zip(self.choices, self.exclude_from_analysis): if c in choices: new_excl.append(True) else: new_excl.append(e) self.exclude_from_analysis = new_excl def excluded_choices(self): x = list(compress(self.choices, [x for x in self.exclude_from_analysis])) return(x) class NominalScale(QuestionScale): def __init__(self, choices, exclude_from_analysis): super().__init__(choices, exclude_from_analysis) class OrdinalScale(QuestionScale): def __init__(self, choices, exclude_from_analysis, values): super().__init__(choices, exclude_from_analysis) self.values = values def __eq__(self, other): if super().__eq__(other): return(self.values == other.values) else: return(False) def reverse_choices(self): super().reverse_choices() self.values.reverse() def get_values(self, remove_exclusions=True): values = self.values if remove_exclusions: values = list(compress(values, [not x for x in self.exclude_from_analysis])) return(values) def choices_to_str(self, remove_exclusions=False, show_values=True): choices = self.get_choices(remove_exclusions) values = self.get_values(remove_exclusions) if show_values: new_choices = [] for c, v, x in zip(choices, values, self.exclude_from_analysis): if x: new_choices.append("{} (X)".format(c)) else: new_choices.append("{} ({})".format(c, v)) choices = new_choices return(choices) class LikertScale(OrdinalScale): def __init__(self, choices, exclude_from_analysis, values, midpoint=None): super().__init__(choices, exclude_from_analysis, values) ct = len(self.exclude_from_analysis) - sum(self.exclude_from_analysis) if not midpoint: self.midpoint = ct/2 else: if midpoint > ct or midpoint < 0: raise( Exception("Invalid midpoint {} for {} point scale".format(midpoint, ct )) ) else: self.midpoint = midpoint def __eq__(self, other): if super().__eq__(other): return(self.midpoint == other.midpoint) else: return(False) def exclude_choices_from_analysis(self, choices): super().exclude_choices_from_analysis(choices) ct = len(self.exclude_from_analysis) - sum(self.exclude_from_analysis) self.midpoint = ct/2 def get_negative_mapping(self): neg_map = {} for val in self.values: if val <= self.midpoint: neg_map[val] = -1 elif val > np.ceil(self.midpoint): neg_map[val] = 0 elif val > self.midpoint: neg_map[val] = val - 1 - self.midpoint return(neg_map)
{'content_hash': '21aaf924f6535937919fb77d40b528ce', 'timestamp': '', 'source': 'github', 'line_count': 150, 'max_line_length': 90, 'avg_line_length': 33.58, 'alnum_prop': 0.5568790946992257, 'repo_name': 'cwade/surveyhelper', 'id': '1db58f0b03b3661475a775d5a1139f4fc03fa0f1', 'size': '5037', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'surveyhelper/scale.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2951'}, {'name': 'HTML', 'bytes': '49673'}, {'name': 'Python', 'bytes': '68173'}]}
package org.wso2.carbon.apimgt.rest.api.service.catalog.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import org.wso2.carbon.apimgt.rest.api.service.catalog.dto.PaginationDTO; import org.wso2.carbon.apimgt.rest.api.service.catalog.dto.ServiceCRUDStatusDTO; import javax.validation.constraints.*; import io.swagger.annotations.*; import java.util.Objects; import javax.xml.bind.annotation.*; import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope; import com.fasterxml.jackson.annotation.JsonCreator; import javax.validation.Valid; public class ServicesStatusListDTO { private Integer count = null; private List<ServiceCRUDStatusDTO> list = new ArrayList<ServiceCRUDStatusDTO>(); private PaginationDTO pagination = null; /** * MD5 hashes of services returned. **/ public ServicesStatusListDTO count(Integer count) { this.count = count; return this; } @ApiModelProperty(example = "1", value = "MD5 hashes of services returned. ") @JsonProperty("count") public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } /** **/ public ServicesStatusListDTO list(List<ServiceCRUDStatusDTO> list) { this.list = list; return this; } @ApiModelProperty(value = "") @Valid @JsonProperty("list") public List<ServiceCRUDStatusDTO> getList() { return list; } public void setList(List<ServiceCRUDStatusDTO> list) { this.list = list; } /** **/ public ServicesStatusListDTO pagination(PaginationDTO pagination) { this.pagination = pagination; return this; } @ApiModelProperty(value = "") @Valid @JsonProperty("pagination") public PaginationDTO getPagination() { return pagination; } public void setPagination(PaginationDTO pagination) { this.pagination = pagination; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServicesStatusListDTO servicesStatusList = (ServicesStatusListDTO) o; return Objects.equals(count, servicesStatusList.count) && Objects.equals(list, servicesStatusList.list) && Objects.equals(pagination, servicesStatusList.pagination); } @Override public int hashCode() { return Objects.hash(count, list, pagination); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ServicesStatusListDTO {\n"); sb.append(" count: ").append(toIndentedString(count)).append("\n"); sb.append(" list: ").append(toIndentedString(list)).append("\n"); sb.append(" pagination: ").append(toIndentedString(pagination)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
{'content_hash': 'bab0008d4ca2d400dcb825eac6aca2c2', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 84, 'avg_line_length': 25.90625, 'alnum_prop': 0.6911942098914354, 'repo_name': 'bhathiya/carbon-apimgt', 'id': '7e72b0b456e40cb5470df4145eccad92ad7612ba', 'size': '3316', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'components/apimgt/org.wso2.carbon.apimgt.rest.api.service.catalog/src/gen/java/org/wso2/carbon/apimgt/rest/api/service/catalog/dto/ServicesStatusListDTO.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '11203'}, {'name': 'CSS', 'bytes': '1846223'}, {'name': 'HTML', 'bytes': '1890915'}, {'name': 'Java', 'bytes': '14569991'}, {'name': 'JavaScript', 'bytes': '12435933'}, {'name': 'PLSQL', 'bytes': '175743'}, {'name': 'Shell', 'bytes': '33403'}, {'name': 'TSQL', 'bytes': '511522'}]}
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.3 * @link http://www.ag-grid.com/ * @license MIT */ var utils_1 = require('../utils'); var CssClassApplier = (function () { function CssClassApplier() { } CssClassApplier.addHeaderClassesFromCollDef = function (abstractColDef, eHeaderCell, gridOptionsWrapper) { if (abstractColDef && abstractColDef.headerClass) { var classToUse; if (typeof abstractColDef.headerClass === 'function') { var params = { // bad naming, as colDef here can be a group or a column, // however most people won't appreciate the difference, // so keeping it as colDef to avoid confusion. colDef: abstractColDef, context: gridOptionsWrapper.getContext(), api: gridOptionsWrapper.getApi() }; var headerClassFunc = abstractColDef.headerClass; classToUse = headerClassFunc(params); } else { classToUse = abstractColDef.headerClass; } if (typeof classToUse === 'string') { utils_1.Utils.addCssClass(eHeaderCell, classToUse); } else if (Array.isArray(classToUse)) { classToUse.forEach(function (cssClassItem) { utils_1.Utils.addCssClass(eHeaderCell, cssClassItem); }); } } }; return CssClassApplier; })(); exports.CssClassApplier = CssClassApplier;
{'content_hash': '68176a5f28ccc10b8766d7b0834e1523', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 110, 'avg_line_length': 40.41463414634146, 'alnum_prop': 0.5648762824381413, 'repo_name': 'hare1039/cdnjs', 'id': 'd1f56f4501387b029e2304757f549bc6c4a03a7f', 'size': '1657', 'binary': False, 'copies': '42', 'ref': 'refs/heads/master', 'path': 'ajax/libs/ag-grid/5.0.3/lib/headerRendering/cssClassApplier.js', 'mode': '33188', 'license': 'mit', 'language': []}
package org.apache.lucene.search; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.util.DocIdBitSet; import org.apache.lucene.util.FixedBitSet; import org.apache.lucene.util.Bits; public class MockFilter extends Filter { private boolean wasCalled; @Override public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) { wasCalled = true; return new FixedBitSet(context.reader().maxDoc()); } public void clear() { wasCalled = false; } public boolean wasCalled() { return wasCalled; } }
{'content_hash': '6f6e9222f8caa11b934f039cb06c8865', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 77, 'avg_line_length': 21.76923076923077, 'alnum_prop': 0.7455830388692579, 'repo_name': 'fogbeam/Heceta_solr', 'id': '56b6dcec367217e8d77211516f09a5c63647a7d2', 'size': '1367', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'lucene/core/src/test/org/apache/lucene/search/MockFilter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '13377'}, {'name': 'CSS', 'bytes': '124656'}, {'name': 'Java', 'bytes': '36810389'}, {'name': 'JavaScript', 'bytes': '1215645'}, {'name': 'Perl', 'bytes': '85397'}, {'name': 'Python', 'bytes': '181578'}, {'name': 'Shell', 'bytes': '84876'}, {'name': 'XSLT', 'bytes': '87852'}]}
title: My Drama subtitle: Game Design layout: default modal-id: -MyDrama date: 2016-6-19 thumbnail: drama3-thumbnail.png project-date: February 2015 link1: Project paper, link1-href: https://www.dropbox.com/s/ulrhekdahrpugyc/MyDramaShenBarakovaCR.pdf?dl=0 link2: Design report link2-href: https://www.dropbox.com/s/ndirga33bpdp5zp/MyDramaDesignReport.pdf?dl=0 client: Kentalis Eindhoven client-href: http://www.kentalis.nl category: Design Project description: Individual design project collaborating with <a href="http://www.kentalis.nl/" target="_blank">Royal Dutch Kentalis</a> with which lasts 6 months in 2015 at the faculty of Industrial Design in TU/Eindhoven. --- <div class="videoWrapper"> <iframe src="https://player.vimeo.com/video/131111426?title=0&byline=0&portrait=0" width="560" height="315" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> <br> #### Background Autism is a pervasive developmental disorder that is characterized by social impairments. Children with autism may have trouble understanding the non-verbal emotion cues. It ends up with difficulties in isolation from their peers and difficulty to integrate in everyday life situations. This project embeds the training process in a digital game, which persuades children to develop a skill or behavior with enjoyment. <p class="item-figure"><i><b>Impairments resulted from autism</b></i></p> <img src="img/portfolio/pic/drama-3.jpg" class="img-responsive img-centered" alt="Impairments resulted from autism"> #### Final Design My Drama is a story-based game application that helps children with autism to understand emotions in context. Elements of drama therapy and mobile game design were integrated to let players experience taking perspectives by assuming the role of the cartoon character, practicing context-dependent recognition of expressed emotions in the story and collecting story-related emotional expression photographs in a known environment. A cartoon movie The Song of the Sea has been adopted as the story background in My Drama. The script of the game is adapted from the original story to make the tasks fit into the storyline smoothly. Tasks that intend to help understanding of emotional states were divided into four increasingly complex levels and embedded in the storyline: emotion learning, facial expression recognition, emotion expression in the context and social interaction with the people around. By experiencing being in another people’s shoe, practicing communication and social skills in a safe environment, children can develop emotional skills with enjoyment. <p class="item-figure"><i><b>My Drama</b></i></p> <img src="img/portfolio/pic/drama-page.png" class="img-responsive img-centered" alt="My Drama"> #### Design Process This design was developed and polished with an iterative design process and formatting testing. <p class="item-figure"><i><b>Iterative Design Process</b></i></p> <img src="img/portfolio/pic/drama-process.png" class="img-responsive img-centered" alt="Iterative Design Process"> My Drama was piloted with one therapist and two 15-year-old autistic teenagers at <a href="http://www.kentalis.nl/" target="_blank">Royal Dutch Kentalis</a>. It was evaluated mainly from the perspective of learning effectiveness, playfulness and interaction. The outcomes of the test indicate that My Drama is a promising and engaging training tool for emotion understanding while collecting of emotional expression photographs increased the communication. Playfulness eliminated the anxiety of being trained, but retained the effect of learning and prolonged training time. <p class="item-figure"><i><b>Pilot test</b></i></p> <img src="img/portfolio/pic/drama-test.png" class="img-responsive img-centered" alt="Pilot test">
{'content_hash': '16fc9f2bcee864729e8be7243f31a81b', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 638, 'avg_line_length': 97.07692307692308, 'alnum_prop': 0.7984680401479134, 'repo_name': 'shenxiaoyu/shenxiaoyu.github.io', 'id': '33cb0e2e0964b92f070ccb77ff8497fb67cd5a5d', 'size': '3792', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2016-06-31-project-drama.markdown', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '20869'}, {'name': 'HTML', 'bytes': '1000849'}, {'name': 'JavaScript', 'bytes': '85692'}, {'name': 'PHP', 'bytes': '2184'}, {'name': 'Ruby', 'bytes': '715'}]}
namespace autofill { namespace addressinput { namespace { using ::i18n::addressinput::AddressData; using ::i18n::addressinput::AddressField; using ::i18n::addressinput::AddressProblem; using ::i18n::addressinput::IsFieldRequired; using ::i18n::addressinput::MISSING_REQUIRED_FIELD; // Returns true if the |problem| should not be reported for the |field| because // the |filter| excludes it. bool FilterExcludes(const std::multimap<AddressField, AddressProblem>* filter, AddressField field, AddressProblem problem) { return filter != NULL && !filter->empty() && std::find(filter->begin(), filter->end(), std::multimap<AddressField, AddressProblem>::value_type( field, problem)) == filter->end(); } } // namespace bool HasAllRequiredFields(const AddressData& address_to_check) { std::multimap<AddressField, AddressProblem> problems; ValidateRequiredFields(address_to_check, NULL, &problems); return problems.empty(); } void ValidateRequiredFields( const AddressData& address_to_check, const std::multimap<AddressField, AddressProblem>* filter, std::multimap<AddressField, AddressProblem>* problems) { DCHECK(problems); static const AddressField kFields[] = { ::i18n::addressinput::COUNTRY, ::i18n::addressinput::ADMIN_AREA, ::i18n::addressinput::LOCALITY, ::i18n::addressinput::DEPENDENT_LOCALITY, ::i18n::addressinput::SORTING_CODE, ::i18n::addressinput::POSTAL_CODE, ::i18n::addressinput::STREET_ADDRESS, // ORGANIZATION is never required. ::i18n::addressinput::RECIPIENT }; for (size_t i = 0; i < arraysize(kFields); ++i) { AddressField field = kFields[i]; if (address_to_check.IsFieldEmpty(field) && IsFieldRequired(field, address_to_check.region_code) && !FilterExcludes(filter, field, MISSING_REQUIRED_FIELD)) { problems->insert(std::make_pair(field, MISSING_REQUIRED_FIELD)); } } } } // namespace addressinput } // namespace autofill
{'content_hash': '08d254d3c3033109a2d21be8883f718c', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 79, 'avg_line_length': 33.54838709677419, 'alnum_prop': 0.6721153846153847, 'repo_name': 'highweb-project/highweb-webcl-html5spec', 'id': 'ca10d41ddef195349a912c493247e0756af2f76d', 'size': '2586', 'binary': False, 'copies': '21', 'ref': 'refs/heads/highweb-20160310', 'path': 'third_party/libaddressinput/chromium/addressinput_util.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("05.TheBiggestOf3Numbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05.TheBiggestOf3Numbers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b5b7d2d8-fc52-46bb-aaf4-03f0eb8c7f15")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{'content_hash': 'c9a9c38d3a76aaf2e0b7c97085eaf6a4', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 84, 'avg_line_length': 39.416666666666664, 'alnum_prop': 0.7477096546863988, 'repo_name': 'BiserSirakov/TelerikAcademyHomeworks', 'id': '271ad0bcd7e03d25b5bfaf338462813e2c1c34dd', 'size': '1422', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'C# - Part 1/Conditional-Statements/05.TheBiggestOf3Numbers/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '597348'}, {'name': 'CSS', 'bytes': '34086'}, {'name': 'HTML', 'bytes': '92428'}, {'name': 'JavaScript', 'bytes': '85148'}]}
class AddLibrarianIdToCheckedItem < ActiveRecord::Migration[4.2] def change add_reference :checked_items, :user, index: true, foreign_key: true, column_name: :librarian_id end end
{'content_hash': '0e5c26f569e15faa7f783a724e823b1e', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 99, 'avg_line_length': 37.6, 'alnum_prop': 0.7553191489361702, 'repo_name': 'next-l/enju_grid', 'id': '173014fc3702249748a11e02b37fffc1f6157296', 'size': '188', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'spec/dummy/db/migrate/20120424103932_add_librarian_id_to_checked_item.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '546'}, {'name': 'HTML', 'bytes': '9900'}, {'name': 'JavaScript', 'bytes': '831'}, {'name': 'Ruby', 'bytes': '215659'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright 2019 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. --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/share_sheet_scrollview" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout xmlns:tools="http://schemas.android.com/tools" android:id="@+id/share_sheet_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="@dimen/min_touch_target_size" android:orientation="vertical"> <RelativeLayout android:id="@+id/preview_header" android:layout_gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="20dp" android:paddingStart="16dp" android:paddingEnd="16dp" android:paddingTop="24dp"> <org.chromium.components.browser_ui.widget.RoundedCornerImageView android:id="@+id/image_preview" android:layout_height="@dimen/sharing_hub_preview_icon_size" android:layout_width="@dimen/sharing_hub_preview_icon_size" android:background="@drawable/preview_icon_border_background" app:cornerRadiusBottomStart="@dimen/sharing_hub_preview_icon_rounded_corner_radius" app:cornerRadiusBottomEnd="@dimen/sharing_hub_preview_icon_rounded_corner_radius" app:cornerRadiusTopStart="@dimen/sharing_hub_preview_icon_rounded_corner_radius" app:cornerRadiusTopEnd="@dimen/sharing_hub_preview_icon_rounded_corner_radius" tools:ignore="ContentDescription"/> <TextView android:id="@+id/title_preview" android:ellipsize="end" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toEndOf="@id/image_preview" android:layout_toStartOf="@id/link_toggle_view" android:maxLines="1" android:minHeight="18dp" android:paddingEnd="16dp" android:paddingStart="12dp" android:paddingBottom="4dp" android:textAlignment="gravity" android:textDirection="locale"/> <TextView android:id="@+id/subtitle_preview" android:ellipsize="end" android:layout_below="@id/title_preview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toEndOf="@id/image_preview" android:layout_toStartOf="@id/link_toggle_view" android:layout_centerVertical="true" android:maxLines="1" android:minHeight="18dp" android:paddingEnd="16dp" android:paddingStart="12dp" android:textAlignment="gravity" android:textDirection="locale" android:textAppearance="@style/TextAppearance.TextMedium.Primary"/> <org.chromium.ui.widget.ChromeImageView android:id="@+id/link_toggle_view" android:layout_height="@dimen/sharing_hub_preview_icon_size" android:layout_width="@dimen/sharing_hub_preview_icon_size" android:layout_alignParentEnd="true" android:visibility="gone" android:clickable="true" android:focusable="true" android:background="?attr/selectableItemBackground"/> </RelativeLayout> <View android:id="@+id/preview_divider" android:background="@macro/divider_line_bg_color" android:layout_height="1dp" android:layout_width="match_parent"/> <androidx.recyclerview.widget.RecyclerView android:id="@+id/share_sheet_other_apps" android:clipToPadding="false" android:layout_width="wrap_content" android:layout_height="113dp" android:minHeight="@dimen/min_touch_target_size" android:orientation="horizontal" android:paddingStart="8dp" android:paddingEnd="8dp" /> <View android:id="@+id/share_sheet_divider" android:background="@macro/divider_line_bg_color" android:layout_height="1dp" android:layout_width="match_parent" android:visibility="gone" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/share_sheet_chrome_apps" android:clipToPadding="false" android:layout_width="wrap_content" android:layout_height="113dp" android:minHeight="@dimen/min_touch_target_size" android:paddingStart="8dp" android:paddingEnd="8dp" android:visibility="gone" /> </LinearLayout> </ScrollView>
{'content_hash': 'c5e25f1d8d0624b496a382bcb248aa7b', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 93, 'avg_line_length': 39.75423728813559, 'alnum_prop': 0.6768279684502239, 'repo_name': 'ric2b/Vivaldi-browser', 'id': 'f27298626bc0125d4d305818993a47f6a11c3460', 'size': '4691', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'chromium/chrome/android/java/res/layout/share_sheet_content.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
""" Assesment of Generalized Estimating Equations using simulation. This script checks ordinal and nominal models for multinomial data. See the generated file "gee_categorical_simulation_check.txt" for results. """ from statsmodels.compat.python import lrange import numpy as np from scipy import stats from statsmodels.genmod.generalized_estimating_equations import GEE,\ gee_setup_ordinal, gee_setup_nominal,\ gee_ordinal_starting_values, Multinomial from statsmodels.genmod.families import Binomial from statsmodels.genmod.dependence_structures import GlobalOddsRatio from .gee_gaussian_simulation_check import GEE_simulator class ordinal_simulator(GEE_simulator): # The thresholds where the latent continuous process is cut to # obtain the categorical values. thresholds = None def true_params(self): return np.concatenate((self.thresholds, self.params)) def starting_values(self, nconstraints): beta = gee_ordinal_starting_values(self.endog, len(self.params)) if nconstraints > 0: m = self.exog_ex.shape[1] - nconstraints beta = beta[0:m] return beta def print_dparams(self, dparams_est): OUT.write("Odds ratio estimate: %8.4f\n" % dparams_est[0]) OUT.write("Odds ratio truth: %8.4f\n" % self.dparams[0]) OUT.write("\n") def simulate(self): endog, exog, group, time = [], [], [], [] for i in range(self.ngroups): gsize = np.random.randint(self.group_size_range[0], self.group_size_range[1]) group.append([i,] * gsize) time1 = np.random.normal(size=(gsize,2)) time.append(time1) exog1 = np.random.normal(size=(gsize, len(self.params))) exog.append(exog1) lp = np.dot(exog1, self.params) z = np.random.uniform(size=gsize) z = np.log(z / (1 - z)) + lp endog1 = np.array([np.sum(x > self.thresholds) for x in z]) endog.append(endog1) self.exog = np.concatenate(exog, axis=0) self.endog = np.concatenate(endog) self.time = np.concatenate(time, axis=0) self.group = np.concatenate(group) self.offset = np.zeros(len(self.endog), dtype=np.float64) class nominal_simulator(GEE_simulator): def starting_values(self, nconstraints): return None def true_params(self): return np.concatenate(self.params[:-1]) def print_dparams(self, dparams_est): OUT.write("Odds ratio estimate: %8.4f\n" % dparams_est[0]) OUT.write("Odds ratio truth: %8.4f\n" % self.dparams[0]) OUT.write("\n") def simulate(self): endog, exog, group, time = [], [], [], [] for i in range(self.ngroups): gsize = np.random.randint(self.group_size_range[0], self.group_size_range[1]) group.append([i,] * gsize) time1 = np.random.normal(size=(gsize,2)) time.append(time1) exog1 = np.random.normal(size=(gsize, len(self.params[0]))) exog.append(exog1) # Probabilities for each outcome prob = [np.exp(np.dot(exog1, p)) for p in self.params] prob = np.vstack(prob).T prob /= prob.sum(1)[:, None] m = len(self.params) endog1 = [] for k in range(gsize): pdist = stats.rv_discrete(values=(lrange(m), prob[k,:])) endog1.append(pdist.rvs()) endog.append(np.asarray(endog1)) self.exog = np.concatenate(exog, axis=0) self.endog = np.concatenate(endog).astype(np.int32) self.time = np.concatenate(time, axis=0) self.group = np.concatenate(group) self.offset = np.zeros(len(self.endog), dtype=np.float64) def gendat_ordinal(): os = ordinal_simulator() os.params = np.r_[0., 1] os.ngroups = 200 os.thresholds = [1, 0, -1] os.dparams = [1.,] os.simulate() data = np.concatenate((os.endog[:,None], os.exog, os.group[:,None]), axis=1) os.endog_ex, os.exog_ex, os.intercepts, os.nthresh = \ gee_setup_ordinal(data, 0) os.group_ex = os.exog_ex[:,-1] os.exog_ex = os.exog_ex[:,0:-1] os.exog_ex = np.concatenate((os.intercepts, os.exog_ex), axis=1) va = GlobalOddsRatio(4, "ordinal") lhs = np.array([[0., 0., 0, 1., 0.], [0., 0, 0, 0, 1]]) rhs = np.r_[0., 1] return os, va, Binomial(), (lhs, rhs) def gendat_nominal(): ns = nominal_simulator() # The last component of params must be identically zero ns.params = [np.r_[0., 1], np.r_[-1., 0], np.r_[0., 0]] ns.ngroups = 200 ns.dparams = [1., ] ns.simulate() data = np.concatenate((ns.endog[:,None], ns.exog, ns.group[:,None]), axis=1) ns.endog_ex, ns.exog_ex, ns.exog_ne, ns.nlevel = \ gee_setup_nominal(data, 0, [3,]) ns.group_ex = ns.exog_ne[:,0] va = GlobalOddsRatio(3, "nominal") lhs = np.array([[0., 1., 1, 0],]) rhs = np.r_[0.,] return ns, va, Multinomial(3), (lhs, rhs) if __name__ == '__main__': nrep = 100 OUT = open("gee_categorical_simulation_check.txt", "w") np.set_printoptions(formatter={'all': lambda x: "%8.3f" % x}, suppress=True) # Loop over data generating models gendats = [gendat_nominal, gendat_ordinal] for jg,gendat in enumerate(gendats): dparams = [] params = [] std_errors = [] pvalues = [] for j in range(nrep): da, va, mt, constraint = gendat() beta = da.starting_values(0) md = GEE(da.endog_ex, da.exog_ex, da.group_ex, None, mt, va) mdf = md.fit(start_params = beta) if mdf is None: continue scale_inv = 1 / md.estimate_scale() dparams.append(np.r_[va.dparams, scale_inv]) params.append(np.asarray(mdf.params)) std_errors.append(np.asarray(mdf.standard_errors)) da, va, mt, constraint = gendat() beta = da.starting_values(constraint[0].shape[0]) md = GEE(da.endog_ex, da.exog_ex, da.group_ex, None, mt, va, constraint=constraint) mdf = md.fit(start_params = beta) if mdf is None: continue score = md.score_test_results pvalues.append(score["p-value"]) dparams_mean = np.array(sum(dparams) / len(dparams)) OUT.write("%s data.\n" % ("Nominal", "Ordinal")[jg]) OUT.write("%d runs converged successfully.\n" % len(pvalues)) OUT.write("Checking dependence parameters:\n") da.print_dparams(dparams_mean) params = np.array(params) eparams = params.mean(0) sdparams = params.std(0) std_errors = np.array(std_errors) std_errors = std_errors.mean(0) true_params = da.true_params() OUT.write("Checking parameter values:\n") OUT.write("Observed: ") OUT.write(np.array_str(eparams) + "\n") OUT.write("Expected: ") OUT.write(np.array_str(true_params) + "\n") OUT.write("Absolute difference: ") OUT.write(np.array_str(eparams - true_params) + "\n") OUT.write("Relative difference: ") OUT.write(np.array_str((eparams - true_params) / true_params) + "\n") OUT.write("\n") OUT.write("Checking standard errors:\n") OUT.write("Observed: ") OUT.write(np.array_str(sdparams) + "\n") OUT.write("Expected: ") OUT.write(np.array_str(std_errors) + "\n") OUT.write("Absolute difference: ") OUT.write(np.array_str(sdparams - std_errors) + "\n") OUT.write("Relative difference: ") OUT.write(np.array_str((sdparams - std_errors) / std_errors) + "\n") OUT.write("\n") OUT.write("Checking constrained estimation:\n") OUT.write("Observed Expected\n") pvalues.sort() for q in np.arange(0.1, 0.91, 0.1): OUT.write("%10.3f %10.3f\n" % (pvalues[int(q*len(pvalues))], q)) OUT.write("=" * 80 + "\n\n") OUT.close()
{'content_hash': '1cc2924651dfd557e584509f141ee7c6', 'timestamp': '', 'source': 'github', 'line_count': 288, 'max_line_length': 71, 'avg_line_length': 29.770833333333332, 'alnum_prop': 0.5481688826685328, 'repo_name': 'rgommers/statsmodels', 'id': '01b36d8fff13d6de141dae00d263cfdb26112d40', 'size': '8574', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'statsmodels/genmod/tests/gee_categorical_simulation_check.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '10509'}, {'name': 'C', 'bytes': '12092'}, {'name': 'CSS', 'bytes': '30159'}, {'name': 'JavaScript', 'bytes': '16353'}, {'name': 'Python', 'bytes': '7397890'}, {'name': 'R', 'bytes': '21637'}, {'name': 'Shell', 'bytes': '5232'}, {'name': 'Stata', 'bytes': '16079'}]}
/** * \file * \brief Barrelfish collections library list data structure */ /* * Copyright (c) 2010, 2012, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, CAB F.78, Universitaetstr. 6, CH-8092 Zurich, * Attn: Systems Group. */ #include <collections/list.h> /****************************************************** * a simple linked list implementation. ******************************************************/ /* * private functions. */ static void list_push(collections_listnode *existing, collections_listnode *insert) { insert->next = existing->next; insert->prev = existing; existing->next = insert; insert->next->prev = insert; } static void *list_pop(collections_listnode *n) { void *data = n->data; n->next->prev = n->prev; n->prev->next = n->next; n->next = n->prev = NULL; return data; } /* * Insert the data at the head. */ static collections_listnode *list_create_node(collections_listnode *start, collections_listnode *where, void *data) { collections_listnode *newnode = (collections_listnode *) malloc(sizeof(collections_listnode)); newnode->data = data; list_push(where, newnode); ((collections_header_data *)(start->data))->size ++; return newnode; } static void list_destroy_node(collections_listnode *start, collections_listnode *node) { list_pop(node); free(node); ((collections_header_data*)start->data)->size--; } /* * public functions. */ /* * Creates a new linked list. */ void collections_list_create(collections_listnode **start, collections_release_data func) { collections_listnode *t; // // this is an empty list containing only the header. // t = (collections_listnode *)malloc(sizeof(collections_listnode)); t->next = t->prev = t; collections_header_data *h = (collections_header_data *) malloc(sizeof(collections_header_data)); h->size = 0; h->data_free = func; h->cur_item = NULL; t->data = (void *)h; *start = t; } /* * Releases all the nodes in the list. */ void collections_list_release(collections_listnode *start) { collections_release_data data_free = ((collections_header_data*)start->data)->data_free; collections_listnode *cur = start->next; // // travel through the rest of the // list and release all the nodes. // while (cur != start) { void *data = cur->data; if (data != NULL && data_free) { data_free(data); } list_destroy_node(start, cur); cur = start->next; } // // release the header. // free(start->data); free(start); return; } /* * Inserts an element in the head of the list. */ int32_t collections_list_insert(collections_listnode *start, void *data) { collections_listnode *ret = list_create_node(start, start, data); if (ret) { // success ... return 0; } return 1; } /* * Inserts an element at the tail of the list. */ int32_t collections_list_insert_tail(collections_listnode *start, void *data) { collections_listnode *ret = list_create_node(start, start->prev, data); if (ret) { // success ... return 0; } return 1; } /* * Returns the data that matches the user provided key. */ void *collections_list_find_if(collections_listnode *start, collections_list_predicate p, void *arg) { collections_listnode *cur = start->next; while (cur != start) { if (p(cur->data, arg)) { return cur->data; } cur = cur->next; } return NULL; } /** * Remove the first item that matches the given predicate and return it. * * \return The removed item. */ void *collections_list_remove_if(collections_listnode *start, collections_list_predicate p, void *arg) { collections_listnode *cur = start->next; while (cur != start) { if (p(cur->data, arg)) { void *data = cur->data; list_destroy_node(start, cur); return data; } cur = cur->next; } return NULL; } /** * Remove all the items that match the given predicate. * * \return The number of items removed. */ uint32_t collections_list_remove_if_all(collections_listnode *start, collections_list_predicate p, void *arg) { uint32_t items_removed = 0; collections_listnode *cur = start->next; while (cur != start) { if (p(cur->data, arg)) { list_destroy_node(start, cur); items_removed++; } cur = cur->next; } return items_removed; } void *collections_list_remove_ith_item(collections_listnode *start, uint32_t item) { void *element; uint32_t n = collections_list_size(start); if (item >= n) { element = NULL; } else if (item <= n/2) { collections_listnode *cur = start->next; while (item != 0) { cur = cur->next; item--; } element = cur->data; list_destroy_node(start, cur); } else { collections_listnode *cur = start; do { cur = cur ->prev; item++; } while (item !=n); element = cur->data; list_destroy_node(start, cur); } return element; } void *collections_list_get_ith_item(collections_listnode *start, uint32_t item) { uint32_t n = collections_list_size(start); if (item >= n) { return NULL; } else if (item <= n / 2) { collections_listnode* cur = start->next; while (item != 0) { cur = cur->next; item--; } return cur->data; } else { collections_listnode *cur = start; do { cur = cur->prev; item++; } while (item != n); return cur->data; } } /* * Return the total number of nodes in the list. */ uint32_t collections_list_size(collections_listnode *start) { return ((collections_header_data *)(start->data))->size; } #if 0 static void* list_front(collections_listnode* start) { return (start->next == start) ? NULL : start->next->data; } static void* list_back(collections_listnode* start) { return (start->prev == start) ? NULL : start->prev->data; } #endif /* * A set of routines for iteratively traversing through * the linked list. */ /* * Opens the list for traversal. */ int32_t collections_list_traverse_start(collections_listnode *start) { collections_header_data* head = (collections_header_data *) start->data; if (head->cur_item) { // if the next item is not null, a // traversal is already in progress. printf("Error: list is already opened for traversal.\n"); return -1; } head->cur_item = start; return 1; } /* * Fetches the next item in the list. * If all the items have been fetched, * returns null. */ void *collections_list_traverse_next(collections_listnode *start) { collections_header_data *head = (collections_header_data *) start->data; if (!head->cur_item) { // asking for the next item without // starting the traversal. printf("Error: list must be opened for traversal.\n"); return NULL; } head->cur_item = head->cur_item->next; if (head->cur_item == start) { return NULL; } else { return head->cur_item->data; } } /* * Finishes the list traversal. */ int32_t collections_list_traverse_end(collections_listnode *start) { collections_header_data *head = (collections_header_data *) start->data; if (!head->cur_item) { // closing without // starting the traversal. printf("Error: list must be opened before ending.\n"); return -1; } head->cur_item = NULL; return 1; } int collections_list_visit(collections_listnode *start, collections_list_visitor_func func, void *arg) { collections_listnode *cur = start->next; while (cur != start && func(cur->data, arg)) { cur = cur->next; } return cur == start; }
{'content_hash': '2954bad6e34d6ae18abda2ab2f4ba351', 'timestamp': '', 'source': 'github', 'line_count': 377, 'max_line_length': 79, 'avg_line_length': 22.954907161803714, 'alnum_prop': 0.5620522301825746, 'repo_name': 'joe9/barrelfish', 'id': '6856e4b6b96f91cf440a34855c4597b965a65e0b', 'size': '8654', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'lib/collections/list.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '1058785'}, {'name': 'Awk', 'bytes': '8919'}, {'name': 'C', 'bytes': '55789373'}, {'name': 'C++', 'bytes': '2866627'}, {'name': 'Clojure', 'bytes': '7003'}, {'name': 'Emacs Lisp', 'bytes': '1639'}, {'name': 'Gnuplot', 'bytes': '3830'}, {'name': 'Haskell', 'bytes': '167351'}, {'name': 'Objective-C', 'bytes': '122473'}, {'name': 'Perl', 'bytes': '2717951'}, {'name': 'Prolog', 'bytes': '2797394'}, {'name': 'Python', 'bytes': '5352'}, {'name': 'Scheme', 'bytes': '4249'}, {'name': 'Scilab', 'bytes': '5315'}, {'name': 'Shell', 'bytes': '300184'}, {'name': 'Tcl', 'bytes': '18591'}, {'name': 'TeX', 'bytes': '895566'}, {'name': 'eC', 'bytes': '5079'}]}
package com.vaadin.v7.client.widget.grid.events; import com.google.gwt.dom.client.BrowserEvents; import com.vaadin.v7.client.widget.grid.CellReference; import com.vaadin.v7.client.widget.grid.events.AbstractGridMouseEventHandler.GridDoubleClickHandler; import com.vaadin.v7.client.widgets.Grid; import com.vaadin.v7.client.widgets.Grid.AbstractGridMouseEvent; import com.vaadin.v7.shared.ui.grid.GridConstants.Section; /** * Represents native mouse double click event in Grid. * * @since 7.4 * @author Vaadin Ltd */ public class GridDoubleClickEvent extends AbstractGridMouseEvent<GridDoubleClickHandler> { public static final Type<GridDoubleClickHandler> TYPE = new Type<GridDoubleClickHandler>( BrowserEvents.DBLCLICK, new GridDoubleClickEvent()); /** * @since 7.7.9 */ public GridDoubleClickEvent() { } /** * @deprecated This constructor's arguments are no longer used. Use the * no-args constructor instead. */ @Deprecated public GridDoubleClickEvent(Grid<?> grid, CellReference<?> targetCell) { } @Override public Type<GridDoubleClickHandler> getAssociatedType() { return TYPE; } @Override protected String getBrowserEventType() { return BrowserEvents.DBLCLICK; } @Override protected void doDispatch(GridDoubleClickHandler handler, Section section) { if ((section == Section.BODY && handler instanceof BodyDoubleClickHandler) || (section == Section.HEADER && handler instanceof HeaderDoubleClickHandler) || (section == Section.FOOTER && handler instanceof FooterDoubleClickHandler)) { handler.onDoubleClick(this); } } }
{'content_hash': 'f6a0e90c8a62f60923f7bc92e74b4ce6', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 100, 'avg_line_length': 31.103448275862068, 'alnum_prop': 0.6751662971175166, 'repo_name': 'kironapublic/vaadin', 'id': '17231ee3a8a31637579cefe84196d60e32187236', 'size': '2399', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'compatibility-client/src/main/java/com/vaadin/v7/client/widget/grid/events/GridDoubleClickEvent.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '740138'}, {'name': 'HTML', 'bytes': '102292'}, {'name': 'Java', 'bytes': '23876126'}, {'name': 'JavaScript', 'bytes': '128039'}, {'name': 'Python', 'bytes': '34992'}, {'name': 'Shell', 'bytes': '14720'}, {'name': 'Smarty', 'bytes': '175'}]}
package com.github.witkai.watchedit; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.github.witkai.watchedit", appContext.getPackageName()); } }
{'content_hash': '98680c384e06510b1aedf509df729d91', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 81, 'avg_line_length': 29.153846153846153, 'alnum_prop': 0.7493403693931399, 'repo_name': 'witkai/watched-it', 'id': 'b23ae5c6e732075dfda13b835cf673804c37a49b', 'size': '758', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/androidTest/java/com/github/witkai/watchedit/ExampleInstrumentedTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '32352'}]}
<?xml version="1.0" encoding="utf-8"?> <nine-patch xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:src="@drawable/ms9_spot_shadow_z8_x4" tools:ignore="unused" />
{'content_hash': '48fe7dc37034e4a705722f60a9eab5ee', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 70, 'avg_line_length': 48.0, 'alnum_prop': 0.6958333333333333, 'repo_name': 'NormandyTechnologyInc/android-materialshadowninepatch', 'id': '2d77fd85e1884f6ece5d9892af8576ba34877378', 'size': '240', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'library/src/main/res/drawable-xxxhdpi/ms9_spot_shadow_z8.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '62036'}, {'name': 'Python', 'bytes': '1396'}, {'name': 'Shell', 'bytes': '14703'}]}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff" android:fitsSystemWindows="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary"> <TextView android:id="@+id/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="20sp"/> <Button android:id="@+id/back_button" android:layout_width="25dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:background="@drawable/ic_back"/> </RelativeLayout> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorPrimaryWeak"/> </LinearLayout>
{'content_hash': '1427982e17dbc97723b46a29fae44589', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 62, 'avg_line_length': 33.76923076923077, 'alnum_prop': 0.6271829916476841, 'repo_name': 'xavieryang2011/SimpleWeather', 'id': '1b69808f8040296090968f15f054533a2b8c9786', 'size': '1317', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/choose_area.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '148377'}]}
package org.elasticsearch.script.javascript; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.script.CompiledScript; import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.ScriptService; import org.elasticsearch.test.ESTestCase; import org.junit.After; import org.junit.Before; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; /** * */ public class JavaScriptScriptEngineTests extends ESTestCase { private JavaScriptScriptEngineService se; @Before public void setup() { se = new JavaScriptScriptEngineService(Settings.Builder.EMPTY_SETTINGS); } @After public void close() { se.close(); } public void testSimpleEquation() { Map<String, Object> vars = new HashMap<String, Object>(); Object o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testSimpleEquation", "js", se.compile("1 + 2")), vars).run(); assertThat(((Number) o).intValue(), equalTo(3)); } public void testMapAccess() { Map<String, Object> vars = new HashMap<String, Object>(); Map<String, Object> obj2 = MapBuilder.<String, Object>newMapBuilder().put("prop2", "value2").map(); Map<String, Object> obj1 = MapBuilder.<String, Object>newMapBuilder().put("prop1", "value1").put("obj2", obj2).put("l", Arrays.asList("2", "1")).map(); vars.put("obj1", obj1); Object o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testMapAccess", "js", se.compile("obj1")), vars).run(); assertThat(o, instanceOf(Map.class)); obj1 = (Map<String, Object>) o; assertThat((String) obj1.get("prop1"), equalTo("value1")); assertThat((String) ((Map<String, Object>) obj1.get("obj2")).get("prop2"), equalTo("value2")); o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testMapAccess", "js", se.compile("obj1.l[0]")), vars).run(); assertThat(((String) o), equalTo("2")); } public void testJavaScriptObjectToMap() { Map<String, Object> vars = new HashMap<String, Object>(); Object o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testJavaScriptObjectToMap", "js", se.compile("var obj1 = {}; obj1.prop1 = 'value1'; obj1.obj2 = {}; obj1.obj2.prop2 = 'value2'; obj1")), vars).run(); Map obj1 = (Map) o; assertThat((String) obj1.get("prop1"), equalTo("value1")); assertThat((String) ((Map<String, Object>) obj1.get("obj2")).get("prop2"), equalTo("value2")); } public void testJavaScriptObjectMapInter() { Map<String, Object> vars = new HashMap<String, Object>(); Map<String, Object> ctx = new HashMap<String, Object>(); Map<String, Object> obj1 = new HashMap<String, Object>(); obj1.put("prop1", "value1"); ctx.put("obj1", obj1); vars.put("ctx", ctx); ExecutableScript executable = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testJavaScriptObjectMapInter", "js", se.compile("ctx.obj2 = {}; ctx.obj2.prop2 = 'value2'; ctx.obj1.prop1 = 'uvalue1'")), vars); executable.run(); ctx = (Map<String, Object>) executable.unwrap(vars.get("ctx")); assertThat(ctx.containsKey("obj1"), equalTo(true)); assertThat((String) ((Map<String, Object>) ctx.get("obj1")).get("prop1"), equalTo("uvalue1")); assertThat(ctx.containsKey("obj2"), equalTo(true)); assertThat((String) ((Map<String, Object>) ctx.get("obj2")).get("prop2"), equalTo("value2")); } public void testJavaScriptInnerArrayCreation() { Map<String, Object> ctx = new HashMap<String, Object>(); Map<String, Object> doc = new HashMap<String, Object>(); ctx.put("doc", doc); Object compiled = se.compile("ctx.doc.field1 = ['value1', 'value2']"); ExecutableScript script = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testJavaScriptInnerArrayCreation", "js", compiled), new HashMap<String, Object>()); script.setNextVar("ctx", ctx); script.run(); Map<String, Object> unwrap = (Map<String, Object>) script.unwrap(ctx); assertThat(((Map) unwrap.get("doc")).get("field1"), instanceOf(List.class)); } public void testAccessListInScript() { Map<String, Object> vars = new HashMap<String, Object>(); Map<String, Object> obj2 = MapBuilder.<String, Object>newMapBuilder().put("prop2", "value2").map(); Map<String, Object> obj1 = MapBuilder.<String, Object>newMapBuilder().put("prop1", "value1").put("obj2", obj2).map(); vars.put("l", Arrays.asList("1", "2", "3", obj1)); Object o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testAccessInScript", "js", se.compile("l.length")), vars).run(); assertThat(((Number) o).intValue(), equalTo(4)); o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testAccessInScript", "js", se.compile("l[0]")), vars).run(); assertThat(((String) o), equalTo("1")); o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testAccessInScript", "js", se.compile("l[3]")), vars).run(); obj1 = (Map<String, Object>) o; assertThat((String) obj1.get("prop1"), equalTo("value1")); assertThat((String) ((Map<String, Object>) obj1.get("obj2")).get("prop2"), equalTo("value2")); o = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testAccessInScript", "js", se.compile("l[3].prop1")), vars).run(); assertThat(((String) o), equalTo("value1")); } public void testChangingVarsCrossExecution1() { Map<String, Object> vars = new HashMap<String, Object>(); Map<String, Object> ctx = new HashMap<String, Object>(); vars.put("ctx", ctx); Object compiledScript = se.compile("ctx.value"); ExecutableScript script = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testChangingVarsCrossExecution1", "js", compiledScript), vars); ctx.put("value", 1); Object o = script.run(); assertThat(((Number) o).intValue(), equalTo(1)); ctx.put("value", 2); o = script.run(); assertThat(((Number) o).intValue(), equalTo(2)); } public void testChangingVarsCrossExecution2() { Map<String, Object> vars = new HashMap<String, Object>(); Object compiledScript = se.compile("value"); ExecutableScript script = se.executable(new CompiledScript(ScriptService.ScriptType.INLINE, "testChangingVarsCrossExecution2", "js", compiledScript), vars); script.setNextVar("value", 1); Object o = script.run(); assertThat(((Number) o).intValue(), equalTo(1)); script.setNextVar("value", 2); o = script.run(); assertThat(((Number) o).intValue(), equalTo(2)); } }
{'content_hash': 'c2e033e09e101aa5b284e9de97e52cae', 'timestamp': '', 'source': 'github', 'line_count': 159, 'max_line_length': 159, 'avg_line_length': 45.58490566037736, 'alnum_prop': 0.6396247240618101, 'repo_name': 'PhaedrusTheGreek/elasticsearch', 'id': 'fe9cc324f1c994462e2a57da2def460de9331ead', 'size': '8036', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'plugins/lang-javascript/src/test/java/org/elasticsearch/script/javascript/JavaScriptScriptEngineTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '11703'}, {'name': 'Emacs Lisp', 'bytes': '3243'}, {'name': 'Groovy', 'bytes': '115065'}, {'name': 'HTML', 'bytes': '3624'}, {'name': 'Java', 'bytes': '30051378'}, {'name': 'Perl', 'bytes': '264378'}, {'name': 'Perl6', 'bytes': '103207'}, {'name': 'Python', 'bytes': '91088'}, {'name': 'Ruby', 'bytes': '17776'}, {'name': 'Shell', 'bytes': '93129'}]}
local fs = require "nixio.fs" local util = require "nixio.util" local has_fscheck = fs.access("/usr/sbin/e2fsck") local block = io.popen("block info", "r") local ln, dev, devices = nil, nil, {} repeat ln = block:read("*l") dev = ln and ln:match("^/dev/(.-):") if dev then local e, s, key, val = { } for key, val in ln:gmatch([[(%w+)="(.-)"]]) do e[key:lower()] = val end s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev))) e.dev = "/dev/%s" % dev e.size = s and math.floor(s / 2048) devices[#devices+1] = e end until not ln block:close() m = Map("fstab", translate("Mount Points - Mount Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false o = mount:taboption("general", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o:value("", translate("-- match by uuid --")) for i, d in ipairs(devices) do if d.uuid and d.size then o:value(d.uuid, "%s (%s, %d MB)" %{ d.uuid, d.dev, d.size }) elseif d.uuid then o:value(d.uuid, "%s (%s)" %{ d.uuid, d.dev }) end end o = mount:taboption("general", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) o:value("", translate("-- match by label --")) o:depends("uuid", "") for i, d in ipairs(devices) do if d.label and d.size then o:value(d.label, "%s (%s, %d MB)" %{ d.label, d.dev, d.size }) elseif d.label then o:value(d.label, "%s (%s)" %{ d.label, d.dev }) end end o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) o:value("", translate("-- match by device --")) o:depends({ uuid = "", label = "" }) for i, d in ipairs(devices) do if d.size then o:value(d.dev, "%s (%d MB)" %{ d.dev, d.size }) else o:value(d.dev) end end o = mount:taboption("general", Value, "target", translate("Mount point"), translate("Specifies the directory the device is attached to")) o:value("/", translate("Use as root filesystem (/)")) o:value("/overlay", translate("Use as external overlay (/overlay)")) o = mount:taboption("general", DummyValue, "__notice", translate("Root preparation")) o:depends("target", "/") o.rawhtml = true o.default = [[ <p>%s</p><pre>mkdir -p /tmp/introot mkdir -p /tmp/extroot mount --bind / /tmp/introot mount /dev/sda1 /tmp/extroot tar -C /tmp/introot -cvf - . | tar -C /tmp/extroot -xf - umount /tmp/introot umount /tmp/extroot</pre> ]] %{ translate("Make sure to clone the root filesystem using something like the commands below:"), } o = mount:taboption("advanced", Value, "fstype", translate("Filesystem"), translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)")) o:value("", "auto") local fs for fs in io.lines("/proc/filesystems") do fs = fs:match("%S+") if fs ~= "nodev" then o:value(fs) end end o = mount:taboption("advanced", Value, "options", translate("Mount options"), translate("See \"mount\" manpage for details")) o.placeholder = "defaults" if has_fscheck then o = mount:taboption("advanced", Flag, "enabled_fsck", translate("Run filesystem check"), translate("Run a filesystem check before mounting the device")) end return m
{'content_hash': '80d8e09f19fef63dea7a886e30e8a469', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 173, 'avg_line_length': 26.114864864864863, 'alnum_prop': 0.656921086675291, 'repo_name': 'kuoruan/luci', 'id': 'a85872afad852f7c9a46abdfca232196b06565b9', 'size': '3974', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '44'}, {'name': 'Awk', 'bytes': '526'}, {'name': 'C', 'bytes': '1161097'}, {'name': 'C#', 'bytes': '42820'}, {'name': 'C++', 'bytes': '29700'}, {'name': 'CSS', 'bytes': '73264'}, {'name': 'HTML', 'bytes': '675646'}, {'name': 'Java', 'bytes': '49574'}, {'name': 'JavaScript', 'bytes': '64583'}, {'name': 'Lex', 'bytes': '7173'}, {'name': 'Lua', 'bytes': '1637998'}, {'name': 'Makefile', 'bytes': '117882'}, {'name': 'Perl', 'bytes': '47647'}, {'name': 'Shell', 'bytes': '193962'}, {'name': 'Visual Basic', 'bytes': '33030'}, {'name': 'Yacc', 'bytes': '14699'}]}
namespace net::ndp { static constexpr int REACHABLE_TIME = 30000; // in milliseconds static constexpr int RETRANS_TIMER = 1000; // in milliseconds static constexpr double MIN_RANDOM_FACTOR = 0.5; static constexpr double MAX_RANDOM_FACTOR = 1.5; // Ndp host parameters configured for a particular inet stack struct Host_params { public: Host_params() : link_mtu_{1500}, cur_hop_limit_{255}, base_reachable_time_{REACHABLE_TIME}, retrans_time_{RETRANS_TIMER} { reachable_time_ = compute_reachable_time(); } // Compute random time in the range of min and max // random factor times base reachable time double compute_reachable_time() { auto lower = MIN_RANDOM_FACTOR * base_reachable_time_; auto upper = MAX_RANDOM_FACTOR * base_reachable_time_; return (std::fmod(rand(), (upper - lower + 1)) + lower); } uint16_t link_mtu_; uint8_t cur_hop_limit_; uint32_t base_reachable_time_; uint32_t reachable_time_; uint32_t retrans_time_; }; }
{'content_hash': '2fe635fd44d2ed717ef94ca341fa3087', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 80, 'avg_line_length': 33.24242424242424, 'alnum_prop': 0.6271649954421149, 'repo_name': 'AndreasAakesson/IncludeOS', 'id': 'fde69394eae75cc56e4d71b6547a1c6f1f463221', 'size': '1878', 'binary': False, 'copies': '4', 'ref': 'refs/heads/dev', 'path': 'api/net/ip6/ndp/host_params.hpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '74689'}, {'name': 'C', 'bytes': '42647'}, {'name': 'C++', 'bytes': '3355508'}, {'name': 'CMake', 'bytes': '121023'}, {'name': 'Dockerfile', 'bytes': '846'}, {'name': 'GDB', 'bytes': '255'}, {'name': 'JavaScript', 'bytes': '2898'}, {'name': 'Makefile', 'bytes': '1719'}, {'name': 'Python', 'bytes': '96273'}, {'name': 'Ruby', 'bytes': '586'}, {'name': 'Shell', 'bytes': '35133'}]}
require "rexml/element" require "rexml/xmldecl" require "rexml/source" require "rexml/comment" require "rexml/doctype" require "rexml/instruction" require "rexml/rexml" require "rexml/parseexception" require "rexml/output" require "rexml/parsers/baseparser" require "rexml/parsers/streamparser" require "rexml/parsers/treeparser" module REXML # Represents a full XML document, including PIs, a doctype, etc. A # Document has a single child that can be accessed by root(). # Note that if you want to have an XML declaration written for a document # you create, you must add one; REXML documents do not write a default # declaration for you. See |DECLARATION| and |write|. class Document < Element # A convenient default XML declaration. If you want an XML declaration, # the easiest way to add one is mydoc << Document::DECLARATION # +DEPRECATED+ # Use: mydoc << XMLDecl.default DECLARATION = XMLDecl.default # Constructor # @param source if supplied, must be a Document, String, or IO. # Documents have their context and Element attributes cloned. # Strings are expected to be valid XML documents. IOs are expected # to be sources of valid XML documents. # @param context if supplied, contains the context of the document; # this should be a Hash. def initialize( source = nil, context = {} ) @entity_expansion_count = 0 super() @context = context return if source.nil? if source.kind_of? Document @context = source.context super source else build( source ) end end def node_type :document end # Should be obvious def clone Document.new self end # According to the XML spec, a root node has no expanded name def expanded_name '' #d = doc_type #d ? d.name : "UNDEFINED" end alias :name :expanded_name # We override this, because XMLDecls and DocTypes must go at the start # of the document def add( child ) if child.kind_of? XMLDecl @children.unshift child child.parent = self elsif child.kind_of? DocType # Find first Element or DocType node and insert the decl right # before it. If there is no such node, just insert the child at the # end. If there is a child and it is an DocType, then replace it. insert_before_index = 0 @children.find { |x| insert_before_index += 1 x.kind_of?(Element) || x.kind_of?(DocType) } if @children[ insert_before_index ] # Not null = not end of list if @children[ insert_before_index ].kind_of DocType @children[ insert_before_index ] = child else @children[ index_before_index-1, 0 ] = child end else # Insert at end of list @children[insert_before_index] = child end child.parent = self else rv = super raise "attempted adding second root element to document" if @elements.size > 1 rv end end alias :<< :add def add_element(arg=nil, arg2=nil) rv = super raise "attempted adding second root element to document" if @elements.size > 1 rv end # @return the root Element of the document, or nil if this document # has no children. def root elements[1] #self #@children.find { |item| item.kind_of? Element } end # @return the DocType child of the document, if one exists, # and nil otherwise. def doctype @children.find { |item| item.kind_of? DocType } end # @return the XMLDecl of this document; if no XMLDecl has been # set, the default declaration is returned. def xml_decl rv = @children[0] return rv if rv.kind_of? XMLDecl rv = @children.unshift(XMLDecl.default)[0] end # @return the XMLDecl version of this document as a String. # If no XMLDecl has been set, returns the default version. def version xml_decl().version end # @return the XMLDecl encoding of this document as a String. # If no XMLDecl has been set, returns the default encoding. def encoding xml_decl().encoding end # @return the XMLDecl standalone value of this document as a String. # If no XMLDecl has been set, returns the default setting. def stand_alone? xml_decl().stand_alone? end # Write the XML tree out, optionally with indent. This writes out the # entire XML document, including XML declarations, doctype declarations, # and processing instructions (if any are given). # # A controversial point is whether Document should always write the XML # declaration (<?xml version='1.0'?>) whether or not one is given by the # user (or source document). REXML does not write one if one was not # specified, because it adds unnecessary bandwidth to applications such # as XML-RPC. # # See also the classes in the rexml/formatters package for the proper way # to change the default formatting of XML output # # _Examples_ # Document.new("<a><b/></a>").serialize # # output_string = "" # tr = Transitive.new( output_string ) # Document.new("<a><b/></a>").serialize( tr ) # # output:: # output an object which supports '<< string'; this is where the # document will be written. # indent:: # An integer. If -1, no indenting will be used; otherwise, the # indentation will be twice this number of spaces, and children will be # indented an additional amount. For a value of 3, every item will be # indented 3 more levels, or 6 more spaces (2 * 3). Defaults to -1 # trans:: # If transitive is true and indent is >= 0, then the output will be # pretty-printed in such a way that the added whitespace does not affect # the absolute *value* of the document -- that is, it leaves the value # and number of Text nodes in the document unchanged. # ie_hack:: # Internet Explorer is the worst piece of crap to have ever been # written, with the possible exception of Windows itself. Since IE is # unable to parse proper XML, we have to provide a hack to generate XML # that IE's limited abilities can handle. This hack inserts a space # before the /> on empty tags. Defaults to false def write( output=$stdout, indent=-1, trans=false, ie_hack=false ) if xml_decl.encoding != "UTF-8" && !output.kind_of?(Output) output = Output.new( output, xml_decl.encoding ) end formatter = if indent > -1 if trans REXML::Formatters::Transitive.new( indent, ie_hack ) else REXML::Formatters::Pretty.new( indent, ie_hack ) end else REXML::Formatters::Default.new( ie_hack ) end formatter.write( self, output ) end def Document::parse_stream( source, listener ) Parsers::StreamParser.new( source, listener ).parse end @@entity_expansion_limit = 10_000 # Set the entity expansion limit. By default the limit is set to 10000. def Document::entity_expansion_limit=( val ) @@entity_expansion_limit = val end # Get the entity expansion limit. By default the limit is set to 10000. def Document::entity_expansion_limit return @@entity_expansion_limit end attr_reader :entity_expansion_count def record_entity_expansion @entity_expansion_count += 1 if @entity_expansion_count > @@entity_expansion_limit raise "number of entity expansions exceeded, processing aborted." end end private def build( source ) Parsers::TreeParser.new( source, self ).parse end end end
{'content_hash': 'fd8df9f3a5e1d84e453459c173da11d8', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 82, 'avg_line_length': 33.12608695652174, 'alnum_prop': 0.6620291376821105, 'repo_name': 'ThoughtWorksStudios/mingle_hg_plugin', 'id': '3d1300a06b157043e739b47a3c4c36eb9518d040', 'size': '7619', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'tools/jruby-1.5.5/lib/ruby/1.8/rexml/document.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '74444'}, {'name': 'Ruby', 'bytes': '93988'}, {'name': 'Shell', 'bytes': '314'}]}
// Code generated by client-gen. DO NOT EDIT. package v1beta1 import ( v1beta1 "k8s.io/api/scheduling/v1beta1" "k8s.io/client-go/deprecated/scheme" rest "k8s.io/client-go/rest" ) type SchedulingV1beta1Interface interface { RESTClient() rest.Interface PriorityClassesGetter } // SchedulingV1beta1Client is used to interact with features provided by the scheduling.k8s.io group. type SchedulingV1beta1Client struct { restClient rest.Interface } func (c *SchedulingV1beta1Client) PriorityClasses() PriorityClassInterface { return newPriorityClasses(c) } // NewForConfig creates a new SchedulingV1beta1Client for the given config. func NewForConfig(c *rest.Config) (*SchedulingV1beta1Client, error) { config := *c if err := setConfigDefaults(&config); err != nil { return nil, err } client, err := rest.RESTClientFor(&config) if err != nil { return nil, err } return &SchedulingV1beta1Client{client}, nil } // NewForConfigOrDie creates a new SchedulingV1beta1Client for the given config and // panics if there is an error in the config. func NewForConfigOrDie(c *rest.Config) *SchedulingV1beta1Client { client, err := NewForConfig(c) if err != nil { panic(err) } return client } // New creates a new SchedulingV1beta1Client for the given RESTClient. func New(c rest.Interface) *SchedulingV1beta1Client { return &SchedulingV1beta1Client{c} } func setConfigDefaults(config *rest.Config) error { gv := v1beta1.SchemeGroupVersion config.GroupVersion = &gv config.APIPath = "/apis" config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() if config.UserAgent == "" { config.UserAgent = rest.DefaultKubernetesUserAgent() } return nil } // RESTClient returns a RESTClient that is used to communicate // with API server by this client implementation. func (c *SchedulingV1beta1Client) RESTClient() rest.Interface { if c == nil { return nil } return c.restClient }
{'content_hash': 'efaba9cea905e0807b55e9657d1c38a4', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 101, 'avg_line_length': 25.493333333333332, 'alnum_prop': 0.7609832635983264, 'repo_name': 'du2016/kubernetes', 'id': '81bec7c4f0b95811f7547fa1b6d48f463e7d248e', 'size': '2476', 'binary': False, 'copies': '29', 'ref': 'refs/heads/master', 'path': 'staging/src/k8s.io/client-go/deprecated/typed/scheduling/v1beta1/scheduling_client.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '978'}, {'name': 'Go', 'bytes': '40693381'}, {'name': 'HTML', 'bytes': '2587634'}, {'name': 'Makefile', 'bytes': '76926'}, {'name': 'Nginx', 'bytes': '1608'}, {'name': 'Protocol Buffer', 'bytes': '587550'}, {'name': 'Python', 'bytes': '1002836'}, {'name': 'SaltStack', 'bytes': '55138'}, {'name': 'Shell', 'bytes': '1596987'}]}
module Mutant class Subject class Method # Singleton method subjects class Singleton < self NAME_INDEX = 1 SYMBOL = '.'.freeze # Prepare subject for mutation insertion # # @return [self] def prepare scope.singleton_class.__send__(:undef_method, name) self end end # Singleton end # Method end # Subject end # Mutant
{'content_hash': '6ad0808b865c6441c192db69d9a57281', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 61, 'avg_line_length': 20.428571428571427, 'alnum_prop': 0.5524475524475524, 'repo_name': 'backus/mutant', 'id': 'b69b21fd6a0fa753d0bb46cda119f4946010b707', 'size': '429', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/mutant/subject/method/singleton.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Roff', 'bytes': '466'}, {'name': 'Ruby', 'bytes': '486518'}]}