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
service.js
const fs = require('fs'); const path = require('path'); class Service {
() { this.getFileRecursevly = this.getFileRecursevly.bind(this); this.getFiles = this.getFiles.bind(this); } getFileRecursevly(folderPath, shortPath = '') { var files = []; var folder = fs.readdirSync(path.resolve(__dirname, folderPath)); var x = folder.forEach(file => { ...
constructor
identifier_name
service.js
const fs = require('fs'); const path = require('path');
constructor() { this.getFileRecursevly = this.getFileRecursevly.bind(this); this.getFiles = this.getFiles.bind(this); } getFileRecursevly(folderPath, shortPath = '') { var files = []; var folder = fs.readdirSync(path.resolve(__dirname, folderPath)); var x = folder.for...
class Service {
random_line_split
urls.py
"""course_discovery URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') C...
urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls)))
url('', include('social.apps.django_app.urls', namespace='social')), ] if settings.DEBUG and os.environ.get('ENABLE_DJANGO_TOOLBAR', False): # pragma: no cover import debug_toolbar # pylint: disable=import-error
random_line_split
urls.py
"""course_discovery URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') C...
import debug_toolbar # pylint: disable=import-error urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls)))
conditional_block
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to...
raise OSError( """Unable to determine user's application-data directory, no ${HOME} or ${APPDATA} in environment""" ) if __name__ == "__main__": print 'AppData', appdatadirectory()
return possible
conditional_block
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to...
( ): """Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for Win32 systems i...
appdatadirectory
identifier_name
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to...
if __name__ == "__main__": print 'AppData', appdatadirectory()
"""Attempt to retrieve the current user's app-data directory This is the location where application-specific files should be stored. On *nix systems, this will be the ${HOME}/.config directory. On Win32 systems, it will be the "Application Data" directory. Note that for Win32 systems it is norma...
identifier_body
homedirectory.py
"""Attempt to determine the current user's "system" directories""" try: ## raise ImportError from win32com.shell import shell, shellcon except ImportError: shell = None try: import _winreg except ImportError: _winreg = None import os, sys ## The registry keys where the SHGetFolderPath values appear to...
if name in os.environ: return os.path.join( os.environ[name], '.config' ) # well, someone's being naughty, see if we can get ~ to expand to a directory... possible = os.path.abspath(os.path.expanduser( '~/.config' )) if os.path.exists( possible ): return possible raise OSErro...
# a direct registry access, likely to fail on Win98/Me return _winreg_getShellFolder( 'AppData' ) # okay, what if for some reason _winreg is missing? would we want to allow ctypes? ## default case, look for name in environ... for name in ['APPDATA', 'HOME']:
random_line_split
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators i...
if not (self.get("language") and self.language in Languages.ALL): self.language = settings.MOBILE_ID_DEFAULT_LANGUAGE return result class MobileIdSessionData(InterimSessionData): session_id: str
random_line_split
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators i...
raise InvalidParameter(param="phone_number") if not id_code_ee_is_valid(self.id_code): if not raise_exception: return False raise InvalidIdCode if not (self.get("language") and self.language in Languages.ALL): s...
return False
conditional_block
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators i...
(PredictableDict): phone_number: str id_code: str language: Optional[str] def is_valid(self, raise_exception=True): result = super().is_valid(raise_exception=raise_exception) if result: if not self.phone_number or PHONE_NUMBER_REGEXP and not re.match(PHONE_NUMBER_REGEXP, sel...
UserInput
identifier_name
types.py
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators i...
session_id: str
identifier_body
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod mac...
" = \"{}\" \t(downloads: {})\n", cr.max_version, cr.downloads ); if !quiet { cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentati...
fn show_crate(t: &mut Box<term::StdoutTerminal>, cr: &EncodableCrate, quiet: bool, max_len: usize) { p_green!(t, "{}", cr.name.pad_to_width(max_len)); p_white!( t,
random_line_split
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod mac...
} main!(|args: Cli| { let Cli::Ssearch { query, page, limit, quiet, recent, } = args; let mut t = term::stdout().unwrap(); // TODO: Add decoding of updated_at and allow to use it for sorting let (total, crates) = query_crates_io(&query, page, limit, recent...
{ cr.description .as_ref() .map(|description| p_yellow!(t, " -> {}\n", description.clone().trim())); cr.documentation .as_ref() .map(|documentation| p_white!(t, " docs: {}\n", documentation)); cr.homepage .as_ref() .map(|...
conditional_block
main.rs
#![allow(unused_must_use)] extern crate pad; #[macro_use] extern crate quicli; extern crate reqwest; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate term; use pad::PadStr; use reqwest::Url; use std::process; use std::str; use quicli::prelude::*; #[macro_use] mod mac...
( query: &str, page: usize, per_page: usize, recent: bool, ) -> Result<(i32, Vec<EncodableCrate>)> { let sort = if recent { "recent-downloads" } else { "downloads" }; let url = Url::parse_with_params( "https://crates.io/api/v1/crates", &[ ("q",...
query_crates_io
identifier_name
app.config.ts
import { InjectionToken } from '@angular/core'; export let APP_CONFIG = new InjectionToken('app.config'); export const AppConfig: any = { votesLimit: 3, topHeroesLimit: 5, snackBarDuration: 3000, repositoryURL: 'https://github.com/ismaestro/angular8-example-app', sentryDSN: 'https://38434a1b115f41d3a31e356c...
upgradeInsecureRequests: true, styleSrc: [ '\'self\'', '\'unsafe-inline\'', 'https://*.googleapis.com' ], scriptSrc: [ '\'self\'', '\'unsafe-inline\'', 'http://*.googletagmanager.com', 'https://*.google-analytics.com' ] } };
'https://sentry.io', 'ws://localhost:4200' ], frameAncestors: ['\'self\''],
random_line_split
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(t...
if not name: discovered_lock.acquire() global discovered tmp = [] print discovered for i in discovered: tmp.append(i) discovered_lock.release() print tmp return tmp else: discovered_lock.acquire() # print discovered ...
d = mDNS_Discovery(reg_type) d.start() discovery_running = True
conditional_block
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(t...
(self, sdRef, flags, interfaceIndex, errorCode, fullname, hosttarget, port, txtRecord): if errorCode == pybonjour.kDNSServiceErr_NoError: #print 'Resolved service:' #print ' fullname =', fullname #print ' hosttarget =', hosttarget #print ' ...
resolve_cb
identifier_name
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(t...
discovered_lock.acquire() del self.discovered[hash(serviceName+regtype)] for item in discovered: if item[0] == serviceName: discovered.remove(item) discovered_lock.release() return if hash(serviceName+regtype) not i...
if not (flags & pybonjour.kDNSServiceFlagsAdd): # print 'Service removed: ', serviceName, " ", regtype
random_line_split
discovery.py
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(t...
def discover_mDNS(name = None, reg_type = "_kspace._tcp"): global discovery_running if not discovery_running: # print "Starting mDNS discovery" d = mDNS_Discovery(reg_type) d.start() discovery_running = True if not name: discovered_lock.acquire() global di...
print "Manual Discovery. Enter details:" ssname = raw_input("SmartSpace name >") ip = raw_input("SmartSpace IP Address >" ) port = raw_input("SmartSpace Port >" ) print ssname, ip, port rtuple = ( ssname, ("TCP", (ip,int(port)) )) return rtuple
identifier_body
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBui...
return True # anyone can do this..
conditional_block
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBui...
def actionAllowed(self, action, request, *args): """Is this ACTION allowed, given this http REQUEST?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: if cfg == 'auth' or callable(cfg): ...
"""Does this action require an authentication form?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False
identifier_body
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBui...
(self, action): """Does this action require an authentication form?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False def actionAllo...
needAuthForm
identifier_name
authz.py
from buildbot.status.web.auth import IAuth class Authz(object): """Decide who can do what.""" knownActions = [ # If you add a new action here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBui...
def advertiseAction(self, action): """Should the web interface even show the form for ACTION?""" if action not in self.knownActions: raise KeyError("unknown action") cfg = self.config.get(action, False) if cfg: return True return False def needAu...
if kwargs: raise ValueError("unknown authorization action(s) " + ", ".join(kwargs.keys()))
random_line_split
compositionevent.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 crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use...
#[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &CompositionEventBinding::CompositionEventInit, ) -> Fallible<DomRoot<CompositionEvent>> { let event = CompositionEvent::new( window, type_, init.parent...
{ let ev = reflect_dom_object( Box::new(CompositionEvent { uievent: UIEvent::new_inherited(), data: data, }), window, CompositionEventBinding::Wrap, ); ev.uievent .InitUIEvent(type_, can_bubble, cancelabl...
identifier_body
compositionevent.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 crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use...
uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEvent> { reflect_dom_object( Box::new(CompositionEvent::new_inherited()), window, CompositionEventBinding::W...
impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent {
random_line_split
compositionevent.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 crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ self, CompositionEventMethods, }; use...
{ uievent: UIEvent, data: DOMString, } impl CompositionEvent { pub fn new_inherited() -> CompositionEvent { CompositionEvent { uievent: UIEvent::new_inherited(), data: DOMString::new(), } } pub fn new_uninitialized(window: &Window) -> DomRoot<CompositionEve...
CompositionEvent
identifier_name
population.py
"""Provide infrastructure to allow exploration of variations within populations. Uses the gemini framework (https://github.com/arq5x/gemini) to build SQLite database of variations for query and evaluation. """ import collections import csv from distutils.version import LooseVersion import os import subprocess import ...
(samples, base_vcf): """Create a GEMINI-compatible PED file, including gender, family and phenotype information. Checks for a specified `ped` file in metadata, and will use sample information from this file before reconstituting from metadata information. """ def _code_gender(data): g = dd....
create_ped_file
identifier_name
population.py
"""Provide infrastructure to allow exploration of variations within populations. Uses the gemini framework (https://github.com/arq5x/gemini) to build SQLite database of variations for query and evaluation. """ import collections import csv from distutils.version import LooseVersion import os import subprocess import ...
else: return False def get_gemini_files(data): """Enumerate available gemini data files in a standard installation. """ try: from gemini import annotations, config except ImportError: return {} return {"base": config.read_gemini_config()["annotation_dir"], "...
if not gresources: gresources = samples[0]["genome_resources"] return (tz.get_in(["aliases", "human"], gresources, False) and _has_gemini(samples[0]))
conditional_block
population.py
"""Provide infrastructure to allow exploration of variations within populations. Uses the gemini framework (https://github.com/arq5x/gemini) to build SQLite database of variations for query and evaluation. """ import collections import csv from distutils.version import LooseVersion import os import subprocess import ...
def _has_gemini(data): from bcbio import install gemini_dir = install.get_gemini_dir(data) return ((os.path.exists(gemini_dir) and len(os.listdir(gemini_dir)) > 0) and os.path.exists(os.path.join(os.path.dirname(gemini_dir), "gemini-config.yaml"))) def do_db_build(samples, need_bam=True, gres...
"""Retrieve a multiple sample VCF file in a standard location. Handles inputs with multiple repeated input files from batches. """ unique_fnames = [] for f in fnames: if f not in unique_fnames: unique_fnames.append(f) out_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"...
identifier_body
population.py
"""Provide infrastructure to allow exploration of variations within populations. Uses the gemini framework (https://github.com/arq5x/gemini) to build SQLite database of variations for query and evaluation. """ import collections import csv from distutils.version import LooseVersion import os import subprocess import ...
batch_groups, singles, out_retrieve, extras = _group_by_batches(samples, _has_variant_calls) to_process = [] has_batches = False for (name, caller), info in batch_groups.iteritems(): fnames = [x[0] for x in info] to_process.append([fnames, (str(name), caller, True), [x[1] for x in info],...
return False def prep_db_parallel(samples, parallel_fn): """Prepares gemini databases in parallel, handling jointly called populations. """
random_line_split
inject.py
#First parameter is path for binary file containing instructions to be injected #Second parameter is Process Identifier for process to be injected to import binascii import sys from ctypes import * if len(sys.argv) < 3: print("usage inject.py <shellcodefile.bin> <pid>") sys.exit(1) file = open(sys.argv[1],'rb')...
if(handle1 == 0): print("handle1 = = 0"); sys.exit(1) windll.kernel32.CloseHandle(handle)
random_line_split
inject.py
#First parameter is path for binary file containing instructions to be injected #Second parameter is Process Identifier for process to be injected to import binascii import sys from ctypes import * if len(sys.argv) < 3: print("usage inject.py <shellcodefile.bin> <pid>") sys.exit(1) file = open(sys.argv[1],'rb')...
windll.kernel32.CloseHandle(handle)
print("handle1 = = 0"); sys.exit(1)
conditional_block
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name (...
return None # I had to copy (and slightly modify) those utils from django-admin-tools # to override get_admin_site def get_avail_models(context): """ Returns (model, perm,) for all models user can possibly see """ items = [] admin_site = get_admin_site(context) for model, model_admin in list(adm...
mod, inst = menu_cls.rsplit('.', 1) mod = import_module(mod) return getattr(mod, inst)()
conditional_block
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name (...
""" Returns the admin change url. """ app_label = model._meta.app_label return reverse('%s:app_list' % get_admin_site_name(context), args=(app_label,)) def _get_admin_change_url(self, model, context): """ Returns the admin change url. ...
included = ["*"] return filter_models(context, included, excluded) def _get_admin_app_list_url(self, model, context):
random_line_split
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name (...
class AppListElementMixin(object): """ Mixin class for AppList and ModelList MenuItem. """ def _visible_models(self, context): included = self.models[:] excluded = self.exclude[:] if excluded and not included: included = ["*"] return filter_models(contex...
""" This method can be overwritten to check if current user can see this element. """ return True
identifier_body
utils.py
""" Menu utilities. """ from fnmatch import fnmatch from django.utils.importlib import import_module from django.core.urlresolvers import reverse from wpadmin.utils import ( get_wpadmin_settings, get_admin_site, get_admin_site_name) def get_menu_cls(menu, admin_site_name='admin'): """ menu - menu name (...
(context): """ Returns (model, perm,) for all models user can possibly see """ items = [] admin_site = get_admin_site(context) for model, model_admin in list(admin_site._registry.items()): perms = model_admin.get_model_perms(context.get('request')) if True not in list(perms.values()): ...
get_avail_models
identifier_name
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn chop<T: Ord>(item : T, slice : &[T]) -> i32
fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5])); assert_...
{ let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); match comparison { Less => ...
identifier_body
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn chop<T: Ord>(item : T, slice : &[T]) -> i32 { let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low +...
return -1; } fn main() { println!("{}", chop(3, &[1,3,5])); } #[test] fn test_chop() { assert_eq!(-1, chop(3, &[])); assert_eq!(-1, chop(3, &[1])); assert_eq!(0, chop(1, &[1])); assert_eq!(0, chop(1, &[1, 3, 5])); assert_eq!(1, chop(3, &[1, 3, 5])); assert_eq!(2, chop(5, &[1, 3, 5...
Equal => return mid_index as i32 } width /= 2; }
random_line_split
main.rs
use std::cmp::Ord; use std::cmp::Ordering::{Less, Equal, Greater}; fn
<T: Ord>(item : T, slice : &[T]) -> i32 { let length = slice.len(); // Catch empty slices if length < 1 { return -1; } let mut width = length; let mut low = 0; while width > 0 { let mid_index = low + (width / 2); let comparison = item.cmp(&slice[mid_index]); ...
chop
identifier_name
borrowck-unboxed-closures.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 ...
{}
identifier_body
borrowck-unboxed-closures.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 ...
f(1, 2); //~ ERROR use of moved value } fn main() {}
random_line_split
borrowck-unboxed-closures.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 ...
<F:FnMut(isize, isize) -> isize>(f: F) { f(1, 2); //~ ERROR cannot borrow immutable local variable } fn c<F:FnOnce(isize, isize) -> isize>(f: F) { f(1, 2); f(1, 2); //~ ERROR use of moved value } fn main() {}
b
identifier_name
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
fmt
identifier_name
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::...
} } impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
{ Ok(None) }
conditional_block
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::...
} impl<N: DName + fmt::Display> fmt::Display for Srv<N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} {} {} {}", self.priority, self.weight, self.port, self.target) } }
{ if rtype == Rtype::Srv { Srv::parse_always(parser).map(Some) } else { Ok(None) } }
identifier_body
rfc2782.rs
//! Record data from [RFC 2782]. //! //! This RFC defines the Srv record type. //! //! [RFC 2782]: https://tools.ietf.org/html/rfc2782 use std::fmt; use ::bits::{Composer, ComposeResult, DNameSlice, ParsedRecordData, Parser, ParseResult, RecordData, DName, DNameBuf, ParsedDName}; use ::iana::Rtype; use ::...
priority: u16, weight: u16, port: u16, target: N } impl<N: DName> Srv<N> { pub fn new(priority: u16, weight: u16, port: u16, target: N) -> Self { Srv { priority: priority, weight: weight, port: port, target: target } } pub fn priority(&self) -> u16 { self.priority } pub fn weig...
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Srv<N: DName> {
random_line_split
0004_auto_20170703_1156.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-03 18:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration):
dependencies = [ ('wiblog', '0003_auto_20160325_1441'), ] operations = [ migrations.AlterModelManagers( name='comment', managers=[ ('approved', django.db.models.manager.Manager()), ], ), migrations.AlterModelManagers( ...
identifier_body
0004_auto_20170703_1156.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-03 18:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager
class Migration(migrations.Migration): dependencies = [ ('wiblog', '0003_auto_20160325_1441'), ] operations = [ migrations.AlterModelManagers( name='comment', managers=[ ('approved', django.db.models.manager.Manager()), ], ), ...
random_line_split
0004_auto_20170703_1156.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-03 18:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager class
(migrations.Migration): dependencies = [ ('wiblog', '0003_auto_20160325_1441'), ] operations = [ migrations.AlterModelManagers( name='comment', managers=[ ('approved', django.db.models.manager.Manager()), ], ), migrations....
Migration
identifier_name
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, ...
(id, callback) { if (!id) { return callback(new Error('id is not defined')); } return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); ...
get
identifier_name
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, ...
if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).exec(callback); } function getForUser(user, query, callback) { const id = user._id || user;...
random_line_split
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, ...
function setAcknowledged(usernotification, acknowledged, callback) { if (!usernotification) { return callback(new Error('usernotification is required')); } usernotification.acknowledged = acknowledged; usernotification.save(callback); } function setAllRead(usernotifications, read, callback) { if (!use...
{ UserNotification.remove(query, callback); }
identifier_body
usernotification.js
'use strict'; const async = require('async'); const mongoose = require('mongoose'); const UserNotification = mongoose.model('Usernotification'); const DEFAULT_LIMIT = 50; const DEFAULT_OFFSET = 0; module.exports = { countForUser, create, get, getAll, getForUser, remove, setAcknowledged, setAllRead, ...
return UserNotification.findById(id).exec(callback); } function getAll(ids, callback) { if (!ids) { return callback(new Error('id is not defined')); } const formattedIds = ids.map(id => mongoose.Types.ObjectId(id)); const query = { _id: { $in: formattedIds } }; return UserNotification.find(query).e...
{ return callback(new Error('id is not defined')); }
conditional_block
profiler-plugin.js
/* profiler-plugin.js is part of Aloha Editor project http://aloha-editor.org * * Aloha Editor is a WYSIWYG HTML5 inline editing library and editor. * Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria. * Contributors http://aloha-editor.org/contribution.php * * Aloha Editor is free software;...
( path, obj ) { if ( typeof path !== 'string' ) { return null; } var parts = path.split( '.' ), pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ), prop; obj = resolvePath( pathToProp, obj ); if ( !obj ) { return null; } if ( parts.length > 1 ) { ...
parseObjectPath
identifier_name
profiler-plugin.js
/* profiler-plugin.js is part of Aloha Editor project http://aloha-editor.org * * Aloha Editor is a WYSIWYG HTML5 inline editing library and editor. * Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria. * Contributors http://aloha-editor.org/contribution.php * * Aloha Editor is free software;...
return { obj : obj[ prop ], path : path, parentObj : obj, propName : prop }; }; var panel; function initSidebarPanel(sidebar) { sidebar.addPanel( { id : 'aloha-devtool-profiler-panel', title : 'Aloha Profiler', expanded : true, activeOn : true, ...
pathToProp ); } else { prop = lastProp; } }
random_line_split
profiler-plugin.js
/* profiler-plugin.js is part of Aloha Editor project http://aloha-editor.org * * Aloha Editor is a WYSIWYG HTML5 inline editing library and editor. * Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria. * Contributors http://aloha-editor.org/contribution.php * * Aloha Editor is free software;...
else { prop = lastProp; } } return { obj : obj[ prop ], path : path, parentObj : obj, propName : prop }; }; var panel; function initSidebarPanel(sidebar) { sidebar.addPanel( { id : 'aloha-devtool-profiler-panel', title : 'Aloha Profiler', ...
{ console.error( 'Aloha.Profiler', 'Property "' + lastProp + '" does not exist in object ' + pathToProp ); }
conditional_block
profiler-plugin.js
/* profiler-plugin.js is part of Aloha Editor project http://aloha-editor.org * * Aloha Editor is a WYSIWYG HTML5 inline editing library and editor. * Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria. * Contributors http://aloha-editor.org/contribution.php * * Aloha Editor is free software;...
; function parseObjectPath( path, obj ) { if ( typeof path !== 'string' ) { return null; } var parts = path.split( '.' ), pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ), prop; obj = resolvePath( pathToProp, obj ); if ( !obj ) { return null; } ...
{ if ( typeof path !== 'string' ) { return path; } if ( !obj || typeof obj !== 'object' ) { obj = window; } var parts = path.split( '.' ), i = 0, j = parts.length; for ( ; i < j; ++i ) { obj = obj[ parts[ i ] ]; if ( typeof obj === 'undefined' ) { console.error( ...
identifier_body
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl Par...
}
{ write!(f, "{}", &self[..]) }
identifier_body
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl Par...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "InternedStr({:?})", self.0) } } impl fmt::Display for InternedStr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self[..]) } }
fmt
identifier_name
interner.rs
use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; use std::ops::Deref; use Result; use base::fnv::FnvMap; use gc::{GcPtr, Gc, Traverseable}; use array::Str; /// Interned strings which allow for fast equality checks and hashing #[derive(Copy, Clone, Eq)] pub struct InternedStr(GcPtr<Str>); impl Par...
impl PartialOrd for InternedStr { fn partial_cmp(&self, other: &InternedStr) -> Option<Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } impl Ord for InternedStr { fn cmp(&self, other: &InternedStr) -> Ordering { self.as_ptr().cmp(&other.as_ptr()) } } impl Hash for InternedStr...
random_line_split
0012_video.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', model...
identifier_body
0012_video.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
Migration
identifier_name
0012_video.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-26 09:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('directorio', '0011_auto_20160225_0957'), ] operations = [ migrations.CreateM...
), ]
random_line_split
ResourceConfig.ts
/** * Copyright (c) Egret-Labs.org. Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, dist...
{ public constructor() { RES["configInstance"] = this; } /** * 根据组名获取组加载项列表 * @method RES.ResourceConfig#getGroupByName * @param name {string} 组名 * @returns {Array<egret.ResourceItem>} */ public getGroupByName(name:string):Array<ResourceIte...
ResourceConfig
identifier_name
ResourceConfig.ts
/** * Copyright (c) Egret-Labs.org. Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, dist...
esourceItem = new ResourceItem(data.name, data.url, data.type); resItem.data = data; return resItem; } } }
ta:any):ResourceItem { var resItem:R
identifier_body
ResourceConfig.ts
/** * Copyright (c) Egret-Labs.org. Permission is hereby granted, free of charge, * to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, dist...
*/ public getResourceItem(key:string):ResourceItem { var data:any = this.keyMap[key]; if (data) return this.parseResourceItem(data); return null; } /** * 转换Object数据为ResourceItem对象 */ private parseResourceItem...
random_line_split
atn-generate-food-web.py
#!/usr/bin/env python3 """ Generates a plot and JSON file describing a food web. Files are stored in a directory named based on the species in the food web. If --parent-dir is not specified, the parent directory is determined automatically based on DATA_HOME. """ import os import sys import argparse from atntools ...
if args.subparser_name == 'generate': subweb = foodwebs.serengeti_predator_complete_subweb(args.size, args.num_basal_species) node_ids = sorted(subweb.nodes()) food_web_id = '-'.join([str(x) for x in node_ids]) if args.parent_dir is None: food_web_dir = util.get_food_web_dir(food_web_id) ...
parser.print_usage() sys.exit(1)
conditional_block
atn-generate-food-web.py
#!/usr/bin/env python3 """ Generates a plot and JSON file describing a food web. Files are stored in a directory named based on the species in the food web. If --parent-dir is not specified, the parent directory is determined automatically based on DATA_HOME. """ import os import sys import argparse from atntools ...
figsize=args.figsize, dpi=args.dpi) with open(os.path.join(food_web_dir, 'foodweb.{}.json'.format(food_web_id)), 'w') as f: print(foodwebs.food_web_json(subweb), file=f)
output_file=os.path.join(food_web_dir, 'foodweb.{}.png'.format(food_web_id)),
random_line_split
models.py
from __future__ import unicode_literals from future.builtins import str from future.utils import with_metaclass from json import loads try: from urllib.request import urlopen from urllib.parse import urlencode except ImportError: from urllib import urlopen, urlencode from django.contrib.contenttypes.gener...
``get_absolute_url`` defined, to ensure all search results contains a URL. """ name = self.__class__.__name__ raise NotImplementedError("The model %s does not have " "get_absolute_url defined" % name) def set_short_url(self): """ ...
def get_absolute_url(self): """ Raise an error if called on a subclass without
random_line_split
models.py
from __future__ import unicode_literals from future.builtins import str from future.utils import with_metaclass from json import loads try: from urllib.request import urlopen from urllib.parse import urlencode except ImportError: from urllib import urlopen, urlencode from django.contrib.contenttypes.gener...
(models.Model): """ Abstract model that provides ownership of an object for a user. """ user = models.ForeignKey(user_model_name, verbose_name=_("Author"), related_name="%(class)ss") class Meta: abstract = True def is_editable(self, request): """ Restrict in-li...
Ownable
identifier_name
models.py
from __future__ import unicode_literals from future.builtins import str from future.utils import with_metaclass from json import loads try: from urllib.request import urlopen from urllib.parse import urlencode except ImportError: from urllib import urlopen, urlencode from django.contrib.contenttypes.gener...
user = kw["instance"] if user.is_staff and not user.is_superuser: perm, created = SitePermission.objects.get_or_create(user=user) if created or perm.sites.count() < 1: perm.sites.add(current_site_id()) # We don't specify the user model here, because with 1.5's custom # user models,...
return
conditional_block
models.py
from __future__ import unicode_literals from future.builtins import str from future.utils import with_metaclass from json import loads try: from urllib.request import urlopen from urllib.parse import urlencode except ImportError: from urllib import urlopen, urlencode from django.contrib.contenttypes.gener...
def get_next_by_publish_date(self, **kwargs): """ Retrieves next object by publish date. """ return self._get_next_or_previous_by_publish_date(True, **kwargs) def get_previous_by_publish_date(self, **kwargs): """ Retrieves previous object by publish date. ...
""" Retrieves next or previous object by publish date. We implement our own version instead of Django's so we can hook into the published manager and concrete subclasses. """ arg = "publish_date__gt" if is_next else "publish_date__lt" order = "publish_date" if is_next els...
identifier_body
remote.ts
import { CallbacksRegistry } from '../remote/callbacks-registry'; import { isPromise, isSerializableObject, serialize, deserialize } from '../../common/type-utils'; import { MetaTypeFromRenderer, ObjectMember, ObjProtoDescriptor, MetaType } from '../../common/remote/types'; import { ipcRendererInternal } from '../ipc-r...
} else { let ret; if ('id' in meta) { const cached = getCachedRemoteObject(meta.id); if (cached !== undefined) { return cached; } } // A shadow class to represent the remote function object. if (meta.type === 'function') { const remoteFunction = function (this: any, ...args: any...
} else if (meta.type === 'exception') { if (meta.value.type === 'error') { throw metaToError(meta.value); } else { throw new Error(`Unexpected value type in exception: ${meta.value.type}`); }
random_line_split
remote.ts
import { CallbacksRegistry } from '../remote/callbacks-registry'; import { isPromise, isSerializableObject, serialize, deserialize } from '../../common/type-utils'; import { MetaTypeFromRenderer, ObjectMember, ObjProtoDescriptor, MetaType } from '../../common/remote/types'; import { ipcRendererInternal } from '../ipc-r...
// Populate object's members from descriptors. // The |ref| will be kept referenced by |members|. // This matches |getObjectMembers| in rpc-server. function setObjectMembers (ref: any, object: any, metaId: number, members: ObjectMember[]) { if (!Array.isArray(members)) return; for (const member of members) { ...
{ const valueToMeta = (value: any): any => { // Check for circular reference. if (visited.has(value)) { return { type: 'value', value: null }; } if (value && value.constructor && value.constructor.name === 'NativeImage') { return { type: 'nativeimage', value: seriali...
identifier_body
remote.ts
import { CallbacksRegistry } from '../remote/callbacks-registry'; import { isPromise, isSerializableObject, serialize, deserialize } from '../../common/type-utils'; import { MetaTypeFromRenderer, ObjectMember, ObjProtoDescriptor, MetaType } from '../../common/remote/types'; import { ipcRendererInternal } from '../ipc-r...
(): WebContents { const command = IPC_MESSAGES.BROWSER_GET_CURRENT_WEB_CONTENTS; const meta = ipcRendererInternal.sendSync(command, contextId, getCurrentStack()); return metaToValue(meta); } // Get a global object in browser. export function getGlobal<T = any> (name: string): T { const command = IPC_MESSAGES....
getCurrentWebContents
identifier_name
sandbox.ts
namespace $ { export class $mol_func_sandbox { static blacklist = new Set([ ( function() {} ).constructor , ( async function() {} ).constructor , ( function*() {} ).constructor , ( async function*() {} ).constructor , eval , setTimeout , setInterval , ]) static whitelist = new WeakSet()...
() { return false }, apply( val , host , args ) { return safe_value( val.call( host , ... args ) ) }, construct( val , args ) { return safe_value( new val( ... args ) ) }, }) this.whitelist.add( proxy ) return proxy } return this._make = ( ( ... contexts : Ob...
preventExtensions
identifier_name
sandbox.ts
namespace $ { export class $mol_func_sandbox { static blacklist = new Set([ ( function() {} ).constructor , ( async function() {} ).constructor , ( function*() {} ).constructor , ( async function*() {} ).constructor , eval , setTimeout , setInterval , ]) static whitelist = new WeakSet()...
Object.defineProperty( AsyncGeneratorFunction.prototype , 'constructor' , { value : undefined } ) delete Object.prototype.__proto__ for( const Class of [ String , Number , BigInt , Boolean , Array , Object , Promise , Symbol , RegExp , Window, Error , RangeError , ReferenceError , SyntaxErr...
var AsyncGeneratorFunction = AsyncGeneratorFunction || ( async function*() {} ).constructor Object.defineProperty( Function.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( AsyncFunction.prototype , 'constructor' , { value : undefined } ) Object.defineProperty( GeneratorFuncti...
random_line_split
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata';...
}); } getControlGroup(dir: NgControlGroup): ControlGroup { return <ControlGroup>this.form.find(dir.path); } updateModel(dir: NgControl, value: any): void { this._later(_ => { var c = <Control>this.form.find(dir.path); c.updateValue(value); }); } onSubmit(): boolean { Obse...
{ container.removeControl(dir.name); container.updateValidity(); }
conditional_block
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata';...
* </form> * `}) * class SignupComp { * onSignUp(value) { * // value === {personal: {name: 'some name'}, * // credentials: {login: 'some login', password: 'some password'}} * } * } * * ``` */ @Directive({ selector: 'form:not([ng-no-form]):not([ng-form-model]),ng-form,[ng-form]', ...
random_line_split
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata';...
getControl(dir: NgControl): Control { return <Control>this.form.find(dir.path); } removeControl(dir: NgControl): void { this._later(_ => { var container = this._findContainer(dir.path); if (isPresent(container)) { container.removeControl(dir.name); container.updateValidity(); ...
{ this._later(_ => { var container = this._findContainer(dir.path); var c = new Control(); setUpControl(c, dir); container.addControl(dir.name, c); c.updateValidity(); }); }
identifier_body
ng_form.ts
import { PromiseWrapper, ObservableWrapper, EventEmitter, PromiseCompleter } from 'angular2/src/facade/async'; import {StringMapWrapper, List, ListWrapper} from 'angular2/src/facade/collection'; import {isPresent, isBlank, CONST_EXPR} from 'angular2/src/facade/lang'; import {Directive} from 'angular2/metadata';...
(dir: NgControlGroup): ControlGroup { return <ControlGroup>this.form.find(dir.path); } updateModel(dir: NgControl, value: any): void { this._later(_ => { var c = <Control>this.form.find(dir.path); c.updateValue(value); }); } onSubmit(): boolean { ObservableWrapper.callNext(this.ngS...
getControlGroup
identifier_name
base.ts
import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UIInputFlow { protected fillElement: HTMLElement; ...
import { WebSocketSession } from '@xoutput/client';
random_line_split
base.ts
import { WebSocketSession } from '@xoutput/client'; import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UI...
(): void { const value = this.onEnd(); if (value != null) { this.fill(value); this.sendValue(value); } } protected abstract onStart(event: UIInputEvent): T; protected abstract onMove(event: UIInputEvent): T; protected abstract onEnd(): T; protected abstract fill(value: T): void; pro...
end
identifier_name
base.ts
import { WebSocketSession } from '@xoutput/client'; import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UI...
if (value < 0) { return 0; } return value; } }
{ return 1; }
conditional_block
base.ts
import { WebSocketSession } from '@xoutput/client'; import { MouseEvent, Touch } from 'react'; export type UIInputEvent = Touch | MouseEvent; export interface UIInputFlow { start(event: UIInputEvent): void; move(event: UIInputEvent): void; end(): void; } export abstract class AbstractInputFlow<T> implements UI...
protected abstract onStart(event: UIInputEvent): T; protected abstract onMove(event: UIInputEvent): T; protected abstract onEnd(): T; protected abstract fill(value: T): void; protected abstract sendValue(value: T): void; protected getXRatio(event: UIInputEvent, inverted = false): number { const eleme...
{ const value = this.onEnd(); if (value != null) { this.fill(value); this.sendValue(value); } }
identifier_body
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn build() -> App<'static, 'static> { App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcomm...
.short("f") .takes_value(true)) .arg(Arg::with_name("description") .help("Prints results with description") .long("description") .short("d") .requires("filter")) .group(ArgGroup::with_name("modes") ...
.long("filter")
random_line_split
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn build() -> App<'static, 'static>
{ App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph lookup and resolution") ...
identifier_body
app.rs
use clap::{App, AppSettings, Arg, ArgGroup, SubCommand}; pub fn
() -> App<'static, 'static> { App::new(crate_name!()) .about(crate_description!()) .version(crate_version!()) .setting(AppSettings::SubcommandRequired) .setting(AppSettings::VersionlessSubcommands) .subcommand(SubCommand::with_name("digraph") .about("Digraph looku...
build
identifier_name
xhr.js
'use strict'; /*global ActiveXObject:true*/ var defaults = require('./../defaults'); var utils = require('./../utils'); var buildUrl = require('./../helpers/buildUrl'); var cookies = require('./../helpers/cookies'); var parseHeaders = require('./../helpers/parseHeaders'); var transformData = require('./../helpers/tra...
}); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') ...
{ request.setRequestHeader(key, val); }
conditional_block
xhr.js
'use strict'; /*global ActiveXObject:true*/ var defaults = require('./../defaults'); var utils = require('./../utils'); var buildUrl = require('./../helpers/buildUrl'); var cookies = require('./../helpers/cookies'); var parseHeaders = require('./../helpers/parseHeaders'); var transformData = require('./../helpers/tra...
var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the P...
request.onreadystatechange = function () { if (request && request.readyState === 4) { // Prepare the response var responseHeaders = parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response;
random_line_split
x6hr.py
#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: x6hr.py # Purpose: log reader of SUUNTO H6HR # Author: tomoya kamata (iware pref. japan) # Created: 15 Mar 2010 # Copyright: GPL. please read COPYING file # ma...
lut = [] for i in data: if i != 0: lut.append(i) return lut def read_chrono_log(self, index): p = self.read_register(0x19fa + (index - 1) * 0x32, 0x32) log = {} firstchunk = p[0] log['date'] = "%0.2d/%0.2d/%0.2d %0.2d:%0....
def read_chrono_index(self): data = self.read_register(0x19c9, 0x1e)
random_line_split
x6hr.py
#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: x6hr.py # Purpose: log reader of SUUNTO H6HR # Author: tomoya kamata (iware pref. japan) # Created: 15 Mar 2010 # Copyright: GPL. please read COPYING file # ma...
# Get list of "hiking" (logbook) logs def read_hiking_index(self): data = self.read_register(0x0fb4, 0x14) lut = [] for i in data: if i != 0: lut.append(i) return lut def read_hiking_log(self, index): p = self.read_register(0...
data = self.read_register(0x005d, 4) return (data[0] * 1000000) + (data[1] * 10000) + (data[2] * 100) + data[3]
identifier_body
x6hr.py
#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: x6hr.py # Purpose: log reader of SUUNTO H6HR # Author: tomoya kamata (iware pref. japan) # Created: 15 Mar 2010 # Copyright: GPL. please read COPYING file # ma...
return self.x6hr def write_raw(self, bin): """ write raw binaly data bin : sequence of write data to suunto """ cmd = "".join(map(chr, bin)) self.x6hr.write(cmd) def write_cmd(self, bin): """ write data. before write data th...
self.x6hr = serial.Serial(port=serial_port, timeout=3)
conditional_block
x6hr.py
#!/usr/bin/python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: x6hr.py # Purpose: log reader of SUUNTO H6HR # Author: tomoya kamata (iware pref. japan) # Created: 15 Mar 2010 # Copyright: GPL. please read COPYING file # ma...
(self): self.x6hr = None def open(self, serial_port = "COM1"): """ open serial communication port serial_port : port name return : becomes None when Fail to open. """ if self.x6hr == None: self.x6hr = serial.Serial(port=serial_port, ti...
__init__
identifier_name
admin.py
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin): list...
(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) class ComfortAdmin(admin.ModelAdmin): list_display = ('comfort', 'structure') search_fields = ('comfort', 'structure') list_filter = ('structure',) admin.site.reg...
NetworkAdmin
identifier_name
admin.py
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin): list...
class NetworkAdmin(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) class ComfortAdmin(admin.ModelAdmin): list_display = ('comfort', 'structure') search_fields = ('comfort', 'structure') list_filter = ('structur...
list_display = ('usage', 'structure') search_fields = ('usage', 'structure') list_filter = ('structure',)
identifier_body
admin.py
from django.contrib import admin from geotrek.core.models import (PathSource, Stake, Usage, Network, Comfort) class PathSourceAdmin(admin.ModelAdmin): list_display = ('source', 'structure') search_fields = ('source', 'structure') list_filter = ('structure',) class StakeAdmin(admin.ModelAdmin):
class UsageAdmin(admin.ModelAdmin): list_display = ('usage', 'structure') search_fields = ('usage', 'structure') list_filter = ('structure',) class NetworkAdmin(admin.ModelAdmin): list_display = ('network', 'structure') search_fields = ('network', 'structure') list_filter = ('structure',) cl...
list_display = ('stake', 'structure') search_fields = ('stake', 'structure') list_filter = ('structure',)
random_line_split
gotoSymbolQuickAccess.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
protected provideWithoutTextEditor(picker: IQuickPick<IGotoSymbolQuickPickItem>): IDisposable { this.provideLabelPick(picker, localize('cannotRunGotoSymbolWithoutEditor', "To go to a symbol, first open a text editor with symbol information.")); return Disposable.None; } protected provideWithTextEditor(editor...
{ super(options); options.canAcceptInBackground = true; }
identifier_body
gotoSymbolQuickAccess.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(symbolsPromise: Promise<DocumentSymbol[]>, query: IPreparedQuery, options: { extraContainerLabel?: string } | undefined, token: CancellationToken): Promise<Array<IGotoSymbolQuickPickItem | IQuickPickSeparator>> { const symbols = await symbolsPromise; if (token.isCancellationRequested) { return []; } const ...
doGetSymbolPicks
identifier_name