language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def clear_bp(cls, ctx, register): """ Clears a hardware breakpoint. @see: find_slot, set_bp @type ctx: dict( str S{->} int ) @param ctx: Thread context dictionary. @type register: int @param register: Slot (debug register) for hardware breakpoint. """...
python
def load_config_file(configuration_file=None, expand=True): """ Load a configuration file with backup directories and rotation schemes. :param configuration_file: Override the pathname of the configuration file to load (a string or :data:`None`). :param expand: :data:`Tru...
python
def create_constant(self, expression, *, verbose=True): """Append a constant to the stored list. Parameters ---------- expression : str Expression for the new constant. verbose : boolean (optional) Toggle talkback. Default is True See...
java
public static SVGPath drawFakeVoronoi(Projection2D proj, List<double[]> means) { CanvasSize viewport = proj.estimateViewport(); final SVGPath path = new SVGPath(); // Difference final double[] dirv = VMath.minus(means.get(1), means.get(0)); VMath.rotate90Equals(dirv); double[] dir = proj.fastPro...
python
def _construct_key(previous_key, separator, new_key): """ Returns the new_key if no previous key exists, otherwise concatenates previous key, separator, and new_key :param previous_key: :param separator: :param new_key: :return: a string if previous_key exists and simply passes through the ...
java
public Observable<RoleDefinitionInner> getAsync(String scope, String roleDefinitionId) { return getWithServiceResponseAsync(scope, roleDefinitionId).map(new Func1<ServiceResponse<RoleDefinitionInner>, RoleDefinitionInner>() { @Override public RoleDefinitionInner call(ServiceResponse<Role...
python
def convert(self): """Initiate one-shot conversion. The current settings are used, with the exception of continuous mode.""" c = self.config c &= (~MCP342x._continuous_mode_mask & 0x7f) # Force one-shot c |= MCP342x._not_ready_mask # Convert logger.debu...
python
def parse_datetime(value): """Attempts to parse `value` into an instance of ``datetime.datetime``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string or datetime.datetime value. """ if not value: return None elif isinstanc...
python
def hide_routemap_holder_route_map_content_set_ipv6_interface_ipv6_null0(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.S...
java
public static HttpResponse executePost(final String url, final String basicAuthUsername, final String basicAuthPassword, final String entity, final ...
java
private SemanticType checkConstant(Expr.Constant expr, Environment env) { Value item = expr.getValue(); switch (item.getOpcode()) { case ITEM_null: return Type.Null; case ITEM_bool: return Type.Bool; case ITEM_int: return Type.Int; case ITEM_byte: return Type.Byte; case ITEM_utf8: // FIXME:...
java
protected void createIndexesOnColumns(EntityMetadata m, String tableName, List<Column> columns, Class columnType) { Object pooledConnection = null; try { Cassandra.Client api = null; pooledConnection = getConnection(); api = (org.apache.cassandra.thrift.Cassandra.Clie...
python
def gpg_verify( path_to_verify, sigdata, sender_key_info, config_dir=None ): """ Verify a file on disk was signed by the given sender. @sender_key_info should be a dict with { 'key_id': ... 'key_data': ... 'app_name'; ... } Return {'status': True} on success Return {'...
java
@Override public void handlePress(CallbackQuery query) { InlineMenu lastMenu = owner.getLastMenu(); if (lastMenu != null) { executeCallback(); owner.unregister(); lastMenu.start(); } }
java
public ArrayList<String> collections() { string_vector v = ti.collections(); int size = (int) v.size(); ArrayList<String> l = new ArrayList<>(size); for (int i = 0; i < size; i++) { l.add(v.get(i)); } return l; }
java
public ConfigParseOptions appendIncluder(ConfigIncluder includer) { if (includer == null) throw new NullPointerException("null includer passed to appendIncluder"); if (this.includer == includer) return this; else if (this.includer != null) return setIncluder(t...
python
def read_gpx(xml, gpxns=None): """Parse a GPX file into a GpxModel. Args: xml: A file-like-object opened in binary mode - that is containing bytes rather than characters. The root element of the XML should be a <gpx> element containing a version attribute. GPX versions ...
java
@GET @Path("{guid}/traits") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getTraitNames(@PathParam("guid") String guid) { if (LOG.isDebugEnabled()) { LOG.debug("==> EntityResource.getTraitNames({})", guid); } AtlasPerfTracer perf = null; try { i...
python
def is_line_in_file(filename: str, line: str) -> bool: """ Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match) """ assert "\n" not in line with open(filename, "r") as file: for fileline in file: ...
python
def get_vault_query_session(self, proxy): """Gets the OsidSession associated with the vault query service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.authorization.VaultQuerySession) - a ``VaultQuerySession`` raise: NullArgument - ``proxy`` is ``null`` ...
java
private static Type findGenericInterface(Class<?> sourceClass, Class<?> targetBaseInterface) { for (int i = 0; i < sourceClass.getInterfaces().length; i++) { Class<?> inter = sourceClass.getInterfaces()[i]; if (inter == targetBaseInterface) { return sourceClass.getGeneric...
java
protected DomainObjectMatch<DomainObject> createGenMatchForInternal(List<DomainObject> domainObjects, String domainObjectTypeName) { InternalDomainAccess iAccess = this.queryExecutor.getMappingInfo().getInternalDomainAccess(); try { iAccess.loadDomainInfoIfNeeded(); List<Object> dobjs = new ArrayList<Objec...
java
public static vrid_nsip_binding[] get(nitro_service service, Long id) throws Exception{ vrid_nsip_binding obj = new vrid_nsip_binding(); obj.set_id(id); vrid_nsip_binding response[] = (vrid_nsip_binding[]) obj.get_resources(service); return response; }
python
def satisfier(self, term): # type: (Term) -> Assignment """ Returns the first Assignment in this solution such that the sublist of assignments up to and including that entry collectively satisfies term. """ assigned_term = None # type: Term for assignment in self._assi...
python
def patch_data(data, L=100, try_diag=True, verbose=False): '''Patch ``data`` (for example Markov chain output) into parts of length ``L``. Return a Gaussian mixture where each component gets the empirical mean and covariance of one patch. :param data: Matrix-like array; the points to be patche...
python
def create_time_labels(self): """Create the time labels, but don't plot them yet. Notes ----- It's necessary to have the height of the time labels, so that we can adjust the main scene. Not very robust, because it uses seconds as integers. """ min_time =...
python
def auth(self, request): """ let's auth the user to the Service :param request: request object :return: callback url :rtype: string that contains the url to redirect after auth """ request_token = super(ServiceTrello, self).auth(request) ca...
python
def read_index(group, version='1.1'): """Return the index stored in a h5features group. :param h5py.Group group: The group to read the index from. :param str version: The h5features version of the `group`. :return: a 1D numpy array of features indices. """ if version == '0.1': return np...
python
def mock_bable(monkeypatch): """ Mock the BaBLEInterface class with some controllers inside. """ mocked_bable = MockBaBLE() mocked_bable.set_controllers([ Controller(0, '11:22:33:44:55:66', '#0'), Controller(1, '22:33:44:55:66:11', '#1', settings={'powered': True, 'low_energy': True}), ...
python
def cmd_connection_type(self): """Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they s...
python
def grid_search(script: str, params: typing.Iterable[str], dry_run: bool=False) -> None: """ Build all grid search parameter configurations and optionally run them. :param script: String of command prefix, e.g. ``cxflow train -v -o log``. :param params: Iterable collection of strings in standard **cxfl...
java
public void extractValues(HashMap<String, String> values) { for (MultipleSyntaxElements l : childContainers) { l.extractValues(values); } }
python
def eqarea_magic(in_file='sites.txt', dir_path=".", input_dir_path="", spec_file="specimens.txt", samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt", plot_by="all", crd="g", ignore_tilt=False, save_plots=True, fmt="svg", contour=False, color_map="coo...
python
def get_total_irradiance(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth, dni, ghi, dhi, dni_extra=None, airmass=None, albedo=.25, surface_type=None, model='isotropic', model_perez='al...
java
@SuppressWarnings("unchecked") public <T extends XPathBuilder> T setContainer(WebLocator container) { this.container = container; return (T) this; }
java
public static String getDefaultDesignPath(Component component) { String className = component.getClass().getName(); String designPath = className.replace(".", "/") + ".html"; return designPath; }
python
def parse_relationship(document, xmlcontent, rel_type): """Parse relationship document. Relationships hold information like external or internal references for links. Relationships are placed in file '_rels/document.xml.rels'. """ doc = etree.fromstring(xmlcontent) for elem in doc: i...
java
public static double truncate(double value, int places) { if (places < 0) { throw new IllegalArgumentException(); } long factor = (long) java.lang.Math.pow(10, places); value = value * factor; long tmp = (long) value; return (double) tmp / factor; }
java
public boolean enlist(BeanO beanO) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "enlist : " + beanO); ensureActive(); BeanO oldBeanO = ivBeanOs.put(beanO.beanId, beanO); if (oldBeanO == null) ...
python
def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._one...
java
public Action build(Class<?> clazz) { Action action = new Action(); String className = clazz.getName(); Profile profile = profileService.getProfile(className); org.beangle.struts2.annotation.Action an = clazz .getAnnotation(org.beangle.struts2.annotation.Action.class); StringBuilder sb = new...
java
public static Statement close(Statement stmt, Logger logExceptionTo) { return close(stmt, logExceptionTo, null); }
java
public static Table tablePercents(Table table, CategoricalColumn<?> column1, CategoricalColumn<?> column2) { Table xTabs = counts(table, column1, column2); return tablePercents(xTabs); }
python
def visit_index(self, node, parent): """visit a Index node by returning a fresh instance of it""" newnode = nodes.Index(parent=parent) newnode.postinit(self.visit(node.value, newnode)) return newnode
python
def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: ba...
python
def _version_less_than_or_equal_to(self, v1, v2): """ Returns true if v1 <= v2. """ # pylint: disable=no-name-in-module, import-error from distutils.version import LooseVersion return LooseVersion(v1) <= LooseVersion(v2)
java
public static long factorial(int n) { if (n < 0 || n > MAX_LONG_FACTORIAL) { throw new IllegalArgumentException("Argument must be in the range 0 - 20."); } long factorial = 1; for (int i = n; i > 1; i--) { factorial *= i; } retu...
java
public static <O> KNNQuery<O> getKNNQuery(Relation<O> relation, DistanceFunction<? super O> distanceFunction, Object... hints) { final DistanceQuery<O> distanceQuery = relation.getDistanceQuery(distanceFunction, hints); return relation.getKNNQuery(distanceQuery, hints); }
python
def _NotesSlideShapeFactory(shape_elm, parent): """ Return an instance of the appropriate shape proxy class for *shape_elm* on a notes slide. """ tag_name = shape_elm.tag if tag_name == qn('p:sp') and shape_elm.has_ph_elm: return NotesSlidePlaceholder(shape_elm, parent) return BaseSh...
python
def _step_envs(self, action): """Perform step(action) on environments and update initial_frame_stack.""" self._frame_counter += 1 real_env_step_tuple = self.real_env.step(action) sim_env_step_tuple = self.sim_env.step(action) self.sim_env.add_to_initial_stack(real_env_step_tuple[0]) return self....
python
def _create_thumbnail(self, model_instance, thumbnail, image_name): """ Resizes and saves the thumbnail image """ thumbnail = self._do_resize(thumbnail, self.thumbnail_size) full_image_name = self.generate_filename(model_instance, image_name) thumbnail_filename = _get_thu...
java
public static Set<SelectorName> nameSetFrom( SelectorName name ) { if (name == null) return Collections.emptySet(); return Collections.singleton(name); }
java
public static void assertTree(int rootType, String preorder, ParseResults parseResults) { assertTree(rootType, preorder, parseResults.getTree()); }
python
def getRenderModelThumbnailURL(self, pchRenderModelName, pchThumbnailURL, unThumbnailURLLen): """Returns the URL of the thumbnail image for this rendermodel""" fn = self.function_table.getRenderModelThumbnailURL peError = EVRRenderModelError() result = fn(pchRenderModelName, pchThumbnai...
java
public int getInt(String key, int default_) { Object o = get(key); return o instanceof Number ? ((Number) o).intValue() : default_; }
java
public static <T> T[] noNullElements(final T[] array, final String message) { return INSTANCE.noNullElements(array, message); }
python
def stop_consuming(self): """Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consum...
java
public static <K, V> Stream<Entry<K, V>> getEntryStreamWithFilter( Map<K, V> map, Predicate<? super Entry<K, V>> predicate) { return buildEntryStream(map).filter(predicate); }
python
def dicts_equal(d1, d2): """ Perform a deep comparison of two dictionaries Handles: - Primitives - Nested dicts - Lists of primitives """ # check for different sizes if len(d1) != len(d2): return False # check for different keys for k in d1: if k not in d2: return Fa...
java
protected int tasksToPreempt(JobInProgress job, TaskType type, long curTime) { JobInfo info = infos.get(job); if (info == null || poolMgr.isMaxTasks(info.poolName, type)) return 0; String pool = info.poolName; long minShareTimeout = poolMgr.getMinSharePreemptionTimeout(pool); long fairShareTimeout =...
python
def krai_to_raw(self, amount): """ Multiply an krai amount by the krai ratio. :param amount: Amount in krai to convert to raw :type amount: int :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.krai_to_raw(amount=1) 1000000000000000000000000000 """ ...
java
public void getAllTitleID(Callback<List<Integer>> callback) throws NullPointerException { gw2API.getAllTitleIDs().enqueue(callback); }
python
def get_selected_tab(self): """Returns the tab specific by the GET request parameter. In the event that there is no GET request parameter, the value of the query parameter is invalid, or the tab is not allowed/enabled, the return value of this function is None. """ selec...
java
private void resolveAllUnresolvedBindings(GinjectorBindings collection) throws UnableToCompleteException { // Create known/explicit bindings before descending into children. This ensures that they are // available to any children that may need to depend on them. createBindingsForFactories(collection...
python
def train_phrases(paths, out='data/bigram_model.phrases', tokenizer=word_tokenize, **kwargs): """ Train a bigram phrase model on a list of files. """ n = 0 for path in paths: print('Counting lines for {0}...'.format(path)) n += sum(1 for line in open(path, 'r')) print('Processing...
python
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None): """ Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_mi...
python
def load_config(cls): """ Load global and local configuration files and update if needed.""" config_file = os.path.expanduser(cls.home_config) global_conf = cls.load(config_file, 'global') cls.load(cls.local_config, 'local') # update global configuration if needed cls.upd...
python
def mapping_ref(self, es_mappings): """ Retruns a dictionary of mappings and the fiels names in dot notation args: mappings: es mapping defitions to parse """ new_map = {} for key, value in es_mappings.items(): for sub_key, sub_value in...
python
def reduce_formula(sym_amt, iupac_ordering=False): """ Helper method to reduce a sym_amt dict to a reduced formula and factor. Args: sym_amt (dict): {symbol: amount}. iupac_ordering (bool, optional): Whether to order the formula by the iupac "electronegativity" series, defined i...
python
def populateFromRow(self, continuousSetRecord): """ Populates the instance variables of this ContinuousSet from the specified DB row. """ self._filePath = continuousSetRecord.dataurl self.setAttributesJson(continuousSetRecord.attributes)
java
public void setStatusMapping(Map<String, Integer> statusMapping) { Assert.notNull(statusMapping, "StatusMapping must not be null"); this.statusMapping = new HashMap<>(statusMapping); }
python
def get_slice(self, start=None, end=None): """ Return a new list of text fragments, indexed from start (included) to end (excluded). :param int start: the start index, included :param int end: the end index, excluded :rtype: :class:`~aeneas.textfile.TextFile` """...
python
def _resolve(self, spec): """Attempt resolving cache URIs when a remote spec is provided. """ if not spec.remote: return spec try: resolved_urls = self._resolver.resolve(spec.remote) if resolved_urls: # keep the bar separated list of URLs convention return CacheSpec(local=...
java
private Entity createOntologyTerm(OWLClass ontologyTermClass) { String ontologyTermIRI = ontologyTermClass.getIRI().toString(); String ontologyTermName = loader.getLabel(ontologyTermClass); OntologyTerm ontologyTerm = ontologyTermFactory.create(); ontologyTerm.setId(idGenerator.generateId()); ontolo...
java
final DAO loadExternalDAO(String classSimpleName) { ServiceLoader<DAO> daoLoader = ServiceLoader.load(DAO.class, Para.getParaClassLoader()); for (DAO dao : daoLoader) { if (dao != null && classSimpleName.equalsIgnoreCase(dao.getClass().getSimpleName())) { return dao; } } return null; }
java
public static MomentInterval parse( String text, ChronoParser<Moment> parser, String intervalPattern ) throws ParseException { return IntervalParser.parsePattern(text, MomentIntervalFactory.INSTANCE, parser, intervalPattern); }
java
private static Map<Tag, String> createTags(String ufsName, UfsStatus status) { Map<Tag, String> tagMap = new HashMap<>(); tagMap.put(Tag.UFS, ufsName); tagMap.put(Tag.OWNER, status.getOwner()); tagMap.put(Tag.GROUP, status.getGroup()); tagMap.put(Tag.MODE, String.valueOf(status.getMode())); if (...
java
@SuppressWarnings("unchecked") public List<Failure> validate(Validate v, ResourceBundle rb) { if (v != null && Key.MANAGED_CONNECTION == v.getKey() && ManagedConnection.class.isAssignableFrom(v.getClazz())) { boolean error = false; ValidateObject vo = null; ...
java
protected boolean areBranchCompatible(PlanNode plan1, PlanNode plan2) { if (plan1 == null || plan2 == null) { throw new NullPointerException(); } // if there is no open branch, the children are always compatible. // in most plans, that will be the dominant case if (this.hereJoinedBranches == null || thi...
python
def _execute(self, method_function, method_name, resource, **params): """ Generic TeleSign REST API request handler. :param method_function: The Requests HTTP request function to perform the request. :param method_name: The HTTP method name, as an upper case string. :param resou...
java
public void addPoi(final Poi BLIP) { if (pois.keySet().contains(BLIP.getName())) { updatePoi(BLIP.getName(), BLIP.getLocation()); } else { pois.put(BLIP.getName(), BLIP); } checkForBlips(); }
java
@Override public final void prepareNarInfo(final File baseDir, final MavenProject project, final NarInfo narInfo, final AbstractNarMojo mojo) throws MojoExecutionException { if (getNoArchDirectory(baseDir, project.getArtifactId(), project.getVersion()).exists()) { narInfo.setNar(null, NarConstants.NAR...
python
def conf_budget(self, budget): """ Set limit on the number of conflicts. """ if self.minisat: pysolvers.minisat22_cbudget(self.minisat, budget)
java
@Override @FFDCIgnore({ RuntimeException.class }) public Object invoke(Exchange exchange, final Object serviceObject, Method m, List<Object> params) { //bean customizer.... final Object realServiceObject; final OperationResourceInfo ori = exchange.get(OperationResourceInfo.class); ...
python
def _set_bin_view(self, session): """Sets the underlying bin view to match current view""" if self._bin_view == COMPARATIVE: try: session.use_comparative_bin_view() except AttributeError: pass else: try: session....
python
def print_solution(model, solver): """Prints the solution associated with solver. If solver has already had Solve() called on it, prints the solution. This includes each variable and its assignment, along with the objective function and its optimal value. If solver has not had Solve() called on it, or there ...
java
public V get(SerializationService serializationService) { if (!valueExists) { // it's ok to deserialize twice in case of race assert serializationService != null; value = serializationService.toObject(serializedValue); valueExists = true; } return ...
java
public static <T> void verify(Vertex<T> vertex) throws CyclicDependencyException { // We need a list of vertices that contains the entire graph, so build it. List<Vertex<T>> vertices = new ArrayList<Vertex<T>>(); addDependencies(vertex, vertices); verify(vertices); }
python
def __get_pid_and_tid(self): "Internally used by get_pid() and get_tid()." self.dwThreadId, self.dwProcessId = \ win32.GetWindowThreadProcessId(self.get_handle())
java
public DoublePoint Multiply(DoublePoint point1, DoublePoint point2) { DoublePoint result = new DoublePoint(point1); result.Multiply(point2); return result; }
python
def send_caught_exception_stack_proceeded(self, thread): """Sends that some thread was resumed and is no longer showing an exception trace. """ thread_id = get_thread_id(thread) int_cmd = InternalSendCurrExceptionTraceProceeded(thread_id) self.post_internal_command(int_cmd, threa...
python
def enter_history(self): """ Display the history. """ app = get_app() app.vi_state.input_mode = InputMode.NAVIGATION def done(f): result = f.result() if result is not None: self.default_buffer.text = result app.vi_stat...
java
public com.squareup.okhttp.Call getAlliancesAllianceIdIconsAsync(Integer allianceId, String datasource, String ifNoneMatch, final ApiCallback<AllianceIconsResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getAlliancesAllianceIdIconsValidateBeforeCall(allianceId, datasource, ...
java
public void add(String name,String value) throws IllegalArgumentException { if (value==null) throw new IllegalArgumentException("null value"); FieldInfo info=getFieldInfo(name); Field field=getField(info,false); Field last=null; if (field!=null) ...
java
synchronized void updateValue(long value) { if (value != currentValue) { currentValue = value; IOEvent evt = new IOEvent(this); getDevice().pinChanged(evt); // the device listeners receive the event first for (PinEventListener listener : listeners) { // then pin l...
python
def rarity(brands, exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.""" rarity = compute_rarity_scores(exemplars) scores = {} for brand, followers in br...
python
def get_encoded_text(container, xpath): """Return text for element at xpath in the container xml if it is there. Parameters ---------- container : xml.etree.ElementTree.Element The element to be searched in. xpath : str The path to be looked for. Returns ------- result...
java
public boolean checkAccess(String path, boolean readOnly) { final FileServiceMXBean fileService = getFileService(); if (readOnly) { //we can read from both the read and write list return (FileServiceUtil.isPathContained(fileService.getReadList(), path) || FileServiceUtil.isPathCo...
java
protected int StackOpp() { if (key == "ifelse") return -3; if (key == "roll" || key == "put") return -2; if (key == "callsubr" || key == "callgsubr" || key == "add" || key == "sub" || key == "div" || key == "mul" || key == "drop" || key == "and" || key == "or" || key == "eq") return -1; if (key...
java
public DescribeTransitGatewayRouteTablesResult withTransitGatewayRouteTables(TransitGatewayRouteTable... transitGatewayRouteTables) { if (this.transitGatewayRouteTables == null) { setTransitGatewayRouteTables(new com.amazonaws.internal.SdkInternalList<TransitGatewayRouteTable>(transitGatewayRouteTab...