file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
app.py | # 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 writing, software
# di... | ():
cfg_file = None
cfg_path = CONF.api.api_paste_config
if not os.path.isabs(cfg_path):
cfg_file = CONF.find_file(cfg_path)
elif os.path.exists(cfg_path):
cfg_file = cfg_path
if not cfg_file:
raise cfg.ConfigFilesNotFoundError([CONF.api.api_paste_config])
LOG.info("Full... | load_app | identifier_name |
ascribe_user_type.rs | // Copyright 2016 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 perform_query(
tcx: TyCtxt<'_, 'gcx, 'tcx>,
canonicalized: Canonicalized<'gcx, ParamEnvAnd<'tcx, Self>>,
) -> Fallible<CanonicalizedQueryResponse<'gcx, ()>> {
tcx.type_op_ascribe_user_type(canonicalized)
}
fn shrink_to_tcx_lifetime(
v: &'a CanonicalizedQueryResponse... | {
None
} | identifier_body |
ascribe_user_type.rs | // Copyright 2016 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 ... | (
_tcx: TyCtxt<'_, 'gcx, 'tcx>,
_key: &ParamEnvAnd<'tcx, Self>,
) -> Option<Self::QueryResponse> {
None
}
fn perform_query(
tcx: TyCtxt<'_, 'gcx, 'tcx>,
canonicalized: Canonicalized<'gcx, ParamEnvAnd<'tcx, Self>>,
) -> Fallible<CanonicalizedQueryResponse<'gcx, ()... | try_fast_path | identifier_name |
ascribe_user_type.rs | // Copyright 2016 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 ... | }
}
BraceStructLiftImpl! {
impl<'a, 'tcx> Lift<'tcx> for AscribeUserType<'a> {
type Lifted = AscribeUserType<'tcx>;
mir_ty, variance, def_id, user_substs, projs
}
}
impl_stable_hash_for! {
struct AscribeUserType<'tcx> {
mir_ty, variance, def_id, user_substs, projs
}
} | random_line_split | |
everyObject-test.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails o... | describe('everyObject', function() {
var mockObject;
var mockCallback;
beforeEach(() => {
mockObject = {foo: 1, bar: 2, baz: 3};
mockCallback = jest.fn();
});
it('handles null', () => {
everyObject(null, mockCallback);
expect(mockCallback).not.toBeCalled();
});
it('returns true if all ... | random_line_split | |
test_delete.py | import os
from jenkins_jobs import cmd
from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
@mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock)
class DeleteTests(CmdTestsBase):
@mock.patch('jenkins_jobs.cmd.Builder.delete_job')
def | (self, delete_job_mock):
"""
Test handling the deletion of a single Jenkins job.
"""
args = self.parser.parse_args(['delete', 'test_job'])
cmd.execute(args, self.config) # passes if executed without error
@mock.patch('jenkins_jobs.cmd.Builder.delete_job')
def test_dele... | test_delete_single_job | identifier_name |
test_delete.py | import os
from jenkins_jobs import cmd
from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
@mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock)
class DeleteTests(CmdTestsBase):
@mock.patch('jenkins_jobs.cmd.Builder.delete_job')
def test_delete_single_job(self, del... | """
args = self.parser.parse_args(['delete', 'test_job1', 'test_job2'])
cmd.execute(args, self.config) # passes if executed without error
@mock.patch('jenkins_jobs.builder.Jenkins.delete_job')
def test_delete_using_glob_params(self, delete_job_mock):
"""
Test handling ... | Test handling the deletion of multiple Jenkins jobs. | random_line_split |
test_delete.py | import os
from jenkins_jobs import cmd
from tests.base import mock
from tests.cmd.test_cmd import CmdTestsBase
@mock.patch('jenkins_jobs.builder.Jenkins.get_plugins_info', mock.MagicMock)
class DeleteTests(CmdTestsBase):
@mock.patch('jenkins_jobs.cmd.Builder.delete_job')
def test_delete_single_job(self, del... | """
Test handling the deletion of multiple Jenkins jobs using the glob
parameters feature.
"""
args = self.parser.parse_args(['delete',
'--path',
os.path.join(self.fixtures_path,
... | identifier_body | |
sidemenu.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { SideMenuItem } from "../../models/sidemenuitem";
import { LoginPage } from "../../pages/login/login";
import { EventsPage } from "../../pages/events/events";
import { HoursPage } from "../../pages/... | (public http: Http, public auth: AuthProvider) {
}
public GetSideMenuItems(): Array<SideMenuItem> {
var isAuthenticated = (this.auth && !this.auth.isAuthenticated);
var sideMenuItems: Array<SideMenuItem> = [
{ title: 'Login', component: LoginPage, active: false, icon: 'person... | constructor | identifier_name |
sidemenu.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { SideMenuItem } from "../../models/sidemenuitem";
import { LoginPage } from "../../pages/login/login";
import { EventsPage } from "../../pages/events/events";
import { HoursPage } from "../../pages/... |
public GetSideMenuItems(): Array<SideMenuItem> {
var isAuthenticated = (this.auth && !this.auth.isAuthenticated);
var sideMenuItems: Array<SideMenuItem> = [
{ title: 'Login', component: LoginPage, active: false, icon: 'person-add', show: isAuthenticated },
... | {
} | identifier_body |
sidemenu.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { SideMenuItem } from "../../models/sidemenuitem";
import { LoginPage } from "../../pages/login/login";
import { EventsPage } from "../../pages/events/events";
import { HoursPage } from "../../pages/... |
var sideMenuItems: Array<SideMenuItem> = [
{ title: 'Login', component: LoginPage, active: false, icon: 'person-add', show: isAuthenticated },
{ title: 'Events', component: EventsPage, active: false, icon: 'calendar', show: true }, ... |
var isAuthenticated = (this.auth && !this.auth.isAuthenticated); | random_line_split |
coerce-unify.rs | // run-pass
// Check that coercions can unify if-else, match arms and array elements.
// Try to construct if-else chains, matches and arrays out of given expressions.
macro_rules! check {
($last:expr $(, $rest:expr)+) => {
// Last expression comes first because of whacky ifs and matches.
let _ = $(... | {
check3!(foo, bar, foo as fn());
check3!(size_of::<u8>, size_of::<u16>, size_of::<usize> as fn() -> usize);
let s = String::from("bar");
check2!("foo", &s);
let a = [1, 2, 3];
let v = vec![1, 2, 3];
check2!(&a[..], &v);
// Make sure in-array coercion still works.
let _ = [("a", D... | identifier_body | |
coerce-unify.rs | // run-pass
// Check that coercions can unify if-else, match arms and array elements.
// Try to construct if-else chains, matches and arrays out of given expressions.
macro_rules! check {
($last:expr $(, $rest:expr)+) => {
// Last expression comes first because of whacky ifs and matches.
let _ = $(... | () {}
pub fn main() {
check3!(foo, bar, foo as fn());
check3!(size_of::<u8>, size_of::<u16>, size_of::<usize> as fn() -> usize);
let s = String::from("bar");
check2!("foo", &s);
let a = [1, 2, 3];
let v = vec![1, 2, 3];
check2!(&a[..], &v);
// Make sure in-array coercion still works.... | bar | identifier_name |
coerce-unify.rs | // run-pass
// Check that coercions can unify if-else, match arms and array elements.
// Try to construct if-else chains, matches and arrays out of given expressions.
macro_rules! check {
($last:expr $(, $rest:expr)+) => {
// Last expression comes first because of whacky ifs and matches.
let _ = $(... |
// Check all non-uniform cases of 2 and 3 expressions of 3 types.
macro_rules! check3 {
($a:expr, $b:expr, $c:expr) => {
// Delegate to check2 for cases where a type repeats.
check2!($a, $b);
check2!($b, $c);
check2!($a, $c);
// Check the remaining cases, i.e., permutations... | random_line_split | |
SetPEVersion.py | # -*- coding: utf-8 -*-
# 2016-10-20T16:00+08:00
import fnmatch
import glob
import itertools
import os
import re
import subprocess
import sys
import fileutil
# Match version numbers of these formats:
# 1.2.3
# 1.2.3.4
version_number_re = r'([0-9]+(?:.[0-9]+){2,3})'
# Match version numbers of this format:
incompl... |
def iterate_module_files_v3(module_path):
assert os.path.isdir(module_path)
yield from itertools.chain.from_iterable(
glob.iglob(pattern) for pattern in map(lambda pattern: os.path.join(module_path, pattern), _module_patterns))
def main():
"""
Usage:
SetPEVersion.py (--module-path=<P... | assert os.path.isdir(module_path)
for pattern in _module_patterns:
pattern = os.path.join(module_path, pattern)
yield from glob.iglob(pattern) | identifier_body |
SetPEVersion.py | # -*- coding: utf-8 -*-
# 2016-10-20T16:00+08:00
import fnmatch
import glob
import itertools
import os
import re
import subprocess
import sys
import fileutil
# Match version numbers of these formats:
# 1.2.3
# 1.2.3.4
version_number_re = r'([0-9]+(?:.[0-9]+){2,3})'
# Match version numbers of this format:
incompl... |
elif os.path.isdir(args['--module-path']):
modules.extend(iterate_module_files_v3(args['--module-path']))
else:
perror('Invalid module path "{0}": Neither an existing file nor an existing directory.'.format(args['--module-path']))
else:
perror('"--module-path" option... | modules.append(args['--module-path']) | conditional_block |
SetPEVersion.py | # -*- coding: utf-8 -*-
# 2016-10-20T16:00+08:00
import fnmatch
import glob
import itertools
import os
import re
import subprocess
import sys
import fileutil
# Match version numbers of these formats:
# 1.2.3
# 1.2.3.4
version_number_re = r'([0-9]+(?:.[0-9]+){2,3})'
# Match version numbers of this format:
incompl... | if candidate_path is None:
candidate_path = ''
if os.path.isfile(candidate_path):
return candidate_path
elif os.path.isdir(candidate_path):
return os.path.join(candidate_path, file_name)
else:
return os.path.join(os.path.dirname(sys.argv[0]), file_name)
def _iterate_mo... |
def _get_full_path(candidate_path, file_name): | random_line_split |
SetPEVersion.py | # -*- coding: utf-8 -*-
# 2016-10-20T16:00+08:00
import fnmatch
import glob
import itertools
import os
import re
import subprocess
import sys
import fileutil
# Match version numbers of these formats:
# 1.2.3
# 1.2.3.4
version_number_re = r'([0-9]+(?:.[0-9]+){2,3})'
# Match version numbers of this format:
incompl... | (file):
assert os.path.isfile(file)
return fnmatch.fnmatch(file, '*.dll') or fnmatch.fnmatch(file, '*.exe')
def _get_full_path(candidate_path, file_name):
if candidate_path is None:
candidate_path = ''
if os.path.isfile(candidate_path):
return candidate_path
elif os.path.isdir... | is_dll_or_exe | identifier_name |
OptionElement.tsx | import React, { FC } from 'react';
import { FormAPI, Input, InputControl, Select, TextArea } from '@grafana/ui';
import { NotificationChannelOption } from '../../../types';
interface Props extends Pick<FormAPI<any>, 'register' | 'control'> {
option: NotificationChannelOption;
invalid?: boolean;
}
export const Opt... | console.error('Element not supported', option.element);
return null;
}
};
const validateOption = (value: string, validationRule: string) => {
return RegExp(validationRule).test(value) ? true : 'Invalid format';
}; | })}
/>
);
default: | random_line_split |
FullscreenUtils.web.ts | /**
* Detect if the browser supports the standard fullscreen API on the given
* element:
* https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
*/
const supportsFullscreenAPI = (element: HTMLMediaElement): boolean =>
'requestFullscreen' in element;
/**
* Detect if the browser supports the non-standar... | */
const supportsEvent = (elementName: string, eventName: string): boolean => {
// Detect if the browser supports the event by attempting to add a handler
// attribute for that event to the provided element. If the event is supported
// then the browser will accept the attribute and report the type of the
// a... | random_line_split | |
FullscreenUtils.web.ts | /**
* Detect if the browser supports the standard fullscreen API on the given
* element:
* https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
*/
const supportsFullscreenAPI = (element: HTMLMediaElement): boolean =>
'requestFullscreen' in element;
/**
* Detect if the browser supports the non-standar... | (
element: HTMLVideoElement,
callback: (isFullscreen: boolean) => void
): () => any {
if (supportsFullscreenAPI(element)) {
// Used by browsers that support the official spec
return addEventListener(element, 'fullscreenchange', (event) =>
callback(document.fullscreenElement === event.target)
);
... | addFullscreenListener | identifier_name |
FullscreenUtils.web.ts | /**
* Detect if the browser supports the standard fullscreen API on the given
* element:
* https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
*/
const supportsFullscreenAPI = (element: HTMLMediaElement): boolean =>
'requestFullscreen' in element;
/**
* Detect if the browser supports the non-standar... | else if (supportsWebkitFullscreenAPI(element)) {
// This API is synchronous so no need to return the result
element['webkitExitFullScreen']?.();
} else if (supportsMsFullscreenAPI(element)) {
// This API is synchronous so no need to return the result
document['msExitFullscreen']?.();
} else {
t... | {
return document.exitFullscreen();
} | conditional_block |
FullscreenUtils.web.ts | /**
* Detect if the browser supports the standard fullscreen API on the given
* element:
* https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
*/
const supportsFullscreenAPI = (element: HTMLMediaElement): boolean =>
'requestFullscreen' in element;
/**
* Detect if the browser supports the non-standar... | {
if (supportsFullscreenAPI(element)) {
// Used by browsers that support the official spec
return addEventListener(element, 'fullscreenchange', (event) =>
callback(document.fullscreenElement === event.target)
);
} else if (supportsWebkitFullscreenAPI(element) && supportsWebkitFullscreenChangeEvent... | identifier_body | |
cross_validation_test.py | '''
Created on 10 August 2014
@author: vincent
'''
# Loading necessary packages
import numpy as np
import sys
from seizures.data.DataLoader_v2 import DataLoader
from seizures.evaluation.XValidation import XValidation
from seizures.evaluation.performance_measures import accuracy, auc
from seizures.features.FeatureExt... |
else:
print 'Preprocessing OFF'
print 'predictor: ',predictor
Xval_on_patients(predictor,feature_extractor, patients_list,preprocess=preprocess)
if __name__ == '__main__':
main()
| print 'Preprocessing ON' | conditional_block |
cross_validation_test.py | ''' | import numpy as np
import sys
from seizures.data.DataLoader_v2 import DataLoader
from seizures.evaluation.XValidation import XValidation
from seizures.evaluation.performance_measures import accuracy, auc
from seizures.features.FeatureExtractBase import FeatureExtractBase
from seizures.features.MixFeatures import MixF... | Created on 10 August 2014
@author: vincent
'''
# Loading necessary packages | random_line_split |
cross_validation_test.py | '''
Created on 10 August 2014
@author: vincent
'''
# Loading necessary packages
import numpy as np
import sys
from seizures.data.DataLoader_v2 import DataLoader
from seizures.evaluation.XValidation import XValidation
from seizures.evaluation.performance_measures import accuracy, auc
from seizures.features.FeatureExt... |
if __name__ == '__main__':
main()
| patients_list = ["Dog_%d" % i for i in range(1, 5)] + ["Patient_%d" % i for i in range(1, 9)]
patients_list = ["Dog_%d" % i for i in [1]] #["Patient_%d" % i for i in range(1, 9)]#++
#feature_extractor = MixFeatures([{'name':"ARFeatures",'args':{}}])
#feature_extractor = PLVFeatures()
#feature_extrac... | identifier_body |
cross_validation_test.py | '''
Created on 10 August 2014
@author: vincent
'''
# Loading necessary packages
import numpy as np
import sys
from seizures.data.DataLoader_v2 import DataLoader
from seizures.evaluation.XValidation import XValidation
from seizures.evaluation.performance_measures import accuracy, auc
from seizures.features.FeatureExt... | ():
# code run at script launch
#patient_name = sys.argv[1]
# There are Dog_[1-4] and Patient_[1-8]
patients_list = ["Dog_%d" % i for i in range(1, 5)] + ["Patient_%d" % i for i in range(1, 9)]
patients_list = ["Dog_%d" % i for i in [1]] #["Patient_%d" % i for i in range(1, 9)]#++
#feature_... | main | identifier_name |
ppdgrid.py | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:17:42 2016
@author: ibackus
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
def _hexline(nx, firstSpacing=1):
"""
"""
x = np.zeros(nx)
nx0 = int((nx + 1)/2)
nx1 = nx - nx0
x0 = 3 * np.arang... |
xmat = np.ones([nx, ny])
ymat = np.dot(np.ones([nx, 1]), y[None, :])
for i in range(0, ny, 2):
# Even loop
xmat[:,i] = xshift[i] + xeven
for i in range(1, ny, 2):
# odd loop
xmat[:,i] = xshift[i] + xodd
return xmat, ymat
def rho(w, h,... |
y = (np.sqrt(3)/2.) * np.arange(ny, dtype=float) | random_line_split |
ppdgrid.py | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:17:42 2016
@author: ibackus
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
def _hexline(nx, firstSpacing=1):
"""
"""
x = np.zeros(nx)
nx0 = int((nx + 1)/2)
nx1 = nx - nx0
x0 = 3 * np.arang... | (n, H, R0, eps, nScaleHeight=5, nSplinePts=1e5, m=None):
"""
Generate z positions for an isothermal PPD with no self gravity.
Parameters
----------
n : int
Number of positions to make
H : float-like
Disk scale height. :math:`H = c_s / \\Omega`
R0 : float-like
Di... | posGen | identifier_name |
ppdgrid.py | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:17:42 2016
@author: ibackus
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
def _hexline(nx, firstSpacing=1):
"""
"""
x = np.zeros(nx)
nx0 = int((nx + 1)/2)
nx1 = nx - nx0
x0 = 3 * np.arang... |
def posGen(n, H, R0, eps, nScaleHeight=5, nSplinePts=1e5, m=None):
"""
Generate z positions for an isothermal PPD with no self gravity.
Parameters
----------
n : int
Number of positions to make
H : float-like
Disk scale height. :math:`H = c_s / \\Omega`
R0 : float... | """
Estimate (linear) density from sampled points, assuming constant mass,
using rho = dm/dz
"""
dz = np.gradient(z, edge_order=2)
dm = float(m)/len(z)
rho = dm/dz
return rho | identifier_body |
ppdgrid.py | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 12:17:42 2016
@author: ibackus
"""
import numpy as np
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
def _hexline(nx, firstSpacing=1):
"""
"""
x = np.zeros(nx)
nx0 = int((nx + 1)/2)
nx1 = nx - nx0
x0 = 3 * np.arang... |
return xmat, ymat
def rho(w, h, eps=0., rho0=1.):
"""
Vertical density profile as a function of dimensionless z
For an isothermal PPD with no self gravity.
Parameters
----------
w : array-like
Dimensionless z-coordinate (z/R0)
h : array-like
Dime... | xmat[:,i] = xshift[i] + xodd | conditional_block |
basic-types-mut-globals.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
_zzz();
unsafe {
B = true;
I = 2;
C = 'f';
I8 = 78;
I16 = -26;
I32 = -12;
I64 = -54;
U = 5;
U8 = 20;
U16 = 32;
U32 = 16;
U64 = 128;
F32 = 5.75;
F64 = 9.25;
}
_zzz();
}
fn _zzz() {()}
| main | identifier_name |
basic-types-mut-globals.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {()} | identifier_body | |
taskdb.py | import json, time
from pyspider.database.base.taskdb import TaskDB as BaseTaskDB
from .couchdbbase import SplitTableMixin
class TaskDB(SplitTableMixin, BaseTaskDB):
collection_prefix = ''
def __init__(self, url, database='taskdb', username=None, password=None):
self.username = username
self.p... | super().__init__()
self.create_database(database)
self.projects = set()
self._list_project()
def _get_collection_name(self, project):
return self.database + "_" + self._collection_name(project)
def _create_project(self, project):
collection_name = self._get_col... | self.base_url = url
self.url = url + database + "/"
self.database = database
self.index = None
| random_line_split |
taskdb.py | import json, time
from pyspider.database.base.taskdb import TaskDB as BaseTaskDB
from .couchdbbase import SplitTableMixin
class TaskDB(SplitTableMixin, BaseTaskDB):
collection_prefix = ''
def __init__(self, url, database='taskdb', username=None, password=None):
self.username = username
self.p... | (self, status, project=None, fields=None):
if not project:
self._list_project()
if fields is None:
fields = []
if project:
projects = [project, ]
else:
projects = self.projects
for project in projects:
collection_name = ... | load_tasks | identifier_name |
taskdb.py | import json, time
from pyspider.database.base.taskdb import TaskDB as BaseTaskDB
from .couchdbbase import SplitTableMixin
class TaskDB(SplitTableMixin, BaseTaskDB):
collection_prefix = ''
def __init__(self, url, database='taskdb', username=None, password=None):
self.username = username
self.p... |
if project not in self.projects:
return {}
collection_name = self._get_collection_name(project)
def _count_for_status(collection_name, status):
total = len(self.get_docs(collection_name, {"selector": {'status': status}}))
return {'total': total, "_id": statu... | self._list_project() | conditional_block |
taskdb.py | import json, time
from pyspider.database.base.taskdb import TaskDB as BaseTaskDB
from .couchdbbase import SplitTableMixin
class TaskDB(SplitTableMixin, BaseTaskDB):
collection_prefix = ''
def __init__(self, url, database='taskdb', username=None, password=None):
self.username = username
self.p... |
def get_task(self, project, taskid, fields=None):
if project not in self.projects:
self._list_project()
if project not in self.projects:
return
if fields is None:
fields = []
collection_name = self._get_collection_name(project)
ret = self... | if not project:
self._list_project()
if fields is None:
fields = []
if project:
projects = [project, ]
else:
projects = self.projects
for project in projects:
collection_name = self._get_collection_name(project)
for ... | identifier_body |
textsearch.perf.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
const n = 3;
const argv = minimist(process.argv);
const testWorkspaceArg = argv['testWorkspace'];
const testWorkspacePath = testWorkspaceArg ? path.resolve(testWorkspaceArg) : __dirname;
if (!fs.existsSync(testWorkspacePath)) {
throw new Error(`--testWorkspace doesn't exist`);
}
const telemetryServi... | {
return; // TODO@Rob find out why test fails when run from within VS Code
} | conditional_block |
textsearch.perf.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
}
let resolve;
let error;
return new TPromise((_resolve, _error) => {
resolve = _resolve;
error = _error;
// Don't wait on this promise, we're waiting on the event fired above
searchModel.search(query).then(
null,
_error);
});
}
const finishedEvents = [];
return r... | // Fail the runSearch() promise
error(e); | random_line_split |
textsearch.perf.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
};
| {
return defaultExperiments;
} | identifier_body |
textsearch.perf.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): void {
try {
const allEvents = telemetryService.events.map(e => JSON.stringify(e)).join('\n');
assert.equal(telemetryService.events.length, 3, 'Expected 3 telemetry events, got:\n' + allEvents);
const [firstRenderEvent, resultsShownEvent, resultsFinishedEvent] = telemetryService.events;
ass... | onComplete | identifier_name |
config.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... | a = configCache[project_root];
if (data === undefined) {
var configPath = path.join(project_root, '.xface', 'config.json');
if (!fs.existsSync(configPath)) {
data = '{}';
} else {
data = fs.readFileSync(configPath, 'utf-8');
}
}
configCache[project_roo... | };
config.read = function get_config(project_root) {
var dat | conditional_block |
config.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... | ject_root];
if (data === undefined) {
var configPath = path.join(project_root, '.xface', 'config.json');
if (!fs.existsSync(configPath)) {
data = '{}';
} else {
data = fs.readFileSync(configPath, 'utf-8');
}
}
configCache[project_root] = data;
retu... | _root, json);
} else {
configCache[project_root] = JSON.stringify(json);
}
return json;
};
config.setAutoPersist = function(value) {
autoPersist = value;
};
config.read = function get_config(project_root) {
var data = configCache[pro | identifier_body |
config.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... | shell = require('shelljs');
// Map of project_root -> JSON
var configCache = {};
var autoPersist = true;
/**
* 将opts中的属性值以json格式添加到<proj_root>/.xface/config.json中
* config.json包含的属性主要有id, name, lib, dev_type。id和name分别为工程的id和名称,
* dev_type用于标识是内部项目开发还是外部开发者使用('internal'表示内部项目开发,不存在或者为空时为外部使用)
* @param ... | */
var path = require('path'),
fs = require('fs'),
url = require('url'), | random_line_split |
config.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"... | config.write(project_root, json);
} else {
configCache[project_root] = JSON.stringify(json);
}
return json;
};
config.setAutoPersist = function(value) {
autoPersist = value;
};
config.read = function get_config(project_root) {
var data = configCache[project_root];
if (data === undefin... | identifier_name | |
streams.py | from operator import itemgetter
from lxml import html
from fuzzywuzzy import fuzz
from helpers.utils import cached_request, thread_pool, replace_all
class StreamsApi:
def __init__(self, data, cache):
self.data = data
self.cache = cache
def get(self, url='', ttl=3600):
base_url = 'livefootballol.me'... | 'fixture': fixture.id,
'stream': stream
})
self.data.set_multiple('event', items, 'fs_id')
def get_fixture_channels(self, events, fixture):
chann = []
items = []
for item in events:
evnt = item['event']
comp = fuzz.ratio(fixture.competition.name, evnt['compe... | for stream in streams:
items.append({
'fs_id': "%s_%s" % (fixture.id, stream.id), | random_line_split |
streams.py | from operator import itemgetter
from lxml import html
from fuzzywuzzy import fuzz
from helpers.utils import cached_request, thread_pool, replace_all
class StreamsApi:
def __init__(self, data, cache):
self.data = data
self.cache = cache
def get(self, url='', ttl=3600):
base_url = 'livefootballol.me'... |
def get_channels_page_links(self, url):
data = self.get(url)
items = []
if data is not None:
for channel in data.xpath('//div[@id="system"]//table//a[contains(@href, "acestream")]'):
items.append(channel.get('href'))
return items
def get_channels_links(self):
pages = self.get... | data = self.get('channels')
items = ['channels']
if data is not None:
for page in data.xpath('//div[@id="system"]//div[@class="pagination"]//a[@class=""]'):
items.append(page.get('href'))
return items | identifier_body |
streams.py | from operator import itemgetter
from lxml import html
from fuzzywuzzy import fuzz
from helpers.utils import cached_request, thread_pool, replace_all
class StreamsApi:
def __init__(self, data, cache):
self.data = data
self.cache = cache
def get(self, url='', ttl=3600):
base_url = 'livefootballol.me'... |
return items
def get_event_channels(self, url):
data = self.get(url=url, ttl=60)
items = []
if data is None:
return items
try:
root = data.xpath('//div[@id="system"]//table')[0]
comp = root.xpath('.//td[text()="Competition"]//following-sibling::td[1]')[0]
team = root.... | items.append(link.get('href')) | conditional_block |
streams.py | from operator import itemgetter
from lxml import html
from fuzzywuzzy import fuzz
from helpers.utils import cached_request, thread_pool, replace_all
class StreamsApi:
def __init__(self, data, cache):
self.data = data
self.cache = cache
def get(self, url='', ttl=3600):
base_url = 'livefootballol.me'... | (self, url):
data = self.get(url)
items = []
if data is not None:
for channel in data.xpath('//div[@id="system"]//table//a[contains(@href, "acestream")]'):
items.append(channel.get('href'))
return items
def get_channels_links(self):
pages = self.get_channels_pages()
items = t... | get_channels_page_links | identifier_name |
employer-profile-view.client.controller.test.js | 'use strict';
(function() {
// Employer profile view Controller Spec
describe('Employer profile view Controller Tests', function() {
// Initialize global variables
var EmployerProfileViewController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object... | EmployerProfileViewController = $controller('EmployerProfileViewController', {
$scope: scope
});
}));
it('Should do some controller test', inject(function() {
// The test logic
// ...
}));
});
}()); |
// Initialize the Employer profile view controller. | random_line_split |
linear_transformation.rs | use crate::{Point, Transformation, Vector};
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(C)]
pub struct LinearTransformation {
pub x: Vector,
pub y: Vector,
}
impl LinearTransformation {
pub fn new(x: Vector, y: Vector) -> LinearTransformation {
LinearTransformation { x, y }
}
pub fn i... | (v: Vector) -> LinearTransformation {
LinearTransformation::new(Vector::new(v.x, 0.0), Vector::new(0.0, v.y))
}
pub fn uniform_scaling(k: f32) -> LinearTransformation {
LinearTransformation::scaling(Vector::new(k, k))
}
pub fn scale(self, v: Vector) -> LinearTransformation {
Li... | scaling | identifier_name |
linear_transformation.rs | use crate::{Point, Transformation, Vector};
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(C)]
pub struct LinearTransformation {
pub x: Vector,
pub y: Vector,
}
impl LinearTransformation {
pub fn new(x: Vector, y: Vector) -> LinearTransformation {
LinearTransformation { x, y }
}
pub fn i... | LinearTransformation::new(
self.transform_vector(other.x),
self.transform_vector(other.y),
)
}
}
impl Transformation for LinearTransformation {
fn transform_point(&self, p: Point) -> Point {
(self.x * p.x + self.y * p.y).to_point()
}
fn transform_vector(... | pub fn compose(self, other: LinearTransformation) -> LinearTransformation { | random_line_split |
linear_transformation.rs | use crate::{Point, Transformation, Vector};
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(C)]
pub struct LinearTransformation {
pub x: Vector,
pub y: Vector,
}
impl LinearTransformation {
pub fn new(x: Vector, y: Vector) -> LinearTransformation {
LinearTransformation { x, y }
}
pub fn i... |
pub fn scaling(v: Vector) -> LinearTransformation {
LinearTransformation::new(Vector::new(v.x, 0.0), Vector::new(0.0, v.y))
}
pub fn uniform_scaling(k: f32) -> LinearTransformation {
LinearTransformation::scaling(Vector::new(k, k))
}
pub fn scale(self, v: Vector) -> LinearTransfo... | {
LinearTransformation::new(Vector::new(1.0, 0.0), Vector::new(0.0, 1.0))
} | identifier_body |
maquette.d.ts | /**
* Welcome to the API documentation of the **maquette** library.
*
* [[http://maquettejs.org/|To the maquette homepage]]
*/
/**
* A virtual representation of a DOM Node. Maquette assumes that [[VNode]] objects are never modified externally.
* Instances of [[VNode]] can be created using [[h]].
*/
export interf... | * Keeps an array of result objects synchronized with an array of source objects.
* See {@link http://maquettejs.org/docs/arrays.html|Working with arrays}.
*
* Mapping provides a [[map]] function that updates its [[results]].
* The [[map]] function can be called multiple times and the results will get created, remo... | */
export declare let createCache: <Result>() => CalculationCache<Result>;
/** | random_line_split |
lzwhutf16-min.js | // Copyright © 2016 Gary W. Hudson Esq.
// Released under GNU GPL 3.0
var lzwh = (function() {var z={
Decode:function(p)
{function f(){--h?k>>=1:(k=p.charCodeAt(q++)-32,h=15);return k&1}var h=1,q=0,k=0,e=[""],l=[],g=0,m=0,c="",d,a=0,n,b;
do{m&&(e[g-1]=c.charAt(0));m=a;l.push(c);d=0;for(a=g++;d!=a;)f()?d=(d+a>... | b,d){for(var a=0,e,c=l++;a!=c;)
e=a+c>>1,b>e?(a=e+1,f(1)):(c=e,f(0));if(!a){-1!=b&&(a=d+1);do{for(c=8;c--;a=(a-a%2)/2)f(a%2);f(a)}while(a)}}for(var q=[],k=0,
e=1,l=0,g=[],m=[],c=0,d=p.length,a,n,b=0;c<d;)a=p.charCodeAt(c++),g[b]?(n=g[b].indexOf(a),-1==n?(g[b].push(a),m[b].push(l+1),
c-=b?1:0,h(b,a),b=0):b=m[b][n]):(... | ( | identifier_name |
lzwhutf16-min.js | // Copyright © 2016 Gary W. Hudson Esq.
// Released under GNU GPL 3.0
var lzwh = (function() {var z={
Decode:function(p)
{function f(){--h?k>>=1:(k=p.charCodeAt(q++)-32,h=15);return k&1}var h=1,q=0,k=0,e=[""],l=[],g=0,m=0,c="",d,a=0,n,b;
do{m&&(e[g-1]=c.charAt(0));m=a;l.push(c);d=0;for(a=g++;d!=a;)f()?d=(d+a>... | unction h(b,d){for(var a=0,e,c=l++;a!=c;)
e=a+c>>1,b>e?(a=e+1,f(1)):(c=e,f(0));if(!a){-1!=b&&(a=d+1);do{for(c=8;c--;a=(a-a%2)/2)f(a%2);f(a)}while(a)}}for(var q=[],k=0,
e=1,l=0,g=[],m=[],c=0,d=p.length,a,n,b=0;c<d;)a=p.charCodeAt(c++),g[b]?(n=g[b].indexOf(a),-1==n?(g[b].push(a),m[b].push(l+1),
c-=b?1:0,h(b,a),b=0):b=... | b&&(k|=e);16384==e?(q.push(String.fromCharCode(k+32)),e=1,k=0):e<<=1}f | identifier_body |
utils.js | ///////////////////////
/// UTILS ///
///////////////////////
var u = {};
u.distance = function (p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return Math.sqrt((dx * dx) + (dy * dy));
};
u.angle = function(p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return u.degre... | }; | random_line_split | |
utils.js | ///////////////////////
/// UTILS ///
///////////////////////
var u = {};
u.distance = function (p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return Math.sqrt((dx * dx) + (dy * dy));
};
u.angle = function(p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return u.degre... |
}
return obj;
};
u.getVendorStyle = function (property, value) {
var obj = u.configStylePropertyObject(property);
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
obj[i] = value;
}
}
return obj;
};
u.configStylePropertyObject = function (prop) {
var obj = {};
... | {
if (typeof values === 'string') {
obj[i] = values + ' ' + time;
} else {
var st = '';
for (var j = 0, max = values.length; j < max; j += 1) {
st += values[j] + ' ' + time + ', ';
}
obj[i] = st.s... | conditional_block |
forms-single-select-example.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'forms-single-select-example',
templateUrl: './forms-single-select-example.component.html',
styleUrls: ['./fo... | ngOnInit() {
this.heroForm = this.fb.group({
age: [null, Validators.required],
});
}
toggleAgeDisable() {
if (this.heroForm.controls.age.disabled) {
this.heroForm.controls.age.enable();
} else {
this.heroForm.controls.age.disable();
... | ];
constructor(private fb: FormBuilder, private modalService: NgbModal) {
}
| random_line_split |
forms-single-select-example.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'forms-single-select-example',
templateUrl: './forms-single-select-example.component.html',
styleUrls: ['./fo... | (private fb: FormBuilder, private modalService: NgbModal) {
}
ngOnInit() {
this.heroForm = this.fb.group({
age: [null, Validators.required],
});
}
toggleAgeDisable() {
if (this.heroForm.controls.age.disabled) {
this.heroForm.controls.age.enable();
... | constructor | identifier_name |
forms-single-select-example.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'forms-single-select-example',
templateUrl: './forms-single-select-example.component.html',
styleUrls: ['./fo... | else {
this.heroForm.controls.age.disable();
}
}
showConfirm(content) {
this.modalService.open(content);
}
}
| {
this.heroForm.controls.age.enable();
} | conditional_block |
forms-single-select-example.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'forms-single-select-example',
templateUrl: './forms-single-select-example.component.html',
styleUrls: ['./fo... |
showConfirm(content) {
this.modalService.open(content);
}
}
| {
if (this.heroForm.controls.age.disabled) {
this.heroForm.controls.age.enable();
} else {
this.heroForm.controls.age.disable();
}
} | identifier_body |
printTileConfigCoords.py | import os, sys
sys.path = [os.path.join(os.getcwd(), "..") ] + sys.path
sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path
from flTile.amConfig import CreateAMConfig
def run():
tileConfig = CreateAMConfig()
#hostname = gethostname()
#machineDesc = tileConfig.getMachineDescByHostname(hostname)... |
fullRect = tileConfig.getMainDisplayRect()
print "FULL DISPLAY:", fullRect.width, fullRect.height
if __name__ == "__main__":
run()
| localRects = []
absoluteRects = []
for tile in machineDesc.tiles:
localRects.append(tileConfig.getLocalDrawRect(tile.uid))
absoluteRects.append(tileConfig.getAbsoluteFullDisplayRect(tile.uid))
print machineDesc.hostname, localRects, absoluteRects | conditional_block |
printTileConfigCoords.py | import os, sys
sys.path = [os.path.join(os.getcwd(), "..") ] + sys.path
sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path
from flTile.amConfig import CreateAMConfig
def run():
|
if __name__ == "__main__":
run()
| tileConfig = CreateAMConfig()
#hostname = gethostname()
#machineDesc = tileConfig.getMachineDescByHostname(hostname)
print "Machine, local rects, absolute rects"
for machineDesc in tileConfig.machines:
localRects = []
absoluteRects = []
for tile in machineDesc.tiles:
... | identifier_body |
printTileConfigCoords.py | import os, sys
sys.path = [os.path.join(os.getcwd(), "..") ] + sys.path
sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path
from flTile.amConfig import CreateAMConfig
def | ():
tileConfig = CreateAMConfig()
#hostname = gethostname()
#machineDesc = tileConfig.getMachineDescByHostname(hostname)
print "Machine, local rects, absolute rects"
for machineDesc in tileConfig.machines:
localRects = []
absoluteRects = []
for tile in machineDesc.tiles:
... | run | identifier_name |
printTileConfigCoords.py | import os, sys
sys.path = [os.path.join(os.getcwd(), "..") ] + sys.path
sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path
from flTile.amConfig import CreateAMConfig
def run():
tileConfig = CreateAMConfig()
#hostname = gethostname()
#machineDesc = tileConfig.getMachineDescByHostname(hostname)... |
if __name__ == "__main__":
run() | random_line_split | |
ball_ball.rs | use std::marker::PhantomData;
use na::Translate;
use na;
use math::{Scalar, Point, Vect};
use entities::shape::Ball;
use entities::inspection::Repr;
use queries::geometry::Contact;
use queries::geometry::contacts_internal;
use narrow_phase::{CollisionDetector, CollisionDispatcher};
/// Collision detector between two ... | (&self) -> usize {
match self.contact {
None => 0,
Some(_) => 1
}
}
#[inline]
fn colls(&self, out_colls: &mut Vec<Contact<P>>) {
match self.contact {
Some(ref c) => out_colls.push(c.clone()),
None => ()
}
}
}
| num_colls | identifier_name |
ball_ball.rs | use std::marker::PhantomData;
use na::Translate;
use na;
use math::{Scalar, Point, Vect};
use entities::shape::Ball;
use entities::inspection::Repr;
use queries::geometry::Contact;
use queries::geometry::contacts_internal;
use narrow_phase::{CollisionDetector, CollisionDispatcher};
/// Collision detector between two ... | contact: None,
mat_type: PhantomData
}
}
}
impl<P, M> CollisionDetector<P, M> for BallBall<P, M>
where P: Point,
M: 'static + Translate<P> {
fn update(&mut self,
_: &CollisionDispatcher<P, M>,
ma: &M,
a: &Repr<P, M>,... | #[inline]
pub fn new(prediction: <P::Vect as Vect>::Scalar) -> BallBall<P, M> {
BallBall {
prediction: prediction, | random_line_split |
ball_ball.rs | use std::marker::PhantomData;
use na::Translate;
use na;
use math::{Scalar, Point, Vect};
use entities::shape::Ball;
use entities::inspection::Repr;
use queries::geometry::Contact;
use queries::geometry::contacts_internal;
use narrow_phase::{CollisionDetector, CollisionDispatcher};
/// Collision detector between two ... |
#[inline]
fn colls(&self, out_colls: &mut Vec<Contact<P>>) {
match self.contact {
Some(ref c) => out_colls.push(c.clone()),
None => ()
}
}
}
| {
match self.contact {
None => 0,
Some(_) => 1
}
} | identifier_body |
lib.rs | // Copyright (c) 2016 Herman J. Radtke III <herman@hermanradtke.com>
//
// This file is part of carp-rs.
//
// carp-rs is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License,... | extern crate log;
#[cfg(unix)]
extern crate nix;
extern crate rand;
extern crate pcap;
extern crate crypto;
extern crate byteorder;
use std::result;
pub mod net;
mod error;
mod node;
pub mod advert;
pub mod ip_carp;
pub mod config;
pub mod carp;
pub type Result<T> = result::Result<T, error::Error>; | random_line_split | |
intrinsic.rs | use super::BackendTypes;
use crate::mir::operand::OperandRef;
use rustc_middle::ty::{self, Ty};
use rustc_span::Span;
use rustc_target::abi::call::FnAbi;
| pub trait IntrinsicCallMethods<'tcx>: BackendTypes {
/// Remember to add all intrinsics here, in `compiler/rustc_typeck/src/check/mod.rs`,
/// and in `library/core/src/intrinsics.rs`; if you need access to any LLVM intrinsics,
/// add them to `compiler/rustc_codegen_llvm/src/context.rs`.
fn codegen_intr... | random_line_split | |
glyph.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 https://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::Point2D;
#[cfg(all(
feature = "unstable",
any(target_feature = "sse2", tar... |
}
spaces
}
}
impl fmt::Debug for GlyphStore {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "GlyphStore:\n")?;
let mut detailed_buffer = self.detail_store.detail_buffer.iter();
for entry in self.entry_buffer.iter() {
if ent... | {
spaces += 1
} | conditional_block |
glyph.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 https://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::Point2D;
#[cfg(all(
feature = "unstable",
any(target_feature = "sse2", tar... | assert!(main_detail_offset + (detail_offset as usize) < self.detail_buffer.len());
&self.detail_buffer[main_detail_offset + (detail_offset as usize)]
}
fn ensure_sorted(&mut self) {
if self.lookup_is_sorted {
return;
}
// Sorting a unique vector is surprisin... | let i = self
.detail_lookup
.binary_search(&key)
.expect("Invalid index not found in detailed glyph lookup table!");
let main_detail_offset = self.detail_lookup[i].detail_offset; | random_line_split |
glyph.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 https://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::Point2D;
#[cfg(all(
feature = "unstable",
any(target_feature = "sse2", tar... |
fn is_initial(&self) -> bool {
*self == GlyphEntry::initial()
}
}
/// The id of a particular glyph within a font
pub type GlyphId = u32;
// TODO: make this more type-safe.
const FLAG_CHAR_IS_SPACE: u32 = 0x40000000;
#[cfg(feature = "unstable")]
#[cfg(any(target_feature = "sse2", target_feature = "n... | {
assert!(glyph_count <= u16::MAX as usize);
debug!(
"creating complex glyph entry: starts_cluster={}, starts_ligature={}, \
glyph_count={}",
starts_cluster, starts_ligature, glyph_count
);
GlyphEntry::new(glyph_count as u32)
} | identifier_body |
glyph.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 https://mozilla.org/MPL/2.0/. */
use app_units::Au;
use euclid::Point2D;
#[cfg(all(
feature = "unstable",
any(target_feature = "sse2", tar... | (&self) -> &[u32] {
// Statically assert identical sizes
let _ = mem::transmute::<GlyphEntry, u32>;
unsafe { mem::transmute::<&[GlyphEntry], &[u32]>(self.entry_buffer.as_slice()) }
}
pub fn char_is_space(&self, i: ByteIndex) -> bool {
assert!(i < self.len());
self.entry... | transmute_entry_buffer_to_u32_buffer | identifier_name |
label-container.js | import React from 'react';
import { Link } from 'react-router-dom';
import { sparqlConnect } from 'sparql-connect';
import Spinner from 'components/shared/spinner';
import { simsLink } from '../routes';
import D, { getLang } from 'i18n';
/**
* Builds the query that retrieves the products issued of a given series.
*/... | ({ simsURI, simsLabel }) {
return <Link to={simsLink(simsURI)}>{simsLabel}</Link>;
}
export default connector(SimsLabelBySeries, {
loading: () => <Spinner text={D.loadingSims} />,
});
| SimsLabelBySeries | identifier_name |
label-container.js | import React from 'react';
import { Link } from 'react-router-dom';
import { sparqlConnect } from 'sparql-connect';
import Spinner from 'components/shared/spinner';
import { simsLink } from '../routes';
import D, { getLang } from 'i18n';
/**
* Builds the query that retrieves the products issued of a given series.
*/... |
export default connector(SimsLabelBySeries, {
loading: () => <Spinner text={D.loadingSims} />,
});
| {
return <Link to={simsLink(simsURI)}>{simsLabel}</Link>;
} | identifier_body |
label-container.js | import React from 'react';
import { Link } from 'react-router-dom';
import { sparqlConnect } from 'sparql-connect';
import Spinner from 'components/shared/spinner';
import { simsLink } from '../routes';
import D, { getLang } from 'i18n';
/**
* Builds the query that retrieves the products issued of a given series.
*/... | }
export default connector(SimsLabelBySeries, {
loading: () => <Spinner text={D.loadingSims} />,
}); | function SimsLabelBySeries({ simsURI, simsLabel }) {
return <Link to={simsLink(simsURI)}>{simsLabel}</Link>; | random_line_split |
Nav.tsx | import React from "react";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
import { selectIsAuthenticated } from "../auth/authSlice";
const Nav = () => {
const { t } = useTranslation();
const isAuthenticated = useSelector(selectIsA... | }
return (
<nav>
<ul>
<li>
<Link to="/">LessPass</Link>
</li>
<li>
<Link data-testid="settings-link" to="/settings">{t("nav.settings")}</Link>
</li>
<li>
<Link data-testid="sign-in-link" to="/signIn">{t("nav.signin")}</Link>
</l... | ); | random_line_split |
Clone.test.ts | import { shallowMount } from '@vue/test-utils';
import T from '../../lang';
import contest_Clone from './Clone.vue';
describe('Clone.vue', () => {
beforeAll(() => {
const div = document.createElement('div');
div.id = 'root';
document.body.appendChild(div);
});
afterAll(() => {
const rootDiv = ... |
});
it('Should display the form', async () => {
const wrapper = shallowMount(contest_Clone);
expect(wrapper.text()).toContain(T.wordsTitle);
});
it('Should pass the right arguments to event', async () => {
const wrapper = shallowMount(contest_Clone, {
attachTo: '#root',
});
const ... | {
document.removeChild(rootDiv);
} | conditional_block |
Clone.test.ts | import { shallowMount } from '@vue/test-utils';
import T from '../../lang';
import contest_Clone from './Clone.vue';
describe('Clone.vue', () => {
beforeAll(() => {
const div = document.createElement('div');
div.id = 'root';
document.body.appendChild(div);
});
afterAll(() => {
const rootDiv = ... | });
it('Should pass the right arguments to event', async () => {
const wrapper = shallowMount(contest_Clone, {
attachTo: '#root',
});
const contest = {
alias: 'contestAlias',
title: 'Contest Title',
description: 'Contest description.',
};
await wrapper.setData(contest);... |
expect(wrapper.text()).toContain(T.wordsTitle); | random_line_split |
upgrade.py | # upgrade.py - test the upgrade transaction using RPM
#
# Copyright (C) 2012 Red Hat Inc.
#
# 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, or
# (at your option)... | def check(self, *args, **kwargs):
TransactionSetCore.check(self, *args, **kwargs)
# NOTE: rpm.TransactionSet throws out all problems but these
return [p for p in self.problems()
if p.type in (rpm.RPMPROB_CONFLICT, rpm.RPMPROB_REQUIRES)]
def add_install(self, path, key=... | if rv != rpm.RPMRC_OK and problems:
raise TransactionError(problems)
return rv
| random_line_split |
upgrade.py | # upgrade.py - test the upgrade transaction using RPM
#
# Copyright (C) 2012 Red Hat Inc.
#
# 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, or
# (at your option)... |
def get_details(self):
return None
def format_details(self):
raise NotImplementedError
def _log_probs(self):
for p in self.problems:
log.debug('%s -> "%s"', prob2dict(p), p)
def __str__(self):
if self.details:
return "\n ".join([self.desc+':'... | self.type = probtype
self.problems = [p for p in problems if p.type == self.type]
self.desc = probtypes.get(probtype)
self.details = self.get_details() | identifier_body |
upgrade.py | # upgrade.py - test the upgrade transaction using RPM
#
# Copyright (C) 2012 Red Hat Inc.
#
# 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, or
# (at your option)... | (self):
if self.logpipe:
self.closepipe()
| __del__ | identifier_name |
upgrade.py | # upgrade.py - test the upgrade transaction using RPM
#
# Copyright (C) 2012 Red Hat Inc.
#
# 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, or
# (at your option)... |
if otherpkg not in pkgprobs[thispkg]:
pkgprobs[thispkg][otherpkg] = set()
pkgprobs[thispkg][otherpkg].add(req)
return pkgprobs
def format_details(self):
return [_("%s requires %s") % (pkg, ", ".join(pkgprob))
for (pkg, pkgprob) in self.detai... | pkgprobs[thispkg] = {} | conditional_block |
test-registry-datasets.py | """Tests for registry module - datasets method"""
import vcr
from pygbif import registry
@vcr.use_cassette("test/vcr_cassettes/test_datasets.yaml")
def | ():
"registry.datasets - basic test"
res = registry.datasets()
assert dict == res.__class__
@vcr.use_cassette("test/vcr_cassettes/test_datasets_limit.yaml")
def test_datasets_limit():
"registry.datasets - limit param"
res = registry.datasets(limit=1)
assert dict == res.__class__
assert 1 =... | test_datasets | identifier_name |
test-registry-datasets.py | """Tests for registry module - datasets method"""
import vcr
from pygbif import registry
@vcr.use_cassette("test/vcr_cassettes/test_datasets.yaml")
def test_datasets():
"registry.datasets - basic test"
res = registry.datasets()
assert dict == res.__class__
@vcr.use_cassette("test/vcr_cassettes/test_data... | res = registry.datasets(limit=1)
assert dict == res.__class__
assert 1 == len(res["results"])
res = registry.datasets(limit=3)
assert dict == res.__class__
assert 3 == len(res["results"])
@vcr.use_cassette("test/vcr_cassettes/test_datasets_type.yaml")
def test_datasets_type():
"registry.d... | random_line_split | |
test-registry-datasets.py | """Tests for registry module - datasets method"""
import vcr
from pygbif import registry
@vcr.use_cassette("test/vcr_cassettes/test_datasets.yaml")
def test_datasets():
|
@vcr.use_cassette("test/vcr_cassettes/test_datasets_limit.yaml")
def test_datasets_limit():
"registry.datasets - limit param"
res = registry.datasets(limit=1)
assert dict == res.__class__
assert 1 == len(res["results"])
res = registry.datasets(limit=3)
assert dict == res.__class__
assert... | "registry.datasets - basic test"
res = registry.datasets()
assert dict == res.__class__ | identifier_body |
moveconnectionlabel.py | from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta):
self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__conn... | yield ConnectionMovedEvent(self.__connection_label.connection) | identifier_body | |
moveconnectionlabel.py | from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta):
self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__conn... | (self, ruler):
self.__connection_label.move(ruler, self.__label_position + self.__delta)
def _undo(self, ruler):
self.__connection_label.move(ruler, self.__label_position)
def get_updates(self):
yield ConnectionMovedEvent(self.__connection_label.connection)
| _redo | identifier_name |
moveconnectionlabel.py | from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta): |
@property
def description(self):
return "Moved label on connection in diagram {0}".format(self.__diagram_name)
def _do(self, ruler):
self.__label_position = self.__connection_label.get_position(ruler)
self._redo(ruler)
def _redo(self, ruler):
self.__connect... | self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__connection_label = connection_label
self.__delta = delta
self.__label_position = None | random_line_split |
string.rs | // Copyright 2015-2017 Daniel P. Clark & array_tool Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 dist... | se {
use string::SubstMarks;
return t.subst_marks(mrkrs.to_vec(), "\n")
}
},
}
},
Some(x) => {
wordwrap(t, chunk, offset+x+1, mrkrs)
},
}
};
wordwrap(self, width+1, 0, &mut markers)
}
}
| / String may continue
wordwrap(t, chunk, offset+1, mrkrs) // Recurse + 1 until next space
} el | conditional_block |
string.rs | // Copyright 2015-2017 Daniel P. Clark & array_tool Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 dist... | }
}
}
impl<'a> Iterator for GraphemeBytesIter<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<&'a [u8]> {
let mut result: Option<&[u8]> = None;
let mut idx = self.offset;
for _ in self.offset..self.source.len() {
idx += 1;
if self.offset < self.source.len() {
if self.... | GraphemeBytesIter {
source: source,
offset: 0,
grapheme_count: 0, | random_line_split |
string.rs | // Copyright 2015-2017 Daniel P. Clark & array_tool Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 dist... | elf, marks: Vec<usize>, chr: &'static str) -> String {
let mut output = Vec::<u8>::with_capacity(self.len());
let mut count = 0;
let mut last = 0;
for i in 0..self.len() {
let idx = i + 1;
if self.is_char_boundary(idx) {
if marks.contains(&count) {
count += 1;
las... | st_marks(&s | identifier_name |
string.rs | // Copyright 2015-2017 Daniel P. Clark & array_tool Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 dist... | wordwrap(self, width+1, 0, &mut markers)
}
}
| match t[offset..*vec![offset+chunk,t.len()].iter().min().unwrap()].rfind("\n") {
None => {
match t[offset..*vec![offset+chunk,t.len()].iter().min().unwrap()].rfind(" ") {
Some(x) => {
let mut eows = x; // end of white space
if offset+chunk < t.len() { // ch... | identifier_body |
promptForm.test.js | /*jshint undef:false, strict:false*/ // Note: to avoid having to write QUnit.module, etc
module('promptForm', {
setup: function () {
this.sinon = sinon.sandbox.create(); | }
});
test('construction', function () {
// given
this.sinon.stub(window, 'AutoComplete', function () {
this.focus = sinon.spy();
});
// when
var form = new window.PromptForm('#form', {
listUrl: '/someUrl'
});
// then
ok(form, 'created');
equal(window.AutoCompl... | $('<div id="form"><input id="name" /></div>').appendTo('#qunit-fixture');
},
teardown: function () {
this.sinon.restore();
detectLeaks(); | random_line_split |
issue-4448.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let (tx, rx) = channel::<&'static str>();
let t = thread::spawn(move|| {
assert_eq!(rx.recv().unwrap(), "hello, world");
});
tx.send("hello, world").unwrap();
t.join().ok().unwrap();
}
| main | identifier_name |
issue-4448.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let (tx, rx) = channel::<&'static str>();
let t = thread::spawn(move|| {
assert_eq!(rx.recv().unwrap(), "hello, world");
});
tx.send("hello, world").unwrap();
t.join().ok().unwrap();
} | identifier_body | |
jquery.effects.explode.min.js | /*
* jQuery UI Effects Explode 1.8.7
*
* Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Effects/Explode
*
* Depends: | e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duratio... | * jquery.effects.core.js
*/
(function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;... | random_line_split |
main.py | # -*- coding: utf-8 -*-
try:
import simplejson as json
except ImportError:
import json
import logging
import werkzeug
from openerp import http
from openerp.http import request
_logger = logging.getLogger(__name__)
class SipsController(http.Controller):
| _notify_url = '/payment/sips/ipn/'
_return_url = '/payment/sips/dpn/'
def _get_return_url(self, **post):
""" Extract the return URL from the data coming from sips. """
return_url = post.pop('return_url', '')
if not return_url:
tx_obj = request.registry['payment.transaction']... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.