language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def path_to_url(path): # type: (Union[str, Text]) -> str """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urllib_parse.urljoin('file:', urllib_request.pathname2url(path)) return url
python
def listcall(self, *arg, **kw): """Call each plugin sequentially. Return the first result that is not None. """ final_result = None for _, meth in self.plugins: result = meth(*arg, **kw) if final_result is None and result is not None: final_result = result return final_result
python
def get(self, name_or_klass): """ Gets a mode by name (or class) :param name_or_klass: The name or the class of the mode to get :type name_or_klass: str or type :rtype: pyqode.core.api.Mode """ if not isinstance(name_or_klass, str): name_or_klass = name_or_klass.__name__ return self._modes[name_or_klass]
java
public void start() { if (state == State.RUNNING) return; final Lock lock = this.lock.writeLock(); try { lock.lock(); this.state = State.STARTING; // Create an executor service that we'll use to start the repositories ... ThreadFactory threadFactory = new NamedThreadFactory("modeshape-start-repo"); repositoryStarterService = Executors.newCachedThreadPool(threadFactory); state = State.RUNNING; } catch (RuntimeException e) { state = State.NOT_RUNNING; throw e; } finally { lock.unlock(); } }
java
public static Location getLocation(Object obj, String description) { if (obj instanceof Location) { return (Location) obj; } if (obj instanceof Locatable) { return ((Locatable) obj).getLocation(); } if (obj instanceof SAXParseException) { SAXParseException spe = (SAXParseException) obj; if (spe.getSystemId() != null) { return new LocationImpl(description, spe.getSystemId(), spe.getLineNumber(), spe.getColumnNumber()); } else { return LocationImpl.UNKNOWN; } } if (obj instanceof TransformerException) { TransformerException ex = (TransformerException) obj; SourceLocator locator = ex.getLocator(); if (locator != null && locator.getSystemId() != null) { return new LocationImpl(description, locator.getSystemId(), locator.getLineNumber(), locator.getColumnNumber()); } else { return LocationImpl.UNKNOWN; } } if (obj instanceof Locator) { Locator locator = (Locator) obj; if (locator.getSystemId() != null) { return new LocationImpl(description, locator.getSystemId(), locator.getLineNumber(), locator.getColumnNumber()); } else { return LocationImpl.UNKNOWN; } } if (obj instanceof Element) { return LocationAttributes.getLocation((Element) obj); } List<WeakReference<LocationFinder>> currentFinders = finders; int size = currentFinders.size(); for (int i = 0; i < size; i++) { WeakReference<LocationFinder> ref = currentFinders.get(i); LocationFinder finder = ref.get(); if (finder == null) { synchronized (LocationFinder.class) { List<WeakReference<LocationFinder>> newFinders = new ArrayList<WeakReference<LocationFinder>>( finders); newFinders.remove(ref); finders = newFinders; } } Location result = finder.getLocation(obj, description); if (result != null) { return result; } } if (obj instanceof Throwable) { Throwable t = (Throwable) obj; StackTraceElement[] stack = t.getStackTrace(); if (stack != null && stack.length > 0) { StackTraceElement trace = stack[0]; if (trace.getLineNumber() >= 0) { String uri = trace.getClassName(); if (trace.getFileName() != null) { uri = uri.replace('.', '/'); uri = uri.substring(0, uri.lastIndexOf('/') + 1); uri = uri + trace.getFileName(); URL url = ClassLoaderUtil.getResource(uri, LocationUtils.class); if (url != null) { uri = url.toString(); } } if (description == null) { StringBuilder sb = new StringBuilder(); sb.append("Class: ").append(trace.getClassName()).append("\n"); sb.append("File: ").append(trace.getFileName()).append("\n"); sb.append("Method: ").append(trace.getMethodName()).append("\n"); sb.append("Line: ").append(trace.getLineNumber()); description = sb.toString(); } return new LocationImpl(description, uri, trace.getLineNumber(), -1); } } } return LocationImpl.UNKNOWN; }
java
public XmlAssert isNotValidAgainst(Object... schemaSources) { isNotNull(); ValidationAssert.create(actual, schemaSources).isInvalid(); return this; }
python
def pop_ctx(): """Removes the test context(s) from the current stack(s) """ if getattr(_request_ctx_stack.top, 'fixtures_request_context', False): _request_ctx_stack.pop() if _app_ctx_stack is not None and getattr(_app_ctx_stack.top, 'fixtures_app_context', False): _app_ctx_stack.pop()
java
private void reportError(ErrorReporter errorReporter, SoyAutoescapeException e) { // First, get to the root cause of the exception, and assemble an error message indicating // the full call stack that led to the failure. String message = "- " + e.getOriginalMessage(); while (e.getCause() instanceof SoyAutoescapeException) { e = (SoyAutoescapeException) e.getCause(); message += "\n- " + e.getMessage(); } errorReporter.report(e.getSourceLocation(), AUTOESCAPE_ERROR, message); }
python
def transform_absolute_coords(self, width, height): """Return the current absolute coordinates of the pointer event, transformed to screen coordinates. For pointer events that are not of type :attr:`~libinput.constant.EventType.POINTER_MOTION_ABSOLUTE`, this method raises :exc:`AttributeError`. Args: width (int): The current output screen width. height (int): The current output screen height. Returns: (float, float): The current absolute (x, y) coordinates transformed to a screen coordinates. Raises: AttributeError """ if self.type != EventType.POINTER_MOTION_ABSOLUTE: raise AttributeError(_wrong_meth.format(self.type)) abs_x = self._libinput \ .libinput_event_pointer_get_absolute_x_transformed( self._handle, width) abs_y = self._libinput \ .libinput_event_pointer_get_absolute_y_transformed( self._handle, height) return abs_x, abs_y
python
def delete(self, id, id_name='id', **kwargs): """ Deletes the item corresponding to ``id``. """ response = self._new_response() if self._check_supported_op('delete', response): params = {'Key': {id_name: id}} self._call_ddb_method(self.table.delete_item, params, response) response.data = 'true' response.prepare() return response
python
def _parse_config_file(self, cfg_files): """Parse config file (ini) and set properties :return: """ cfg_handler = configparser.ConfigParser(interpolation=None) if not cfg_handler.read(map(str, cfg_files)): return self._parse_global_section(cfg_handler) self._parse_vcs_section(cfg_handler) self._parse_file_section(cfg_handler)
python
def strictly_increasing(values): """True if values are stricly increasing.""" return all(x < y for x, y in zip(values, values[1:]))
java
public void setDataHandler(DataHandler dataHandler) { this._dataHandler = dataHandler; if(dataHandler == null) { _properties.remove(PARAM_DATA_HANDLER_CLASS); } else { if (dataHandler.getClass() != DefaultDataSetHandler.class && dataHandler.getClass() != DefaultDataStoreHandler.class) { _properties.setProperty(PARAM_DATA_HANDLER_CLASS, dataHandler.getClass().getName()); } } }
python
def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False): ''' Get whether 2 data frames are equal. ``NaN`` is considered equal to ``NaN`` and `None`. Parameters ---------- df1 : ~pandas.DataFrame Data frame to compare. df2 : ~pandas.DataFrame Data frame to compare. ignore_order : ~typing.Set[int] Axi in which to ignore order. ignore_indices : ~typing.Set[int] Axi of which to ignore the index. E.g. ``{1}`` allows differences in ``df.columns.name`` and ``df.columns.equals(df2.columns)``. all_close : bool If `False`, values must match exactly, if `True`, floats are compared as if compared with `numpy.isclose`. _return_reason : bool Internal. If `True`, `equals` returns a tuple containing the reason, else `equals` only returns a bool indicating equality (or equivalence rather). Returns ------- bool Whether they are equal (after ignoring according to the parameters). Internal note: if ``_return_reason``, ``Tuple[bool, str or None]`` is returned. The former is whether they're equal, the latter is `None` if equal or a short explanation of why the data frames aren't equal, otherwise. Notes ----- All values (including those of indices) must be copyable and ``__eq__`` must be such that a copy must equal its original. A value must equal itself unless it's ``NaN``. Values needn't be orderable or hashable (however pandas requires index values to be orderable and hashable). By consequence, this is not an efficient function, but it is flexible. Examples -------- >>> from pytil import data_frame as df_ >>> import pandas as pd >>> df = pd.DataFrame([ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ], ... index=pd.Index(('i1', 'i2', 'i3'), name='index1'), ... columns=pd.Index(('c1', 'c2', 'c3'), name='columns1') ... ) >>> df columns1 c1 c2 c3 index1 i1 1 2 3 i2 4 5 6 i3 7 8 9 >>> df2 = df.reindex(('i3', 'i1', 'i2'), columns=('c2', 'c1', 'c3')) >>> df2 columns1 c2 c1 c3 index1 i3 8 7 9 i1 2 1 3 i2 5 4 6 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_order=(0,1)) True >>> df2 = df.copy() >>> df2.index = [1,2,3] >>> df2 columns1 c1 c2 c3 1 1 2 3 2 4 5 6 3 7 8 9 >>> df_.equals(df, df2) False >>> df_.equals(df, df2, ignore_indices={0}) True >>> df2 = df.reindex(('i3', 'i1', 'i2')) >>> df2 columns1 c1 c2 c3 index1 i3 7 8 9 i1 1 2 3 i2 4 5 6 >>> df_.equals(df, df2, ignore_indices={0}) # does not ignore row order! False >>> df_.equals(df, df2, ignore_order={0}) True >>> df2 = df.copy() >>> df2.index.name = 'other' >>> df_.equals(df, df2) # df.index.name must match as well, same goes for df.columns.name False ''' result = _equals(df1, df2, ignore_order, ignore_indices, all_close) if _return_reason: return result else: return result[0]
java
static Source updateSource(SourceName sourceName) { try (SecurityCenterClient client = SecurityCenterClient.create()) { // Start setting up a request to update a source. // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ // "423432321"); Source source = Source.newBuilder() .setDisplayName("Updated Display Name") .setName(sourceName.toString()) .build(); FieldMask updateMask = FieldMask.newBuilder().addPaths("display_name").build(); UpdateSourceRequest.Builder request = UpdateSourceRequest.newBuilder().setSource(source).setUpdateMask(updateMask); // Call the API. Source response = client.updateSource(request.build()); System.out.println("Updated Source: " + response); return response; } catch (IOException e) { throw new RuntimeException("Couldn't create client.", e); } }
python
def _maybe_cast_indexer(self, key): """ If we have a float key and are not a floating index, then try to cast to an int if equivalent. """ if is_float(key) and not self.is_floating(): try: ckey = int(key) if ckey == key: key = ckey except (OverflowError, ValueError, TypeError): pass return key
java
@Override protected void doTransform(ITransformable.Translate transformable, float comp) { float fromX = reversed ? this.toX : this.fromX; float toX = reversed ? this.fromX : this.toX; float fromY = reversed ? this.toY : this.fromY; float toY = reversed ? this.fromY : this.toY; float fromZ = reversed ? this.toZ : this.fromZ; float toZ = reversed ? this.fromZ : this.toZ; transformable.translate(fromX + (toX - fromX) * comp, fromY + (toY - fromY) * comp, fromZ + (toZ - fromZ) * comp); }
python
def choice_info(self): """View .info file """ info = ReadSBo(self.sbo_url).info(self.name, ".info") fill = self.fill_pager(info) self.pager(info + fill)
java
public static Sprite addBorder(Sprite original, int color, int size) { int[] newPix = Arrays.copyOf(original.getPixels(), original.getPixels().length); for (int x = 0; x < original.getWidth(); x++) { for (int y = 0; y < original.getHeight(); y++) { if (x < size || x >= original.getWidth() - size || y < size || y >= original.getHeight() - size) { newPix[x + y * original.getWidth()] = color; } } } return new Sprite(original.getWidth(), original.getHeight(), newPix); }
java
public static Map<String, String> mapStringToMap(String map) { String[] m = map.split("[,;]"); Map<String, String> res = new HashMap<String, String>(); for (String str : m) { int index = str.lastIndexOf('='); String key = str.substring(0, index); String val = str.substring(index + 1); res.put(key.trim(), val.trim()); } return res; }
java
private ViterbiNode findGlueNodeCandidate(int index, ViterbiNode[] latticeNodes, int startIndex) { List<ViterbiNode> candidates = new ArrayList<>(); for (ViterbiNode viterbiNode : latticeNodes) { if (viterbiNode != null) { candidates.add(viterbiNode); } } if (!candidates.isEmpty()) { ViterbiNode glueBase = null; int length = index + 1 - startIndex; for (ViterbiNode candidate : candidates) { if (isAcceptableCandidate(length, glueBase, candidate)) { glueBase = candidate; } } if (glueBase != null) { return glueBase; } } return null; }
python
def _make_token_async(scopes, service_account_id): """Get a fresh authentication token. Args: scopes: A list of scopes. service_account_id: Internal-use only. Raises: An ndb.Return with a tuple (token, expiration_time) where expiration_time is seconds since the epoch. """ rpc = app_identity.create_rpc() app_identity.make_get_access_token_call(rpc, scopes, service_account_id) token, expires_at = yield rpc raise ndb.Return((token, expires_at))
java
public int compareTo(ReadablePartial partial) { if (partial == null) { throw new IllegalArgumentException("The partial must not be null"); } int thisValue = get(); int otherValue = partial.get(getFieldType()); if (thisValue < otherValue) { return -1; } else if (thisValue > otherValue) { return 1; } else { return 0; } }
java
public void marshall(EnableAWSServiceAccessRequest enableAWSServiceAccessRequest, ProtocolMarshaller protocolMarshaller) { if (enableAWSServiceAccessRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(enableAWSServiceAccessRequest.getServicePrincipal(), SERVICEPRINCIPAL_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
private AnnotationNode getAnnotation(String desc, List<AnnotationNode> annotations) { if (annotations == null) { return null; } for (AnnotationNode an : annotations) { if (desc.equals(an.desc)) { return an; } } return null; }
java
public static String urlEncode(String str) throws UnsupportedEncodingException { // Preserve original behavior that passing null for an object id will lead // to us actually making a request to /v1/foo/null if (str == null) { return null; } else { // Don't use strict form encoding by changing the square bracket control // characters back to their literals. This is fine by the server, and // makes these parameter strings easier to read. return URLEncoder.encode(str, CHARSET) .replaceAll("%5B", "[") .replaceAll("%5D", "]"); } }
java
public Object opt( String key ) { verifyIsNull(); return key == null ? null : this.properties.get( key ); }
java
@Override public GetConfigurationSetEventDestinationsResult getConfigurationSetEventDestinations(GetConfigurationSetEventDestinationsRequest request) { request = beforeClientExecution(request); return executeGetConfigurationSetEventDestinations(request); }
python
def hclust_ordering(X, metric="sqeuclidean"): """ A leaf ordering is under-defined, this picks the ordering that keeps nearby samples similar. """ # compute a hierarchical clustering D = sp.spatial.distance.pdist(X, metric) cluster_matrix = sp.cluster.hierarchy.complete(D) # merge clusters, rotating them to make the end points match as best we can sets = [[i] for i in range(X.shape[0])] for i in range(cluster_matrix.shape[0]): s1 = sets[int(cluster_matrix[i,0])] s2 = sets[int(cluster_matrix[i,1])] # compute distances between the end points of the lists d_s1_s2 = pdist(np.vstack([X[s1[-1],:], X[s2[0],:]]), metric)[0] d_s2_s1 = pdist(np.vstack([X[s1[0],:], X[s2[-1],:]]), metric)[0] d_s1r_s2 = pdist(np.vstack([X[s1[0],:], X[s2[0],:]]), metric)[0] d_s1_s2r = pdist(np.vstack([X[s1[-1],:], X[s2[-1],:]]), metric)[0] # concatenete the lists in the way the minimizes the difference between # the samples at the junction best = min(d_s1_s2, d_s2_s1, d_s1r_s2, d_s1_s2r) if best == d_s1_s2: sets.append(s1 + s2) elif best == d_s2_s1: sets.append(s2 + s1) elif best == d_s1r_s2: sets.append(list(reversed(s1)) + s2) else: sets.append(s1 + list(reversed(s2))) return sets[-1]
python
def update(self, *others): """Update the set, adding elements from all others.""" self.db.sunionstore(self.key, [self.key] + [o.key for o in others])
java
public java.util.List<java.util.Map<String, String>> getTags() { return tags; }
python
def prt_report_grp0(self, prt=sys.stdout): """Print full GO/gene report without grouping.""" summaryline = self.str_summaryline() kws_grp = {'use_sections':False, 'hdrgo_prt':False, 'sortby':lambda nt: [-1*nt.dcnt, nt.depth]} # Print grouped GO IDs prt.write("{SUMMARY}\n".format(SUMMARY=summaryline)) self.prt_gos_grouped(sys.stdout, **kws_grp) # genes genes = sorted(self.gene2gos.keys()) prt.write("\n\n{SUMMARY}\n\n".format(SUMMARY=summaryline)) self.prt_gene_aart(genes, prt) # Sort genes prt.write("\n\n{SUMMARY}\n\n".format(SUMMARY=summaryline)) self.prt_gene_aart_details(genes, prt) return (self.name, self.get_section_marks())
java
@Override public DescribeDomainResult describeDomain(DescribeDomainRequest request) { request = beforeClientExecution(request); return executeDescribeDomain(request); }
python
def add_row(self, data: list): """ Add a row of buttons each with their own callbacks to the current widget. Each element in `data` will consist of a label and a command. :param data: a list of tuples of the form ('label', <callback>) :return: None """ # validation if self.headers and data: if len(self.headers) != len(data): raise ValueError offset = 0 if not self.headers else 1 row = list() for i, e in enumerate(data): if not isinstance(e, tuple): raise ValueError('all elements must be a tuple ' 'consisting of ("label", <command>)') label, command = e button = tk.Button(self, text=str(label), relief=tk.RAISED, command=command, padx=self.padding, pady=self.padding) button.grid(row=len(self._rows) + offset, column=i, sticky='ew') row.append(button) self._rows.append(row)
python
def get_connected_sites(self, n): """ Returns a named tuple of neighbors of site n: periodic_site, jimage, index, weight. Index is the index of the corresponding site in the original structure, weight can be None if not defined. :param n: index of Site in Molecule :param jimage: lattice vector of site :return: list of ConnectedSite tuples, sorted by closest first """ connected_sites = set() out_edges = [(u, v, d) for u, v, d in self.graph.out_edges(n, data=True)] in_edges = [(u, v, d) for u, v, d in self.graph.in_edges(n, data=True)] for u, v, d in out_edges + in_edges: weight = d.get('weight', None) if v == n: site = self.molecule[u] dist = self.molecule[v].distance(self.molecule[u]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=u, weight=weight, dist=dist) else: site = self.molecule[v] dist = self.molecule[u].distance(self.molecule[v]) connected_site = ConnectedSite(site=site, jimage=(0, 0, 0), index=v, weight=weight, dist=dist) connected_sites.add(connected_site) # return list sorted by closest sites first connected_sites = list(connected_sites) connected_sites.sort(key=lambda x: x.dist) return connected_sites
java
private void finish() throws IOException { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"finish", "finish"); } if (length == -1 && total != 0) length = total; //PK89810 Start if (WCCustomProperties.FINISH_RESPONSE_ON_CLOSE) { WebContainerRequestState reqState = WebContainerRequestState.getInstance(false); if (reqState==null || reqState.getAttribute("com.ibm.ws.webcontainer.appIsArdEnabled")==null){ if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"finish", "finishresponseonclose and appIsNotArdEnabled, setLastBuffer to true"); response.setLastBuffer(true); } }//PK89810 End flush(); }
python
def item_enclosure_url(self, item): """ Return an image for enclosure. """ try: url = item.image.url except (AttributeError, ValueError): img = BeautifulSoup(item.html_content, 'html.parser').find('img') url = img.get('src') if img else None self.cached_enclosure_url = url if url: url = urljoin(self.site_url, url) if self.feed_format == 'rss': url = url.replace('https://', 'http://') return url
python
def leaking(self, z, module, name, node, context, *data): ''' an expression leaking ... assignment nodes into the nearest block list of nodes c++ guys, stay calm ''' # input(node.y) args = [node.receiver] + node.args if node.type == 'standard_method_call' else node.args z = z(module, name, args) if context == 'expression': if isinstance(z, NormalLeakingNode): leaked_nodes, exp = z.as_expression() else: leaked_nodes, exp = z.as_expression() zz = local(z.temp_name(getattr(z, 'default', '')), node.pseudo_type) leaked_nodes = z.as_assignment(zz) exp = local(zz, node.pseudo_type) if exp is None or exp.pseudo_type == 'Void': raise PseudoTypeError("pseudo can't handle values with void type in expression: %s?%s" % (module, name)) self.leaked_nodes += leaked_nodes return exp elif context == 'assignment': if isinstance(z, NormalLeakingNode): leaked_nodes, exp = z.as_expression() if exp is None or exp.pseudo_type == 'Void': raise PseudoTypeError("pseudo can't handle values with void type in expression: %s?%s" % (module, name)) self.leaked_nodes += leaked_nodes return assignment(data[0], exp) else: self.leaked_nodes += z.as_assignment(data[0]) return None elif context == 'block': leaked_nodes, exp = z.as_expression() self.leaked_nodes += leaked_nodes return exp
java
private String colorType(SchemaConcept schemaConcept) { if(colorize) { return ANSI.color(label(schemaConcept.label()), ANSI.PURPLE); } else { return label(schemaConcept.label()); } }
python
def _get_kwsdag(self, goids, go2obj, **kws_all): """Get keyword args for a GoSubDag.""" kws_dag = {} # Term Counts for GO Term information score tcntobj = self._get_tcntobj(goids, go2obj, **kws_all) # TermCounts or None if tcntobj is not None: kws_dag['tcntobj'] = tcntobj # GO letters specified by the user if 'go_aliases' in kws_all: fin_go_aliases = kws_all['go_aliases'] if os.path.exists(fin_go_aliases): go2letter = read_d1_letter(fin_go_aliases) if go2letter: kws_dag['go2letter'] = go2letter return kws_dag
java
public void unbind() throws Exception { InstanceInfo myInfo = applicationInfoManager.getInfo(); String myInstanceId = ((AmazonInfo) myInfo.getDataCenterInfo()).get(AmazonInfo.MetaDataKey.instanceId); AmazonEC2 ec2 = getEC2Service(); List<InstanceNetworkInterface> result = instanceData(myInstanceId, ec2).getNetworkInterfaces(); List<String> ips = getCandidateIps(); for(InstanceNetworkInterface networkInterface: result){ if (ips.contains(networkInterface.getPrivateIpAddress())) { String attachmentId = networkInterface.getAttachment().getAttachmentId(); ec2.detachNetworkInterface(new DetachNetworkInterfaceRequest().withAttachmentId(attachmentId)); break; } } }
python
def _check_for_bom(self, first_row): """ Checks whether the file begins with the BOM character. If it does, remove it. In addition, if there is quoting in the field subsequent to the BOM, remove it as well because it technically takes place at the beginning of the name, not the middle of it. """ # first_row will be a list, so we need to check # that that list is not empty before proceeding. if not first_row: return first_row # The first element of this row is the one that could have the # BOM that we want to remove. Check that the first element is a # string before proceeding. if not isinstance(first_row[0], str): return first_row # Check that the string is not empty, as that would # obviously not have a BOM at the start of it. if not first_row[0]: return first_row # Since the string is non-empty, check that it does # in fact begin with a BOM. first_elt = first_row[0][0] if first_elt != _BOM: return first_row first_row = first_row[0] if len(first_row) > 1 and first_row[1] == self.quotechar: start = 2 quote = first_row[1] end = first_row[2:].index(quote) + 2 # Extract the data between the quotation marks new_row = first_row[start:end] # Extract any remaining data after the second # quotation mark. if len(first_row) > end + 1: new_row += first_row[end + 1:] return [new_row] elif len(first_row) > 1: return [first_row[1:]] else: # First row is just the BOM, so we # return an empty string. return [""]
java
@Override public Serializable invokeCommand(String key, String commandName, Serializable commandData) throws SIConnectionDroppedException, SIConnectionUnavailableException, SINotAuthorizedException, SIResourceException, SIIncorrectCallException, SICommandInvocationFailedException { return _delegateConnection.invokeCommand(key, commandName, commandData); }
java
public static ConfigProperties ofFlatMap(String key, Map<String, String> map) { SimpleConfigProperties root = new SimpleConfigProperties(key); root.fromFlatMap(map); return root; }
python
def forwardMessage(self, chat_id, from_chat_id, message_id, disable_notification=None): """ See: https://core.telegram.org/bots/api#forwardmessage """ p = _strip(locals()) return self._api_request('forwardMessage', _rectify(p))
java
public void setNu(double nu) { if(Double.isNaN(nu) || nu <= 0 || nu >= 1) throw new IllegalArgumentException("nu must be in the range (0, 1)"); this.nu = nu; }
java
public static String buildString(Consumer<StringPrinter> printer) { StringBuilder builder = new StringBuilder(); printer.accept(new StringPrinter(builder::append)); return builder.toString(); }
python
def add_nio(self, nio): """ Adds a NIO as new port on this bridge. :param nio: NIO instance to add """ yield from self._hypervisor.send('nio_bridge add_nio "{name}" {nio}'.format(name=self._name, nio=nio)) self._nios.append(nio)
java
@SuppressWarnings("unchecked") public List<Failure> validate(Validate vo, ResourceBundle rb) { if (vo != null && Key.CONNECTION_FACTORY == vo.getKey() && vo.getClazz() != null && ConnectionFactory.class.isAssignableFrom(vo.getClazz())) { try { SecurityActions.getConstructor(vo.getClazz(), (Class[])null); } catch (Throwable t) { List<Failure> failures = new ArrayList<Failure>(1); Failure failure = new Failure(Severity.ERROR, SECTION, rb.getString("cf.CFConstructor")); failures.add(failure); return failures; } } return null; }
python
def edit(self, body): """Edit this comment. :param str body: (required), new body of the comment, Markdown formatted :returns: bool """ if body: json = self._json(self._patch(self._api, data=dumps({'body': body})), 200) if json: self._update_(json) return True return False
python
def visitNodeConstraintDatatype(self, ctx: ShExDocParser.NodeConstraintDatatypeContext): """ nodeConstraint: datatype xsFacet* # nodeConstraintDatatype """ self.nodeconstraint.datatype = self.context.iri_to_iriref(ctx.datatype().iri()) self.visitChildren(ctx)
python
def list_ports(self, retrieve_all=True, **_params): """Fetches a list of all ports for a project.""" # Pass filters in "params" argument to do_request return self.list('ports', self.ports_path, retrieve_all, **_params)
java
@Override public Integer getOffset(Integer id, Integer type) { Integer result = null; Map<Integer, Integer> map = m_table.get(id); if (map != null && type != null) { result = map.get(type); } return (result); }
python
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet implemented or not applicable if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]): return {} if 'pkg.list_pkgs' in __context__: if versions_as_list: return __context__['pkg.list_pkgs'] else: ret = copy.deepcopy(__context__['pkg.list_pkgs']) __salt__['pkg_resource.stringify'](ret) return ret ret = {} pkgs = _vartree().dbapi.cpv_all() for cpv in pkgs: __salt__['pkg_resource.add_pkg'](ret, _cpv_to_cp(cpv), _cpv_to_version(cpv)) __salt__['pkg_resource.sort_pkglist'](ret) __context__['pkg.list_pkgs'] = copy.deepcopy(ret) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) return ret
java
@Override public String getFromName(String languageId, boolean useDefault) { return _commerceNotificationTemplate.getFromName(languageId, useDefault); }
java
@Override public synchronized boolean setSafeMode(boolean safeMode) { /** * If we are switching off the safe mode, so we need to reset the last * heartbeat timestamp for each of the sessions and nodes. */ if (safeMode == false) { LOG.info("Resetting the heartbeat times for all sessions"); sessionManager.resetSessionsLastHeartbeatTime(); LOG.info("Resetting the heartbeat times for all nodes"); nodeManager.resetNodesLastHeartbeatTime(); /** * If we are setting the safe mode to false, we should first set it * in-memory, before we set it at the CPJT. */ this.safeMode = false; } try { ClusterManagerAvailabilityChecker.getPJTClient(conf). setClusterManagerSafeModeFlag(safeMode); } catch (IOException e) { LOG.info("Exception while setting the safe mode flag in ProxyJobTracker: " + e.getMessage()); return false; } catch (TException e) { LOG.info("Exception while setting the safe mode flag in ProxyJobTracker: " + e.getMessage()); return false; } this.safeMode = safeMode; LOG.info("Flag successfully set in ProxyJobTracker"); LOG.info("Safe mode is now: " + (this.safeMode ? "ON" : "OFF")); return true; }
python
def install(modal): """Perform first time install""" if _state.get("installed"): sys.stdout.write("Already installed, uninstalling..\n") uninstall() use_threaded_wrapper = not modal install_callbacks() install_host(use_threaded_wrapper) _state["installed"] = True
java
private static Class<?> loadClass(final String className) throws ClassNotFoundException { ClassLoader ctxCL = Thread.currentThread().getContextClassLoader(); if (ctxCL == null) { return Class.forName(className); } return ctxCL.loadClass(className); }
java
@Activate protected void activate(ComponentContext cc) { executorServiceRef.activate(cc); scheduledExecutorServiceRef.activate(cc); classLoadingServiceSR.activate(cc); WSExecutorService executorService = executorServiceRef.getService(); ScheduledExecutorService scheduledExecutorService = scheduledExecutorServiceRef.getService(); if (executorService != null && scheduledExecutorService != null) { automaticeWorkQueue = new LibertyJaxRsAutomaticWorkQueueImpl(scheduledExecutorService, executorService); workQueueBusListener = new LibertyAutomaticWorkQueueBusListener(); LibertyApplicationBusFactory.getInstance().registerApplicationBusListener(workQueueBusListener); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "LibertyAutomaticWorkQueueBusListener is registered into LibertyApplicationBusFactory"); } } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "LibertyAutomaticWorkQueueBusListener is not registered into LibertyApplicationBusFactory due to executorService {0} or scheduledExecutorService {1}", (executorService == null ? "NULL" : "NOT NULL"), (scheduledExecutorService == null ? "NULL" : "NOT NULL")); } } }
java
private Source sanitizeXml(@Nullable String xml) { if (xml != null && !sensitiveXPathStrings.isEmpty()) { try { DocumentBuilder documentBuilder = documentBuilderSupplier.get(); XPath xpath = xpathSupplier.get(); if (documentBuilder != null && xpath != null) { Document doc = documentBuilder.parse(new InputSource(new StringReader(xml))); for (String xpathString : sensitiveXPathStrings) { XPathExpression expr = xpath.compile(xpathString); Node node = (Node) expr.evaluate(doc, XPathConstants.NODE); if (node != null && node.getTextContent() != null) { node.setTextContent("REDACTED"); } } return new DOMSource(doc); } } catch (SAXException e) { libLogger.warn("Unable to parse XML: {}", e); } catch (IOException e) { libLogger.warn("Unable to parse XML: {}", e); } catch (XPathExpressionException e) { libLogger.warn("Unable to parse XML: {}", e); } } return null; }
java
public static FormValidation validateArtifactoryCombinationFilter(String value) throws IOException, InterruptedException { String url = Util.fixEmptyAndTrim(value); if (url == null) return FormValidation.error("Mandatory field - You don`t have any deploy matches"); return FormValidation.ok(); }
java
public void marshall(FlinkApplicationConfigurationDescription flinkApplicationConfigurationDescription, ProtocolMarshaller protocolMarshaller) { if (flinkApplicationConfigurationDescription == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(flinkApplicationConfigurationDescription.getCheckpointConfigurationDescription(), CHECKPOINTCONFIGURATIONDESCRIPTION_BINDING); protocolMarshaller.marshall(flinkApplicationConfigurationDescription.getMonitoringConfigurationDescription(), MONITORINGCONFIGURATIONDESCRIPTION_BINDING); protocolMarshaller.marshall(flinkApplicationConfigurationDescription.getParallelismConfigurationDescription(), PARALLELISMCONFIGURATIONDESCRIPTION_BINDING); protocolMarshaller.marshall(flinkApplicationConfigurationDescription.getJobPlanDescription(), JOBPLANDESCRIPTION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def draw(self): '''Draw the tree of UI elements once directly to the terminal. The root element of the UI is referenced by this instance's :attr:`element` attribute. Layout is automatically calculated by the UI elements in the tree in reponse ultimately to the :attr:`width` and :attr:`height` attributes of this instances :class:`Terminal`: instance. There is no async behaviour triggered from this method - see :meth:`run` if you want to :mod:`jcn` to take care redrawing when required. ''' super().draw( self.terminal.width, self.terminal.height, terminal=self.terminal, styles=self.style)
java
@Override public JsMessage getSent(boolean copy) throws MessageCopyFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getSent", copy); // We don't want to fluff up an MQMD PropertyMap unnecessarily, so we try to // figure out first whether there have been any MQMD properties set.... if (hasMQMDPropertiesSet()) { // If there may be some explicitly set JMS_IBM_MQMD_ properties, get it from // the map. Do NOT just call getMQMDProperty() as that would also look in any // underlying MQMD. byte[] apiMsgId = (byte[]) getMQMDSetPropertiesMap().get(SIProperties.JMS_IBM_MQMD_MsgId); if (apiMsgId != null) { setApiMessageIdAsBytes(apiMsgId); } } // Finally call the superclass's method & return the result. JsMessage newMsg = super.getSent(copy); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getSent", newMsg); return newMsg; }
java
public static <T> Gather<T> from(Enumeration<T> enumeration) { return null == enumeration ? Gather.<T>empty() : from(Iterators.forEnumeration(enumeration)); }
java
static String javaPropertyToJSProperty(final String getterSetterMethod) { if (!isJavaPropertyMethod(getterSetterMethod)) { throw new JsiiException("Invalid getter/setter method. Must start with get/set"); } String camelCase = getterSetterMethod.substring( PROPERTY_METHOD_PREFIX_LEN, PROPERTY_METHOD_PREFIX_LEN + 1).toLowerCase(); if (getterSetterMethod.length() > PROPERTY_METHOD_PREFIX_LEN + 1) { camelCase += getterSetterMethod.substring(PROPERTY_METHOD_PREFIX_LEN + 1); } return camelCase; }
python
def get_data(start, end, username=None, password=None, data_path=os.path.abspath(".")+'/tmp_data'): """**Download data (badly) from Blitzorg** Using a specified time stamp for start and end, data is downloaded at a default frequency (10 minute intervals). If a directory called data is not present, it will be added to the cwd as the target for the downloads. This is probably a bad idea however. It is much better to 1) get the data from Blitzorg directly, or 2) if you only want a small part of the data and have an account, download a csv file via their web interface. :paramter start: string :parameter end: string :parameter freq: string :Example: >>> get_data(start="2015-02-01T06:30", end="2015-02-01T10:05") """ dl_link = "http://data.blitzortung.org/Data_1/Protected/Strokes/" if not os.path.exists(data_path): os.makedirs(data_path) if not username: username = input("Username to access Blitzorg with:") password = getpass.getpass( prompt='Enter password for {0}:'.format(username)) auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm='Blitzortung', uri='http://data.blitzortung.org', user=username, passwd=password) opener = urllib.request.build_opener(auth_handler) urllib.request.install_opener(opener) time_range = pd.date_range(start, end, freq='10min') for time_stamp in tqdm(time_range): tmp_link = dl_link+'/'.join(return_time_elements(time_stamp))\ + '.json.gz' tmp_name = "./tmp_data/bz-"+'-'.join(return_time_elements(time_stamp))\ + ".json.gz" if os.path.isfile(tmp_name): print("{0} exists. Aborting download attempt".format(tmp_name)) else: try: urllib.request.urlretrieve(tmp_link, tmp_name) except Exception as inst: print(inst) print(' Encountered unknown error. Continuing.')
java
public void addJobListener (@Nonnull final IJobListener aJobListener) { ValueEnforcer.notNull (aJobListener, "JobListener"); try { m_aScheduler.getListenerManager ().addJobListener (aJobListener, EverythingMatcher.allJobs ()); } catch (final SchedulerException ex) { throw new IllegalStateException ("Failed to add job listener " + aJobListener.toString (), ex); } }
java
@ManyToOne(targetEntity = org.openprovenance.prov.sql.QualifiedName.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "TRIGGER_") public org.openprovenance.prov.model.QualifiedName getTrigger() { return trigger; }
python
def set_examples(self, examples): """Sets the examples to be displayed in WIT. Args: examples: List of example protos. Returns: self, in order to enabled method chaining. """ self.store('examples', examples) if len(examples) > 0: self.store('are_sequence_examples', isinstance(examples[0], tf.train.SequenceExample)) return self
java
public void beforeConvert(SO outputSchema, DI inputRecord, WorkUnitState workUnit) { Instrumented.markMeter(this.recordsInMeter); }
python
def resolve_font(name): """Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir, 'NotoSans-Bold.ttf') >>> noto_path = os.path.abspath(noto_path) >>> assert path == noto_path Absolute paths are allowed:: >>> resolve_font(noto_path) == noto_path True Raises :exc:`FontNotFound` on failure:: >>> try: ... resolve_font('blahahaha') ... assert False ... except FontNotFound: ... pass """ if os.path.exists(name): return os.path.abspath(name) fonts = get_font_files() if name in fonts: return fonts[name] raise FontNotFound("Can't find %r :'( Try adding it to ~/.fonts" % name)
python
def _pick_best_quality_score(vrn_file): """Flexible quality score selection, picking the best available. Implementation based on discussion: https://github.com/bcbio/bcbio-nextgen/commit/a538cecd86c0000d17d3f9d4f8ac9d2da04f9884#commitcomment-14539249 (RTG=AVR/GATK=VQSLOD/MuTect=t_lod_fstar, otherwise GQ, otherwise QUAL, otherwise DP.) For MuTect, it's not clear how to get t_lod_fstar, the right quality score, into VCF cleanly. MuTect2 has TLOD in the INFO field. """ # pysam fails on checking reference contigs if input is empty if not vcfutils.vcf_has_variants(vrn_file): return "DP" to_check = 25 scores = collections.defaultdict(int) try: in_handle = VariantFile(vrn_file) except ValueError: raise ValueError("Failed to parse input file in preparation for validation: %s" % vrn_file) with contextlib.closing(in_handle) as val_in: for i, rec in enumerate(val_in): if i > to_check: break if "VQSLOD" in rec.info and rec.info.get("VQSLOD") is not None: scores["INFO=VQSLOD"] += 1 if "TLOD" in rec.info and rec.info.get("TLOD") is not None: scores["INFO=TLOD"] += 1 for skey in ["AVR", "GQ", "DP"]: if len(rec.samples) > 0 and rec.samples[0].get(skey) is not None: scores[skey] += 1 if rec.qual: scores["QUAL"] += 1 for key in ["AVR", "INFO=VQSLOD", "INFO=TLOD", "GQ", "QUAL", "DP"]: if scores[key] > 0: return key raise ValueError("Did not find quality score for validation from %s" % vrn_file)
java
protected ResourceBundle getResourceBundle(String basename, Locale locale) { if (this.cacheMillis >= 0) { // Fresh ResourceBundle.getBundle call in order to let ResourceBundle // do its native caching, at the expense of more extensive lookup steps. return doGetBundle(basename, locale); } else { // Cache forever: prefer locale cache over repeated getBundle calls. Map<Locale, ResourceBundle> localeMap = this.cachedResourceBundles.get(basename); if (localeMap != null) { ResourceBundle bundle = localeMap.get(locale); if (bundle != null) { return bundle; } } try { ResourceBundle bundle = doGetBundle(basename, locale); if (localeMap == null) { localeMap = new ConcurrentHashMap<>(); Map<Locale, ResourceBundle> existing = this.cachedResourceBundles.putIfAbsent(basename, localeMap); if (existing != null) { localeMap = existing; } } localeMap.put(locale, bundle); return bundle; } catch (MissingResourceException ex) { log.warn("ResourceBundle [" + basename + "] not found for MessageSource: " + ex.getMessage()); // Assume bundle not found // -> do NOT throw the exception to allow for checking parent message source. return null; } } }
python
def update_value(self, offset, value): """Update the binary value currently stored for this config value. Returns: int: An opaque error code that can be returned from a set_config rpc """ if offset + len(value) > self.total_size: return Error.INPUT_BUFFER_TOO_LONG if len(self.current_value) < offset: self.current_value += bytearray(offset - len(self.current_value)) if len(self.current_value) > offset: self.current_value = self.current_value[:offset] self.current_value += bytearray(value) return 0
java
public void removePort(TCPPort endPoint) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "removePort: " + endPoint.getServerSocket()); } synchronized (this) { NBAcceptChannelSelector accept = endPointToAccept.get(endPoint); if (accept != null) { // PK44756 - prevent hang on System.exit by accept selector if (3100 <= accept.numExceptions) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Ignoring removePort call on fatal selector/system.exit path"); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "removePort"); } return; } EndPointActionInfo work = new EndPointActionInfo(REMOVE_ENDPOINT, endPoint, workSync); synchronized (workSync) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(this, tc, "Passing remove to selector; " + endPoint.getServerSocket()); } accept.addWork(work); try { workSync.wait(); } catch (InterruptedException x) { // nothing to do } } // end-sync if (accept == sharedAccept && accept.getUsageCount() <= 0) { sharedAccept = null; } } else { IllegalArgumentException iae = new IllegalArgumentException("TCP Port to be removed is not registered."); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Throwing IllegalArgumentException"); } FFDCFilter.processException(iae, CLASS_NAME + ".removePort", "387", this); throw iae; } } // end-sync-this if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "removePort"); } }
java
private File calculateLogFile(long timestamp) { if (ivSubDirectory == null) getControllingProcessDirectory(timestamp, svPid) ; return getLogFile(ivSubDirectory, timestamp); }
python
def axisfn(reverse=False, principal_node_type=xml.dom.Node.ELEMENT_NODE): """Axis function decorator. An axis function will take a node as an argument and return a sequence over the nodes along an XPath axis. Axis functions have two extra attributes indicating the axis direction and principal node type. """ def decorate(f): f.__name__ = f.__name__.replace('_', '-') f.reverse = reverse f.principal_node_type = principal_node_type return f return decorate
python
def priority_compare(self, other): """ Compares the MIME::Type based on how reliable it is before doing a normal <=> comparison. Used by MIME::Types#[] to sort types. The comparisons involved are: 1. self.simplified <=> other.simplified (ensures that we don't try to compare different types) 2. IANA-registered definitions < other definitions. 3. Generic definitions < platform definitions. 3. Complete definitions < incomplete definitions. 4. Current definitions < obsolete definitions. 5. Obselete with use-instead references < obsolete without. 6. Obsolete use-instead definitions are compared. """ pc = cmp(self.simplified, other.simplified) if pc is 0: if self.is_registered != other.is_registered: # registered < unregistered pc = -1 if self.is_registered else 1 elif self.platform != other.platform: # generic < platform pc = 1 if self.platform else -1 elif self.is_complete != other.is_complete: # complete < incomplete pc = -1 if self.is_complete else 1 elif self.is_obsolete != other.is_obsolete: # current < obsolete pc = 1 if self.is_obsolete else -1 if pc is 0 and self.is_obsolete and (self.use_instead != other.use_instead): if self.use_instead is None: pc = -1 elif other.use_instead is None: pc = 1 else: pc = cmp(self.use_instead, other.use_instead) return pc
python
def get_queryset(self): ''' If MultiTenantMiddleware is used, filter queryset by request.site_id ''' queryset = super(PageList, self).get_queryset() if hasattr(self.request, 'site_id'): queryset = queryset.filter(site_id=self.request.site_id) return queryset
python
def uv_at_xy(self, x, y, x0, y0, s0): """Returns two arrays of u, v""" dx, dy = self.distance(x0, y0, x, y) #print 'dx, dy:', dx, dy rr2 = (dx**2 + dy**2)**-1 u = - s0 * dy * r_twopi * rr2 v = s0 * dx * r_twopi * rr2 #print 'u, v', u, v return u, v
python
def norm_locale (loc): """Normalize a locale.""" loc = locale.normalize(loc) # split up the locale into its base components pos = loc.find('@') if pos >= 0: loc = loc[:pos] pos = loc.find('.') if pos >= 0: loc = loc[:pos] pos = loc.find('_') if pos >= 0: loc = loc[:pos] return loc
java
private static int cqlDateToDaysSinceEpoch(long raw) { if (raw < 0 || raw > MAX_CQL_LONG_VALUE) throw new IllegalArgumentException( String.format( "Numeric literals for DATE must be between 0 and %d (got %d)", MAX_CQL_LONG_VALUE, raw)); return (int) (raw - EPOCH_AS_CQL_LONG); }
python
def sample(self, count, return_index=False): """ Return random samples distributed normally across the surface of the mesh Parameters --------- count : int Number of points to sample return_index : bool If True will also return the index of which face each sample was taken from. Returns --------- samples : (count, 3) float Points on surface of mesh face_index : (count, ) int Index of self.faces """ samples, index = sample.sample_surface(self, count) if return_index: return samples, index return samples
java
public int deleteCascade( Collection<DataColumnConstraints> constraintsCollection) throws SQLException { int count = 0; if (constraintsCollection != null) { for (DataColumnConstraints constraints : constraintsCollection) { count += deleteCascade(constraints); } } return count; }
java
public DescribeReservedInstancesOfferingsResult withReservedInstancesOfferings(ReservedInstancesOffering... reservedInstancesOfferings) { if (this.reservedInstancesOfferings == null) { setReservedInstancesOfferings(new com.amazonaws.internal.SdkInternalList<ReservedInstancesOffering>(reservedInstancesOfferings.length)); } for (ReservedInstancesOffering ele : reservedInstancesOfferings) { this.reservedInstancesOfferings.add(ele); } return this; }
java
public TransportApiResult<List<Stop>> getStopsByBoundingBox(StopQueryOptions options, String boundingBox) { if (options == null) { options = StopQueryOptions.defaultQueryOptions(); } if (boundingBox == null) { throw new IllegalArgumentException("BoundingBox is required."); } String[] bbox = boundingBox.split(",", -1); if (bbox.length != 4) { throw new IllegalArgumentException("Invalid bounding box. See valid examples here: http://developer.whereismytransport.com/documentation#bounding-box."); } return TransportApiClientCalls.getStops(tokenComponent, settings, options, null, null, boundingBox); }
python
def __apply_func(self, other, func_name): """ delegate operations to the *samples* attribute, but in a time correct manner by considering the *timestamps* """ if isinstance(other, Signal): if len(self) and len(other): start = max(self.timestamps[0], other.timestamps[0]) stop = min(self.timestamps[-1], other.timestamps[-1]) s1 = self.cut(start, stop) s2 = other.cut(start, stop) else: s1 = self s2 = other time = np.union1d(s1.timestamps, s2.timestamps) s = self.interp(time).samples o = other.interp(time).samples func = getattr(s, func_name) s = func(o) elif other is None: s = self.samples time = self.timestamps else: func = getattr(self.samples, func_name) s = func(other) time = self.timestamps return Signal( samples=s, timestamps=time, unit=self.unit, name=self.name, conversion=self.conversion, raw=self.raw, master_metadata=self.master_metadata, display_name=self.display_name, attachment=self.attachment, stream_sync=self.stream_sync, invalidation_bits=self.invalidation_bits, source=self.source, encoding=self.encoding, )
java
public Iterator<Entry<K, V>> iterator(int fetchSize, int partitionId, boolean prefetchValues) { return new MapPartitionIterator<>(this, fetchSize, partitionId, prefetchValues); }
java
@Override public void start(Screen screen) { Check.notNull(screen); this.screen = screen; screen.addListener(this); renderer.setScreen(screen); renderer.initResolution(resolution); currentFrameRate = config.getOutput().getRate(); screen.requestFocus(); load(); onLoaded(Constant.EXTRP, screen.getGraphic()); // Main loop final Timing updateFpsTimer = new Timing(); updateFpsTimer.start(); loop.notifyRateChanged(resolution.getRate()); loop.start(screen, new Frame() { @Override public void update(double extrp) { Sequence.this.update(extrp); } @Override public void render() { renderer.render(); } @Override public void computeFrameRate(long lastTime, long currentTime) { Sequence.this.computeFrameRate(updateFpsTimer, lastTime, currentTime); } }); screen.removeListener(this); }
java
public TableWriteItems addHashOnlyPrimaryKeyToDelete( String hashKeyName, Object hashKeyValue) { this.addPrimaryKeyToDelete(new PrimaryKey(hashKeyName, hashKeyValue)); return this; }
java
public final EObject ruleAction() throws RecognitionException { EObject current = null; Token otherlv_0=null; Token otherlv_2=null; Token lv_operator_4_1=null; Token lv_operator_4_2=null; Token otherlv_5=null; Token otherlv_6=null; EObject lv_type_1_0 = null; AntlrDatatypeRuleToken lv_feature_3_0 = null; enterRule(); try { // InternalXtext.g:1359:2: ( (otherlv_0= '{' ( (lv_type_1_0= ruleTypeRef ) ) (otherlv_2= '.' ( (lv_feature_3_0= ruleValidID ) ) ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) otherlv_5= 'current' )? otherlv_6= '}' ) ) // InternalXtext.g:1360:2: (otherlv_0= '{' ( (lv_type_1_0= ruleTypeRef ) ) (otherlv_2= '.' ( (lv_feature_3_0= ruleValidID ) ) ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) otherlv_5= 'current' )? otherlv_6= '}' ) { // InternalXtext.g:1360:2: (otherlv_0= '{' ( (lv_type_1_0= ruleTypeRef ) ) (otherlv_2= '.' ( (lv_feature_3_0= ruleValidID ) ) ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) otherlv_5= 'current' )? otherlv_6= '}' ) // InternalXtext.g:1361:3: otherlv_0= '{' ( (lv_type_1_0= ruleTypeRef ) ) (otherlv_2= '.' ( (lv_feature_3_0= ruleValidID ) ) ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) otherlv_5= 'current' )? otherlv_6= '}' { otherlv_0=(Token)match(input,34,FollowSets000.FOLLOW_13); newLeafNode(otherlv_0, grammarAccess.getActionAccess().getLeftCurlyBracketKeyword_0()); // InternalXtext.g:1365:3: ( (lv_type_1_0= ruleTypeRef ) ) // InternalXtext.g:1366:4: (lv_type_1_0= ruleTypeRef ) { // InternalXtext.g:1366:4: (lv_type_1_0= ruleTypeRef ) // InternalXtext.g:1367:5: lv_type_1_0= ruleTypeRef { newCompositeNode(grammarAccess.getActionAccess().getTypeTypeRefParserRuleCall_1_0()); pushFollow(FollowSets000.FOLLOW_32); lv_type_1_0=ruleTypeRef(); state._fsp--; if (current==null) { current = createModelElementForParent(grammarAccess.getActionRule()); } set( current, "type", lv_type_1_0, "org.eclipse.xtext.Xtext.TypeRef"); afterParserOrEnumRuleCall(); } } // InternalXtext.g:1384:3: (otherlv_2= '.' ( (lv_feature_3_0= ruleValidID ) ) ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) otherlv_5= 'current' )? int alt38=2; int LA38_0 = input.LA(1); if ( (LA38_0==17) ) { alt38=1; } switch (alt38) { case 1 : // InternalXtext.g:1385:4: otherlv_2= '.' ( (lv_feature_3_0= ruleValidID ) ) ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) otherlv_5= 'current' { otherlv_2=(Token)match(input,17,FollowSets000.FOLLOW_3); newLeafNode(otherlv_2, grammarAccess.getActionAccess().getFullStopKeyword_2_0()); // InternalXtext.g:1389:4: ( (lv_feature_3_0= ruleValidID ) ) // InternalXtext.g:1390:5: (lv_feature_3_0= ruleValidID ) { // InternalXtext.g:1390:5: (lv_feature_3_0= ruleValidID ) // InternalXtext.g:1391:6: lv_feature_3_0= ruleValidID { newCompositeNode(grammarAccess.getActionAccess().getFeatureValidIDParserRuleCall_2_1_0()); pushFollow(FollowSets000.FOLLOW_33); lv_feature_3_0=ruleValidID(); state._fsp--; if (current==null) { current = createModelElementForParent(grammarAccess.getActionRule()); } set( current, "feature", lv_feature_3_0, "org.eclipse.xtext.Xtext.ValidID"); afterParserOrEnumRuleCall(); } } // InternalXtext.g:1408:4: ( ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) ) // InternalXtext.g:1409:5: ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) { // InternalXtext.g:1409:5: ( (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) ) // InternalXtext.g:1410:6: (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) { // InternalXtext.g:1410:6: (lv_operator_4_1= '=' | lv_operator_4_2= '+=' ) int alt37=2; int LA37_0 = input.LA(1); if ( (LA37_0==35) ) { alt37=1; } else if ( (LA37_0==36) ) { alt37=2; } else { NoViableAltException nvae = new NoViableAltException("", 37, 0, input); throw nvae; } switch (alt37) { case 1 : // InternalXtext.g:1411:7: lv_operator_4_1= '=' { lv_operator_4_1=(Token)match(input,35,FollowSets000.FOLLOW_34); newLeafNode(lv_operator_4_1, grammarAccess.getActionAccess().getOperatorEqualsSignKeyword_2_2_0_0()); if (current==null) { current = createModelElement(grammarAccess.getActionRule()); } setWithLastConsumed(current, "operator", lv_operator_4_1, null); } break; case 2 : // InternalXtext.g:1422:7: lv_operator_4_2= '+=' { lv_operator_4_2=(Token)match(input,36,FollowSets000.FOLLOW_34); newLeafNode(lv_operator_4_2, grammarAccess.getActionAccess().getOperatorPlusSignEqualsSignKeyword_2_2_0_1()); if (current==null) { current = createModelElement(grammarAccess.getActionRule()); } setWithLastConsumed(current, "operator", lv_operator_4_2, null); } break; } } } otherlv_5=(Token)match(input,37,FollowSets000.FOLLOW_35); newLeafNode(otherlv_5, grammarAccess.getActionAccess().getCurrentKeyword_2_3()); } break; } otherlv_6=(Token)match(input,38,FollowSets000.FOLLOW_2); newLeafNode(otherlv_6, grammarAccess.getActionAccess().getRightCurlyBracketKeyword_3()); } } leaveRule(); } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; }
java
@Override public void remove(Object handle) throws IOException { if (!(handle instanceof File)) { throw new IllegalArgumentException("Expected File, but was " + handle.getClass()); } File eventFile = (File) handle; if (eventFile.exists() && eventFile.isFile()) { if (eventFile.delete()) { KeenLogging.log(String.format(Locale.US, "Successfully deleted file: %s", eventFile.getAbsolutePath())); } else { KeenLogging.log(String.format(Locale.US, "CRITICAL ERROR: Could not remove event at %s", eventFile.getAbsolutePath())); } } else { KeenLogging.log(String.format(Locale.US, "WARNING: no event found at %s", eventFile.getAbsolutePath())); } }
java
public StrPosition getAfterOfWithDetails(String srcStr, String token) { return getAfterOfWithDetails(srcStr, token, true); }
python
def determine_2(self, container_name, container_alias, meta, val): """"Default the alias to the name of the container""" if container_alias is not NotSpecified: return container_alias return container_name[container_name.rfind(":")+1:].replace('/', '-')
python
def updated_current_fields( self, update_fields): """updated_current_fields :param update_fields: dict with values for updating fields_to_add """ self.fields_to_add = {} for k in self.org_fields: self.fields_to_add[k] = self.org_fields[k] self.fields_to_add.update(update_fields)
python
def retrieve_dcnm_net_info(self, tenant_id, direc): """Retrieves the DCNM network info for a tenant. """ serv_obj = self.get_service_obj(tenant_id) net_dict = serv_obj.get_dcnm_net_dict(direc) return net_dict
python
def get(self): """ Get a JSON-ready representation of this CustomArg. :returns: This CustomArg, ready for use in a request body. :rtype: dict """ custom_arg = {} if self.key is not None and self.value is not None: custom_arg[self.key] = self.value return custom_arg
python
def meanApprox(self, timeout, confidence=0.95): """ .. note:: Experimental Approximate operation to return the mean within a timeout or meet the confidence. >>> rdd = sc.parallelize(range(1000), 10) >>> r = sum(range(1000)) / 1000.0 >>> abs(rdd.meanApprox(1000) - r) / r < 0.05 True """ jrdd = self.map(float)._to_java_object_rdd() jdrdd = self.ctx._jvm.JavaDoubleRDD.fromRDD(jrdd.rdd()) r = jdrdd.meanApprox(timeout, confidence).getFinalValue() return BoundedFloat(r.mean(), r.confidence(), r.low(), r.high())
java
protected void sendData(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws IOException { long resLength = resource.length(); boolean include = request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) != null; // Get the output stream (or writer) OutputStream out = null; try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } // see if there are any range headers Enumeration reqRanges = include ? null : request.getHeaders(HttpFields.__Range); if (reqRanges == null || !reqRanges.hasMoreElements()) { // if there were no ranges, send entire entity Resource data = resource; if (!include) { // look for a gziped content. if (_minGzipLength > 0) { String accept = request.getHeader(HttpFields.__AcceptEncoding); if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz")) { Resource gz = getResource(pathInContext + ".gz"); if (gz.exists() && accept.indexOf("gzip") >= 0 && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null) { response.setHeader(HttpFields.__ContentEncoding, "gzip"); data = gz; resLength = data.length(); } } } writeHeaders(response, resource, resLength); } data.writeTo(out, 0, resLength); return; } // Parse the satisfiable ranges List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength); // if there are no satisfiable ranges, send 416 response if (ranges == null || ranges.size() == 0) { writeHeaders(response, resource, resLength); response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable); response.setHeader(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength)); resource.writeTo(out, 0, resLength); return; } // if there is only a single valid range (must be satisfiable // since were here now), send that range with a 216 response if (ranges.size() == 1) { InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0); long singleLength = singleSatisfiableRange.getSize(resLength); writeHeaders(response, resource, singleLength); response.setStatus(HttpResponse.__206_Partial_Content); response.setHeader(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength)); resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength); return; } // multiple non-overlapping valid ranges cause a multipart // 216 response which does not require an overall // content-length header // writeHeaders(response, resource, -1); ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource); String encoding = metaData.getMimeType(); MultiPartResponse multi = new MultiPartResponse(response.getOutputStream()); response.setStatus(HttpResponse.__206_Partial_Content); // If the request has a "Request-Range" header then we need to // send an old style multipart/x-byteranges Content-Type. This // keeps Netscape and acrobat happy. This is what Apache does. String ctp; if (request.getHeader(HttpFields.__RequestRange) != null) ctp = "multipart/x-byteranges; boundary="; else ctp = "multipart/byteranges; boundary="; response.setContentType(ctp + multi.getBoundary()); InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream(); long pos = 0; for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength); multi.startPart(encoding, new String[] { header}); long start = ibr.getFirst(resLength); long size = ibr.getSize(resLength); if (in != null) { // Handle non cached resource if (start < pos) { in.close(); in = resource.getInputStream(); pos = 0; } if (pos < start) { in.skip(start - pos); pos = start; } IO.copy(in, out, size); pos += size; } else // Handle cached resource (resource).writeTo(out, start, size); } if (in != null) in.close(); multi.close(); return; }