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 |
|---|---|---|---|---|
borrowck-loan-rcvr-overloaded-op.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 ... | // Here I create an outstanding loan and check that we get conflicts:
let q = &mut p;
p + 3; //~ ERROR cannot use `p`
p.times(3); //~ ERROR cannot borrow `p`
*q + 3; // OK to use the new alias `q`
q.x += 1; // and OK to mutate it
}
fn main() {
} | fn b() {
let mut p = Point {x: 3, y: 4};
| random_line_split |
borrowck-loan-rcvr-overloaded-op.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 ... |
fn b() {
let mut p = Point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let q = &mut p;
p + 3; //~ ERROR cannot use `p`
p.times(3); //~ ERROR cannot borrow `p`
*q + 3; // OK to use the new alias `q`
q.x += 1; // and OK to mutate it
}
fn main() {... | {
let mut p = Point {x: 3, y: 4};
// ok (we can loan out rcvr)
p + 3;
p.times(3);
} | identifier_body |
gpu_test_expectations.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlio... | (self, url_pattern, conditions=None, bug=None, max_num_retries=2):
expectation = _FlakyExpectation(self.CreateExpectation(
'pass', url_pattern, conditions, bug), max_num_retries)
self._flaky_expectations.append(expectation)
def GetFlakyRetriesForPage(self, page, browser):
for fe in self._flaky_expe... | Flaky | identifier_name |
gpu_test_expectations.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlio... | # Add support for browser-type-specific expectations.
if condition in BROWSER_TYPE_MODIFIERS:
return True
return super(GpuTestExpectations,
self).IsValidUserDefinedCondition(condition)
def ModifiersApply(self, browser, expectation):
if not super(GpuTestExpectations, self).ModifiersApply... | def __init__(self):
self._flaky_expectations = []
super(GpuTestExpectations, self).__init__()
def Flaky(self, url_pattern, conditions=None, bug=None, max_num_retries=2):
expectation = _FlakyExpectation(self.CreateExpectation(
'pass', url_pattern, conditions, bug), max_num_retries)
self._flaky_e... | identifier_body |
gpu_test_expectations.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlio... |
# We'll only get here if the OS and GPU matched the expectation.
# TODO(kbr): refactor _Expectation to be a public class so that
# the GPU-specific properties can be moved into a subclass, and
# run the unit tests from this directory on the CQ and the bots.
# crbug.com/495868 crbug.com/495870
... | return False | conditional_block |
gpu_test_expectations.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlio... | def __init__(self, expectation, max_num_retries):
self.expectation = expectation
self.max_num_retries = max_num_retries
class GpuTestExpectations(test_expectations.TestExpectations):
def __init__(self):
self._flaky_expectations = []
super(GpuTestExpectations, self).__init__()
def Flaky(self, url... | 'android-webview-shell', 'android-content-shell', 'debug' ]
class _FlakyExpectation(object): | random_line_split |
rs_enum.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import gettext
from enum import Enum, unique
_ = gettext.gettext
strategy_descriptions = [_("New resourcelist strategy"),
_("New changelist strategy"),
_("Incremental changelist strategy")]
@unique
class Strategy(Enum... |
elif isinstance(value, int):
return Strategy(value)
else:
return Strategy[value]
except KeyError as err:
raise ValueError(err)
def describe(self):
return strategy_descriptions[self.value]
class Capability(Enum):
"""
:sam... | return value | conditional_block |
rs_enum.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import gettext
from enum import Enum, unique
_ = gettext.gettext
strategy_descriptions = [_("New resourcelist strategy"),
_("New changelist strategy"),
_("Incremental changelist strategy")]
@unique
class | (Enum):
"""
:samp:`Strategy for ResourceSync Publishing`
"""
resourcelist = 0
"""
``0`` :samp:`New resourcelist {strategy}`
Create new resourcelist(s) every run.
"""
new_changelist = 1
"""
``1`` :samp:`New changelist {strategy}`
Create a new changelist every run.
I... | Strategy | identifier_name |
rs_enum.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import gettext
from enum import Enum, unique
_ = gettext.gettext
strategy_descriptions = [_("New resourcelist strategy"),
_("New changelist strategy"),
_("Incremental changelist strategy")]
@unique
class Strategy(Enum... |
@staticmethod
def select_mode_for(mode):
try:
if isinstance(mode, SelectMode):
return mode
elif isinstance(mode, int):
return SelectMode(mode)
else:
return SelectMode[mode]
except KeyError as err:
r... | """
:samp:`Get SelectMode names`
:return: List<str> of names
"""
names = dir(SelectMode)
return [x for x in names if not x.startswith("_")] | identifier_body |
rs_enum.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import gettext
from enum import Enum, unique
_ = gettext.gettext
strategy_descriptions = [_("New resourcelist strategy"),
_("New changelist strategy"),
_("Incremental changelist strategy")]
@unique
class Strategy(Enum... | return Strategy[value]
except KeyError as err:
raise ValueError(err)
def describe(self):
return strategy_descriptions[self.value]
class Capability(Enum):
"""
:samp:`Capabilities as defined in the ResourceSync Framework`
"""
resourcelist = 0
"""
... | return value
elif isinstance(value, int):
return Strategy(value)
else: | random_line_split |
quicklinks.spec.js | import { mount } from '@cypress/vue';
import Vuex from 'vuex';
import quicklinks from '../../../vuex/store/quicklinks';
import Quicklinks from './quicklinks.vue';
describe('<Quicklinks />', () => {
it('Verify adding/removing links works', () => {
// Load data from a fixture ('another name for mock data, all fi... | });
// Mount the Notices component with store instance and the localVue
// instance
mount(Quicklinks, {store, localVue}).then(() => {
// A custom helper that will wait for a components card to have some condition
// in this case the card's isReady or isErrored needs to be true
... | csrfToken: "dfsdfsgfsdg",
}, | random_line_split |
provider.js | License
*
* Copyright (c) 2015, Sebastian Sdorra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify,... | /**
* @ngdoc object
* @name adf.dashboardProvider
* @description
*
* The dashboardProvider can be used to register structures and widgets.
*/
angular.module('adf.provider', [])
.provider('dashboard', function(){
var widgets = {};
var widgetsPath = '';
var structures = {};
var messageTemplate = ... | */
'use strict';
| random_line_split |
provider.js |
*
* Copyright (c) 2015, Sebastian Sdorra
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, ... | widgets[name] = w;
return this;
};
/**
* @ngdoc method
* @name adf.dashboardProvider#widgetsPath
* @methodOf adf.dashboardProvider
* @description
*
* Sets the path to the directory which contains the widgets. The widgets
* path is used for widgets with a templateUr... | var edit = {reload: true};
angular.extend(edit, w.edit);
w.edit = edit;
}
| conditional_block |
command.rs | use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DroneMode {
Normal = 0,
TakingOff = 1,
Landing = 2,
TookOff = 3, // Helper mode, doesn't exist on drone
Abort = 4,
}
| pub mode: DroneMode,
pub as_array: [u8; 8],
}
impl Command {
pub fn new() -> Command {
Command { throttle: 0, yaw: 0, pitch: 0, roll: 0, mode: DroneMode::Normal, as_array: [0; 8] }
}
pub fn toggle_mode(&mut self, is_toggling: bool) {
match self.mode {
DroneMode::Normal ... | pub struct Command {
pub pitch: i8,
pub yaw: i8,
pub roll: i8,
pub throttle: i8, | random_line_split |
command.rs | use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DroneMode {
Normal = 0,
TakingOff = 1,
Landing = 2,
TookOff = 3, // Helper mode, doesn't exist on drone
Abort = 4,
}
pub struct Command {
pub pitch: i8,
pub yaw: i8,
pub roll: i8,
pub throttle: i8,
pub mode: DroneM... | ,
DroneMode::TakingOff => if is_toggling { () } else { self.mode = DroneMode::TookOff },
DroneMode::TookOff => if is_toggling { self.mode = DroneMode::Landing },
DroneMode::Landing => if is_toggling { () } else { self.mode = DroneMode::Normal },
DroneMode::Abort =... | { self.mode = DroneMode::TakingOff } | conditional_block |
command.rs | use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DroneMode {
Normal = 0,
TakingOff = 1,
Landing = 2,
TookOff = 3, // Helper mode, doesn't exist on drone
Abort = 4,
}
pub struct Command {
pub pitch: i8,
pub yaw: i8,
pub roll: i8,
pub throttle: i8,
pub mode: DroneM... | () {
let mut cmd = Command::new();
cmd.throttle = 127;
cmd.update_array();
assert_eq!(cmd.as_array[3], 254);
}
#[test]
fn test_throttle_down() {
let mut cmd = Command::new();
cmd.throttle = -127;
cmd.update_array();
assert_eq!(cmd.as_array[3... | test_throttle_up | identifier_name |
working.js | components from pre-define file
const StandardComponents = require('../../components/standard-components');
// component categories
class ComponentCategories extends NComponent {
constructor(props) {
super(props);
this.onCategoryExpanded = this.onCategoryExpanded.bind(this);
}
postDidMount() {
this.refs[Stan... |
}
Envs.COMPONENT_TYPES.OWL_COMPONENT_DEF = {type: 'owl-component-def', label: false, error: false};
Envs.setRenderer(Envs.COMPONENT_TYPES.OWL_COMPONENT_DEF.type, function (options) {
return <ComponentDef {...options} />;
});
class SideBar extends React.Component {
render() {
return <NTab model={this.getModel()}
... | {
evt.dataTransfer.setData('componentKey', this.getComponentKey());
} | identifier_body |
working.js | components from pre-define file
const StandardComponents = require('../../components/standard-components');
// component categories
class ComponentCategories extends NComponent {
constructor(props) {
super(props);
this.onCategoryExpanded = this.onCategoryExpanded.bind(this);
}
postDidMount() {
this.refs[Stan... |
return this.formLayout;
}
appendComponent(component) {
let children = this.getFormLayout().getOptionValue('children');
let maxRow = Object.keys(children).reduce((maxRow, cellKey) => {
let layout = children[cellKey];
let rowIndex = (layout && layout.pos) ? layout.pos.row : 0;
if (rowIndex > maxRow) {
... | {
this.formLayout = new Layout('form', {
comp: {
children: {}
}
});
} | conditional_block |
working.js | components from pre-define file
const StandardComponents = require('../../components/standard-components');
// component categories
class ComponentCategories extends NComponent {
constructor(props) {
super(props);
this.onCategoryExpanded = this.onCategoryExpanded.bind(this);
}
postDidMount() {
this.refs[Stan... | }
getModel() {
if (this.state.model == null) {
this.state.model = new Model({});
}
return this.state.model;
}
getLayout() {
if (this.state.layout == null) {
this.state.layout = this.createLayout();
}
return this.state.layout;
}
createLayout() {
return new Layout('bottombar', {
comp: {
s... | layout={this.getLayout()} />; | random_line_split |
working.js | components from pre-define file
const StandardComponents = require('../../components/standard-components');
// component categories
class ComponentCategories extends NComponent {
constructor(props) {
super(props);
this.onCategoryExpanded = this.onCategoryExpanded.bind(this);
}
postDidMount() {
this.refs[Stan... | () {
return {
nothing: {
label: 'No Component Selected...',
comp: {
type: Envs.COMPONENT_TYPES.LABEL,
textFromModel: false
},
pos: {width: 12, row: 100, col: 100 | getNoComponentLayout | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Gedit Better Defaults plugin
# Copyright (C) 2017 Fabio Zendhi Nagao
#
# 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 version 3 of the License, or
# (at your o... | (self, window):
helper = BetterDefaultsWindowHelper(self, window)
window.set_data(self.WINDOW_DATA_KEY, helper)
def deactivate(self, window):
window.get_data(self.WINDOW_DATA_KEY).deactivate()
window.set_data(self.WINDOW_DATA_KEY, None)
def update_ui(self, window):
window.get_data(self.WINDOW_DATA_KEY).up... | activate | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Gedit Better Defaults plugin
# Copyright (C) 2017 Fabio Zendhi Nagao
#
# 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 version 3 of the License, or
# (at your o... |
doc.end_user_action()
def enclose_selected(self, l, r):
doc = self._window.get_active_document()
(a, b) = doc.get_selection_bounds()
doc.insert(b, r)
(a, b) = doc.get_selection_bounds()
doc.insert(a, l)
def on_key_press_event(self, window, event):
doc = self._window.get_active_document()
bounds = d... | doc.insert(riter, '\n' + line) | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# Gedit Better Defaults plugin
# Copyright (C) 2017 Fabio Zendhi Nagao
#
# 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 version 3 of the License, or
# (at your o... | liter.set_line_offset(0);
riter = doc.get_iter_at_mark(doc.get_insert())
f = riter.forward_line()
line = doc.get_slice(liter, riter, True)
if f:
doc.insert(riter, line)
else:
doc.insert(riter, '\n' + line)
doc.end_user_action()
def enclose_selected(self, l, r):
doc = self._window.get_active_docu... | liter = doc.get_iter_at_mark(doc.get_insert()) | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# Gedit Better Defaults plugin
# Copyright (C) 2017 Fabio Zendhi Nagao
#
# 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 version 3 of the License, or
# (at your o... |
class BetterDefaultsPlugin(gedit.Plugin):
WINDOW_DATA_KEY = "BetterDefaultsPluginWindowData"
def __init__(self):
gedit.Plugin.__init__(self)
def activate(self, window):
helper = BetterDefaultsWindowHelper(self, window)
window.set_data(self.WINDOW_DATA_KEY, helper)
def deactivate(self, window):
window.... | doc = self._window.get_active_document()
bounds = doc.get_selection_bounds()
if bounds:
c = event.keyval
if c == 123:
self.enclose_selected('{', '}')
elif c == 91:
self.enclose_selected('[', ']')
elif c == 40:
self.enclose_selected('(', ')')
elif c == 60:
self.enclose_selected('<', '>... | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::RwLock;
use futures::Fu... |
}
pub fn counters(&self) -> HashMap<&'static str, &'static Counter> {
self.counters.read().unwrap().clone()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn counters_test() {
static COUNTER1: Counter = Counter::new("COUNTER1");
static COUNTER2: Counter = Counter::... | {
panic!("Counter {} is duplicated", counter.name)
} | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::RwLock;
use futures::Fu... | () -> &'static Self {
static REGISTRY: Lazy<Registry> = Lazy::new(Registry::default);
&*REGISTRY
}
pub fn register_counter(&self, counter: &'static Counter) {
if self
.counters
.write()
.unwrap()
.insert(counter.name, counter)
... | global | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::RwLock;
use futures::Fu... |
fn inner(&'static self) -> &AtomicUsize {
self.registered
.get_or_init(|| Registry::global().register_counter(self));
&self.inner
}
}
pub struct EntranceGuard(&'static Counter, usize);
impl Drop for EntranceGuard {
fn drop(&mut self) {
self.0.sub(self.1);
}
}
pub... | {
self.add(v);
EntranceGuard(self, v)
} | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::RwLock;
use futures::Fu... | COUNTER1.increment();
COUNTER2.add(5);
let counters = Registry::global().counters();
assert_eq!(1, counters.get("COUNTER1").unwrap().value());
assert_eq!(5, counters.get("COUNTER2").unwrap().value());
}
#[test]
fn entrance_test() {
static COUNTER3: Counter = ... | fn counters_test() {
static COUNTER1: Counter = Counter::new("COUNTER1");
static COUNTER2: Counter = Counter::new("COUNTER2"); | random_line_split |
lib.rs | /// - `Error.description` is an optional human-readable description of the error.
/// - `Error.runtime_id` is the numeric ID of the runtime in which the error has occurred. Note
/// that the runtime is defined for all error types, not just `runtime_error`s, since
/// for any request it's possible to say which runti... | {
self.schema.height()
} | identifier_body | |
lib.rs | (&self) -> &Verified<AnyTx> {
&self.message
}
/// Returns the transaction location in block.
pub fn location(&self) -> &TxLocation {
&self.location
}
/// Returns a proof that transaction is recorded in the blockchain.
pub fn location_proof(&self) -> &ListProof<Hash> {
&... | fmt | identifier_name | |
lib.rs | 100;
/// let tx = keypair.create_wallet(SERVICE_ID, "Alice".to_owned());
/// // This transaction in pool will be represented as follows:
/// let json = json!({
/// "type": "in_pool",
/// "message": tx,
/// });
/// let parsed: TransactionInfo = serde_json::from_value(json).unwrap();
/// assert!(parsed.is_in_pool... | {
UNIX_EPOCH.into()
} | conditional_block | |
lib.rs | self.explorer.precommits(&self.header);
*self.precommits.borrow_mut() = Some(precommits);
}
Ref::map(self.precommits.borrow(), |cache| {
cache.as_ref().unwrap().as_ref()
})
}
/// Lists hashes of transactions included in this block.
pub fn transaction_hashes... |
/// Execution error together with its location within the block.
#[derive(Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ErrorWithLocation {
/// Location of the error.
pub location: CallInBlock,
/// Error data.
pub error: ExecutionError,
}
impl fmt::Display for ErrorWithLocation {
fn... | } | random_line_split |
pagination.component.ts | {
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnInit,
Output,
Provider,
TemplateRef
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ConfigModel, PagesModel, PaginationLinkContext, PaginationNumberLinkContext }... | (config: Partial<ConfigModel>): void {
this.config = Object.assign({}, config);
}
ngOnInit(): void {
if (typeof window !== 'undefined') {
this.classMap = this.elementRef.nativeElement.getAttribute('class') || '';
}
// watch for maxSize
if (typeof this.maxSize === 'undefined') {
thi... | configureOptions | identifier_name |
pagination.component.ts | ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnInit,
Output,
Provider,
TemplateRef
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ConfigModel, PagesModel, PaginationLinkContext, PaginationNumberLinkContext } fr... |
protected getPages(currentPage: number, totalPages: number): PagesModel[] {
const pages: PagesModel[] = [];
// Default page limits
let startPage = 1;
let endPage = totalPages;
const isMaxSized =
typeof this.maxSize !== 'undefined' && this.maxSize < totalPages;
// recompute if maxSize... | {
return { text, number: num, active };
} | identifier_body |
pagination.component.ts | ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnInit,
Output,
Provider,
TemplateRef
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ConfigModel, PagesModel, PaginationLinkContext, PaginationNumberLinkContext } fr... |
// base class
if (typeof this.itemsPerPage === 'undefined') {
this.itemsPerPage = this.config?.itemsPerPage || 0;
}
this.totalPages = this.calculateTotalPages();
// this class
this.pages = this.getPages(this.page, this.totalPages);
this.inited = true;
}
writeValue(value: number... | {
this.pageBtnClass = this.config?.pageBtnClass || '';
} | conditional_block |
pagination.component.ts | {
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnInit,
Output,
Provider,
TemplateRef
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ConfigModel, PagesModel, PaginationLinkContext, PaginationNumberLinkContext }... | @Component({
selector: 'pagination',
templateUrl: './pagination.component.html',
providers: [PAGINATION_CONTROL_VALUE_ACCESSOR]
})
export class PaginationComponent implements ControlValueAccessor, OnInit {
config?: Partial<ConfigModel>;
/** if `true` aligns each link to the sides of pager */
@Input() align ... | };
| random_line_split |
243_topology_tables.py | from migrate.changeset import UniqueConstraint
from migrate import ForeignKeyConstraint
from sqlalchemy import Boolean, BigInteger, Column, DateTime, Enum, Float
from sqlalchemy import dialects
from sqlalchemy import ForeignKey, Index, Integer, MetaData, String, Table
from sqlalchemy import Text
from sqlalchemy.types i... | meta = MetaData()
meta.bind = migrate_engine
node_info = Table('node_info',meta)
try:
node_info.drop()
except Exception:
LOG.info("Table node_info doesn't exist")
#LOG.info(repr(node_info))
#LOG.exception(_('Exception while deleting table node_info.'))
edge_inf... | identifier_body | |
243_topology_tables.py | from migrate.changeset import UniqueConstraint
from migrate import ForeignKeyConstraint
from sqlalchemy import Boolean, BigInteger, Column, DateTime, Enum, Float
from sqlalchemy import dialects
from sqlalchemy import ForeignKey, Index, Integer, MetaData, String, Table |
LOG = logging.getLogger(__name__)
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
node_info = Table('node_info',meta,
Column('created_at', DateTime),
Column('updated_at', DateTime),
Column('deleted_at', DateTime),
Column('deleted', Integer),
C... | from sqlalchemy import Text
from sqlalchemy.types import NullType
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging | random_line_split |
243_topology_tables.py | from migrate.changeset import UniqueConstraint
from migrate import ForeignKeyConstraint
from sqlalchemy import Boolean, BigInteger, Column, DateTime, Enum, Float
from sqlalchemy import dialects
from sqlalchemy import ForeignKey, Index, Integer, MetaData, String, Table
from sqlalchemy import Text
from sqlalchemy.types i... | (migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
node_info = Table('node_info',meta,
Column('created_at', DateTime),
Column('updated_at', DateTime),
Column('deleted_at', DateTime),
Column('deleted', Integer),
Column('id', Integer, primary_key=True, nullable... | upgrade | identifier_name |
regress-452476.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
jit(false);
reportCompare(expect, actual, summary);
| {
for (var i = 0; i < j; ++i)
this["n" + i] = 1;
__defineGetter__('w', (function(){}));
[1 for each (g in this) for each (t in /x/g)];
} | conditional_block |
regress-452476.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | * the Initial Developer. All Rights Reserved.
*
* Contributor(s): Jesse Ruderman
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in ... | *
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2008 | random_line_split |
middleware.rs | /// Macro to reduce the boilerplate required for using unboxed
/// closures as `Middleware` due to current type inference behaviour.
///
/// In future, the macro should hopefully be able to be removed while
/// having minimal changes to the closure's code.
///
/// # Limitations
///
/// The body of the `middleware!` mac... |
restrict_closure(move |as_pat!($req), $res_binding| {
restrict(as_block!({$($b)+}), $res)
})
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! as_block { ($b:block) => ( $b ) }
#[doc(hidden)]
#[macro_export]
macro_rules! as_pat { ($p:pat) => ( $p ) } | fn restrict_closure<F, D: Send + 'static + Sync>(f: F) -> F
where F: for<'r>
Fn(&'r mut Request<D>, Response<D>)
-> MiddlewareResult<D> + Send + Sync { f } | random_line_split |
scaffold10.py | # This challenge is similar to the previous one. It operates under the same
# premise that you will have to replace the check_equals_ function. In this
# case, however, check_equals_ is called so many times that it wouldn't make
# sense to hook where each one was called. Instead, use a SimProcedure to write
# your ow... |
# Hook the check_equals symbol. Angr automatically looks up the address
# associated with the symbol. Alternatively, you can use 'hook' instead
# of 'hook_symbol' and specify the address of the function. To find the
# correct symbol, disassemble the binary.
# (!)
check_equals_symbol = ??? # :string
p... | def run(self, to_check, ...???):
# We can almost copy and paste the solution from the previous challenge.
# Hint: Don't look up the address! It's passed as a parameter.
# (!)
user_input_buffer_address = ???
user_input_buffer_length = ???
# Note the use of self.state to find the stat... | identifier_body |
scaffold10.py | # This challenge is similar to the previous one. It operates under the same
# premise that you will have to replace the check_equals_ function. In this
# case, however, check_equals_ is called so many times that it wouldn't make
# sense to hook where each one was called. Instead, use a SimProcedure to write
# your ow... |
if __name__ == '__main__':
main(sys.argv)
| raise Exception('Could not find the solution') | conditional_block |
scaffold10.py | # This challenge is similar to the previous one. It operates under the same
# premise that you will have to replace the check_equals_ function. In this
# case, however, check_equals_ is called so many times that it wouldn't make
# sense to hook where each one was called. Instead, use a SimProcedure to write
# your ow... | (angr.SimProcedure):
# A SimProcedure replaces a function in the binary with a simulated one
# written in Python. Other than it being written in Python, the function
# acts largely the same as any function written in C. Any parameter after
# 'self' will be treated as a parameter to the function you are ... | ReplacementCheckEquals | identifier_name |
scaffold10.py | # This challenge is similar to the previous one. It operates under the same
# premise that you will have to replace the check_equals_ function. In this
# case, however, check_equals_ is called so many times that it wouldn't make
# sense to hook where each one was called. Instead, use a SimProcedure to write
# your ow... | user_input_buffer_address = ???
user_input_buffer_length = ???
# Note the use of self.state to find the state of the system in a
# SimProcedure.
user_input_string = self.state.memory.load(
user_input_buffer_address,
user_input_buffer_length
)
check_against_st... | # (!)
def run(self, to_check, ...???):
# We can almost copy and paste the solution from the previous challenge.
# Hint: Don't look up the address! It's passed as a parameter.
# (!) | random_line_split |
tests.rs | extern crate bufstream;
extern crate cargo;
extern crate filetime;
extern crate flate2;
extern crate git2;
extern crate hamcrest;
extern crate libc;
extern crate rustc_serialize;
extern crate tar;
extern crate tempdir;
extern crate term;
extern crate url;
#[cfg(windows)] extern crate kernel32;
#[cfg(windows)] extern cr... | mod test_cargo_registry;
mod test_cargo_run;
mod test_cargo_rustc;
mod test_cargo_rustdoc;
mod test_cargo_search;
mod test_cargo_test;
mod test_cargo_tool_paths;
mod test_cargo_verify_project;
mod test_cargo_version;
mod test_shell;
thread_local!(static RUSTC: Rustc = Rustc::new("rustc").unwrap());
fn rustc_host() ->... | random_line_split | |
tests.rs | extern crate bufstream;
extern crate cargo;
extern crate filetime;
extern crate flate2;
extern crate git2;
extern crate hamcrest;
extern crate libc;
extern crate rustc_serialize;
extern crate tar;
extern crate tempdir;
extern crate term;
extern crate url;
#[cfg(windows)] extern crate kernel32;
#[cfg(windows)] extern cr... | () -> bool {
RUSTC.with(|r| !(r.host.contains("msvc") && !r.host.contains("x86_64")))
}
| can_panic | identifier_name |
tests.rs | extern crate bufstream;
extern crate cargo;
extern crate filetime;
extern crate flate2;
extern crate git2;
extern crate hamcrest;
extern crate libc;
extern crate rustc_serialize;
extern crate tar;
extern crate tempdir;
extern crate term;
extern crate url;
#[cfg(windows)] extern crate kernel32;
#[cfg(windows)] extern cr... | {
RUSTC.with(|r| !(r.host.contains("msvc") && !r.host.contains("x86_64")))
} | identifier_body | |
lib.rs | // Copyright 2013-2014 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-MI... |
#[cfg(not(test))]
mod std {
pub use core::ops; // RangeFull
}
#[cfg(test)]
mod prelude {
// from core.
pub use core::clone::Clone;
pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord};
pub use core::cmp::Ordering::{Less, Equal, Greater};
pub use core::iter::range;
pub use core::iter::... | {} | identifier_body |
lib.rs | // Copyright 2013-2014 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-MI... | pub use core::iter::{ExactSizeIterator};
pub use core::marker::{Copy, Send, Sized, Sync};
pub use core::mem::drop;
pub use core::ops::{Drop, Fn, FnMut, FnOnce};
pub use core::option::Option;
pub use core::option::Option::{Some, None};
pub use core::ptr::PtrExt;
pub use core::result::Resu... | random_line_split | |
lib.rs | // Copyright 2013-2014 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-MI... | () {}
#[cfg(not(test))]
mod std {
pub use core::ops; // RangeFull
}
#[cfg(test)]
mod prelude {
// from core.
pub use core::clone::Clone;
pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord};
pub use core::cmp::Ordering::{Less, Equal, Greater};
pub use core::iter::range;
pub use core::i... | fixme_14344_be_sure_to_link_to_collections | identifier_name |
chat-panel.module.ts | import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
import { PERFECT_SCROLLBAR_CONFIG } from '../../services/common';
import... | PasteImageModule,
DropFileModule,
AtListModule,
SharedPipeModule,
MessageFileModule,
CardModalModule,
SharedDirectiveModule
],
exports: [
ChatPanelComponent
],
providers: [
StorageService
]
})
export class ChatPanelModule { } | EmojiModule,
RouterModule,
HoverTipModule,
ImageViewerModule,
MessageMenuModule, | random_line_split |
chat-panel.module.ts | import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { PerfectScrollbarModule } from 'ngx-perfect-scrollbar';
import { PERFECT_SCROLLBAR_CONFIG } from '../../services/common';
import... | { }
| ChatPanelModule | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 02:47
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car_model', models... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 02:47
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| ('date', models.DateTimeField(verbose_name='date changed')),
('mileage', models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0)])),
('car', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='car.Car')),
],
... | initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car_model', models.CharField(max_length=20)),
... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 02:47 | import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
('id', models.... | from __future__ import unicode_literals
| random_line_split |
client.py | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... |
def onOpen(self):
self.sendHello()
def onMessage(self, payload, isBinary):
if not isBinary:
print("Text message received: {}".format(payload.decode('utf8')))
reactor.callLater(1, self.sendHello)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Need th... | self.sendMessage("Hello, world!".encode('utf8')) | identifier_body |
client.py | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... | self.sendHello()
def onMessage(self, payload, isBinary):
if not isBinary:
print("Text message received: {}".format(payload.decode('utf8')))
reactor.callLater(1, self.sendHello)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Need the WebSocket server addre... |
def onOpen(self): | random_line_split |
client.py | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... |
factory = WebSocketClientFactory(sys.argv[1],
debug=debug,
debugCodePaths=debug)
factory.protocol = EchoClientProtocol
connectWS(factory)
reactor.run()
| debug = False | conditional_block |
client.py | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... | (self):
self.sendHello()
def onMessage(self, payload, isBinary):
if not isBinary:
print("Text message received: {}".format(payload.decode('utf8')))
reactor.callLater(1, self.sendHello)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Need the WebSocket serv... | onOpen | identifier_name |
build_gecko.rs | ) = search_include(cap.get(1).unwrap().as_str()) {
add_headers_recursively(path, added_paths);
}
}
}
fn add_include(name: &str) -> String {
let mut added_paths = ADDED_PATHS.lock().unwrap();
let file = search_include(name).expect("Include not found!");
... | "Unrecognized line in ServoArcTypeList.h: '{}'",
line
))
.get(1)
.unwrap()
.as_str()
.to_string()
})
.collect()
}
struct BuilderWithConfig... | {
// Read the file
let mut list_file = File::open(DISTDIR_PATH.join("include/mozilla/ServoArcTypeList.h"))
.expect("Unable to open ServoArcTypeList.h");
let mut content = String::new();
list_file
.read_to_string(&mut content)
.expect("Fail to read Serv... | identifier_body |
build_gecko.rs | ) = search_include(cap.get(1).unwrap().as_str()) {
add_headers_recursively(path, added_paths);
}
}
}
fn add_include(name: &str) -> String {
let mut added_paths = ADDED_PATHS.lock().unwrap();
let file = search_include(name).expect("Include not found!");
... | (self, ty: &str, structs_list: &HashSet<&str>) -> Builder {
if !structs_list.contains(ty) {
self.blacklist_type(ty)
.raw_line(format!("enum {}Void {{ }}", ty))
.raw_line(format!("pub struct {0}({0}Void);", ty))
} else {
self... | zero_size_type | identifier_name |
build_gecko.rs | (path) = search_include(cap.get(1).unwrap().as_str()) {
add_headers_recursively(path, added_paths);
}
}
}
fn add_include(name: &str) -> String {
let mut added_paths = ADDED_PATHS.lock().unwrap();
let file = search_include(name).expect("Include not found!");
... | fn include<T: Into<String>>(self, file: T) -> Builder;
fn zero_size_type(self, ty: &str, structs_list: &HashSet<&str>) -> Builder;
fn borrowed_type(self, ty: &str) -> Builder;
fn mutable_borrowed_type(self, ty: &str) -> Builder;
}
fn add_clang_args(mut builder: Builder, config: ... | trait BuilderExt {
fn get_initial_builder() -> Builder; | random_line_split |
build_gecko.rs | Void);", ty))
} else {
self
}
}
fn borrowed_type(self, ty: &str) -> Builder {
self.blacklist_type(format!("{}Borrowed", ty))
.raw_line(format!("pub type {0}Borrowed<'a> = &'a {0};", ty))
.blacklist_type(format!("{}Borrow... | {
file.lock().unwrap().flush().unwrap();
} | conditional_block | |
hookenv.py | """Write a message to the juju log"""
command = ['juju-log']
if level:
command += ['-l', level]
command += [message]
subprocess.call(command)
class Serializable(UserDict.IterableUserDict):
"""Wrapper, an object that can be serialized to yaml or json"""
def __init__(self, obj):
... |
def log(message, level=None): | random_line_split | |
hookenv.py |
return wrapper
def flush(key):
"""Flushes any entries from function cache where the
key is found in the function+args """
flush_list = []
for item in cache:
if key in item:
flush_list.append(item)
for item in flush_list:
del cache[item]
def log(message, level=Non... | global cache
key = str((func, args, kwargs))
try:
return cache[key]
except KeyError:
res = func(*args, **kwargs)
cache[key] = res
return res | identifier_body | |
hookenv.py | .data = obj
def __getattr__(self, attr):
# See if this object has attribute.
if attr in ("json", "yaml", "data"):
return self.__dict__[attr]
# Check for attribute in wrapped object.
got = getattr(self.data, attr, MARKER)
if got is not MARKER:
return g... |
def __getitem__(self, key):
"""For regular dict lookups, check the current juju config first,
then the previous (saved) copy. This ensures that user-saved values
will be returned by a dict lookup.
"""
try:
return dict.__getitem__(self, key)
except KeyEr... | self.load_previous() | conditional_block |
hookenv.py | .data = obj
def __getattr__(self, attr):
# See if this object has attribute.
if attr in ("json", "yaml", "data"):
return self.__dict__[attr]
# Check for attribute in wrapped object.
got = getattr(self.data, attr, MARKER)
if got is not MARKER:
return g... | (self):
"""Serialize the object to yaml"""
return yaml.dump(self.data)
def execution_environment():
"""A convenient bundling of the current execution context"""
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid... | yaml | identifier_name |
myLibs.js | function | (){
this.client = {};
this.add = function(id, value){
if( id )
this.client[id] = value;
else
throw "Não da pra adicionar um valor [ " + id + " ] ao dicionario hash;";
}
this.remove = function(id){
delete this.client[id];
}
thi... | ConnectionList | identifier_name |
myLibs.js | function ConnectionList(){
this.client = {};
this.add = function(id, value){
if( id )
this.client[id] = value;
else
throw "Não da pra adicionar um valor [ " + id + " ] ao dicionario hash;";
}
this.remove = function(id){
delete this.client[... |
this.find = function(id){
if (this.client[id] == undefined)
return false
else
return true;
}
this.getAll = function(){
return Object.values(this.client);
}
this.broadcast = function(evt, msg){
for (var key in this.cl... | return this.client[id];
} | random_line_split |
myLibs.js | function ConnectionList() |
this.length = function(){
return Object.keys( this.client ).length;
}
this.get = function(id){
return this.client[id];
}
this.find = function(id){
if (this.client[id] == undefined)
return false
else
return true;
}
this.getAll... | {
this.client = {};
this.add = function(id, value){
if( id )
this.client[id] = value;
else
throw "Não da pra adicionar um valor [ " + id + " ] ao dicionario hash;";
}
this.remove = function(id){
delete this.client[id];
}
this.... | identifier_body |
edit.js | import React, { Component } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group'; // ES6
import SaveButton from './saveButton';
import FacebookProvider, { Share} from 'react-facebook';
export default class Edit extends Component {
constructor(props) {
super(props);
this.state = {
m... | e.log("componentWillUnmount");
}
// viewChange(view){
// console.log("call viewChange in input.js",view);
// // console.log(this.state);
// // this.setState(state);
// //
// var state = {route:view};
//
// this.setState(state);
// }
showBody(data){
console.log("input.js",data);
data = "<p>" ... | ;
}
componentWillUnmount() {
consol | identifier_body |
edit.js | import React, { Component } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group'; // ES6
import SaveButton from './saveButton';
import FacebookProvider, { Share} from 'react-facebook';
export default class Edit extends Component {
constructor(props) {
super(props);
this.state = {
m... | // TODO model内 で処理するようリファクタリングする
$.ajax({
url: '/api/isyos?filter={"where":{"hash":"' + this.props.params.isyoHash + '"}}',
type: 'GET',
success: function(res) {
console.log("editjs get api success",res);
// this.setState({data: data})
var body = res[0].body;
... |
var that = this; | random_line_split |
edit.js | import React, { Component } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group'; // ES6
import SaveButton from './saveButton';
import FacebookProvider, { Share} from 'react-facebook';
export default class Edit extends Component {
| (props) {
super(props);
this.state = {
message: "",
isyoId: ""
};
this.showBody = this.showBody.bind(this);
console.log("edit.js constructor",this.props);
var that = this;
// TODO model内 で処理するようリファクタリングする
$.ajax({
url: '/api/isyos?filter={"where":{"hash":"' + this.props.params.isyoH... | constructor | identifier_name |
edit.js | import React, { Component } from 'react';
import CSSTransitionGroup from 'react-addons-css-transition-group'; // ES6
import SaveButton from './saveButton';
import FacebookProvider, { Share} from 'react-facebook';
export default class Edit extends Component {
constructor(props) {
super(props);
this.state = {
m... |
console.log("componentDidMount");
}
componentWillUnmount() {
console.log("componentWillUnmount");
}
// viewChange(view){
// console.log("call viewChange in input.js",view);
// // console.log(this.state);
// // this.setState(state);
// //
// var state = {route:view};
//
// this.setState(state);
... | ta.responseCode);
}
});
}
componentDidMount() { | conditional_block |
config.ts | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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 appli... | onUncaughtException: 'ignore',
// EXPERIMENTAL:
// Allows to ignore the requests X-Cloud-Trace-Context -header if set. Setting this
// to true will cause traces generated by this module to appear separately from other
// distributed work done by other services on behalf of the same incoming request... | // publish the traces to the API, and then terminate the application after
// a delay. Note that presence of other uncaught exception handlers may
// chose to terminate the application before the buffer has been flushed to
// the network. | random_line_split |
shell.rs | /// Creates a new shell (color choice and verbosity), defaulting to 'auto' color and verbose
/// output.
pub fn new() -> Shell {
Shell {
err: ShellOut::Stream {
stream: StandardStream::stderr(ColorChoice::CargoAuto.to_termcolor_color_choice()),
color_choice: ... | (&mut self) -> &mut dyn Write {
match *self {
ShellOut::Stream { ref mut stream, .. } => stream,
Shell | as_write | identifier_name |
shell.rs | {
match self.err {
ShellOut::Stream { tty, .. } => tty,
_ => false,
}
}
/// Gets a reference to the underlying writer.
pub fn err(&mut self) -> &mut dyn Write {
if self.needs_clear {
self.err_erase_line();
}
self.err.as_write()
... | use winapi::um::fileapi::*;
use winapi::um::handleapi::*;
use winapi::um::processenv::*; | random_line_split | |
elfinder.pt_BR.js | 'errConf': 'Configuração inválida do backend.',
'errJSON': 'Módulo PHP JSON não está instalado.',
'errNoVolumes': 'Não existe nenhum volume legível disponivel.',
'errCmdParams': 'Parâmetro inválido para o comando "$1".',
'errDataNotJSON': 'Dados não estão no f... | {
elFinder.prototype.i18.pt_BR = {
translator: 'Leandro Carvalho <contato@leandrowebdev.net>',
language: 'Português',
direction: 'ltr',
messages: {
/********************************** errors **********************************/
'error': 'Erro',
... | conditional_block | |
elfinder.pt_BR.js | ado.',
'errNoVolumes': 'Não existe nenhum volume legível disponivel.',
'errCmdParams': 'Parâmetro inválido para o comando "$1".',
'errDataNotJSON': 'Dados não estão no formato JSON.',
'errDataEmpty': 'Dados vazios.',
'errCmdReq': 'Requisição do Backend requer ... | 'chiefdev': 'Desenvolvedor chefe',
'developer': 'Desenvolvedor',
'contributor': 'Contribuinte',
'maintainer': 'Mantenedor',
'translator': 'Tradutor',
'icons': 'Ícones',
'dontforget': 'e não se esqueça de levar sua toalha',
'... | 'facebook': 'Junte-se a nós no Facebook',
'team': 'Time', | random_line_split |
find.test.ts | /* globals describe, it */
import { assert } from 'chai'
import { find, preCache } from '../src/find'
import { oceanZones } from '../src/oceanUtils'
const issueCoords = require('./fixtures/issues.json')
process.chdir('/tmp')
/**
* Assert that a lookup includes certain timezones
*
* @param {number} lat
* @para... |
describe('find tests', function () {
it('should find the timezone name for a valid coordinate', function () {
assertTzResultContainsTzs(47.650499, -122.35007, 'America/Los_Angeles')
})
it('should find the timezone name for a valid coordinate via subfile examination', function () {
assertTzResultContain... | {
if (typeof tzs === 'string') {
tzs = [tzs]
}
const result = find(lat, lon)
assert.isArray(result)
assert.sameMembers(result, tzs)
} | identifier_body |
find.test.ts | /* globals describe, it */
import { assert } from 'chai'
import { find, preCache } from '../src/find'
import { oceanZones } from '../src/oceanUtils'
const issueCoords = require('./fixtures/issues.json')
process.chdir('/tmp')
/**
* Assert that a lookup includes certain timezones
*
* @param {number} lat
* @para... | (lat, lon, tzs) {
if (typeof tzs === 'string') {
tzs = [tzs]
}
const result = find(lat, lon)
assert.isArray(result)
assert.sameMembers(result, tzs)
}
describe('find tests', function () {
it('should find the timezone name for a valid coordinate', function () {
assertTzResultContainsTzs(47.650499, -1... | assertTzResultContainsTzs | identifier_name |
find.test.ts | /* globals describe, it */
import { assert } from 'chai'
import { find, preCache } from '../src/find'
import { oceanZones } from '../src/oceanUtils'
const issueCoords = require('./fixtures/issues.json')
process.chdir('/tmp')
/**
* Assert that a lookup includes certain timezones
*
* @param {number} lat
* @para... | })
})
describe('performance aspects', function () {
this.timeout(20000)
const europeTopLeft = [56.432158, -11.9263934]
const europeBottomRight = [39.8602076, 34.9127951]
const count = 2000
const findRandomPositions = function () {
const timingStr = 'find tz of ' + count + ' random e... | 'should find ' + spotDescription + ' (' + spot.description + ')',
function () {
assertTzResultContainsTzs(spot.lat, spot.lon, spot.zid || spot.zids)
}
) | random_line_split |
find.test.ts | /* globals describe, it */
import { assert } from 'chai'
import { find, preCache } from '../src/find'
import { oceanZones } from '../src/oceanUtils'
const issueCoords = require('./fixtures/issues.json')
process.chdir('/tmp')
/**
* Assert that a lookup includes certain timezones
*
* @param {number} lat
* @para... |
const result = find(lat, lon)
assert.isArray(result)
assert.sameMembers(result, tzs)
}
describe('find tests', function () {
it('should find the timezone name for a valid coordinate', function () {
assertTzResultContainsTzs(47.650499, -122.35007, 'America/Los_Angeles')
})
it('should find the timezone ... | {
tzs = [tzs]
} | conditional_block |
pages.ts | import {IDSPaginator, IDSPaginatorProvider} from "./interface";
import {Inject, Injectable, InjectionToken, Optional} from "@angular/core";
export let PAGINATOR_PAGE_CONFIG = new InjectionToken<any>("paginator.page.config");
@Injectable()
export class DSPagePaginator implements IDSPaginator {
public page: number... |
this.page = this._config.page || 1;
this.page_size = this._config.page_size || 100;
this.page_parameter = this._config.page_parameter || "page";
this.page_size_parameter = this._config.page_size_parameter || "page_size";
}
public getPaginationInfos(result: any): any {
i... | {
this._config = {};
} | conditional_block |
pages.ts | import {IDSPaginator, IDSPaginatorProvider} from "./interface";
import {Inject, Injectable, InjectionToken, Optional} from "@angular/core";
export let PAGINATOR_PAGE_CONFIG = new InjectionToken<any>("paginator.page.config");
@Injectable()
export class DSPagePaginator implements IDSPaginator {
public page: number... |
public getResults(results: any): any {
if (results.nav) {
return results.results;
} else {
return results;
}
}
public update(params: any): void {
if (params.page) {
this.page = params.page;
}
if (params.page_size) {
... | {
if (result.nav) {
this.page = result.nav.page;
this.page_size = result.nav.size;
return {nav: result.nav, parameters: result.parameters};
} else {
return {};
}
} | identifier_body |
pages.ts | import {IDSPaginator, IDSPaginatorProvider} from "./interface";
import {Inject, Injectable, InjectionToken, Optional} from "@angular/core";
export let PAGINATOR_PAGE_CONFIG = new InjectionToken<any>("paginator.page.config");
@Injectable()
export class DSPagePaginator implements IDSPaginator {
public page: number... | public get localPaginate(): any {
let pagination = {};
pagination[this.page_parameter] = this.page;
pagination[this.page_size_parameter] = this.page_size;
return pagination;
}
}
@Injectable()
export class DSPagePaginatorProvider implements IDSPaginatorProvider {
public provi... | }
| random_line_split |
pages.ts | import {IDSPaginator, IDSPaginatorProvider} from "./interface";
import {Inject, Injectable, InjectionToken, Optional} from "@angular/core";
export let PAGINATOR_PAGE_CONFIG = new InjectionToken<any>("paginator.page.config");
@Injectable()
export class DSPagePaginator implements IDSPaginator {
public page: number... | (results: any): any {
if (results.nav) {
return results.results;
} else {
return results;
}
}
public update(params: any): void {
if (params.page) {
this.page = params.page;
}
if (params.page_size) {
this.page_size =... | getResults | identifier_name |
setup.py | #!/usr/bin/env python
#==============================================================================
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... |
_opts = {
'build_scripts': {'executable': '/usr/bin/env python'},
'bdist_rpm': {'requires': rpm_requires}
}
_data_files = [('share/doc/%s-%s' % (name, bridge.__version__), ['NOTICE.txt', 'LICENSE']),
('init/redhat', ['init/redhat/cfn-resource-bridge']),
('init/ubuntu', ['init/ubu... | rpm_requires.append('python-argparse >= 1.1')
dependencies.append('argparse>=1.1') | conditional_block |
setup.py | #!/usr/bin/env python
#==============================================================================
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... | ('init/redhat', ['init/redhat/cfn-resource-bridge']),
('init/ubuntu', ['init/ubuntu/cfn-resource-bridge'])]
try:
import py2exe
_opts['py2exe'] = {
# TODO: Need to update this for this package
'typelibs': [('{000C1092-0000-0000-C000-000000000046}', 1033, 1, 0),
... | }
_data_files = [('share/doc/%s-%s' % (name, bridge.__version__), ['NOTICE.txt', 'LICENSE']), | random_line_split |
queue.js | 'use strict';
const Command = require('../../util/helpers/modules/Command');
class Queue extends Command {
constructor() {
super();
this.help = {
name: 'queue',
category: 'music',
description: 'Queue a song or check the queue, to check the queue, just run `{pref... |
}
module.exports = new Queue(); | {
const player = await client.musicManager.getPlayer(message.channel.guild.channels.get(clientMember.voiceState.channelID));
let formattedQueue = `:musical_note: Now playing: **${connection.nowPlaying.info.title}** (${client.musicManager.parseDuration(player.state.position)}/${client.musicManager.parseD... | identifier_body |
queue.js | 'use strict';
const Command = require('../../util/helpers/modules/Command');
class Queue extends Command {
constructor() {
super();
this.help = {
name: 'queue',
category: 'music',
description: 'Queue a song or check the queue, to check the queue, just run `{pref... | }],
color: client.config.options.embedColor
}});
}
async selectTrack(client, message, tracks) {
tracks = tracks.splice(0, 15);
let searchResults = `Your search has returned multiple results, please select one by replying their corresponding number\n\n`;
l... | value: client.musicManager.parseDuration(track),
inline: true | random_line_split |
queue.js | 'use strict';
const Command = require('../../util/helpers/modules/Command');
class | extends Command {
constructor() {
super();
this.help = {
name: 'queue',
category: 'music',
description: 'Queue a song or check the queue, to check the queue, just run `{prefix}queue`. You can input: A `YouTube` URL (including livestreams), a `Soundcloud` URL, a `... | Queue | identifier_name |
queue.js | 'use strict';
const Command = require('../../util/helpers/modules/Command');
class Queue extends Command {
constructor() {
super();
this.help = {
name: 'queue',
category: 'music',
description: 'Queue a song or check the queue, to check the queue, just run `{pref... |
}
for (const track of queue) {
if (formattedQueue.length >= 1900) {
return formattedQueue += `\n\nAnd **${queue.length - i}** more...`;
}
formattedQueue += `\`${i++}\` - **${track.info.title}** (\`${client.musicManager.parseDuration(track)}\`)\n`;
... | {
const toPlay = queue.splice(connection.queuePosition);
queue = toPlay.concat(queue);
} | conditional_block |
static-method-on-struct-and-enum.rs | // Copyright 2013-2014 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-MI... | {
Variant1 { x: isize },
Variant2,
Variant3(f64, isize, char),
}
impl Enum {
fn static_method(arg1: isize, arg2: f64, arg3: usize) -> isize {
zzz(); // #break
arg1
}
}
fn main() {
Struct::static_method(1, 2);
Enum::static_method(-3, 4.5, 5);
}
fn zzz() {()}
| Enum | identifier_name |
static-method-on-struct-and-enum.rs | // 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.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ========================... | // Copyright 2013-2014 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 | random_line_split | |
record.rs | use std::ops::Deref;
use config::gobjects::GObject;
use env::Env;
use library;
use nameutil::*;
use super::*;
use super::imports::Imports;
use super::info_base::InfoBase;
use traits::*;
#[derive(Default)]
pub struct Info {
pub base: InfoBase,
}
impl Deref for Info {
type Target = InfoBase;
fn deref(&sel... | ;
special_functions::analyze_imports(&specials, &mut imports);
//don't `use` yourself
imports.remove(&name);
let base = InfoBase {
full_name: full_name,
type_id: record_tid,
name: name,
functions: functions,
specials: specials,
imports: imports,
... | {
// `copy` will duplicate a struct while `clone` just adds a reference
special_functions::unhide(&mut functions, &specials, special_functions::Type::Copy);
} | conditional_block |
record.rs | use std::ops::Deref;
use config::gobjects::GObject;
use env::Env;
use library;
use nameutil::*;
use super::*;
use super::imports::Imports;
use super::info_base::InfoBase;
use traits::*;
#[derive(Default)]
pub struct Info {
pub base: InfoBase,
}
impl Deref for Info {
type Target = InfoBase;
fn deref(&sel... |
}
pub fn new(env: &Env, obj: &GObject) -> Option<Info> {
let full_name = obj.name.clone();
let record_tid = match env.library.find_type(0, &full_name) {
Some(tid) => tid,
None => return None,
};
let type_ = env.type_(record_tid);
let name: String = split_namespace_name(&full_nam... | {
let type_ = library.type_(self.type_id).maybe_ref()
.unwrap_or_else(|| panic!("{} is not a record.", self.full_name));
type_
} | identifier_body |
record.rs | use std::ops::Deref;
use config::gobjects::GObject;
use env::Env;
use library;
use nameutil::*;
use super::*;
use super::imports::Imports;
use super::info_base::InfoBase;
use traits::*;
#[derive(Default)]
pub struct Info {
pub base: InfoBase,
}
impl Deref for Info {
type Target = InfoBase;
fn deref(&sel... | (env: &Env, obj: &GObject) -> Option<Info> {
let full_name = obj.name.clone();
let record_tid = match env.library.find_type(0, &full_name) {
Some(tid) => tid,
None => return None,
};
let type_ = env.type_(record_tid);
let name: String = split_namespace_name(&full_name).1.into();
... | new | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.