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 |
|---|---|---|---|---|
dom.rs | Some(*self) == scoped_to {
return None;
}
let mut current = *self;
loop {
if let Some(s) = current.next_sibling() {
return Some(s);
}
let parent = current.parent_node();
if parent == scoped_to {
return... |
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this elem... | {
unreachable!("Servo doesn't know about NAC");
} | identifier_body |
users.py | , value)
if error:
raise JsonableError(_("Invalid {} value {} ({})").format(key, value, error))
elif bot_type == UserProfile.EMBEDDED_BOT:
try:
from zerver.lib.bot_lib import get_bot_handler
bot_handler = get_bot_handler(service_name)
if hasa... | (
user_profile: UserProfile,
target_user_id: int,
*,
allow_deactivated: bool = False,
allow_bots: bool = False,
for_admin: bool,
) -> UserProfile:
"""Master function for accessing another user by ID in API code;
verifies the user ID is in the same realm, and if requested checks
for a... | access_user_by_id | identifier_name |
users.py | int, field: CustomProfileField, value: Union[int, str, List[int]]
) -> Union[int, str, List[int]]:
validators = CustomProfileField.FIELD_VALIDATORS
field_type = field.field_type
var_name = f"{field.name}"
if field_type in validators:
validator = validators[field_type]
return validator(v... | custom_profile_field_values = base_query.filter(user_profile=target_user) | conditional_block | |
users.py |
def check_short_name(short_name_raw: str) -> str:
short_name = short_name_raw.strip()
if len(short_name) == 0:
raise JsonableError(_("Bad name or username"))
return short_name
def check_valid_bot_config(bot_type: int, service_name: str, config_data: Dict[str, str]) -> None:
if bot_type == Us... |
if dup_exists:
raise JsonableError(_("Name is already in use!")) | random_line_split | |
users.py | , value)
if error:
raise JsonableError(_("Invalid {} value {} ({})").format(key, value, error))
elif bot_type == UserProfile.EMBEDDED_BOT:
try:
from zerver.lib.bot_lib import get_bot_handler
bot_handler = get_bot_handler(service_name)
if hasa... |
def bulk_get_users(
emails: List[str], realm: Optional[Realm], base_query: "QuerySet[UserProfile]" = None
) -> Dict[str, UserProfile]:
if base_query is None:
assert realm is not None
query = UserProfile.objects.filter(realm=realm, is_active=True)
realm_id = realm.id
else:
... | return role in {UserProfile.ROLE_REALM_ADMINISTRATOR, UserProfile.ROLE_REALM_OWNER} | identifier_body |
codemap.rs | -> CharPos {
CharPos(**self + **rhs)
}
}
impl Sub<CharPos,CharPos> for CharPos {
fn sub(&self, rhs: &CharPos) -> CharPos {
CharPos(**self - **rhs)
}
}
/**
Spans represent a region of code, used for error reporting. Positions in spans
are *absolute* positions from the beginning of the code... | <T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
respan(mk_sp(lo, hi), t)
}
pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
Spanned {node: t, span: sp}
}
pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
respan(dummy_sp(), t)
}
/* assuming that we're not in macro expansion */
pub fn mk_sp(lo: BytePos, hi... | spanned | identifier_name |
codemap.rs | ,
// the format with which the macro was invoked.
format: MacroFormat,
span: Option<Span>
}
/// Extra information for tracking macro expansion of spans
#[deriving(IterBytes)]
pub struct ExpnInfo {
call_site: Span,
callee: NameAndSpan
}
pub type FileName = @str;
pub struct FileLines
{
file: @F... | let chpos = self.bytepos_to_local_charpos(pos); | random_line_split | |
curried-value.ts | import { CapturedArguments, CurriedType, Owner } from '@glimmer/interfaces';
import { symbol, _WeakSet } from '@glimmer/util';
import { Reference } from '@glimmer/reference';
const TYPE: unique symbol = symbol('TYPE');
const INNER: unique symbol = symbol('INNER');
const OWNER: unique symbol = symbol('OWNER');
const AR... | <T extends CurriedType = CurriedType> {
[TYPE]: T;
[INNER]: object | string | CurriedValue<T>;
[OWNER]: Owner;
[ARGS]: CapturedArguments | null;
[RESOLVED]: boolean;
/** @internal */
constructor(
type: T,
inner: object | string | CurriedValue<T>,
owner: Owner,
args: CapturedArguments | nu... | CurriedValue | identifier_name |
curried-value.ts | import { CapturedArguments, CurriedType, Owner } from '@glimmer/interfaces';
import { symbol, _WeakSet } from '@glimmer/util';
import { Reference } from '@glimmer/reference';
const TYPE: unique symbol = symbol('TYPE');
const INNER: unique symbol = symbol('INNER');
const OWNER: unique symbol = symbol('OWNER');
const AR... | [TYPE]: T;
[INNER]: object | string | CurriedValue<T>;
[OWNER]: Owner;
[ARGS]: CapturedArguments | null;
[RESOLVED]: boolean;
/** @internal */
constructor(
type: T,
inner: object | string | CurriedValue<T>,
owner: Owner,
args: CapturedArguments | null,
resolved = false
) {
CURRI... | }
export class CurriedValue<T extends CurriedType = CurriedType> { | random_line_split |
curried-value.ts | import { CapturedArguments, CurriedType, Owner } from '@glimmer/interfaces';
import { symbol, _WeakSet } from '@glimmer/util';
import { Reference } from '@glimmer/reference';
const TYPE: unique symbol = symbol('TYPE');
const INNER: unique symbol = symbol('INNER');
const OWNER: unique symbol = symbol('OWNER');
const AR... | // we'll fetch the value of this register and set it as the owner on the
// new root scope.
definition = inner;
owner = currentWrapper[OWNER];
resolved = currentWrapper[RESOLVED];
break;
}
currentWrapper = inner;
}
return { definition, owner, resolved, positional, name... | {
let { [ARGS]: curriedArgs, [INNER]: inner } = currentWrapper;
if (curriedArgs !== null) {
let { named: curriedNamed, positional: curriedPositional } = curriedArgs;
if (curriedPositional.length > 0) {
positional =
positional === undefined ? curriedPositional : curriedPositional.... | conditional_block |
curried-value.ts | import { CapturedArguments, CurriedType, Owner } from '@glimmer/interfaces';
import { symbol, _WeakSet } from '@glimmer/util';
import { Reference } from '@glimmer/reference';
const TYPE: unique symbol = symbol('TYPE');
const INNER: unique symbol = symbol('INNER');
const OWNER: unique symbol = symbol('OWNER');
const AR... |
}
interface ResolvedCurriedValue<T> {
definition: T;
owner: Owner;
resolved: boolean;
positional: Reference[] | undefined;
named: Record<string, Reference>[] | undefined;
}
export function resolveCurriedValue(
curriedValue: CurriedValue<CurriedType.Component>
): ResolvedCurriedValue<object | string>;
exp... | {
CURRIED_VALUES.add(this);
this[TYPE] = type;
this[INNER] = inner;
this[OWNER] = owner;
this[ARGS] = args;
this[RESOLVED] = resolved;
} | identifier_body |
Spinner.py | import sublime
from . import SblmCmmnFnctns
class Spinner:
SYMBOLS_ROW = u'←↑→↓'
SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
def __init__(self, symbols, view, startStr, endStr):
self.symbols = symbols
self.length = len(symbols)
self.position = 0
self.stopFlag = False
self.view = view
self.startStr = startStr
self.... | ew.erase_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER)
self.stopFlag = True
| nFnctns.SUBLIME_STATUS_SPINNER, self.__next__())
sublime.set_timeout(lambda: self.start(), 300)
def stop(self):
self.vi | conditional_block |
Spinner.py | import sublime
from . import SblmCmmnFnctns
class Spinner:
SYMBOLS_ROW = u'←↑→↓'
SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
def __init__(self, symbols, view, startStr, endStr):
self.symbols = symbols
sel | f.position = self.position + 1
return self.startStr + self.symbols[self.position % self.length] + self.endStr
def start(self):
if not self.stopFlag:
self.view.set_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER, self.__next__())
sublime.set_timeout(lambda: self.start(), 300)
def stop(self):
self.view.er... | f.length = len(symbols)
self.position = 0
self.stopFlag = False
self.view = view
self.startStr = startStr
self.endStr = endStr
def __next__(self):
sel | identifier_body |
Spinner.py | import sublime
| from . import SblmCmmnFnctns
class Spinner:
SYMBOLS_ROW = u'←↑→↓'
SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
def __init__(self, symbols, view, startStr, endStr):
self.symbols = symbols
self.length = len(symbols)
self.position = 0
self.stopFlag = False
self.view = view
self.startStr = startStr
self.endStr = endStr
... | random_line_split | |
Spinner.py | import sublime
from . import SblmCmmnFnctns
class Spinner:
SYMBOLS_ROW = u'←↑→↓'
SYMBOLS_BOX = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
def __init__(self, symbols, view, startStr, endStr):
self.symbols = symbols
self.length = len(symbols)
self.position = 0
self.stopFlag = False
self.view = view
self.startStr = startStr
self.... | lf.position + 1
return self.startStr + self.symbols[self.position % self.length] + self.endStr
def start(self):
if not self.stopFlag:
self.view.set_status(SblmCmmnFnctns.SUBLIME_STATUS_SPINNER, self.__next__())
sublime.set_timeout(lambda: self.start(), 300)
def stop(self):
self.view.erase_status(Sblm... | ion = se | identifier_name |
fileEditorInput.ts | EditorInput, IFileEditorInput, ITextEditorModel, Verbosity, IRevertOptions } from 'vs/workbench/common/editor';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { BinaryEditorModel } from 'vs/workbench/common/editor/binaryEditorModel';
import { FileOperationError,... | (): string {
return this.labelService.getUriLabel(this.resource);
}
getTitle(verbosity: Verbosity): string {
let title: string;
switch (verbosity) {
case Verbosity.SHORT:
title = this.shortTitle;
break;
case Verbosity.MEDIUM:
title = this.mediumTitle;
break;
case Verbosity.LONG:
ti... | longTitle | identifier_name |
fileEditorInput.ts | /common/editor';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { BinaryEditorModel } from 'vs/workbench/common/editor/binaryEditorModel';
import { FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
import { ITextFileService, AutoSav... | return this.instantiationService.createInstance(BinaryEditorModel, this.resource, this.getName()).load().then(m => m as BinaryEditorModel);
}
isResolved(): boolean { | random_line_split | |
fileEditorInput.ts | EditorInput, IFileEditorInput, ITextEditorModel, Verbosity, IRevertOptions } from 'vs/workbench/common/editor';
import { TextFileEditorModel } from 'vs/workbench/services/textfile/common/textFileEditorModel';
import { BinaryEditorModel } from 'vs/workbench/common/editor/binaryEditorModel';
import { FileOperationError,... |
private decorateLabel(label: string): string {
const model = this.textFileService.models.get(this.resource);
if (model && model.hasState(ModelState.ORPHAN)) {
return localize('orphanedFile', "{0} (deleted from disk)", label);
}
if (model && model.isReadonly()) {
return localize('readonlyFile', "{0} (re... | {
let title: string;
switch (verbosity) {
case Verbosity.SHORT:
title = this.shortTitle;
break;
case Verbosity.MEDIUM:
title = this.mediumTitle;
break;
case Verbosity.LONG:
title = this.longTitle;
break;
}
return this.decorateLabel(title);
} | identifier_body |
ipv4.rs | .0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
... | (&self) -> &SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_ref!(SockAddr, Ipv4SockAddr);
impl AsMut<SockAddr> for Ipv4SockAddr {
fn as_mut(&mut self) -> &mut SockAddr {
unsafe { mem::cast(self) }
}
}
impl_try_as_mut!(SockAddr, Ipv4SockAddr | as_ref | identifier_name |
ipv4.rs | 2.0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
... | const PORT_OFF: usize = 2;
const ADDR_OFF: usize = 4;
pub fn validate(bytes: &[u8]) -> Result<usize> {
if bytes.len() < IPV4_SOCK_ADDR_SIZE {
return Err(error::InvalidArgument);
}
let mut family: sa_family_t = 0;
mem::copy(family.as_mut(), bytes);
match family as c_int {
AF_INET => ... | // should have a static assert that this size
// is actually correct.
// Offsets of the port and address. Same XXX applies. | random_line_split |
ipv4.rs | .0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
... |
/// Turns the address into a 32 bit integer in network byte order.
pub fn to_be(self) -> u32 {
unsafe { mem::cast(self.to_bytes()) }
}
/// Compares the address to the current prefix `0.0.0.0/8`.
pub fn is_current(self) -> bool {
self.0 == 0
}
/// Compares the address to t... | {
[self.0, self.1, self.2, self.3]
} | identifier_body |
ipv4.rs | .0/.
use base::prelude::*;
use core::{mem};
use base::{error};
use cty::{
AF_INET, sa_family_t, c_int, sockaddr_in, in_addr,
};
use addr::{SockAddr};
use fmt::{Debug, Write};
/// The size of an Ipv4 socket address.
pub const IPV4_SOCK_ADDR_SIZE: usize = 16; // == size_of::<sockaddr_in>()
... |
let mut family: sa_family_t = 0;
mem::copy(family.as_mut(), bytes);
match family as c_int {
AF_INET => Ok(IPV4_SOCK_ADDR_SIZE),
_ => Err(error::InvalidArgument),
}
}
/// An Ipv4 address.
#[derive(Pod, Eq)]
pub struct Ipv4Addr(pub u8, pub u8, pub u8, pub u8);
impl Ipv4Addr {
/// Cr... | {
return Err(error::InvalidArgument);
} | conditional_block |
controller.d.ts | /// <reference types="node" />
import * as cp from 'child_process';
import * as data from './data';
import { TSEventEmitter } from './events';
import * as GameJolt from './gamejolt';
export declare function getExecutable(): string;
export declare type Events = {
'fatal': (err: Error) => void;
'err': (err: Error... | static launchNew(args: string[], options?: LaunchOptions): Promise<Controller>;
readonly connected: boolean;
connect(): Promise<void>;
disconnect(): Promise<void>;
dispose(): Promise<void>;
private consumeSendQueue;
private send;
private sendControl;
sendKillGame(timeout?: number): P... | private nextMessageId;
private newJsonStream;
static ensureMigrationFile(localPackage: GameJolt.IGamePackage): Promise<void>; | random_line_split |
controller.d.ts | /// <reference types="node" />
import * as cp from 'child_process';
import * as data from './data';
import { TSEventEmitter } from './events';
import * as GameJolt from './gamejolt';
export declare function getExecutable(): string;
export declare type Events = {
'fatal': (err: Error) => void;
'err': (err: Error... | extends TSEventEmitter<Events> {
readonly port: number;
private process;
private reconnector;
private connectionLock;
private conn;
private _nextMessageId;
private sequentialMessageId;
private sendQueue;
private sentMessage;
private consumingQueue;
private expectingQueuePaus... | Controller | identifier_name |
data.rs | }
}
/// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
///
/// We use an Arc so that sharing these styles via the style sharing cache does
/// not require duplicate allocations. We leverage the copy-on-write semantics of
/// Arc::make_mut(), which is free (i.e. does not require atomic RMU ... | /// structs via rule node identity. The former gives us stronger transitive
/// guarantees that allows us to apply the style sharing cache to cousins.
const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 3; | random_line_split | |
data.rs | substitute the rule node instead.
impl fmt::Debug for ElementStyles {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
self.primary.as_ref().map(|x| &x.rules), self.pseudos)
}
}
/// Style system data associated with an ... | {
self.flags.remove(ElementDataFlags::ANCESTOR_WAS_RECONSTRUCTED);
} | conditional_block | |
data.rs | {
/// We need to run selector matching plus re-cascade, that is, a full
/// restyle.
MatchAndCascade,
/// We need to recascade with some replacement rule, such as the style
/// attribute, or animation rules.
CascadeWithReplacements(RestyleHint),
/// We only need to recascade, for example, b... | {
self.is_restyle() || !self.hint.is_empty() || !self.damage.is_empty()
} | identifier_body | |
data.rs | , and later siblings,
/// based on the snapshot of the element that we took when attributes or
/// state changed.
pub fn invalidate_style_if_needed<'a, E: TElement>(
&mut self,
element: E,
shared_context: &SharedStyleContext,
stack_limit_checker: Option<&StackLimitChecker>,
... | skip_applying_damage | identifier_name | |
lib.rs | //! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display... |
&None => None
}
}
fn collect_anchor_lines(tangled: Tangled,
anchors: &mut BTreeMap<String, Anchor>,
lines: &mut Vec<String>,
indentation: usize,
options: &OutputOptions)
{
use std::iter;
let indent_prefix = iter... | {
let header = format!(
"{} '{}', line {}",
comment_prefix,
&block.file,
block.lineno
);
Some(header)
} | conditional_block |
lib.rs | //! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display... | loop {
let next_anchor = process_block_lines(&mut lines, &mut block, &mut errors);
if !block.lines.is_empty() {
tangled_section.push_back(Either::Left(block));
}
match next_anchor {
Some((lineno, indentation, anchor)) => {
macro_rules! has_anchor {
($a... | random_line_split | |
lib.rs | //! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display... | {
indentation: usize, // The *absolute* level of indentation.
tangled: Tangled
}
impl Anchor {
fn new(indentation: usize) -> Self {
Anchor {
indentation: indentation,
tangled: List::new()
}
}
}
/// An `Either` represents the situation when *either* arm is a valid
/// value, as opposed to... | Anchor | identifier_name |
lib.rs | //! kaiseki -- literate programming preprocessing
#[macro_use] extern crate error_chain;
extern crate regex;
pub mod input;
pub mod list;
mod parsing;
pub mod processing_errors {
error_chain! {
errors {
NotUTF8(file: String, lineno: usize) {
description("line is not valid UTF-8")
display... |
fn collect_anchor_lines(tangled: Tangled,
anchors: &mut BTreeMap<String, Anchor>,
lines: &mut Vec<String>,
indentation: usize,
options: &OutputOptions)
{
use std::iter;
let indent_prefix = iter::repeat(' ').take(inden... | {
match &options.comment {
&Some(ref comment_prefix) => {
let header = format!(
"{} '{}', line {}",
comment_prefix,
&block.file,
block.lineno
);
Some(header)
}
&None => None
}
} | identifier_body |
sample_oscillator.js | import {Sample} from './sample'
import {context} from './init_audio'
let instanceIndex = 0
export class SampleOscillator extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
... | ,
}
}else{
// @TODO add type 'custom' => PeriodicWave
let type = this.sampleData.type
this.source = context.createOscillator()
switch(type){
case 'sine':
case 'square':
case 'sawtooth':
case 'triangle':
this.source.type = type
brea... | {} | identifier_body |
sample_oscillator.js | import {Sample} from './sample'
import {context} from './init_audio'
let instanceIndex = 0
export class SampleOscillator extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
... |
this.output = context.createGain()
this.volume = event.data2 / 127
this.output.gain.value = this.volume
this.source.connect(this.output)
//this.output.connect(context.destination)
}
}
| {
// @TODO add type 'custom' => PeriodicWave
let type = this.sampleData.type
this.source = context.createOscillator()
switch(type){
case 'sine':
case 'square':
case 'sawtooth':
case 'triangle':
this.source.type = type
break
default:
... | conditional_block |
sample_oscillator.js | import {Sample} from './sample'
import {context} from './init_audio'
let instanceIndex = 0
export class | extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
// create dummy source
this.source = {
start(){},
stop(){},
connect(){},
}
... | SampleOscillator | identifier_name |
sample_oscillator.js | import {Sample} from './sample' | let instanceIndex = 0
export class SampleOscillator extends Sample{
constructor(sampleData, event){
super(sampleData, event)
this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}`
if(this.sampleData === -1){
// create dummy source
this.source = {
start(){},
... | import {context} from './init_audio'
| random_line_split |
action_buttons.ts | export class ActionBtnProp {
constructor(_id: string,
_text: string,
_icon: string,
_enabled: boolean,
_hide: boolean,
_ddloptions?: any
) {
this.id = _id;
this.text = _text;
this.icon = _icon;
this.enabled = _enabled;
this.hide = _... | {
constructor(_evt: string,
_$event: any) {
this.evt = _evt;
this.$event = _$event;
}
evt: string
$event: any
}
| Evt | identifier_name |
action_buttons.ts | export class ActionBtnProp {
constructor(_id: string,
_text: string,
_icon: string,
_enabled: boolean,
_hide: boolean,
_ddloptions?: any
) {
this.id = _id;
this.text = _text;
this.icon = _icon;
this.enabled = _enabled;
this.hide = _... |
type: string
details: any
}
export class Evt {
constructor(_evt: string,
_$event: any) {
this.evt = _evt;
this.$event = _$event;
}
evt: string
$event: any
}
| {
this.type = _type;
this.details = _details;
} | identifier_body |
action_buttons.ts | export class ActionBtnProp {
constructor(_id: string,
_text: string,
_icon: string,
_enabled: boolean,
_hide: boolean,
_ddloptions?: any
) {
this.id = _id;
this.text = _text;
this.icon = _icon;
this.enabled = _enabled;
this.hide = _... | icon: string
enabled: boolean
hide: boolean
ddloptions: any
}
export class Details {
constructor(_type: string,
_details: any) {
this.type = _type;
this.details = _details;
}
type: string
details: any
}
export class Evt {
constructor(_evt: string,
... | random_line_split | |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast:... | else {
Ok(Some(CargoTestError::new(test, errors)))
}
}
pub fn run_benches(ws: &Workspace,
options: &TestOptions,
args: &[String]) -> CargoResult<Option<CargoTestError>> {
let mut args = args.to_vec();
args.push("--bench".to_string());
let compilation = com... | {
Ok(None)
} | conditional_block |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast:... | <'a>(ws: &Workspace<'a>,
options: &TestOptions<'a>)
-> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2))
});
... | compile_tests | identifier_name |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast:... | });
Ok(compilation)
}
/// Run the unit and integration tests of a project.
fn run_unit_tests(options: &TestOptions,
test_args: &[String],
compilation: &Compilation)
-> CargoResult<(Test, Vec<ProcessError>)> {
let config = options.compile_opts.config;
... | compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1, &b.2)) | random_line_split |
cargo_test.rs | use std::ffi::{OsString, OsStr};
use ops::{self, Compilation};
use util::{self, CargoTestError, Test, ProcessError};
use util::errors::{CargoResult, CargoErrorKind, CargoError};
use core::Workspace;
pub struct TestOptions<'a> {
pub compile_opts: ops::CompileOptions<'a>,
pub no_run: bool,
pub no_fail_fast:... |
fn compile_tests<'a>(ws: &Workspace<'a>,
options: &TestOptions<'a>)
-> CargoResult<Compilation<'a>> {
let mut compilation = ops::compile(ws, &options.compile_opts)?;
compilation.tests.sort_by(|a, b| {
(a.0.package_id(), &a.1, &a.2).cmp(&(b.0.package_id(), &b.1... | {
let mut args = args.to_vec();
args.push("--bench".to_string());
let compilation = compile_tests(ws, options)?;
if options.no_run {
return Ok(None)
}
let (test, errors) = run_unit_tests(options, &args, &compilation)?;
match errors.len() {
0 => Ok(None),
_ => Ok(Some... | identifier_body |
helpers.py | #-*- coding: utf-8 -*-
from PIL import Image, ImageChops, ImageDraw
from django.contrib.auth.models import User
from filer.models.foldermodels import Folder
from filer.models.clipboardmodels import Clipboard, ClipboardItem
def create_superuser():
superuser = User.objects.create_superuser('admin',
... |
def create_clipboard_item(user, file):
clipboard, was_clipboard_created = Clipboard.objects.get_or_create(user=user)
clipboard_item = ClipboardItem(clipboard=clipboard, file=file)
return clipboard_item
def create_image(mode='RGB', size=(800, 600)):
image = Image.new(mo... | for s in range(1,sibling+1):
name = "folder: %s -- %s" %(str(d), str(s))
folder = Folder(name=name, parent=parent)
folder.save()
create_folder_structure(depth=d-1, sibling=sibling, parent=folder) | conditional_block |
helpers.py | #-*- coding: utf-8 -*-
from PIL import Image, ImageChops, ImageDraw
from django.contrib.auth.models import User
from filer.models.foldermodels import Folder
from filer.models.clipboardmodels import Clipboard, ClipboardItem
def create_superuser():
superuser = User.objects.create_superuser('admin',
... | for s in range(1,sibling+1):
name = "folder: %s -- %s" %(str(d), str(s))
folder = Folder(name=name, parent=parent)
folder.save()
create_folder_structure(depth=d-1, sibling=sibling, parent=folder)
def create_clipboard_item(user... | if depth > 0 and sibling > 0:
depth_range = range(1, depth+1)
depth_range.reverse()
for d in depth_range: | random_line_split |
helpers.py | #-*- coding: utf-8 -*-
from PIL import Image, ImageChops, ImageDraw
from django.contrib.auth.models import User
from filer.models.foldermodels import Folder
from filer.models.clipboardmodels import Clipboard, ClipboardItem
def create_superuser():
superuser = User.objects.create_superuser('admin',
... | (user, file):
clipboard, was_clipboard_created = Clipboard.objects.get_or_create(user=user)
clipboard_item = ClipboardItem(clipboard=clipboard, file=file)
return clipboard_item
def create_image(mode='RGB', size=(800, 600)):
image = Image.new(mode, size)
draw = ImageDraw.Draw(image)
... | create_clipboard_item | identifier_name |
helpers.py | #-*- coding: utf-8 -*-
from PIL import Image, ImageChops, ImageDraw
from django.contrib.auth.models import User
from filer.models.foldermodels import Folder
from filer.models.clipboardmodels import Clipboard, ClipboardItem
def create_superuser():
|
def create_folder_structure(depth=2, sibling=2, parent=None):
"""
This method creates a folder structure of the specified depth.
* depth: is an integer (default=2)
* sibling: is an integer (default=2)
* parent: is the folder instance of the parent.
"""
if depth > 0 and sibling > 0:
... | superuser = User.objects.create_superuser('admin',
'admin@free.fr',
'secret')
return superuser | identifier_body |
hisat2_index_builder.py | #!/usr/bin/env python
# Based heavily on the Bowtie 2 data manager wrapper script by Dan Blankenberg
from __future__ import print_function
import argparse
import os
import shlex
import subprocess
import sys
from json import dumps, loads
DEFAULT_DATA_TABLE_NAME = "hisat2_indexes"
def get_id_name( params, dbkey, fast... | ( data_manager_dict, options, params, sequence_id, sequence_name ):
data_table_name = options.data_table_name or DEFAULT_DATA_TABLE_NAME
target_directory = params[ 'output_data' ][0]['extra_files_path']
if not os.path.exists( target_directory ):
os.mkdir( target_directory )
fasta_base_name = os.... | build_hisat_index | identifier_name |
hisat2_index_builder.py | #!/usr/bin/env python
# Based heavily on the Bowtie 2 data manager wrapper script by Dan Blankenberg
from __future__ import print_function
import argparse
import os
import shlex
import subprocess
import sys
from json import dumps, loads
DEFAULT_DATA_TABLE_NAME = "hisat2_indexes"
def get_id_name( params, dbkey, fast... |
return sequence_id, sequence_name
def build_hisat_index( data_manager_dict, options, params, sequence_id, sequence_name ):
data_table_name = options.data_table_name or DEFAULT_DATA_TABLE_NAME
target_directory = params[ 'output_data' ][0]['extra_files_path']
if not os.path.exists( target_directory ):
... | sequence_name = fasta_description
if not sequence_name:
sequence_name = dbkey | conditional_block |
hisat2_index_builder.py | #!/usr/bin/env python
# Based heavily on the Bowtie 2 data manager wrapper script by Dan Blankenberg
from __future__ import print_function
import argparse
import os
import shlex
import subprocess
import sys
from json import dumps, loads
DEFAULT_DATA_TABLE_NAME = "hisat2_indexes"
def get_id_name( params, dbkey, fast... |
def _add_data_table_entry( data_manager_dict, data_table_name, data_table_entry ):
data_manager_dict['data_tables'] = data_manager_dict.get( 'data_tables', {} )
data_manager_dict['data_tables'][ data_table_name ] = data_manager_dict['data_tables'].get( data_table_name, [] )
data_manager_dict['data_tables... | data_table_name = options.data_table_name or DEFAULT_DATA_TABLE_NAME
target_directory = params[ 'output_data' ][0]['extra_files_path']
if not os.path.exists( target_directory ):
os.mkdir( target_directory )
fasta_base_name = os.path.split( options.fasta_filename )[-1]
sym_linked_fasta_filename =... | identifier_body |
hisat2_index_builder.py | #!/usr/bin/env python
# Based heavily on the Bowtie 2 data manager wrapper script by Dan Blankenberg
from __future__ import print_function
import argparse
import os
import shlex
import subprocess
import sys
from json import dumps, loads
DEFAULT_DATA_TABLE_NAME = "hisat2_indexes"
def get_id_name( params, dbkey, fast... | if not sequence_name:
sequence_name = dbkey
return sequence_id, sequence_name
def build_hisat_index( data_manager_dict, options, params, sequence_id, sequence_name ):
data_table_name = options.data_table_name or DEFAULT_DATA_TABLE_NAME
target_directory = params[ 'output_data' ][0]['ext... | sequence_name = params['param_dict']['sequence_name']
if not sequence_name:
sequence_name = fasta_description | random_line_split |
SecretFormField.tsx | import omit from 'lodash/omit';
import React, { InputHTMLAttributes, FunctionComponent } from 'react';
import { FormField } from '../FormField/FormField';
import { Button } from '../Button/Button';
import { css, cx } from 'emotion';
export interface Props extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onReset'> ... | {...inputProps}
/>
)
}
/>
);
};
SecretFormField.displayName = 'SecretFormField'; | ) : (
<input
type="password"
className={`gf-form-input width-${inputWidth}`}
placeholder={placeholder} | random_line_split |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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 ap... | export = hasOwnProp; | // EXPORTS //
| random_line_split |
runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"pinax.pinax_hello",
"pinax.pinax_hello.tests"
],
MIDD... | runtests(*sys.argv[1:]) | conditional_block | |
runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"pinax.pinax_hello",
"pinax.pinax_hello.tests"
],
MIDD... | (*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
test_args... | runtests | identifier_name |
runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"pinax.pinax_hello",
"pinax.pinax_hello.tests"
],
MIDD... |
if __name__ == "__main__":
runtests(*sys.argv[1:])
| if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try:
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
test_args = ["pinax.pinax_h... | identifier_body |
runtests.py | #!/usr/bin/env python
import os
import sys
import django
from django.conf import settings
DEFAULT_SETTINGS = dict(
INSTALLED_APPS=[
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sites",
"pinax.pinax_hello",
"pinax.pinax_hello.tests" | MIDDLEWARE_CLASSES=[],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
},
SITE_ID=1,
ROOT_URLCONF="pinax.pinax_hello.tests.urls",
SECRET_KEY="notasecret",
)
def runtests(*test_args):
if not settings.configured:
... | ], | random_line_split |
tests.rs | pub use datatypes::{GridSettings, Region, ResizeRule, SplitKind, SaveGrid};
pub use datatypes::ResizeRule::*;
pub use datatypes::SplitKind::*;
pub use terminal::interfaces::{Resizeable, ConstructGrid};
pub use super::panel::Panel;
pub use super::panel::Panel::*;
pub use super::ring::Ring;
pub use super::section::Screen... | (self.0, self.1)
}
fn resize_width(&mut self, width: u32) {
self.0 = width;
}
fn resize_height(&mut self, height: u32) {
self.1 = height;
}
}
impl ConstructGrid for MockFill {
fn new(settings: GridSettings) -> MockFill {
MockFill(settings.width, settings.height... | #[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct MockFill(pub u32, pub u32);
impl Resizeable for MockFill {
fn dims(&self) -> (u32, u32) { | random_line_split |
tests.rs | pub use datatypes::{GridSettings, Region, ResizeRule, SplitKind, SaveGrid};
pub use datatypes::ResizeRule::*;
pub use datatypes::SplitKind::*;
pub use terminal::interfaces::{Resizeable, ConstructGrid};
pub use super::panel::Panel;
pub use super::panel::Panel::*;
pub use super::ring::Ring;
pub use super::section::Screen... |
}
impl ConstructGrid for MockFill {
fn new(settings: GridSettings) -> MockFill {
MockFill(settings.width, settings.height)
}
}
pub const GRID: MockFill = MockFill(8, 8);
pub const OLD_AREA: Region = Region { left: 0, top: 2, right: 8, bottom: 10 };
pub const NEW_AREA: Region = Region { left: 1, top: ... | {
self.1 = height;
} | identifier_body |
tests.rs | pub use datatypes::{GridSettings, Region, ResizeRule, SplitKind, SaveGrid};
pub use datatypes::ResizeRule::*;
pub use datatypes::SplitKind::*;
pub use terminal::interfaces::{Resizeable, ConstructGrid};
pub use super::panel::Panel;
pub use super::panel::Panel::*;
pub use super::ring::Ring;
pub use super::section::Screen... | (&self) -> (u32, u32) {
(self.0, self.1)
}
fn resize_width(&mut self, width: u32) {
self.0 = width;
}
fn resize_height(&mut self, height: u32) {
self.1 = height;
}
}
impl ConstructGrid for MockFill {
fn new(settings: GridSettings) -> MockFill {
MockFill(setting... | dims | identifier_name |
jjv-tests.ts |
// Register a `user` schema
env.addSchema('user', {
type: 'object',
properties: {
firstname: {
type: 'string',
minLength: 2,
maxLength: 15,
},
lastname: {
type: 'string',
minLength: 2,
maxLength: 25,
},
gender: {
type: 'string',
enum: ['male', 'female'],
},
email: {
type: 'st... | import jjv = require('jjv');
// create new JJV environment
var env = jjv();
var errors: jjv.Errors; | random_line_split | |
jjv-tests.ts |
import jjv = require('jjv');
// create new JJV environment
var env = jjv();
var errors: jjv.Errors;
// Register a `user` schema
env.addSchema('user', {
type: 'object',
properties: {
firstname: {
type: 'string',
minLength: 2,
maxLength: 15,
},
lastname: {
type: 'string',
minLength: 2,
maxLen... |
env.defaultOptions.checkRequired = false;
env.validate('schemaName', {}, { checkRequired: false });
env.addType('date', (v: any) => !isNaN(Date.parse(v)));
env.addFormat('hexadecimal', (v: any) => (/^[a-fA-F0-9]+$/).test(v));
env.addCheck('exactLength', (v: any, p: any) => v.length === p);
env.addTypeCoercion('i... | {
console.log('y is required');
} | conditional_block |
function.py | ]
# up to here.
if options.get('evaluate') is False:
return Basic.__new__(cls, *args, **options)
r = cls.eval(*args)
if isinstance(r, Basic):
return r
elif r is None:
# Just undefined functions have nargs == None
if not cls.nargs an... | (Function, Atom):
"""
WildFunction() matches any expression but another WildFunction()
XXX is this as intended, does it work ?
"""
nargs = 1
def __new__(cls, name=None, **assumptions):
if name is None:
name = 'Wf%s' % (Symbol.dummycount + 1) # XXX refactor dummy counting
... | WildFunction | identifier_name |
function.py | name
return obj
def matches(pattern, expr, repl_dict={}, evaluate=False):
for p,v in repl_dict.items():
if p==pattern:
if v==expr: return repl_dict
return None
if pattern.nargs is not None:
if pattern.nargs != expr.nargs:
... |
#replace arguments
expression = self.args[self.nargs] | random_line_split | |
function.py | ]
# up to here.
if options.get('evaluate') is False:
return Basic.__new__(cls, *args, **options)
r = cls.eval(*args)
if isinstance(r, Basic):
return r
elif r is None:
# Just undefined functions have nargs == None
if not cls.nargs an... |
return r
return
def _eval_derivative(self, s):
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
i = 0
l = []
r = S.Zero
for a in self.args:
i += 1
da = a.diff(s)
if da is S.Zero:
continue
if isin... | c = s.is_comparable
if c is None: return
if not c: r = False | conditional_block |
function.py | ]
# up to here.
if options.get('evaluate') is False:
return Basic.__new__(cls, *args, **options)
r = cls.eval(*args)
if isinstance(r, Basic):
return r
elif r is None:
# Just undefined functions have nargs == None
if not cls.nargs an... |
def _eval_derivative(self, s):
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
i = 0
l = []
r = S.Zero
for a in self.args:
i += 1
da = a.diff(s)
if da is S.Zero:
continue
if isinstance(self.func, FunctionClass):
... | if self.is_Function:
r = True
for s in self.args:
c = s.is_comparable
if c is None: return
if not c: r = False
return r
return | identifier_body |
createMoqInjector.ts | import { InjectionToken, Injector, StaticProvider, Type } from "@angular/core";
import { IMock, Mock, MoqAPI } from "moq.ts";
import { IOptions, IParameter, moqInjectorProviders } from "ng-auto-moq";
import { InjectionFactory, TypeOfInjectionFactory } from "../L0/L0.injection-factory/injection-factory";
export let inj... | <T, R = T extends InjectionFactory ? TypeOfInjectionFactory<T> : T>
(token: Type<T> | InjectionToken<T>): IMock<R> {
const object = injector.get(token) as unknown;
return object[MoqAPI];
}
export function resolve<T,
R = T extends InjectionFactory ? TypeOfInjectionFactory<T> : T>(token: Type<T> | InjectionT... | resolveMock | identifier_name |
createMoqInjector.ts | import { InjectionToken, Injector, StaticProvider, Type } from "@angular/core";
import { IMock, Mock, MoqAPI } from "moq.ts";
import { IOptions, IParameter, moqInjectorProviders } from "ng-auto-moq";
import { InjectionFactory, TypeOfInjectionFactory } from "../L0/L0.injection-factory/injection-factory";
export let inj... |
return new Mock<any>({name: displayName});
}
| {
const target = () => undefined;
return new Mock<any>({name: displayName, target})
.prototypeof(token.prototype);
} | conditional_block |
createMoqInjector.ts | import { InjectionToken, Injector, StaticProvider, Type } from "@angular/core";
import { IMock, Mock, MoqAPI } from "moq.ts";
import { IOptions, IParameter, moqInjectorProviders } from "ng-auto-moq";
import { InjectionFactory, TypeOfInjectionFactory } from "../L0/L0.injection-factory/injection-factory";
export let inj... | }
return new Mock<any>({name: displayName});
} | random_line_split | |
createMoqInjector.ts | import { InjectionToken, Injector, StaticProvider, Type } from "@angular/core";
import { IMock, Mock, MoqAPI } from "moq.ts";
import { IOptions, IParameter, moqInjectorProviders } from "ng-auto-moq";
import { InjectionFactory, TypeOfInjectionFactory } from "../L0/L0.injection-factory/injection-factory";
export let inj... |
function mockFactory({token, displayName}: IParameter) {
if (typeof token === "function") {
const target = () => undefined;
return new Mock<any>({name: displayName, target})
.prototypeof(token.prototype);
}
return new Mock<any>({name: displayName});
}
| {
return injector.get(token) as any;
} | identifier_body |
register.ts | import SimpleSchema from 'simpl-schema';
import { filterDOMProps } from 'uniforms';
// Register custom property.
SimpleSchema.extendOptions(['uniforms']);
// There's no possibility to retrieve them at runtime.
declare module 'uniforms' {
interface FilterDOMProps {
autoValue: never;
blackbox: never;
cust... | regEx: never;
trim: never;
type: never;
}
}
filterDOMProps.register(
'autoValue',
'blackbox',
'custom',
'decimal',
'defaultValue',
'exclusiveMax',
'exclusiveMin',
'max',
'maxCount',
'min',
'minCount',
'optional',
'regEx',
'trim',
'type',
); | min: never;
minCount: never;
optional: never; | random_line_split |
msgsend-pipes.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 ... | {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
vec!("".to_string(), "1000000".to_string(), "8".to_string())
} else if args.len() <= 1u {
vec!("".to_string(), "10000".to_string(), "4".to_string())
} else {
args.clone().into_iter().map(|x| x.to_string()... | identifier_body | |
msgsend-pipes.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 ... |
Ok(request::bytes(b)) => {
//println!("server: received {} bytes", b);
count += b;
}
Err(..) => { done = true; }
_ => { }
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[String]) {
let (to_parent, from_ch... | { responses.send(count.clone()); } | conditional_block |
msgsend-pipes.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: T) {}
enum request {
get_count,
bytes(uint),
stop
}
fn server(requests: &Receiver<request>, responses: &Sender<uint>) {
let mut count: uint = 0;
let mut done = false;
while !done {
match requests.recv_opt() {
Ok(request::get_count) => { responses.send(count.clone()); ... | move_out | identifier_name |
msgsend-pipes.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 ... | _ => { }
}
}
responses.send(count);
//println!("server exiting");
}
fn run(args: &[String]) {
let (to_parent, from_child) = channel();
let size = from_str::<uint>(args[1].as_slice()).unwrap();
let workers = from_str::<uint>(args[2].as_slice()).unwrap();
let num_bytes = 10... | count += b;
}
Err(..) => { done = true; } | random_line_split |
binary_spots.py | #!/usr/bin/env python
# coding: utf-8
# Binary with Spots
# ============================
#
# Setup
# -----------------------------
# Let's first make sure we have the latest version of PHOEBE 2.2 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the lates... |
# Let's add a spot to the primary component in our binary.
#
# The 'colat' parameter defines the colatitude on the star measured from its North (spin) Pole. The 'long' parameter measures the longitude of the spot - with longitude = 0 being defined as pointing towards the other star at t0. See the [spots tutorial](.... | b.run_compute(irrad_method='none', model='no_spot')
# Adding Spots
# --------------------- | random_line_split |
messages.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.u... |
def _notify(contact, txt, subject=None):
from frappe.utils import get_fullname, get_url
try:
if not isinstance(contact, list):
contact = [frappe.db.get_value("User", contact, "email") or contact]
frappe.sendmail(\
recipients=contact,
sender= frappe.db.get_value("User", frappe.session.user, "email"),
... | frappe.get_doc("Communication", frappe.form_dict['name']).delete() | identifier_body |
messages.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.u... |
return data
@frappe.whitelist()
def post(txt, contact, parenttype=None, notify=False, subject=None):
"""post message"""
d = frappe.new_doc('Communication')
d.communication_type = 'Notification' if parenttype else 'Chat'
d.subject = subject
d.content = txt
d.reference_doctype = 'User'
d.reference_name = cont... | data.append({"name": frappe.session.user, "has_session": 100}) | conditional_block |
messages.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.u... | ():
data = frappe.db.sql("""select name,
(select count(*) from tabSessions where user=tabUser.name
and timediff(now(), lastupdate) < time("01:00:00")) as has_session
from tabUser
where enabled=1 and
ifnull(user_type, '')!='Website User' and
name not in ({})
order by first_name""".format(", ".join(["%s"... | get_active_users | identifier_name |
messages.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.notifications import delete_notification_count_for
from frappe.core.doctype.user.user import STANDARD_USERS
from frappe.utils.u... | recipients=contact,
sender= frappe.db.get_value("User", frappe.session.user, "email"),
subject=subject or "New Message from " + get_fullname(frappe.session.user),
message=frappe.get_template("templates/emails/new_message.html").render({
"from": get_fullname(frappe.session.user),
"message": txt,
... | try:
if not isinstance(contact, list):
contact = [frappe.db.get_value("User", contact, "email") or contact]
frappe.sendmail(\ | random_line_split |
ifreturn.js | /*
* Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
* Circulation and User's Management. It's written in Perl, and uses Apache2
* Web-Server, MySQL database and Sphinx 2 indexing.
* Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
*
* This file is part of Meran. | * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Meran is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Pub... | *
* Meran is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by | random_line_split |
ifreturn.js | /*
* Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
* Circulation and User's Management. It's written in Perl, and uses Apache2
* Web-Server, MySQL database and Sphinx 2 indexing.
* Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
*
* This file is part of Meran.
*
... | {return a==1?2:17} | identifier_body | |
ifreturn.js | /*
* Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
* Circulation and User's Management. It's written in Perl, and uses Apache2
* Web-Server, MySQL database and Sphinx 2 indexing.
* Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
*
* This file is part of Meran.
*
... | (a){return a==1?2:17} | a | identifier_name |
union-borrow-move-parent-sibling.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 ... | unsafe fn parent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut u.x.0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn parent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = u.x.0;
let b =... | fn use_borrow<T>(_: &T) {}
| random_line_split |
union-borrow-move-parent-sibling.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 ... |
unsafe fn grandparent_sibling_borrow() {
let mut u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = &mut (u.x.0).0;
let b = &u.y; //~ ERROR cannot borrow `u.y`
use_borrow(a);
}
unsafe fn grandparent_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = (u... | {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = u.x.0;
let b = u.y; //~ ERROR use of moved value: `u.y`
} | identifier_body |
union-borrow-move-parent-sibling.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 ... | () {
let mut u = U { y: Box::default() };
let a = &mut *u.y;
let b = &u.x; //~ ERROR cannot borrow `u` (via `u.x`)
use_borrow(a);
}
unsafe fn deref_sibling_move() {
let u = U { x: ((Vec::new(), Vec::new()), Vec::new()) };
let a = *u.y;
let b = u.x; //~ ERROR use of moved value: `u.x`
}
fn... | deref_sibling_borrow | identifier_name |
Routing.tsx | import * as React from 'react'
import {Router, Route, browserHistory, IndexRoute} from 'react-router'
import {syncHistoryWithStore} from 'react-router-redux'
import {InlineStyles} from '../Containers/InlineStyles'
import {WelcomePage} from '../Containers/WelcomePage'
import {NoMatch} from '../Containers/NoMatch'
import... | () {
return (
<div>
{this.routerConfig}
</div>
)
}
}
| render | identifier_name |
Routing.tsx | import * as React from 'react'
import {Router, Route, browserHistory, IndexRoute} from 'react-router'
import {syncHistoryWithStore} from 'react-router-redux'
import {InlineStyles} from '../Containers/InlineStyles'
import {WelcomePage} from '../Containers/WelcomePage'
import {NoMatch} from '../Containers/NoMatch'
import... |
authorizeOnEnter(nextState, replace): void {
if (store.getState().LoginReducer.user.login === '') {
alert('You must be logged!')
replace('/login')
}
}
render() {
return (
<div>
{this.routerConfig}
</div>
)
... | {
super();
this.history = syncHistoryWithStore(browserHistory, store)
this.authorizeOnEnter = this.authorizeOnEnter.bind(this)
this.routerConfig = (
<Router history={this.history}>
<Route path="/" component={App}>
<IndexRoute component={W... | identifier_body |
Routing.tsx | import * as React from 'react'
import {Router, Route, browserHistory, IndexRoute} from 'react-router'
import {syncHistoryWithStore} from 'react-router-redux'
import {InlineStyles} from '../Containers/InlineStyles'
import {WelcomePage} from '../Containers/WelcomePage'
import {NoMatch} from '../Containers/NoMatch'
import... |
}
render() {
return (
<div>
{this.routerConfig}
</div>
)
}
}
| {
alert('You must be logged!')
replace('/login')
} | conditional_block |
Routing.tsx | import * as React from 'react'
import {Router, Route, browserHistory, IndexRoute} from 'react-router'
import {syncHistoryWithStore} from 'react-router-redux'
import {InlineStyles} from '../Containers/InlineStyles'
import {WelcomePage} from '../Containers/WelcomePage'
import {NoMatch} from '../Containers/NoMatch'
import... | <IndexRoute component={WelcomePage}/>
<Route path="/login" component={Login}/>
<Route path="/style" component={InlineStyles}/>
<Route path="/chat" component={Chat} onEnter={this.authorizeOnEnter}/>
<Route path="*" compon... | <Router history={this.history}>
<Route path="/" component={App}> | random_line_split |
fields.ts | import { FieldState } from "../model";
import { AllActions } from "../actions";
import { satisfies } from "../util";
/**
* fields member reducer - handles actions and state related to field management
*/
export function fields(state: FieldState | undefined, action: AllActions): FieldState {
if (!state) {
... | case "REMOVE_FIELDS_BY_ID": {
return action.payload.fields.reduce((prev, id) => {
if (!prev[id]) {
throw new Error("Attempted to remove field which did not exist in the state!");
}
delete prev[id];
return prev;
... | ).reduce((prev, f) => {
prev[f.id] = f;
return prev;
}, {} as FieldState);
} | random_line_split |
fields.ts | import { FieldState } from "../model";
import { AllActions } from "../actions";
import { satisfies } from "../util";
/**
* fields member reducer - handles actions and state related to field management
*/
export function fields(state: FieldState | undefined, action: AllActions): FieldState | item => satisfies(Object.keys(state).map(k => state[+k]),
field => item.name === field.name && item.table === field.table && item.dataSource === field.dataSource
)
);
if (validFields.length !== action.payload.fields.length) throw new Error("Fi... | {
if (!state) {
return {};
}
if (action.error) {
throw action.error;
}
switch (action.type) {
case "ADD_FIELDS": {
return action.payload.fields.reduce((prev, f) => {
if (prev[f.id]) {
throw new Error("Attempted to add field whic... | identifier_body |
fields.ts | import { FieldState } from "../model";
import { AllActions } from "../actions";
import { satisfies } from "../util";
/**
* fields member reducer - handles actions and state related to field management
*/
export function fields(state: FieldState | undefined, action: AllActions): FieldState {
if (!state) |
if (action.error) {
throw action.error;
}
switch (action.type) {
case "ADD_FIELDS": {
return action.payload.fields.reduce((prev, f) => {
if (prev[f.id]) {
throw new Error("Attempted to add field which already existed in the state!");
... | {
return {};
} | conditional_block |
fields.ts | import { FieldState } from "../model";
import { AllActions } from "../actions";
import { satisfies } from "../util";
/**
* fields member reducer - handles actions and state related to field management
*/
export function | (state: FieldState | undefined, action: AllActions): FieldState {
if (!state) {
return {};
}
if (action.error) {
throw action.error;
}
switch (action.type) {
case "ADD_FIELDS": {
return action.payload.fields.reduce((prev, f) => {
if (prev[f.id]) {
... | fields | identifier_name |
send_receive.rs | #![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn | () {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } else { 0 };
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } ... | main | identifier_name |
send_receive.rs | #![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn main() {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } ... | ;
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } else { size - 1 };
let previous_process = world.process_at_rank(previous_rank);
let (msg, status): (Rank, _) = p2p::send_receive(&rank, &previous_process, &next_process);
println!("Process {} go... | { 0 } | conditional_block |
send_receive.rs | #![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn main() {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } ... |
let x = status.source_rank();
let v = vec![x, x + 1, x - 1];
assert_eq!(v, msg);
}
}
world.barrier();
let mut x = rank;
p2p::send_receive_replace_into(&mut x, &next_process, &previous_process);
assert_eq!(x, previous_rank);
} | let (msg, status) = world.any_process().receive_vec::<Rank>();
println!("Process {} got long message {:?}.\nStatus is: {:?}", rank, msg, status); | random_line_split |
send_receive.rs | #![deny(warnings)]
extern crate mpi;
use mpi::traits::*;
use mpi::point_to_point as p2p;
use mpi::topology::Rank;
fn main() | for _ in 1..size {
let (msg, status) = world.any_process().receive_vec::<Rank>();
println!("Process {} got long message {:?}.\nStatus is: {:?}", rank, msg, status);
let x = status.source_rank();
let v = vec![x, x + 1, x - 1];
assert_eq!(v, msg);
... | {
let universe = mpi::initialize().unwrap();
let world = universe.world();
let size = world.size();
let rank = world.rank();
let next_rank = if rank + 1 < size { rank + 1 } else { 0 };
let next_process = world.process_at_rank(next_rank);
let previous_rank = if rank - 1 >= 0 { rank - 1 } els... | identifier_body |
fs.ts | import path from "path";
import fs from "fs";
import { ResolverSource } from "../source";
export class FS implements ResolverSource {
workingDirectory: string;
contractsBuildDirectory: string;
constructor(workingDirectory: string, contractsBuildDirectory: string) {
this.workingDirectory = workingDirectory;... | }
}
return { body, filePath };
}
// Here we're resolving from local files to local files, all absolute.
resolveDependencyPath(importPath: string, dependencyPath: string) {
if (
!(dependencyPath.startsWith("./") || dependencyPath.startsWith("../"))
) {
//if it's *not* a relative... | } catch (error) {
// do nothing | random_line_split |
fs.ts | import path from "path";
import fs from "fs";
import { ResolverSource } from "../source";
export class FS implements ResolverSource {
workingDirectory: string;
contractsBuildDirectory: string;
constructor(workingDirectory: string, contractsBuildDirectory: string) {
this.workingDirectory = workingDirectory;... |
}
try {
const result = fs.readFileSync(
path.join(searchPath, `${contractName}.json`),
"utf8"
);
return JSON.parse(result);
} catch (e) {
return null;
}
}
getContractName(
sourcePath: string,
searchPath = this.contractsBuildDirectory
) {
const... | {
return null;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.