language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void parseJobTasks(String jobHistoryFile, JobHistory.JobInfo job, FileSystem fs) throws IOException { JobHistory.parseHistoryFromFS(jobHistoryFile, new JobTasksParseListener(job), fs); }
java
protected static boolean fileDoesNotExist(String file, String path, String dest_dir) { File f = new File(dest_dir); if (!f.isDirectory()) return false; String folderPath = createFolderPath(path); f = new File(f, folderPath); File javaFile = new File(f,...
python
def _get_caller(self, callers: List[str], function: str) -> str: """ Get the caller function from the provided function """ is_next = False for c in callers: if is_next is True: return c if function == c: is_next = True
java
@Override public List<CommerceWarehouse> findByGroupId(long groupId, int start, int end) { return findByGroupId(groupId, start, end, null); }
java
static long toBIO(ByteBufAllocator allocator, X509Certificate... certChain) throws Exception { if (certChain == null) { return 0; } if (certChain.length == 0) { throw new IllegalArgumentException("certChain can't be empty"); } PemEncoded pem = PemX509Cer...
java
protected void addEqualsCondition(final Expression<String> property, final String value) { fieldConditions.add(getCriteriaBuilder().equal(property, value)); }
python
def signup(self, project_name, email): """ Signup for a new project. """ uri = 'openstack/sign-up' data = { "project_name": project_name, "email": email, } post_body = json.dumps(data) resp, body = self.post(uri, body=post_body) self.expec...
java
@Override public Iterable<T> get() throws Exception { Iterable<T> original = originalState.get(); return original != null ? original : emptyState; }
java
private static void addDependency(List<Dependency> dependencies, MavenCoordinates requiredArtifact, Constants.ArtifactType type, String scope) { Dependency dependency = new Dependency(); dependency.setGroupId(requiredArtifact.getGroupId()); dependency.setArtifactId(requiredArtifact.getArtifactId()); dependency....
java
public void clear() { setElementNames(new StringStack(STRINGSTACK_SIZE)); setContentBuffer(new StringBuilder()); setSpecificElement(false); minLat = 0; maxLat = 0; minLon = 0; maxLon = 0; creator = null; version = null; name = null; ...
python
def scopes(self, **kwargs): """Scopes associated to the team.""" return self._client.scopes(team=self.id, **kwargs)
python
def call_cc(fn: Callable) -> 'Observable': r"""call-with-current-continuation. Haskell: callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c """ def subscribe(on_next): return fn(lambda a: Observable(lambda _: on_next(a))).subscribe(on_next) return Observ...
python
def purge(context, resource, **kwargs): """Purge resource type.""" uri = '%s/%s/purge' % (context.dci_cs_api, resource) if 'force' in kwargs and kwargs['force']: r = context.session.post(uri, timeout=HTTP_TIMEOUT) else: r = context.session.get(uri, timeout=HTTP_TIMEOUT) return r
java
public BlockOrder setBlockOrder(BlockOrder order) { verifyTrue(order != null, "block order cannot be null"); if (order == layout.blockOrder) { return order; // quick exit, already same } BlockMatrixLayout newLayout = new BlockMatrixLayout(layout.rows, layout.columns, layout.blockStripe, order);...
java
@CodingStyleguideUnaware public static <T extends Collection <?>> T notEmpty (final T aValue, final String sName) { if (isEnabled ()) return notEmpty (aValue, () -> sName); return aValue; }
python
def _set_traffic_class_mutation(self, v, load=False): """ Setter method for traffic_class_mutation, mapped from YANG variable /qos/map/traffic_class_mutation (list) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_class_mutation is considered as a private meth...
python
def press(*keys): """ Simulates a key-press for all the keys passed to the function :param keys: list of keys to be pressed :return: None """ for key in keys: win32api.keybd_event(codes[key], 0, 0, 0) release(key)
python
def _get_result_paths(self, data): """Return dict of {key: ResultPath}""" result = {} result['FASTA'] = ResultPath(Path=self._get_seqs_outfile()) result['CLSTR'] = ResultPath(Path=self._get_clstr_outfile()) return result
java
public static base_response delete(nitro_service client, String name) throws Exception { netbridge deleteresource = new netbridge(); deleteresource.name = name; return deleteresource.delete_resource(client); }
java
JavaXmlQuery compile(XPath xpath) { try { this.expression = xpath.compile(getQuery()); } catch (XPathExpressionException e) { LOGGER.error("Cannot compile XPath query: " + getQuery(), e); } return this; }
java
@SuppressWarnings("unchecked") public <FRAMETYPE extends WindupVertexFrame> FRAMETYPE findSingletonVariable(Class<FRAMETYPE> type, String name) { WindupVertexFrame frame = findSingletonVariable(name); if (type != null && !type.isAssignableFrom(frame.getClass())) { throw new ...
java
@Override protected BaseDialogFragment.Builder build(BaseDialogFragment.Builder builder) { final CharSequence title = getTitle(); if (!TextUtils.isEmpty(title)) { builder.setTitle(title); } final CharSequence message = getMessage(); if (!TextUtils.isEmpty(message...
python
def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0 ...
python
def get_service_instance(host, username=None, password=None, protocol=None, port=None, mechanism='userpass', principal=None, domain=None): ''' Authenticate with a vCenter server or ESX/ESXi host and return the service instance object. host The locat...
java
@Override public Vector3f getNormal() { Vector3f v = null; if (this.normal!=null) { v = this.normal.get(); } if (v==null) { v = new Vector3f(); FunctionalVector3D.crossProduct( this.p2.getX() - this.p1.getX(), this.p2.getY() - this.p1.getY(), this.p2.getZ() - this.p1.getZ(), this.p...
python
def is_valid_int_param(param): """Verifica se o parâmetro é um valor inteiro válido. :param param: Valor para ser validado. :return: True se o parâmetro tem um valor inteiro válido, ou False, caso contrário. """ if param is None: return False try: param = int(param) if ...
python
def verify_callable_argspec(callable_, expected_args=Argument.ignore, expect_starargs=Argument.ignore, expect_kwargs=Argument.ignore): """ Checks the callable_ to make sure that it satisfies the given expectations. expec...
java
void applySourceMap(SourceMapConsumer aSourceMapConsumer, String aSourceFile, String aSourceMapPath) { String sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { ...
java
public Observable<LogAnalyticsOperationResultInner> exportThrottledRequestsAsync(String location, ThrottledRequestsInput parameters) { return exportThrottledRequestsWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<LogAnalyticsOperationResultInner>, LogAnalyticsOperationResultInner>()...
java
boolean deleteFromBucket(long i1, long tag) { for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) { if (checkTag(i1, i, tag)) { deleteTag(i1, i); return true; } } return false; }
java
public static <T> List<T> listFromClause(Class<T> clazz, String clause, Object... args) { return SqlClosure.sqlExecute(c -> OrmElf.listFromClause(c, clazz, clause, args)); }
python
def gather_votes(self, candidates): """Gather votes for the given candidates from the agents in the environment. Returned votes are anonymous, i.e. they cannot be tracked to any individual agent afterwards. :returns: A list of votes. Each vote is a list of ``(artifa...
java
@Override public GetHealthCheckLastFailureReasonResult getHealthCheckLastFailureReason(GetHealthCheckLastFailureReasonRequest request) { request = beforeClientExecution(request); return executeGetHealthCheckLastFailureReason(request); }
java
public static void setContnent(String content) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); try { StringSelection selection = new StringSelection( content ); clipboard.setContents(selection, selection); } catch (Exception ex) { //n...
java
@SuppressWarnings("unchecked") @Deprecated public static <V> Spy.SpyWithValue<V> call(Callable<V> callable) throws Exception { return Sniffy.call(callable); }
python
def connect(self, config): """Connect to database with given configuration, which may be a dict or a path to a pymatgen-db configuration. """ if isinstance(config, str): conn = dbutil.get_database(config_file=config) elif isinstance(config, dict): conn = d...
java
public List<CmsOrganizationalUnit> getManageableOrgUnits( CmsObject cms, String ouFqn, boolean includeSubOus, boolean includeWebusers) throws CmsException { List<CmsOrganizationalUnit> result = Lists.newArrayList(); List<CmsOrganizationalUnit> ous = getOrgUnitsForRol...
java
public void handleDirectRequest(HttpServerExchange exchange) { Log.Info(this,"direct request received "+exchange); getDirectRequestResponse(exchange.getRequestPath()).then( (s,err) -> { exchange.setResponseCode(200); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/h...
java
public static String rightTrim(final String aString) { if (aString == null) { return null; } int end = aString.length() - 1; while ((end >= 0) && (aString.charAt(end) <= ' ')) { end--; } if (end == aString.length() - 1) { return aString; } return aString.substring(0, end + 1); }
java
public void marshall(UpdateCertificateAuthorityRequest updateCertificateAuthorityRequest, ProtocolMarshaller protocolMarshaller) { if (updateCertificateAuthorityRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocol...
python
def enable_mp_crash_reporting(): """ Monkey-patch the multiprocessing.Process class with our own CrashReportingProcess. Any subsequent imports of multiprocessing.Process will reference CrashReportingProcess instead. This function must be called before any imports to mulitprocessing in order for the mon...
java
private SoyList newListFromIterable(Iterable<?> items) { // Create a list backed by a Java list which has eagerly converted each value into a lazy // value provider. Specifically, the list iteration is done eagerly so that the lazy value // provider can cache its value. ImmutableList.Builder<SoyValuePro...
java
public boolean is(T state, T... otherStates) { return EnumSet.of(state, otherStates).contains(currentState); }
java
public static Logger getLogger(Class<?> clazz) { return Logger.getLogger(Checker.isNull(clazz) ? LOCAL_CLASS : clazz); }
python
def to_array(self): """ Serializes this MaskPosition to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(MaskPosition, self).to_array() array['point'] = u(self.point) # py2: type unicode, py3: type str arra...
java
private Map<Pair<String, Integer>, Pair<String, Integer>> getViewColumnMaps(MaterializedViewInfo mv) { // A functor to iterate table columns from given MV, the first k entries are k GBY columns/expressions. final Iterable<Column> ciViewColumns = () -> mv.getDest().getColumns().iterator(); // NOT...
python
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._courses_default = self._mdata['courses']['default_id_values'] self._assessments_default = self._mdata['assessments']['default_id_values'] self._asse...
java
public static dnscnamerec[] get(nitro_service service) throws Exception{ dnscnamerec obj = new dnscnamerec(); dnscnamerec[] response = (dnscnamerec[])obj.get_resources(service); return response; }
python
def hash_key(self, key): """ "Hash" all keys in a timerange to the same value. """ for i, destination_key in enumerate(self._dict): if key < destination_key: return destination_key return key
java
@Override public GZIPChannel position(long newPosition) throws IOException { int skip = (int) (newPosition - position()); if (skip < 0) { throw new UnsupportedOperationException("backwards position not supported"); } if (skip > skipBuffer.capacity()) ...
python
def noop(self): """ Send a NOOP command :return: Returns the status. :rtype: int """ logger.debug('Sending NOOP') data = struct.pack(self.HEADER_STRUCT + self.COMMANDS['noop']['struct'], self.MAGIC['request'],...
java
private boolean isExecutionPaused(Execution nextStepExecution) { // If execution was paused if (nextStepExecution == null) { //set current step to finished executionMessage.setStatus(ExecStatus.FINISHED); executionMessage.incMsgSeqId(); executionMessage.se...
python
def Kill(self): """Send death pill to Gdb and forcefully kill it if that doesn't work.""" try: if self.is_running: self.Detach() if self._Execute('__kill__') == '__kill_ack__': # acknowledged, let's give it some time to die in peace time.sleep(0.1) except (TimeoutError, P...
python
def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong. """ from turicreate.toolki...
python
def locate_config(self): ''' Locate config file ''' for f in self.__potential: f = FileHelper.abspath(f) if os.path.isfile(f): return f return None
python
def getDone(self, done): """ :desc: Fetches a list of all the done ToDs :param bool done: done or undone? :returns: A list of matching IDs :rval: list """ doneItems = self.noteDB['todo'] \ .find({"done": done}) \ ...
java
public MethodNode addMethod(String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) { MethodNo...
java
private static ByteBuf nextReadableBuf(EmbeddedChannel decompressor) { for (;;) { final ByteBuf buf = decompressor.readInbound(); if (buf == null) { return null; } if (!buf.isReadable()) { buf.release(); continue; ...
java
private synchronized void setChannelState(String channelName, RuntimeState state) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setChannelState channelName=" + channelName + ", state=" + state.ordinal); } if (null != channelName) { Cha...
python
def handle_lock(handle): """ Decorate the handle method with a file lock to ensure there is only ever one process running at any one time. """ def wrapper(self, *args, **options): def on_interrupt(signum, frame): # It's necessary to release lockfile sys.exit() ...
python
def get_default_config(self): """ Return default config for the handler """ config = super(DatadogHandler, self).get_default_config() config.update({ 'api_key': '', 'queue_size': '', }) return config
python
def _set_dynamic_bypass_global(self, v, load=False): """ Setter method for dynamic_bypass_global, mapped from YANG variable /mpls_state/dynamic_bypass/dynamic_bypass_global (container) If this variable is read-only (config: false) in the source YANG file, then _set_dynamic_bypass_global is considered as...
python
def between(self, minimum: int = 1, maximum: int = 1000) -> int: """Generate a random number between minimum and maximum. :param minimum: Minimum of range. :param maximum: Maximum of range. :return: Number. """ return self.random.randint(minimum, maximum)
java
@SuppressWarnings("unchecked") public static void writeJSONString(Object value, Appendable out, JSONStyle compression) throws IOException { if (value == null) { out.append("null"); return; } Class<?> clz = value.getClass(); @SuppressWarnings("rawtypes") JsonWriterI w = defaultWriter.getWrite(clz); if...
python
def discover(name, timeout=None, minimum_providers=1): """ discovers a service. If timeout is specified, waits for at least minimum_providers service instance to be available. Note : we do not want to make the discovery block undefinitely since we never know for sure if a service is running or n...
java
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public void registerSearchView(@NonNull final Activity activity, @NonNull Menu menu, int id) { searchMenu = menu; searchMenuId = id; final SearchViewFacade actionView = new SearchViewFacade(menu, id); registerSearchVi...
java
protected String[] getPS() { ShellCommandExecutor shellExecutor = new ShellCommandExecutor(CMD); try { shellExecutor.execute(); } catch (IOException e) { LOG.error(StringUtils.stringifyException(e)); return null; } return shellExecutor.getOutput().split("\n"); }
java
public ImportDescr importStatement(PackageDescrBuilder pkg) throws RecognitionException { try { String kwd; if (helper.validateLT(2, kwd = DroolsSoftKeywords.ACC) || helper.validateLT(2, kwd = DroolsSoftKeywords.ACCUMULATE)) { AccumulateImportDescrBuil...
python
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Terminal Server Client Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.Wi...
java
int refreshAndGetMin() { int min = Integer.MAX_VALUE; ResultSubpartition[] allPartitions = partition.getAllPartitions(); if (allPartitions.length == 0) { // meaningful value when no channels exist: return 0; } for (ResultSubpartition part : allPartitions) { int size = part.unsynchronizedGetNumberOf...
java
public void setMemberAccounts(java.util.Collection<String> memberAccounts) { if (memberAccounts == null) { this.memberAccounts = null; return; } this.memberAccounts = new java.util.ArrayList<String>(memberAccounts); }
python
def get_objective_ids_by_objective_banks(self, objective_bank_ids): """Gets the list of ``Objective Ids`` corresponding to a list of ``ObjectiveBanks``. arg: objective_bank_ids (osid.id.IdList): list of objective bank ``Ids`` return: (osid.id.IdList) - list of objective ``Ids...
python
def version(self): """ Generate a Unique version value from the git information :return: """ git_rev = len(os.popen('git rev-list HEAD').readlines()) if git_rev != 0: self.version_list[-1] = '%d' % git_rev version = '.'.join(self.version_list) ...
python
def _new_session(self): """Helper for concrete methods creating session instances. :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: new session instance. """ if self.labels: return self._database.session(labels=self.labels) return self._dat...
python
def eom(self): """ Send the message to DSPAM for classification and a return a milter response based on the results. If <DspamMilter>.static_user is set, that single DSPAM user account will be used for processing the message. If it is unset, all envelope recipients will ...
java
public SystemInputDef removeFunctionInputDef( String name) { int i = findFunctionInputDef( name); if( i >= 0) { functionInputDefs_.remove(i); } return this; }
java
public String format(Description description) { for (BlockElement blockElement : description.getBlocks()) { blockElement.format(this); } return finalizeFormatting(); }
java
protected ClientHttpRequestInterceptor buildAddHeadersRequestInterceptor(String header1, String value1, String header2, String value2, String header3, String value3, String header4, String value4){ return new AddHeadersRequestInterceptor(new String[]{header1, header2, header3, header4}, new String[]{value1, value2, v...
java
public static final long getLong(byte[] data, int offset) { long result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 64; shiftBy += 8) { result |= ((long) (data[i] & 0xff)) << shiftBy; ++i; } return result; }
python
def registerItem(self, regItem): """ Adds a ClassRegItem object to the registry. """ check_class(regItem, ClassRegItem) if regItem.identifier in self._index: oldRegItem = self._index[regItem.identifier] logger.warn("Class key {!r} already registered as {}. Removin...
java
public java.lang.String getDocumentationRootUrl() { java.lang.Object ref = documentationRootUrl_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toSt...
python
def elapsed(self): """ Return the current elapsed time since start If the `elapsed` property is called in the context manager scope, the elapsed time bewteen start and property access is returned. However, if it is accessed outside of the context manager scope, it returns the ela...
java
public String convertIfcGasTerminalTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public static ObjectName makeObjectName(JmxResource jmxResource, JmxSelfNaming selfNamingObj) { String domainName = selfNamingObj.getJmxDomainName(); if (domainName == null) { if (jmxResource != null) { domainName = jmxResource.domainName(); } if (isEmpty(domainName)) { throw new IllegalArgumentExc...
python
def onlyOnce(fn): 'Set up FN to only run once within an interpreter instance' def wrap(*args, **kwargs): if hasattr(fn, 'called'): return fn.called = 1 return fn(*args, **kwargs) util.mergeFunctionMetadata(fn, wrap) return wrap
java
protected BaseTile computeFringeTile (int tx, int ty) { return _ctx.getTileManager().getAutoFringer().getFringeTile(_model, tx, ty, _fringes, _masks); }
python
def start(self): ''' Listen to messages and publish them. ''' # counter metrics for messages c_logs_ingested = Counter( 'napalm_logs_listener_logs_ingested', 'Count of ingested log messages', ['listener_type', 'address', 'port'], ) ...
java
public Observable<ServiceResponse<Page<ResourceMetricInner>>> listWorkerPoolInstanceMetricsSinglePageAsync(final String resourceGroupName, final String name, final String workerPoolName, final String instance, final Boolean details, final String filter) { if (resourceGroupName == null) { throw new I...
python
def which(program, add_win_suffixes=True): """Mimic 'which' command behavior. Adapted from https://stackoverflow.com/a/377028 """ def is_exe(fpath): """Determine if program exists and is executable.""" return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.pat...
python
def _get_setup(self, result): """Internal method which process the results from the server.""" self.__devices = {} if ('setup' not in result.keys() or 'devices' not in result['setup'].keys()): raise Exception( "Did not find device definition.") ...
python
def update_frame(self, key, ranges=None, element=None): """ Update the internal state of the Plot to represent the given key tuple (where integers represent frames). Returns this state. """ reused = isinstance(self.hmap, DynamicMap) and self.overlaid if not reused...
python
def plot_two_columns(self, reset_xlimits=False, reset_ylimits=False): """Simple line plot for two selected columns.""" self.clear_plot() if self.tab is None: # No table data to plot return plt_kw = { 'lw': self.settings.get('linewidth', 1), 'ls': se...
java
public ResultPoint[] detect() throws NotFoundException { int height = image.getHeight(); int width = image.getWidth(); int halfHeight = height / 2; int halfWidth = width / 2; int deltaY = Math.max(1, height / (MAX_MODULES * 8)); int deltaX = Math.max(1, width / (MAX_MODULES * 8)); int top =...
java
public static MozuUrl publishDraftsUrl() { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/publishing/publishdrafts"); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
python
def get_gl_configuration(): """Read the current gl configuration This function uses constants that are not in the OpenGL ES 2.1 namespace, so only use this on desktop systems. Returns ------- config : dict The currently active OpenGL configuration. """ # XXX eventually maybe we...
python
def run(self, service_id, **kwargs): """ Retrieve a list of metrics. Ensure they are set as metric data sources. """ log = self.get_logger(**kwargs) log.info("Loading Service for metric sync") try: service = Service.objects.get(id=service_id) log....
java
private boolean loadPage() { Collection<T> list; if( pages.size() <= pageIndex ) { return false; } list = pages.get(pageIndex); currentPage = list.iterator(); return true; }
python
def read(self): """ Read the target value Use $project aggregate operator in order to support nested objects """ result = self.get_collection().aggregate([ {'$match': {'_id': self._document_id}}, {'$project': {'_value': '$' + self._path, '_id': False}} ...
python
def GetRunlevelsNonLSB(states): """Accepts a string and returns a list of strings of numeric LSB runlevels.""" if not states: return set() convert_table = { "0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", # SysV, Gentoo, Solaris, HP-UX all ...
java
public boolean contains(Privilege p) { if (p.getName().equalsIgnoreCase(this.getName())) { return true; } Privilege[] list = getAggregatePrivileges(); for (Privilege privilege : list) { if (privilege.getName().equalsIgnoreCase(p.getName())) { ...