language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _getFromTime(self, atDate=None): """ Time that the event starts (in the local time zone). """ return getLocalTime(self.date_from, self.time_from, self.tz)
python
def scan_file(self, this_file, this_filename): """ Submit a file to be scanned by Malwares :param this_file: File to be scanned (200MB file size limit) :param this_filename: Filename for scanned file :return: JSON response that contains scan_id and permalink. """ params ...
python
def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True, cadence=1626./86400,frac=1,sec=False,pars0=None,tol=1e-4,width=3): """ Trapezoidal parameters for simulated orbit. All arguments passed to :func:`eclipse` except the following: :param pars0: (optional) ...
java
private boolean isPossibleValue(PdfName value, PdfName[] accepted) { for (int i = 0; i < accepted.length; i++) { if (accepted[i].equals(value)) { return true; } } return false; }
python
def putcol(self, value, startrow=0, nrow=-1, rowincr=1): """Put an entire column or part of it. (see :func:`table.putcol`)""" return self._table.putcol(self._column, value, startrow, nrow, rowincr)
python
async def on_connect(self, connection): "Re-subscribe to any channels and patterns previously subscribed to" # NOTE: for python3, we can't pass bytestrings as keyword arguments # so we need to decode channel/pattern names back to str strings # before passing them to [p]subscribe. ...
python
def listBlockOrigin(self, origin_site_name="", dataset="", block_name=""): """ API to list blocks first generated in origin_site_name. :param origin_site_name: Origin Site Name (Optional, No wildcards) :type origin_site_name: str :param dataset: dataset ( No wildcards, either d...
python
def _get_branches(self): """Get branches from org/repo.""" if self.offline: local_path = Path(LOCAL_PATH).expanduser() / self.org / self.repo get_refs = f"git -C {shlex.quote(str(local_path))} show-ref --heads" else: get_refs = f"git ls-remote --heads https://...
java
public <T extends ServiceConfiguration<?>> T getExistingServiceConfiguration(Class<T> clazz) { for (ServiceConfiguration<?> serviceConfiguration : serviceConfigurations) { if (clazz.equals(serviceConfiguration.getClass())) { return clazz.cast(serviceConfiguration); } } return null; }
python
def _update(collection_name, upsert, multi, spec, doc, check_keys, opts): """Get an OP_UPDATE message.""" flags = 0 if upsert: flags += 1 if multi: flags += 2 encode = _dict_to_bson # Make local. Uses extensions. encoded_update = encode(doc, check_keys, opts) return b"".join...
java
@SuppressWarnings("all") public void normalize() { // Start on samples int samplesPerFrame = (int) ((float) getSamplesPerSecond() / (float) getFramesPerSecond()); setFrames(getFrames() + (int) (getSamples() * (1.0f / samplesPerFrame))); setSamples(getSamples() % samplesPerFrame); setSecond...
java
@Pure public int getPointIndex(int groupIndex, int position) { final int groupMemberCount = getPointCountInGroup(groupIndex); final int pos; if (position < 0) { pos = 0; } else if (position >= groupMemberCount) { pos = groupMemberCount - 1; } else { pos = position; } // Move the start/end index...
java
static Node getBestLValueOwner(@Nullable Node lValue) { if (lValue == null || lValue.getParent() == null) { return null; } if (mayBeObjectLitKey(lValue) || lValue.isComputedProp()) { return getBestLValue(lValue.getParent()); } else if (isGet(lValue)) { return lValue.getFirstChild(); ...
java
public void setClientInfo(String name, String value) throws SQLClientInfoException { try { checkClosed(); } catch (SQLException ex) { SQLClientInfoException e = new SQLClientInfoException(ex.getMessage(), null); e.initCa...
java
protected String getColName(TableAlias aTableAlias, PathInfo aPathInfo, boolean translate) { FieldDescriptor fld = null; String result; if (translate) { fld = getFieldDescriptor(aTableAlias, aPathInfo); } if (fld != null) { /...
python
def configman_keys(a_mapping): """return a DotDict that is a copy of the provided mapping with keys transformed into a configman compatible form: if the key is not all uppercase then all doubled underscores will be replaced with the '.' character. This has a specific use with the os.en...
java
public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{ clusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding(); obj.set_name(name); clusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nsli...
java
private List<Integer> getPriviledgedRoles(String url, RequestMethod method) { Map<String, Map<RequestMethod, List<Integer>>> roleResMap = roleResMgr.getAllAsMap(); Map<RequestMethod, List<Integer>> methodMap = roleResMap.get(url); if (methodMap == null) { return new ArrayList<Intege...
python
def get_merge_direction(cell1, cell2): """ Determine the side of cell1 that can be merged with cell2. This is based on the location of the two cells in the table as well as the compatability of their height and width. For example these cells can merge:: cell1 cell2 merge "RIGHT" ...
python
def cluster_replicate(self, node_id): """Reconfigure a node as a slave of the specified master node.""" fut = self.execute(b'CLUSTER', b'REPLICATE', node_id) return wait_ok(fut)
python
def plotImagesWithNoise(suite, noise_values, plotPath): """ Plot Sample MNIST images with noise :param suite: The configured experiment suite. Must call `parse_opt` and ` parse_cfg` before calling this functions :param noise: list of noise values to plot """ datadir = suite.cfgparser.default...
python
def approximate_split(x, num_splits, axis=0): """Split approximately equally into num_splits parts. Args: x: a Tensor num_splits: an integer axis: an integer. Returns: a list of num_splits Tensors. """ size = shape_list(x)[axis] size_splits = [tf.div(size + i, num_splits) for i in range(nu...
python
def job_listener(event): '''Listens to completed job''' job_id = event.job.args[0] if event.code == events.EVENT_JOB_MISSED: db.mark_job_as_missed(job_id) elif event.exception: if isinstance(event.exception, util.JobError): error_object = event.exception.as_dict() el...
java
@Override public CreateCloudFormationStackResult createCloudFormationStack(CreateCloudFormationStackRequest request) { request = beforeClientExecution(request); return executeCreateCloudFormationStack(request); }
python
def create(self, ensure_keys_exist=True, mkstream=False): """ Create the consumer group and register it with the group's stream keys. :param ensure_keys_exist: Ensure that the streams exist before creating the consumer group. Streams that do not exist will be created. :param...
python
def _fit_one_class(self, clx, cl): """ Train clas number cl with data clx. Use trainFromImageAndSeeds() function if you want to use 3D image data as an input. clx: data, 2d matrix cl: label, integer label: gmmsame, gaussian_kde, dpgmm, stored """ logge...
python
def validate(idText, alpha, r, cert, caPubkey): """ A server can validate an implicit certificate response using identity string @idText, private value @alpha (used to generate cert request), and the certificate response @r (private key component) and implicit @cert. @raises Exception if the cer...
java
@Override public PropertyMap getResourceAsProperties(String path, InputStream input, PropertyMap substitutions) throws IOException { if (input == null) { return null; } Reader reader = new InputStreamReader(input); // g...
java
public final EObject ruleXClosure() throws RecognitionException { EObject current = null; Token otherlv_1=null; Token otherlv_3=null; Token lv_explicitSyntax_5_0=null; Token otherlv_7=null; EObject lv_declaredFormalParameters_2_0 = null; EObject lv_declaredForma...
python
def approximate_spectral_radius(A, tol=0.01, maxiter=15, restart=5, symmetric=None, initial_guess=None, return_vector=False): """Approximate the spectral radius of a matrix. Parameters ---------- A : {dense or sparse matrix} E.g. c...
java
public static void multAdd(DMatrixSparseCSC A , double b[] , int offsetB , double c[] , int offsetC ) { if( b.length-offsetB < A.numCols) throw new IllegalArgumentException("Length of 'b' isn't long enough"); if( c.length-offs...
java
public FxRateCalculatorBuilder addRateSnapshot(final FxRate rate) { if (rate != null) { this.ratesSnapshot.put(rate.getCurrencyPair(), rate); } return this; }
java
public static Collection<CollisionCategory> imports(Configurer configurer, MapTileCollision map) { Check.notNull(configurer); Check.notNull(map); final Collection<Xml> children = configurer.getRoot().getChildren(NODE_CATEGORY); final Collection<CollisionCategory> categories = ...
java
public static long getMinutesDifference(Date startDate, Date endDate) { long startTime = startDate.getTime(); long endTime = endDate.getTime(); long diffTime = endTime - startTime; long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(diffTime); return diffInMinutes; }
java
void putIntoCanonical( SquareGrid grid ) { boolean rowOdd = grid.rows%2 == 1; boolean colOdd = grid.columns%2 == 1; if( colOdd == rowOdd ) { // if odd and square then 4 solutions. Otherwise just two solution that are on // opposite sides on the grid if( rowOdd && grid.rows == grid.columns ) { int ...
java
public float[] getFloatArray(String attributeName) { float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName); if (array == null) { throw new IllegalArgumentException("Attribute name " + attributeName + " cannot be accessed"); } return array; ...
python
def main(): """ This is the main body of the process that does the work. Summary: - load the raw data - read in rules list - create log events for AIKIF according to rules [map] - create new facts / reports based on rules [report] OUTPUT = AIKIF mapping : Date_of_...
python
def density_matrix_from_state_vector( state: Sequence, indices: Iterable[int] = None ) -> np.ndarray: r"""Returns the density matrix of the wavefunction. Calculate the density matrix for the system on the given qubit indices, with the qubits not in indices that are present in state traced out. ...
python
def b58decode(v: str) -> bytes: '''Decode a Base58 encoded string''' origlen = len(v) v = v.lstrip(alphabet[0]) newlen = len(v) p, acc = 1, 0 for c in v[::-1]: acc += p * alphabet.index(c) p *= 58 result = [] while acc > 0: acc, mod = divmod(acc, 256) r...
java
public void billingAccount_fax_serviceName_settings_PUT(String billingAccount, String serviceName, OvhFaxProperties body) throws IOException { String qPath = "/telephony/{billingAccount}/fax/{serviceName}/settings"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), bod...
python
def refresh_plugin(self): """Refresh widget""" if self._starting_up: self._starting_up = False self.switch_to_rich_text() self.show_intro_message()
python
def get_authorization_admin_session_for_vault(self, vault_id): """Gets the ``OsidSession`` associated with the authorization admin service for the given vault. arg: vault_id (osid.id.Id): the ``Id`` of the vault return: (osid.authorization.AuthorizationAdminSession) - ``an _a...
python
def _prefix_from_ip_int(self, ip_int): """Return prefix length from a bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format. Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid n...
python
def instantiate_from_data(self, object_data): """ Instantiate object from the supplied data, additional args may come from the environment """ if isinstance(object_data, dict) and 'name' in object_data: name = object_data['name'] module = importlib.import_module(name) ...
python
def is_user_id_available(self, user_id, note=None, loglevel=logging.DEBUG): """Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype...
python
def _assemble_translation(sequence: np.ndarray, length: np.ndarray, attention_lists: np.ndarray, seq_score: np.ndarray, beam_history: Optional[BeamHistory], estimated_ref...
python
def Output(self): """Output all sections of the page.""" self.Open() self.Header() self.Body() self.Footer()
python
def set_translation_end(self, feature_id, end, organism=None, sequence=None): """ Set a feature's end :type feature_id: str :param feature_id: Feature UUID :type end: int :param end: Feature end :type organism: str :param organism: Organism Common Name ...
java
private void checkOrMarkPrivateAccess(Expression source, FieldNode fn, boolean lhsOfAssignment) { if (fn == null) return; ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode(); ClassNode declaringClass = fn.getDeclaringClass(); if (fn.isPrivate() && (...
java
public static Bitmap scaleFill(Bitmap src, int w, int h) { Bitmap res = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); scaleFill(src, res); return res; }
python
def blockSignals(self, state): """ Propagates the block signals for this editor down to the text editor. :param state | <bool> """ super(XRichTextEdit, self).blockSignals(state) self.uiEditTXT.blockSignals(state)
python
def phone_number(random=random, *args, **kwargs): """ Return a phone number >>> mock_random.seed(0) >>> phone_number(random=mock_random) '555-0000' >>> phone_number(random=mock_random) '1-604-555-0000' >>> phone_number(random=mock_random) '864-70-555-0000' """ return random...
python
def get_reference_repository(self, reference: Optional[Path], repo: str) -> Optional[Path]: """ Returns a repository to use in clone command, if there is one to be referenced. Either provided by the user of generated from already cloned branches (master is preferred). :param reference: ...
java
@SuppressWarnings("unchecked") private void processManuallyTracedMethods(ClassTraceInfo info) { for (MethodNode mn : (List<MethodNode>) info.classNode.methods) { // Don't re-process methods that have already had trace injected if (isMethodAlreadyInjectedAnnotationPresent(mn)) { ...
java
@Override public boolean isIdle() { if (ioSession != null) { if (log.isDebugEnabled()) { log.debug("Connection idle - read: {} write: {}", ioSession.isReaderIdle(), ioSession.isWriterIdle()); } return super.isIdle() && ioSession.isBothIdle(); ...
python
def auth(self): """ Contains the auth token for use with connecting to the dataservice. :return: """ return self.values.get(Config.AUTH, os.environ.get(AUTH_ENV_KEY_NAME, None))
python
def delete_columns(mat, columns_to_delete): ''' >>> a = csr_matrix(np.array([[0, 1, 3, 0, 1, 0], [0, 0, 1, 0, 1, 1]]) >>> delete_columns(a, [1,2]).todense() matrix([[0, 0, 1, 0], [0, 0, 1, 1]]) Parameters ---------- mat : csr_matrix columns_to_delete : list[int] Returns...
python
def _ctorCmprRange(self, vals): ''' Override default *range= handler to account for relative computation. ''' if not isinstance(vals, (list, tuple)): raise s_exc.BadCmprValu(valu=vals, cmpr='*range=') if len(vals) != 2: raise s_exc.BadCmprValu(valu=vals,...
python
def init_realms(self, realms): """ :type realms: tuple """ # this eliminates the need for an authorizing_realms attribute: self.realms = tuple(realm for realm in realms if isinstance(realm, realm_abcs.AuthorizingRealm)) self.register_cache_clea...
python
def __exists(self, p): """ Check if file of given path exists. Parameters ---------- p : str or tuple Path or tuple identifier. Returns ------- exists : bool ``True``, if file exists. Otherwise ``False``. """ try...
python
def merge_translations(localization_bundle_path): """ Merges the new translation with the old one. The translated files are saved as '.translated' file, and are merged with old translated file. Args: localization_bundle_path (str): The path to the localization bundle. """ logging.info("Me...
java
public FbBotMillResponse build(MessageEnvelope envelope) { User recipient = getRecipient(envelope); Message message = new TextMessage(messageText); message.setQuickReplies(quickReplies); return new FbBotMillMessageResponse(recipient, message); }
python
def set_device_state(self, device, state, id_override=None, type_override=None): """ Set device state via online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. id_override (String, option...
java
public static <A extends Annotation> List<A> getMethodParameterAnnotations(Method method, int index, Class<A> annotationClass, boolean inherits) { List<A> annotations = getMethodParameterAnnotations(method, index, annotationClass); if (inherits && annotationClass.getAnnotation(Inherited.cla...
python
def render_template(env, html_path, template_filename, context): """ Render a template file into the given output location. """ template = env.get_template(template_filename) rendered_html = template.render(**context) # pylint: disable=no-member html_path.write_text(rendered_html, encoding='utf...
java
public static void writeShort(OutputStream out, short v) throws IOException { out.write((byte) (0xff & (v >> 8))); out.write((byte) (0xff & v)); }
java
public static String omitXmlDeclaration(String xml) { if (xml.startsWith("<?xml") && xml.contains("?>")) { return xml.substring(xml.indexOf("?>") + 2).trim(); } return xml; }
java
@Override public DescribeCompilationJobResult describeCompilationJob(DescribeCompilationJobRequest request) { request = beforeClientExecution(request); return executeDescribeCompilationJob(request); }
python
def _premium(fn): """Premium decorator for APIs that require premium access level.""" @_functools.wraps(fn) def _fn(self, *args, **kwargs): if self._lite: raise RuntimeError('Premium API not available in lite access.') return fn(self, *args, **kwargs) ...
python
def BVC(self, params): """ BVC label Branch to the instruction at label if the V flag is not set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BVC label def BVC_func(): if not se...
python
def unwire(awsclient, events, lambda_name, alias_name=ALIAS_NAME): """Unwire a list of event from an AWS Lambda function. 'events' is a list of dictionaries, where the dict must contains the 'schedule' of the event as string, and an optional 'name' and 'description'. :param awsclient: :param event...
java
@Override public synchronized void stop(StopContext context) { try { sipService.stop(); // FIXME: kakonyii // server.stop(); } catch (Exception e) { } // FIXME: kakonyii // engine = null; // service = null; // server = null;...
java
private void replaceUris(uk.ac.open.kmi.msm4j.Resource resource, URI newUriBase) throws URISyntaxException { // Exit early if (resource == null || newUriBase == null || !newUriBase.isAbsolute()) return; resource.setUri(URIUtil.replaceNamespace(resource....
java
private State<O> updateSignature(State<O> state, int idx, State<O> succ) { StateSignature<O> sig = state.getSignature(); if (sig.successors.array[idx] == succ) { return state; } register.remove(sig); if (sig.successors.array[idx] != null) { sig.successors...
java
protected boolean i_recordScannedClassName(String i_className) { boolean didPlaceClass = annotationTargets.i_placeClass(i_getClassSourceName(), i_className); if (!didPlaceClass) { return false; } boolean didAddClass = annotationTargets.i_addScannedClassName(i_className, getS...
python
def get_config_value(name, path_to_file='config.txt'): """ gets the value for "name" from "path_to_file" config file Args: name: name of varibale in config file path_to_file: path to config file Returns: path to dll if name exists in the file; otherwise, returns None """ # if ...
python
def _len_lcs(x, y): """Returns the length of the Longest Common Subsequence between two seqs. Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence Args: x: sequence of words y: sequence of words Returns integer: Length of LCS between x and y """ table = _lcs(x, y) n, m =...
python
def _ignore_comments(lines_enum): """ Strips comments and filter empty lines. """ for line_number, line in lines_enum: line = COMMENT_RE.sub('', line) line = line.strip() if line: yield line_number, line
python
def mask_loss(input_tensor, binary_tensor): """ Mask a loss by using a tensor filled with 0 or 1. :param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy :param binary_tensor: A float tensor of shape [batch_size, ...] representing the mask. :return: A floa...
java
public static final long getLong(InputStream is) throws IOException { byte[] data = new byte[8]; is.read(data); return getLong(data, 0); }
python
def games(self, platform): """ It returns a list of games given the platform *alias* (usually is the game name separated by "-" instead of white spaces). """ platform = platform.lower() data_list = self.db.get_data(self.games_path, platform=platform) data_list = data_list...
java
private static int compareEntry(ArrayList<Entry> entries, int entry, int target) { return entries.get(entry).getGeneratedColumn() - target; }
python
def login_in_terminal(self, need_captcha=False, use_getpass=True): """不使用cookies,在终端中根据提示登陆知乎 :param bool need_captcha: 是否要求输入验证码,如果登录失败请设为 True :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: 如果成功返回cookies字符串 :r...
python
def docker2singularity(self, runscript="/bin/bash", force=False): '''docker2singularity will return a Singularity build recipe based on a the loaded recipe object. It doesn't take any arguments as the recipe object contains the sections, and the calling function determines saving / output logi...
java
@Post("/custom") @ProducesText @RequestConverter(CustomRequestConverter.class) @ResponseConverter(CustomResponseConverter.class) public Response custom(@RequestObject Request request) { return new Response(Response.SUCCESS, request.name()); }
python
def rewrap_long(s, width=COLS): """ Rewrap longer texts with paragraph breaks (two consecutive LF) """ paras = s.split('\n\n') return '\n\n'.join(rewrap(p) for p in paras)
java
static String getDataSourceClassName(String vendorPropertiesPID) { String[] classNames = classNamesByPID.get(vendorPropertiesPID); return classNames == null ? null : classNames[0]; }
java
public <R> Stream<R> map(final Func1<? super T, ? extends R> func) { return new Stream<R>() { @Override public Iterator<R> iterator() { return new ReadOnlyIterator<R>() { Iterator<T> iterator = Stream.this.iterator(); @Override ...
java
protected PathMapped<Service<I, O>> findService(PathMappingContext mappingCtx) { assert router != null; return router.find(mappingCtx); }
java
public static <T> Const<T> of(final String name, final T value) { return new Const<>(requireNonNull(name), value); }
java
static void saveLastExecVersion(@Nonnull String version) { File lastExecVersionFile = getLastExecVersionFile(); try { FileUtils.write(lastExecVersionFile, version); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to save " + lastExecVersionFile.getAbsolutePath(), e);...
java
static byte[] readFully(DataInput stream, int len) throws IOException { if (len == 0) { return null; } byte[] data = new byte[len]; stream.readFully(data); return data; }
python
def full_travel_count(self): """ Returns the number of tacho counts in the full travel of the motor. When combined with the `count_per_m` atribute, you can use this value to calculate the maximum travel distance of the motor. (linear motors only) """ (self._full_travel_co...
java
public void configure() throws Exception { final Namespaces ns = new Namespaces("rdf", RDF.uri); ns.add("premis", "http://www.loc.gov/premis/rdf/v1#"); /** * A generic error handler (specific to this RouteBuilder) */ onException(Exception.class) .maximumRe...
java
public static sslocspresponder[] get(nitro_service service) throws Exception{ sslocspresponder obj = new sslocspresponder(); sslocspresponder[] response = (sslocspresponder[])obj.get_resources(service); return response; }
python
def divide(self, factorset, inplace=True): r""" Returns a new factor set instance after division by the factor set Division of two factor sets :math:`\frac{\vec\phi_1}{\vec\phi_2}` basically translates to union of all the factors present in :math:`\vec\phi_2` and :math:`\frac{1}{\phi_i}...
java
public static QueuedMessage createSIBQueuedMessage(SIMPQueuedMessageControllable qmc) { String id = null; int jsApproximateLength = 0; String name = null; String state = null; String transactionId = null; String type = null; String busSystemMessageId = null; ...
java
public final <T> void parseArray( Collection<? super T> destinationCollection, Class<T> destinationItemClass) throws IOException { parseArray(destinationCollection, destinationItemClass, null); }
java
@Export public JsHandlerRegistration addDispatchStoppedHandler(final DispatchStoppedHandler handler) { HandlerRegistration registration = GwtCommandDispatcher.getInstance().addDispatchStoppedHandler( new org.geomajas.gwt.client.command.event.DispatchStoppedHandler() { public void onDispatchStopped(Dispatch...
java
static UrlEncodedFormEntity buildPostBody(Event event, String analyticsId, Random random) { checkNotNull(event); checkNotNull(analyticsId); checkNotNull(random); String virtualPageName = buildVirtualPageName(event.type(), event.objectType(), event.name()); String virtualPageTitle = buildVir...