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 |
|---|---|---|---|---|
validators.ts | import {isBlank, isPresent, CONST_EXPR, isString} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {ObservableWrapper} from 'angular2/src/facade/async';
import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/co... |
/**
* Compose multiple validators into a single function that returns the union
* of the individual error maps.
*/
static compose(validators: ValidatorFn[]): ValidatorFn {
if (isBlank(validators)) return null;
var presentValidators = validators.filter(isPresent);
if (presentValidators.length ... | { return null; } | identifier_body |
validators.ts | import {isBlank, isPresent, CONST_EXPR, isString} from 'angular2/src/facade/lang';
import {PromiseWrapper} from 'angular2/src/facade/promise';
import {ObservableWrapper} from 'angular2/src/facade/async';
import {ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';
import {OpaqueToken} from 'angular2/co... | * Provide this using `multi: true` to add validators.
*
* See {@link NG_VALIDATORS} for more details.
*/
export const NG_ASYNC_VALIDATORS: OpaqueToken = CONST_EXPR(new OpaqueToken('NgAsyncValidators'));
/**
* Provides a set of validators used by form controls.
*
* A validator is a function that processes a {@li... |
/**
* Providers for asynchronous validators to be used for {@link Control}s
* in a form.
* | random_line_split |
vmware_vmkernel_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | vnics_with_service_type = [vnic.device for vnic in query.candidateVnic if vnic.key in selected_vnics]
return vnics_with_service_type
def gather_host_vmk_facts(self):
hosts_facts = {}
for host in self.hosts:
host_vmk_facts = []
host_network_system = host.conf... | "%s" % (service_type, to_native(e)))
if not query.selectedVnic:
return vmks_list
selected_vnics = [vnic for vnic in query.selectedVnic] | random_line_split |
vmware_vmkernel_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... |
def query_service_type_for_vmks(self, host_system, service_type):
"""
Function to return list of VMKernels
Args:
host_system: Host system managed object
service_type: Name of service type
Returns: List of VMKernel which belongs to that service type
... | vmks_list = self.query_service_type_for_vmks(host, service_type)
self.service_type_vmks[host.name][service_type] = vmks_list | conditional_block |
vmware_vmkernel_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | ():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hos... | main | identifier_name |
vmware_vmkernel_facts.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... |
if __name__ == "__main__":
main()
| argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],... | identifier_body |
postgres.py | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import copy
import logging
import django
from api.webview.models import HarvesterResponse, Document, Version
from scrapi import events
from scrapi.util import json_without_bytes
from scrapi.linter i... |
def tear_down(self):
pass
def clear(self, force=False):
pass
def celery_setup(self, *args, **kwargs):
pass
def paginated(query, page_size=10):
for offset in range(0, query.count(), page_size):
for doc in query[offset:offset + page_size]:
yield doc
clas... | return True | identifier_body |
postgres.py | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import copy
import logging
import django
from api.webview.models import HarvesterResponse, Document, Version
from scrapi import events
from scrapi.util import json_without_bytes
from scrapi.linter i... | timestamps = raw_doc.get('timestamps') or normalized.get('timestamps')
document.raw = raw_doc.attributes
document.timestamps = timestamps
document.normalized = normalized.attributes
document.providerUpdatedDateTime = normalized['providerUpdatedDateTime']
document.save()... | def process_normalized(self, raw_doc, normalized):
document = self.version(raw=raw_doc, normalized=normalized) | random_line_split |
postgres.py | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import copy
import logging
import django
from api.webview.models import HarvesterResponse, Document, Version
from scrapi import events
from scrapi.util import json_without_bytes
from scrapi.linter i... |
@property
def method(self):
return str(self.response.method)
@property
def url(self):
return str(self.response.url)
@property
def ok(self):
return bool(self.response.ok)
@property
def content(self):
if isinstance(self.response.content, memoryview):
... | self.response = args[0] | conditional_block |
postgres.py | from __future__ import absolute_import
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings")
import copy
import logging
import django
from api.webview.models import HarvesterResponse, Document, Version
from scrapi import events
from scrapi.util import json_without_bytes
from scrapi.linter i... | (self, force=False):
pass
def celery_setup(self, *args, **kwargs):
pass
def paginated(query, page_size=10):
for offset in range(0, query.count(), page_size):
for doc in query[offset:offset + page_size]:
yield doc
class PostgresProcessor(BaseProcessor):
NAME = 'postgr... | clear | identifier_name |
response.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import (
deferred, Noted, Describ... | (cls):
from sqlalchemy import orm
query = super(InterviewResponse, cls).eager_query()
return query.options(
orm.subqueryload('meetings'))
class PopulationSampleResponse(Relatable, Documentable, Personable, Response):
__mapper_args__ = {
'polymorphic_identity': 'population sample'
}
_... | eager_query | identifier_name |
response.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import (
deferred, Noted, Describ... | @classmethod
def _filter_by_request(cls, predicate):
return Request.query.filter(
(Request.id == cls.request_id) &
predicate(Request.slug)
).exists()
@classmethod
def eager_query(cls):
from sqlalchemy import orm
query = super(Response, cls).eager_query()
return query.option... |
def _display_name(self):
return u'Response with id={0} for Audit "{1}"'.format(
self.id, self.request.audit.display_name)
| random_line_split |
response.py | # Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: vraj@reciprocitylabs.com
from ggrc import db
from ggrc.models.mixins import (
deferred, Noted, Describ... |
class DocumentationResponse(Relatable, Documentable, Personable, Response):
__mapper_args__ = {
'polymorphic_identity': 'documentation'
}
_table_plural = 'documentation_responses'
_publish_attrs = []
_sanitize_html = []
class InterviewResponse(Relatable, Documentable, Personable, Response):
__... | from sqlalchemy import orm
query = super(Response, cls).eager_query()
return query.options(
orm.joinedload('request')) | identifier_body |
suggestMemory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (data: [string, MemItem][]): void {
this._cache.clear();
let seq = 0;
for (const [key, value] of data) {
value.touch = seq;
value.type = typeof value.type === 'number' ? value.type : completionKindFromLegacyString(value.type);
this._cache.set(key, value);
}
this._seq = this._cache.size;
}
}
export... | fromJSON | identifier_name |
suggestMemory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | try {
const raw = this._storageService.get(`${this._storagePrefix}/${this._mode}`, StorageScope.WORKSPACE);
if (raw) {
this._strategy.fromJSON(JSON.parse(raw));
}
} catch (e) {
// things can go wrong with JSON...
}
}
memorize(model: ITextModel, pos: IPosition, item: ICompletionItem): void {
t... | this._mode = mode;
this._strategy = mode === 'recentlyUsedByPrefix' ? new PrefixMemory() : mode === 'recentlyUsed' ? new LRUMemory() : new NoMemory();
| random_line_split |
suggestMemory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
return super.select(model, pos, items);
}
toJSON(): object {
let entries: [string, MemItem][] = [];
this._trie.forEach((value, key) => entries.push([key, value]));
// sort by last recently used (touch), then
// take the top 200 item and normalize their
// touch
entries
.sort((a, b) => -(a[1].... | {
let { kind, insertText } = items[i].suggestion;
if (kind === item.type && insertText === item.insertText) {
return i;
}
} | conditional_block |
settings.py | from os import environ
# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs
# in SESSION_CONFIGS, except those that explicitly override it.
# the session config can be accessed from methods in your apps as self.session.config,
# e.g. self.session.config['participation_fee']
SESSION_... |
# AUTH_LEVEL:
# this setting controls which parts of your site are freely accessible,
# and which are password protected:
# - If it's not set (the default), then the whole site is freely accessible.
# - If you are launching a study and want visitors to only be able to
# play your app if you provided them with a star... | CHANNEL_ROUTING = 'redirect.routing.channel_routing' | random_line_split |
TileComponent.tsx | /**
*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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
*
... | }
});
it("can render tile title and load tile string content", (done: () => void): void => {
const tile = {
title: "Penguins (order Sphenisciformes, family Spheniscidae)",
loadableContent: () => {
... | {
describe(`Tile component tests.`, (): void => {
const target = super.createTargetElement();
const tileContentPlaceholder = "Penguins (order Sphenisciformes, family Spheniscidae) are a group of aquatic, "
+ "flightless birds living almost exclusively in the south... | identifier_body |
TileComponent.tsx | /**
*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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
*
... |
return Promise.reject(errorMessage);
}
} as ITile;
this._renderComponent({
tile: tile
}, target);
const appNode = ReactDOM.findDOMNode(target);
setTimeout((): vo... | {
done();
} | conditional_block |
TileComponent.tsx | /**
*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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
*
... | const viewMoreButtonNode = appNode.querySelector(".sdl-dita-delivery-tile button") as HTMLElement;
expect(viewMoreButtonNode).not.toBeNull();
viewMoreButtonNode.click();
});
});
}
private _renderComponent(props: ITileProps, target: HT... | random_line_split | |
TileComponent.tsx | /**
*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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
*
... | (props: ITileProps, target: HTMLElement): Tile {
const comp = ReactDOM.render(
(
<ComponentWithContext {...services}>
<Tile {...props} />
</ComponentWithContext>
), target) as React.Component<{}, {}>;
return TestUtils.fin... | _renderComponent | identifier_name |
entity_set_proxy.ts | import { Component, ComponentId } from "./component";
import { ComponentDef, ComponentDefObj } from "./component_def";
import { Entity, EntityId } from "./entity";
import {
AddOptions,
CloneOptions,
EntitySet,
EntitySetOptions,
RemoveEntityType,
RemoveType
} from "./entity_set";
import { Queryab... |
query(q: string, options?: QueryOptions): Promise<QueryStack> {
return this.es.query(q, options);
}
queryEntities(q: string, options?: QueryOptions): Promise<Entity[]> {
return this.es.queryEntities(q, options);
}
async register(value: ComponentDef | ComponentDefObj | any): Promi... | {
return this.es.prepare(q, options);
} | identifier_body |
entity_set_proxy.ts | import { Component, ComponentId } from "./component";
import { ComponentDef, ComponentDefObj } from "./component_def";
import { Entity, EntityId } from "./entity";
import {
AddOptions,
CloneOptions,
EntitySet,
EntitySetOptions,
RemoveEntityType,
RemoveType
} from "./entity_set";
import { Queryab... | (value: ComponentDef | ComponentDefObj | any): Promise<ComponentDef> {
return this.es.register(value);
}
async getComponentDefs(): Promise<ComponentDef[]> {
return this.es.getComponentDefs();
}
async getComponent(id: ComponentId | Component): Promise<Component> {
return this.es... | register | identifier_name |
entity_set_proxy.ts | import { Component, ComponentId } from "./component";
import { ComponentDef, ComponentDefObj } from "./component_def";
import { Entity, EntityId } from "./entity";
import {
AddOptions,
CloneOptions,
EntitySet,
EntitySetOptions,
RemoveEntityType,
RemoveType
} from "./entity_set";
import { Queryab... | return this.es.getComponents();
}
getEntities() {
return this.es.getEntities();
}
async getEntity(eid: EntityId, populate: boolean = true): Promise<Entity> {
return this.es.getEntity(eid, populate);
}
addComponents(components: Component[], options?: AddOptions): Promi... | random_line_split | |
diaryitems.js | exports.post = function(req, res) {
var DiaryItem = require('../models/diaryItem');
var diaryitem = new DiaryItem(req.body.diaryitem);
diaryitem.addedBy = req.user._id;
diaryitem.addedByName = req.user.firstName + ' ' + req.user.lastName;
diaryitem.addedOn = new Date();
diaryitem.save(function(err) {
if(err) t... | });
};
exports.delete = function(req, res) {
var DiaryItem = require('../models/diaryItem');
var diaryitem = req.param('id');
DiaryItem.remove({_id: diaryitem}, function(err) {
if(err) throw err;
res.send(null);
});
}; | if(err) throw err;
doc.canEdit = doc.addedBy.toString() == req.user._id;
res.send({diaryitem: doc}); | random_line_split |
main.rs | use std::io;
use std::iter;
mod zipper;
fn get_numbers_divisible_by(divisor: uint, max: uint) -> Vec<uint> {
iter::count(1u, 1).
filter(|&n| n % divisor == 0).
take_while(|&n| n < max).
collect()
}
fn get_factors(number: uint) -> Vec<uint> {
iter::range(1u, number + 1).
filter(|&n| number % n... | () {
let numbers = super::get_numbers_divisible_by(2, 100);
for n in numbers.into_iter() {
let half_n: f32 = n as f32 / 2.0;
assert!(half_n == half_n.ceil());
}
}
#[test]
fn get_numbers_divisible_by_3 () {
let numbers = super::get_numbers_divisible_b... | get_numbers_divisible_by_2 | identifier_name |
main.rs | use std::io;
use std::iter;
mod zipper;
fn get_numbers_divisible_by(divisor: uint, max: uint) -> Vec<uint> |
fn get_factors(number: uint) -> Vec<uint> {
iter::range(1u, number + 1).
filter(|&n| number % n == 0).
collect()
}
#[cfg(test)]
mod test {
use std::num::Float;
use std::slice::PartialEqSliceExt;
#[test]
fn get_numbers_divisible_by_2 () {
let numbers = super::get_numbers_divisible... | {
iter::count(1u, 1).
filter(|&n| n % divisor == 0).
take_while(|&n| n < max).
collect()
} | identifier_body |
main.rs | use std::io;
use std::iter;
mod zipper;
fn get_numbers_divisible_by(divisor: uint, max: uint) -> Vec<uint> { |
fn get_factors(number: uint) -> Vec<uint> {
iter::range(1u, number + 1).
filter(|&n| number % n == 0).
collect()
}
#[cfg(test)]
mod test {
use std::num::Float;
use std::slice::PartialEqSliceExt;
#[test]
fn get_numbers_divisible_by_2 () {
let numbers = super::get_numbers_divisible_... | iter::count(1u, 1).
filter(|&n| n % divisor == 0).
take_while(|&n| n < max).
collect()
} | random_line_split |
harfbuzz.rs | }
pub fn len(&self) -> uint {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn get_entry_for_glyph(&self, i: uint, y_pos: &mut Au) -> ShapedGlyphEntry {
assert!(i < self.count);
unsafe {
let glyph_info_i = ptr... | {
max_glyph_idx = num::max(byteToGlyph[i] as uint + 1, max_glyph_idx);
} | conditional_block | |
harfbuzz.rs | {
// start by looking at just one glyph.
glyph_span.extend_by(1);
debug!("Processing glyph at idx={:u}", glyph_span.begin());
let char_byte_start = glyph_data.byte_offset_of_glyph(glyph_span.begin());
char_byte_span.reset(char_byte_start, 0);
//... | destroy_blob_func | identifier_name | |
harfbuzz.rs | _i = ptr::offset(self.glyph_infos, i as int);
(*glyph_info_i).cluster as uint
}
}
pub fn len(&self) -> uint {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn get_entry_for_glyph(&self, i: uint, y_pos: &mut Au) -> S... | glyph", char_byte_span.end());
let range = text.char_range_at(char_byte_span.end());
drop(range.ch);
char_byte_span.extend_to(range.next);
}
// extend glyph range to max glyph index covered by char_s... | random_line_split | |
harfbuzz.rs | == char_max {
byteToGlyph = vec::from_elem(byte_max, NO_GLYPH);
} else {
byteToGlyph = vec::from_elem(byte_max, CONTINUATION_BYTE);
for (i, _) in text.char_indices() {
byteToGlyph[i] = NO_GLYPH;
}
}
debug!("(glyph idx) -> (text by... | {
let font: *Font = font_data as *Font;
assert!(font.is_not_null());
unsafe {
match (*font).glyph_index(char::from_u32(unicode).unwrap()) {
Some(g) => {
*glyph = g as hb_codepoint_t;
true as hb_bool_t
}
None => false as hb_bool_t
... | identifier_body | |
managers.py | .instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
class APIManager(metaclass=Singleton):
STATELESS_PROCESS = {
'오늘의 식단': FoodMessage,
'운영시간': TimeTableMessage,
'학식': PupilFoodMessage,
'교식': FacultyFoodMessage,
# '기식': DormFoodMessage,
... | TODO: mongodb 기능에 count 하는게 있을듯 그걸로 대체
s = 0
for i in lst:
if i.get('user_key') == user_key:
s | w_review: str):
def count_user_key(lst):
# | identifier_body |
managers.py | .instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
class APIManager(metaclass=Singleton):
STATELESS_PROCESS = {
'오늘의 식단': FoodMessage,
'운영시간': TimeTableMessage,
'학식': PupilFoodMessage,
'교식': FacultyFoodMessage,
# '기식': DormFoodMessage,
... | :param content:
:return: Message Object
"""
if content in self.PROCESS:
UserSessionAdmin.init_process(user_key, content)
new_msg = self.PROCESS[content][0][content]
return new_msg()
else:
new_msg = self.STATELESS_PROCESS[content]
... | :param user_key: | random_line_split |
managers.py | '정문(20166)': BusFrontMessage,
'베라 앞(20165)': BusBeraMessage,
'중문(20169)': BusMiddleMessage,
'지하철': SubMessage,
'도서관': LibMessage,
}
PROCESS = {
'내일의 식단': [
{
'내일의 식단': TomorrowFoodMessage,
},
{
'... | identifier_name | ||
managers.py | .instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
class APIManager(metaclass=Singleton):
STATELESS_PROCESS = {
'오늘의 식단': FoodMessage,
'운영시간': TimeTableMessage,
'학식': PupilFoodMessage,
'교식': FacultyFoodMessage,
# '기식': DormFoodMessage,
... | c)
def session_wrapper(*args, **kwargs):
user_key = args[1]
if session.find_one({'user_key': user_key}):
return func(*args, **kwargs)
else:
return False
return session_wrapper
def init(self, user_key, content=None, process=None):
... | fail')")
class SessionManager(metaclass=Singleton):
@staticmethod
def check_user_key(user_key):
if session.find_one({'user_key': user_key}):
return True
else:
return False
def verify_session(func):
@wraps(fun | conditional_block |
dir_ind.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Indirect};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get_value::GetValue;
use machine::M... |
}
impl WriteTo for DirInd {
fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match *self {
DirInd::Direct(direct) => direct.write_to(writer),
DirInd::Indirect(indirect) => indirect.write_to(writer),
}
}
}
impl ParamTypeOf for DirInd {
fn param_type(... | {
match *self {
DirInd::Direct(direct) => direct.mem_size(),
DirInd::Indirect(indirect) => indirect.mem_size(),
}
} | identifier_body |
dir_ind.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Indirect};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get_value::GetValue;
use machine::M... | <R: Read>(param_type: ParamType, reader: &mut R) -> Result<Self, Error> {
match param_type {
ParamType::Direct => Ok(DirInd::Direct(Direct::read_from(reader)?)),
ParamType::Indirect => Ok(DirInd::Indirect(Indirect::read_from(reader)?)),
_ => Err(Error::InvalidParamType(Invali... | read_from | identifier_name |
dir_ind.rs | use std::io::{self, Read, Write};
use std::fmt;
use instruction::parameter::{Direct, Indirect};
use instruction::parameter::{ParamType, ParamTypeOf};
use instruction::parameter::InvalidParamType;
use instruction::mem_size::MemSize;
use instruction::write_to::WriteTo;
use instruction::get_value::GetValue;
use machine::M... | fn mem_size(&self) -> usize {
match *self {
DirInd::Direct(direct) => direct.mem_size(),
DirInd::Indirect(indirect) => indirect.mem_size(),
}
}
}
impl WriteTo for DirInd {
fn write_to<W: Write>(&self, writer: &mut W) -> io::Result<()> {
match *self {
... | }
impl MemSize for DirInd { | random_line_split |
karma.conf.js | // Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
'use strict';
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: './../..',
// testing framework to use (jasmine/mocha/qunit/...)
framew... |
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
sing... |
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false, | random_line_split |
AnnouncementDeleteRequest.ts | import {AsyncTask} from "@/objects/task/AsyncTask";
import {TaskCallback} from "@/objects/task/TaskCallback";
import {NetworkCallStatus} from "@/objects/network/NetworkCallStatus";
import {TaskType} from "@/enums/TaskType";
import jqXHR = JQuery.jqXHR;
export class AnnouncementDeleteRequest implements AsyncTask {
pri... |
provideApiDetails(apiKey: string, apiUrl: string): void {
this.apiKey = apiKey;
this.apiUrl = apiUrl;
}
execute(): void {
let bodyRaw: any = {
"guild_id": this.guildId,
"announcement_id": this.anId
};
$.ajax({
url: this.apiUrl + "/v2/announceme... | {
this.guildId = guildId;
this.anId = anId;
this.callback = callback;
} | identifier_body |
AnnouncementDeleteRequest.ts | import {AsyncTask} from "@/objects/task/AsyncTask";
import {TaskCallback} from "@/objects/task/TaskCallback";
import {NetworkCallStatus} from "@/objects/network/NetworkCallStatus";
import {TaskType} from "@/enums/TaskType";
import jqXHR = JQuery.jqXHR;
export class AnnouncementDeleteRequest implements AsyncTask {
pri... | }
provideApiDetails(apiKey: string, apiUrl: string): void {
this.apiKey = apiKey;
this.apiUrl = apiUrl;
}
execute(): void {
let bodyRaw: any = {
"guild_id": this.guildId,
"announcement_id": this.anId
};
$.ajax({
url: this.apiUrl + "/v2/announce... | this.callback = callback; | random_line_split |
AnnouncementDeleteRequest.ts | import {AsyncTask} from "@/objects/task/AsyncTask";
import {TaskCallback} from "@/objects/task/TaskCallback";
import {NetworkCallStatus} from "@/objects/network/NetworkCallStatus";
import {TaskType} from "@/enums/TaskType";
import jqXHR = JQuery.jqXHR;
export class AnnouncementDeleteRequest implements AsyncTask {
pri... | (guildId: string, anId: string, callback: TaskCallback) {
this.guildId = guildId;
this.anId = anId;
this.callback = callback;
}
provideApiDetails(apiKey: string, apiUrl: string): void {
this.apiKey = apiKey;
this.apiUrl = apiUrl;
}
execute(): void {
let bodyRaw: any = {
"guild_id... | constructor | identifier_name |
build.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
fn commit_hash() -> Option<String> {
Command::new("git")
.args(&["rev-parse", "--short", "HEAD"])
.output()
.ok()
.and_then(|r| String::from_utf8(r.stdout).ok())
}
fn commit_date() -> Option<String> {
Command::new("git")
.args(&["log", "-1", "--date=short", "--p... | match (commit_hash(), commit_date()) {
(Some(hash), Some(date)) => format!(" ({} {})", hash.trim_right(), date),
_ => String::new(), | random_line_split |
build.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> String {
match (commit_hash(), commit_date()) {
(Some(hash), Some(date)) => format!(" ({} {})", hash.trim_right(), date),
_ => String::new(),
}
}
fn commit_hash() -> Option<String> {
Command::new("git")
.args(&["rev-parse", "--short", "HEAD"])
.output()
.ok()
... | commit_info | identifier_name |
build.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn commit_date() -> Option<String> {
Command::new("git")
.args(&["log", "-1", "--date=short", "--pretty=format:%cd"])
.output()
.ok()
.and_then(|r| String::from_utf8(r.stdout).ok())
}
| {
Command::new("git")
.args(&["rev-parse", "--short", "HEAD"])
.output()
.ok()
.and_then(|r| String::from_utf8(r.stdout).ok())
} | identifier_body |
Number.js | Number.prototype.setSlotsIfAbsent(
{
cssString: function()
{
return this.toString();
},
milliseconds: function()
{
return this;
},
seconds: function()
{
return Number(this) * 1000;
},
minutes: function()
{
return this.seconds() * 60;
},
hours: function()
{
return this.minutes() * 60;
},... | },
repeat: function(callback)
{
for(var i = 0; i < this; i++)
{
callback(i);
}
return this;
},
map: function()
{
var a = [];
for(var i = 0; i < this; i ++)
{
a.push(i);
}
return Array.prototype.map.apply(a, arguments);
},
isEven: function()
{
return this % 2 == 0;
},
abs: funct... | random_line_split | |
Number.js | Number.prototype.setSlotsIfAbsent(
{
cssString: function()
{
return this.toString();
},
milliseconds: function()
{
return this;
},
seconds: function()
{
return Number(this) * 1000;
},
minutes: function()
{
return this.seconds() * 60;
},
hours: function()
{
return this.minutes() * 60;
},... |
return this;
},
map: function()
{
var a = [];
for(var i = 0; i < this; i ++)
{
a.push(i);
}
return Array.prototype.map.apply(a, arguments);
},
isEven: function()
{
return this % 2 == 0;
},
abs: function()
{
return Math.abs(this);
}
});
| {
callback(i);
} | conditional_block |
exercises.py | # lesson4/exercises.py
# Control flow and conditionals
#
# This file contains exercises about Python conditionals.
# Last lesson, we encountered the boolean type.
# Python uses booleans to evaluate conditions.
# Last time, we directly assigned boolean values True and False, but booleans are
# also returned by compari... | if how_many_potatoes > 20:
print("lots of potatoes")
elif how_many_potatoes > 5:
print("some potatoes, but not more than 20!")
elif how_many_potatoes > 10:
print("the program will never get here " + \
"because the previous case will be " + \
"true if there are more than 5 potatoes.")... |
how_many_potatoes = 4 | random_line_split |
exercises.py | # lesson4/exercises.py
# Control flow and conditionals
#
# This file contains exercises about Python conditionals.
# Last lesson, we encountered the boolean type.
# Python uses booleans to evaluate conditions.
# Last time, we directly assigned boolean values True and False, but booleans are
# also returned by compari... |
elif how_many_potatoes > 0:
print("a few potatoes")
# It is possible to have multiple elif statements.
# However, notice that an control flow statement must always start with an if
# statement and else statements, if they exist, should always be in the end.
# Exercise 3:
# To practice your newly acquired skills ... | print("the program will never get here " + \
"because the previous case will be " + \
"true if there are more than 5 potatoes.") | conditional_block |
sshengine.rs |
use std::net::TcpStream;
use std::path::Path;
use std::path::PathBuf;
use ssh2::Session;
use std::io;
use std::io::Write;
use std::io::Read;
use std::fs::File;
use std::io::BufReader;
use std::io::BufWriter;
pub fn | (adress: &str, user: &str, password: &str, remote_root_path: &Path, files_path: &Vec<PathBuf>) {
let tcp = TcpStream::connect(adress).unwrap();
let mut sess = Session::new().unwrap();
sess.handshake(&tcp).unwrap();
sess.userauth_password(user, password).unwrap();
for file_path in files_path {
let filename = fil... | upload_to_remote | identifier_name |
sshengine.rs | use std::net::TcpStream;
use std::path::Path;
use std::path::PathBuf;
use ssh2::Session;
use std::io;
use std::io::Write;
use std::io::Read;
use std::fs::File;
use std::io::BufReader;
use std::io::BufWriter;
pub fn upload_to_remote(adress: &str, user: &str, password: &str, remote_root_path: &Path, files_path: &Vec<Pa... | let file_size = file.metadata().unwrap().len();
let mut file_reader = BufReader::new(file);
let mut remote_path = remote_root_path.join(filename);
println!("Remote path {:?}", remote_path);
let mut remote_channel = sess.scp_send(&remote_path, 0o644, file_size, None).unwrap();
let mut remote_file_writer =... | for file_path in files_path {
let filename = file_path.file_name().unwrap();
let mut file = File::open(&file_path).unwrap(); | random_line_split |
sshengine.rs |
use std::net::TcpStream;
use std::path::Path;
use std::path::PathBuf;
use ssh2::Session;
use std::io;
use std::io::Write;
use std::io::Read;
use std::fs::File;
use std::io::BufReader;
use std::io::BufWriter;
pub fn upload_to_remote(adress: &str, user: &str, password: &str, remote_root_path: &Path, files_path: &Vec<P... | io::copy(&mut file_reader, &mut remote_file_writer);
}
}
pub fn download_file_from_remote(adress: &str, user: &str, password: &str, remote_path: &Path, local_path: &Path) {
//remote duplicate code
let tcp = TcpStream::connect(adress).unwrap();
let mut sess = Session::new().unwrap();
sess.handshake(&tcp).unwrap... | {
let tcp = TcpStream::connect(adress).unwrap();
let mut sess = Session::new().unwrap();
sess.handshake(&tcp).unwrap();
sess.userauth_password(user, password).unwrap();
for file_path in files_path {
let filename = file_path.file_name().unwrap();
let mut file = File::open(&file_path).unwrap();
let file_size... | identifier_body |
eq_op_macros.rs | #![warn(clippy::eq_op)]
// lint also in macro definition
macro_rules! assert_in_macro_def {
() => {
let a = 42;
assert_eq!(a, a);
assert_ne!(a, a);
debug_assert_eq!(a, a);
debug_assert_ne!(a, a);
};
}
// lint identical args in assert-like macro invocations (see #3574)
f... | // ok
debug_assert_ne!(a, b);
debug_assert_ne!(a, a + 1);
debug_assert_ne!(a + 1, b + 1);
let my_vec = vec![1; 5];
let mut my_iter = my_vec.iter();
assert_ne!(my_iter.next(), my_iter.next());
} | random_line_split | |
eq_op_macros.rs | #![warn(clippy::eq_op)]
// lint also in macro definition
macro_rules! assert_in_macro_def {
() => {
let a = 42;
assert_eq!(a, a);
assert_ne!(a, a);
debug_assert_eq!(a, a);
debug_assert_ne!(a, a);
};
}
// lint identical args in assert-like macro invocations (see #3574)
f... | () {
assert_in_macro_def!();
let a = 1;
let b = 2;
// lint identical args in `assert_eq!`
assert_eq!(a, a);
assert_eq!(a + 1, a + 1);
// ok
assert_eq!(a, b);
assert_eq!(a, a + 1);
assert_eq!(a + 1, b + 1);
// lint identical args in `assert_ne!`
assert_ne!(a, a);
as... | main | identifier_name |
eq_op_macros.rs | #![warn(clippy::eq_op)]
// lint also in macro definition
macro_rules! assert_in_macro_def {
() => {
let a = 42;
assert_eq!(a, a);
assert_ne!(a, a);
debug_assert_eq!(a, a);
debug_assert_ne!(a, a);
};
}
// lint identical args in assert-like macro invocations (see #3574)
f... | assert_ne!(a + 1, b + 1);
// lint identical args in `debug_assert_eq!`
debug_assert_eq!(a, a);
debug_assert_eq!(a + 1, a + 1);
// ok
debug_assert_eq!(a, b);
debug_assert_eq!(a, a + 1);
debug_assert_eq!(a + 1, b + 1);
// lint identical args in `debug_assert_ne!`
debug_assert_ne!... | {
assert_in_macro_def!();
let a = 1;
let b = 2;
// lint identical args in `assert_eq!`
assert_eq!(a, a);
assert_eq!(a + 1, a + 1);
// ok
assert_eq!(a, b);
assert_eq!(a, a + 1);
assert_eq!(a + 1, b + 1);
// lint identical args in `assert_ne!`
assert_ne!(a, a);
asser... | identifier_body |
test.py | # Python3
from solution1 import urlSimilarity as f
qa = [
('https://codesignal.com/home/test?param1=42¶m3=testing&login=admin',
'https://codesignal.com/home/secret/test?param3=fish¶m1=42&password=admin',
19),
('https://codesignal.com/home/test?param1=42¶m3=testing&login=admin',
'htt... | print(' [ok]')
print(' output:', ans)
print() | random_line_split | |
test.py | # Python3
from solution1 import urlSimilarity as f
qa = [
('https://codesignal.com/home/test?param1=42¶m3=testing&login=admin',
'https://codesignal.com/home/secret/test?param3=fish¶m1=42&password=admin',
19),
('https://codesignal.com/home/test?param1=42¶m3=testing&login=admin',
'htt... |
else:
print(' [ok]')
print(' output:', ans)
print()
| print(' [failed]')
print(' output:', ans)
print(' expected:', a) | conditional_block |
shared.js | function | (context) {
describe('the paginated result', function() {
var result;
beforeEach(function() {
result = context.result;
});
it('is defined', function(){
expect(result).toBeDefined();
});
it('has not previous page at the beginning', function() {
expect(result.hasPrevious).toBe(... | paginatedResultInterface | identifier_name |
shared.js | function paginatedResultInterface(context) | expect(result.parameters().endkey).toBeUndefined();
});
it('flips existing keys when changing descending', function(){
result.parameters({
startkey: 'start',
endkey: 'end'
});
result.setDescending(true);
expect(result.parameters()).toEqual({
startkey: 'end',... | {
describe('the paginated result', function() {
var result;
beforeEach(function() {
result = context.result;
});
it('is defined', function(){
expect(result).toBeDefined();
});
it('has not previous page at the beginning', function() {
expect(result.hasPrevious).toBe(false);
... | identifier_body |
shared.js | function paginatedResultInterface(context) {
describe('the paginated result', function() {
var result;
beforeEach(function() {
result = context.result; | it('is defined', function(){
expect(result).toBeDefined();
});
it('has not previous page at the beginning', function() {
expect(result.hasPrevious).toBe(false);
});
it('allows to get parameters', function() {
var params = result.parameters();
expect(params.limit).toEqual(jasm... | }); | random_line_split |
test_pdfminer_psparser.py | import logging
from pdfminer.psparser import KWD, LIT, PSBaseParser, PSStackParser, PSEOF
logger = logging.getLogger(__name__)
class TestPSBaseParser:
"""Simplistic Test cases"""
TESTDATA = rb"""%!PS
begin end
" @ #
/a/BCD /Some_Name /foo#5f#xbaa
0 +1 -2 .5 1.234
(abc) () (abc ( def ) ghi)
(def\040\0\040... | pass
return r
def get_objects(self, s):
from io import BytesIO
class MyParser(PSStackParser):
def flush(self):
self.add_results(*self.popall())
parser = MyParser(BytesIO(s))
r = []
try:
while True:
... | while True:
r.append(parser.nexttoken())
except PSEOF: | random_line_split |
test_pdfminer_psparser.py | import logging
from pdfminer.psparser import KWD, LIT, PSBaseParser, PSStackParser, PSEOF
logger = logging.getLogger(__name__)
class TestPSBaseParser:
"""Simplistic Test cases"""
TESTDATA = rb"""%!PS
begin end
" @ #
/a/BCD /Some_Name /foo#5f#xbaa
0 +1 -2 .5 1.234
(abc) () (abc ( def ) ghi)
(def\040\0\040... | objs = self.get_objects(self.TESTDATA)
logger.info(objs)
assert objs == self.OBJS
return | identifier_body | |
test_pdfminer_psparser.py | import logging
from pdfminer.psparser import KWD, LIT, PSBaseParser, PSStackParser, PSEOF
logger = logging.getLogger(__name__)
class TestPSBaseParser:
"""Simplistic Test cases"""
TESTDATA = rb"""%!PS
begin end
" @ #
/a/BCD /Some_Name /foo#5f#xbaa
0 +1 -2 .5 1.234
(abc) () (abc ( def ) ghi)
(def\040\0\040... |
except PSEOF:
pass
return r
def get_objects(self, s):
from io import BytesIO
class MyParser(PSStackParser):
def flush(self):
self.add_results(*self.popall())
parser = MyParser(BytesIO(s))
r = []
try:
whil... | r.append(parser.nexttoken()) | conditional_block |
test_pdfminer_psparser.py | import logging
from pdfminer.psparser import KWD, LIT, PSBaseParser, PSStackParser, PSEOF
logger = logging.getLogger(__name__)
class TestPSBaseParser:
"""Simplistic Test cases"""
TESTDATA = rb"""%!PS
begin end
" @ #
/a/BCD /Some_Name /foo#5f#xbaa
0 +1 -2 .5 1.234
(abc) () (abc ( def ) ghi)
(def\040\0\040... | (self):
self.add_results(*self.popall())
parser = MyParser(BytesIO(s))
r = []
try:
while True:
r.append(parser.nexttoken())
except PSEOF:
pass
return r
def get_objects(self, s):
from io import BytesIO
... | flush | identifier_name |
arm_unknown_linux_gnueabihf.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 ... | {
let base = super::linux_base::opts();
Target {
llvm_target: "arm-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "gnueabihf".t... | identifier_body | |
arm_unknown_linux_gnueabihf.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 ... | () -> Target {
let base = super::linux_base::opts();
Target {
llvm_target: "arm-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: ... | target | identifier_name |
arm_unknown_linux_gnueabihf.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 ... |
options: TargetOptions {
features: "+v6,+vfp2".to_string(),
.. base
}
}
} | random_line_split | |
utils.ts | import type { Stats } from 'fs'
import * as fs from 'fs/promises'
import * as path from 'path'
import { URLSearchParams } from 'url'
import { promisify } from 'util'
const setTimeoutPromise = promisify(setTimeout)
export function | (val: unknown): val is string[] {
return Array.isArray(val) && val.every(v => typeof v === 'string')
}
export async function delay(ms: number) {
return setTimeoutPromise(ms)
}
function formatPath({
pathname,
nonChar,
lowerCase,
}: {
pathname: string
nonChar: string
lowerCase: boolean
}): string {
co... | isStringArray | identifier_name |
utils.ts | import type { Stats } from 'fs'
import * as fs from 'fs/promises'
import * as path from 'path'
import { URLSearchParams } from 'url'
import { promisify } from 'util'
const setTimeoutPromise = promisify(setTimeout)
export function isStringArray(val: unknown): val is string[] {
return Array.isArray(val) && val.every... |
function formatQs({
search,
ignoreQueries,
}: {
search: string|null
ignoreQueries: string[]|boolean
}): string {
if (search == null || ignoreQueries === true) {
return ''
}
const sp = new URLSearchParams(search)
if (ignoreQueries !== false) {
ignoreQueries.forEach(ignore => {
sp.delete(... | {
const caseNormalized = lowerCase ? pathname.toLowerCase() : pathname
return caseNormalized.replace(/[^a-zA-Z0-9/]/ug, nonChar)
} | identifier_body |
utils.ts | import type { Stats } from 'fs'
import * as fs from 'fs/promises'
import * as path from 'path'
import { URLSearchParams } from 'url'
import { promisify } from 'util'
const setTimeoutPromise = promisify(setTimeout)
export function isStringArray(val: unknown): val is string[] {
return Array.isArray(val) && val.every... |
sp.sort()
return sp.toString()
}
export function composeModulePath({
method,
pathname,
search,
lowerCase,
nonChar,
apiDir,
ignoreQueries,
}: {
method: string
pathname: string
search: string|null
lowerCase: boolean
nonChar: string
apiDir: string
ignoreQueries: string[]|boolean
}): strin... | {
ignoreQueries.forEach(ignore => {
sp.delete(ignore)
})
} | conditional_block |
utils.ts | import type { Stats } from 'fs'
import * as fs from 'fs/promises'
import * as path from 'path'
import { URLSearchParams } from 'url'
import { promisify } from 'util'
const setTimeoutPromise = promisify(setTimeout)
export function isStringArray(val: unknown): val is string[] {
return Array.isArray(val) && val.every... | export async function delay(ms: number) {
return setTimeoutPromise(ms)
}
function formatPath({
pathname,
nonChar,
lowerCase,
}: {
pathname: string
nonChar: string
lowerCase: boolean
}): string {
const caseNormalized = lowerCase ? pathname.toLowerCase() : pathname
return caseNormalized.replace(/[^a-zA... | random_line_split | |
replicatorStatus.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | }
module.exports = ReplicatorStatus; | }
}
}
};
} | random_line_split |
replicatorStatus.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | {
/**
* Create a ReplicatorStatus.
* @member {string} kind Polymorphic Discriminator
*/
constructor() {
}
/**
* Defines the metadata of ReplicatorStatus
*
* @returns {object} metadata of ReplicatorStatus
*
*/
mapper() {
return {
required: false,
serializedName: 'Repli... | ReplicatorStatus | identifier_name |
replicatorStatus.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | }
}
};
}
}
module.exports = ReplicatorStatus;
| {
return {
required: false,
serializedName: 'ReplicatorStatus',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'Kind',
clientName: 'kind'
},
uberParent: 'ReplicatorStatus',
className: 'ReplicatorStatus',
mo... | identifier_body |
htmloptionelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bi... |
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_parent_disabled_state_for_option();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if... | {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(false);
node.set_enabled_state(true);
... | identifier_body |
htmloptionelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bi... | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLOptionElement> {
let element = HTMLOptionElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap)
}
}
fn collect_tex... | new | identifier_name |
htmloptionelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bi... |
}
}
}
impl HTMLOptionElementMethods for HTMLOptionElement {
// https://www.whatwg.org/html/#dom-option-disabled
make_bool_getter!(Disabled);
// https://www.whatwg.org/html/#dom-option-disabled
fn SetDisabled(&self, disabled: bool) {
let elem = ElementCast::from_ref(self);
... | {
collect_text(&child.r(), value);
} | conditional_block |
htmloptionelement.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 dom::attr::Attr;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bi... | let node = NodeCast::from_ref(self);
node.check_parent_disabled_state_for_option();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
if ... | random_line_split | |
osconfig_generated_osconfig_v1_os_config_zonal_service_list_inventories_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
# [END osconfig_generated_osconfig_v1_OsConfigZonalService_ListInventories_async]
| print(response) | conditional_block |
osconfig_generated_osconfig_v1_os_config_zonal_service_list_inventories_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | ():
# Create a client
client = osconfig_v1.OsConfigZonalServiceAsyncClient()
# Initialize request argument(s)
request = osconfig_v1.ListInventoriesRequest(
parent="parent_value",
)
# Make the request
page_result = client.list_inventories(request=request)
# Handle the response
... | sample_list_inventories | identifier_name |
osconfig_generated_osconfig_v1_os_config_zonal_service_list_inventories_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
# [END osconfig_generated_osconfig_v1_OsConfigZonalService_ListInventories_async]
| client = osconfig_v1.OsConfigZonalServiceAsyncClient()
# Initialize request argument(s)
request = osconfig_v1.ListInventoriesRequest(
parent="parent_value",
)
# Make the request
page_result = client.list_inventories(request=request)
# Handle the response
async for response in page... | identifier_body |
osconfig_generated_osconfig_v1_os_config_zonal_service_list_inventories_async.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
# | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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 ... | # 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 | random_line_split |
youtube-videos.effects.ts | import { Store } from '@ngrx/store';
import { EchoesState } from '../store';
import { Injectable } from '@angular/core';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import 'rxjs/add/operator/withLatestFrom';
import { EchoesVideos, YoutubeVideosActions } from '../store/youtube-videos';
import { YoutubeS... | .switchMap((mediaIds) => this.youtubeVideosInfo.fetchVideoData(mediaIds))
.map((videos) => this.youtubeVideosActions.addVideos(videos));
@Effect()
searchMoreVideos$ = this.actions$
.ofType(YoutubeVideosActions.SEARCH_MORE)
.map(toPayload)
.withLatestFrom(this.store.select(state => state.videos)... | random_line_split | |
youtube-videos.effects.ts | import { Store } from '@ngrx/store';
import { EchoesState } from '../store';
import { Injectable } from '@angular/core';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import 'rxjs/add/operator/withLatestFrom';
import { EchoesVideos, YoutubeVideosActions } from '../store/youtube-videos';
import { YoutubeS... | (
private actions$: Actions,
private store: Store<EchoesState>,
private youtubeVideosActions: YoutubeVideosActions,
private youtubeSearch: YoutubeSearch,
private youtubeVideosInfo: YoutubeVideosInfo
) {}
@Effect()
resetVideos$ = this.actions$
.ofType(YoutubeVideosActions.SEARCH_NEW_QUERY)... | constructor | identifier_name |
youtube-videos.effects.ts | import { Store } from '@ngrx/store';
import { EchoesState } from '../store';
import { Injectable } from '@angular/core';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import 'rxjs/add/operator/withLatestFrom';
import { EchoesVideos, YoutubeVideosActions } from '../store/youtube-videos';
import { YoutubeS... |
@Effect()
resetVideos$ = this.actions$
.ofType(YoutubeVideosActions.SEARCH_NEW_QUERY)
.map(toPayload)
.filter((query: string) => this.youtubeSearch.isNewSearchQuery(query))
.do(() => this.youtubeSearch.resetPageToken())
.map(() => this.youtubeVideosActions.reset());
@Effect()
startSearch$... | {} | identifier_body |
auto-activation.test.ts | import * as assert from "assert";
import * as vscode from "vscode";
import * as rimraf from "rimraf";
import * as path from "path";
suite("Auto activation tests", function() {
let workspaceRoot = vscode.workspace.workspaceFolders[0].uri.fsPath;
let launchJson = path.join(workspaceRoot, ".vscode", "launch.json... | rimraf(launchJson, done);
});
test("Rubic is detected", function() {
const ext = vscode.extensions.getExtension("kimushu.rubic");
assert(ext);
});
test("Rubic has been automatically activated by existence of rubic.json", function() {
const ext = vscode.extensions.getExt... |
suiteTeardown(function(done) { | random_line_split |
radio-button-group.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import {FORM_DIRECTIVES} from '@angular/common';
@Component({
selector: 'auiNgRadioButtonGroup',
directives: [...FORM_DIRECTIVES],
styles: [`
.aui-ng2-orientation-horizontal .radio{
float: left;
margin-right: 10px;
... | @Input() title: string;
@Input() name: string;
@Input() selection: any;
@Input() items: any[];
@Input() idProperty: string;
@Input() labelProperty: any;
@Output() changed : EventEmitter<any> = new EventEmitter<any>();
private selection: any = {};
private onChange (item) {
t... | })
export class AuiNgRadioButtonGroupComponent {
@Input() orientation: string; | random_line_split |
radio-button-group.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import {FORM_DIRECTIVES} from '@angular/common';
@Component({
selector: 'auiNgRadioButtonGroup',
directives: [...FORM_DIRECTIVES],
styles: [`
.aui-ng2-orientation-horizontal .radio{
float: left;
margin-right: 10px;
... |
}
| {
return item && item[this.idProperty];
} | identifier_body |
radio-button-group.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import {FORM_DIRECTIVES} from '@angular/common';
@Component({
selector: 'auiNgRadioButtonGroup',
directives: [...FORM_DIRECTIVES],
styles: [`
.aui-ng2-orientation-horizontal .radio{
float: left;
margin-right: 10px;
... |
return item && item[this.labelProperty];
}
private getId(item:any):string {
return item && item[this.idProperty];
}
}
| {
return this.labelProperty(item);
} | conditional_block |
radio-button-group.component.ts | import {Component, Input, Output, EventEmitter} from '@angular/core';
import {FORM_DIRECTIVES} from '@angular/common';
@Component({
selector: 'auiNgRadioButtonGroup',
directives: [...FORM_DIRECTIVES],
styles: [`
.aui-ng2-orientation-horizontal .radio{
float: left;
margin-right: 10px;
... | {
@Input() orientation: string;
@Input() title: string;
@Input() name: string;
@Input() selection: any;
@Input() items: any[];
@Input() idProperty: string;
@Input() labelProperty: any;
@Output() changed : EventEmitter<any> = new EventEmitter<any>();
private selection: any = {};
... | AuiNgRadioButtonGroupComponent | identifier_name |
GameEventTest.js | import GameEvent from "../../../src/artifact/js/GameEvent.js";
QUnit.module("GameEvent");
var GameEventTest = {};
QUnit.test("GameEvent properties Quest card drawn", function(assert)
{
var eventKey = GameEvent.QUEST_CARD_DRAWN;
var properties = GameEvent.properties[eventKey];
assert.equal(properties.name, "... | {
// Run.
var result = GameEvent.keys();
// Verify.
assert.ok(result);
var length = 6;
assert.equal(result.length, length);
var i = 0;
assert.equal(result[i++], GameEvent.CARD_PLAYED);
assert.equal(result[i++], GameEvent.QUEST_CARD_DRAWN);
assert.equal(result[i++], GameEvent.QUEST_SUCCEED... | });
QUnit.test("GameEvent.keys()", function(assert) | random_line_split |
GameEventTest.js | import GameEvent from "../../../src/artifact/js/GameEvent.js";
QUnit.module("GameEvent");
var GameEventTest = {};
QUnit.test("GameEvent properties Quest card drawn", function(assert)
{
var eventKey = GameEvent.QUEST_CARD_DRAWN;
var properties = GameEvent.properties[eventKey];
assert.equal(properties.name, "... |
});
result.forEach(function(value)
{
var p = ownPropertyNames.filter(function(key)
{
return GameEvent[key] === value;
});
assert.equal(p.length, 1, "Missing key for value = " + value);
});
});
QUnit.test("GameEvent.keys()", function(assert)
{
// Run.
var result = G... | {
assert.ok(GameEvent.properties[key2], "Missing value for key = " + key);
} | conditional_block |
observable.ts | import "core-js/es6/promise";
import "core-js/es6/array"
import "core-js/es6/set"
import {IObservable} from "./interfaces/observable";
import {IObservableEvent} from "./interfaces/observable-event";
import {IObserver, ObserverCallback} from "./interfaces/observer";
import {IObserverItem} from "./interfaces/obervable-i... | types: new Set<string>(type.map(item => isObservableEvent(item) ? item.name : item)),
callback: callback
});
}
// If type is not an array
else {
this.observers.push({
id: cancel,
types: new Set<string>([isOb... | {
let cancel : ICancel = {
cancel: () => {
let index : number = this.observers.findIndex((item : IObserverItem) => item.id === cancel);
// If the index is larger than -1, then remove the item
if (index > -1) {
this.observers.splice... | identifier_body |
observable.ts | import "core-js/es6/promise";
import "core-js/es6/array"
import "core-js/es6/set"
import {IObservable} from "./interfaces/observable";
import {IObservableEvent} from "./interfaces/observable-event";
import {IObserver, ObserverCallback} from "./interfaces/observer";
import {IObserverItem} from "./interfaces/obervable-i... | (type: string | IObservableEvent | (string | IObservableEvent)[], callback: ObserverCallback | IObserver)
: ICancel {
let cancel : ICancel = {
cancel: () => {
let index : number = this.observers.findIndex((item : IObserverItem) => item.id === cancel);
// If the i... | on | identifier_name |
observable.ts | import "core-js/es6/promise";
import "core-js/es6/array"
import "core-js/es6/set"
import {IObservable} from "./interfaces/observable";
import {IObservableEvent} from "./interfaces/observable-event";
import {IObserver, ObserverCallback} from "./interfaces/observer";
import {IObserverItem} from "./interfaces/obervable-i... |
// Else the remove failed
return false;
}
notify(event: IObservableEvent, data: any): Promise<void> {
// Make function decoupled
return Promise.resolve().then(() => {
let types: string[] = [event.name],
calledEventName: string = event.name;
... | {
this.observers.splice(index, 1);
return true;
} | conditional_block |
observable.ts | import "core-js/es6/promise";
import "core-js/es6/array"
import "core-js/es6/set"
import {IObservable} from "./interfaces/observable";
import {IObservableEvent} from "./interfaces/observable-event";
import {IObserver, ObserverCallback} from "./interfaces/observer";
import {IObserverItem} from "./interfaces/obervable-i... | event = event.parent;
types.push(event.name);
}
// Call all observers having the type
this.observers.forEach(observer => {
if (types.some(type => observer.types.has(type))) {
if (isObserver(observer.callback)) {
... | let types: string[] = [event.name],
calledEventName: string = event.name;
// Select all events to be called
while (event.parent !== undefined && event.parent !== null) { | random_line_split |
ComparisonTable.tsx | (props: PlanFeatuerProps) {
const { text, sx, variant, bold = false, tooltipText } = props;
const child = (
<Typography
component="span"
variant={variant || (bold ? 'h5' : 'body2')}
sx={{
...sx,
borderBottom: tooltipText ? '1px dashed rgb(19 47 78 / 40%)' : '',
}}
>
... | },
'& .MuiTableCell-root': {
border: 0,
verticalAlign: 'top',
paddingRight: 2,
paddingLeft: 2,
'&:nth-of-type(1)': {
paddingLeft: theme.spacing(2),
[theme.breakpoints.up('sm')]: {
paddingLeft: theme.spacing(5),
},
[theme.breakpoints.up('lg')]: {
paddingLef... | backgroundColor: theme.palette.greyF3, | random_line_split |
tagging_converter_test.py | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | },
# Test special characters.
{
'input_texts': ['Turing was born in 1912 .', 'Turing died in 1954 .'],
'target': 'Turing was born in 1912 ädåö died in 1954 .',
'phrase_vocabulary': ['ädåö'],
'target_tags': [
'KEEP', 'KEEP', 'KEEP', 'KEEP', 'KEEP', ... | random_line_split | |
tagging_converter_test.py | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ame__ == '__main__':
tf.test.main()
| = {'KEEP|, and': 0, 'DELETE|but': 1, 'DELETE': 2, 'KEEP|and': 3,
'DELETE|and': 4}
self.assertEqual(
tagging_converter.get_phrase_vocabulary_from_label_map(label_map),
{', and', 'but', 'and'})
if __n | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.