language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def load_config_json(conf_file): """Banana?""" try: with open(conf_file) as _: try: json_conf = json.load(_) except ValueError as ze_error: error('invalid-config', 'The provided configuration file %s is not valid json.\n' ...
java
public final void shiftOp() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:465:5: ( ( LESS LESS | GREATER GREATER GREATER | GREATER GREATER ) ) // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:465:7: ( LESS LESS | GREATER GREATER GREATER | GR...
python
def generate_id(self): """Generate a fresh id""" if self.use_repeatable_ids: self.repeatable_id_counter += 1 return 'autobaked-{}'.format(self.repeatable_id_counter) else: return str(uuid4())
python
def run(vcf, conf_fns, lua_fns, data, basepath=None, decomposed=False): """Annotate a VCF file using vcfanno (https://github.com/brentp/vcfanno) decomposed -- if set to true we'll convert allele based output into single values to match alleles and make compatible with vcf2db (https://github.com/qui...
python
def find_elb(name='', env='', region=''): """Get an application's AWS elb dns name. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS record """ LOG.info('Find %s ELB in %s [%s].', name, env, region) ...
python
def _is_inside(self, span1, span2, covered_spans): """Returns True if both `span1` and `span2` fall within `covered_spans`. :param span1: start and end indices of a span :type span1: 2-`tuple` of `int` :param span2: start and end indices of a span :type span2: 2-`tuple` ...
java
public static void swap(int[] intArray1, int array1Index, int[] intArray2, int array2Index) { if(intArray1[array1Index] != intArray2[array2Index]) { intArray1[array1Index] = intArray1[array1Index] ^ intArray2[array2Index]; intArray2[array2Index] = intArray1[array1Index] ^ intArray2[array2Index]; intArray1[ar...
python
def days(self): """Return the 7 days of the week as a list (of datetime.date objects)""" monday = self.day(0) return [monday + timedelta(days=i) for i in range(7)]
java
public JSONObject match(List<MatchRequest> input) { AipRequest request = new AipRequest(); preOperation(request); JSONArray arr = new JSONArray(); for (MatchRequest req : input) { arr.put(req.toJsonObject()); } request.addBody("body", arr.toString()); ...
python
def CheckRegistryKey(javaKey): """ Method checks for the java in the registry entries. """ from _winreg import ConnectRegistry, HKEY_LOCAL_MACHINE, OpenKey, QueryValueEx path = None try: aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) rk = OpenKey(aReg, javaKey) for i in range(1024): currentVersi...
java
private void obtainFragment(@NonNull final TypedArray typedArray) { setFragment(typedArray.getString(R.styleable.NavigationPreference_android_fragment)); }
python
def compute_node_colors(self): """Compute the node colors. Also computes the colorbar.""" data = [self.graph.node[n][self.node_color] for n in self.nodes] if self.group_order == "alphabetically": data_reduced = sorted(list(set(data))) elif self.group_order == "default": ...
java
public static <T extends Enum<T> & SaneEnum> Set<T> enumSet(Class<T> enumType, int wireValue) { T[] enumConstants = enumType.getEnumConstants(); List<T> values = Lists.newArrayListWithCapacity(enumConstants.length); for (T value : enumConstants) { if ((wireValue & value.getWireValue()) != 0) { ...
python
def satisfy_custom_matcher(self, args, kwargs): """Return a boolean indicating if the args satisfy the stub :return: Whether or not the stub accepts the provided arguments. :rtype: bool """ if not self._custom_matcher: return False try: return sel...
java
public void dereferenceControllable() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "dereferenceControllable"); messageProcessor = null; destinationIndex = null; destinationManager = null; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnable...
java
@Nonnull public static DAType from(@Nonnull Class<?> clazz, @Nonnull List<DAType> typeArgs) { return instance(clazz.getSimpleName(), clazz.getCanonicalName(), typeArgs); }
python
async def on_raw_730(self, message): """ Someone we are monitoring just came online. """ for nick in message.params[1].split(','): self._create_user(nick) await self.on_user_online(nickname)
python
def register(email): ''' Register a new user account CLI Example: .. code-block:: bash salt-run venafi.register email@example.com ''' data = __utils__['http.query']( '{0}/useraccounts'.format(_base_url()), method='POST', data=salt.utils.json.dumps({ ...
python
def get( self, name=None, group=None, index=None, raster=None, samples_only=False, data=None, raw=False, ignore_invalidation_bits=False, source=None, record_offset=0, record_count=None, copy_master=True, ): ...
java
boolean recoverLease(String src, String holder, String clientMachine, boolean discardLastBlock) throws IOException { // convert names to array of bytes w/o holding lock byte[][] components = INodeDirectory.getPathComponents(src); writeLock(); try { if (isInSafeMode...
java
private void loadAliases(ApplicationContext applicationContext, String propertyFile) { if (propertyFile.isEmpty()) { return; } Resource[] resources; try { resources = applicationContext.getResources(propertyFile); } catch (IOException e) { lo...
python
def set_file_path(self, path): """Update the file_path Entry widget""" self.file_path.delete(0, END) self.file_path.insert(0, path)
python
def new(cls, arg): """ Creates a new Parameter object from the given ParameterArgument. """ content = None if arg.kind == 'file': if os.path.exists(arg.value): with open(arg.value, 'r') as f: content = f.read() else: ...
java
public static <T> Collection<T> unique(Collection<T> self) { return unique(self, true); }
java
private Function findField(String name) { Selection slkt; Function f; if (name.indexOf('.') == -1) { name = type.getName() + "." + name; } slkt = Method.forName(name); if (slkt.size() == 0) { f = Field.forName(name); if (f != null) { ...
python
def reference(self, reference): """ Sets the reference of this CreateCertificateIssuerConfig. The certificate name, as created in the factory, to which the certificate issuer configuration applies. The following names are reserved and cannot be configured: LwM2M, BOOTSTRAP. :param refe...
python
def extract(args): """ %prog extract idsfile sizesfile Extract the lines containing only the given IDs. """ p = OptionParser(extract.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) idsfile, sizesfile = args sizes = Sizes(sizesfile)....
python
def getNumberOfRegularSamples(self): """ Returns the number of regular samples. :returns: number of regular samples :rtype: integer """ analyses = self.getRegularAnalyses() samples = [a.getRequestUID() for a in analyses] # discarding any duplicate values ...
python
def return_collection(collection_type): """Change method return value from raw API output to collection of models """ def outer_func(func): @functools.wraps(func) def inner_func(self, *pargs, **kwargs): result = func(self, *pargs, **kwargs) return list(map(collection_...
python
def basek_string_to_base10_integer(k, x): """Convert a base k string into an integer.""" assert 1 < k <= max_k_labeled return sum(numeral_index[c]*(k**i) for i, c in enumerate(reversed(x)))
java
public static String getHBCIHostForBLZ(String blz) { BankInfo info = getBankInfo(blz); if (info == null) return ""; return info.getRdhAddress() != null ? info.getRdhAddress() : ""; }
java
private CompletableFuture<WriterFlushResult> flushPendingAppends(Duration timeout) { // Gather an InputStream made up of all the operations we can flush. FlushArgs flushArgs; try { flushArgs = getFlushArgs(); } catch (DataCorruptionException ex) { return Futures.f...
python
def _try_acquire_lease(self, shard_state, tstate): """Validate datastore and the task payload are consistent. If so, attempt to get a lease on this slice's execution. See model.ShardState doc on slice_start_time. Args: shard_state: model.ShardState from datastore. tstate: model.TransientSh...
python
def delete(self): """ Delete the instance from redis storage. """ # Delete each field for field_name in self._fields: field = self.get_field(field_name) if not isinstance(field, PKField): # pk has no stored key field.delete(...
java
@Override public ICmdLineArg<E> setEnumCriteria(final String _enumClassName) throws ParseException, IOException { this.enumClassName = _enumClassName; Class<?> enumClass; try { enumClass = CmdLine.ClassLoader.loadClass(_enumClassName); } catch (fin...
python
def toStr (self, separator = ':'): """ Returns the address as string consisting of 12 hex chars separated by separator. """ return separator.join(('{:02x}'.format(x) for x in self.__value))
python
def restart(self, all=False): """Restarts the given process.""" if all: data = {'type': self.type} else: data = {'ps': self.process} r = self._h._http_resource( method='POST', resource=('apps', self.app.name, 'ps', 'restart'), ...
python
def _link_variables_on_block(self, block, kb): """ Link atoms (AIL expressions) in the given block to corresponding variables identified previously. :param ailment.Block block: The AIL block to work on. :return: None """ variable_manager = kb.variable...
python
def _validate(self, schema): """ Validates a schema that defines rules against supported rules. :param schema: The schema to be validated as a legal cerberus schema according to the rules of this Validator object. """ if isinstance(schema, _str_type): ...
java
public static <T> T notNullNotEquals (final T aValue, @Nonnull final Supplier <? extends String> aName, @Nonnull final T aUnexpectedValue) { notNull (aValue, aName); notNull (aUnexpectedValue, "UnexpectedValue"); if (isEnabled...
python
def get_binaries(): """Download and return paths of all platform-specific binaries""" paths = [] for arp in [False, True]: paths.append(get_binary(arp=arp)) return paths
java
public ServiceFuture<SubscriptionQuotasListResultInner> listQuotasAsync(String location, final ServiceCallback<SubscriptionQuotasListResultInner> serviceCallback) { return ServiceFuture.fromResponse(listQuotasWithServiceResponseAsync(location), serviceCallback); }
java
public static void notNull(Object obj, Supplier<String> message) { if (isNull(obj)) { throw new IllegalArgumentException(message.get()); } }
python
def filter_duplicate(self, url): """ url去重 """ if self.filterDuplicate: if url in self.historys: raise Exception('duplicate excepiton: %s is duplicate' % url) else: self.historys.add(url) else: pass
java
public Stylesheet parse() throws ParseException { while (tokenizer.more()) { if (tokenizer.current().isKeyword(KEYWORD_IMPORT)) { // Handle @import parseImport(); } else if (tokenizer.current().isKeyword(KEYWORD_MIXIN)) { // Handle @mixin ...
python
def set_config(self, config): """Set (replace) the configuration for the session. Args: config: Configuration object """ with self._conn: self._conn.execute("DELETE FROM config") self._conn.execute('INSERT INTO config VALUES(?)', ...
java
protected CmsBasicFormField createUrlNameField() { if (m_urlNameField != null) { m_urlNameField.unbind(); } String description = message(Messages.GUI_URLNAME_PROPERTY_DESC_0); String label = message(Messages.GUI_URLNAME_PROPERTY_0); final CmsTextBox textbox = new Cm...
java
public static void childConnectionObserver(ServerBootstrap b, ConnectionObserver connectionObserver) { Objects.requireNonNull(b, "bootstrap"); Objects.requireNonNull(connectionObserver, "connectionObserver"); b.childOption(OBSERVER_OPTION, connectionObserver); }
java
public void initialize(Iterable<ModuleMetadataFileFinder> moduleMetadataFiles, ClassLoader cl) { // First init core module metadata FileLookup fileLookup = FileLookupFactory.newInstance(); try { readMetadata(fileLookup.lookupFileLocation("infinispan-core-component-metadata.dat", cl)); }...
java
public List<FeatureTileLink> queryForTileTableName(String tileTableName) { List<FeatureTileLink> results = null; try { results = queryForEq(FeatureTileLink.COLUMN_TILE_TABLE_NAME, tileTableName); } catch (SQLException e) { throw new GeoPackageException( "Failed to query for Feature Tile Link objec...
python
def _load_relationship_info(self): """Maps parent and child entries in the MFT. Because the library expects the MFT file to be provided, it doesn't have access to anything non-resident. Because of that, if we want all the information related to the entry, it is necessary to visit all th...
python
def convert_random_normal(node, **kwargs): """Map MXNet's random_normal operator attributes to onnx's RandomNormal operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) # Converting to float32 mean = float(attrs.get("loc", 0)) scale = float(attrs.get(...
java
@Override public int prolepticYear(Era era, int yearOfEra) { if (era instanceof EthiopicEra == false) { throw new ClassCastException("Era must be EthiopicEra"); } return (era == EthiopicEra.INCARNATION ? yearOfEra : 1 - yearOfEra); }
java
public static InterestingSomething getInterestingSomething(Throwable cause, File sourceDir) { InterestingSomething something = null; for (StackTraceElement stackTraceElement : cause.getStackTrace()) { if (stackTraceElement.getLineNumber() > 0) { String path = stackTraceElemen...
python
def genl_ctrl_probe_by_name(sk, name): """Look up generic Netlink family by family name querying the kernel directly. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L237 Directly query's the kernel for a given family name. Note: This API call differs from genl_ctrl_search_by_name i...
python
def GetEventTaggingRules(self): """Retrieves the event tagging rules from the tagging file. Returns: dict[str, FilterObject]: tagging rules, that consists of one or more filter objects per label. Raises: TaggingFileError: if a filter expression cannot be compiled. """ tagging...
python
def _predict_with_options(self, dataset, with_ground_truth, postprocess=True, confidence_threshold=0.001, iou_threshold=None, verbose=True): """ Predict with options for what kind of SFrame should be returned. ...
java
public CollectionDescriptor getCollectionDescriptorByName(String name) { if (name == null) { return null; } CollectionDescriptor cod = (CollectionDescriptor) getCollectionDescriptorNameMap().get(name); // // BRJ: if the CollectionDescriptor is...
python
def _to_http_hosts(hosts: Union[Iterable[str], str]) -> List[str]: """Convert a string of whitespace or comma separated hosts into a list of hosts. Hosts may also already be a list or other iterable. Each host will be prefixed with 'http://' if it is not already there. >>> _to_http_hosts('n1:4200,n2:4...
python
def clean(self): """ Make sure the lookup makes sense """ if self.lookup == '?': # Randomly sort return else: lookups = self.lookup.split(LOOKUP_SEP) opts = self.model_def.model_class()._meta valid = True while len(look...
python
def gap_index_map(sequence, gap_chars='-'): """ Opposite of ungap_index_map: returns mapping from gapped index to ungapped index. >>> gap_index_map('AC-TG-') {0: 0, 1: 1, 3: 2, 4: 3} """ return dict( (v, k) for k, v in list(ungap_index_map(sequence, gap_chars).items()))
python
def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Visualize the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visual...
python
def paginate(self, page=None, per_page=None, error_out=True, max_per_page=None, count=True): """Returns ``per_page`` items from page ``page``. If ``page`` or ``per_page`` are ``None``, they will be retrieved from the request query. If ``max_per_page`` is specified, ``per_page`` will be ...
java
private static boolean isTransformPossible(byte[] bytes) { if (bytes.length < 8) { return false; } // The transform method will be called for all classes, but ASM is only // capable of processing some class file format versions. That's ok // because the transformer ...
java
boolean isStarvedForFairShare(JobInfo info, TaskType type) { int desiredFairShare = (int) Math.floor(Math.min( (fairTasks(info, type) + 1) / 2, runnableTasks(info, type))); return (runningTasks(info, type) < desiredFairShare); }
java
public void setClientInfo(final String name, final String value) throws SQLClientInfoException { checkClientClose(name); checkClientReconnect(name); checkClientValidProperty(name); try { Statement statement = createStatement(); statement.execute(buildClientQuery(name, value)); } catch (...
python
def _build_id_tuple(params, spec): """ Builds a 2-element tuple used to identify fields by grabbing the class_ and tag from an Asn1Value class and the params dict being passed to it :param params: A dict of params to pass to spec :param spec: An Asn1Value class :return: ...
java
@Override public ResourceFactory createResourceFactory(Map<String, Object> props) throws Exception { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(tc, "createResourceFactory", props); //Place holder for admin object propert...
python
def content_type(self, request=None, response=None): """Returns the content type that should be used by default for this endpoint""" if callable(self.outputs.content_type): return self.outputs.content_type(request=request, response=response) else: return self.outputs.cont...
python
def param_value_send(self, param_id, param_value, param_type, param_count, param_index, force_mavlink1=False): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of rece...
java
@Override public List<Component> listComponents( String applicationName ) { this.logger.fine( "Request: list components for the application " + applicationName + "." ); List<Component> result = new ArrayList<> (); Application app = this.manager.applicationMngr().findApplicationByName( applicationName ); if( a...
java
public static Dater iso(String date) { //Converting ISO8601-compliant String to java.util.Date return of(DatatypeConverter.parseDateTime( Strs.WHITESPACE.removeFrom(checkNotNull(date)))); }
java
public Thread newThread(final Runnable runnable) { final Thread thread = new Thread(runnable); thread.setName("HSQLDB Timer @" + Integer.toHexString(hashCode())); thread.setDaemon(true); return thread; }
java
public boolean isEUI64(boolean partial) { int segmentCount = getSegmentCount(); int endIndex = addressSegmentIndex + segmentCount; if(addressSegmentIndex <= 5) { if(endIndex > 6) { int index3 = 5 - addressSegmentIndex; IPv6AddressSegment seg3 = getSegment(index3); IPv6AddressSegment seg4 = getSegme...
python
def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000): """ Calculates a good piece size for a size """ logger.debug('Calculating piece size for %i' % size) for i in range(min_piece_size, max_piece_size): # 20 = 1MB if size / (2**i) < max_piece_count: ...
java
public static InsnList addLabel(LabelNode labelNode) { Validate.notNull(labelNode); InsnList ret = new InsnList(); ret.add(labelNode); return ret; }
java
@Reqiured public void setInterceptors(Interceptor[] interceptors) { Listener last = null; for (int i = interceptors.length - 1; i >= 0; i--) { final Interceptor current = interceptors[i]; final Listener next = last; last = new Listener() { public v...
java
public ResourceadapterType<ConnectorDescriptor> getOrCreateResourceadapter() { Node node = model.getOrCreate("resourceadapter"); ResourceadapterType<ConnectorDescriptor> resourceadapter = new ResourceadapterTypeImpl<ConnectorDescriptor>(this, "resourceadapter", model, node); return resourceadapter;...
python
def log_batch(self, log_data): """Logs batch of messages with attachment. Args: log_data: list of log records. log record is a dict of; time, message, level, attachment attachment is a dict of: name: name of attachment ...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.MCF__RG: return rg != null && !rg.isEmpty(); } return super.eIsSet(featureID); }
java
@Override public synchronized TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException { checkNotClosed(); RemoteTopicSession session = new RemoteTopicSession(idProvider.createID(), this, ...
python
def parse_codons(ref, start, end, strand): """ parse codon nucleotide positions in range start -> end, wrt strand """ codon = [] c = cycle([1, 2, 3]) ref = ref[start - 1:end] if strand == -1: ref = rc_stats(ref) for pos in ref: n = next(c) codon.append(pos) ...
python
def create_data_iters_and_vocabs(args: argparse.Namespace, max_seq_len_source: int, max_seq_len_target: int, shared_vocab: bool, resume_training: bool, out...
java
public static byte[] getContent(HttpResponse response) { try { if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return ResourceUtils.getBytes(response.getEntity().getContent()); } } catch (IOException e) { log.error("Failed to read response: ", e.getMessage());...
java
public void setPointerList(FSArray v) { if (MMAXAnnotation_Type.featOkTst && ((MMAXAnnotation_Type)jcasType).casFeat_pointerList == null) jcasType.jcas.throwFeatMissing("pointerList", "de.julielab.jules.types.mmax.MMAXAnnotation"); jcasType.ll_cas.ll_setRefValue(addr, ((MMAXAnnotation_Type)jcasType).casFe...
java
private void initFromSeriesDefinition(String seriesDefinition) { String seriesDefinitionString = seriesDefinition; m_seriesDefinition = new CmsSerialDateValue(seriesDefinitionString); if (m_seriesDefinition.isValid()) { I_CmsSerialDateBean bean = CmsSerialDateBeanFactory.createSeria...
java
public Content commentTagsToOutput(Element holder, List<? extends DocTree> tags) { return commentTagsToOutput(null, holder, tags, false); }
java
public FieldDefinition getInverseLinkDef() { assert isLinkType(); TableDefinition inverseTableDef = getInverseTableDef(); if (inverseTableDef == null) { return null; } return inverseTableDef.getFieldDef(m_linkInverse); }
java
public CommandAuthorization createOrUpdate(String chargingStationId, String userIdentity, Class commandClass) { EntityManager em = getEntityManager(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); CommandAuthorization storedCommand...
java
private static String getFinalResponseUrl( final HttpClientContext context, final String candidateUrl) { List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { return redirectLocations.get(redirectLocations.size() - 1).toSt...
java
public int read(byte[] buff, int offset, int length) { if (buffer == null) throw new AssertionError("Attempted to read from closed RAR"); if (length == 0) return 0; if (isEOF()) return -1; if (current >= bufferOffset + buffer.length || validBufferBy...
java
public void sendTimed(Long chatId, Object messageRequest) { MessageQueue queue = mMessagesMap.get(chatId); if (queue == null) { queue = new MessageQueue(chatId); queue.putMessage(messageRequest); mMessagesMap.put(chatId, queue); } else { queue.putMessage(messageRequest); mMessagesMap.putIfAb...
java
private <E> boolean onCheckListAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass) { if (pluralAttribute != null) { if (isListAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass)) { return true; } ...
java
public CMAEditorInterface addControl(Control control) { if (controls == null) { controls = new ArrayList<Control>(); } controls.add(control); return this; }
python
def parse_dtype_info(flags): """Convert dtype string to tf dtype, and set loss_scale default as needed. Args: flags: namespace object returned by arg parser. Raises: ValueError: If an invalid dtype is provided. """ if flags.dtype in (i[0] for i in DTYPE_MAP.values()): return # Make function ide...
java
protected void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref) { try { if (this != u.getHandler()) { throw new SecurityException("handler for url diff...
python
def compose_capability(base, *classes): """Create a new class starting with the base and adding capabilities.""" if _debug: compose_capability._debug("compose_capability %r %r", base, classes) # make sure the base is a Collector if not issubclass(base, Collector): raise TypeError("base must be ...
java
void encode(ChannelBuffer buf) { buf.writeByte('*'); writeInt(buf, 1 + (args != null ? args.count() : 0)); buf.writeBytes(CRLF); buf.writeByte('$'); writeInt(buf, type.bytes.length); buf.writeBytes(CRLF); buf.writeBytes(type.bytes); buf.writeBytes(CRLF); ...
java
public LaSchedulingNow start() { final ClassLoader originalLoader = startHotdeploy(); final Cron4jScheduler cron4jScheduler; final Cron4jNow cron4jNow; try { final LaJobScheduler appScheduler = findAppScheduler(); inject(appScheduler); final LaJobRunne...
java
private void init() { cacheable = null; status = SC_OK; streamDelegate = new ServletResponseStreamDelegate(this) { protected OutputStream createOutputStream() throws IOException { // Test if this request is really cacheable, otherwise, // just wr...