language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public int size() { int result = 0; for (O o : multiplicities.keySet()) { result += multiplicity(o); } return result; }
python
def append(self, result): """ Append a new Result to the list. :param result: Result to append :return: Nothing :raises: TypeError if result is not Result or ResultList """ if isinstance(result, Result): self.data.append(result) elif isinstance(result, ResultList): self.data += result.data else: raise TypeError('unknown result type')
python
def tensor_index(self, datapoint_index): """ Returns the index of the tensor containing the referenced datapoint. """ if datapoint_index >= self._num_datapoints: raise ValueError('Datapoint index %d is greater than the number of datapoints (%d)' %(datapoint_index, self._num_datapoints)) return self._index_to_file_num[datapoint_index]
python
def as_dict(self, absolute=False): """ Return the dependencies as a dictionary. Returns: dict: dictionary of dependencies. """ return { 'name': self.absolute_name() if absolute else self.name, 'path': self.path, 'dependencies': [{ # 'source': d.source.absolute_name(), # redundant 'target': d.target if d.external else d.target.absolute_name(), 'lineno': d.lineno, 'what': d.what, 'external': d.external } for d in self.dependencies] }
java
public static AnnotatorCache getInstance() { if (INSTANCE == null) { synchronized (AnnotatorCache.class) { if (INSTANCE == null) { INSTANCE = new AnnotatorCache(); } } } return INSTANCE; }
java
private void refreshItemViewHolder(@NonNull ViewHolder holder, boolean isRowDragging, boolean isColumnDragging) { int left = getEmptySpace() + mManager.getColumnsWidth(0, Math.max(0, holder.getColumnIndex())); int top = mManager.getRowsHeight(0, Math.max(0, holder.getRowIndex())); View view = holder.getItemView(); if (isColumnDragging && holder.isDragging() && mDragAndDropPoints.getOffset().x > 0) { // visible dragging column. Calculate left offset using drag and drop points. left = mState.getScrollX() + mDragAndDropPoints.getOffset().x - view.getWidth() / 2; if (!isRTL()) { left -= mManager.getHeaderRowWidth(); } view.bringToFront(); } else if (isRowDragging && holder.isDragging() && mDragAndDropPoints.getOffset().y > 0) { // visible dragging row. Calculate top offset using drag and drop points. top = mState.getScrollY() + mDragAndDropPoints.getOffset().y - view.getHeight() / 2 - mManager.getHeaderColumnHeight(); view.bringToFront(); } int leftMargin = holder.getColumnIndex() * mSettings.getCellMargin() + mSettings.getCellMargin(); int topMargin = holder.getRowIndex() * mSettings.getCellMargin() + mSettings.getCellMargin(); if (!isRTL()) { left += mManager.getHeaderRowWidth(); } // calculate view layout positions int viewPosLeft = left - mState.getScrollX() + leftMargin; int viewPosRight = viewPosLeft + mManager.getColumnWidth(holder.getColumnIndex()); int viewPosTop = top - mState.getScrollY() + mManager.getHeaderColumnHeight() + topMargin; int viewPosBottom = viewPosTop + mManager.getRowHeight(holder.getRowIndex()); // update layout position view.layout(viewPosLeft, viewPosTop, viewPosRight, viewPosBottom); }
java
public void setMemberServices(MemberServices memberServices) { this.memberServices = memberServices; if (memberServices instanceof MemberServicesImpl) { this.cryptoPrimitives = ((MemberServicesImpl) memberServices).getCrypto(); } }
python
def get_logging_file(maximum_logging_files=10, retries=2 ^ 16): """ Returns the logging file path. :param maximum_logging_files: Maximum allowed logging files in the logging directory. :type maximum_logging_files: int :param retries: Number of retries to generate a unique logging file name. :type retries: int :return: Logging file path. :rtype: unicode """ logging_directory = os.path.join(RuntimeGlobals.user_application_data_directory, Constants.logging_directory) for file in sorted(foundations.walkers.files_walker(logging_directory), key=lambda y: os.path.getmtime(os.path.abspath(y)), reverse=True)[maximum_logging_files:]: try: os.remove(file) except OSError: LOGGER.warning( "!> {0} | Cannot remove '{1}' file!".format(__name__, file, Constants.application_name)) path = None for i in range(retries): path = os.path.join(RuntimeGlobals.user_application_data_directory, Constants.logging_directory, Constants.logging_file.format(foundations.strings.get_random_sequence())) if not os.path.exists(path): break if path is None: raise umbra.exceptions.EngineConfigurationError( "{0} | Logging file is not available, '{1}' will now close!".format(__name__, Constants.application_name)) LOGGER.debug("> Current Logging file: '{0}'".format(path)) return path
java
public void marshall(GitSubmodulesConfig gitSubmodulesConfig, ProtocolMarshaller protocolMarshaller) { if (gitSubmodulesConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gitSubmodulesConfig.getFetchSubmodules(), FETCHSUBMODULES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
private void processDumpFileContentsRecovery(InputStream inputStream) throws IOException { JsonDumpFileProcessor.logger .warn("Entering recovery mode to parse rest of file. This might be slightly slower."); BufferedReader br = new BufferedReader(new InputStreamReader( inputStream)); String line = br.readLine(); if (line == null) { // can happen if iterator already has consumed all // the stream return; } if (line.length() >= 100) { line = line.substring(0, 100) + "[...]" + line.substring(line.length() - 50); } JsonDumpFileProcessor.logger.warn("Skipping rest of current line: " + line); line = br.readLine(); while (line != null && line.length() > 1) { try { EntityDocument document; if (line.charAt(line.length() - 1) == ',') { document = documentReader.readValue(line.substring(0, line.length() - 1)); } else { document = documentReader.readValue(line); } handleDocument(document); } catch (JsonProcessingException e) { logJsonProcessingException(e); JsonDumpFileProcessor.logger.error("Problematic line was: " + line.substring(0, Math.min(50, line.length())) + "..."); } line = br.readLine(); } }
java
void appendHex( int value, int digits ) { if( digits > 1 ) { appendHex( value >>> 4, digits-1 ); } output.append( DIGITS[ value & 0xF ] ); }
python
def pythonise(id, encoding='ascii'): """Return a Python-friendly id""" replace = {'-': '_', ':': '_', '/': '_'} func = lambda id, pair: id.replace(pair[0], pair[1]) id = reduce(func, replace.iteritems(), id) id = '_%s' % id if id[0] in string.digits else id return id.encode(encoding)
java
public static Icon getAvatar(DiscordApi api, String avatarHash, String discriminator, long userId) { StringBuilder url = new StringBuilder("https://cdn.discordapp.com/"); if (avatarHash == null) { url.append("embed/avatars/") .append(Integer.parseInt(discriminator) % 5) .append(".png"); } else { url.append("avatars/") .append(userId).append('/').append(avatarHash) .append(avatarHash.startsWith("a_") ? ".gif" : ".png"); } try { return new IconImpl(api, new URL(url.toString())); } catch (MalformedURLException e) { logger.warn("Seems like the url of the avatar is malformed! Please contact the developer!", e); return null; } }
python
def print_summary(self) -> None: """ Prints the tasks' timing summary. """ print("Tasks execution time summary:") for mon_task in self._monitor_tasks: print("%s:\t%.4f (sec)" % (mon_task.task_name, mon_task.total_time))
python
def set_url (self, url): """Set the URL referring to a robots.txt file.""" self.url = url self.host, self.path = urlparse.urlparse(url)[1:3]
java
private List<String> getValues(UserCoreResult<?, ?, ?> results) { List<String> values = null; if (results != null) { try { if (results.getCount() > 0) { int columnIndex = results.getColumnIndex(COLUMN_VALUE); values = getColumnResults(columnIndex, results); } else { values = new ArrayList<>(); } } finally { results.close(); } } else { values = new ArrayList<>(); } return values; }
python
def get_angle_degrees(self, indices): """Return the angles between given atoms. Calculates the angle in degrees between the atoms with indices ``i, b, a``. The indices can be given in three ways: * As simple list ``[i, b, a]`` * As list of lists: ``[[i1, b1, a1], [i2, b2, a2]...]`` * As :class:`pd.DataFrame` where ``i`` is taken from the index and ``b`` and ``a`` from the respective columns ``'b'`` and ``'a'``. Args: indices (list): Returns: :class:`numpy.ndarray`: Vector of angles in degrees. """ coords = ['x', 'y', 'z'] if isinstance(indices, pd.DataFrame): i_pos = self.loc[indices.index, coords].values b_pos = self.loc[indices.loc[:, 'b'], coords].values a_pos = self.loc[indices.loc[:, 'a'], coords].values else: indices = np.array(indices) if len(indices.shape) == 1: indices = indices[None, :] i_pos = self.loc[indices[:, 0], coords].values b_pos = self.loc[indices[:, 1], coords].values a_pos = self.loc[indices[:, 2], coords].values BI, BA = i_pos - b_pos, a_pos - b_pos bi, ba = [v / np.linalg.norm(v, axis=1)[:, None] for v in (BI, BA)] dot_product = np.sum(bi * ba, axis=1) dot_product[dot_product > 1] = 1 dot_product[dot_product < -1] = -1 angles = np.degrees(np.arccos(dot_product)) return angles
python
def list(self, request, *args, **kwargs): """ To get a list of customers, run GET against */api/customers/* as authenticated user. Note that a user can only see connected customers: - customers that the user owns - customers that have a project where user has a role Staff also can filter customers by user UUID, for example /api/customers/?user_uuid=<UUID> Staff also can filter customers by exists accounting_start_date, for example: The first category: /api/customers/?accounting_is_running=True has accounting_start_date empty (i.e. accounting starts at once) has accounting_start_date in the past (i.e. has already started). Those that are not in the first: /api/customers/?accounting_is_running=False # exists accounting_start_date """ return super(CustomerViewSet, self).list(request, *args, **kwargs)
java
public Point<Object> getValues(Point<Integer> locations) { Point<Object> result; Object[] values; int i; if (locations.dimensions() != dimensions()) throw new IllegalArgumentException( "Dimension mismatch: space=" + dimensions() + ", locations=" + locations.dimensions()); values = new Object[locations.dimensions()]; for (i = 0; i < values.length; i++) values[i] = getDimension(i).getValue(locations.getValue(i)); result = new Point<Object>(values); return result; }
java
private void setWidth(int width) { contentParams.width = options.fullScreenPeek() ? screenWidth : width; content.setLayoutParams(contentParams); }
java
public boolean isSpecTopicInLevel(final SpecTopic topic) { final SpecTopic foundTopic = getClosestTopic(topic, false); return foundTopic != null; }
java
public void note(DiagnosticPosition pos, String key, Object ... args) { note(pos, diags.noteKey(key, args)); }
python
def extract_sequences(self, ids, new_path=None): """Will take all the sequences from the current file who's id appears in the ids given and place them in the new file path given.""" # Temporary path # if new_path is None: new_fasta = self.__class__(new_temp_path()) elif isinstance(new_path, FASTA): new_fasta = new_path else: new_fasta = self.__class__(new_path) # Do it # new_fasta.create() for seq in self: if seq.id in ids: new_fasta.add_seq(seq) new_fasta.close() return new_fasta
python
def tick(self): """Return the time cost string as expect.""" string = self.passed if self.rounding: string = round(string) if self.readable: string = self.readable(string) return string
python
def get_absolute_tool_path(command): """ Given an invocation command, return the absolute path to the command. This works even if commnad has not path element and is present in PATH. """ assert isinstance(command, basestring) if os.path.dirname(command): return os.path.dirname(command) else: programs = path.programs_path() m = path.glob(programs, [command, command + '.exe' ]) if not len(m): if __debug_configuration: print "Could not find:", command, "in", programs return None return os.path.dirname(m[0])
java
public void forEach(final IntIntConsumer consumer) { final int[] entries = this.entries; final int initialValue = this.initialValue; @DoNotSub final int length = entries.length; for (@DoNotSub int i = 0; i < length; i += 2) { if (entries[i + 1] != initialValue) // lgtm [java/index-out-of-bounds] { consumer.accept(entries[i], entries[i + 1]); // lgtm [java/index-out-of-bounds] } } }
java
public org.tensorflow.framework.OptimizerOptions getOptimizerOptions() { return optimizerOptions_ == null ? org.tensorflow.framework.OptimizerOptions.getDefaultInstance() : optimizerOptions_; }
java
public static Function<Object,BigInteger> methodForBigInteger(final String methodName, final Object... optionalParameters) { return new Call<Object,BigInteger>(Types.BIG_INTEGER, methodName, VarArgsUtil.asOptionalObjectArray(Object.class,optionalParameters)); }
python
def checkout(self, revision, options): """ Checkout a specific revision. :param revision: The revision identifier. :type revision: :class:`Revision` :param options: Any additional options. :type options: ``dict`` """ rev = revision.key self.repo.git.checkout(rev)
java
@Nonnull public static EChange setUseSSL (final boolean bUseSSL) { return s_aRWLock.writeLocked ( () -> { if (s_bUseSSL == bUseSSL) return EChange.UNCHANGED; s_bUseSSL = bUseSSL; return EChange.CHANGED; }); }
python
def jwt_optional(fn): """ If you decorate a view with this, it will check the request for a valid JWT and put it into the Flask application context before calling the view. If no authorization header is present, the view will be called without the application context being changed. Other authentication errors are not affected. For example, if an expired JWT is passed in, it will still not be able to access an endpoint protected by this decorator. :param fn: The view function to decorate """ @wraps(fn) def wrapper(*args, **kwargs): try: jwt_data = _decode_jwt_from_headers() ctx_stack.top.jwt = jwt_data except (NoAuthorizationError, InvalidHeaderError): pass return fn(*args, **kwargs) return wrapper
java
public JBBPDslBuilder Custom(final String type, final String name) { return this.Custom(type, name, null); }
python
def reduce_logsumexp(x, reduced_dim, extra_logit=None, name=None): """Numerically stable version of log(reduce_sum(exp(x))). Unlike other reductions, the output has the same shape as the input. Note: with a minor change, we could allow multiple reduced dimensions. Args: x: a Tensor reduced_dim: a dimension in x extra_logit: an optional Tensor broadcastable to (x.shape - reduced_dim) name: an optional string Returns: a Tensor with the same shape and dtype as x. """ reduced_dim = convert_to_dimension(reduced_dim) with tf.variable_scope(name, default_name="reduce_logsumexp"): reduced_shape = x.shape - reduced_dim max_logit = reduce_max(stop_gradient(x), output_shape=reduced_shape) if extra_logit is not None: if isinstance(extra_logit, Tensor): extra_logit = stop_gradient(extra_logit) max_logit = maximum(max_logit, extra_logit) x -= max_logit exp_x = exp(x) sum_exp_x = reduce_sum(exp_x, output_shape=reduced_shape) if extra_logit is not None: sum_exp_x += exp(extra_logit - max_logit) return log(sum_exp_x) + max_logit
python
def set_(package, question, type, value, *extra): ''' Set answers to debconf questions for a package. CLI Example: .. code-block:: bash salt '*' debconf.set <package> <question> <type> <value> [<value> ...] ''' if extra: value = ' '.join((value,) + tuple(extra)) fd_, fname = salt.utils.files.mkstemp(prefix="salt-", close_fd=False) line = "{0} {1} {2} {3}".format(package, question, type, value) os.write(fd_, salt.utils.stringutils.to_bytes(line)) os.close(fd_) _set_file(fname) os.unlink(fname) return True
python
def __start_timer(self, delay): """ Starts the reconnection timer :param delay: Delay (in seconds) before calling the reconnection method """ self.__timer = threading.Timer(delay, self.__reconnect) self.__timer.daemon = True self.__timer.start()
python
def get_hierarchy_traversal_session_for_hierarchy(self, hierarchy_id, proxy): """Gets the ``OsidSession`` associated with the hierarchy traversal service for the given hierarchy. arg: hierarchy_id (osid.id.Id): the ``Id`` of the hierarchy arg: proxy (osid.proxy.Proxy): a proxy return: (osid.hierarchy.HierarchyTraversalSession) - a ``HierarchyTraversalSession`` raise: NotFound - ``hierarchyid`` not found raise: NullArgument - ``hierarchy_id`` or ``proxy`` is ``null`` raise: OperationFailed - ``unable to complete request`` raise: Unimplemented - ``supports_hierarchy_traversal()`` or ``supports_visible_federation()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_hierarchy_traversal()`` and ``supports_visible_federation()`` are ``true``.* """ if not self.supports_hierarchy_traversal(): raise errors.Unimplemented() ## # Also include check to see if the catalog Id is found otherwise raise errors.NotFound ## # pylint: disable=no-member return sessions.HierarchyTraversalSession(hierarchy_id, proxy, self._runtime)
java
public static Message DecodeFromBytes(byte[] rgbData, MessageTag defaultTag) throws CoseException { CBORObject messageObject = CBORObject.DecodeFromBytes(rgbData); if (messageObject.getType() != CBORType.Array) throw new CoseException("Message is not a COSE security Message"); if (messageObject.isTagged()) { if (messageObject.GetTags().length != 1) throw new CoseException("Malformed message - too many tags"); if (defaultTag == MessageTag.Unknown) { defaultTag = MessageTag.FromInt(messageObject.getInnermostTag().intValue()); } else if (defaultTag != MessageTag.FromInt(messageObject.getInnermostTag().intValue())) { throw new CoseException("Passed in tag does not match actual tag"); } } Message msg; switch (defaultTag) { case Unknown: // Unknown throw new CoseException("Message was not tagged and no default tagging option given"); case Encrypt: msg = new EncryptMessage(); break; case Encrypt0: msg = new Encrypt0Message(); break; case MAC: msg = new MACMessage(); break; case MAC0: msg = new MAC0Message(); break; case Sign1: msg = new Sign1Message(); break; case Sign: msg = new SignMessage(); break; default: throw new CoseException("Message is not recognized as a COSE security Object"); } msg.DecodeFromCBORObject(messageObject); CBORObject countersignature = msg.findAttribute(HeaderKeys.CounterSignature, UNPROTECTED); if (countersignature != null) { if ((countersignature.getType() != CBORType.Array) || (countersignature.getValues().isEmpty())) { throw new CoseException("Invalid countersignature attribute"); } if (countersignature.get(0).getType() == CBORType.Array) { for (CBORObject obj : countersignature.getValues()) { if (obj.getType() != CBORType.Array) { throw new CoseException("Invalid countersignature attribute"); } CounterSign cs = new CounterSign(obj); cs.setObject(msg); msg.addCountersignature(cs); } } else { CounterSign cs = new CounterSign(countersignature); cs.setObject(msg); msg.addCountersignature(cs); } } countersignature = msg.findAttribute(HeaderKeys.CounterSignature0, UNPROTECTED); if (countersignature != null) { if (countersignature.getType() != CBORType.ByteString) { throw new CoseException("Invalid Countersignature0 attribute"); } CounterSign1 cs = new CounterSign1(countersignature.GetByteString()); cs.setObject(msg); msg.counterSign1 = cs; } return msg; }
java
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map<?, ?> map) { buffer.append(map); }
java
private void calcPrincipalRotationVector() { // AxisAngle4d axisAngle = helixLayers.getByLowestAngle().getAxisAngle(); AxisAngle4d axisAngle = helixLayers.getByLargestContacts().getAxisAngle(); principalRotationVector = new Vector3d(axisAngle.x, axisAngle.y, axisAngle.z); }
python
def equals(self, actual_seq): """Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool """ try: expected = dict([(element, None) for element in self._expected_seq]) actual = dict([(element, None) for element in actual_seq]) except TypeError: # Fall back to slower list-compare if any of the objects are unhashable. expected = list(self._expected_seq) actual = list(actual_seq) expected.sort() actual.sort() return expected == actual
java
public Set<OIdentifiable> getOutEdgesHavingProperties(final OIdentifiable iVertex, Iterable<String> iProperties) { final ODocument vertex = iVertex.getRecord(); checkVertexClass(vertex); return filterEdgesByProperties((OMVRBTreeRIDSet) vertex.field(VERTEX_FIELD_OUT), iProperties); }
java
public void addBroadcastConnection(String name, DagConnection broadcastConnection) { this.broadcastConnectionNames.add(name); this.broadcastConnections.add(broadcastConnection); }
python
def query_by_assignment(self, assignment_id, end_time=None, start_time=None): """ Query by assignment. List grade change events for a given assignment. """ path = {} data = {} params = {} # REQUIRED - PATH - assignment_id """ID""" path["assignment_id"] = assignment_id # OPTIONAL - start_time """The beginning of the time range from which you want events.""" if start_time is not None: params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want events.""" if end_time is not None: params["end_time"] = end_time self.logger.debug("GET /api/v1/audit/grade_change/assignments/{assignment_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/audit/grade_change/assignments/{assignment_id}".format(**path), data=data, params=params, all_pages=True)
python
def check_types(srctype, sinktype, linkMerge, valueFrom): # type: (Any, Any, Optional[Text], Optional[Text]) -> Text """Check if the source and sink types are "pass", "warning", or "exception". """ if valueFrom is not None: return "pass" if linkMerge is None: if can_assign_src_to_sink(srctype, sinktype, strict=True): return "pass" if can_assign_src_to_sink(srctype, sinktype, strict=False): return "warning" return "exception" if linkMerge == "merge_nested": return check_types({"items": _get_type(srctype), "type": "array"}, _get_type(sinktype), None, None) if linkMerge == "merge_flattened": return check_types(merge_flatten_type(_get_type(srctype)), _get_type(sinktype), None, None) raise WorkflowException(u"Unrecognized linkMerge enum '{}'".format(linkMerge))
python
def default_styles(): """Generate default ODF styles.""" styles = {} def _add_style(name, **kwargs): styles[name] = _create_style(name, **kwargs) _add_style('heading-1', family='paragraph', fontsize='24pt', fontweight='bold', ) _add_style('heading-2', family='paragraph', fontsize='22pt', fontweight='bold', ) _add_style('heading-3', family='paragraph', fontsize='20pt', fontweight='bold', ) _add_style('heading-4', family='paragraph', fontsize='18pt', fontweight='bold', ) _add_style('heading-5', family='paragraph', fontsize='16pt', fontweight='bold', ) _add_style('heading-6', family='paragraph', fontsize='14pt', fontweight='bold', ) _add_style('normal-paragraph', family='paragraph', fontsize='12pt', marginbottom='0.25cm', ) _add_style('code', family='paragraph', fontsize='10pt', fontweight='bold', fontfamily='Courier New', color='#555555', ) _add_style('quote', family='paragraph', fontsize='12pt', fontstyle='italic', ) _add_style('list-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('sublist-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('numbered-list-paragraph', family='paragraph', fontsize='12pt', marginbottom='.1cm', ) _add_style('normal-text', family='text', fontsize='12pt', ) _add_style('italic', family='text', fontstyle='italic', fontsize='12pt', ) _add_style('bold', family='text', fontweight='bold', fontsize='12pt', ) _add_style('url', family='text', fontsize='12pt', fontweight='bold', fontfamily='Courier', ) _add_style('inline-code', family='text', fontsize='10pt', fontweight='bold', fontfamily='Courier New', color='#555555', ) styles['_numbered_list'] = _numbered_style() return styles
java
@Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { int high = highIndexOf(toElement, inclusive); return new BinarySet(comparator, list.subList(0, high+1), false); }
java
public Response serveFile( String uri, Properties header, File homeDir, boolean allowDirectoryListing ) { Response res = null; // Make sure we won't die of an exception later if ( !homeDir.isDirectory()) res = new Response( HTTP_INTERNALERROR, MIME_PLAINTEXT, "INTERNAL ERRROR: serveFile(): given homeDir is not a directory." ); if ( res == null ) { // Remove URL arguments uri = uri.trim().replace( File.separatorChar, '/' ); if ( uri.indexOf( '?' ) >= 0 ) uri = uri.substring(0, uri.indexOf( '?' )); // Prohibit getting out of current directory if ( uri.startsWith( ".." ) || uri.endsWith( ".." ) || uri.indexOf( "../" ) >= 0 ) res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons." ); } File f = new File( homeDir, uri ); if ( res == null && !f.exists()) res = new Response( HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found." ); // List the directory, if necessary if ( res == null && f.isDirectory()) { // Browsers get confused without '/' after the // directory, send a redirect. if ( !uri.endsWith( "/" )) { uri += "/"; res = new Response( HTTP_REDIRECT, MIME_HTML, "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>"); res.addHeader( "Location", uri ); } if ( res == null ) { // First try index.html and index.htm if ( new File( f, "index.html" ).exists()) f = new File( homeDir, uri + "/index.html" ); else if ( new File( f, "index.htm" ).exists()) f = new File( homeDir, uri + "/index.htm" ); // No index file, list the directory if it is readable else if ( allowDirectoryListing && f.canRead() ) { String[] files = f.list(); String msg = "<html><body><h1>Directory " + uri + "</h1><br/>"; if ( uri.length() > 1 ) { String u = uri.substring( 0, uri.length()-1 ); int slash = u.lastIndexOf( '/' ); if ( slash >= 0 && slash < u.length()) msg += "<b><a href=\"" + uri.substring(0, slash+1) + "\">..</a></b><br/>"; } if (files!=null) { for ( int i=0; i<files.length; ++i ) { File curFile = new File( f, files[i] ); boolean dir = curFile.isDirectory(); if ( dir ) { msg += "<b>"; files[i] += "/"; } msg += "<a href=\"" + encodeUri( uri + files[i] ) + "\">" + files[i] + "</a>"; // Show file size if ( curFile.isFile()) { long len = curFile.length(); msg += " &nbsp;<font size=2>("; if ( len < 1024 ) msg += len + " bytes"; else if ( len < 1024 * 1024 ) msg += len/1024 + "." + (len%1024/10%100) + " KB"; else msg += len/(1024*1024) + "." + len%(1024*1024)/10%100 + " MB"; msg += ")</font>"; } msg += "<br/>"; if ( dir ) msg += "</b>"; } } msg += "</body></html>"; res = new Response( HTTP_OK, MIME_HTML, msg ); } else { res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing." ); } } } try { if ( res == null ) { // Get MIME type from file name extension, if possible String mime = null; int dot = f.getCanonicalPath().lastIndexOf( '.' ); if ( dot >= 0 ) mime = (String)theMimeTypes.get( f.getCanonicalPath().substring( dot + 1 ).toLowerCase()); if ( mime == null ) mime = MIME_DEFAULT_BINARY; // Calculate etag String etag = Integer.toHexString((f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode()); // Support (simple) skipping: long startFrom = 0; long endAt = -1; String range = header.getProperty( "range" ); if ( range != null ) { if ( range.startsWith( "bytes=" )) { range = range.substring( "bytes=".length()); int minus = range.indexOf( '-' ); try { if ( minus > 0 ) { startFrom = Long.parseLong( range.substring( 0, minus )); endAt = Long.parseLong( range.substring( minus+1 )); } } catch ( NumberFormatException nfe ) {} } } // Change return code and add Content-Range header when skipping is requested long fileLen = f.length(); if (range != null && startFrom >= 0) { if ( startFrom >= fileLen) { res = new Response( HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "" ); res.addHeader( "Content-Range", "bytes 0-0/" + fileLen); res.addHeader( "ETag", etag); } else { if ( endAt < 0 ) endAt = fileLen-1; long newLen = endAt - startFrom + 1; if ( newLen < 0 ) newLen = 0; final long dataLen = newLen; FileInputStream fis = new FileInputStream( f ) { public int available() throws IOException { return (int)dataLen; } }; fis.skip( startFrom ); res = new Response( HTTP_PARTIALCONTENT, mime, fis ); res.addHeader( "Content-Length", "" + dataLen); res.addHeader( "Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen); res.addHeader( "ETag", etag); } } else { if (etag.equals(header.getProperty("if-none-match"))) res = new Response( HTTP_NOTMODIFIED, mime, ""); else { res = new Response( HTTP_OK, mime, new FileInputStream( f )); res.addHeader( "Content-Length", "" + fileLen); res.addHeader( "ETag", etag); } } } } catch( IOException ioe ) { res = new Response( HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed." ); } res.addHeader( "Accept-Ranges", "bytes"); // Announce that the file server accepts partial content requestes return res; }
java
protected static void main(String[] args, CliTool command) { JCommander jc = new JCommander(command); jc.addConverterFactory(new CustomParameterConverters()); jc.setProgramName(command.getClass().getAnnotation(Parameters.class).commandNames()[0]); ExitStatus exitStatus = ExitStatus.SUCCESS; try { jc.parse(args); if (command.help) { helpDisplayCommandOptions(System.err, jc); } else { exitStatus = command.call(); } } catch (ExitStatusException e) { System.err.println(e.getMessage()); if (e.getCause() != null) { e.getCause().printStackTrace(System.err); } exitStatus = e.exitStatus; } catch (MissingCommandException e) { System.err.println("Invalid argument: " + e); System.err.println(); helpDisplayCommandOptions(System.err, jc); exitStatus = ExitStatus.ERROR_INVALID_ARGUMENTS; } catch (ParameterException e) { System.err.println("Invalid argument: " + e.getMessage()); System.err.println(); if (jc.getParsedCommand() == null) { helpDisplayCommandOptions(System.err, jc); } else { helpDisplayCommandOptions(System.err, jc.getParsedCommand(), jc); } exitStatus = ExitStatus.ERROR_INVALID_ARGUMENTS; } catch (Throwable t) { System.err.println("An unhandled exception occurred. Stack trace below."); t.printStackTrace(System.err); exitStatus = ExitStatus.ERROR_OTHER; } if (command.callSystemExit) { System.exit(exitStatus.code); } }
python
def register(self, context, stream): """ Register a newly constructed context and its associated stream, and add the stream's receive side to the I/O multiplexer. This method remains public while the design has not yet settled. """ _v and LOG.debug('register(%r, %r)', context, stream) self._write_lock.acquire() try: self._stream_by_id[context.context_id] = stream self._context_by_id[context.context_id] = context finally: self._write_lock.release() self.broker.start_receive(stream) listen(stream, 'disconnect', lambda: self._on_stream_disconnect(stream))
java
@Override public ListCoreDefinitionsResult listCoreDefinitions(ListCoreDefinitionsRequest request) { request = beforeClientExecution(request); return executeListCoreDefinitions(request); }
python
async def apply_json(self, data): """Apply a JSON data object for a service """ if not isinstance(data, list): data = [data] result = [] for entry in data: if not isinstance(entry, dict): raise KongError('dictionary required') ensure = entry.pop('ensure', None) name = entry.pop('name', None) routes = entry.pop('routes', []) plugins = entry.pop('plugins', []) host = entry.pop('host', None) if host in LOCAL_HOST: host = local_ip() if not name: raise KongError('Service name is required') if ensure in REMOVE: if await self.has(name): await self.delete(name) continue # backward compatible with config entry config = entry.pop('config', None) if isinstance(config, dict): entry.update(config) if await self.has(name): srv = await self.update(name, host=host, **entry) else: srv = await self.create(name=name, host=host, **entry) srv.data['routes'] = await srv.routes.apply_json(routes) srv.data['plugins'] = await srv.plugins.apply_json(plugins) result.append(srv.data) return result
python
def getDescriptor(self, dir): """ Detects the descriptor file for either an Unreal project or an Unreal plugin in the specified directory """ try: return self.getProjectDescriptor(dir) except: try: return self.getPluginDescriptor(dir) except: raise UnrealManagerException('could not detect an Unreal project or plugin in the directory "{}"'.format(dir))
java
SoyExpression compile(ExprNode node, Label reattachPoint) { return asBasicCompiler(reattachPoint).compile(node); }
python
def findkey(d, *keys): """ Get a value from a dictionary based on a list of keys and/or list indexes. Parameters ---------- d: dict A Python dictionary keys: list A list of key names, or list indexes Returns ------- dict The composite dictionary object at the path specified by the keys Example ------- To return the value of the first class of the first layer in a Mapfile:: s = ''' MAP LAYER NAME "Layer1" TYPE POLYGON CLASS NAME "Class1" COLOR 0 0 255 END END END ''' d = mappyfile.loads(s) pth = ["layers", 0, "classes", 0] cls1 = mappyfile.findkey(d, *pth) assert cls1["name"] == "Class1" """ if keys: keys = list(keys) key = keys.pop(0) return findkey(d[key], *keys) else: return d
python
def hash_value(self, value, salt=''): '''Hashes the specified value combined with the specified salt. The hash is done HASHING_ROUNDS times as specified by the application configuration. An example usage of :class:``hash_value`` would be:: val_hash = hashing.hash_value('mysecretdata', salt='abcd') # save to a db or check against known hash :param value: The value we want hashed :param salt: The salt to use when generating the hash of ``value``. Default is ''. :return: The resulting hash as a string :rtype: str ''' def hashit(value, salt): h = hashlib.new(self.algorithm) tgt = salt+value h.update(tgt) return h.hexdigest() def fix_unicode(value): if VER < 3 and isinstance(value, unicode): value = str(value) elif VER >= 3 and isinstance(value, str): value = str.encode(value) return value salt = fix_unicode(salt) for i in range(self.rounds): value = fix_unicode(value) value = hashit(value, salt) return value
java
public void init(CalendarModel model, ProductTypeInfo productType, Date startTime, Date endTime, String description, String[] rgstrMeals, int iStatus) { m_model = (CachedCalendarModel)model; m_cachedInfo = new CachedInfo(productType, startTime, endTime, description, rgstrMeals, iStatus); }
java
public static <T> T unmarshal(JAXBContext self, String xml, Class<T> declaredType) throws JAXBException { return unmarshal(self.createUnmarshaller(), xml, declaredType); }
java
private ByteBuffer readBuffer(final byte[] content) throws IOException { final int startPos = getCheckBytesFrom(); if (startPos > content.length) { return null; } ByteBuffer buf; switch (getType()) { case MagicMimeEntry.STRING_TYPE: { final int len = getContent().length(); buf = ByteBuffer.allocate(len + 1); buf.put(content, startPos, len); break; } case MagicMimeEntry.SHORT_TYPE: case MagicMimeEntry.LESHORT_TYPE: case MagicMimeEntry.BESHORT_TYPE: { buf = ByteBuffer.allocate(2); buf.put(content, startPos, 2); break; } case MagicMimeEntry.LELONG_TYPE: case MagicMimeEntry.BELONG_TYPE: { buf = ByteBuffer.allocate(4); buf.put(content, startPos, 4); break; } case MagicMimeEntry.BYTE_TYPE: { buf = ByteBuffer.allocate(1); buf.put(buf.array(), startPos, 1); } default: { buf = null; break; } } return buf; }
java
@Override public void bindJavaApp(String name, EJBBinding bindingObject) { String bindingName = buildJavaAppName(name); ejbJavaColonHelper.addAppBinding(moduleMetaData, bindingName, bindingObject); }
java
public Coding addSubType() { //3 Coding t = new Coding(); if (this.subType == null) this.subType = new ArrayList<Coding>(); this.subType.add(t); return t; }
java
@Contract(pure = true) @NotNull public static <T> Promise<T> schedule(@NotNull Promise<T> promise, long timestamp) { MaterializedPromise<T> materializedPromise = promise.materialize(); return Promise.ofCallback(cb -> getCurrentEventloop().schedule(timestamp, () -> materializedPromise.whenComplete(cb))); }
python
def get(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[_T]: """Remove and return an item from the queue. Returns an awaitable which resolves once an item is available, or raises `tornado.util.TimeoutError` after a timeout. ``timeout`` may be a number denoting a time (on the same scale as `tornado.ioloop.IOLoop.time`, normally `time.time`), or a `datetime.timedelta` object for a deadline relative to the current time. .. note:: The ``timeout`` argument of this method differs from that of the standard library's `queue.Queue.get`. That method interprets numeric values as relative timeouts; this one interprets them as absolute deadlines and requires ``timedelta`` objects for relative timeouts (consistent with other timeouts in Tornado). """ future = Future() # type: Future[_T] try: future.set_result(self.get_nowait()) except QueueEmpty: self._getters.append(future) _set_timeout(future, timeout) return future
python
def _open_debug_interface(self, conn_id, callback, connection_string=None): """Enable debug interface for this IOTile device Args: conn_id (int): the unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason) """ self._try_connect(connection_string) callback(conn_id, self.id, True, None)
java
public static String constructUniqueName(String[] RDNs, String[] RDNValues, String parentDN) throws InvalidUniqueNameException { int length; if (RDNs != null) { length = RDNs.length; } else { return null; } if (length != RDNValues.length || length == 0) return null; StringBuffer RDN = new StringBuffer(); for (int i = 0; i < length; i++) { if (RDNValues[i] != null && RDNValues[i].length() != 0) { if (i != 0 && RDN.length() != 0) { RDN.append("+"); } RDN.append(RDNs[i] + "=" + escapeAttributeValue(RDNValues[i])); } } String DN = null; if (parentDN.length() == 0) { DN = RDN.toString(); } else { DN = RDN.toString() + "," + parentDN; } return formatUniqueName(DN); }
java
private static JSONArray _fromArray( Object[] array, JsonConfig jsonConfig ) { if( !addInstance( array ) ){ try{ return jsonConfig.getCycleDetectionStrategy() .handleRepeatedReferenceAsArray( array ); }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } } fireArrayStartEvent( jsonConfig ); JSONArray jsonArray = new JSONArray(); try{ for( int i = 0; i < array.length; i++ ){ Object element = array[i]; jsonArray.addValue( element, jsonConfig ); fireElementAddedEvent( i, jsonArray.get( i ), jsonConfig ); } }catch( JSONException jsone ){ removeInstance( array ); fireErrorEvent( jsone, jsonConfig ); throw jsone; }catch( RuntimeException e ){ removeInstance( array ); JSONException jsone = new JSONException( e ); fireErrorEvent( jsone, jsonConfig ); throw jsone; } removeInstance( array ); fireArrayEndEvent( jsonConfig ); return jsonArray; }
python
def find_one_and_replace(self, filter, replacement, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace """ self._arctic_lib.check_quota() return self._collection.find_one_and_replace(filter, replacement, **kwargs)
java
static public byte[] byteSubstring(byte[] bytes, int start, int end) { byte[] rc = null; if (0 > start || start > bytes.length || start > end) { // invalid start position if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Invalid start position in byteSubstring: " + start); } } else if (0 > end || end > bytes.length) { // invalid end position if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Invalid end position in byteSubstring: " + end); } } else { // now pull the substring int len = end - start; rc = new byte[len]; System.arraycopy(bytes, start, rc, 0, len); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "byteSubstring returning: [" + getEnglishString(rc) + "]"); } return rc; }
java
public static String getPermissionsVerbose(int permissions) { StringBuffer buf = new StringBuffer("Allowed:"); if ((PdfWriter.ALLOW_PRINTING & permissions) == PdfWriter.ALLOW_PRINTING) buf.append(" Printing"); if ((PdfWriter.ALLOW_MODIFY_CONTENTS & permissions) == PdfWriter.ALLOW_MODIFY_CONTENTS) buf.append(" Modify contents"); if ((PdfWriter.ALLOW_COPY & permissions) == PdfWriter.ALLOW_COPY) buf.append(" Copy"); if ((PdfWriter.ALLOW_MODIFY_ANNOTATIONS & permissions) == PdfWriter.ALLOW_MODIFY_ANNOTATIONS) buf.append(" Modify annotations"); if ((PdfWriter.ALLOW_FILL_IN & permissions) == PdfWriter.ALLOW_FILL_IN) buf.append(" Fill in"); if ((PdfWriter.ALLOW_SCREENREADERS & permissions) == PdfWriter.ALLOW_SCREENREADERS) buf.append(" Screen readers"); if ((PdfWriter.ALLOW_ASSEMBLY & permissions) == PdfWriter.ALLOW_ASSEMBLY) buf.append(" Assembly"); if ((PdfWriter.ALLOW_DEGRADED_PRINTING & permissions) == PdfWriter.ALLOW_DEGRADED_PRINTING) buf.append(" Degraded printing"); return buf.toString(); }
java
protected boolean containWildcard(Object value) { if (!(value instanceof String)) { return false; } String casted = (String) value; return casted.contains(LIKE_WILDCARD.toString()); }
java
@Override public Object parse(String value) throws ParseException { if(value == null || value.isEmpty()) { return null; } dateFormat = createDateFormat(locale); dateFormat.setTimeZone(timeZone); return dateFormat.parse(value); }
python
def addValue(self, type_uri, value): """Add a single value for the given attribute type to the message. If there are already values specified for this type, this value will be sent in addition to the values already specified. @param type_uri: The URI for the attribute @param value: The value to add to the response to the relying party for this attribute @type value: unicode @returns: None """ try: values = self.data[type_uri] except KeyError: values = self.data[type_uri] = [] values.append(value)
java
public void marshall(CreateDocumentClassifierRequest createDocumentClassifierRequest, ProtocolMarshaller protocolMarshaller) { if (createDocumentClassifierRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createDocumentClassifierRequest.getDocumentClassifierName(), DOCUMENTCLASSIFIERNAME_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getDataAccessRoleArn(), DATAACCESSROLEARN_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getTags(), TAGS_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getInputDataConfig(), INPUTDATACONFIG_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getOutputDataConfig(), OUTPUTDATACONFIG_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getLanguageCode(), LANGUAGECODE_BINDING); protocolMarshaller.marshall(createDocumentClassifierRequest.getVolumeKmsKeyId(), VOLUMEKMSKEYID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
Element getElement(Node node) { if (node == null) { return null; } // element instance is cached as node user defined data and reused Object value = node.getUserData(BACK_REF); if (value != null) { return (Element) value; } Element el = new ElementImpl(this, node); node.setUserData(BACK_REF, el, null); return el; }
python
def protorpc_to_endpoints_error(self, status, body): """Convert a ProtoRPC error to the format expected by Google Endpoints. If the body does not contain an ProtoRPC message in state APPLICATION_ERROR the status and body will be returned unchanged. Args: status: HTTP status of the response from the backend body: JSON-encoded error in format expected by Endpoints frontend. Returns: Tuple of (http status, body) """ try: rpc_error = self.__PROTOJSON.decode_message(remote.RpcStatus, body) except (ValueError, messages.ValidationError): rpc_error = remote.RpcStatus() if rpc_error.state == remote.RpcStatus.State.APPLICATION_ERROR: # Try to map to HTTP error code. error_class = _ERROR_NAME_MAP.get(rpc_error.error_name) if error_class: status, body = self.__write_error(error_class.http_status, rpc_error.error_message) return status, body
java
public void addSoftClause(int weight, final LNGIntVector lits) { final LNGIntVector rVars = new LNGIntVector(); this.softClauses.push(new MSSoftClause(lits, weight, LIT_UNDEF, rVars)); this.nbSoft++; }
java
public static ServerSocketBar create(InetAddress host, int port, int listenBacklog, boolean isEnableJni) throws IOException { return currentFactory().create(host, port, listenBacklog, isEnableJni); }
python
def get_media_url(self, context): """ Checks to see whether to use the normal or the secure media source, depending on whether the current page view is being sent over SSL. The USE_SSL setting can be used to force HTTPS (True) or HTTP (False). NOTE: Not all backends implement SSL media. In this case, they'll just return an unencrypted URL. """ use_ssl = msettings['USE_SSL'] is_secure = use_ssl if use_ssl is not None else self.is_secure(context) return client.media_url(with_ssl=True) if is_secure else client.media_url()
java
public static <T> T getLast(Iterable<T> iterable) { if (iterable instanceof RichIterable) { return ((RichIterable<T>) iterable).getLast(); } if (iterable instanceof RandomAccess) { return RandomAccessListIterate.getLast((List<T>) iterable); } if (iterable instanceof SortedSet && !((SortedSet<T>) iterable).isEmpty()) { return ((SortedSet<T>) iterable).last(); } if (iterable instanceof LinkedList && !((LinkedList<T>) iterable).isEmpty()) { return ((LinkedList<T>) iterable).getLast(); } if (iterable != null) { return IterableIterate.getLast(iterable); } throw new IllegalArgumentException("Cannot get last from null"); }
python
def _init_polling(self): """ Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll. """ with self.lock: if not self.running: return r = random.Random() delay = r.random() * self.refresh_interval self.channel.io_loop.call_later( delay=delay, callback=self._delayed_polling) self.logger.info( 'Delaying throttling credit polling by %d sec', delay)
python
def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): """Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path with the CSV data for that asset show_progress : bool Whether or not to show a progress bar while writing. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is encountered that is outside the range of a uint32. """ read = partial( read_csv, parse_dates=['day'], index_col='day', dtype=self._csv_dtypes, ) return self.write( ((asset, read(path)) for asset, path in iteritems(asset_map)), assets=viewkeys(asset_map), show_progress=show_progress, invalid_data_behavior=invalid_data_behavior, )
python
def indication(self, pdu): """Direct this PDU to the appropriate server.""" if _debug: TCPServerDirector._debug("indication %r", pdu) # get the destination addr = pdu.pduDestination # get the server server = self.servers.get(addr, None) if not server: raise RuntimeError("not a connected server") # pass the indication to the actor server.indication(pdu)
python
def parse_buffer_to_ppm(data): """ Parse PPM file bytes to Pillow Image """ images = [] index = 0 while index < len(data): code, size, rgb = tuple(data[index:index + 40].split(b'\n')[0:3]) size_x, size_y = tuple(size.split(b' ')) file_size = len(code) + len(size) + len(rgb) + 3 + int(size_x) * int(size_y) * 3 images.append(Image.open(BytesIO(data[index:index + file_size]))) index += file_size return images
python
def _nbinom_ztrunc_p(mu, k_agg): """ Calculates p parameter for truncated negative binomial Function given in Sampford 1955, equation 4 Note that omega = 1 / 1 + p in Sampford """ p_eq = lambda p, mu, k_agg: (k_agg * p) / (1 - (1 + p)**-k_agg) - mu # The upper bound needs to be large. p will increase with increasing mu # and decreasing k_agg p = optim.brentq(p_eq, 1e-10, 1e10, args=(mu, k_agg)) return p
python
def visit_assert(self, node, parent): """visit a Assert node by returning a fresh instance of it""" newnode = nodes.Assert(node.lineno, node.col_offset, parent) if node.msg: msg = self.visit(node.msg, newnode) else: msg = None newnode.postinit(self.visit(node.test, newnode), msg) return newnode
python
def methods(self, methods): """Setter method; for a description see the getter method.""" # We make sure that the dictionary is a NocaseDict object, and that the # property values are CIMMethod objects: # pylint: disable=attribute-defined-outside-init self._methods = NocaseDict() if methods: try: # This is used for iterables: iterator = methods.items() except AttributeError: # This is used for dictionaries: iterator = methods for item in iterator: if isinstance(item, CIMMethod): key = item.name value = item elif isinstance(item, tuple): key, value = item else: raise TypeError( _format("Input object for methods has invalid item in " "iterable: {0!A}", item)) self.methods[key] = _cim_method(key, value)
python
def make_dist_mat(xy1, xy2, longlat=True): """ Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- xy1 : numpy.array The first set of coordinates as [(x, y), (x, y), (x, y)]. xy2 : numpy.array The second set of coordinates as [(x, y), (x, y), (x, y)]. longlat : boolean, optionnal Whether the coordinates are in geographic (longitude/latitude) format or not (default: False) Returns ------- mat_dist : numpy.array The distance matrix between xy1 and xy2 """ if longlat: return hav_dist(xy1[:, None], xy2) else: d0 = np.subtract.outer(xy1[:, 0], xy2[:, 0]) d1 = np.subtract.outer(xy1[:, 1], xy2[:, 1]) return np.hypot(d0, d1)
python
def login(self): """ Return True if we successfully logged into this Koji hub. We support GSSAPI and SSL Client authentication (not the old-style krb-over-xmlrpc krbLogin method). :returns: deferred that when fired returns True """ authtype = self.lookup(self.profile, 'authtype') if authtype is None: cert = self.lookup(self.profile, 'cert') if cert and os.path.isfile(os.path.expanduser(cert)): authtype = 'ssl' # Note: official koji cli is a little more lax here. If authtype is # None and we have a valid kerberos ccache, we still try kerberos # auth. if authtype == 'kerberos': # Note: we don't try the old-style kerberos login here. result = yield self._gssapi_login() elif authtype == 'ssl': result = yield self._ssl_login() else: raise NotImplementedError('unsupported auth: %s' % authtype) self.session_id = result['session-id'] self.session_key = result['session-key'] self.callnum = 0 # increment this on every call for this session. defer.returnValue(True)
java
public static CommerceWishList findByUUID_G(String uuid, long groupId) throws com.liferay.commerce.wish.list.exception.NoSuchWishListException { return getPersistence().findByUUID_G(uuid, groupId); }
java
ScheduledExecutorService createSchedulerExecutor(final String prefix) { ThreadFactory threadFactory = new ThreadFactory() { private int counter = 0; @Override public Thread newThread(Runnable runnable) { return new Thread(runnable, prefix + ++counter); } }; ScheduledExecutorService executor = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(threadFactory); return executor; }
python
def bam2fastq(job, bamfile, univ_options): """ split an input bam to paired fastqs. ARGUMENTS 1. bamfile: Path to a bam file 2. univ_options: Dict of universal arguments used by almost all tools univ_options |- 'dockerhub': <dockerhub to use> +- 'java_Xmx': value for max heap passed to java """ work_dir = os.path.split(bamfile)[0] base_name = os.path.split(os.path.splitext(bamfile)[0])[1] parameters = ['SamToFastq', ''.join(['I=', docker_path(bamfile)]), ''.join(['F=/data/', base_name, '_1.fastq']), ''.join(['F2=/data/', base_name, '_2.fastq']), ''.join(['FU=/data/', base_name, '_UP.fastq'])] docker_call(tool='picard', tool_parameters=parameters, work_dir=work_dir, dockerhub=univ_options['dockerhub'], java_opts=univ_options['java_Xmx']) first_fastq = ''.join([work_dir, '/', base_name, '_1.fastq']) assert os.path.exists(first_fastq) return first_fastq
java
public String confusionMatrix(){ int nClasses = numClasses(); if(confusion == null){ return "Confusion matrix: <no data>"; } //First: work out the maximum count List<Integer> classes = confusion.getClasses(); int maxCount = 1; for (Integer i : classes) { for (Integer j : classes) { int count = confusion().getCount(i, j); maxCount = Math.max(maxCount, count); } } maxCount = Math.max(maxCount, nClasses); //Include this as header might be bigger than actual values int numDigits = (int)Math.ceil(Math.log10(maxCount)); if(numDigits < 1) numDigits = 1; String digitFormat = "%" + (numDigits+1) + "d"; StringBuilder sb = new StringBuilder(); //Build header: for( int i=0; i<nClasses; i++ ){ sb.append(String.format(digitFormat, i)); } sb.append("\n"); int numDividerChars = (numDigits+1) * nClasses + 1; for( int i=0; i<numDividerChars; i++ ){ sb.append("-"); } sb.append("\n"); //Build each row: for( int actual=0; actual<nClasses; actual++){ String actualName = resolveLabelForClass(actual); for( int predicted=0; predicted<nClasses; predicted++){ int count = confusion.getCount(actual, predicted); sb.append(String.format(digitFormat, count)); } sb.append(" | ").append(actual).append(" = ").append(actualName).append("\n"); } sb.append("\nConfusion matrix format: Actual (rowClass) predicted as (columnClass) N times"); return sb.toString(); }
java
public void addOrUpdate(long[] indexes, double value) { long[] physicalIndexes = isView() ? translateToPhysical(indexes) : indexes; for (int i = 0; i < length; i++) { long[] idx = getUnderlyingIndicesOf(i).asLong(); if (Arrays.equals(idx, physicalIndexes)) { // There is already a non-null value at this index // -> update the current value, the sort is maintained if (value == 0) { removeEntry(i); length--; } else { values.put(i, value); length++; } return; } } // If the value is 0 and there is no existing non-null value at the given index if (value == 0) { return; } /* It's a new non-null element. We add the value and the indexes at the end of their respective databuffers. * The buffers are no longer sorted ! * /!\ We need to reallocate the buffers if they are full */ while (!canInsert(values, 1)) { long size = (long) Math.ceil((values.capacity() * THRESHOLD_MEMORY_ALLOCATION)); values.reallocate(size); } values.put(length, value); while (!canInsert(indices, physicalIndexes.length)) { long size = (long) Math.ceil((indices.capacity() * THRESHOLD_MEMORY_ALLOCATION)); indices.reallocate(size); } for (int i = 0; i < physicalIndexes.length; i++) { indices.put(length * rank() + i, physicalIndexes[i]); } length++; isSorted = false; }
python
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, interval=1, reloader=False, **kargs): """ Runs bottle as a web server. """ app = app if app else default_app() quiet = bool(kargs.get('quiet', False)) # Instantiate server, if it is a class instead of an instance if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise RuntimeError("Server must be a subclass of WSGIAdapter") if not quiet and isinstance(server, ServerAdapter): # pragma: no cover if not reloader or os.environ.get('BOTTLE_CHILD') == 'true': print("Bottle server starting up (using %s)..." % repr(server)) print("Listening on http://%s:%d/" % (server.host, server.port)) print("Use Ctrl-C to quit.") print() else: print("Bottle auto reloader starting up...") try: if reloader and interval: reloader_run(server, app, interval) else: server.run(app) except KeyboardInterrupt: if not quiet: # pragma: no cover print("Shutting Down...")
java
public static UUID generateTxnId(int epoch, int msb, long lsb) { long msb64Bit = (long) epoch << 32 | msb & 0xFFFFFFFFL; return new UUID(msb64Bit, lsb); }
python
def luhn_checksum(number, chars=DIGITS): ''' Calculates the Luhn checksum for `number` :param number: string or int :param chars: string >>> luhn_checksum(1234) 4 ''' length = len(chars) number = [chars.index(n) for n in reversed(str(number))] return ( sum(number[::2]) + sum(sum(divmod(i * 2, length)) for i in number[1::2]) ) % length
python
def deprecated(new_name: str): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. """ def decorator(func): @wraps(func) def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) # turn off filter warnings.warn( 'Use {0} instead of {1}, {1} will be removed in the future.' .format(new_name, func.__name__), category=DeprecationWarning, stacklevel=2, ) warnings.simplefilter('default', DeprecationWarning) # reset filter return func(*args, **kwargs) setattr(new_func, '__deprecated', True) return new_func return decorator
python
def create_attr_filter(request, mapped_class): """Create an ``and_`` SQLAlchemy filter (a ClauseList object) based on the request params (``queryable``, ``eq``, ``ne``, ...). Arguments: request the request. mapped_class the SQLAlchemy mapped class. """ mapping = { 'eq': '__eq__', 'ne': '__ne__', 'lt': '__lt__', 'lte': '__le__', 'gt': '__gt__', 'gte': '__ge__', 'like': 'like', 'ilike': 'ilike' } filters = [] if 'queryable' in request.params: queryable = request.params['queryable'].split(',') for k in request.params: if len(request.params[k]) <= 0 or '__' not in k: continue col, op = k.split("__") if col not in queryable or op not in mapping: continue column = getattr(mapped_class, col) f = getattr(column, mapping[op])(request.params[k]) filters.append(f) return and_(*filters) if len(filters) > 0 else None
java
public static final Function<String,Float> toFloat(final int scale, final RoundingMode roundingMode) { return new ToFloat(scale, roundingMode); }
java
public final String getCommaSeparatedArgumentNames(final int less) { final List<SgArgument> args = getArguments(less); return commaSeparated(args); }
python
def _wave(self): """Return a wave.Wave_read instance from the ``wave`` module.""" try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise