language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SafeVarargs public static String[] addAll(final String[] a, final String... b) { if (N.isNullOrEmpty(a)) { return N.isNullOrEmpty(b) ? N.EMPTY_STRING_ARRAY : b.clone(); } final String[] newArray = new String[a.length + b.length]; copy(a, 0, newArray, 0, a.length); copy(b, 0, newArray, a.length, b.length); return newArray; }
python
def getType(self, short=False): """Return a string describing the type of the location, i.e. origin, on axis, off axis etc. :: >>> l = Location() >>> l.getType() 'origin' >>> l = Location(pop=1) >>> l.getType() 'on-axis, pop' >>> l = Location(pop=1, snap=1) >>> l.getType() 'off-axis, pop snap' >>> l = Location(pop=(1,2)) >>> l.getType() 'on-axis, pop, split' """ if self.isOrigin(): return "origin" t = [] onAxis = self.isOnAxis() if onAxis is False: if short: t.append("off-axis") else: t.append("off-axis, "+ " ".join(self.getActiveAxes())) else: if short: t.append("on-axis") else: t.append("on-axis, %s"%onAxis) if self.isAmbivalent(): t.append("split") return ', '.join(t)
java
public void marshall(CancelWorkflowExecutionFailedEventAttributes cancelWorkflowExecutionFailedEventAttributes, ProtocolMarshaller protocolMarshaller) { if (cancelWorkflowExecutionFailedEventAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cancelWorkflowExecutionFailedEventAttributes.getCause(), CAUSE_BINDING); protocolMarshaller.marshall(cancelWorkflowExecutionFailedEventAttributes.getDecisionTaskCompletedEventId(), DECISIONTASKCOMPLETEDEVENTID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
@Override public void messageEventOccurred( int event, SIMPMessage msg, TransactionCommon tran) throws SIRollbackException, SIConnectionLostException, SIIncorrectCallException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "messageEventOccurred", new Object[] { Integer.valueOf(event), msg, tran }); if (event == MessageEvents.REFERENCES_DROPPED_TO_ZERO) { _pubSubRealization.itemReferencesDroppedToZero(msg); } else if (event == MessageEvents.EXPIRY_NOTIFICATION) { eventMessageExpiryNotification(msg, tran); } else if (event == MessageEvents.COD_CALLBACK) //183715.1 { sendCODMessage(msg, tran); } else { final SIErrorException e = new SIErrorException( nls.getFormattedMessage( "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.BaseDestinationHandler", "1:3717:1.700.3.45" }, null)); FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.BaseDestinationHandler.messageEventOccurred", "1:3723:1.700.3.45", this); SibTr.exception(tc, e); SibTr.error( tc, "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.BaseDestinationHandler", "1:3733:1.700.3.45" }); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "messageEventOccurred", e); throw e; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "messageEventOccurred"); }
python
def inject(self, function=None, **names): """ Inject dependencies into `funtion`'s arguments when called. >>> @injector.inject ... def use_dependency(dependency_name): ... >>> use_dependency() The `Injector` will look for registered dependencies matching named arguments and automatically pass them to the given function when it's called. :param function: The function to inject into :type function: callable :param \**names: in the form of ``argument='name'`` to override the default behavior which matches dependency names with argument names. """ def decorator(function): @wraps(function) def wrapper(*args, **kwargs): sig = signature(function) params = sig.parameters bound = sig.bind_partial(*args, **kwargs) bound.apply_defaults() injected_kwargs = {} for key, value in params.items(): if key not in bound.arguments: name = names.get(key) if name: # Raise error when dep named explicitly # and missing injected_kwargs[key] = self.get(name) else: try: injected_kwargs[key] = self.get(key) except DependencyNotFoundError as e: warnings.warn( ambigious_not_found_msg.format(key), DependencyNotFoundWarning ) injected_kwargs.update(bound.kwargs) return function(*bound.args, **injected_kwargs) return wrapper if function: return decorator(function) return decorator
java
private Collection<DependencyInfo> mergeDependencyInfos(AgentProjectInfo projectInfo) { Map<String, DependencyInfo> infoMap = new HashedMap(); Collection<DependencyInfo> dependencyInfos = new LinkedList<>(); if (projectInfo != null) { Collection<DependencyInfo> dependencies = projectInfo.getDependencies(); for (DependencyInfo dependencyInfo : dependencies) { infoMap.putIfAbsent(dependencyInfo.getArtifactId(), dependencyInfo); } } for (Map.Entry<String, DependencyInfo> entry : infoMap.entrySet()) { if (entry.getValue() != null) { dependencyInfos.add(entry.getValue()); } } return dependencyInfos; }
python
def click(self, x, y): ''' same as adb -s ${SERIALNO} shell input tap x y FIXME(ssx): not tested on horizontal screen ''' self.shell('input', 'tap', str(x), str(y))
java
@Override public void flushBuffer() throws IOException { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Flushing buffers: " + this); } if (null != this.outWriter) { this.outWriter.flush(); } else { this.outStream.flush(); } }
java
public T join() { try { long spin = 1; while (!done) { LockSupport.parkNanos(spin++); } if (completedExceptionally) throw new SimpleReactCompletionException( exception()); return result(); } finally { markComplete(); } }
python
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
python
def _check_module_is_image_embedding(module_spec): """Raises ValueError if `module_spec` is not usable as image embedding. Args: module_spec: A `_ModuleSpec` to test. Raises: ValueError: if `module_spec` default signature is not compatible with mappingan "images" input to a Tensor(float32, shape=(_,K)). """ issues = [] # Find issues with "default" signature inputs. The common signatures for # image models prescribe a specific name; we trust it if we find it # and if we can do the necessary inference of input shapes from it. input_info_dict = module_spec.get_input_info_dict() if (list(input_info_dict.keys()) != ["images"] or input_info_dict["images"].dtype != tf.float32): issues.append("Module 'default' signature must require a single input, " "which must have type float32 and name 'images'.") else: try: image_util.get_expected_image_size(module_spec) except ValueError as e: issues.append("Module does not support hub.get_expected_image_size(); " "original error was:\n" + str(e)) # Raised again below. # Find issues with "default" signature outputs. We test that the dtype and # shape is appropriate for use in input_layer(). output_info_dict = module_spec.get_output_info_dict() if "default" not in output_info_dict: issues.append("Module 'default' signature must have a 'default' output.") else: output_type = output_info_dict["default"].dtype output_shape = output_info_dict["default"].get_shape() if not (output_type == tf.float32 and output_shape.ndims == 2 and output_shape.dims[1].value): issues.append("Module 'default' signature must have a 'default' output " "of tf.Tensor(shape=(_,K), dtype=float32).") if issues: raise ValueError("Module is not usable as image embedding: %r" % issues)
java
public static JMenuItem addMenuItem ( ActionListener l, JMenu menu, String name, Integer mnem, KeyStroke accel) { JMenuItem item = createItem(name, mnem, accel); item.addActionListener(l); menu.add(item); return item; }
java
public void move(String srcAbsPath, String destAbsPath) throws ConstraintViolationException, VersionException, AccessDeniedException, PathNotFoundException, ItemExistsException, RepositoryException { session.checkLive(); // get destination node JCRPath destNodePath = session.getLocationFactory().parseAbsPath(destAbsPath); if (destNodePath.isIndexSetExplicitly()) { throw new RepositoryException("The destination path provided must not have an index on its final element. " + destNodePath.getAsString(false)); } // get source node JCRPath srcNodePath = session.getLocationFactory().parseAbsPath(srcAbsPath); NodeImpl srcNode = (NodeImpl)session.getTransientNodesManager().getItem(srcNodePath.getInternalPath(), false); // get dst parent node NodeImpl destParentNode = (NodeImpl)session.getTransientNodesManager().getItem(destNodePath.makeParentPath().getInternalPath(), true); if (srcNode == null || destParentNode == null) { throw new PathNotFoundException("No node exists at " + srcAbsPath + " or no node exists one level above " + destAbsPath); } try { destParentNode.checkPermission(PermissionType.ADD_NODE); srcNode.checkPermission(PermissionType.REMOVE); } catch (AccessControlException e) { throw new AccessDeniedException(e.getMessage()); } destParentNode.validateChildNode(destNodePath.getName().getInternalName(), ((NodeTypeImpl)srcNode .getPrimaryNodeType()).getQName()); // Check for node with destAbsPath name in session NodeImpl destNode = (NodeImpl)session.getTransientNodesManager().getItem((NodeData)destParentNode.getData(), new QPathEntry(destNodePath.getInternalPath().getName(), 0), false, ItemType.NODE); if (destNode != null && !destNode.getDefinition().allowsSameNameSiblings()) { throw new ItemExistsException("A node with this name (" + destAbsPath + ") already exists. "); } NodeImpl srcParentNode = null; Boolean triggerEventsForDescendants; if (destParentNode.getIdentifier().equals(srcNode.getParentIdentifier())) { // move to same parent srcParentNode = destParentNode; triggerEventsForDescendants = session.triggerEventsForDescendantsOnRename; } else { srcParentNode = srcNode.parent(); triggerEventsForDescendants = session.triggerEventsForDescendantsOnMove; } // Check if versionable ancestor is not checked-in if (!srcParentNode.checkedOut()) { throw new VersionException("Source parent node " + srcNode.getPath() + " or its nearest ancestor is checked-in"); } // Check locking if (!srcNode.checkLocking()) { throw new LockException("Source parent node " + srcNode.getPath() + " is locked "); } ItemDataMoveVisitor initializer = new ItemDataMoveVisitor((NodeData)destParentNode.getData(), destNodePath.getName().getInternalName(), (NodeData)srcParentNode.getData(), nodeTypeManager, session.getTransientNodesManager(), true, triggerEventsForDescendants, session.maxDescendantNodesAllowed); srcNode.getData().accept(initializer); PlainChangesLog changes = new PlainChangesLogImpl(initializer.getAllStates(), session); // reload items pool session.getTransientNodesManager().reloadItems(initializer); session.getActionHandler().postMove(srcNode, (NodeImpl) session.getTransientNodesManager(). readItem(initializer.getItemMoveState().getData(), destParentNode.nodeData(), false, false)); // persist the changes session.getTransientNodesManager().getTransactManager().save(changes); }
java
public int[] getReferenceNumbers() { Iterator it = m_tunes.keySet().iterator(); int[] refNb = new int[m_tunes.size()]; int index = 0; while (it.hasNext()) { refNb[index] = (Integer) it.next(); index++; } return refNb; }
java
@Override public CommerceDiscount fetchByLtE_S_First(Date expirationDate, int status, OrderByComparator<CommerceDiscount> orderByComparator) { List<CommerceDiscount> list = findByLtE_S(expirationDate, status, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; }
java
public List<Entry<String, Object>> getTraceParameterSettings(int index) { List<Entry<String, Object>> result = new ArrayList<Map.Entry<String,Object>>(); List<String> dimensions = getSearchDimensions(); for (int i = 0; i < dimensions.size(); ++i) { String parameter = dimensions.get(i); Object value = m_Trace.get(index).getValue().getValues().getValue(i); Map.Entry<String, Object> current = new AbstractMap.SimpleEntry<String,Object>(parameter,value); result.add(i, current); } return result; }
java
private static List<Monomer> getMonomersRNAOnlyBase(MonomerNotationUnitRNA rna, MonomerStore monomerStore) throws HELM2HandledException { try { List<Monomer> monomers = new ArrayList<Monomer>(); for (MonomerNotationUnit unit : rna.getContents()) { String id = unit.getUnit().replace("[", ""); id = id.replace("]", ""); Monomer mon = MethodsMonomerUtils.getMonomer(rna.getType(), id, ""); if (mon.getMonomerType().equals(Monomer.BRANCH_MOMONER_TYPE)) { monomers.add(mon); } } return monomers; } catch (Exception e) { e.printStackTrace(); throw new HELM2HandledException(e.getMessage()); } }
java
public static HttpRequestBase delete(String path, Map<String, String> headers, Integer timeOutInSeconds) { HttpDelete delete = new HttpDelete(path); addHeaders(delete, headers); delete.setConfig(getConfig(timeOutInSeconds)); return delete; }
java
public ServiceFuture<List<SharedAccessSignatureAuthorizationRuleInner>> listKeysAsync(final String resourceGroupName, final String resourceName, final ListOperationCallback<SharedAccessSignatureAuthorizationRuleInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listKeysSinglePageAsync(resourceGroupName, resourceName), new Func1<String, Observable<ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>>>>() { @Override public Observable<ServiceResponse<Page<SharedAccessSignatureAuthorizationRuleInner>>> call(String nextPageLink) { return listKeysNextSinglePageAsync(nextPageLink); } }, serviceCallback); }
python
async def _nodes_found(self, responses): """ Handle the result of an iteration in _find. """ toremove = [] found_values = [] for peerid, response in responses.items(): response = RPCFindResponse(response) if not response.happened(): toremove.append(peerid) elif response.has_value(): found_values.append(response.get_value()) else: peer = self.nearest.get_node(peerid) self.nearest_without_value.push(peer) self.nearest.push(response.get_node_list()) self.nearest.remove(toremove) if found_values: return await self._handle_found_values(found_values) if self.nearest.have_contacted_all(): # not found! return None return await self.find()
java
public static final <T extends Calendar> Function<T, MutableDateTime> calendarToMutableDateTime(Chronology chronology) { return new CalendarToMutableDateTime<T>(chronology); }
java
public static XContentBuilder marshall(ApiVersionBean bean) throws StorageException { try (XContentBuilder builder = XContentFactory.jsonBuilder()) { ApiBean api = bean.getApi(); OrganizationBean org = api.getOrganization(); preMarshall(bean); builder .startObject() .field("organizationId", org.getId()) .field("organizationName", org.getName()) .field("apiId", api.getId()) .field("apiName", api.getName()) .field("apiDescription", api.getDescription()) .field("version", bean.getVersion()) .field("status", bean.getStatus()) .field("createdBy", bean.getCreatedBy()) .field("createdOn", bean.getCreatedOn().getTime()) .field("modifiedBy", bean.getModifiedBy()) .field("modifiedOn", bean.getModifiedOn().getTime()) .field("publishedOn", bean.getPublishedOn() != null ? bean.getPublishedOn().getTime() : null) .field("retiredOn", bean.getRetiredOn() != null ? bean.getRetiredOn().getTime() : null) .field("publicAPI", bean.isPublicAPI()) .field("endpoint", bean.getEndpoint()) .field("endpointType", bean.getEndpointType()) .field("endpointContentType", bean.getEndpointContentType()) .field("parsePayload", bean.isParsePayload()) .field("definitionType", bean.getDefinitionType()); Set<ApiGatewayBean> gateways = bean.getGateways(); if (gateways != null) { builder.startArray("gateways"); for (ApiGatewayBean gateway : gateways) { builder.startObject() .field("gatewayId", gateway.getGatewayId()) .endObject(); } builder.endArray(); } Set<ApiPlanBean> plans = bean.getPlans(); if (plans != null) { builder.startArray("plans"); for (ApiPlanBean plan : plans) { builder.startObject() .field("planId", plan.getPlanId()) .field("version", plan.getVersion()) .endObject(); } builder.endArray(); } Map<String, String> endpointProperties = bean.getEndpointProperties(); if (endpointProperties != null) { builder.startObject("endpointProperties"); for (Entry<String, String> property : endpointProperties.entrySet()) { builder.field(property.getKey(), property.getValue()); } builder.endObject(); } builder.endObject(); postMarshall(bean); return builder; } catch (IOException e) { throw new StorageException(e); } }
java
public void init(BaseMessageReceiver messageReceiver, BaseMessageFilter messageFilter) { if (messageFilter == null) { if (messageReceiver != null) { messageFilter = messageReceiver.createDefaultFilter(this); // Add filter to handler return; // All done. (createDefaultFilter adds the message listener to the new filter) } } if (messageFilter != null) messageFilter.addMessageListener(this); // This will also add the message filter to my list. }
python
def p_enumerated_subtype_field(self, p): 'subtype_field : ID type_ref NL' p[0] = AstSubtypeField( self.path, p.lineno(1), p.lexpos(1), p[1], p[2])
python
def set_keywords(self, keywords): """Changes the <meta> keywords tag.""" self.head.keywords.attr(content=", ".join(keywords)) return self
python
def page(self): '''Current page.''' page = self.request.GET.get(self.page_param) if not page: return 1 try: page = int(page) except ValueError: self.invalid_page() return 1 if page<1: self.invalid_page() return 1 return page
python
def create_from_fits(cls, fitsfile, norm_type='flux'): """Build a TSCube object from a fits file created by gttscube Parameters ---------- fitsfile : str Path to the tscube FITS file. norm_type : str String specifying the quantity used for the normalization """ tsmap = WcsNDMap.read(fitsfile) tab_e = Table.read(fitsfile, 'EBOUNDS') tab_s = Table.read(fitsfile, 'SCANDATA') tab_f = Table.read(fitsfile, 'FITDATA') tab_e = convert_sed_cols(tab_e) tab_s = convert_sed_cols(tab_s) tab_f = convert_sed_cols(tab_f) emin = np.array(tab_e['e_min']) emax = np.array(tab_e['e_max']) try: if str(tab_e['e_min'].unit) == 'keV': emin /= 1000. except: pass try: if str(tab_e['e_max'].unit) == 'keV': emax /= 1000. except: pass nebins = len(tab_e) npred = tab_e['ref_npred'] ndim = len(tsmap.data.shape) if ndim == 2: cube_shape = (tsmap.data.shape[0], tsmap.data.shape[1], nebins) elif ndim == 1: cube_shape = (tsmap.data.shape[0], nebins) else: raise RuntimeError("Counts map has dimension %i" % (ndim)) refSpec = ReferenceSpec.create_from_table(tab_e) nll_vals = -np.array(tab_s["dloglike_scan"]) norm_vals = np.array(tab_s["norm_scan"]) axis = MapAxis.from_edges(np.concatenate((emin, emax[-1:])), interp='log') geom_3d = tsmap.geom.to_cube([axis]) tscube = WcsNDMap(geom_3d, np.rollaxis(tab_s["ts"].reshape(cube_shape), 2, 0)) ncube = WcsNDMap(geom_3d, np.rollaxis(tab_s["norm"].reshape(cube_shape), 2, 0)) nmap = WcsNDMap(tsmap.geom, tab_f['fit_norm'].reshape(tsmap.data.shape)) ref_colname = 'ref_%s' % norm_type norm_vals *= tab_e[ref_colname][np.newaxis, :, np.newaxis] return cls(tsmap, nmap, tscube, ncube, norm_vals, nll_vals, refSpec, norm_type)
python
def _normalize_timestamps(self, timestamp, intervals, config): ''' Helper for the subclasses to generate a list of timestamps. ''' rval = [timestamp] if intervals<0: while intervals<0: rval.append( config['i_calc'].normalize(timestamp, intervals) ) intervals += 1 elif intervals>0: while intervals>0: rval.append( config['i_calc'].normalize(timestamp, intervals) ) intervals -= 1 return rval
python
def storage_get(self, key): """ Retrieve a value for the module. """ if not self._module: return self._storage_init() module_name = self._module.module_full_name return self._storage.storage_get(module_name, key)
java
private String[] split(final String sCommandLine) { return it.jnrpe.utils.StringUtils.split(sCommandLine, '!', false); }
java
private void declarePyramid( int imageWidth , int imageHeight ) { int minSize = (config.trackerFeatureRadius*2+1)*5; int scales[] = TldTracker.selectPyramidScale(imageWidth, imageHeight, minSize); currentImage = FactoryPyramid.discreteGaussian(scales,-1,1,false, ImageType.single(imageType)); currentImage.initialize(imageWidth, imageHeight); previousImage = FactoryPyramid.discreteGaussian(scales, -1, 1, false,ImageType.single(imageType)); previousImage.initialize(imageWidth, imageHeight); int numPyramidLayers = currentImage.getNumLayers(); previousDerivX = (Derivative[]) Array.newInstance(derivType, numPyramidLayers); previousDerivY = (Derivative[])Array.newInstance(derivType,numPyramidLayers); currentDerivX = (Derivative[])Array.newInstance(derivType,numPyramidLayers); currentDerivY = (Derivative[])Array.newInstance(derivType,numPyramidLayers); for( int i = 0; i < numPyramidLayers; i++ ) { int w = currentImage.getWidth(i); int h = currentImage.getHeight(i); previousDerivX[i] = GeneralizedImageOps.createSingleBand(derivType, w, h); previousDerivY[i] = GeneralizedImageOps.createSingleBand(derivType, w, h); currentDerivX[i] = GeneralizedImageOps.createSingleBand(derivType, w, h); currentDerivY[i] = GeneralizedImageOps.createSingleBand(derivType, w, h); } track = new PyramidKltFeature(numPyramidLayers,config.trackerFeatureRadius); }
java
public Waiter<DescribeInstancesRequest> instanceStopped() { return new WaiterBuilder<DescribeInstancesRequest, DescribeInstancesResult>().withSdkFunction(new DescribeInstancesFunction(client)) .withAcceptors(new InstanceStopped.IsStoppedMatcher(), new InstanceStopped.IsPendingMatcher(), new InstanceStopped.IsTerminatedMatcher()) .withDefaultPollingStrategy(new PollingStrategy(new MaxAttemptsRetryStrategy(40), new FixedDelayStrategy(15))) .withExecutorService(executorService).build(); }
python
async def check(self, message: types.Message): """ If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler :param message: :return: """ check = await super(CommandStart, self).check(message) if check and self.deep_link is not None: if not isinstance(self.deep_link, re.Pattern): return message.get_args() == self.deep_link match = self.deep_link.match(message.get_args()) if match: return {'deep_link': match} return False return check
java
public ListDocumentsRequest withFilters(DocumentKeyValuesFilter... filters) { if (this.filters == null) { setFilters(new com.amazonaws.internal.SdkInternalList<DocumentKeyValuesFilter>(filters.length)); } for (DocumentKeyValuesFilter ele : filters) { this.filters.add(ele); } return this; }
java
private static void notifyServers(Database db) { Iterator it = serverMap.keySet().iterator(); for (; it.hasNext(); ) { Server server = (Server) it.next(); HashSet databases = (HashSet) serverMap.get(server); if (databases.contains(db)) { // A VoltDB extension to disable a package dependency /* disable 2 lines ... server.notify(ServerConstants.SC_DATABASE_SHUTDOWN, db.databaseID); ... disabled 2 lines */ // End of VoltDB extension } } }
java
private static void addFormatInfoEval(byte[] eval, int size, EccLevel ecc_level, int pattern) { int format = pattern; int seq; int i; switch(ecc_level) { case L: format += 0x08; break; case Q: format += 0x18; break; case H: format += 0x10; break; } seq = QR_ANNEX_C[format]; for (i = 0; i < 6; i++) { eval[(i * size) + 8] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); } for (i = 0; i < 8; i++) { eval[(8 * size) + (size - i - 1)] = (byte) ((((seq >> i) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); } for (i = 0; i < 6; i++) { eval[(8 * size) + (5 - i)] = (byte) ((((seq >> (i + 9)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); } for (i = 0; i < 7; i++) { eval[(((size - 7) + i) * size) + 8] = (byte) ((((seq >> (i + 8)) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); } eval[(7 * size) + 8] = (byte) ((((seq >> 6) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); eval[(8 * size) + 8] = (byte) ((((seq >> 7) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); eval[(8 * size) + 7] = (byte) ((((seq >> 8) & 0x01) != 0) ? (0x01 >> pattern) : 0x00); }
java
public Object convert( String value, TypeLiteral<?> toType ) { try { return InetAddress.getByName( value ); } catch ( UnknownHostException e ) { throw new ProvisionException( "String value '" + value + "' is not a valid InetAddress", e ); } }
java
@Override public final boolean filter() { boolean returnVal = false; if (getNode() instanceof ITreeNameData) { final ITreeNameData node = (ITreeNameData)getNode(); returnVal = (node.getNameKey() == mLocalPartKey); } return returnVal; }
python
def create(self, **kwargs): """Custom create method for v12.x and above. Change of behavior in v12 where the returned selfLink is different from target resource, requires us to append URI after object is created. So any modify() calls will not lead to json kind inconsistency when changing the resource attribute. See issue #844 """ if LooseVersion(self.tmos_v) < LooseVersion('12.0.0'): return self._create(**kwargs) else: new_instance = self._create(**kwargs) tmp_name = str(new_instance.id) tmp_path = new_instance._meta_data['container']._meta_data['uri'] finalurl = tmp_path + tmp_name new_instance._meta_data['uri'] = finalurl return new_instance
java
static void writeMillis(DataOutput out, long millis) throws IOException { if (millis % (30 * 60000L) == 0) { // Try to write in 30 minute units. long units = millis / (30 * 60000L); if (((units << (64 - 6)) >> (64 - 6)) == units) { // Form 00 (6 bits effective precision) out.writeByte((int)(units & 0x3f)); return; } } if (millis % 60000L == 0) { // Try to write minutes. long minutes = millis / 60000L; if (((minutes << (64 - 30)) >> (64 - 30)) == minutes) { // Form 01 (30 bits effective precision) out.writeInt(0x40000000 | (int)(minutes & 0x3fffffff)); return; } } if (millis % 1000L == 0) { // Try to write seconds. long seconds = millis / 1000L; if (((seconds << (64 - 38)) >> (64 - 38)) == seconds) { // Form 10 (38 bits effective precision) out.writeByte(0x80 | (int)((seconds >> 32) & 0x3f)); out.writeInt((int)(seconds & 0xffffffff)); return; } } // Write milliseconds either because the additional precision is // required or the minutes didn't fit in the field. // Form 11 (64-bits effective precision, but write as if 70 bits) out.writeByte(millis < 0 ? 0xff : 0xc0); out.writeLong(millis); }
java
public synchronized String hash(final URI... properties) { final List<URI> propertiesToHash; if (properties == null || properties.length == 0) { propertiesToHash = doGetProperties(); } else { propertiesToHash = Arrays.asList(properties); } final Hasher hasher = Hashing.md5().newHasher(); for (final URI property : propertiesToHash) { final Object object = doGet(property, Object.class); @SuppressWarnings("unchecked") final Iterable<Object> nodes = object instanceof List<?> ? (List<Object>) object : ImmutableList.of(object); for (final Object node : ((Ordering<Object>) Data.getTotalComparator()) .sortedCopy(nodes)) { // TODO: this is not efficient! add Node.toBytes hasher.putString(Data.toString(node, null, true), Charsets.UTF_16LE); } hasher.putByte((byte) 0); } final StringBuilder builder = new StringBuilder(16); final byte[] bytes = hasher.hash().asBytes(); int max = 52; for (int i = 0; i < bytes.length; ++i) { final int n = (bytes[i] & 0x7F) % max; if (n < 26) { builder.append((char) (65 + n)); } else if (n < 52) { builder.append((char) (71 + n)); } else { builder.append((char) (n - 4)); } max = 62; } return builder.toString(); }
python
def checkCorpNums(self, MemberCorpNum, CorpNumList): """ ํœดํ์—…์กฐํšŒ ๋Œ€๋Ÿ‰ ํ™•์ธ, ์ตœ๋Œ€ 1000๊ฑด args MemberCorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ CorpNumList : ์กฐํšŒํ•  ์‚ฌ์—…์ž๋ฒˆํ˜ธ ๋ฐฐ์—ด return ํœดํ์—…์ •๋ณด Object as List raise PopbillException """ if CorpNumList == None or len(CorpNumList) < 1: raise PopbillException(-99999999,"์กฐ์ฃ„ํ•  ์‚ฌ์—…์ž๋ฒˆํ˜ธ ๋ชฉ๋ก์ด ์ž…๋ ฅ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.") postData = self._stringtify(CorpNumList) return self._httppost('/CloseDown',postData,MemberCorpNum)
java
public void setPrecision(TemporalPrecisionEnum thePrecision) throws IllegalArgumentException { if (thePrecision == null) { throw new NullPointerException("Precision may not be null"); } myPrecision = thePrecision; updateStringValue(); }
python
def update(self, equipments): """ Method to update equipments :param equipments: List containing equipments desired to updated :return: None """ data = {'equipments': equipments} equipments_ids = [str(env.get('id')) for env in equipments] return super(ApiV4Equipment, self).put('api/v4/equipment/%s/' % ';'.join(equipments_ids), data)
java
public ApiResponse<ApiSuccessResponse> deleteMediaUserDataWithHttpInfo(String mediatype, String id, UserData1 userData) throws ApiException { com.squareup.okhttp.Call call = deleteMediaUserDataValidateBeforeCall(mediatype, id, userData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
protected void storeDataSource(DataSource ds, XMLStreamWriter writer) throws Exception { writer.writeStartElement(XML.ELEMENT_DATASOURCE); if (ds.isJTA() != null && (ds.hasExpression(XML.ATTRIBUTE_JTA) || !Defaults.JTA.equals(ds.isJTA()))) writer.writeAttribute(XML.ATTRIBUTE_JTA, ds.getValue(XML.ATTRIBUTE_JTA, ds.isJTA().toString())); if (ds.getJndiName() != null) writer.writeAttribute(XML.ATTRIBUTE_JNDI_NAME, ds.getValue(XML.ATTRIBUTE_JNDI_NAME, ds.getJndiName())); if (ds.getId() != null) writer.writeAttribute(XML.ATTRIBUTE_ID, ds.getValue(XML.ATTRIBUTE_ID, ds.getId())); if (ds.isEnabled() != null && (ds.hasExpression(XML.ATTRIBUTE_ENABLED) || !Defaults.ENABLED.equals(ds.isEnabled()))) writer.writeAttribute(XML.ATTRIBUTE_ENABLED, ds.getValue(XML.ATTRIBUTE_ENABLED, ds.isEnabled().toString())); if (ds.isSpy() != null && (ds.hasExpression(XML.ATTRIBUTE_SPY) || !Defaults.SPY.equals(ds.isSpy()))) writer.writeAttribute(XML.ATTRIBUTE_SPY, ds.getValue(XML.ATTRIBUTE_SPY, ds.isSpy().toString())); if (ds.isUseCcm() != null && (ds.hasExpression(XML.ATTRIBUTE_USE_CCM) || !Defaults.USE_CCM.equals(ds.isUseCcm()))) writer.writeAttribute(XML.ATTRIBUTE_USE_CCM, ds.getValue(XML.ATTRIBUTE_USE_CCM, ds.isUseCcm().toString())); if (ds.isConnectable() != null && (ds.hasExpression(XML.ATTRIBUTE_CONNECTABLE) || !Defaults.CONNECTABLE.equals(ds.isConnectable()))) writer.writeAttribute(XML.ATTRIBUTE_CONNECTABLE, ds.getValue(XML.ATTRIBUTE_CONNECTABLE, ds.isConnectable().toString())); if (ds.isTracking() != null) writer.writeAttribute(XML.ATTRIBUTE_TRACKING, ds.getValue(XML.ATTRIBUTE_TRACKING, ds.isTracking().toString())); if (ds.getConnectionUrl() != null) { writer.writeStartElement(XML.ELEMENT_CONNECTION_URL); writer.writeCharacters(ds.getValue(XML.ELEMENT_CONNECTION_URL, ds.getConnectionUrl())); writer.writeEndElement(); } if (ds.getDriverClass() != null) { writer.writeStartElement(XML.ELEMENT_DRIVER_CLASS); writer.writeCharacters(ds.getValue(XML.ELEMENT_DRIVER_CLASS, ds.getDriverClass())); writer.writeEndElement(); } if (ds.getDataSourceClass() != null) { writer.writeStartElement(XML.ELEMENT_DATASOURCE_CLASS); writer.writeCharacters(ds.getValue(XML.ELEMENT_DATASOURCE_CLASS, ds.getDataSourceClass())); writer.writeEndElement(); } if (ds.getDriver() != null) { writer.writeStartElement(XML.ELEMENT_DRIVER); writer.writeCharacters(ds.getValue(XML.ELEMENT_DRIVER, ds.getDriver())); writer.writeEndElement(); } if (ds.getConnectionProperties() != null && !ds.getConnectionProperties().isEmpty()) { Iterator<Map.Entry<String, String>> it = ds.getConnectionProperties().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); writer.writeStartElement(XML.ELEMENT_CONNECTION_PROPERTY); writer.writeAttribute(XML.ATTRIBUTE_NAME, entry.getKey()); writer.writeCharacters(ds.getValue(XML.ELEMENT_CONNECTION_PROPERTY, entry.getKey(), entry.getValue())); writer.writeEndElement(); } } if (ds.getNewConnectionSql() != null) { writer.writeStartElement(XML.ELEMENT_NEW_CONNECTION_SQL); writer.writeCharacters(ds.getValue(XML.ELEMENT_NEW_CONNECTION_SQL, ds.getNewConnectionSql())); writer.writeEndElement(); } if (ds.getTransactionIsolation() != null) { writer.writeStartElement(XML.ELEMENT_TRANSACTION_ISOLATION); writer.writeCharacters(ds.getValue(XML.ELEMENT_TRANSACTION_ISOLATION, ds.getTransactionIsolation().toString())); writer.writeEndElement(); } if (ds.getUrlDelimiter() != null) { writer.writeStartElement(XML.ELEMENT_URL_DELIMITER); writer.writeCharacters(ds.getValue(XML.ELEMENT_URL_DELIMITER, ds.getUrlDelimiter())); writer.writeEndElement(); } if (ds.getUrlSelectorStrategyClassName() != null) { writer.writeStartElement(XML.ELEMENT_URL_SELECTOR_STRATEGY_CLASS_NAME); writer.writeCharacters(ds.getValue(XML.ELEMENT_URL_SELECTOR_STRATEGY_CLASS_NAME, ds.getUrlSelectorStrategyClassName())); writer.writeEndElement(); } if (ds.getPool() != null) storePool(ds.getPool(), writer); if (ds.getSecurity() != null) storeSecurity(ds.getSecurity(), writer); if (ds.getValidation() != null) storeValidation(ds.getValidation(), writer); if (ds.getTimeout() != null) storeTimeout(ds.getTimeout(), writer); if (ds.getStatement() != null) storeStatement(ds.getStatement(), writer); writer.writeEndElement(); }
java
@Override public Long get(Entity entity) { Objects.requireNonNull(entity, "entity cannot be null"); // return id() return entity.id(); }
python
def _convert_ddb_list_to_list(conversion_list): """Given a dynamodb list, it will return a python list without the dynamodb datatypes Args: conversion_list (dict): a dynamodb list which includes the datatypes Returns: list: Returns a sanitized list without the dynamodb datatypes """ ret_list = [] for v in conversion_list: for v1 in v: ret_list.append(v[v1]) return ret_list
java
public void updateBuildpackInstallations(String appName, List<String> buildpacks) { connection.execute(new BuildpackInstallationUpdate(appName, buildpacks), apiKey); }
java
@Override protected void loadBitmap(int position) { if (position < 0 || position >= items.size()) onBitmapNotAvailable(position); // If a task is already running, cancel it LoadBitmapTask task = runningTasks.get(position); if (task != null) { task.cancel(true); } task = new LoadBitmapTask(position); task.execute(items.get(position)); }
python
def check_basestring(item): """Return ``bol`` on string check item. :param item: Item to check if its a string :type item: ``str`` :returns: ``bol`` """ try: return isinstance(item, (basestring, unicode)) except NameError: return isinstance(item, str)
java
public static <C extends CameraPinhole>C matrixToPinhole(FMatrixRMaj K , int width , int height , C output ) { return (C)ImplPerspectiveOps_F32.matrixToPinhole(K, width, height, output); }
python
def boto_fix_security_token_in_profile(self, connect_args): ''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + self.boto_profile if boto.config.has_option(profile, 'aws_security_token'): connect_args['security_token'] = boto.config.get(profile, 'aws_security_token') return connect_args
python
def round_optimum(self, x): """ Rounds some value x to a feasible value in the design space. x is expected to be a vector or an array with a single row """ x = np.array(x) if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)): raise ValueError("Unexpected dimentionality of x. Got {}, expected (1, N) or (N,)".format(x.ndim)) if x.ndim == 2: x = x[0] x_rounded = [] value_index = 0 for variable in self.space_expanded: var_value = x[value_index : value_index + variable.dimensionality_in_model] var_value_rounded = variable.round(var_value) x_rounded.append(var_value_rounded) value_index += variable.dimensionality_in_model return np.atleast_2d(np.concatenate(x_rounded))
java
public DatabaseAccountInner patch(String resourceGroupName, String accountName, DatabaseAccountPatchParameters updateParameters) { return patchWithServiceResponseAsync(resourceGroupName, accountName, updateParameters).toBlocking().last().body(); }
java
@SuppressWarnings("WeakerAccess") public ApiFuture<Void> dropRowRangeAsync(String tableId, String rowKeyPrefix) { return dropRowRangeAsync(tableId, ByteString.copyFromUtf8(rowKeyPrefix)); }
python
def setup(self, path=None): """ Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed. """ # -- Finding sextractor program and its version # first look for 'sextractor', then 'sex' candidates = ['sextractor', 'sex'] if (path): candidates = [path] selected = None for candidate in candidates: try: p = subprocess.Popen(candidate, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) (_out_err, _in) = (p.stdout, p.stdin) versionline = _out_err.read() if (versionline.find("SExtractor") != -1): selected = candidate break except IOError: continue if not(selected): raise SExtractorException( """ Cannot find SExtractor program. Check your PATH, or provide the SExtractor program path in the constructor. """ ) _program = selected # print versionline _version_match = re.search("[Vv]ersion ([0-9\.])+", versionline) if not _version_match: raise SExtractorException( "Cannot determine SExtractor version." ) _version = _version_match.group()[8:] if not _version: raise SExtractorException( "Cannot determine SExtractor version." ) # print "Use " + self.program + " [" + self.version + "]" return _program, _version
python
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") """ variables_needed = [] variables_optional = [] imports = set() if params_string: # WHITELISTED_FUNCS have no params for param in params_string.split("\n"): variable = parse_param_types(param) # any variable.types has always_is_value => lenght must be 1. assert (not any([type_.always_is_value is not None for type_ in variable.types]) or len(variable.types) == 1) if variable.optional: variables_optional.append(variable) else: variables_needed.append(variable) # end if imports.update(variable.all_imports) # end for # end if imports = list(imports) imports.sort() returns = Variable(types=as_types(return_type, variable_name="return type"), description=returns) func_object = Function( imports=imports, api_name=command, link=link, description=description, returns=returns, parameters=variables_needed, keywords=variables_optional ) return func_object
java
public void printAllPuts(List<Put> p) { for (Put p1 : p) { Map<byte[], List<KeyValue>> d = p1.getFamilyMap(); for (byte[] k : d.keySet()) { System.out.println(" k " + Bytes.toString(k)); } for (List<KeyValue> lkv : d.values()) { for (KeyValue kv : lkv) { System.out.println("\n row: " + taskKeyConv.fromBytes(kv.getRow()) + "\n " + Bytes.toString(kv.getQualifier()) + ": " + Bytes.toString(kv.getValue())); } } } }
java
private void parseProviderRefs( JsonParser jp, Results results ) throws JsonParseException, IOException { ProviderRef pRef = null; String fieldName = null; while (jp.nextToken() != JsonToken.END_ARRAY ) { pRef = new ProviderRef(); pRef.setLocations( new ArrayList<Map<String,String>>() ); while (jp.nextToken() != JsonToken.END_OBJECT ) { fieldName = jp.getCurrentName(); if( "id".equals( fieldName )) { pRef.setId( jp.getText() ); } else if( "slug".equals( fieldName )) { pRef.setSlug( jp.getText() ); } else if( "name".equals( fieldName )) { pRef.setName( jp.getText() ); } else if( "snippet".equals( fieldName )) { pRef.setSnippet( jp.getText() ); } else if( "permission".equals( fieldName )) { pRef.setPermission( jp.getText() ); } else if( "score".equals( fieldName )) { // pRef.setScore( jp.getFloatValue() ); } else if( "locations".equals( fieldName )) { getLocations( jp, pRef ); } else if( "urls".equals( fieldName )) { getUrls( jp, pRef ); } } results.getProviderRefs().add( pRef ); } }
java
public List<String> commands(boolean sys, boolean app) { C.List<String> list = C.newList(); Act.Mode mode = Act.mode(); boolean all = !sys && !app; for (String s : registry.keySet()) { boolean isSysCmd = s.startsWith("act."); if (isSysCmd && !sys && !all) { continue; } if (!isSysCmd && !app && !all) { continue; } CliHandler h = registry.get(s); if (h.appliedIn(mode)) { list.add(s); } } return list.sorted(new $.Comparator<String>() { @Override public int compare(String o1, String o2) { boolean b1 = (o1.startsWith("act.")); boolean b2 = (o2.startsWith("act.")); if (b1 & !b2) { return -1; } if (!b1 & b2) { return 1; } return o1.compareTo(o2); } }); }
java
public Observable<ServiceResponse<Page<SasTokenInformationInner>>> listSasTokensNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listSasTokensNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<SasTokenInformationInner>>>>() { @Override public Observable<ServiceResponse<Page<SasTokenInformationInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<SasTokenInformationInner>> result = listSasTokensNextDelegate(response); return Observable.just(new ServiceResponse<Page<SasTokenInformationInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); }
java
protected void replayTranLog() throws Exception { if (tc.isEntryEnabled()) Tr.entry(tc, "replayTranLog"); final LogCursor recoverableUnits = _tranLog.recoverableUnits(); LogCursor recoverableUnitSections = null; int recoveredServiceItems = 0; boolean shuttingDown = false; boolean recoveredTransactions = false; try { // The recovered transctions may include completed transactions. // These will be filtered out by the TransactionImpl.reconstruct call // We will force a checkpoint after this in case we previously crashed. while (recoverableUnits.hasNext() && !shuttingDown) { final RecoverableUnit ru = (RecoverableUnit) recoverableUnits.next(); if (tc.isEventEnabled()) Tr.event(tc, "Replaying record " + ru.identity() + " from the transaction log"); recoverableUnitSections = ru.sections(); boolean tranRecord = false; while (!tranRecord && recoverableUnitSections.hasNext()) { final RecoverableUnitSection rus = (RecoverableUnitSection) recoverableUnitSections.next(); final int rusId = rus.identity(); final byte[] logData = rus.lastData(); // Only ever have 1 data item per service data sections if (tc.isEventEnabled()) Tr.event(tc, "Replaying section " + rusId, Util.toHexString(logData)); switch (rusId) { case TransactionImpl.SERVER_DATA_SECTION: if (tc.isDebugEnabled()) Tr.debug(tc, "Server name data record"); if (_tranlogServerSection != null) { if (tc.isEventEnabled()) Tr.event(tc, "Multiple log SERVER_DATA_SECTIONs found"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } if (_tranlogServiceData == null) { _tranlogServiceData = ru; } else if (_tranlogServiceData != ru) { if (tc.isEventEnabled()) Tr.event(tc, "Multiple log service data records found"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } _tranlogServerSection = rus; recoveredServiceItems++; if (logData != null && logData.length != 0) { final String recoveredServerName = new String(logData); if (_recoveredServerName == null) { _recoveredServerName = recoveredServerName; // // Check to see if the logged serverName is the same as this server // If it is different, we just output a message as we may be replaying another server log // on this server. We leave the service data set to the original server name in case we // crash before recovery has completed. We need to ensure we have a matching server name // with that from the partner log. On shutdown, if there are no transactions running, we // clear out the transaction log, but leave the partner log and may update the server name // to this server in the partner log. If there are transactions running, we never update // the server name in the log. // if (!_failureScopeController.serverName().equals(_recoveredServerName)) { Tr.warning(tc, "WTRN0020_RECOVERING_TRANSACTIONS", _recoveredServerName); } } else if (!_recoveredServerName.equals(recoveredServerName)) { Tr.error(tc, "WTRN0024_INCONSISTENT_LOGS"); throw new IOException("Inconsistent Transaction and XA Resource recovery logs"); } } break; case TransactionImpl.APPLID_DATA_SECTION: if (tc.isDebugEnabled()) Tr.debug(tc, "Applid data record"); if (_tranlogApplIdSection != null) { if (tc.isEventEnabled()) Tr.event(tc, "Multiple log APPLID_DATA_SECTIONs found"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } if (_tranlogServiceData == null) { _tranlogServiceData = ru; } else if (_tranlogServiceData != ru) { if (tc.isEventEnabled()) Tr.event(tc, "Multiple log service data records found"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } _tranlogApplIdSection = rus; recoveredServiceItems++; if (logData != null) { if (_recoveredApplId == null) { _recoveredApplId = logData; } else if (!Util.equal(_recoveredApplId, logData)) { Tr.error(tc, "WTRN0024_INCONSISTENT_LOGS"); throw new IOException("Inconsistent Transaction and XA Resource recovery logs"); } } break; case TransactionImpl.EPOCH_DATA_SECTION: if (tc.isDebugEnabled()) Tr.debug(tc, "Epoch data record"); if (_tranlogEpochSection != null) { if (tc.isEventEnabled()) Tr.event(tc, "Multiple log EPOCH_DATA_SECTIONs found"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } if (_tranlogServiceData == null) { _tranlogServiceData = ru; } else if (_tranlogServiceData != ru) { if (tc.isEventEnabled()) Tr.event(tc, "Multiple log service data records found"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } _tranlogEpochSection = rus; recoveredServiceItems++; if (logData != null && logData.length > 3) { final int recoveredEpoch = Util.getIntFromBytes(logData, 0, 4); if (tc.isDebugEnabled()) Tr.debug(tc, "Recovered epoch: " + recoveredEpoch); // If epoch isnt set or tranlog epoch is larger than partner, take the larger. // These can get out of step if one crashes during a restart. if (recoveredEpoch > _recoveredEpoch) { _recoveredEpoch = recoveredEpoch; } } break; default: tranRecord = true; break; } } recoverableUnitSections.close(); recoverableUnitSections = null; // reset in case of throw/catch if (tranRecord) { recoveredTransactions = handleTranRecord(ru, recoveredTransactions, recoverableUnits); } // Check to see if shutdown has begun before proceeding. If it has, no // further action can be taken. shuttingDown = shutdownInProgress(); } // Only bother to check that the retrieved information is valid if we are not // trying to stop processing the partner log. if (!shuttingDown) { if (recoveredTransactions) { // We have at least recovered a transaction // Check we have all of the service data if (recoveredServiceItems != TRANSACTION_SERVICE_ITEMS) { if (tc.isEventEnabled()) Tr.event(tc, "Recoverable log records found without service data records"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } } else if (recoveredServiceItems != 0 && recoveredServiceItems != TRANSACTION_SERVICE_ITEMS) { if (tc.isEventEnabled()) Tr.event(tc, "Only a subset of service data records recovered"); Tr.warning(tc, "WTRN0019_LOGFILE_CORRUPTED", _tranLog.logProperties().logName()); throw new IOException(_tranLog.logProperties().logName() + " corrupted"); } } } catch (Throwable exc) { FFDCFilter.processException(exc, "com.ibm.tx.jta.impl.RecoveryManager.replayTranLog", "512", this); if (recoverableUnitSections != null) recoverableUnitSections.close(); Tr.error(tc, "WTRN0025_TRAN_RECOVERY_FAILED", exc); SystemException se = new SystemException(exc.toString()); if (tc.isEntryEnabled()) Tr.exit(tc, "replayTranLog", se); throw se; } finally { recoverableUnits.close(); } if (tc.isEntryEnabled()) Tr.exit(tc, "replayTranLog"); }
java
public final void freeMem() { assert isPersisted() || _pojo != null || _key._kb[0]==Key.DVEC; _mem = null; }
python
def _try_parse_formula(self, compound_id, s): """Try to parse the given compound formula string. Logs a warning if the formula could not be parsed. """ s = s.strip() if s == '': return None try: # Do not return the parsed formula. For now it is better to keep # the original formula string unchanged in all cases. formula.Formula.parse(s) except formula.ParseError: logger.warning('Unable to parse compound formula {}: {}'.format( compound_id, s)) return s
python
def hdrmap(xmethod, dmethod, opt): """Return ``hdrmap`` argument for ``.IterStatsConfig`` initialiser. """ hdr = {'Itn': 'Iter', 'Fnc': 'ObjFun', 'DFid': 'DFid', u('โ„“1'): 'RegL1', 'Cnstr': 'Cnstr'} if xmethod == 'admm': hdr.update({'r_X': 'XPrRsdl', 's_X': 'XDlRsdl', u('ฯ_X'): 'XRho'}) else: if opt['CBPDN', 'BackTrack', 'Enabled']: hdr.update({'F_X': 'X_F_Btrack', 'Q_X': 'X_Q_Btrack', 'It_X': 'X_ItBt', 'L_X': 'X_L'}) else: hdr.update({'L_X': 'X_L'}) if dmethod != 'fista': hdr.update({'r_D': 'DPrRsdl', 's_D': 'DDlRsdl', u('ฯ_D'): 'DRho'}) else: if opt['CCMOD', 'BackTrack', 'Enabled']: hdr.update({'F_D': 'D_F_Btrack', 'Q_D': 'D_Q_Btrack', 'It_D': 'D_ItBt', 'L_D': 'D_L'}) else: hdr.update({'L_D': 'D_L'}) return hdr
java
@Override protected boolean validate(int classifierID, Object value, DiagnosticChain diagnostics, Map<Object, Object> context) { switch (classifierID) { case ColorPackage.DOCUMENT_ROOT: return validateDocumentRoot((DocumentRoot)value, diagnostics, context); case ColorPackage.HEX_COLOR: return validateHexColor((String)value, diagnostics, context); default: return true; } }
python
def on_consumer_cancelled(self, method_frame): """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer receiving messages. :param pika.frame.Method method_frame: The Basic.Cancel frame """ msg = 'Consumer was cancelled remotely, shutting down: {0!r}' logger.info(msg.format(method_frame)) if self._channel: self._channel.close()
python
def read_b(self, size): """ Read bytes with length `size` without incrementing the current offset :param int size: length to read in bytes :rtype: bytearray """ return self.__buff[self.__idx:self.__idx + size]
python
def _parse_version_string(version_conditions_string): ''' Returns a list of two-tuples containing (operator, version). ''' result = [] version_conditions_string = version_conditions_string.strip() if not version_conditions_string: return result for version_condition in version_conditions_string.split(','): operator_and_version = _get_comparison_spec(version_condition) result.append(operator_and_version) return result
java
@Override public void eventPostCommitAdd(Transaction transaction) throws SevereMessageStoreException { super.eventPostCommitAdd(transaction); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "eventPostCommitAdd", new Object[] { transaction }); if ((getMessageItem().getRegisterForPostEvents()) || failedInitInRestore) { stream = (MessageReferenceStream) getReferenceStream(); //we can only register the listeners if we are fully initialized if ((stream instanceof DurableSubscriptionItemStream) || (stream instanceof ProxyReferenceStream)) { stream.registerListeners(this); } failedInitInRestore = false; getMessageItem().setRegisterForPostEvents(failedInitInRestore); } if (!transaction.isAutoCommit()) { try { if (POST_COMMIT_ADD_1 != null) { POST_COMMIT_ADD_1.messageEventOccurred(MessageEvents.POST_COMMIT_ADD, this, transaction); } if (POST_COMMIT_ADD_2 != null) { POST_COMMIT_ADD_2.messageEventOccurred(MessageEvents.POST_COMMIT_ADD, this, transaction); } } catch (SIException e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.items.MessageItemReference.eventPostCommitAdd", "1:422:1.147", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "eventPostCommitAdd", e); throw new SIErrorException(e); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "eventPostCommitAdd"); }
python
def plot_triaxial(height, width, tools): '''Plot pandas dataframe containing an x, y, and z column''' import bokeh.plotting p = bokeh.plotting.figure(x_axis_type='datetime', plot_height=height, plot_width=width, title=' ', toolbar_sticky=False, tools=tools, active_drag=BoxZoomTool(), output_backend='webgl') p.yaxis.axis_label = 'Acceleration (count)' p.xaxis.axis_label = 'Time (timezone as programmed)' # Plot accelerometry data as lines and scatter (for BoxSelectTool) colors = ['#1b9e77', '#d95f02', '#7570b3'] axes = ['x', 'y', 'z'] lines = [None,]*3 scats = [None,]*3 for i, (ax, c) in enumerate(zip(axes, colors)): lines[i] = p.line(y=ax, x='dt', color=c, legend=False, source=source) scats[i] = p.scatter(y=ax, x='dt', color=c, legend=False, size=1, source=source) return p, lines, scats
python
def _process_file(self): '''Process rebase file into dict with name and cut site information.''' print 'Processing file' with open(self._rebase_file, 'r') as f: raw = f.readlines() names = [line.strip()[3:] for line in raw if line.startswith('<1>')] seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')] if len(names) != len(seqs): raise Exception('Found different number of enzyme names and ' 'sequences.') self._enzyme_dict = {} for name, seq in zip(names, seqs): if '?' in seq: # Is unknown sequence, don't keep it pass elif seq.startswith('(') and seq.endswith(')'): # Has four+ cut sites, don't keep it pass elif '^' in seq: # Has reasonable internal cut sites, keep it top_cut = seq.index('^') bottom_cut = len(seq) - top_cut - 1 site = seq.replace('^', '') self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) elif seq.endswith(')'): # Has reasonable external cut sites, keep it # (4-cutter also starts with '(') # separate site and cut locations site, cuts = seq.split('(') cuts = cuts.replace(')', '') top_cut, bottom_cut = [int(x) + len(site) for x in cuts.split('/')] self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) shutil.rmtree(self._tmpdir)
java
@Override public void writeDouble(double value) throws JMSException { try { getOutput().writeDouble(value); } catch (IOException e) { throw new FFMQException("Cannot write message body","IO_ERROR",e); } }
python
def create_flash(self): """! @brief Instantiates flash objects for memory regions. This init task iterates over flash memory regions and for each one creates the Flash instance. It uses the flash_algo and flash_class properties of the region to know how to construct the flash object. """ for region in self.memory_map.get_regions_of_type(MemoryType.FLASH): # If a path to an FLM file was set on the region, examine it first. if region.flm is not None: flmPath = self.session.find_user_file(None, [region.flm]) if flmPath is not None: logging.info("creating flash algo from: %s", flmPath) packAlgo = PackFlashAlgo(flmPath) if self.session.options.get("debug.log_flm_info", False): logging.debug("Flash algo info: %s", packAlgo.flash_info) page_size = packAlgo.page_size if page_size <= 32: page_size = min(s[1] for s in packAlgo.sector_sizes) algo = packAlgo.get_pyocd_flash_algo( page_size, self.memory_map.get_first_region_of_type(MemoryType.RAM)) # If we got a valid algo from the FLM, set it on the region. This will then # be used below. if algo is not None: region.algo = algo else: logging.warning("Failed to find FLM file: %s", region.flm) # If the constructor of the region's flash class takes the flash_algo arg, then we # need the region to have a flash algo dict to pass to it. Otherwise we assume the # algo is built-in. klass = region.flash_class argspec = getargspec(klass.__init__) if 'flash_algo' in argspec.args: if region.algo is not None: obj = klass(self, region.algo) else: logging.warning("flash region '%s' has no flash algo" % region.name) continue else: obj = klass(self) # Set the region in the flash instance. obj.region = region # Store the flash object back into the memory region. region.flash = obj
java
@Override public CreateTransitGatewayRouteTableResult createTransitGatewayRouteTable(CreateTransitGatewayRouteTableRequest request) { request = beforeClientExecution(request); return executeCreateTransitGatewayRouteTable(request); }
java
public static <E> EmptyIterator<E> get() { @SuppressWarnings("unchecked") EmptyIterator<E> iter = (EmptyIterator<E>) INSTANCE; return iter; }
java
public List<String> selectGlobalPermissionsOfUser(DbSession dbSession, int userId, String organizationUuid) { return mapper(dbSession).selectGlobalPermissionsOfUser(userId, organizationUuid); }
python
def get_currency(self, code): """ Returns an iterable of currency elements matching the code: <CtryNm>UNITED STATES MINOR OUTLYING ISLANDS (THE)</CtryNm> <CcyNm>US Dollar</CcyNm> <Ccy>USD</Ccy> <CcyNbr>840</CcyNbr> <CcyMnrUnts>2</CcyMnrUnts> NOTE: the currency is repeated for each country name """ missing = True for currency in self.currencies[0]: try: if code != currency.find('Ccy').text: continue except AttributeError: continue missing = False yield currency if missing: raise RuntimeError("%s: %s not found" % (self.name, code))
java
public static int getBreakLimit(StringBuffer interfaceConfig,StringBuffer methodConfig){ methodConfig.append(".break.limit"); interfaceConfig.append(".break.limit"); String breakLimitConf = ConfigUtils.getProperty(methodConfig.toString(), ConfigUtils.getProperty(interfaceConfig.toString(), ConfigUtils.getProperty("dubbo.reference.default.break.limit", DEFAULT_BREAK_LIMIT))); return Integer.parseInt(breakLimitConf); }
java
private static double[] toArray(DoubleVector v, int length) { double[] arr = new double[length]; for (int i = 0; i < arr.length; ++i) { arr[i] = v.get(i); } return arr; }
python
def listen_loop(self): """Starts the listen loop and executes the receieve_datagram method whenever a packet is receieved. Args: None Returns: None """ while self.listening: try: data, address = self.sock.recvfrom(self.bufsize) self.receive_datagram(data, address) if self.stats_enabled: self.stats['bytes_recieved'] += len(data) except socket.error as error: if error.errno == errno.WSAECONNRESET: logger.info("connection reset") else: raise logger.info("Shutting down the listener...")
java
@Override public CreateStreamingDistributionResult createStreamingDistribution(CreateStreamingDistributionRequest request) { request = beforeClientExecution(request); return executeCreateStreamingDistribution(request); }
python
def iter_child_nodes(node, omit=None, _fields_order=_FieldsOrder()): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. :param node: AST node to be iterated upon :param omit: String or tuple of strings denoting the attributes of the node to be omitted from further parsing :param _fields_order: Order of AST node fields """ for name in _fields_order[node.__class__]: if omit and name in omit: continue field = getattr(node, name, None) if isinstance(field, ast.AST): yield field elif isinstance(field, list): for item in field: yield item
java
static byte[] encode(int count) { // ่ฎก็ฎ—้œ€่ฆๅกซๅ……็š„ไฝๆ•ฐ int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); if (amountToPad == 0) { amountToPad = BLOCK_SIZE; } // ่Žทๅพ—่กฅไฝๆ‰€็”จ็š„ๅญ—็ฌฆ char padChr = chr(amountToPad); StringBuilder tmp = new StringBuilder(); for (int index = 0; index < amountToPad; index++) { tmp.append(padChr); } return tmp.toString().getBytes(CHARSET); }
python
def fetch_next_page(self): """ Manually, synchronously fetch the next page. Supplied for manually retrieving pages and inspecting :meth:`~.current_page`. It is not necessary to call this when iterating through results; paging happens implicitly in iteration. """ if self.response_future.has_more_pages: self.response_future.start_fetching_next_page() result = self.response_future.result() self._current_rows = result._current_rows # ResultSet has already _set_current_rows to the appropriate form else: self._current_rows = []
java
public Element nextElementSibling() { if (parentNode == null) return null; List<Element> siblings = parent().childElementsList(); Integer index = indexInList(this, siblings); Validate.notNull(index); if (siblings.size() > index+1) return siblings.get(index+1); else return null; }
java
public LocalXAResource createConnectableLocalXAResource(ConnectionManager cm, String productName, String productVersion, String jndiName, ConnectableResource cr, XAResourceStatistics xastat) { return new LocalConnectableXAResourceImpl(productName, productVersion, jndiName, cr); }
python
def _ScanFileSystem(self, scan_node, base_path_specs): """Scans a file system scan node for file systems. Args: scan_node (SourceScanNode): file system scan node. base_path_specs (list[PathSpec]): file system base path specifications. Raises: SourceScannerError: if the scan node is invalid. """ if not scan_node or not scan_node.path_spec: raise errors.SourceScannerError( 'Invalid or missing file system scan node.') base_path_specs.append(scan_node.path_spec)
python
def workspace_backup_list(ctx): """ List backups """ backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)) for b in backup_manager.list(): print(b)
python
def match(self, filename): """Searches for a pattern that matches the given filename. :return A matching pattern or None if there is no matching pattern. """ try: for regex, patterns in self._regex_patterns: match = regex.match(filename) debug_template = "%s against %s: %%s" % (filename, regex._real_regex.pattern) if match: if self.debug: logger.info(debug_template % "hit") return patterns[match.lastindex -1] if self.debug: logger.info(debug_template % "miss") except Exception as e: # We can't show the default e.msg to the user as thats for # the combined pattern we sent to regex. Instead we indicate to # the user that an ignore file needs fixing. logger.error('Invalid pattern found in regex: %s.', e.msg) e.msg = "File ~/.bazaar/ignore or .bzrignore contains error(s)." bad_patterns = '' for _, patterns in self._regex_patterns: for p in patterns: if not Globster.is_pattern_valid(p): bad_patterns += ('\n %s' % p) e.msg += bad_patterns raise e return None
python
def setDebugActions( self, startAction, successAction, exceptionAction ): """ Enable display of debugging messages while doing pattern matching. """ self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self
java
public Config addEventJournalConfig(EventJournalConfig eventJournalConfig) { final String mapName = eventJournalConfig.getMapName(); final String cacheName = eventJournalConfig.getCacheName(); if (StringUtil.isNullOrEmpty(mapName) && StringUtil.isNullOrEmpty(cacheName)) { throw new IllegalArgumentException("Event journal config should have either map name or cache name non-empty"); } if (!StringUtil.isNullOrEmpty(mapName)) { mapEventJournalConfigs.put(mapName, eventJournalConfig); } if (!StringUtil.isNullOrEmpty(cacheName)) { cacheEventJournalConfigs.put(cacheName, eventJournalConfig); } return this; }
java
@Override public MultiDataSet next() { if (throwable != null) throw throwable; if (hasDepleted.get()) return null; MultiDataSet temp = nextElement; nextElement = null; return temp; }
python
def _compute_acq_withGradients(self, x): """ Computes the GP-Lower Confidence Bound and its derivative """ m, s, dmdx, dsdx = self.model.predict_withGradients(x) f_acqu = -m + self.exploration_weight * s df_acqu = -dmdx + self.exploration_weight * dsdx return f_acqu, df_acqu
python
def _is_simple_type(value): ''' Returns True, if the given parameter value is an instance of either int, str, float or bool. ''' return isinstance(value, six.string_types) or isinstance(value, int) or isinstance(value, float) or isinstance(value, bool)
python
def url(self, name): """ Since we assume all public storage with no authorization keys, we can just simply dump out a URL rather than having to query S3 for new keys. """ name = urllib.quote_plus(self._clean_name(name), safe='/') if self.bucket_cname: return "http://%s/%s" % (self.bucket_cname, name) elif self.host: return "http://%s/%s/%s" % (self.host, self.bucket_name, name) # No host ? Then it's the default region return "http://s3.amazonaws.com/%s/%s" % (self.bucket_name, name)
python
def sensor(sensor_type, cfg): """ Creates a camera sensor of the specified type. Parameters ---------- sensor_type : :obj:`str` the type of the sensor (real or virtual) cfg : :obj:`YamlConfig` dictionary of parameters for sensor initialization """ sensor_type = sensor_type.lower() if sensor_type == 'kinect2': s = Kinect2Sensor(packet_pipeline_mode=cfg['pipeline_mode'], device_num=cfg['device_num'], frame=cfg['frame']) elif sensor_type == 'bridged_kinect2': s = KinectSensorBridged(quality=cfg['quality'], frame=cfg['frame']) elif sensor_type == 'primesense': flip_images = True if 'flip_images' in cfg.keys(): flip_images = cfg['flip_images'] s = PrimesenseSensor(auto_white_balance=cfg['auto_white_balance'], flip_images=flip_images, frame=cfg['frame']) elif sensor_type == 'virtual': s = VirtualSensor(cfg['image_dir'], frame=cfg['frame']) elif sensor_type == 'tensor_dataset': s = TensorDatasetVirtualSensor(cfg['dataset_dir'], frame=cfg['frame']) elif sensor_type == 'primesense_ros': s = PrimesenseSensor_ROS(frame=cfg['frame']) elif sensor_type == 'ensenso': s = EnsensoSensor(frame=cfg['frame']) elif sensor_type == 'phoxi': s = PhoXiSensor(frame=cfg['frame'], device_name=cfg['device_name'], size=cfg['size']) elif sensor_type == 'webcam': s = WebcamSensor(frame=cfg['frame'], device_id=cfg['device_id']) elif sensor_type == 'colorized_phoxi': s = ColorizedPhoXiSensor(frame=cfg['frame'], phoxi_config=cfg['phoxi_config'], webcam_config=cfg['webcam_config'], calib_dir=cfg['calib_dir']) elif sensor_type == 'realsense': s = RealSenseSensor( cam_id=cfg['cam_id'], filter_depth=cfg['filter_depth'], frame=cfg['frame'], ) else: raise ValueError('RGBD sensor type %s not supported' %(sensor_type)) return s
java
protected int writeTo(SparseBufferOperator<B> op, Splitter<SparseBufferOperator<B>> splitter, int start, int length) throws IOException { return splitter.split(op, start, length); }
python
def get_bounding_box( self, resource, resolution, _id, bb_type, url_prefix, auth, session, send_opts): """Get bounding box containing object specified by id. Currently only supports 'loose' bounding boxes. The bounding box returned is cuboid aligned. Args: resource (intern.resource.Resource): Resource compatible with annotation operations. resolution (int): 0 indicates native resolution. _id (int): Id of object of interest. bb_type (string): Defaults to 'loose'. url_prefix (string): Protocol + host such as https://api.theboss.io auth (string): Token to send in the request header. session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). Returns: (dict): {'x_range': [0, 10], 'y_range': [0, 10], 'z_range': [0, 10], 't_range': [0, 10]} Raises: requests.HTTPError TypeError: if resource is not an annotation channel. """ if not isinstance(resource, ChannelResource): raise TypeError('resource must be ChannelResource') if resource.type != 'annotation': raise TypeError('Channel is not an annotation channel') req = self.get_bounding_box_request( resource, 'GET', 'application/json', url_prefix, auth, resolution, _id, bb_type) prep = session.prepare_request(req) resp = session.send(prep, **send_opts) if resp.status_code == 200: json_data = resp.json() return json_data msg = ('Get bounding box failed on {}, got HTTP response: ({}) - {}'.format( resource.name, resp.status_code, resp.text)) raise HTTPError(msg, request=req, response=resp)