language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_sync_binding_cmds(self, switch_bindings, expected_bindings): """Returns the list of commands required to synchronize ACL bindings 1. Delete any unexpected bindings 2. Add any missing bindings """ switch_cmds = list() # Update any necessary switch interface ACLs ...
python
def parse_rst_index(rstpth): """ Parse the top-level RST index file, at `rstpth`, for the example python scripts. Returns a list of subdirectories in order of appearance in the index file, and a dict mapping subdirectory name to a description. """ pthidx = {} pthlst = [] with open(...
java
public String updateRunner(String oldRunnerName, Vector<Object> runnerParams) { return serviceDelegator.updateRunner(oldRunnerName, runnerParams); }
java
public UUID getMachineId() throws NoSuchAlgorithmException, SocketException, UnknownHostException { return calculator.getMachineId(useNetwork, useHostName, useArchitecture); }
java
public final DRL5Expressions.operator_key_return operator_key() throws RecognitionException { DRL5Expressions.operator_key_return retval = new DRL5Expressions.operator_key_return(); retval.start = input.LT(1); Token id=null; try { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:771:3: ({.....
python
def get_wordlist(language, word_source): """ Takes in a language and a word source and returns a matching wordlist, if it exists. Valid languages: ['english'] Valid word sources: ['bip39', 'wiktionary', 'google'] """ try: wordlist_string = eval(language + '_words_' + word_sou...
python
def strlify(a): ''' Used to turn hexlify() into hex string. Does nothing in Python 2, but is necessary for Python 3, so that all inputs and outputs are always the same encoding. Most of the time it doesn't matter, but some functions in Python 3 brick when they get bytes instead of a string, so...
java
public long alignOnMagic3(InputStream is) throws IOException { long bytesSkipped = 0; byte lookahead[] = new byte[3]; int keep = 0; while(true) { if(keep == 2) { lookahead[0] = lookahead[1]; lookahead[1] = lookahead[2]; } else if(keep == 1) { lookahead[0] = lookahead[2]; } int amt...
java
public void marshall(Output output, ProtocolMarshaller protocolMarshaller) { if (output == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(output.getAudioDescriptions(), AUDIODESCRIPTIONS_BINDING); ...
java
private synchronized void load(int year) { if (alreadyLoadedYears.contains(year)) { return; } alreadyLoadedYears.add(year); ZonedDateTime st = ZonedDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN, ZoneId.systemDefault()); ZonedDat...
python
def get_book_lookup_session(self): """Gets the ``OsidSession`` associated with the book lookup service. return: (osid.commenting.BookLookupSession) - a ``BookLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_book_look...
java
public <T> MutateInBuilder arrayInsert(String path, T value) { asyncBuilder.arrayInsert(path, value); return this; }
java
public static WarpExecutionBuilder initiate(Activity activity) { WarpRuntime runtime = WarpRuntime.getInstance(); if (runtime == null) { throw new IllegalStateException( "The Warp runtime isn't initialized. You need to make sure arquillian-warp-impl is on classpath and anno...
python
def pop_event(self): """Pop an event from event_list.""" if len(self.event_list) > 0: evt = self.event_list.pop(0) return evt return None
python
def users(self): """ Returns known users by exposing as a read-only property. """ if not hasattr(self, "_users"): us = {} if "users" in self.doc: for ur in self.doc["users"]: us[ur["name"]] = u = copy.deepcopy(ur["user"]) ...
python
def run_process(*args, **kwargs): """API used up to version 0.2.0.""" warnings.warn( "procrunner.run_process() is deprecated and has been renamed to run()", DeprecationWarning, stacklevel=2, ) return run(*args, **kwargs)
python
def load_query_string_data(request_schema, query_string_data=None): """ Load query string data using the given schema. Schemas are assumed to be compatible with the `PageSchema`. """ if query_string_data is None: query_string_data = request.args request_data = request_schema.load(quer...
python
def toDebugString(self): """ Returns a printable version of the configuration, as a list of key=value pairs, one per line. """ if self._jconf is not None: return self._jconf.toDebugString() else: return '\n'.join('%s=%s' % (k, v) for k, v in self._...
python
def defaults(d1, d2): """ Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ---...
python
def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it. ``envconfig`` is the testenv configuration which contains per-testenv configuration, notably the ``.envname`` and ``.basepyt...
python
def get_metrics(self, reset: bool = False) -> Dict[str, float]: """ We track three metrics here: 1. dpd_acc, which is the percentage of the time that our best output action sequence is in the set of action sequences provided by DPD. This is an easy-to-compute lower bound ...
java
public int getDistance(Node node1, Node node2) { if (node1 == node2) { return 0; } Node n1=node1, n2=node2; int dis = 0; netlock.readLock().lock(); try { int level1=node1.getLevel(), level2=node2.getLevel(); while(n1!=null && level1>level2) { n1 = n1.getParent(); ...
python
def file_upload(self, folder_id: str, file_name: str, mine_type: str) -> bool: """ Upload file into Google Drive :param folder_id: :param file_name: :param mine_type: :return: """ service = self.__get_service() media_body = MediaFileUpload(file_nam...
java
public AttackDetail withSubResources(SubResourceSummary... subResources) { if (this.subResources == null) { setSubResources(new java.util.ArrayList<SubResourceSummary>(subResources.length)); } for (SubResourceSummary ele : subResources) { this.subResources.add(ele); ...
python
def super(self, name, current): """Render a parent block.""" try: blocks = self.blocks[name] index = blocks.index(current) + 1 blocks[index] except LookupError: return self.environment.undefined('there is no parent block ' ...
java
public static BooleanOperation value() { JcValue val = new WhenJcValue(); BooleanOperation ret = P.valueOf(val); ASTNode an = APIObjectAccess.getAstNode(ret); an.setClauseType(ClauseType.WHEN); return ret; }
python
def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s): """Returns y-component spin for secondary mass. """ chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2) phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s) return chi_perp * numpy.sin(phi2)
python
def plot(self): """ Returns a hvPlot object to provide a high-level plotting API. To display in a notebook, be sure to run ``intake.output_notebook()`` first. """ try: from hvplot import hvPlot except ImportError: raise ImportError("The in...
python
def OnPadIntCtrl(self, event): """Pad IntCtrl event handler""" self.attrs["pad"] = event.GetValue() post_command_event(self, self.DrawChartMsg)
java
public static byte[] decodeBase64(String encodedData) { BufferedReader reader = new BufferedReader(new StringReader(encodedData)); int length = encodedData.length(); byte[] retval = new byte[length]; int actualLength = 0; String line; try { while ((line = reader.readLine()) != null) { byte[] rawData...
python
def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: self.switch_to_plugin() editorstack.set_or_clear_breakpoint()
java
@Override public Object getMember(String name) { switch (name) { case "format": return F_format; case "schema": return F_schema; case "option": return F_option; case "load": return F_load; ...
java
private synchronized static Pattern getPattern(String tagName, String attrName) { String key = tagName + " " + attrName; Pattern pc = pcPatterns.get(key); if (pc == null) { String tagPatString = "<\\s*" + tagName + "\\s+[^>]*\\b" + attrName + "\\s*=\\s*(" + ANY_ATTR_VALUE + ")(?:\\s|>)?"; pc =...
java
boolean handleSortOrder(final List<SortMeta> sortOrder) { boolean changed = false; if (sortOrder == null) { if (multiSortBy != null) { adaptee.clearSorting(); multiSortBy = null; lastSorting = null; changed = true; } } else { final List<SortProperty> newSorting = convert2SortProperty(sor...
python
def make_retry_state(previous_attempt_number, delay_since_first_attempt, last_result=None): """Construct RetryCallState for given attempt number & delay. Only used in testing and thus is extra careful about timestamp arithmetics. """ required_parameter_unset = (previous_attempt_num...
python
def crop(self, height, width, center_i=None, center_j=None): """Crop the image centered around center_i, center_j. Parameters ---------- height : int The height of the desired image. width : int The width of the desired image. center_i : int ...
java
public String generatePoolsConfigIfClassSet() { if (poolsConfigDocumentGenerator == null) { return null; } Document document = poolsConfigDocumentGenerator.generatePoolsDocument(); if (document == null) { LOG.warn("generatePoolsConfig: Did not generate a valid pools xml file"); return ...
python
def as_tree(self, visitor=None, children=None): """ Recursively traverses each tree (starting from each root) in order to generate a dictionary-based tree structure of the entire forest. Each level of the forest/tree is a list of nodes, and each node consists of a dictionary ...
java
public static JavaPlatform register(Config config) { // guard against multiple-registration (only in headless mode because this can happen when // running tests in Maven; in non-headless mode, we want to fail rather than silently ignore // erroneous repeated registration) if (config.headless && testInst...
python
def _getHessian(self): """ Internal function for estimating parameter uncertainty COMPUTES OF HESSIAN OF E(\theta) = - log L(\theta | X, y) """ assert self.init, 'GP not initialised' assert self.fast==False, 'Not supported for fast implementation' if self....
python
def _sections_to_raw_data(sections): '''convert list of sections into the `raw_data` format used in neurom This finds the soma, and attaches the neurites ''' soma = None neurites = [] for section in sections: neurite = _extract_section(section) if neurite is None: co...
java
public static int filterCountByG_T_E(long groupId, String type, boolean enabled) { return getPersistence().filterCountByG_T_E(groupId, type, enabled); }
python
def write_system_config(base_url, datadir, tooldir): """Write a bcbio_system.yaml configuration file with tool information. """ out_file = os.path.join(datadir, "galaxy", os.path.basename(base_url)) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) if o...
python
def handle_api_exceptions_inter(self, method, *url_parts, **kwargs): """The main (middle) part - it is enough if no error occurs.""" global request_count # used only in single thread tests - OK # pylint:disable=global-statement # log.info("request %s %s", method, '/'.join(url_parts)) # ...
python
def element_id_by_label(browser, label): """Return the id of a label's for attribute""" label = XPathSelector(browser, unicode('//label[contains(., "%s")]' % label)) if not label: return False return label.get_attribute('for')
python
async def build_revoc_reg_entry_request(submitter_did: str, revoc_reg_def_id: str, rev_def_type: str, value: str) -> str: """ Builds a REVOC_REG_ENTRY request. Request to add the RevocReg ent...
java
public void doGet(String url, HttpResponse response) { doGet(url, response, null, true); }
python
def is_string(value, coerce_value = False, minimum_length = None, maximum_length = None, whitespace_padding = False, **kwargs): """Indicate whether ``value`` is a string. :param value: The value to evaluate. :param coerce_value: If ``Tr...
java
public static QueryRootNode createQuery(String statement, LocationFactory resolver, QueryNodeFactory factory) throws InvalidQueryException { return new XPathQueryBuilder(statement, resolver, factory).getRootNode(); }
python
def convert_to_bool(text): """ Convert a few common variations of "true" and "false" to boolean :param text: string to test :return: boolean :raises: ValueError """ # handle "1" and "0" try: return bool(int(text)) except: pass text = str(text).lower() if text ==...
java
public static ErrorDescription create(Throwable ex, String correlationId) { ErrorDescription description = new ErrorDescription(); description.setType(ex.getClass().getCanonicalName()); description.setCategory(ErrorCategory.Unknown); description.setStatus(500); description.setCode("Unknown"); ...
java
private void pattern(Attributes attributes) throws SVGParseException { debug("<pattern>"); if (currentElement == null) throw new SVGParseException("Invalid document. Root element must be <svg>"); SVG.Pattern obj = new SVG.Pattern(); obj.document = svgDocument; obj.par...
python
def connection(self): """return authenticated connection""" c = pymongo.MongoClient( self.hostname, fsync=True, socketTimeoutMS=self.socket_timeout, **self.kwargs) connected(c) if not self.is_mongos and self.login and not self.restart_required: db = c[...
python
def getconfig(self, section=None): """ This method provides a way for decorated functions to get the four new configuration parameters *after* it has been called. If no section is specified, then the fully resolved zdesk config will be returned. That is defaults, zdesk ini secti...
python
def create_highlight(self, artist): """Create a new highlight for the given artist.""" highlight = copy.copy(artist) highlight.set(color=self.highlight_color, mec=self.highlight_color, lw=self.highlight_width, mew=self.highlight_width) artist.axes.add_artist(highlig...
java
@Deprecated private void emitJvmMemMetrics(ServiceEmitter emitter) { // I have no idea why, but jvm/mem is slightly more than the sum of jvm/pool. Let's just include // them both. final Map<String, MemoryUsage> usages = ImmutableMap.of( "heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUs...
java
public OvhExchangeMailingListAlias organizationName_service_exchangeService_mailingList_mailingListAddress_alias_alias_GET(String organizationName, String exchangeService, String mailingListAddress, String alias) throws IOException { String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/mailing...
java
public static boolean streamNotConsumed( HttpServletRequest request ) { try { ServletInputStream servletInputStream = request.getInputStream(); //in servlet >= 3.0, available will throw an exception (while previously it didn't) return request.getContentLength() != 0 && servle...
java
private void defineSpinners(UIDefaults d) { d.put("spinnerNextBorderBottomEnabled", new Color(0x4779bf)); d.put("spinnerNextBorderBottomPressed", new Color(0x4879bf)); d.put("spinnerNextInteriorBottomEnabled", new Color(0x85abcf)); d.put("spinnerNextInteriorBottomPressed", new Color(0x6e...
java
public static <T> String makeS3CanonicalString(String method, String resource, SignableRequest<T> request, String expires) { return makeS3CanonicalString(method, resource, request, expires, null); }
python
def ok(self): """ Returns True if OK to use, else False """ try: v = float(self._value) if v < self.fmin or v > self.fmax: return False else: return True except: return False
java
@Override public IGroupMember getGroupMember(String key, Class type) throws GroupsException { IGroupMember gm = null; if (type == ICompositeGroupService.GROUP_ENTITY_TYPE) gm = findGroup(key); else gm = getEntity(key, type); return gm; }
java
public static base_response delete(nitro_service client, Long clid) throws Exception { clusterinstance deleteresource = new clusterinstance(); deleteresource.clid = clid; return deleteresource.delete_resource(client); }
python
def features(self): """ Returns a collection of features available to the current account. """ self._validate_loaded() resource = self.FEATURES.format(id=self.id) response = Request(self.client, 'get', resource).perform() return response.body['data']
python
def worker_pids(cls): """Returns an array of all pids (as strings) of the workers on this machine. Used when pruning dead workers.""" cmd = "ps -A -o pid,command | grep pyres_worker | grep -v grep" output = commands.getoutput(cmd) if output: return map(lambda l: l.st...
java
protected void merge(List<? extends ConfigElement> elements) { if (elements.size() > 1) { Collections.sort(elements, ConfigElementComparator.INSTANCE); } ConfigElement[] elementArray = elements.toArray(new ConfigElement[elements.size()]); LinkedList<ConfigElement> flattened...
java
void endCompoundEdit() { if(!compoundMode) { throw new RuntimeException("not in compound mode"); } ce.end(); undoManager.addEdit(ce); ce = null; compoundMode = false; }
python
def load(): """Load the active experiment.""" initialize_experiment_package(os.getcwd()) try: try: from dallinger_experiment import experiment except ImportError: from dallinger_experiment import dallinger_experiment as experiment classes = inspect.getmembers...
python
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.extensions['inspire-crawler'] = self app.cli.add_command(crawler_cmd)
python
def get(self, x, y): """Get the state of a pixel. Returns bool. :param x: x coordinate of the pixel :param y: y coordinate of the pixel """ x = normalize(x) y = normalize(y) dot_index = pixel_map[y % 4][x % 2] col, row = get_pos(x, y) char = self....
python
def terms(self): """Iterator over the terms of the sum Yield from the (possibly) infinite list of terms of the indexed sum, if the sum was written out explicitly. Each yielded term in an instance of :class:`.Expression` """ from qnet.algebra.core.scalar_algebra import Sc...
java
@Override public FilterSupportStatus isFilterSupported( FilterAdapterContext context, ColumnRangeFilter filter) { // We require a single column family to be specified: int familyCount = context.getScan().numFamilies(); if (familyCount != 1) { return UNSUPPORTED_STATUS; } return F...
java
public static Constraint moreControllerThanParticipant() { return new ConstraintAdapter(1) { PathAccessor partConv = new PathAccessor("PhysicalEntity/participantOf:Conversion"); PathAccessor partCompAss = new PathAccessor("PhysicalEntity/participantOf:ComplexAssembly"); PathAccessor effects = new PathAcce...
python
def cli(env, identifier, domain, userfile, tag, hostname, userdata, public_speed, private_speed): """Edit a virtual server's details.""" if userdata and userfile: raise exceptions.ArgumentError( '[-u | --userdata] not allowed with [-F | --userfile]') data = {} if userdata:...
python
def ko_data(queryset, field_names=None, name=None, safe=False, return_json=False): """ Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript. """ try: try: # Get an inital instance of the QS. queryset_instance = query...
java
@Reference(policy = ReferencePolicy.DYNAMIC, target = "(id=unbound)") protected void setConcurrencyPolicy(ConcurrencyPolicy svc) { policyExecutor = svc.getExecutor(); }
java
@Override @ManagedOperation(description = "Resets statistics gathered by this component", displayName = "Reset statistics") public void resetStatistics() { replicationCount.set(0); replicationFailures.set(0); totalReplicationTime.set(0); syncXSiteReplicationTime = new DefaultSimpleStat(); ...
python
def exportProfile(self, filename=''): """ Exports the current profile to a file. :param filename | <str> """ if not (filename and isinstance(filename, basestring)): filename = QtGui.QFileDialog.getSaveFileName(self, ...
python
def addSignal(self, s): """ Adds a L{Signal} to the interface """ if s.nargs == -1: s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)]) self.signals[s.name] = s self._xml = None
python
def send_sms_with_callback_token(user, mobile_token, **kwargs): """ Sends a SMS to user.mobile via Twilio. Passes silently without sending in test environment. """ base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE) try: if api_settings.PASSWORDLESS_MO...
java
public static String getType (String command) { int cidx = StringUtil.isBlank(command) ? -1 : command.indexOf(':'); return (cidx == -1) ? "" : command.substring(0, cidx); }
java
public ListAWSServiceAccessForOrganizationResult withEnabledServicePrincipals(EnabledServicePrincipal... enabledServicePrincipals) { if (this.enabledServicePrincipals == null) { setEnabledServicePrincipals(new java.util.ArrayList<EnabledServicePrincipal>(enabledServicePrincipals.length)); } ...
python
def send_KeyEvent(self, key, down): """For most ordinary keys, the "keysym" is the same as the corresponding ASCII value. Other common keys are shown in the KEY_ constants. """ self.sendMessage(struct.pack('!BBxxI', 4, down, key))
python
def disconnect_async(self, conn_id, callback): """Asynchronously disconnect from a device.""" future = self._loop.launch_coroutine(self._adapter.disconnect(conn_id)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
java
private static void addSuperAndInterfaces(Set<Class<?>> classes, Class<?> clazz) { if (clazz != null) { classes.add(clazz); addSuperAndInterfaces(classes, clazz.getSuperclass()); for (Class<?> aClass : clazz.getInterfaces()) { addSuperAndInterfaces(classes, aC...
java
private boolean canRun(String flowName, String flowGroup, boolean allowConcurrentExecution) { if (allowConcurrentExecution) { return true; } else { return !flowStatusGenerator.isFlowRunning(flowName, flowGroup); } }
java
private static <T> T extractSingleton(Collection<T> collection) { if (collection == null || collection.isEmpty()) { return null; } if (collection.size() == 1) { return collection.iterator().next(); } else { throw new IllegalStateException("Expected singleton collection, but found size: " + collection....
java
public boolean isValidSecretToken(String secretToken) { return (this.secretToken == null || this.secretToken.equals(secretToken) ? true : false); }
java
public static boolean writeString(String filePath, String content, boolean append) throws IOException { return writeString(filePath != null ? new File(filePath) : null, content, append); }
python
def exportCertificate(self, certificate, folder): """gets the SSL Certificates for a given machine""" url = self._url + "/sslcertificates/%s/export" % certificate params = { "f" : "json", } return self._get(url=url, param_dict=params, ...
python
def fastcc_consistent_subset(model, epsilon, solver): """Return consistent subset of model. The largest consistent subset is returned as a set of reaction names. Args: model: :class:`MetabolicModel` to solve. epsilon: Flux threshold value. solver: LP solver instance to use. ...
python
def _get_projection(cls, obj): """ Uses traversal to find the appropriate projection for a nested object. Respects projections set on Overlays before considering Element based settings, before finally looking up the default projection on the plot type. If more than one no...
java
public static List<MetricDto> transformToDto(List<Metric> metrics) { if (metrics == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<MetricDto> result = new ArrayList<>(); for (Metric me...
java
public StreamAttribute attribute(String streamKey) throws QiniuException { String path = encodeKey(streamKey); return get(path, StreamAttribute.class); }
java
boolean skipObject() throws IOException { int ch = read(); int len; switch (ch) { // inline string (1 byte) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: cas...
python
def page(self, recurring=values.unset, trigger_by=values.unset, usage_category=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of TriggerInstance records from the API. Request is executed immediately ...
python
def set(self, results): """Set results. results is an iterable of tuples, where each tuple is a row of results. >>> x = Results(['title']) >>> x.set([('Konosuba',), ('Oreimo',)]) >>> x Results(['title'], [('Konosuba',), ('Oreimo',)]) """ self.results = ...
python
def _initialize_progress_bar(self): """Initializes the progress bar""" widgets = ['Download: ', Percentage(), ' ', Bar(), ' ', AdaptiveETA(), ' ', FileTransferSpeed()] self._downloadProgressBar = ProgressBar( widgets=widgets, max_value=self._imageCount).start()
python
def present_active(self): """ Strong verbs I >>> verb = StrongOldNorseVerb() >>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"]) >>> verb.present_active() ['lít', 'lítr', 'lítr', 'lítum', 'lítið', 'líta'] II >>> verb = StrongOl...
java
@Override @Nullable public String getMapping(Class<?> type, Method method) { Assert.notNull(type, "Type must not be null!"); Assert.notNull(method, "Method must not be null!"); String[] mapping = getMappingFrom(findMergedAnnotation(method, annotationType)); String typeMapping = getMapping(type); if (mapp...