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 |
|---|---|---|---|---|
common.py | import string
import random
import json
from collections import defaultdict
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from catmaid.fields import Double3D
from catmaid.models import Log, NeuronSearch, CELL_BODY_CHOICES, \
... | (project_id):
return {cname: ID for cname, ID in Class.objects.filter(project=project_id).values_list("class_name", "id")}
def urljoin(a, b):
""" Joins to URL parts a and b while making sure this
exactly one slash inbetween.
"""
if a[-1] != '/':
a = a + '/'
if b[0] == '/':
b = b... | get_class_to_id_map | identifier_name |
lib.rs | //! Implementation of `cpp_to_rust` generator that
//! analyzes a C++ library and produces a Rust crate for it.
//! See [README](https://github.com/rust-qt/cpp_to_rust/tree/master/cpp_to_rust/cpp_to_rust_generator)
//! for more information.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", ... | mod launcher;
mod rust_generator;
mod rust_code_generator;
mod rust_info;
mod rust_type;
mod cpp_parser;
mod versions;
#[cfg(test)]
mod tests; | pub mod cpp_method;
pub mod cpp_type;
mod cpp_operator;
mod doc_formatter; | random_line_split |
MarkerCanvas.js | import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'
// expand to fill entire parent container (ScrollElement)
co... | () {
return (
<MarkerCanvasProvider value={this.state}>
<div
style={staticStyles}
onMouseMove={this.handleMouseMove}
onMouseLeave={this.handleMouseLeave}
ref={el => (this.containerEl = el)}
>
<TimelineMarkersRenderer />
{this.props.ch... | render | identifier_name |
MarkerCanvas.js | import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'
// expand to fill entire parent container (ScrollElement)
co... |
}
handleMouseLeave = () => {
if (this.subscription != null) {
// tell subscriber that we're not on canvas
this.subscription({ leftOffset: 0, date: 0, isCursorOverCanvas: false })
}
}
handleMouseMoveSubscribe = sub => {
this.subscription = sub
return () => {
this.subscription... | {
const { pageX } = evt
// FIXME: dont use getBoundingClientRect. Use passed in scroll amount
const { left: containerLeft } = this.containerEl.getBoundingClientRect()
// number of pixels from left we are on canvas
// we do this calculation as pageX is based on x from viewport whereas
... | conditional_block |
MarkerCanvas.js | import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'
// expand to fill entire parent container (ScrollElement)
co... |
}
const MarkerCanvasWrapper = props => (
<TimelineStateConsumer>
{({ getDateFromLeftOffsetPosition }) => (
<MarkerCanvas
getDateFromLeftOffsetPosition={getDateFromLeftOffsetPosition}
{...props}
/>
)}
</TimelineStateConsumer>
)
export default MarkerCanvasWrapper
| {
return (
<MarkerCanvasProvider value={this.state}>
<div
style={staticStyles}
onMouseMove={this.handleMouseMove}
onMouseLeave={this.handleMouseLeave}
ref={el => (this.containerEl = el)}
>
<TimelineMarkersRenderer />
{this.props.child... | identifier_body |
MarkerCanvas.js | import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'
// expand to fill entire parent container (ScrollElement)
co... | this.subscription = null
}
}
state = {
subscribeToMouseOver: this.handleMouseMoveSubscribe
}
render() {
return (
<MarkerCanvasProvider value={this.state}>
<div
style={staticStyles}
onMouseMove={this.handleMouseMove}
onMouseLeave={this.handleMouseLe... | return () => { | random_line_split |
ckeditor__ckeditor5-engine-tests.ts | import * as engine from "@ckeditor/ckeditor5-engine";
declare let pattern: engine.view.MatcherPattern;
pattern = { name: /^p/ };
pattern = {
attributes: {
title: "foobar",
foo: /^\w+/,
bar: true,
},
};
pattern = {
classes: "foobar",
};
pattern = {
classes: /foo.../,
};
patt... | };
declare let viewDefinition: engine.view.ElementDefinition;
viewDefinition = "p";
viewDefinition = {
name: "h1",
classes: ["foo", "bar"],
};
viewDefinition = {
name: "span",
styles: {
"font-size": "12px",
"font-weight": "bold",
},
attributes: {
"data-id": "123",
... | return { name: true, attribute: ["font-size"] };
}
}
return null; | random_line_split |
ckeditor__ckeditor5-engine-tests.ts | import * as engine from "@ckeditor/ckeditor5-engine";
declare let pattern: engine.view.MatcherPattern;
pattern = { name: /^p/ };
pattern = {
attributes: {
title: "foobar",
foo: /^\w+/,
bar: true,
},
};
pattern = {
classes: "foobar",
};
pattern = {
classes: /foo.../,
};
patt... |
return null;
};
declare let viewDefinition: engine.view.ElementDefinition;
viewDefinition = "p";
viewDefinition = {
name: "h1",
classes: ["foo", "bar"],
};
viewDefinition = {
name: "span",
styles: {
"font-size": "12px",
"font-weight": "bold",
},
attributes: {
"d... | {
const fontSize = element.getStyle("font-size")!;
const size = fontSize.match(/(\d+)/px);
if (size && Number(size[1]) > 26) {
return { name: true, attribute: ["font-size"] };
}
} | conditional_block |
nk.rs | %-------------------------------------------------------------
% Nonlinear New Keynesian Model
% Reference: Foerster, Rubio-Ramirez, Waggoner and Zha (2013)
% Perturbation Methods for Markov Switching Models.
%------------------------------------------------------------- |
exogenous EPS_R "Monetary policy shock"
parameters betta, eta, kappa, rhor sigr a_tp_1_2, a_tp_2_1
parameters(a,2) mu, psi
model
1=betta*(1-.5*kappa*(PAI-1)^2)*Y*R/((1-.5*kappa*(PAI{+1}-1)^2)*Y{+1}*exp(mu)*PAI{+1});
1-eta+eta*(1-.5*kappa*(PAI-1)^2)*Y+betta*kappa*(1-.5*kappa*(PAI-1)^2)*(PAI{+1}-1)*PAI{+1}/(1-.5*... |
endogenous PAI, "Inflation", Y, "Output gap", R, "Interest rate" | random_line_split |
shl.rs | #![feature(core, core_simd)]
extern crate core;
#[cfg(test)]
mod tests {
use core::simd::i32x4;
// #[simd]
// #[derive(Copy, Clone, Debug)]
// #[repr(C)]
// pub struct i32x4(pub i32, pub i32, pub i32, pub i32);
#[test]
fn | () {
let x: i32x4 = i32x4(
0, 1, 2, 3
);
let y: i32x4 = i32x4(
2, 2, 2, 2
);
let z: i32x4 = x << y;
let result: String = format!("{:?}", z);
assert_eq!(result, "i32x4(0, 4, 8, 12)".to_string());
}
}
| shl_test1 | identifier_name |
shl.rs | #![feature(core, core_simd)]
extern crate core;
#[cfg(test)]
mod tests {
use core::simd::i32x4;
// #[simd]
// #[derive(Copy, Clone, Debug)]
// #[repr(C)]
// pub struct i32x4(pub i32, pub i32, pub i32, pub i32);
#[test]
fn shl_test1() {
let x: i32x4 = i32x4(
0, 1, 2, 3
); | );
let z: i32x4 = x << y;
let result: String = format!("{:?}", z);
assert_eq!(result, "i32x4(0, 4, 8, 12)".to_string());
}
} | let y: i32x4 = i32x4(
2, 2, 2, 2 | random_line_split |
shl.rs | #![feature(core, core_simd)]
extern crate core;
#[cfg(test)]
mod tests {
use core::simd::i32x4;
// #[simd]
// #[derive(Copy, Clone, Debug)]
// #[repr(C)]
// pub struct i32x4(pub i32, pub i32, pub i32, pub i32);
#[test]
fn shl_test1() |
}
| {
let x: i32x4 = i32x4(
0, 1, 2, 3
);
let y: i32x4 = i32x4(
2, 2, 2, 2
);
let z: i32x4 = x << y;
let result: String = format!("{:?}", z);
assert_eq!(result, "i32x4(0, 4, 8, 12)".to_string());
} | identifier_body |
configs.py | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common configs for compatibility_lib a... |
return url
# IGNORED_DEPENDENCIES are not direct dependencies for many packages and are
# not installed via pip, resulting in unresolvable high priority warnings.
IGNORED_DEPENDENCIES = [
'pip',
'setuptools',
'wheel',
'virtualenv',
]
# If updating this list, make sure to update the whitelist as ... | url = '{}#subdirectory={}'.format(url, setuppy_path) | conditional_block |
configs.py | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common configs for compatibility_lib a... | _format_url('googleapis/google-cloud-python', 'websecurityscanner'):
'google-cloud-websecurityscanner',
_format_url('googleapis/google-cloud-python', 'api_core'):
'google-api-core',
_format_url('googleapis/google-cloud-python', 'bigquery'):
'google-cloud-bigquery',
_format_url('g... | random_line_split | |
configs.py | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common configs for compatibility_lib a... | (repo_name, setuppy_path=''):
url = 'git+git://github.com/{}.git'.format(repo_name)
if setuppy_path != '':
url = '{}#subdirectory={}'.format(url, setuppy_path)
return url
# IGNORED_DEPENDENCIES are not direct dependencies for many packages and are
# not installed via pip, resulting in unresolvable... | _format_url | identifier_name |
configs.py | agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common configs for compatibility_lib a... |
# IGNORED_DEPENDENCIES are not direct dependencies for many packages and are
# not installed via pip, resulting in unresolvable high priority warnings.
IGNORED_DEPENDENCIES = [
'pip',
'setuptools',
'wheel',
'virtualenv',
]
# If updating this list, make sure to update the whitelist as well with the
#... | url = 'git+git://github.com/{}.git'.format(repo_name)
if setuppy_path != '':
url = '{}#subdirectory={}'.format(url, setuppy_path)
return url | identifier_body |
autopaginator.py | try:
set
except NameError:
from sets import Set as set
from django.core.paginator import Paginator, Page, InvalidPage
from django.db.models import F
from django.http import Http404
from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSynta... | (Extension):
"""
Applies pagination to the given dataset (and saves truncated
dataset to the context variable), sets context variable with
data enough to build html for paginator
General syntax:
{% autopaginate dataset [as ctx_variable] %}
if "as" part is omitted, trying to save truncated... | AutopaginateExtension | identifier_name |
autopaginator.py | try:
set
except NameError:
from sets import Set as set
from django.core.paginator import Paginator, Page, InvalidPage
from django.db.models import F
from django.http import Http404
from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSynta... |
pages.extend(second_list)
else:
unioned = list(first.union(current))
unioned.sort()
pages.extend(unioned)
# If there's no overlap between the current set of pages and the last
# set of pages, then there's a possible nee... | pages.append(None) | conditional_block |
autopaginator.py | try:
set
except NameError:
from sets import Set as set
from django.core.paginator import Paginator, Page, InvalidPage
from django.db.models import F
from django.http import Http404
from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSynta... | if self._count is None:
try:
self.parentcomments = self.object_list.filter(
parent__isnull=True)
self._count = self.parentcomments.count()
except (AttributeError, TypeError):
# AttributeError if object_list has no count(... | def _get_count(self):
"Returns the total number of objects, across all pages." | random_line_split |
autopaginator.py | try:
set
except NameError:
from sets import Set as set
from django.core.paginator import Paginator, Page, InvalidPage
from django.db.models import F
from django.http import Http404
from coffin import template
from jinja2 import nodes
from jinja2.ext import Extension
from jinja2.exceptions import TemplateSynta... |
def _get_count(self):
"Returns the total number of objects, across all pages."
if self._count is None:
try:
self.parentcomments = self.object_list.filter(
parent__isnull=True)
self._count = self.parentcomments.count()
exce... | "Returns a Page object for the given 1-based page number."
number = self.validate_number(number)
if self.count == 0:
return Page(self.object_list, number, self)
bottom = (number - 1) * self.per_page
bottomdate = self.parentcomments[bottom].sortdate
top = bottom + self... | identifier_body |
core_view.js | import {
ActionHandler,
Evented,
FrameworkObject,
deprecateUnderscoreActions
} from 'ember-runtime';
import { initViewElement } from '../system/utils';
import { cloneStates, states } from './states';
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view ... | (name, ...args) {
this._super(...arguments);
let method = this[name];
if (typeof method === 'function') {
return method.apply(this, args);
}
},
has(name) {
return typeof this[name] === 'function' || this._super(name);
}
});
deprecateUnderscoreActions(CoreView);
CoreView.reopenClass({
... | trigger | identifier_name |
core_view.js | import {
ActionHandler,
Evented,
FrameworkObject,
deprecateUnderscoreActions
} from 'ember-runtime';
import { initViewElement } from '../system/utils';
import { cloneStates, states } from './states';
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view ... |
},
has(name) {
return typeof this[name] === 'function' || this._super(name);
}
});
deprecateUnderscoreActions(CoreView);
CoreView.reopenClass({
isViewFactory: true
});
export default CoreView;
| {
return method.apply(this, args);
} | conditional_block |
core_view.js | import {
ActionHandler,
Evented,
FrameworkObject,
deprecateUnderscoreActions
} from 'ember-runtime';
import { initViewElement } from '../system/utils';
import { cloneStates, states } from './states';
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view ... |
});
deprecateUnderscoreActions(CoreView);
CoreView.reopenClass({
isViewFactory: true
});
export default CoreView;
| {
return typeof this[name] === 'function' || this._super(name);
} | identifier_body |
core_view.js | import {
ActionHandler,
Evented,
FrameworkObject,
deprecateUnderscoreActions
} from 'ember-runtime';
import { initViewElement } from '../system/utils';
import { cloneStates, states } from './states';
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view ... | @private
*/
parentView: null,
instrumentDetails(hash) {
hash.object = this.toString();
hash.containerKey = this._debugContainerKey;
hash.view = this;
return hash;
},
/**
Override the default event firing from `Ember.Evented` to
also call methods with the given name.
@method ... | @type Ember.View
@default null | random_line_split |
deriving-span-PartialOrd-tuple-struct.rs | // Copyright 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-MIT or ... | ;
#[derive(PartialOrd,PartialEq)]
struct Struct(
Error //~ ERROR
//~^ ERROR
//~^^ ERROR
//~^^^ ERROR
//~^^^^ ERROR
//~^^^^^ ERROR
//~^^^^^^ ERROR
//~^^^^^^^ ERROR
//~^^^^^^^^ ERROR
);
fn main() {}
| Error | identifier_name |
deriving-span-PartialOrd-tuple-struct.rs | // Copyright 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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This file was... | random_line_split | |
call_request.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 option) any later version.... |
/// Call request
#[derive(Debug, Default, PartialEq, Deserialize)]
pub struct CallRequest {
/// From
pub from: Option<H160>,
/// To
pub to: Option<H160>,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: Option<U256>,
/// Gas
pub gas: Option<U256>,
/// Value
pub value: Option<U256>,
/// Data
pub da... | // You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use v1::helpers::CallRequest as Request;
use v1::types::{Bytes, H160, U256}; | random_line_split |
call_request.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 option) any later version.... | () {
let s = r#"{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}"#;
let... | call_request_deserialize2 | identifier_name |
call_request.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 option) any later version.... |
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use serde_json;
use v1::types::{U256, H160};
use super::CallRequest;
#[test]
fn call_request_deserialize() {
let s = r#"{
"from":"0x0000000000000000000000000000000000000001",
"to":"0x0000000000000000000000000000000000... | {
Request {
from: self.from.map(Into::into),
to: self.to.map(Into::into),
gas_price: self.gas_price.map(Into::into),
gas: self.gas.map(Into::into),
value: self.value.map(Into::into),
data: self.data.map(Into::into),
nonce: self.nonce.map(Into::into),
}
} | identifier_body |
token.rs | => true, // in lambda syntax
OrOr => true, // in lambda syntax
AndAnd => true, // double borrow
DotDot => true, // range notation
ModSep => true,
Interpolated(NtExpr(..)) ... | (&self) -> bool {
match *self {
Literal(_, _) => true,
_ => false,
}
}
/// Returns `true` if the token is an identifier.
pub fn is_ident(&self) -> bool {
match *self {
Ident(_, _) => true,
_ => false,
}
}... | is_lit | identifier_name |
token.rs | (SELF_KEYWORD_NAME_NUM);
const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM);
pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
const STATIC_KEYWORD_NA... | {
get_name(ident.name)
} | identifier_body | |
token.rs | Tilde => true,
Literal(_, _) => true,
Not => true,
BinOp(Minus) => true,
BinOp(Star) => true,
BinOp(And) => true,
BinOp(Or) ... | OpenDelim(_) => true,
Ident(_, _) => true,
Underscore => true, | random_line_split | |
testGoButton.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Include required modules
var { assert, expect } = require("../../../../lib/assertions");
var tab... | locationBar.focus({type: "shortcut"});
locationBar.type(TEST_DATA[1]);
assert.waitFor(function () {
return locationBar.value === TEST_DATA[1];
}, "Location bar contains the typed data - expected '" + TEST_DATA[1] + "'");
assert.ok(utils.isDisplayed(controller, goButton), "Go button is visible");
// Cl... | // Focus and type a URL; a second local page into the location bar | random_line_split |
clean_mac_info_plist.py | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Nichts-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./... | lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open(outFile, "w");
fOut.write(... | for line in open(fileForGrabbingVersion):
| random_line_split |
clean_mac_info_plist.py | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the Nichts-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./... |
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open(outFile, "w");
fOut.write(newFileContent);
print "Info.plist fresh created"
| lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", ""); | conditional_block |
company.service.spec.ts | import { BaseRequestOptions, ConnectionBackend, Http, Response, ResponseOptions } from '@angular/http';
import { TestBed, async } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { Observable } from 'rxjs/Observable';
import { CompanyService } from './company.service';
export... | {
provide: Http,
useFactory: (backend: ConnectionBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
]
});
});
it('should return an Observable when get called', async(() => {
e... | BaseRequestOptions, | random_line_split |
company.service.spec.ts | import { BaseRequestOptions, ConnectionBackend, Http, Response, ResponseOptions } from '@angular/http';
import { TestBed, async } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { Observable } from 'rxjs/Observable';
import { CompanyService } from './company.service';
export... | () {
describe('Scientist Service', () => {
let nameListService: CompanyService;
let mockBackend: MockBackend;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
CompanyService,
MockBackend,
BaseRequestOptions,
{
provide: Htt... | main | identifier_name |
company.service.spec.ts | import { BaseRequestOptions, ConnectionBackend, Http, Response, ResponseOptions } from '@angular/http';
import { TestBed, async } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing';
import { Observable } from 'rxjs/Observable';
import { CompanyService } from './company.service';
export... |
it('should return an Observable when get called', async(() => {
expect(TestBed.get(CompanyService).list()).toEqual(jasmine.any(Observable));
}));
it('should resolve to list of names when get called', async(() => {
let nameListService = TestBed.get(CompanyService);
let mockBackend = TestB... | {
describe('Scientist Service', () => {
let nameListService: CompanyService;
let mockBackend: MockBackend;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
CompanyService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
... | identifier_body |
test_url.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... | self.port = port
self.userid = userid
self.password = password
self.path = path
def __call__(self, test):
url = URL(self.url)
test.assertEqual(url.adapter, self.adapter)
test.assertEqual(url.scheme, self.scheme)
test.assertEqual(url.host, self.host)
... | self.url = url
self.adapter = adapter
self.scheme = scheme
self.host = host | random_line_split |
test_url.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... |
def test_is_ssl(self):
# false
url = URL('amqp://localhost')
self.assertFalse(url.is_ssl())
# true
url = URL('amqps://localhost')
self.assertTrue(url.is_ssl())
def test_hash(self):
url = URL('test')
self.assertEqual(hash(url), hash(url.canonical... | url = URL(_url)
self.assertEqual(url.canonical, _url.split('+')[-1].rsplit('/all')[0]) | conditional_block |
test_url.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... | for n in PORT:
self.assertEqual(Scheme.validated(n), n.lower())
self.assertRaises(ValueError, Scheme.validated, 'unsupported') | identifier_body | |
test_url.py | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... | (object):
def __init__(self,
url,
adapter=None,
scheme=None,
host=None,
port=None,
userid=None,
password=None,
path=None):
self.url = url
self.adapter = adapter
... | Test | identifier_name |
user_timeline_event.py | # listenbrainz-server - Server for the ListenBrainz project.
#
# Copyright (C) 2021 Param Singh <me@param.codes>
#
# 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 2 of the License... | (user_id: int, count: int = 50) -> List[UserTimelineEvent]:
""" Gets track recommendation events created by the specified user.
The optional `count` parameter can be used to control the number of events being returned.
"""
return get_user_timeline_events(
user_id=user_id,
event_type=Use... | get_user_track_recommendation_events | identifier_name |
user_timeline_event.py | # listenbrainz-server - Server for the ListenBrainz project.
#
# Copyright (C) 2021 Param Singh <me@param.codes>
#
# 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 2 of the License... | LIMIT :count
"""), {
'user_id': user_id,
'event_type': event_type.value,
'count': count,
})
return [UserTimelineEvent(**row) for row in result.fetchall()]
def get_user_track_recommendation_events(user_id: int, count: int = 50) -> List[UserTimel... | WHERE user_id = :user_id
AND event_type = :event_type
ORDER BY created | random_line_split |
user_timeline_event.py | # listenbrainz-server - Server for the ListenBrainz project.
#
# Copyright (C) 2021 Param Singh <me@param.codes>
#
# 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 2 of the License... | })
return [UserTimelineEvent(**row) for row in result.fetchall()]
def get_user_notification_events(user_id: int, count: int = 50) -> List[UserTimelineEvent]:
""" Gets notification posted on the user's timeline.
The optional `count` parameter can be used to control the number of events being... | """ Gets a list of recording_recommendation events for specified users.
user_ids is a tuple of user row IDs.
"""
with db.engine.connect() as connection:
result = connection.execute(sqlalchemy.text("""
SELECT id, user_id, event_type, metadata, created
FROM user_timeline_eve... | identifier_body |
mididevice.py | Returns a list of the available MIDI Input Devices.
# @return List of tuples "(portNum, portName)".
def getMIDIInDevices():
midi = rtmidi.RtMidiIn()
return list((port, midi.getPortName(port)) for port in range(midi.getPortCount()))
##
# Returns a list of the available MIDI Output Devices.
# @return List of... | return v
def __iter__(self):
return (tag for tag in self.tags)
def items(self):
for key in iter(self):
yield key, self[key]
def keys(self):
return iter(self)
##
# Sends the MIDI messages that will select this voice on the given device.
# @return None.
def pc(self):
self.devi... | y:
v = getattr(v, k)
except AttributeError:
raise KeyError('Unable to find key {}.'.format(key))
| conditional_block |
mididevice.py | Returns a list of the available MIDI Input Devices.
# @return List of tuples "(portNum, portName)".
def getMIDIInDevices():
midi = rtmidi.RtMidiIn()
return list((port, midi.getPortName(port)) for port in range(midi.getPortCount()))
##
# Returns a list of the available MIDI Output Devices.
# @return List o... | self.midiOutDevice.sendMessage(data)
##
# Class representing a MIDI Output Device.
class MIDIOutDevice(MIDIDevice):
ID = 'Generic USB-MIDI Device'
## Number of the note "A0", usually the lowest supported note on the MIDI device.
noteNumA0 = 21
## Offsets for the different note letters
noteOffsets... | data.setChannel(self.midiOutChannel)
if self.midiOutDevice is not None: | random_line_split |
mididevice.py | @return List of tuples "(portNum, portName)".
def getMIDIInDevices():
midi = rtmidi.RtMidiIn()
return list((port, midi.getPortName(port)) for port in range(midi.getPortCount()))
##
# Returns a list of the available MIDI Output Devices.
# @return List of tuples "(portNum, portName)".
def getMIDIOutDevices():... | tVoiceList(s | identifier_name | |
mididevice.py | Returns a list of the available MIDI Input Devices.
# @return List of tuples "(portNum, portName)".
def getMIDIInDevices():
midi = rtmidi.RtMidiIn()
return list((port, midi.getPortName(port)) for port in range(midi.getPortCount()))
##
# Returns a list of the available MIDI Output Devices.
# @return List o... | if channel is not None and 0 > channel > 15:
raise ValueError('Unexpected channel value "{0}". Expected integer 0-15 or "None".'.format(channel))
with self.forwardingLock:
self.midiOutDevice = midiOutDevice
self.midiOutChannel = channel
def onMIDIMsg(self, data):
# print 'id(self): onM... | f __init__(self, id):
self.midi = rtmidi.RtMidiIn()
self.midi.setCallback(self.onMIDIMsg)
MIDIDevice.__init__(self, id)
self.midiOutDevice = None
self.midiOutChannel = None
self.forwardingLock = threading.Lock()
##
# Enables/disables forwarding of incoming MIDI events to the given output d... | identifier_body |
lib.rs | ::Any;
use std::sync::Arc;
use std::path::PathBuf;
use std::cmp::Ordering;
pub use mouse::MouseButton;
pub use keyboard::Key;
pub use controller::{ControllerAxisArgs, ControllerButton, ControllerHat};
pub mod controller;
pub mod keyboard;
pub mod mouse;
pub use after_render::{AfterRenderArgs, AfterRenderEvent};
pub ... | /// Time stamp is ignored both when comparing custom events for equality and order.
Custom(EventId, Arc<dyn Any + Send + Sync>, Option<TimeStamp>),
}
impl fmt::Debug for Event {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Event::Input(ref input, _) => write!(f, ... | /// When comparing partial order of two custom events,
/// the event ids are checked and if they are equal it returns `None`.
/// | random_line_split |
lib.rs | Any;
use std::sync::Arc;
use std::path::PathBuf;
use std::cmp::Ordering;
pub use mouse::MouseButton;
pub use keyboard::Key;
pub use controller::{ControllerAxisArgs, ControllerButton, ControllerHat};
pub mod controller;
pub mod keyboard;
pub mod mouse;
pub use after_render::{AfterRenderArgs, AfterRenderEvent};
pub us... |
}
impl From<MouseButton> for Button {
fn from(btn: MouseButton) -> Self {
Button::Mouse(btn)
}
}
impl From<ControllerButton> for Button {
fn from(btn: ControllerButton) -> Self {
Button::Controller(btn)
}
}
impl From<ButtonArgs> for Input {
fn from(args: ButtonArgs) -> Self {
... | {
Button::Keyboard(key)
} | identifier_body |
lib.rs | Any;
use std::sync::Arc;
use std::path::PathBuf;
use std::cmp::Ordering;
pub use mouse::MouseButton;
pub use keyboard::Key;
pub use controller::{ControllerAxisArgs, ControllerButton, ControllerHat};
pub mod controller;
pub mod keyboard;
pub mod mouse;
pub use after_render::{AfterRenderArgs, AfterRenderEvent};
pub us... | (key: Key) -> Self {
Button::Keyboard(key)
}
}
impl From<MouseButton> for Button {
fn from(btn: MouseButton) -> Self {
Button::Mouse(btn)
}
}
impl From<ControllerButton> for Button {
fn from(btn: ControllerButton) -> Self {
Button::Controller(btn)
}
}
impl From<ButtonArgs>... | from | identifier_name |
tsxElementResolution.js | //// [tsxElementResolution.tsx]
declare namespace JSX {
interface IntrinsicElements {
foundFirst: { x: string };
'string_named';
'var';
}
}
class foundFirst { }
class Other {}
module Dotted {
export class Name { }
}
// Should find the intrinsic element, not the class element
var a = <foundFirst x="hello"... | var e = <Dotted.Name />; | random_line_split | |
tsxElementResolution.js | //// [tsxElementResolution.tsx]
declare namespace JSX {
interface IntrinsicElements {
foundFirst: { x: string };
'string_named';
'var';
}
}
class | { }
class Other {}
module Dotted {
export class Name { }
}
// Should find the intrinsic element, not the class element
var a = <foundFirst x="hello" />;
var b = <string_named />;
// TODO: This should not be a parse error (should
// parse a property name here, not identifier)
// var c = <var />;
var d = <Oth... | foundFirst | identifier_name |
Network.js | 'use strict'
const debug = require('debug')('kickthemout:Network')
const network = require('network')
const nodeARP = require('node-arp')
const getmac = require('getmac')
const oui = require('oui')
/*
* Class containing network releated functions
*/
class Network {
/*
constructor () {
this.availableInterfaces... | () {
// populate a new field 'vendor' for the hosts
if (Array.isArray(this.hosts)) {
this.hosts = this.hosts.map(function (host) {
debug('getting vendor for:', host)
host.vendor = _getVendorName(host.mac)
return host
})
} else {
return _getVendorName(this.hosts)
... | resolveVendors | identifier_name |
Network.js | 'use strict'
const debug = require('debug')('kickthemout:Network')
const network = require('network')
const nodeARP = require('node-arp')
const getmac = require('getmac')
const oui = require('oui')
/*
* Class containing network releated functions
*/
class Network {
/*
constructor () {
this.availableInterfaces... |
}
/* Private */
function _getVendorName (mac) {
var vendor = oui(mac)
return vendor ? vendor.split('\n')[0] : 'Vendor unknown'
}
module.exports = Network
| {
// populate a new field 'vendor' for the hosts
if (Array.isArray(this.hosts)) {
this.hosts = this.hosts.map(function (host) {
debug('getting vendor for:', host)
host.vendor = _getVendorName(host.mac)
return host
})
} else {
return _getVendorName(this.hosts)
}
... | identifier_body |
Network.js | 'use strict'
const debug = require('debug')('kickthemout:Network')
const network = require('network')
const nodeARP = require('node-arp')
const getmac = require('getmac')
const oui = require('oui')
/*
* Class containing network releated functions
*/
class Network {
/*
constructor () {
this.availableInterfaces... |
}
resolveVendors () {
// populate a new field 'vendor' for the hosts
if (Array.isArray(this.hosts)) {
this.hosts = this.hosts.map(function (host) {
debug('getting vendor for:', host)
host.vendor = _getVendorName(host.mac)
return host
})
} else {
return _getVen... | {
var ip = LAN + '.' + i
;(function (ip) {
// Ping Sweep
nodeARP.getMAC(ip, function (err, mac) {
if (!err && mac) {
if (getmac.isMac(mac)) {
result.push({ip: ip, mac: mac})
}
}
if ((++count) > 254) {
self.host... | conditional_block |
Network.js | 'use strict'
const debug = require('debug')('kickthemout:Network')
const network = require('network')
const nodeARP = require('node-arp')
const getmac = require('getmac')
const oui = require('oui')
/*
* Class containing network releated functions
*/
class Network {
/*
constructor () {
this.availableInterfaces... | // populate a new field 'vendor' for the hosts
if (Array.isArray(this.hosts)) {
this.hosts = this.hosts.map(function (host) {
debug('getting vendor for:', host)
host.vendor = _getVendorName(host.mac)
return host
})
} else {
return _getVendorName(this.hosts)
}
... | }
resolveVendors () { | random_line_split |
utils.py | from corehq.apps.reports.util import get_INFilter_element_bindparam
from dimagi.utils.couch.database import get_db
from corehq.apps.domain.utils import DOMAIN_MODULE_KEY
import fluff
def flat_field(fn):
def getter(item):
return unicode(fn(item) or "")
return fluff.FlatField(getter)
def add_to_module... |
def clean_IN_filter_value(filter_values, filter_value_name):
if filter_value_name in filter_values:
for i, val in enumerate(filter_values[filter_value_name]):
filter_values[get_INFilter_element_bindparam(filter_value_name, i)] = val
del filter_values[filter_value_name]
return filt... | db = get_db()
if db.doc_exist(DOMAIN_MODULE_KEY):
module_config = db.open_doc(DOMAIN_MODULE_KEY)
module_map = module_config.get('module_map')
if module_map:
module_map[domain] = module
else:
module_config['module_map'][domain] = module
else:
module... | identifier_body |
utils.py | from corehq.apps.reports.util import get_INFilter_element_bindparam
from dimagi.utils.couch.database import get_db
from corehq.apps.domain.utils import DOMAIN_MODULE_KEY
import fluff
def flat_field(fn):
def getter(item):
return unicode(fn(item) or "")
return fluff.FlatField(getter)
def | (domain, module):
db = get_db()
if db.doc_exist(DOMAIN_MODULE_KEY):
module_config = db.open_doc(DOMAIN_MODULE_KEY)
module_map = module_config.get('module_map')
if module_map:
module_map[domain] = module
else:
module_config['module_map'][domain] = module
... | add_to_module_map | identifier_name |
utils.py | from corehq.apps.reports.util import get_INFilter_element_bindparam
from dimagi.utils.couch.database import get_db
from corehq.apps.domain.utils import DOMAIN_MODULE_KEY
import fluff
| return unicode(fn(item) or "")
return fluff.FlatField(getter)
def add_to_module_map(domain, module):
db = get_db()
if db.doc_exist(DOMAIN_MODULE_KEY):
module_config = db.open_doc(DOMAIN_MODULE_KEY)
module_map = module_config.get('module_map')
if module_map:
modu... |
def flat_field(fn):
def getter(item): | random_line_split |
utils.py | from corehq.apps.reports.util import get_INFilter_element_bindparam
from dimagi.utils.couch.database import get_db
from corehq.apps.domain.utils import DOMAIN_MODULE_KEY
import fluff
def flat_field(fn):
def getter(item):
return unicode(fn(item) or "")
return fluff.FlatField(getter)
def add_to_module... |
else:
module_config['module_map'][domain] = module
else:
module_config = db.save_doc(
{
'_id': DOMAIN_MODULE_KEY,
'module_map': {
domain: module
}
}
)
db.save_doc(module_config)
def... | module_map[domain] = module | conditional_block |
class-poly-methods-cross-crate.rs | // Copyright 2012-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... | () {
let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!['p']);
let mut kitty = cat(1000_usize, 2, vec!["tabby".to_string()]);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec![1_usize,2_usize,3_usize]);
assert_eq!(nyan.meow_count(), 55_usize);
kitty.speak(vec!["meow"... | main | identifier_name |
class-poly-methods-cross-crate.rs | // Copyright 2012-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... | {
let mut nyan : cat<char> = cat::<char>(52_usize, 99, vec!['p']);
let mut kitty = cat(1000_usize, 2, vec!["tabby".to_string()]);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak(vec![1_usize,2_usize,3_usize]);
assert_eq!(nyan.meow_count(), 55_usize);
kitty.speak(vec!["meow".to... | identifier_body | |
class-poly-methods-cross-crate.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.
// run-pass
// aux-build:cci_class_6.rs
extern crate cci_class_6;
use cci_class_6::kitt... | // Copyright 2012-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 | |
package_commands.py | import glob
import os
from qgis.core import QgsApplication
from command import command, complete_with
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QDesktopServices
folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
"commandbar")
def packages(argname, data):
retu... | (packagename):
"""
Edit a package file
"""
packagepath = os.path.join(folder, packagename)
if not packagename.endswith(".py"):
packagepath += ".py"
open_file(packagepath)
def open_file(path):
import subprocess
try:
subprocess.Popen([os.environ['EDITOR'], path])
exc... | edit_package | identifier_name |
package_commands.py | import glob
import os
from qgis.core import QgsApplication
from command import command, complete_with
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QDesktopServices
folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
"commandbar")
def packages(argname, data):
retu... | def define_package(packagename):
"""
Define new command bar package file
"""
packagename = packagename.replace(" ", "_")
packagepath = os.path.join(folder, packagename) + ".py"
with open(packagepath, 'w') as f:
f.write("""# Package file for QGIS command bar plugin
from q... | @command("Package name") | random_line_split |
package_commands.py | import glob
import os
from qgis.core import QgsApplication
from command import command, complete_with
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QDesktopServices
folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
"commandbar")
def packages(argname, data):
retu... |
open_file(packagepath)
def open_file(path):
import subprocess
try:
subprocess.Popen([os.environ['EDITOR'], path])
except KeyError:
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
@command("Package name")
def define_package(packagename):
"""
Define new command bar package... | packagepath += ".py" | conditional_block |
package_commands.py | import glob
import os
from qgis.core import QgsApplication
from command import command, complete_with
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QDesktopServices
folder = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
"commandbar")
def packages(argname, data):
retu... |
def open_file(path):
import subprocess
try:
subprocess.Popen([os.environ['EDITOR'], path])
except KeyError:
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
@command("Package name")
def define_package(packagename):
"""
Define new command bar package file
"""
packagenam... | """
Edit a package file
"""
packagepath = os.path.join(folder, packagename)
if not packagename.endswith(".py"):
packagepath += ".py"
open_file(packagepath) | identifier_body |
civ5map.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
us... | width: width,
height: height,
playercount: playercount,
flags: flags,
terrain: terrain_list,
features1: feature1_list,
features2: feature2_list,
resources: resource_list,
name: mapname,
description: mapdesc,
unknown: unknown,
}
... | random_line_split | |
civ5map.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
us... | (path: &Path) -> TerrainMap {
let mut fp = File::open(path).unwrap();
let mh = load_map_header(&mut fp);
let tiles = load_map_tiles(&mut fp, mh.width * mh.height);
let mut mapdata: Vec<Terrain> = Vec::new();
let name2terrain = HashMap::<&str, Terrain>::from_iter(vec![
("TERRAIN_COAST", T... | load_civ5map | identifier_name |
civ5map.rs | // Copyright 2015 Virgil Dupras
//
// This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
// which should be included with this package. The terms are also available at
// http://www.gnu.org/licenses/gpl-3.0.html
//
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
us... |
fn load_map_header(fp: &mut File) -> MapHeader {
let version = fp.read_u8().unwrap();
let width = fp.read_u32::<LittleEndian>().unwrap();
let height = fp.read_u32::<LittleEndian>().unwrap();
let playercount = fp.read_u8().unwrap();
let flags = fp.read_u32::<LittleEndian>().unwrap();
let terrai... | {
let s = read_str(fp, len);
let result: Vec<String> = s.split('\0').map(|s| s.to_string()).collect();
result
} | identifier_body |
non-exhaustive-match-nested.rs | // Copyright 2012-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... |
fn main() {
let x = a(c);
match x { //~ ERROR non-exhaustive patterns: `a(c)` not covered
a(d) => { fail!("hello"); }
b => { fail!("goodbye"); }
}
}
| {
match (l1, l2) { //~ ERROR non-exhaustive patterns: `(Some([]), Err(_))` not covered
(Some([]), Ok([])) => "Some(empty), Ok(empty)",
(Some([_, ..]), Ok(_)) | (Some([_, ..]), Err(())) => "Some(non-empty), any",
(None, Ok([])) | (None, Err(())) | (None, Ok([_])) => "None, Ok(less than one el... | identifier_body |
non-exhaustive-match-nested.rs | // Copyright 2012-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... | { c, d }
fn match_nested_vecs<'a, T>(l1: Option<&'a [T]>, l2: Result<&'a [T], ()>) -> &'static str {
match (l1, l2) { //~ ERROR non-exhaustive patterns: `(Some([]), Err(_))` not covered
(Some([]), Ok([])) => "Some(empty), Ok(empty)",
(Some([_, ..]), Ok(_)) | (Some([_, ..]), Err(())) => "Some(non-e... | u | identifier_name |
non-exhaustive-match-nested.rs | // Copyright 2012-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 | enum u { c, d }
fn match_nested_vecs<'a, T>(l1: Option<&'a [T]>, l2: Result<&'a [T], ()>) -> &'static str {
match (l1, l2) { //~ ERROR non-exhaustive patterns: `(Some([]), Err(_))` not covered
(Some([]), Ok([])) => "Some(empty), Ok(empty)",
(Some([_, ..]), Ok(_)) | (Some([_, ..]), Err(())) => "Some... | // <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.
enum t { a(u), b } | random_line_split |
polyfills.ts | // Copyright 2018 Google Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | /** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
/** ALL Firefox browsers require the following to support `@angular/animation`. **/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/*************************************************... | /** IE10 and IE11 requires the following to support `@angular/animation`. */
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
| random_line_split |
polyfills.ts | // Copyright 2018 Google Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {
(window as any).global = window;
} | conditional_block | |
bill.js | /*! 一叶孤舟 | qq:28701884 | 欢迎指教 */
var bill = bill || {};
//初始化
bill.init = function (){
if (com.store){
clearInterval(bill.timer);
bill.setBillList(com.arr2Clone(com.initMap)); //写入棋谱列表
play.isPlay=false;
com.show();
}else {
bill.timer = setInterval("bill.i | = function (map){
var list=com.get("billList")
for (var i=0; i < com.store.length ; i++){
var option = document.createElement('option');
option.text='棋谱'+(i+1);
option.value=i;
list.add(option , null);
}
list.addEventListener("change", function(e) {
bill.setBox (com.store[this.value], map)
})
bill.s... | nit()",300);
}
}
//把所有棋谱写入棋谱列表
bill.setBillList | conditional_block |
bill.js | /*! 一叶孤舟 | qq:28701884 | 欢迎指教 */
var bill = bill || {};
//初始化
bill.init = function (){
if (com.store){
clearInterval(bill.timer);
bill.setBillList(com.arr2Clone(com.initMap)); //写入棋谱列表
play.isPlay=false;
com.show(); | }
}
//把所有棋谱写入棋谱列表
bill.setBillList = function (map){
var list=com.get("billList")
for (var i=0; i < com.store.length ; i++){
var option = document.createElement('option');
option.text='棋谱'+(i+1);
option.value=i;
list.add(option , null);
}
list.addEventListener("change", function(e) {
bill.setBox (c... | }else {
bill.timer = setInterval("bill.init()",300); | random_line_split |
FourLetterTask.py | nTrialsPerBlock = 1
fixDur = 0.2 # before sequence
sequenceDur = 1 # when sequence is displayed
gapDur = 0.5
arrowDur = 0.5 # time arrow is on screen
respDur = 8 # max time to respond
ITI = 0.5 # time between end of one trial and beginning of next trial
IBI = 1 # time between end of block/probe and beginning of next bl... | win.flip()
# get response
key2 = event.waitKeys(keyList=['1','2','3','4','5','q','Escape'],timeStamped=trialClock)
# return results
return (key1[0],key2[0])
# =========================== #
# ===== MAIN EXPERIMENT ===== #
# =========================== #
#display instructions and wait... | trialClock.reset()
# set up stimuli
message1.setText(probe1_string)
message2.setText("1) %s\n2) %s\n3) %s\n4) %s\n5) %s" % probe1_options)
message1.draw()
message2.draw()
win.logOnFlip(level=logging.EXP, msg='Probe 1')
win.flip()
# get response
key1 = event.waitKeys(keyList=['1'... | identifier_body |
FourLetterTask.py | nTrialsPerBlock = 1
fixDur = 0.2 # before sequence
sequenceDur = 1 # when sequence is displayed
gapDur = 0.5
arrowDur = 0.5 # time arrow is on screen
respDur = 8 # max time to respond
ITI = 0.5 # time between end of one trial and beginning of next trial
IBI = 1 # time between end of block/probe and beginning of next bl... |
# declare probe parameters
probe_prob = 0 # probablilty that a given trial will be preceded by a probe
probe1_string = 'Where was your attention focused just before this?'
probe1_options = ('Completely on the task','Mostly on the task','Not sure','Mostly on inward thoughts','Completely on inward thought... | np.random.shuffle(sequences[0])
for i in range(1,len(sequences)):
np.random.shuffle(sequences[i])
while sequences[i] in sequences[0:i-1]:
np.random.shuffle(sequences[i]) | conditional_block |
FourLetterTask.py | nTrialsPerBlock = 1
fixDur = 0.2 # before sequence
sequenceDur = 1 # when sequence is displayed
gapDur = 0.5
arrowDur = 0.5 # time arrow is on screen
respDur = 8 # max time to respond
ITI = 0.5 # time between end of one trial and beginning of next trial
IBI = 1 # time between end of block/probe and beginning of next bl... | (goForward,replay):
# get trial start time
tTrial = globalClock.getTime()*1000
# reset trial clock
trialClock.reset()
# clear event buffer
event.clearEvents()
# display response direction
line.draw()
if goForward:
rightArrow.draw()
win.logOnFlip(level=loggin... | RunTrial | identifier_name |
FourLetterTask.py | nTrialsPerBlock = 1
fixDur = 0.2 # before sequence
sequenceDur = 1 # when sequence is displayed
gapDur = 0.5
arrowDur = 0.5 # time arrow is on screen
respDur = 8 # max time to respond
ITI = 0.5 # time between end of one trial and beginning of next trial
IBI = 1 # time between end of block/probe and beginning of next bl... | # ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='Subject %s, Session %s'%(expInfo['subject'],expInfo['session']))
for i in range(0,len(sequences)):
loggin... | leftArrow = visual.Polygon(win,edges=3,radius=0.5,pos=(-2,0),ori=30,lineColor='black',fillColor='black')
rightArrow = visual.Polygon(win,edges=3,radius=0.5,pos=(2,0),ori=-30,lineColor='black',fillColor='black')
| random_line_split |
user-orders.component.ts | import {Component, Input, OnInit} from "@angular/core";
import {UsersService} from "../../services/users.service";
import SalesOrderModel from "../../models/sales-order.model";
import TableModel from "../data-table/models/table.model";
import {Router} from "@angular/router";
@Component ({
selector: 'nc-user-orders... |
onEdit(): void {
this.router.navigate(['/order', this.selectSalesOrder.salesOrderId]);
}
selectState(): any {
return !this.selectSalesOrder;
}
} | {
this.selectSalesOrder = salesOrder;
} | identifier_body |
user-orders.component.ts | import {Component, Input, OnInit} from "@angular/core";
import {UsersService} from "../../services/users.service";
import SalesOrderModel from "../../models/sales-order.model";
import TableModel from "../data-table/models/table.model";
import {Router} from "@angular/router";
@Component ({
selector: 'nc-user-orders... | {
name: 'Status',
key: 'statusName'
}
]
};
constructor(private usersService: UsersService,
private router: Router){}
ngOnInit(): void {
this.usersService.getOrdersByUserId(this.userId).then(salesOrders => this.model.d... | {
name: 'Amount ($)',
key: 'totalAmount'
}, | random_line_split |
user-orders.component.ts | import {Component, Input, OnInit} from "@angular/core";
import {UsersService} from "../../services/users.service";
import SalesOrderModel from "../../models/sales-order.model";
import TableModel from "../data-table/models/table.model";
import {Router} from "@angular/router";
@Component ({
selector: 'nc-user-orders... | (): void {
this.router.navigate(['/order', this.selectSalesOrder.salesOrderId]);
}
selectState(): any {
return !this.selectSalesOrder;
}
} | onEdit | identifier_name |
test_exareme_integration_logistic_regression.py | import json
import numpy as np
import pytest
import requests
from mipframework.testutils import get_test_params
from tests import vm_url
from tests.algorithm_tests.test_logistic_regression import expected_file
headers = {"Content-type": "application/json", "Accept": "text/plain"}
url = vm_url + "LOGISTIC_REGRESSION"
... | cosine_similarity = np.dot(v, u) / (np.sqrt(np.dot(v, v)) * np.sqrt(np.dot(u, u)))
return np.isclose(abs(cosine_similarity), 1, rtol=1e-5) | identifier_body | |
test_exareme_integration_logistic_regression.py | import json
import numpy as np
import pytest
import requests | url = vm_url + "LOGISTIC_REGRESSION"
@pytest.mark.parametrize(
"test_input, expected", get_test_params(expected_file, slice(95, 100))
)
def test_logistic_regression_algorithm_exareme(test_input, expected):
result = requests.post(url, data=json.dumps(test_input), headers=headers)
result = json.loads(result... | from mipframework.testutils import get_test_params
from tests import vm_url
from tests.algorithm_tests.test_logistic_regression import expected_file
headers = {"Content-type": "application/json", "Accept": "text/plain"} | random_line_split |
test_exareme_integration_logistic_regression.py | import json
import numpy as np
import pytest
import requests
from mipframework.testutils import get_test_params
from tests import vm_url
from tests.algorithm_tests.test_logistic_regression import expected_file
headers = {"Content-type": "application/json", "Accept": "text/plain"}
url = vm_url + "LOGISTIC_REGRESSION"
... | (test_input, expected):
result = requests.post(url, data=json.dumps(test_input), headers=headers)
result = json.loads(result.text)
result = result["result"][0]["data"]
assert are_collinear(result["Coefficients"], expected["coeff"])
def are_collinear(u, v):
cosine_similarity = np.dot(v, u) / (np.s... | test_logistic_regression_algorithm_exareme | identifier_name |
LoadingUI.ts | /**
* Copyright (c) 2014,Egret-Labs.org
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of c... | ():void {
this.textField = new egret.TextField();
this.addChild(this.textField);
this.textField.y = 300;
this.textField.width = 480;
this.textField.height = 100;
this.textField.textAlign = "center";
}
public setProgress(current, total):void {
this.textFie... | createView | identifier_name |
LoadingUI.ts | /**
* Copyright (c) 2014,Egret-Labs.org
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of c... | * * Neither the name of the Egret-Labs.org nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WA... | random_line_split | |
binding.js | will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
@... |
}
}
mixinProperties(Binding, {
/*
See `Ember.Binding.from`.
@method from
@static
*/
from(from) {
var C = this;
return new C(undefined, from);
},
/*
See `Ember.Binding.to`.
@method to
@static
*/
to(to) {
var C = this;
return new C(to, undefined);
},
/**
... | {
to[key] = from[key];
} | conditional_block |
binding.js | will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
@... |
this._direction = undefined;
// if we're synchronizing from the remote object...
if (direction === 'fwd') {
var fromValue = getWithGlobals(obj, this._from);
if (log) {
Ember.Logger.log(' ', this.toString(), '->', fromValue, obj);
}
if (this._oneWay) {
trySet(obj, to... |
var fromPath = this._from;
var toPath = this._to; | random_line_split |
binding.js | var fromPath = this._from;
var toPath = this._to;
this._direction = undefined;
// if we're synchronizing from the remote object...
if (direction === 'fwd') {
var fromValue = getWithGlobals(obj, this._from);
if (log) {
Ember.Logger.log(' ', this.toString(), '->', fromValue, obj);
... | {
return new Binding(to, from).oneWay().connect(obj);
} | identifier_body | |
binding.js | It will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
... | (obj) {
Ember.assert('Must pass a valid object to Ember.Binding.connect()', !!obj);
var fromPath = this._from;
var toPath = this._to;
trySet(obj, toPath, getWithGlobals(obj, fromPath));
// add an observer on the object to be notified when the binding should be updated
addObserver(obj, fromPath... | connect | identifier_name |
index.d.ts | // Type definitions for keycloak-connect 4.5
// Project: https://github.com/keycloak/keycloak-nodejs-connect, http://keycloak.org
// Definitions by: Gregor Stamać <https://github.com/gstamac>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { RequestHandler, Request,... | exp: number;
resource_access?: any;
realm_access?: { roles?: string[] };
}
interface Token {
token: string;
clientId: string;
header?: any;
content: TokenContent;
signature?: Buffer;
signed?: string;
isExpired: () => boolean;
hasRole: (roleName: string) => boolean;
hasApplicationRo... | }
interface TokenContent { | random_line_split |
index.d.ts | // Type definitions for keycloak-connect 4.5
// Project: https://github.com/keycloak/keycloak-nodejs-connect, http://keycloak.org
// Definitions by: Gregor Stamać <https://github.com/gstamac>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { RequestHandler, Request,... | {
constructor(config: Keycloak.Config, keycloakConfig?: {} | string);
middleware(options?: Keycloak.MiddlewareOptions): RequestHandler;
protect(spec?: string | Keycloak.SpecHandler): RequestHandler;
authenticated: (request: Request) => void;
deauthenticated: (request: Request) => void;
accessDenied: (request: Re... | eycloak | identifier_name |
deriving-show-2.rs | // Copyright 2012-2013 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... | { C1(int), C2(B), C3(String) }
#[derive(Show)]
enum D { D1{ a: int } }
#[derive(Show)]
struct E;
#[derive(Show)]
struct F(int);
#[derive(Show)]
struct G(int, int);
#[derive(Show)]
struct H { a: int }
#[derive(Show)]
struct I { a: int, b: int }
#[derive(Show)]
struct J(Custom);
struct Custom;
impl fmt::Show for Custom... | C | identifier_name |
deriving-show-2.rs | // Copyright 2012-2013 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... | struct F(int);
#[derive(Show)]
struct G(int, int);
#[derive(Show)]
struct H { a: int }
#[derive(Show)]
struct I { a: int, b: int }
#[derive(Show)]
struct J(Custom);
struct Custom;
impl fmt::Show for Custom {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "yay")
}
}
trait ToShow {
... | #[derive(Show)] | random_line_split |
ipc.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::time;
use crate::time::ProfilerCategory;
use crate::time::ProfilerChan;
use ipc_channel::ipc;
use serde... | time::profile(
ProfilerCategory::IpcBytesReceiver,
None,
self.time_profile_chan.clone(),
move || self.ipc_bytes_receiver.recv(),
)
}
}
pub fn bytes_channel(
time_profile_chan: ProfilerChan,
) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Erro... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.