file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
test_hoursbalance_model.py
import datetime import pytz from django.utils import timezone from django.contrib.auth.models import User from django.test import TestCase from gerencex.core.models import HoursBalance, Timing, Office from gerencex.core.time_calculations import DateData class HoursBalanceModelTest(TestCase): @classmethod de...
date_time=timezone.make_aware(datetime.datetime(2016, 10, 3, 12, 0, 0, 0)), checkin=True ) # ...and a checkout t2 = Timing.objects.create( user=self.user, date_time=timezone.make_aware(datetime.datetime(2016, 10, 3, 13, 0, 0, 0)), ...
def test_credit_triggers(self): # Let's record a check in... t1 = Timing.objects.create( user=self.user,
random_line_split
timer.d.ts
import { Observable } from '../Observable'; import { SchedulerLike } from '../types'; /** * Creates an Observable that starts emitting after an `initialDelay` and
* <span class="informal">Its like {@link interval}, but you can specify when * should the emissions start.</span> * * <img src="./img/timer.png" width="100%"> * * `timer` returns an Observable that emits an infinite sequence of ascending * integers, with a constant interval of time, `period` of your choosing * ...
* emits ever increasing numbers after each `period` of time thereafter. *
random_line_split
buttons.js
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2015 Photon Storm Ltd. * @license {@link http://choosealicense.com/licenses/no-license/|No License} * * @description This example requires the Phaser Virtual Joystick Plugin to run. * For more details please see http://phaser....
this.fx = game.add.audio('sfx'); this.fx.allowMultiple = true; this.fx.addMarker('charm', 0, 2.7); this.fx.addMarker('curse', 4, 2.9); this.fx.addMarker('fireball', 8, 5.2); this.fx.addMarker('spell', 14, 4.7); this.fx.addMarker('soundscape', 20, 18.8); ...
random_line_split
_jax_backend.py
jnp.ndarray) and not isinstance(x, np.ndarray): # NumPy arrays inherit from Jax arrays return True # if scipy.sparse.issparse(x): # TODO # return True if isinstance(x, jnp.bool_): return True # --- Above considered native --- if only_native: ...
def functional_gradient(self, f, wrt: tuple or list, get_output: bool): if get_output: @wraps(f) def aux_f(*args): output = f(*args) if isinstance(output, (tuple, list)) and len(output) == 1: output = output[0] res...
for v in values: self.block_until_ready(v)
conditional_block
_jax_backend.py
(self) -> bool: return True def list_devices(self, device_type: str or None = None) -> List[ComputeDevice]: devices = [] for jax_dev in jax.devices(): jax_dev_type = jax_dev.platform.upper() if device_type is None or device_type == jax_dev_type: descr...
prefers_channels_last
identifier_name
_jax_backend.py
jnp.ndarray) and not isinstance(x, np.ndarray): # NumPy arrays inherit from Jax arrays return True # if scipy.sparse.issparse(x): # TODO # return True if isinstance(x, jnp.bool_): return True # --- Above considered native --- if only_native: ...
def to_dlpack(self, tensor): from jax import dlpack return dlpack.to_dlpack(tensor) def from_dlpack(self, capsule): from jax import dlpack return dlpack.from_dlpack(capsule) def copy(self, tensor, only_mutable=False): return jnp.array(tensor, copy=True) sqrt ...
return np.array(x)
identifier_body
_jax_backend.py
jnp.ndarray) and not isinstance(x, np.ndarray): # NumPy arrays inherit from Jax arrays return True # if scipy.sparse.issparse(x): # TODO # return True if isinstance(x, jnp.bool_): return True # --- Above considered native --- if only_native: ...
def functional_gradient(self, f, wrt: tuple or list, get_output: bool): if get_output: @wraps(f) def aux_f(*args): output = f(*args) if isinstance(output, (tuple, list)) and len(output) == 1: output = output[0] resu...
if isinstance(values, DeviceArray): values.block_until_ready() if isinstance(values, (tuple, list)): for v in values: self.block_until_ready(v)
random_line_split
authorise.js
/** * Copyright 2013-present NightWorld. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ag...
// Header: http://tools.ietf.org/html/rfc6750#section-2.1 if (headerToken) { var matches = headerToken.match(/Bearer\s(\S+)/); if (!matches) { return done(error('invalid_request', 'Malformed auth header')); } headerToken = matches[1]; } // POST: http://tools.ietf.org/html/rfc6750#sect...
{ return done(error('invalid_request', 'The access token was not found')); }
conditional_block
authorise.js
/** * Copyright 2013-present NightWorld. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ag...
done(); }); }); } function checkImplicitClient (done) { var self = this; this.model.getClient(this.clientId, null, function (err, client) { if (err) return done(error('server_error', false, err)); if (!client) { return done(error('invalid_client', 'Invalid client credentials')); } e...
{ var self = this; this.model.getClient(this.client.clientId, this.client.clientSecret, function (err, client) { if (err) return done(error('server_error', false, err)); if (!client) { return done(error('invalid_client', 'Client credentials are invalid')); } self.model.getUserFromClien...
identifier_body
authorise.js
/** * Copyright 2013-present NightWorld. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ag...
(done) { var self = this; this.model.getAccessToken(this.bearerToken, function (err, token) { if (err) return done(error('server_error', false, err)); if (!token) { return done(error('invalid_token', 'The access token provided is invalid.')); } if (token.expires !== null && (!...
checkToken
identifier_name
authorise.js
/** * Copyright 2013-present NightWorld. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or ag...
* limitations under the License. */ var error = require('./error'), runner = require('./runner'), Client = require('./client'); module.exports = Authorise; /** * This is the function order used by the runner * * @type {Array} */ var fns = [ checkAuthoriseType, checkScope ]; /** * Authorise * * @par...
random_line_split
utils.py
from django.conf import settings from mock import Mock from cabot.cabotapp import defs from datetime import datetime def build_absolute_url(relative_url): """Prepend https?://host to a url, useful for links going into emails""" return '{}://{}{}'.format(settings.WWW_SCHEME, settings.WWW_HTTP_HOST, relative_ur...
(dt): ''' Convert datetime to string. None is converted to empty string. This is used primarily for formatting datetimes in API responses, whereas format_timestamp is used for a more human-readable format to be displayed on the web. ''' return '' if dt is None else datetime.strftime(dt, '%Y-%m-%...
format_datetime
identifier_name
utils.py
from django.conf import settings from mock import Mock from cabot.cabotapp import defs from datetime import datetime def build_absolute_url(relative_url):
def create_failing_service_mock(): """ Create a Mock object mimicking a critical service, with a single (also mocked) failing check. Note that not all attributes are mocked (notably hipchat_instance, mattermost_instance). Primary keys/IDs are mocked to be 0. Functions that return querysets in realit...
"""Prepend https?://host to a url, useful for links going into emails""" return '{}://{}{}'.format(settings.WWW_SCHEME, settings.WWW_HTTP_HOST, relative_url)
identifier_body
utils.py
from django.conf import settings from mock import Mock from cabot.cabotapp import defs from datetime import datetime def build_absolute_url(relative_url): """Prepend https?://host to a url, useful for links going into emails""" return '{}://{}{}'.format(settings.WWW_SCHEME, settings.WWW_HTTP_HOST, relative_ur...
''' Convert datetime to string. None is converted to empty string. This is used primarily for formatting datetimes in API responses, whereas format_timestamp is used for a more human-readable format to be displayed on the web. ''' return '' if dt is None else datetime.strftime(dt, '%Y-%m-%d %H:%...
return service_mock def format_datetime(dt):
random_line_split
setup.py
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.txt')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.txt')) as f:
requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_debugtoolbar', 'pyramid_tm', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'waitress', 'pyramid_layout' ] setup(name='MyShop', version='0.0', description='MyShop', long_description=README + '\n\n' + CHANG...
CHANGES = f.read()
random_line_split
problem.rs
struct Container(i32, i32); // A trait which checks if 2 items are stored inside of container. // Also retrieves first or last value. trait Contains<A, B> { fn contains(&self, &A, &B) -> bool; // Explicitly requires `A` and `B`. fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`. fn last(&sel...
(&self) -> i32 { self.1 } } // `C` contains `A` and `B`. In light of that, having to express `A` and // `B` again is a nuisance. fn difference<A, B, C>(container: &C) -> i32 where C: Contains<A, B> { container.last() - container.first() } fn main() { let number_1 = 3; let number_2 = 10; let conta...
last
identifier_name
problem.rs
struct Container(i32, i32); // A trait which checks if 2 items are stored inside of container. // Also retrieves first or last value. trait Contains<A, B> { fn contains(&self, &A, &B) -> bool; // Explicitly requires `A` and `B`. fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`. fn last(&sel...
fn main() { let number_1 = 3; let number_2 = 10; let container = Container(number_1, number_2); println!("Does container contain {} and {}: {}", &number_1, &number_2, container.contains(&number_1, &number_2)); println!("First number: {}", container.first()); println!("Last nu...
{ container.last() - container.first() }
identifier_body
problem.rs
struct Container(i32, i32); // A trait which checks if 2 items are stored inside of container. // Also retrieves first or last value. trait Contains<A, B> {
} impl Contains<i32, i32> for Container { // True if the numbers stored are equal. fn contains(&self, number_1: &i32, number_2: &i32) -> bool { (&self.0 == number_1) && (&self.1 == number_2) } // Grab the first number. fn first(&self) -> i32 { self.0 } // Grab the last number. fn ...
fn contains(&self, &A, &B) -> bool; // Explicitly requires `A` and `B`. fn first(&self) -> i32; // Doesn't explicitly require `A` or `B`. fn last(&self) -> i32; // Doesn't explicitly require `A` or `B`.
random_line_split
processes.py
"""This module holds the ``Process``es for NER.""" from copy import deepcopy from dataclasses import dataclass from typing import Any, List from boltons.cacheutils import cachedproperty from cltk.core.data_types import Doc, Process from cltk.ner.ner import tag_ner @dataclass class NERProcess(Process): """To be...
@dataclass class OldEnglishNERProcess(NERProcess): """The default OE NER algorithm. .. todo:: Update doctest w/ production model >>> from cltk.core.data_types import Doc, Word >>> from cltk.languages.example_texts import get_example_text >>> from boltons.strutils import split_punct_ws ...
""" language: str = "grc" description: str = "Default NER for Greek."
random_line_split
processes.py
"""This module holds the ``Process``es for NER.""" from copy import deepcopy from dataclasses import dataclass from typing import Any, List from boltons.cacheutils import cachedproperty from cltk.core.data_types import Doc, Process from cltk.ner.ner import tag_ner @dataclass class NERProcess(Process): """To be...
return output_doc @dataclass class GreekNERProcess(NERProcess): """The default Greek NER algorithm. .. todo:: Update doctest w/ production model >>> from cltk.core.data_types import Doc, Word >>> from cltk.languages.example_texts import get_example_text >>> from boltons.strutils...
word_obj.named_entity = entity_values[index] output_doc.words[index] = word_obj
conditional_block
processes.py
"""This module holds the ``Process``es for NER.""" from copy import deepcopy from dataclasses import dataclass from typing import Any, List from boltons.cacheutils import cachedproperty from cltk.core.data_types import Doc, Process from cltk.ner.ner import tag_ner @dataclass class NERProcess(Process): """To be...
(self): return tag_ner def run(self, input_doc: Doc) -> Doc: output_doc = deepcopy(input_doc) ner_obj = self.algorithm entity_values = ner_obj( iso_code=self.language, input_tokens=input_doc.tokens ) # type: List[Any] for index, word_obj in enumerate(ou...
algorithm
identifier_name
processes.py
"""This module holds the ``Process``es for NER.""" from copy import deepcopy from dataclasses import dataclass from typing import Any, List from boltons.cacheutils import cachedproperty from cltk.core.data_types import Doc, Process from cltk.ner.ner import tag_ner @dataclass class NERProcess(Process): """To be...
>>> from boltons.strutils import split_punct_ws >>> tokens = [Word(string=token) for token in split_punct_ws(get_example_text("lat"))] >>> a_process = LatinNERProcess() >>> output_doc = a_process.run(Doc(raw=get_example_text("lat"), words=tokens)) >>> [word.named_entity for word in output_doc.words][:2...
>>> from boltons.strutils import split_punct_ws >>> text = get_example_text(iso_code="ang") >>> tokens = [Word(string=token) for token in split_punct_ws(text)] >>> a_process = OldEnglishNERProcess() >>> output_doc = a_process.run(Doc(raw=text, words=tokens)) >>> output_doc.words[2].string, output_...
identifier_body
schema.rs
table! { __diesel_schema_migrations (version) { version -> VarChar, run_on -> Timestamp, } } pub struct NewMigration<'a>(pub &'a str); use backend::Backend; use expression::AsExpression; use expression::helper_types::AsExpr; use persistable::{Insertable, ColumnInsertValue, InsertValues}; impl...
} }
fn values(self) -> Self::Values { (ColumnInsertValue::Expression( __diesel_schema_migrations::version, AsExpression::<::types::VarChar>::as_expression(self.0), ),)
random_line_split
schema.rs
table! { __diesel_schema_migrations (version) { version -> VarChar, run_on -> Timestamp, } } pub struct
<'a>(pub &'a str); use backend::Backend; use expression::AsExpression; use expression::helper_types::AsExpr; use persistable::{Insertable, ColumnInsertValue, InsertValues}; impl<'update: 'a, 'a, DB> Insertable<__diesel_schema_migrations::table, DB> for &'update NewMigration<'a> where DB: Backend, ...
NewMigration
identifier_name
autobind.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { assert_eq!(g(f), 1); let f1: |Vec<String>| -> String = f; assert_eq!(f1(vec!["x".to_string(), "y".to_string(), "z".to_string()]), "x".to_string()); }
{ return act(vec!(1, 2, 3)); }
identifier_body
autobind.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn f<T>(x: Vec<T>)...
//
random_line_split
autobind.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(x: Vec<T>) -> T { return x.into_iter().next().unwrap(); } fn g(act: |Vec<int> | -> int) -> int { return act(vec!(1, 2, 3)); } pub fn main() { assert_eq!(g(f), 1); let f1: |Vec<String>| -> String = f; assert_eq!(f1(vec!["x".to_string(), "y".to_string(), "z".to_string()]), "x".to_string()...
f
identifier_name
global.js
$(document).ready(() => { const href = window.location.href; const last = href.substr(href.lastIndexOf('/') + 1); if (last == '' || last == 'index') { loadImageSlider(); } else if (last == 'signup' || last == 'admin-signup') { // Validation and state population $(".error").hi...
window.location.href = "/"; } else { console.log("There was an error."); } }, error: (err) => { console.log(err); } }); }); });
data: {}, success: (data) => { if (data.status){ // Database is gone, reload
random_line_split
suggestions.rs
#[cfg(feature = "suggestions")] use strsim; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield /// `Some("foo")`, whereas "blark" would yield `None`. ...
<'a, T, I>(v: &str, possible_values: I) -> Option<&'a str> where T: AsRef<str> + 'a, I: IntoIterator<Item = &'a T> { let mut candidate: Option<(f64, &str)> = None; for pv in possible_values.into_iter() { let confidence = strsim:...
did_you_mean
identifier_name
suggestions.rs
#[cfg(feature = "suggestions")] use strsim; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield /// `Some("foo")`, whereas "blark" would yield `None`. ...
/// A helper to determine message formatting pub enum DidYouMeanMessageStyle { /// Suggested value is a long flag LongFlag, /// Suggested value is one of various possible values EnumValue, } #[cfg(test)] mod test { use super::*; #[test] fn did_you_mean_possible_values() { let p_val...
I: IntoIterator<Item = &'a T> { None }
random_line_split
suggestions.rs
#[cfg(feature = "suggestions")] use strsim; /// Produces a string from a given list of possible values which is similar to /// the passed in value `v` with a certain confidence. /// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield /// `Some("foo")`, whereas "blark" would yield `None`. ...
#[cfg(not(feature = "suggestions"))] pub fn did_you_mean<'a, T, I>(_: &str, _: I) -> Option<&'a str> where T: AsRef<str> + 'a, I: IntoIterator<Item = &'a T> { None } /// A helper to determine message formatting pub enum DidYouMeanMessageS...
{ let mut candidate: Option<(f64, &str)> = None; for pv in possible_values.into_iter() { let confidence = strsim::jaro_winkler(v, pv.as_ref()); if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { candidate = Some((confidence, pv....
identifier_body
outputLinkComputer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(ctx: IWorkerContext, createData: ICreateData) { this.ctx = ctx; this.patterns = new Map<URI, RegExp[]>(); this.computePatterns(createData); } private computePatterns(createData: ICreateData): void { // Produce patterns for each workspace root we are configured with // This means that we will be able to ...
constructor
identifier_name
outputLinkComputer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
private computePatterns(createData: ICreateData): void { // Produce patterns for each workspace root we are configured with // This means that we will be able to detect links for paths that // contain any of the workspace roots as segments. const workspaceFolders = createData.workspaceFolders.map(r => URI.p...
{ this.ctx = ctx; this.patterns = new Map<URI, RegExp[]>(); this.computePatterns(createData); }
identifier_body
outputLinkComputer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
// Example: /workspaces/mankala/Features Special.ts (45,18): error patterns.push(new RegExp(strings.escapeRegExpCharacters(workspaceFolderVariant) + `(${pathPattern})(\\s?\\((\\d+)(,(\\d+))?)\\)`, 'gi')); // Example: at /workspaces/mankala/Game.ts // Example: at /workspaces/mankala/Game.ts:336 // Exampl...
// Example: /workspaces/mankala/Features.ts (45,18): error
random_line_split
outputLinkComputer.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
links.push({ range: linkRange, url: resourceString }); } }); return links; } } export function create(ctx: IWorkerContext, createData: ICreateData): OutputLinkComputer { return new OutputLinkComputer(ctx, createData); }
{ return; // Do not detect duplicate links }
conditional_block
workqueue.rs
&mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData: 'static, WorkData: 'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData)...
/// Retrieves the index of the worker. #[inline] pub fn worker_index(&self) -> u8 { self.worker_index } } /// A work queue on which units of work can be submitted. pub struct WorkQueue<QueueData: 'static, WorkData: 'static> { /// Information about each of the workers. workers: Vec<Wor...
{ self.queue_data }
identifier_body
workqueue.rs
, &mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData: 'static, WorkData: 'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData...
break } } match self.other_deques[victim as usize].steal() { Empty | Abort => { // Continue. } ...
loop { victim = self.rng.next_u32() & deque_index_mask; if (victim as usize) < self.other_deques.len() {
random_line_split
workqueue.rs
&mut WorkerProxy<QueueData, WorkData>), /// Arbitrary data. pub data: WorkData, } /// Messages from the supervisor to the worker. enum WorkerMsg<QueueData: 'static, WorkData: 'static> { /// Tells the worker to start work. Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData)...
(mut v: u32) -> u32 { v -= 1; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v += 1; v } impl<QueueData: Sync, WorkData: Send> WorkerThread<QueueData, WorkData> { /// The main logic. This function starts up the worker and listens for /// messages. fn start...
next_power_of_two
identifier_name
data-resource-data.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
public onAttributeType(row: DataRow) { if (row.attribute) { this.attributeTypeClick.emit(row.attribute); } } public onFocus(row: number, column: number) { this.dataRowFocusService.focus(row, this.editableKeys ? column : 1); } public onResetFocusAndEdit(row: number, column: number) { ...
{ if (row.attribute) { this.attributeFunctionCLick.emit(row.attribute); } }
identifier_body
data-resource-data.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
return d; }, {}); const currentAttributeNames = (this.resource?.attributes || []).map(attr => attr.name); const newData = rows .filter(row => row.key && (!row.attribute || !row.attribute.id) && !currentAttributeNames.includes(row.key)) .reduce( (d, row) => ({ ...d, ...
{ d[row.attribute.id] = row.value; }
conditional_block
data-resource-data.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
this.dataRowService.updateRow(index, value); } public onNewValue(value: any, row: DataRow, index: number) { this.dataRowService.updateRow(index, null, value); } public ngOnDestroy() { this.subscriptions.unsubscribe(); this.dataRowService.destroy(); } public onRemoveRow(index: number) { ...
} public onNewKey(value: string, index: number) {
random_line_split
data-resource-data.component.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
(): Observable<AttributesResource> { if (this.resourceType === AttributesResourceType.Collection) { return this.store$.pipe(select(selectCollectionById(this.resource.id))); } return this.store$.pipe(select(selectLinkTypeById(this.resource.id))); } private selectDataResource$(): Observable<DataRes...
selectResource$
identifier_name
mod.rs
(args: &[String]) { let matches = match handle_options(Vec::from_slice(args)) { Some(matches) => matches, None => return }; let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS); match matches.opt_str("explain") { Some(ref code) => { match descr...
run_compiler
identifier_name
mod.rs
let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS); match matches.opt_str("explain") { Some(ref code) => { match descriptions.find_description(code.as_slice()) { Some(ref description) => { println!("{}", description); ...
let matches = match handle_options(Vec::from_slice(args)) { Some(matches) => matches, None => return };
random_line_split
mod.rs
as_slice(); if ifile == "-" { let contents = io::stdin().read_to_end().unwrap(); let src = String::from_utf8(contents).unwrap(); (StrInput(src), None) } else { (FileInput(Path::new(ifile)), Some(Path::new(ifile))) } ...
} return; } if print_crate_info(&sess, &input, &odir, &ofile) { return; } driver::compile_input(sess, cfg, &input, &odir, &ofile, None); } /// Prints version information and returns None on success or an error /// message on failure. pub fn version(binary: &str, matches: &get...
{ early_error("can not list metadata for stdin"); }
conditional_block
mod.rs
as_slice(); if ifile == "-" { let contents = io::stdin().read_to_end().unwrap(); let src = String::from_utf8(contents).unwrap(); (StrInput(src), None) } else { (FileInput(Path::new(ifile)), Some(Path::new(ifile))) } ...
fn usage() { let message = format!("Usage: rustc [OPTIONS] INPUT"); println!("{}\n\ Additional help: -C help Print codegen options -W help Print 'lint' options and default settings -Z help Print internal options for debugging rustc\n", getopts::usa...
{ let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) { None => false, Some("verbose") => true, Some(s) => return Some(format!("Unrecognized argument: {}", s)) }; println!("{} {}", binary, env!("CFG_VERSION")); if verbose { println!("binary: {}"...
identifier_body
DesktopView.tsx
/* * * Tabs * */ import { FC, useEffect, useRef, useState, useCallback, memo } from 'react' import { isEmpty, findIndex } from 'ramda' import type { TSIZE_SM, TTabItem, TC11NLayout } from '@/spec' import usePlatform from '@/hooks/usePlatform' import { SIZE, C11N } from '@/constant' import { isString } from '@/uti...
faultActiveTabIndex]) // set slipbar with for current nav item // 为下面的滑动条设置当前 TabItem 的宽度 const handleNaviItemWith = useCallback( (index, width) => { tabWidthList[index] = width setTabWidthList(tabWidthList) }, [tabWidthList], ) const handleItemClick = useCallback( (index, e) => ...
.current.childNodes[defaultActiveTabIndex].firstElementChild .offsetWidth setSlipWidth(activeSlipWidth) } setActive(defaultActiveTabIndex) }, [de
conditional_block
DesktopView.tsx
/* * * Tabs * */ import { FC, useEffect, useRef, useState, useCallback, memo } from 'react' import { isEmpty, findIndex } from 'ramda' import type { TSIZE_SM, TTabItem, TC11NLayout } from '@/spec' import usePlatform from '@/hooks/usePlatform' import { SIZE, C11N } from '@/constant' import { isString } from '@/uti...
export default memo(Tabs)
random_line_split
general_spinless_majorana_opstr_test.py
from __future__ import print_function, division import sys,os qspin_path = os.path.join(os.getcwd(),"../") sys.path.insert(0,qspin_path) from quspin.basis import spinless_fermion_basis_general from quspin.operators import hamiltonian import numpy as np J=-np.sqrt(2.0) # hoppping U=+1.0 # nn interaction no_checks...
int_term=[[-0.25*U,j,j,(j+1)%N,(j+1)%N] for j in range(N)] id_term=[[0.25*U,j] for j in range(N)] # static=[['xy',hop_term_p],['yx',hop_term_m], # kinetic energy ['I',id_term],['xy',density_term],['xyxy',int_term], # nn interaction energy ] dynamic=[] # H_majorana=hamiltonian(static,[],basis=basis,dty...
s = np.arange(N) # sites [0,1,2,....] T = (s+1)%N # translation P = s[::-1] # reflection # ###### setting up bases ###### basis=spinless_fermion_basis_general(N, tblock=(T,0),pblock=(P,0),) #basis=spinless_fermion_basis_general(N,pblock=(P,0),)#pblock=(P,0),) #basis=spinless_fermion_basis_general(N,tblock=(T,...
conditional_block
general_spinless_majorana_opstr_test.py
from __future__ import print_function, division import sys,os qspin_path = os.path.join(os.getcwd(),"../") sys.path.insert(0,qspin_path) from quspin.basis import spinless_fermion_basis_general from quspin.operators import hamiltonian import numpy as np J=-np.sqrt(2.0) # hoppping U=+1.0 # nn interaction no_checks...
hop_term_m=[[-0.5j*J,j,(j+1)%N] for j in range(N)] density_term=[[+0.5j*U,j,j] for j in range(N)] int_term=[[-0.25*U,j,j,(j+1)%N,(j+1)%N] for j in range(N)] id_term=[[0.25*U,j] for j in range(N)] # static=[['xy',hop_term_p],['yx',hop_term_m], # kinetic energy ['I',id_term],['xy',density_term],['xyxy',int_...
##### Hamiltonian using Majorana fermions # # hop_term_p=[[+0.5j*J,j,(j+1)%N] for j in range(N)]
random_line_split
combine_array_len.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn main() { assert_eq!(norm2([3.0, 4.0]), 5.0*5.0); } // END RUST SOURCE // START rustc.norm2.InstCombine.before.mir // _4 = Len(_1); // ... // _8 = Len(_1); // END rustc.norm2.InstCombine.before.mir // START rustc.norm2.InstCombine.after.mir // _4 = const 2usize; // ... // _8 = const ...
fn norm2(x: [f32; 2]) -> f32 { let a = x[0]; let b = x[1]; a*a + b*b
random_line_split
combine_array_len.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// END RUST SOURCE // START rustc.norm2.InstCombine.before.mir // _4 = Len(_1); // ... // _8 = Len(_1); // END rustc.norm2.InstCombine.before.mir // START rustc.norm2.InstCombine.after.mir // _4 = const 2usize; // ... // _8 = const 2usize; // END rustc.norm2.InstCombine.after.mir
{ assert_eq!(norm2([3.0, 4.0]), 5.0*5.0); }
identifier_body
combine_array_len.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert_eq!(norm2([3.0, 4.0]), 5.0*5.0); } // END RUST SOURCE // START rustc.norm2.InstCombine.before.mir // _4 = Len(_1); // ... // _8 = Len(_1); // END rustc.norm2.InstCombine.before.mir // START rustc.norm2.InstCombine.after.mir // _4 = const 2usize; // ... // _8 = const 2usize; //...
main
identifier_name
datatype-date-format_fi.js
/* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License:
build: 3167 */ YUI.add("lang/datatype-date-format_fi",function(a){a.Intl.add("datatype-date-format","fi",{"a":["su","ma","ti","ke","to","pe","la"],"A":["sunnuntaina","maanantaina","tiistaina","keskiviikkona","torstaina","perjantaina","lauantaina"],"b":["tammikuuta","helmikuuta","maaliskuuta","huhtikuuta","toukokuuta"...
http://developer.yahoo.com/yui/license.html version: 3.3.0
random_line_split
Case.js
[attr] = value; } if (isStatusChanged) { this.resolve(); } return this; }, /** * A test that determines if a case has one of a set of statuses. * * @return boolean * A bit that indicates if the case has one of the supplied statuses. */ hasStatus: f...
reject
identifier_name
Case.js
} this.attributes[attr] = value; } if (isStatusChanged) { this.resolve(); } return this; }, /** * A test that determines if a case has one of a set of statuses. * * @return boolean * A bit that indicates if the case has one of the supplied statuses...
random_line_split
Case.js
* A bit that indicates if the case has one of the supplied statuses. */ hasStatus: function (statuses) { // This is a rought test of arrayness. if (typeof statuses !== 'object') { statuses = [statuses]; } var status = this.get('status'); for (var i = 0, il = statuse...
{ keepers.push(list[i]); }
conditional_block
Case.js
// Prototype object of the Case. Case.fn = Case.prototype = { constructor: Case, init: function (attributes) { this.listeners = {}; this.timeout = null; this.attributes = attributes || {}; var that = this; // Dispatch a resolve event if the case is initiated with a status. ...
{ return new Case.fn.init(attributes); }
identifier_body
fast_forward_button.js
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.ui.FastForwardButton'); goog.require('shaka.ui.Controls'); goog.require('shaka.ui.Element'); goog.require('shaka.ui.Enums'); goog.require('shaka.ui.Locales'); goog.require('shaka.ui.Localization')...
const trickPlayRate = this.player.getPlaybackRate(); const newRateIndex = this.fastForwardRates_.indexOf(trickPlayRate) + 1; // When the button is clicked, the next rate in this.fastForwardRates_ is // selected. If no more rates are available, the first one is set. const newRate = (newRateIndex !...
{ return; }
conditional_block
fast_forward_button.js
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.ui.FastForwardButton'); goog.require('shaka.ui.Controls'); goog.require('shaka.ui.Element'); goog.require('shaka.ui.Enums'); goog.require('shaka.ui.Locales'); goog.require('shaka.ui.Localization')...
(rootElement, controls) { return new shaka.ui.FastForwardButton(rootElement, controls); } }; shaka.ui.Controls.registerElement( 'fast_forward', new shaka.ui.FastForwardButton.Factory());
create
identifier_name
fast_forward_button.js
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.ui.FastForwardButton'); goog.require('shaka.ui.Controls'); goog.require('shaka.ui.Element'); goog.require('shaka.ui.Enums'); goog.require('shaka.ui.Locales'); goog.require('shaka.ui.Localization')...
}); this.eventManager.listen( this.localization, shaka.ui.Localization.LOCALE_CHANGED, () => { this.updateAriaLabel_(); }); this.eventManager.listen(this.button_, 'click', () => { this.fastForward_(); }); } /** * @private */ updateAriaLabel_() { th...
{ super(parent, controls); /** @private {!HTMLButtonElement} */ this.button_ = shaka.util.Dom.createButton(); this.button_.classList.add('material-icons-round'); this.button_.classList.add('shaka-fast-forward-button'); this.button_.classList.add('shaka-tooltip-status'); this.button_.setAttr...
identifier_body
fast_forward_button.js
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.ui.FastForwardButton'); goog.require('shaka.ui.Controls'); goog.require('shaka.ui.Element'); goog.require('shaka.ui.Enums');
/** * @extends {shaka.ui.Element} * @final * @export */ shaka.ui.FastForwardButton = class extends shaka.ui.Element { /** * @param {!HTMLElement} parent * @param {!shaka.ui.Controls} controls */ constructor(parent, controls) { super(parent, controls); /** @private {!HTMLButtonElement} */ ...
goog.require('shaka.ui.Locales'); goog.require('shaka.ui.Localization'); goog.require('shaka.util.Dom');
random_line_split
pattern_type_mismatch.rs
/// of ownership semantics. /// /// ### Why is this bad? /// It isn't bad in general. But in some contexts it can be desirable /// because it increases ownership hints in the code, and will guard against some changes /// in ownership. /// /// ### Example /// This example shows the ba...
find_first_mismatch_in_struct
identifier_name
pattern_type_mismatch.rs
have to adjust either the expression that is matched /// against or the pattern itself, as well as the bindings that are introduced by the /// adjusted patterns. For matching you will have to either dereference the expression /// with the `*` operator, or amend the patterns to explicitly match against `&<p...
if let TyKind::Tuple(..) = ty.kind() { return find_first_mismatch_in_tuple(cx, pats, ty.tuple_fields()); } } if let PatKind::Or(sub_pats) = pat.kind { for pat in sub_pats { let maybe_mismatch = find_first_mismatch(cx, pat, ty, level); if let Some(mism...
random_line_split
pattern_type_mismatch.rs
have to adjust either the expression that is matched /// against or the pattern itself, as well as the bindings that are introduced by the /// adjusted patterns. For matching you will have to either dereference the expression /// with the `*` operator, or amend the patterns to explicitly match against `&<p...
); true } else { false } } #[derive(Debug, Copy, Clone)] enum Level { Top, Lower, } #[allow(rustc::usage_of_ty_tykind)] fn find_first_mismatch<'tcx>( cx: &LateContext<'tcx>, pat: &Pat<'_>, ty: Ty<'tcx>, level: Level, ) -> Option<(Span, Mutability, Level)> { ...
{ let maybe_mismatch = find_first_mismatch(cx, pat, expr_ty, Level::Top); if let Some((span, mutability, level)) = maybe_mismatch { span_lint_and_help( cx, PATTERN_TYPE_MISMATCH, span, "type of pattern does not match the expression type", None,...
identifier_body
pattern_type_mismatch.rs
be used to highlight areas of interest and ensure a good understanding /// of ownership semantics. /// /// ### Why is this bad? /// It isn't bad in general. But in some contexts it can be desirable /// because it increases ownership hints in the code, and will guard against some changes /// in ...
{ return Some(mismatch); }
conditional_block
vanilla_lstm.py
. layers = {'lstm': (param_init_lstm, lstm_layer)} def sgd(lr, tparams, grads, x, mask, y, cost): """ Stochastic Gradient Descent :note: A more complicated version of sgd then needed. This is done like that for adadelta and rmsprop. """ # New set of shared variable that will contain the gra...
return probs def pred_error(f_pred, prepare_data, data, iterator, verbose=False):
random_line_split
vanilla_lstm.py
(_x, n, dim): if _x.ndim == 3: return _x[:, :, n * dim:(n + 1) * dim] return _x[:, n * dim:(n + 1) * dim] def _step(m_, x_, h_, c_): preact = tensor.dot(h_, tparams[_p(prefix, 'U')]) preact += x_ i = tensor.nnet.sigmoid(_slice(preact, 0, options['dim_proj'])) ...
_slice
identifier_name
vanilla_lstm.py
def _step(m_, x_, h_, c_): preact = tensor.dot(h_, tparams[_p(prefix, 'U')]) preact += x_ i = tensor.nnet.sigmoid(_slice(preact, 0, options['dim_proj'])) f = tensor.nnet.sigmoid(_slice(preact, 1, options['dim_proj'])) o = tensor.nnet.sigmoid(_slice(preact, 2, options['dim_...
if _x.ndim == 3: return _x[:, :, n * dim:(n + 1) * dim] return _x[:, n * dim:(n + 1) * dim]
identifier_body
vanilla_lstm.py
params[kk] = pp[kk] return params def init_tparams(params): tparams = OrderedDict() for kk, pp in params.items(): tparams[kk] = theano.shared(params[kk], name=kk) return tparams def get_layer(name): fns = layers[name] return fns def ortho_weight(ndim): W = numpy.rando...
raise Warning('%s is not in the archive' % kk)
conditional_block
timeEntry.py
### Copyright (C) 2005 Thomas M. Hinkle ### Copyright (C) 2009 Rolf Leggewie ### ### This library is free software; you can redistribute it and/or ### modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation; either version 2 of the ### License, or (at your option) an...
l.set_use_underline(True) l.set_alignment(0,0.5) hb.pack_start(l) te=TimeEntry() import sys te.connect('changed',lambda w: sys.stderr.write('Time value: %s'%w.get_value())) l.set_mnemonic_widget(te) hb.pack_start(te,expand=False,fill=False) vb.add(hb) qb = gtk.Button(stock=gtk.ST...
hb = gtk.HBox() l=gtk.Label('_Label')
random_line_split
timeEntry.py
### Copyright (C) 2005 Thomas M. Hinkle ### Copyright (C) 2009 Rolf Leggewie ### ### This library is free software; you can redistribute it and/or ### modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation; either version 2 of the ### License, or (at your option) an...
self.valid = False self.warn = True self.set_warning_text('Invalid input.' + 'Time must be expressed in hours, minutes, seconds, etc.') self._show_warning() def set_value (self,seconds): self.entry.set_text( convert.seconds_to_timestring(seconds,...
self._hide_warning_slowly() return
conditional_block
timeEntry.py
### Copyright (C) 2005 Thomas M. Hinkle ### Copyright (C) 2009 Rolf Leggewie ### ### This library is free software; you can redistribute it and/or ### modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation; either version 2 of the ### License, or (at your option) an...
return None else: partial_unit = words[-1] for u in self.conv.unit_to_seconds.keys(): if u.lower().find(partial_unit.lower())==0: return None #self._hide_warning_slowly() #return ...
__gtype_name__ = 'TimeEntry' def __init__ (self, conv=None): if not conv: self.conv = convert.get_converter() else: self.conv = conv validatingEntry.ValidatingEntry.__init__(self) self.entry.get_value = self.get_value self.entry.set_value = self.set_value def fi...
identifier_body
timeEntry.py
### Copyright (C) 2005 Thomas M. Hinkle ### Copyright (C) 2009 Rolf Leggewie ### ### This library is free software; you can redistribute it and/or ### modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation; either version 2 of the ### License, or (at your option) an...
(validatingEntry.ValidatingEntry): __gtype_name__ = 'TimeEntry' def __init__ (self, conv=None): if not conv: self.conv = convert.get_converter() else: self.conv = conv validatingEntry.ValidatingEntry.__init__(self) self.entry.get_value = self.get_value self.entry.set_va...
TimeEntry
identifier_name
mod.rs
/// Type definitions and serializations of types used in the VM and in other modules #[derive(Serialize, Deserialize, Clone)] pub struct Instruction { pub opcode: Opcode, pub target: Register, pub left: Register, pub right: Register } #[derive(Serialize, Deserialize)] pub struct Module { pub funct...
<'a> { pub functions: &'a [u64], pub constants: &'a [i64], pub code: &'a [Instruction], pub registers: &'a mut [i64], pub base: usize } /// Definition of the register type and a list of special registers pub type Register = u8; pub mod reg { use super::*; pub const RET: Register = 0; pu...
Thread
identifier_name
mod.rs
/// Type definitions and serializations of types used in the VM and in other modules #[derive(Serialize, Deserialize, Clone)] pub struct Instruction { pub opcode: Opcode, pub target: Register, pub left: Register, pub right: Register } #[derive(Serialize, Deserialize)] pub struct Module { pub funct...
}
random_line_split
countdowntimer.js
function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60);
var days = Math.floor(t / (1000 * 60 * 60 * 24)); // Make sure display does not show negative time if (seconds < 0) seconds = 0; if (minutes < 0) minutes = 0; if (hours < 0) hours = 0; if (days < 0) days = 0; return { 'total': t, 'days': days, 'hours': hours, 'min...
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
random_line_split
countdowntimer.js
function getTimeRemaining(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); var hours = Math.floor((t / (1000 * 60 * 60)) % 24); var days = Math.floor(t / (1000 * 60 * 60 * 24)); // Make sure displa...
updateClock(); var timeinterval = setInterval(updateClock, 1000); } //var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000); var deadline = 'July 8 2016 15:00:00'; initializeClock('clockdiv', deadline);
{ var clock = document.getElementById(id); var daysSpan = clock.querySelector('.days'); var hoursSpan = clock.querySelector('.hours'); var minutesSpan = clock.querySelector('.minutes'); var secondsSpan = clock.querySelector('.seconds'); function updateClock() { var t = getTimeRemaining(endtime); d...
identifier_body
countdowntimer.js
function
(endtime) { var t = Date.parse(endtime) - Date.parse(new Date()); var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 1000 / 60) % 60); var hours = Math.floor((t / (1000 * 60 * 60)) % 24); var days = Math.floor(t / (1000 * 60 * 60 * 24)); // Make sure display does not show negative ...
getTimeRemaining
identifier_name
panic_in_result_fn_assertions.rs
#![warn(clippy::panic_in_result_fn)] #![allow(clippy::unnecessary_wraps)] struct A; impl A { fn result_with_assert_with_message(x: i32) -> Result<bool, String> // should emit lint { assert!(x == 5, "wrong argument"); Ok(true) } fn result_with_assert_eq(x: i32) -> Result<bool, String> ...
assert!(x == 5, "wrong argument"); } fn other_with_assert_eq(x: i32) // should not emit lint { assert_eq!(x, 5); } fn other_with_assert_ne(x: i32) // should not emit lint { assert_ne!(x, 1); } fn result_without_banned_functions() -> Result<bool, String> // shou...
{
random_line_split
panic_in_result_fn_assertions.rs
#![warn(clippy::panic_in_result_fn)] #![allow(clippy::unnecessary_wraps)] struct A; impl A { fn result_with_assert_with_message(x: i32) -> Result<bool, String> // should emit lint { assert!(x == 5, "wrong argument"); Ok(true) } fn result_with_assert_eq(x: i32) -> Result<bool, String> ...
fn result_with_assert_ne(x: i32) -> Result<bool, String> // should emit lint { assert_ne!(x, 1); Ok(true) } fn other_with_assert_with_message(x: i32) // should not emit lint { assert!(x == 5, "wrong argument"); } fn other_with_assert_eq(x: i32) // should not emit ...
{ assert_eq!(x, 5); Ok(true) }
identifier_body
panic_in_result_fn_assertions.rs
#![warn(clippy::panic_in_result_fn)] #![allow(clippy::unnecessary_wraps)] struct A; impl A { fn result_with_assert_with_message(x: i32) -> Result<bool, String> // should emit lint { assert!(x == 5, "wrong argument"); Ok(true) } fn
(x: i32) -> Result<bool, String> // should emit lint { assert_eq!(x, 5); Ok(true) } fn result_with_assert_ne(x: i32) -> Result<bool, String> // should emit lint { assert_ne!(x, 1); Ok(true) } fn other_with_assert_with_message(x: i32) // should not emit lint ...
result_with_assert_eq
identifier_name
backdrop.ts
import {Animate} from "../../core/util/animate"; import {ElementRef, ViewEncapsulation, Component, Input, Output, EventEmitter} from "angular2/core"; import {DOM} from "angular2/src/platform/dom/dom_adapter"; /** * An overlay for content on the page. * Can optionally dismiss when clicked on. * Has outputs for show/...
(): Promise<any> { return this.toggle(false); } /** * Show the backdrop and return a promise that is resolved when the show animations are * complete. */ show(): Promise<any> { return this.toggle(true); } /** * Toggle the visibility of the backdrop. * @param visible whether or not the...
hide
identifier_name
backdrop.ts
import {Animate} from "../../core/util/animate"; import {ElementRef, ViewEncapsulation, Component, Input, Output, EventEmitter} from "angular2/core"; import {DOM} from "angular2/src/platform/dom/dom_adapter"; /** * An overlay for content on the page. * Can optionally dismiss when clicked on. * Has outputs for show/...
/** * Hide the backdrop and return a promise that is resolved when the hide animations are * complete. */ hide(): Promise<any> { return this.toggle(false); } /** * Show the backdrop and return a promise that is resolved when the show animations are * complete. */ show(): Promise<any>...
{ if (this.clickClose && !this._transitioning && this.visible) { this.hide(); } }
identifier_body
backdrop.ts
import {Animate} from "../../core/util/animate"; import {ElementRef, ViewEncapsulation, Component, Input, Output, EventEmitter} from "angular2/core"; import {DOM} from "angular2/src/platform/dom/dom_adapter"; /** * An overlay for content on the page. * Can optionally dismiss when clicked on. * Has outputs for show/...
* opposite will happen when the backdrop is hidden. */ @Input() public transitionAddClass = true; /** * Whether the backdrop is visible. */ get visible(): boolean { return this._visible; } @Input() set visible(value: boolean) { this.toggle(value); } private _visible: boolean = ...
/** * Whether to add the {@see transitionClass} or remove it when the backdrop is shown. The
random_line_split
auth.py
# coding=utf-8 """Request handler for authentication.""" from __future__ import unicode_literals import logging import random import string import time from builtins import range import jwt from medusa import app, helpers, notifiers from medusa.logger.adapters.style import BraceAdapter from medusa.server.api.v2.base...
(BaseRequestHandler): """Auth request handler.""" #: resource name name = 'authenticate' #: allowed HTTP methods allowed_methods = ('POST', ) def _check_authentication(self): """Override authentication check for the authentication endpoint.""" return None def post(self, *a...
AuthHandler
identifier_name
auth.py
# coding=utf-8 """Request handler for authentication.""" from __future__ import unicode_literals import logging import random import string import time from builtins import range import jwt from medusa import app, helpers, notifiers from medusa.logger.adapters.style import BraceAdapter from medusa.server.api.v2.base...
def _failed_login(self, error=None): log.warning('{user} attempted a failed login to the API v2 from IP: {ip}', { 'user': app.WEB_USERNAME, 'ip': self.request.remote_ip }) return self._unauthorized(error=error)
self.set_header('Content-Type', 'application/json') if app.NOTIFY_ON_LOGIN and not helpers.is_ip_private(self.request.remote_ip): notifiers.notify_login(self.request.remote_ip) log.info('{user} logged into the API v2', {'user': app.WEB_USERNAME}) time_now = int(time.time()) ...
identifier_body
auth.py
# coding=utf-8 """Request handler for authentication.""" from __future__ import unicode_literals import logging import random import string import time from builtins import range import jwt from medusa import app, helpers, notifiers from medusa.logger.adapters.style import BraceAdapter from medusa.server.api.v2.base...
if username != submitted_username or password != submitted_password: return self._failed_login(error='Invalid credentials') return self._login(submitted_exp) def _login(self, exp=86400): self.set_header('Content-Type', 'application/json') if app.NOTIFY_ON_LOGIN and not ...
submitted_exp = request_body.get('exp', 86400)
random_line_split
auth.py
# coding=utf-8 """Request handler for authentication.""" from __future__ import unicode_literals import logging import random import string import time from builtins import range import jwt from medusa import app, helpers, notifiers from medusa.logger.adapters.style import BraceAdapter from medusa.server.api.v2.base...
request_body = json_decode(self.request.body) submitted_username = request_body.get('username') submitted_password = request_body.get('password') submitted_exp = request_body.get('exp', 86400) if username != submitted_username or password != submitted_password: retu...
return self._failed_login(error='Incorrect content-type')
conditional_block
device.ts
import logger from "@/logger"; import i18next from "i18next"; import AdBanner from "@/utils/AdBanner"; import AdInterstitial from "@/utils/AdInterstitial"; import Tracking from "@/utils/Tracking"; function showExitAppDialog(): void { navigator.notification.confirm( i18next.t("close_dialog_message"), (choice)...
// Setup localization for cordova devices navigator.globalization.getPreferredLanguage( (language) => { logger.info("ChangeLanguage: [" + language.value + "]"); i18next.changeLanguage(language.value); }, (error: GlobalizationError) => { logger.error("Cha...
try {
random_line_split
device.ts
import logger from "@/logger"; import i18next from "i18next"; import AdBanner from "@/utils/AdBanner"; import AdInterstitial from "@/utils/AdInterstitial"; import Tracking from "@/utils/Tracking"; function showExitAppDialog(): void { navigator.notification.confirm( i18next.t("close_dialog_message"), (choice)...
(): Promise<void> { return new Promise((resolve) => { try { AdBanner.init(); AdInterstitial.init(); } catch (err) { logger.error("[Device] Ad initialize failed"); } try { Tracking.auth(); } catch (err) { logger.error("[Device] Tracking initialize failed"); } ...
setup
identifier_name
device.ts
import logger from "@/logger"; import i18next from "i18next"; import AdBanner from "@/utils/AdBanner"; import AdInterstitial from "@/utils/AdInterstitial"; import Tracking from "@/utils/Tracking"; function showExitAppDialog(): void { navigator.notification.confirm( i18next.t("close_dialog_message"), (choice)...
) { window.StatusBar.overlaysWebView(true); window.StatusBar.backgroundColorByHexString("#A0483C46"); window.StatusBar.styleBlackTranslucent(); } } catch (err) { logger.error("[Device] Statusbar setting failed"); } try { // Setup localization for cordova devi...
{ return new Promise((resolve) => { try { AdBanner.init(); AdInterstitial.init(); } catch (err) { logger.error("[Device] Ad initialize failed"); } try { Tracking.auth(); } catch (err) { logger.error("[Device] Tracking initialize failed"); } try { windo...
identifier_body
device.ts
import logger from "@/logger"; import i18next from "i18next"; import AdBanner from "@/utils/AdBanner"; import AdInterstitial from "@/utils/AdInterstitial"; import Tracking from "@/utils/Tracking"; function showExitAppDialog(): void { navigator.notification.confirm( i18next.t("close_dialog_message"), (choice)...
} catch (err) { logger.error("[Device] Statusbar setting failed"); } try { // Setup localization for cordova devices navigator.globalization.getPreferredLanguage( (language) => { logger.info("ChangeLanguage: [" + language.value + "]"); i18next.changeLanguage(l...
{ window.StatusBar.overlaysWebView(true); window.StatusBar.backgroundColorByHexString("#A0483C46"); window.StatusBar.styleBlackTranslucent(); }
conditional_block
service-server.ts
/** * Created by Deakin on 2017/3/20 0020. */ import { Injectable } from '@angular/core'; import { ServiceItemData } from './service-item-data'; @Injectable() export class
{ public serviceData: ServiceItemData[] = [ { icon: '&#xe6a1;', bg: 'assets/img/service_bg_01.jpg', title: '移动app定制开发', describe: 'Android、iOS系统软件开发<br/>满足移动APP多平台开发需求' }, { icon: '&#xe655;', bg: 'assets/img/service_bg_02.jpg', title: '网站定制开发', describe: '根...
ServiceServer
identifier_name
service-server.ts
/**
* Created by Deakin on 2017/3/20 0020. */ import { Injectable } from '@angular/core'; import { ServiceItemData } from './service-item-data'; @Injectable() export class ServiceServer { public serviceData: ServiceItemData[] = [ { icon: '&#xe6a1;', bg: 'assets/img/service_bg_01.jpg', title: '移动...
random_line_split
service-server.ts
/** * Created by Deakin on 2017/3/20 0020. */ import { Injectable } from '@angular/core'; import { ServiceItemData } from './service-item-data'; @Injectable() export class ServiceServer { public serviceData: ServiceItemData[] = [ { icon: '&#xe6a1;', bg: 'assets/img/service_bg_01.jpg', title:...
identifier_body
destroyObject.js
/*global define*/ define([ './defaultValue', './DeveloperError' ], function( defaultValue, DeveloperError) { "use strict"; function
() { return true; } /** * Destroys an object. Each of the object's functions, including functions in its prototype, * is replaced with a function that throws a {@link DeveloperError}, except for the object's * <code>isDestroyed</code> function, which is set to a function that returns <c...
returnTrue
identifier_name
destroyObject.js
/*global define*/ define([ './defaultValue', './DeveloperError' ], function( defaultValue, DeveloperError) { "use strict"; function returnTrue() { return true; } /** * Destroys an object. Each of the object's functions, including functions in its proto...
} object.isDestroyed = returnTrue; return undefined; }; return destroyObject; });
{ object[key] = throwOnDestroyed; }
conditional_block
destroyObject.js
/*global define*/ define([ './defaultValue', './DeveloperError' ], function( defaultValue, DeveloperError) { "use strict"; function returnTrue() { return true; } /** * Destroys an object. Each of the object's functions, including functions in its proto...
* return Cesium.destroyObject(this); * }; */ var destroyObject = function(object, message) { message = defaultValue(message, 'This object was destroyed, i.e., destroy() was called.'); function throwOnDestroyed() { throw new DeveloperError(message); } ...
* // How a texture would destroy itself. * this.destroy = function () { * _gl.deleteTexture(_texture);
random_line_split
destroyObject.js
/*global define*/ define([ './defaultValue', './DeveloperError' ], function( defaultValue, DeveloperError) { "use strict"; function returnTrue() { return true; } /** * Destroys an object. Each of the object's functions, including functions in its proto...
for ( var key in object) { if (typeof object[key] === 'function') { object[key] = throwOnDestroyed; } } object.isDestroyed = returnTrue; return undefined; }; return destroyObject; });
{ throw new DeveloperError(message); }
identifier_body