language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public GetCrawlerMetricsRequest withCrawlerNameList(String... crawlerNameList) { if (this.crawlerNameList == null) { setCrawlerNameList(new java.util.ArrayList<String>(crawlerNameList.length)); } for (String ele : crawlerNameList) { this.crawlerNameList.add(ele); ...
python
def _remove_ordered_from_queue(self, last_caught_up_3PC=None): """ Remove any Ordered that the replica might be sending to node which is less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is passed else remove all ordered, needed in catchup """ to_remove =...
python
def clean_base_uri(url): """ This will clean up the url so that it is in the form: https://<SUB_DOMAIN>.eagleeyenetworks.com/ :param url: str of the url :return: str of the clean base url """ if url is None: return url if not '//' in url: ...
python
def from_tokens(cls, path:PathOrStr, trn_tok:Collection[Collection[str]], trn_lbls:Collection[Union[int,float]], val_tok:Collection[Collection[str]], val_lbls:Collection[Union[int,float]], vocab:Vocab=None, tst_tok:Collection[Collection[str]]=None, classes:Collection[Any]=None, max_voc...
java
public void buildMethodsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters.get(VisibleMemberMap.Kind.METHODS); VisibleMemberMap visibleMemberMap = getVisibleMemberMap(VisibleMemberMap.Kind.METHODS); addSummary(write...
java
public Date getExpirationDate(ApplicationDefinition appDef, String shard) { checkServiceState(); return m_olap.getExpirationDate(appDef, shard); }
python
def excel_to_bytes(wb: Workbook) -> bytes: """ Obtain a binary version of an :class:`openpyxl.Workbook` representation of an Excel file. """ memfile = io.BytesIO() wb.save(memfile) return memfile.getvalue()
java
private static ParameterizedType newParameterizedType(final Class<?> base, Type... args) throws Exception { return Types.newParameterizedType(base, args); }
python
def read(self, entity=None, attrs=None, ignore=None, params=None): """Deal with different named data returned from the server """ if attrs is None: attrs = self.read_json() attrs['override'] = attrs.pop('override?') attrs['unlimited'] = attrs.pop('unlimited?') ...
java
public void marshall(CreateWorkspacesRequest createWorkspacesRequest, ProtocolMarshaller protocolMarshaller) { if (createWorkspacesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createWork...
python
def add_derived_quantity(self, derived_quantity, func, *quantities): """ Add a derived quantify modifier. Parameters ---------- derived_quantity : str name of the derived quantity to be added func : callable function to calculate the derived quan...
python
def from_first_relation(cls, vertex0, vertex1): """Intialize a fresh match based on the first relation""" result = cls([(vertex0, vertex1)]) result.previous_ends1 = set([vertex1]) return result
java
protected void convertNeighbors(DBIDRange ids, DBIDRef ix, boolean square, KNNList neighbours, DoubleArray dist, IntegerArray ind) { for(DoubleDBIDListIter iter = neighbours.iter(); iter.valid(); iter.advance()) { if(DBIDUtil.equal(iter, ix)) { continue; // Skip query point } double d = it...
java
private static String formatAddress6(int[] hexRepresentation){ if(hexRepresentation == null){ throw new NullPointerException(); } if(hexRepresentation.length != IPV6_LEN){ throw new IllegalArgumentException(); } StringBuilder stringBuilder = new StringBuilder(); ...
java
private String[] extractSegId(StringBuffer sb) { String[] ret = new String[]{"", ""}; if (sb.length() > 1) { int startpos = 0; char ch = sb.charAt(0); if (ch == '+' || ch == ':' || ch == '\'') startpos++; // erste DEG extrahieren ...
python
def execute(self): """ This function Executes the program with set arguments. """ prog_cmd = self.get_cmd().strip() if prog_cmd == '': self.status = 'Failure' debug.log("Error: No program to execute for %s!"%self.name) debug.log(("Could not combine path and arguments into cm...
python
def _is_under_root(self, full_path): """Guard against arbitrary file retrieval.""" if (path.abspath(full_path) + path.sep)\ .startswith(path.abspath(self.root) + path.sep): return True else: return False
java
private Node createUnstubCall(Node functionNode, int stubId) { return astFactory .createCall( // We can't look up the type of the stub creating method, because we add its // definition after type checking. astFactory.createNameWithUnknownType(UNSTUB_METHOD_NAME), ...
java
public void fixupVariables(java.util.Vector vars, int globalsSize) { super.fixupVariables(vars, globalsSize); m_expr.fixupVariables(vars, globalsSize); }
java
public TrieNode matchPredictor(String search) { TrieNode cursor = matchEnd(search); if (cursor.getNumberOfChildren() > 0) { return cursor; } String string = cursor.getString(); if (string.isEmpty()) return null; return matchPredictor(string.substring(1)); }
java
public void push(String symbol) { long now = System.currentTimeMillis(); if (!symbol.equals(lastSymbol) || (now - lastActivity > interdigitInterval)) { lastActivity = now; lastSymbol = symbol; detectorImpl.fireEvent(symbol); } else ...
java
public static boolean isXMLNameStart(int codepoint) { if (codepoint >= Character.codePointAt("A", 0) && codepoint <= Character.codePointAt("Z", 0)) { return true; } else if (codepoint == Character.codePointAt("_", 0)) { return true; } else if (codepoint >= Character.codePointAt("a", 0) && codepoint...
java
public static <T extends ResourceId> Builder<T> newBuilder(Status status) { return new Builder<T>().setStatus(status); }
python
def approx_equals(self, other, atol): """Return ``True`` if ``other`` is equal to this set up to ``atol``. Parameters ---------- other : Object to be tested. atol : float Maximum allowed difference in maximum norm between the interval endpoint...
python
def check_dir(directory, newly_created_files): """Returns list of files that fail the check.""" header_parse_failures = [] for root, dirs, files in os.walk(directory): for f in files: if f.endswith('.py') and os.path.basename(f) != '__init__.py': filename = os.path.join(root, f) try: ...
java
public IfcStructuralSurfaceActivityTypeEnum createIfcStructuralSurfaceActivityTypeEnumFromString( EDataType eDataType, String initialValue) { IfcStructuralSurfaceActivityTypeEnum result = IfcStructuralSurfaceActivityTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( ...
python
def grow_slice(slc, size): """ Grow a slice object by 1 in each direction without overreaching the list. Parameters ---------- slc: slice slice object to grow size: int list length Returns ------- slc: slice extended slice """ return slice(max(0, s...
python
def battery_percent(self): """Get batteries capacity percent.""" if not batinfo_tag or not self.bat.stat: return [] # Init the bsum (sum of percent) # and Loop over batteries (yes a computer could have more than 1 battery) bsum = 0 for b in self.bat.stat: ...
java
public void setXoaOset(Integer newXoaOset) { Integer oldXoaOset = xoaOset; xoaOset = newXoaOset; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.OBP__XOA_OSET, oldXoaOset, xoaOset)); }
java
public static <S extends Storable> OrderedProperty<S> get(StorableProperty<S> property, Direction direction) { return get(ChainedProperty.get(property), direction); }
java
public final void setDialogScrollableArea(@Nullable final Area top, @Nullable final Area bottom) { this.dialogScrollableArea = ScrollableArea.create(top, bottom); }
python
def list_datastores(call=None): ''' Returns a list of data stores on OpenNebula. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt-cloud -f list_datastores opennebula ''' if call == 'action': raise SaltCloudSystemExit( 'The list_datastores func...
java
@Override public boolean save(String content, Charset charset, String location) { File file = new File(location); try { Files.writeToFile(file, content, charset); } catch (IOException ex) { return false; } return true; }
java
private boolean shouldStackButtons() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); String key = getString(R.string.stack_buttons_preference_key); boolean defaultValue = getResources().getBoolean(R.bool.stack_...
java
private void appendDateTime(long epochMillis) { date.setTime(epochMillis); calendar.setTime(date); appendDate(); write(' '); appendTime(); }
python
def transform_obs(self, obs): """Render some SC2 observations into something an agent can handle.""" empty = np.array([], dtype=np.int32).reshape((0, 7)) out = named_array.NamedDict({ # Fill out some that are sometimes empty. "single_select": empty, "multi_select": empty, "build_que...
java
private void _handleMultiValues(ArrayList<String> values, String key, String command) { if (key == null) return; if (values == null || values.isEmpty()) { _generateEmptyMultiValueError(key); return; } ValidationResult vr; // validate the key vr ...
python
def make_script_sig(stack_script, redeem_script): ''' str, str -> bytearray ''' stack_script += ' {}'.format( serialization.hex_serialize(redeem_script)) return serialization.serialize(stack_script)
python
def _check_requirements(self): """ Check if VPCS is available with the correct version. """ path = self._vpcs_path() if not path: raise VPCSError("No path to a VPCS executable has been set") # This raise an error if ubridge is not available self.ubri...
python
def _set_soo(self, v, load=False): """ Setter method for soo, mapped from YANG variable /rbridge_id/route_map/content/set/extcommunity/soo (container) If this variable is read-only (config: false) in the source YANG file, then _set_soo is considered as a private method. Backends looking to populate ...
java
public void add(int position, SoundCloudTrack track) { if (mCurrentTrackIndex == -1) { mCurrentTrackIndex = 0; } mSoundCloudPlaylist.addTrack(position, track); }
java
@Override public EClass getIfcElectricConductanceMeasure() { if (ifcElectricConductanceMeasureEClass == null) { ifcElectricConductanceMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(801); } return ifcElectricConductanceMeasureEClass; }
python
def get_default_config(self): """ Return default config. path: Graphite path output ksm_path: location where KSM kernel data can be found """ config = super(KSMCollector, self).get_default_config() config.update({ 'path': 'ksm', 'ksm_path'...
python
def listar_por_grupo_equipamento(self, id_grupo_equipamento): """Lista todos os direitos de grupos de usuário em um grupo de equipamento. :param id_grupo_equipamento: Identificador do grupo de equipamento para filtrar a pesquisa. :return: Dicionário com a seguinte estrutura: :: ...
python
async def SetMetricCredentials(self, creds): ''' creds : typing.Sequence[~ApplicationMetricCredential] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Application', request='SetMetricCr...
python
def insert(self, **data): """ Insert the passed +data+ into the table. Raises Invalid if a where clause is present (i.e. no INSERT INTO table WHERE) """ if self.where_clause: raise Invalid("Cannot insert with 'where' clause.") # Ensure that order is preserved ...
java
public void marshall(AlgorithmValidationProfile algorithmValidationProfile, ProtocolMarshaller protocolMarshaller) { if (algorithmValidationProfile == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(a...
java
public DatastaxMapperBuilder<T> addMapping(final ColumnDefinitions metaData) { for (int i = 1; i <= metaData.size(); i++) { addMapping(metaData.getName(i), i, metaData.getType(i), new Object[0]); } return this; }
java
@Override public void accept(final double value) { super.accept(value); _min = Math.min(_min, value); _max = Math.max(_max, value); _sum.add(value); }
java
public List<LocalDateTime> top(int n) { List<LocalDateTime> top = new ArrayList<>(); long[] values = data.toLongArray(); LongArrays.parallelQuickSort(values, DescendingLongComparator.instance()); for (int i = 0; i < n && i < values.length; i++) { top.add(PackedLocalDateTime.a...
java
private Object getCursor(Object implObject, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled(...
java
public void setFooterDivider(Drawable drawable) { mFooterDivider = drawable; if (drawable != null) { mFooterDividerHeight = drawable.getIntrinsicHeight(); } else { mFooterDividerHeight = 0; } mContentView.setWillNotDraw(drawable == null); mContentV...
java
public static <T> boolean addAll(Collection<T> target, Iterable<? extends T> iterable) { if (iterable instanceof Collection) { return target.addAll((Collection<? extends T>) iterable); } return Iterators.addAll(target, iterable.iterator()); }
java
protected void setField(Object component, Field field, Object proxy) { try { checkAccessabilityOfField(field); field.set(component, proxy); } catch (Exception e) { throw new RuntimeException("Bumm", e); } }
python
def plot_line_loading_diff(networkA, networkB, timestep=0): """ Plot difference in line loading between two networks (with and without switches) as color on lines Positive values mean that line loading with switches is bigger than without Plot switches as small dots Parameters --------...
python
def get_page_content(id): """Return XHTML content of a page. Parameters: - id: id of a Confluence page. """ data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage")) return data["body"]["storage"]["value"]
java
public boolean upload(WebLocator el, String filePath) { return executor.browse(el) && executor.upload(filePath); }
java
private AuthOutcome secureLevelControl(Account operatedAccount, String resourceAccountSid, UserIdentityContext userIdentityContext) { Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = null; if (operatingAccount != null) ope...
python
def connect_to_queues(region=None, public=True): """Creates a client for working with Queues.""" return _create_client(ep_name="queues", region=region, public=public)
python
def compute_jaccard_index(x_set, y_set): """Return the Jaccard similarity coefficient of 2 given sets. Args: x_set (set): first set. y_set (set): second set. Returns: float: Jaccard similarity coefficient. """ if not x_set or not y_set: return 0.0 intersection...
python
def list_versions(self, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None): """ List version objects within a bucket. This returns an instance of an VersionedBucketListResultSet that automatically handles all of the result paging, etc. from...
python
def get_image(vm_): ''' Return the image object to use ''' vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode( 'ascii', 'salt-cloud-force-ascii' ) images = avail_images() for key, value in six.iteritems(images): if vm_image and vm_image in (images[key]['...
python
def purposes_for_layer(layer_geometry_key): """Get purposes of a layer geometry id. :param layer_geometry_key: The geometry id :type layer_geometry_key: str :returns: List of suitable layer purpose. :rtype: list """ return_value = [] for layer_purpose in layer_purposes: layer_g...
java
public static void main(String[] args) throws IOException { int argIdx = 0; // TODO: Proper argument parsing: -t <type> -c <compression> int type = args.length > argIdx + 1 ? Integer.parseInt(args[argIdx++]) : -1; int compression = args.length > argIdx + 1 ? Integer.parseInt(args[argIdx...
java
public void setLogHandler(String id, LogHandler ref) { if (id != null && ref != null) { logHandlerServices.put(id, ref); } }
python
def goes_requires(self, regs): """ Returns whether any of the goes_to block requires any of the given registers. """ if len(self) and self.mem[-1].inst == 'call' and self.mem[-1].condition_flag is None: for block in self.calls: if block.is_used(regs, 0): ...
java
public static HashMap<String,String> parse(String args){ HashMap<String,String> map = new HashMap<>(); if (args != null){ String[] split = args.split(";"); for (String nameValuePair : split) { String[] nameValue = nameValuePair.split("="); if (nameValue.length == 2){ map.put(nameValue[0].to...
java
public final AbstractItem findFirstMatching(Filter filter) throws MessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "findFirstMatching", filter); AbstractItem item = _references().findFirstMatching(filter); if (TraceComponent.isA...
java
public JSONArray optJSONArray(String name) { Object object = opt(name); return object instanceof JSONArray ? (JSONArray) object : null; }
python
def cluster_over_time(stat, time, window, argmax=numpy.argmax): """Cluster generalized transient events over time via maximum stat over a symmetric sliding window Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time: numpy.ndarray time to use for c...
java
public MuServer start() { if (httpPort < 0 && httpsPort < 0) { throw new IllegalArgumentException("No ports were configured. Please call MuServerBuilder.withHttpPort(int) or MuServerBuilder.withHttpsPort(int)"); } ServerSettings settings = new ServerSettings(minimumGzipSize, maxHead...
python
def get_vcl_html(self, service_id, version_number, name): """Get the uploaded VCL for a particular service and version with HTML syntax highlighting.""" content = self._fetch("/service/%s/version/%d/vcl/%s/content" % (service_id, version_number, name)) return content.get("content", None)
python
def tolist(self): """ Return the array as a list of rows. Each row is a `dict` of values. Facilitates inserting data into a database. .. versionadded:: 0.3.1 Returns ------- quotes : list A list in which each entry is a dictionary representing ...
python
def get_android_id(self) -> str: '''Show Android ID.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'settings', 'get', 'secure', 'android_id') return output.strip()
python
def setTopRight(self, loc): """ Move this region so its top right corner is on ``loc`` """ offset = self.getTopRight().getOffset(loc) # Calculate offset from current top right return self.setLocation(self.getTopLeft().offset(offset)) # Move top left corner by the same offset
python
def _ParseTimeRange(self, timerange): """Parses a timerange argument and always returns non-None timerange.""" if timerange is None: timerange = (None, None) from_time, to_time = timerange if not from_time: from_time = rdfvalue.RDFDatetime().FromSecondsSinceEpoch(0) if not to_time: ...
java
private static ILigand[] getLigands(IAtom atom, IAtomContainer container, IAtom exclude) { List<IAtom> neighbors = container.getConnectedAtomsList(atom); ILigand[] ligands = new ILigand[neighbors.size() - 1]; int i = 0; for (IAtom neighbor : neighbors) { if (!neighbor.equa...
java
public void deregisterConsumerSetMonitor(ConnectionImpl connection, ConsumerSetChangeCallback callback) throws SINotPossibleInCurrentConfigurationException { if (tc.isEntryEnabled()) SibTr.entry( tc, "deregisterConsumerSetMonitor", ...
java
public static <T,V extends Object> void type(Collection<V> valueColl, Class<T> type) { for(V value: valueColl) type(value, type); } //------- Numerical checks ---------------------------------------------------------------------------- //------- Integer -------------------------------- /** * Checks if ...
python
def remote_profile(script, argv, profiler_factory, interval, spawn, signum, pickle_protocol, endpoint, verbose): """Launch a server to profile continuously. The default endpoint is 127.0.0.1:8912. """ filename, code, globals_ = script sys.argv[:] = [filename] + list(argv) # c...
python
def notify_thread_not_alive(self, thread_id, use_lock=True): """ if thread is not alive, cancel trace_dispatch processing """ if self.writer is None: return with self._lock_running_thread_ids if use_lock else NULL: if not self._enable_thread_notifications: ...
python
def _gen_te_xref(self, expr: Union[ShExJ.tripleExpr, ShExJ.tripleExprLabel]) -> None: """ Generate the triple expression map (te_id_map) :param expr: root triple expression """ if expr is not None and not isinstance_(expr, ShExJ.tripleExprLabel) and 'id' in expr and expr.id is ...
java
public AlphabeticIndex<V> addLabels(UnicodeSet additions) { initialLabels.addAll(additions); buckets = null; return this; }
java
public SourceBuilder add(String fmt, Object... args) { TemplateApplier.withParams(args).onText(source::append).onParam(this::add).parse(fmt); return this; }
python
def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs): """ Simplified add for the most common options. Parameters: name (str): Name of the library agent (str): Example com.plexapp.agents.imdb type (str): mo...
java
@SuppressWarnings({ "rawtypes", "unchecked" }) // The alternative would be to change the TopologolyLayerCallback.send() to take List<? extends Command> private void execute(final ListCommand command) { getMetaData(command); final Queue<ListCommand> log = metaData.getUnapprovedCommands(); ...
java
public void execute () throws MojoExecutionException, MojoFailureException { final GrammarInfo [] grammarInfos = scanForGrammars (); if (grammarInfos == null) { getLog ().info ("Skipping non-existing source directory: " + getSourceDirectory ()); return; } else if (grammarInfos.l...
python
def _is_related(parent_entry, child_entry): '''This function checks if a child entry is related to the parent entry. This is done by comparing the reference and sequence numbers.''' if parent_entry.header.mft_record == child_entry.header.base_record_ref and \ parent_entry.header.seq_n...
java
public static org.osmdroid.views.overlay.Polygon addPolygonToMap( MapView map, org.osmdroid.views.overlay.Polygon polygon, PolygonOptions options) { if (options!=null) { polygon.setFillColor(options.getFillColor()); polygon.setTitle(options.getTitle()); polyg...
python
def running(name, restart=False, path=None): ''' .. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named containe...
java
public boolean compatible() { if (tc.isEntryEnabled()) Tr.entry(tc, "compatible", this); if (tc.isEntryEnabled()) Tr.exit(tc, "compatible", new Boolean(_compatible)); return _compatible; }
python
def __deserialize_primitive(self, data, klass): """ Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: ...
java
public static Intent pickContact(String scope) { Intent intent; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ECLAIR) { intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI); } else { intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://com.androi...
java
public static Replacer makeTable(String... pairs) { if(pairs == null || pairs.length < 2) return new Replacer(Pattern.compile("$"), new DummySubstitution("")); TableSubstitution tab = new TableSubstitution(pairs); StringBuilder sb = new StringBuilder(128); sb.append("(?>"...
python
def msg2subjective(msg, processor, subject, **config): """ Return a human-readable text representation of a dict-like fedmsg message from the subjective perspective of a user. For example, if the subject viewing the message is "oddshocks" and the message would normally translate into "oddshocks comment...
java
public void clear() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Clearing this header handler: " + this); } this.num_items = 0; this.values.clear(); this.genericValues.clear(); }
python
def execute(self, args): """Executes the configured cmd passing args in one or more rounds xargs style. :param list args: Extra arguments to pass to cmd. """ all_args = list(args) try: return self._cmd(all_args) except OSError as e: if errno.E2BIG == e.errno: args1, args2 = ...
python
def index(self, pkt_num): """Return datagram index.""" int_check(pkt_num) for counter, datagram in enumerate(self.datagram): if pkt_num in datagram.index: return counter return None
java
private LocalEnvironment joinEnvironments(Context... contexts) { // Context head = contexts[0]; GlobalEnvironment global = head.getEnvironment().getParent(); HashSet<WyilFile.Decl.Variable> modified = new HashSet<>(); HashSet<WyilFile.Decl.Variable> deleted = new HashSet<>(); Map<WyilFile.Decl.Variable, Wya...
python
def random_word(tokens, tokenizer): """ Masking some random tokens for Language Model task with probabilities as in the original BERT paper. :param tokens: list of str, tokenized sentence. :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here) :return: (list of str, list...