language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def check_log(logfile, exited='Exited with exit code', successful='Successfully completed', exists=True): """ Often logfile doesn't exist because the job hasn't begun to run. It is unclear what you want to do in that case... Parameters ---------- logfile : str String with path...
java
private static void createDirectory(Path path) throws IOException { try { Files.createDirectory(path); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(path)) { throw e; } } }
java
public void setKey(org.openprovenance.prov.model.Key value) { this.key = (org.openprovenance.prov.sql.Key)value; }
java
public void isField(String template, Properties attributes) throws XDocletException { if (getCurrentField() != null) { generate(template); } }
python
def declare_const(self, id_, lineno, type_, default_value): """ Similar to the above. But declares a Constant. """ if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False): entry = self.get_entry(id_) if entry.scope == SCOPE.parameter: ...
python
def modifiedBlankLines(logical_line, blank_lines, indent_level, line_number, blank_before, previous_logical, previous_indent_level): """ This function is copied from a modified pycodestyle checker for Twisted. See https://github.com/cyli/TwistySublime/blob/master/twisted_pycodestyle.p...
python
def _parse_message(self, data): """Interpret each message datagram from device and do the needful. This function receives datagrams from _assemble_buffer and inerprets what they mean. It's responsible for maintaining the internal state table for each device attribute and also for firin...
java
public ExecutionInput transform(Consumer<Builder> builderConsumer) { Builder builder = new Builder() .query(this.query) .operationName(this.operationName) .context(this.context) .root(this.root) .dataLoaderRegistry(this.dataLoaderRe...
java
public Observable<VirtualNetworkLinkInner> updateAsync(String resourceGroupName, String privateZoneName, String virtualNetworkLinkName, VirtualNetworkLinkInner parameters, String ifMatch) { return updateWithServiceResponseAsync(resourceGroupName, privateZoneName, virtualNetworkLinkName, parameters, ifMatch).map...
python
def _update_workflow_stages(stage_data: dict, workflow_stage: WorkflowStage, docker: DockerSwarmClient): """Check and update the status of a workflow stage. This function checks and updates the status of a workflow stage specified by the parameters in the specified stage_data di...
java
public boolean isConflict() { if (getCause() != null && getCause() instanceof DatastoreException) { DatastoreException datastoreException = (DatastoreException) getCause(); return datastoreException.getCode() == 10; } else { return false; } }
java
public void setCommerceCurrencyLocalService( com.liferay.commerce.currency.service.CommerceCurrencyLocalService commerceCurrencyLocalService) { this.commerceCurrencyLocalService = commerceCurrencyLocalService; }
java
public void marshall(DeleteCACertificateRequest deleteCACertificateRequest, ProtocolMarshaller protocolMarshaller) { if (deleteCACertificateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(d...
python
def register(self): """ Registers a new device with the name entity_id. This device has permissions for services like subscribe, publish and access historical data. """ register_url = self.base_url + "api/0.1.0/register" register_headers = { "apikey": str(self.owner_...
python
def delete(self): """Delete resource from the API server """ res = self.session.delete(self.href) self.emit('deleted', self) return res
python
def kick_user(self, user_id, reason=""): """Kick a user from this room. Args: user_id (str): The matrix user id of a user. reason (str): A reason for kicking the user. Returns: boolean: Whether user was kicked. """ try: self.cli...
java
@Override public void parse (final int nYear, final HolidayMap aHolidayMap, final Holidays aConfig) { for (final ChristianHoliday aChristianHoliday : aConfig.getChristianHoliday ()) { if (!isValid (aChristianHoliday, nYear)) continue; ChronoLocalDate aEasterSunday; if (aChristianH...
python
def maxCtxSubtable(maxCtx, tag, lookupType, st): """Calculate usMaxContext based on a single lookup table (and an existing max value). """ # single positioning, single / multiple substitution if (tag == 'GPOS' and lookupType == 1) or ( tag == 'GSUB' and lookupType in (1, 2, 3)): max...
python
def make_jagged_equity_info(num_assets, start_date, first_end, frequency, periods_between_ends, auto_close_delta): """ Create a DataFrame representing assets that all begin...
java
public void resetStream() throws IllegalStateException { if ((_deChunker!=null && _deChunker._chunkSize>0) || _realIn.getByteLimit()>0) throw new IllegalStateException("Unread input"); if(log.isTraceEnabled())log.trace("resetStream()"); in=_realIn; if ...
java
public boolean enlistResource(XAResource xaRes, int recoveryIndex) throws RollbackException, IllegalStateException, SystemException { return enlistResource(xaRes, recoveryIndex, XAResource.TMNOFLAGS); }
python
def _check_for_duplicate_sequence_names(self, fasta_file_path): """Test if the given fasta file contains sequences with duplicate sequence names. Parameters ---------- fasta_file_path: string path to file that is to be checked Returns ------- ...
java
protected Context createContext() throws DurableDataLogException { val serviceConfig = getServiceConfig(); val bkConfig = getCommandArgs().getState().getConfigBuilder() .include(BookKeeperConfig.builder().with(BookKeeperConfig.ZK_ADDRESS, serviceConfig.getZkURL()))...
java
private void checkAddresses(Message m, Address[] addresses) throws MessagingException, SendFailedException { if ( isNullOrEmpty((Object[]) addresses) && isNullOrEmpty((Object[]) m.getRecipients(Message.RecipientType.TO)) && isNullOrEmpty((Object[]) m.getRecipients(Me...
java
protected boolean dispatch(final Collection<? extends ItemHolder> all, int size) { ItemHolder[] array = all.toArray(new ItemHolder[all.size()]); // protected against handlers unregistering during this loop for (ItemHolder holder : array) { EventsHandler handler = holder.handler()...
python
def _write_dihedral_information(gsd_file, structure): """Write the dihedrals in the system. Parameters ---------- gsd_file : The file object of the GSD file being written structure : parmed.Structure Parmed structure object holding system information """ gsd_file.dihedrals...
python
def accel_decrease_height(self, *args): """Callback to decrease height. """ height = self.settings.general.get_int('window-height') self.settings.general.set_int('window-height', max(height - 2, 0)) return True
java
@Override protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleString) throws IOException { Charset charset = status.getJawrConfig().getResourceCharset(); // The original JSMin doesn't handle Dos (CRLF) line endings // So here we replace the CRLF with LF only String ...
python
def parse(self, line): """Parse a line of the Nginx error log""" csv_list = line.split(",") date_time_message = csv_list.pop(0).split(" ", 2) otherinfo = dict() for item in csv_list: key_value_pair = item.split(":", 1) key = key_value_pair[0].strip() ...
python
def __visit_target(self, node): """ Call this method to visit assignment targets and to add local variables to the current stack frame. Used in #visit_Assign() and #__visit_comprehension(). """ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store): self.__add_variable(node.id)...
python
def _parse_cond(self, cond): """Replace the format strings in cond with ``self.D[i]`` so it can be used in eval calls. Use ``CHANNEL_RX`` as pattern. Return the parsed string. This method should be exposed so that one can experiment with conditions and see that they are properly...
java
private void updateCache(int index, QueryParameters params) { if (generatedCacheMap.containsKey(index) == true) { this.generatedCacheMap.put(index, params); } else { this.resultSetCacheMap.put(index, params); } }
java
public RequestTable<T> removeMany(LongStream seqnos, Consumer<T> consumer) { if(seqnos == null) return this; AtomicBoolean advance=new AtomicBoolean(false); seqnos.forEach(seqno -> { T element=null; lock.lock(); try { if(seqno < low || seqno >...
java
@Override public DEBBuilder addRequire(String name, String version, Condition... dependency) { control.addDepends(release, version, dependency); return this; }
python
def walk_json(d, func): """ Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result """ if isinstance(d, Mapping): return OrderedDict((k, walk_json(v, func)) for k, v in d.items()) elif isinstance(d, list): return [walk_json(v, func) for...
python
def cutoff(s, length=120): """Cuts a given string if it is longer than a given length.""" if length < 5: raise ValueError('length must be >= 5') if len(s) <= length: return s else: i = (length - 2) / 2 j = (length - 3) / 2 return s[:i] + '...' + s[-j:]
java
private M invalidMessage(Exception cause) { state = State.BAD_MESSAGE; M message = buildInvalidMessage(); message.setDecoderResult(DecoderResult.failure(cause)); return message; }
java
private int selectConstructorAndTransformArguments1(Object[] arguments) { if (arguments == null) arguments = EMPTY_ARGUMENTS; Class[] argClasses = MetaClassHelper.convertToTypeArray(arguments); MetaClassHelper.unwrap(arguments); CachedConstructor constructor = (CachedConstructor) chooseM...
python
def samplerate(self): """Returns the generation rate for this stimulus :returns: int -- the output samplerate (Hz) """ rates = [] for track in self._segments: for component in track: # special case, where component is a wav file: # it ...
java
public static String getElementText(Element elem) { StringBuilder result = new StringBuilder(); NodeList nodeList = elem.getChildNodes(); for (int index = 0; index < nodeList.getLength(); index++) { Node childNode = nodeList.item(index); if (childNode != null && (chi...
java
public static Object getProperty(Object target, String property) { try { return InvokerHelper.getProperty(target, property); } catch (InvokerInvocationException e) { ExceptionUtil.sneakyThrow(e.getCause()); return null; // never reached } }
python
def documentation(default=None, api_version=None, api=None, **kwargs): """returns documentation for the current api""" api_version = default or api_version if api: return api.http.documentation(base_url="", api_version=api_version)
java
public void patchJobSchedule(String jobScheduleId, Schedule schedule, JobSpecification jobSpecification, List<MetadataItem> metadata) throws BatchErrorException, IOException { patchJobSchedule(jobScheduleId, schedule, jobSpecification, metadata, null); }
python
def drop_index(self, raw): """ Executes a drop index command. { "op" : "c", "ns" : "testdb.$cmd", "o" : { "dropIndexes" : "testcoll", "index" : "nuie_1" } } """ dbname = raw['ns'].split('.', 1)[0] collname = raw['o']['dropIndexes']...
python
def timing(module, name): """ Context manager to time a section of code:: with timing(__name__, 'my_timer'): do_some_operation() """ start_time_s = time.time() try: yield finally: end_time_s = time.time() delta_s = end_time_s - start_time_s de...
python
def fastrcnn_Xconv1fc_head(feature, num_convs, norm=None): """ Args: feature (NCHW): num_classes(int): num_category + 1 num_convs (int): number of conv layers norm (str or None): either None or 'GN' Returns: 2D head feature """ assert norm in [None, 'GN'], no...
python
def payoff_vector(self, opponents_actions): """ Return an array of payoff values, one for each own action, given a profile of the opponents' actions. Parameters ---------- opponents_actions : see `best_response`. Returns ------- payoff_vector : n...
java
public com.squareup.okhttp.Call postUiOpenwindowContractAsync(Integer contractId, String datasource, String token, final ApiCallback<Void> callback) throws ApiException { com.squareup.okhttp.Call call = postUiOpenwindowContractValidateBeforeCall(contractId, datasource, token, callba...
java
public void removeExtension(Extension extension) { extensionList.remove(extension); extensionsMap.remove(extension.getClass()); ExtensionHook hook = extensionHooks.remove(extension); if (hook == null) { logger.error("ExtensionHook not found for: " + extension.getClass(...
java
public void run() { int iSFieldCount = this.getSFieldCount(); // Keep out of loop because of chance of free() during run() for (int iFieldSeq = 0; iFieldSeq < iSFieldCount; iFieldSeq++) { // See if any of my children want to handle this command ScreenField sField = this.getSFie...
python
def initialize_logging_path(path: str = None) -> str: """ Initializes the logging path for running the project. If no logging path is specified, the current directory will be used instead. :param path: Path to initialize for logging. Can be either a path to a file or a path to a directo...
python
def parse_cluster(self, global_params, region, cluster): """ Parse a single ElastiCache cluster :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param cluster: ElastiCache cluster ""...
python
def _init_map(self): """stub""" super(MultiLanguageDragAndDropQuestionFormRecord, self)._init_map() self.my_osid_object_form._my_map['droppables'] = \ self._droppables_metadata['default_object_values'][0] self.my_osid_object_form._my_map['targets'] = \ self._targe...
python
def _parse_astorb_database_file( self, astorbgz): """* parse astorb database file* **Key Arguments:** - ``astorbgz`` -- path to the downloaded astorb database file **Return:** - ``astorbDictList`` -- the astorb database parsed as a list of dictio...
python
def get(self, _create=False, **ctx_options): """ NOTE: `ctx_options` are ignored """ if _create: return self._kind_factory.create(key=self) else: return self._kind_factory(key=self)
java
public static boolean isJavaIdentifier( String str ) { if( str.length() == 0 || !Character.isJavaIdentifierStart( str.charAt( 0 ) ) ){ return false; } for( int i = 1; i < str.length(); i++ ){ if( !Character.isJavaIdentifierPart( str.charAt( i ) ) ){ return false; ...
java
protected ArchiveOutputStream createArchiveOutputStream(File archiveFile) throws IOException { try { return CommonsStreamFactory.createArchiveOutputStream(this, archiveFile); } catch (ArchiveException e) { throw new IOException(e); } }
java
public byte[] getTile( int tx, int tyOsm, int zoom ) throws Exception { int ty = tyOsm; if (tileRowType.equals("tms")) { int[] tmsTileXY = MercatorUtils.osmTile2TmsTile(tx, tyOsm, zoom); ty = tmsTileXY[1]; } int _ty = ty; return database.execOnConnection(c...
python
def message_text(self, m_data): ''' Raises ValueError if a value doesn't work out, and TypeError if this isn't a message type ''' if m_data.get('type') != 'message': raise TypeError('This is not a message') # Edited messages have text in message _text ...
java
public static boolean hasAnnotationDeepRegex(Class<?> memberDeclaringClass, String metaAnnotationRegex) { if (memberDeclaringClass.getName().matches(metaAnnotationRegex)) { return true; } for (Annotation anno : memberDeclaringClass.getAnnotations()) ...
java
public static BigMoney total(CurrencyUnit currency, Iterable<? extends BigMoneyProvider> monies) { return BigMoney.zero(currency).plus(monies); }
java
private static String name(final GPX gpx) { return gpx.getMetadata() .flatMap(Metadata::getName) .orElse(null); }
java
private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) { final ClassInfo info = ClassInfo.getClassInfo(theClass); MetaClass mc = null; info.lock(); try { mc = info.getStrongMetaClass(); info.setStrongMetaClass(newMc); } finall...
java
public HashCalculationResult calculateSuperHash(File file) throws IOException { // Ignore files smaller than 0.5kb long fileSize = file.length(); if (fileSize <= FILE_MIN_SIZE_THRESHOLD) { logger.debug("Ignored file " + file.getName() + " (" + FileUtils.byteCountToDisplaySize(fileSiz...
java
public static final FileAttribute<?>[] getDefaultDirectoryFileAttributes(Map<String, ?> env) { FileAttribute<?>[] attrs = (FileAttribute<?>[]) env.get(DEFAULT_DIRECTORY_FILE_ATTRIBUTES); if (attrs == null) { attrs = new FileAttribute<?>[]{ PosixFilePermissio...
java
void sendResetProxySubscriptions() throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "sendResetProxySubscriptions"); // Generate the subscription message that will be sent to this neighbour. SubscriptionMessage message = iBusGroup.generate...
java
public void actionChangeSecureExport() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); String filename = getParamResource(); try { // lock res...
python
def move(self, target, home_flagged_axes=False): ''' Move to the `target` Smoothieware coordinate, along any of the size axes, XYZABC. target: dict dict setting the coordinate that Smoothieware will be at when `move()` returns. `target` keys are the axis in upper...
python
def _create_scheduled_actions(conn, as_name, scheduled_actions): ''' Helper function to create scheduled actions ''' if scheduled_actions: for name, action in six.iteritems(scheduled_actions): if 'start_time' in action and isinstance(action['start_time'], six.string_types): ...
python
def serialize(self, q): """ Serialize a Q object into a (possibly nested) dict. """ children = [] for child in q.children: if isinstance(child, Q): children.append(self.serialize(child)) else: children.append(child) ...
python
def update_or_create(self, model, **kwargs): '''Update or create a new instance of ``model``. This method can raise an exception if the ``kwargs`` dictionary contains field data that does not validate. :param model: a :class:`StdModel` :param kwargs: dictionary of parame...
java
synchronized void add(final Container container) { final String containerId = container.getId().toString(); if (this.hasContainer(containerId)) { throw new RuntimeException("Trying to add a Container that is already known: " + containerId); } this.containers.put(containerId, container); }
java
public void enqueue(RepairDigramRecord digramRecord) { // System.out.println("before == " + this.toString()); // if the same key element is in the queue - something went wrong with tracking... if (elements.containsKey(digramRecord.str)) { throw new IllegalArgumentException( "Element wit...
java
private Object readResolve() { if (DateTimeZone.UTC.equals(getChronology().getZone()) == false) { return new YearMonth(this, getChronology().withUTC()); } return this; }
python
def mktns(self): """ Make the schema's target namespace. @return: The namespace representation of the schema's targetNamespace value. @rtype: (prefix, uri) """ tns = [None, self.root.get('targetNamespace')] if tns[1] is not None: tns[0] = s...
python
def to_csv(self, filename, networks=False, dataset=None, size=False, n_jobs=-1): """ Writes the list of logical networks to a CSV file Parameters ---------- filename : str Absolute path where to write the CSV file networks : boolean If True, a co...
java
@Override public CommerceAvailabilityEstimate findByPrimaryKey( Serializable primaryKey) throws NoSuchAvailabilityEstimateException { CommerceAvailabilityEstimate commerceAvailabilityEstimate = fetchByPrimaryKey(primaryKey); if (commerceAvailabilityEstimate == null) { if (_log.isDebugEnabled()) { _log.de...
python
def delete(self, alert_condition_infra_id): """ This API endpoint allows you to delete an alert condition for infrastucture :type alert_condition_infra_id: integer :param alert_condition_infra_id: Alert Condition Infra ID :rtype: dict :return: The JSON response of the A...
java
@Deprecated public static <T> T firstNonNull(@Nullable T first, @Nullable T second) { return MoreObjects.firstNonNull(first, second); }
python
def import_from_json(self, data): """ Replace the current roster with the :meth:`export_as_json`-compatible dictionary in `data`. No events are fired during this activity. After this method completes, the whole roster contents are exchanged with the contents from `data`. ...
java
private boolean couldBeEnumCollection(int stackPos) { if (stack.getStackDepth() <= stackPos) { return false; } OpcodeStack.Item item = stack.getStackItem(stackPos); CollectionType userValue = (CollectionType) item.getUserValue(); if (userValue != null) { ...
java
public PhotoList<Photo> getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) throws FlickrException { return getContactsPublicPhotos(userId, Extras.MIN_EXTRAS, count, justFriends, singlePhoto, includeSelf); }
java
public byte[] getProgram() { try { // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (Scri...
python
def wrap_multipart_params(func): """ A middleware that parses the multipart request body and adds the parsed content to the `multipart_params` attribute. This middleware also merges the parsed value with the existing `params` attribute in same way as `wrap_form_params` is doing. """ def wr...
python
def build_docstring(func_name, args, ret, throws, signal_owner_type=None): """Create a docstring in the form: name(in_name: type) -> (ret_type, out_name: type) """ out_args = [] if ret and not ret.ignore: if ret.py_type is None: out_args.append("unknown") else: ...
java
private void resetIndicatorFiles() { for (GenericIndicator<S> indicator : experiment.getIndicatorList()) { for (ExperimentAlgorithm<?, Result> algorithm : experiment.getAlgorithmList()) { for (ExperimentProblem<?> problem: experiment.getProblemList()) { String algorithmDirectory; a...
python
async def info(self, session, *, dc=None, watch=None, consistency=None): """Queries a given session Parameters: session (ObjectID): Session ID dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. watch (Block...
java
@Deactivate protected synchronized void deactivate(int reason) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Deactivated: " + reason); } super.deactivate(MY_ALIAS, reason); repertoireMap.clear(); repertoirePIDMap.clear(); ...
python
def display(path_html="mapper_visualization_output.html"): """ Displays a html file inside a Jupyter Notebook output cell. .. note:: Must run ``KeplerMapper.visualize`` first to generate html. This function will then render that output from a file saved to disk. .....
java
void setAction(PdfAction action, float llx, float lly, float urx, float ury) { addAnnotation(new PdfAnnotation(writer, llx, lly, urx, ury, action)); }
java
public Runnable wrap(final Runnable r) { return new Runnable() { @Override public void run() { Context previous = attach(); try { r.run(); } finally { detach(previous); } } }; }
python
def get(self, id=None, **kwargs): """ https://docs.cachethq.io/docs/get-components https://docs.cachethq.io/docs/get-a-component """ if id is not None: return self._get('components/%s' % id, data=kwargs) elif 'params' in kwargs: data = dict(kwargs)...
java
private static IEntity getEntity(String key, Class<?> type, String service) throws GroupsException { return instance().igetEntity(key, type, service); }
python
def show_type(cls, result): """ :param TryHaskell.Result result: Parse result of JSON data. :rtype: str|unicode """ if result.ok: return ' :: '.join([result.expr, result.type]) return result.value
python
def remove_state(self, state_id, recursive=True, force=False, destroy=True): """ Overwrite the parent class remove state method by checking if the user tries to delete the decider state :param state_id: the id of the state to remove :param recursive: a flag to indicate a recursive disassembling...
python
def togpx(self): """Generate a GPX waypoint element subtree. Returns: etree.Element: GPX element """ element = create_elem(self.__class__._elem_name, {'lat': str(self.latitude), 'lon': str(self.longitude)}) ...
python
def split_voxels(self, vtk_filename=None): """ Second step of algorithm :return:() """ self.cache = {} self.stats["t graph 10"] = time.time() - self.start_time self.msi = MultiscaleArray(self.data.shape, block_size=self.nsplit) # old implementation ...
java
private String getUsernameForUserId(int id) { if (id > 0) { String username = userIdentityStore.getPortalUserName(id); if (username != null) { return username; } logger.warn( "Invalid userID {} found when exporting a portlet; re...
java
public boolean waitFor() throws InterruptedException { try { // [START ] Job completedJob = job.waitFor(); if (completedJob == null) { // job no longer exists } else if (completedJob.getStatus().getError() != null) { // job failed, handle error } else { // job c...
java
public static CreateUsingTempTokenRequest createUsingTempToken() throws IOException { String uri = uri("payment_sources", "create_using_temp_token"); return new CreateUsingTempTokenRequest(Method.POST, uri); }