file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
rat-utils.js
'use strict'; var path = require('path'); var _ = require('lodash'); function convertToUnixPath(dir) { if (!_.isString(dir)) { throw new Error('Expected path to be a string'); } if (path.sep === '\\') { dir = path.normalize(dir); dir = dir.split(path.sep).join('/'); } return dir; } function g...
} function generateRunNames(runName, prefix) { return _buildNameObject(runName, 'run', prefix); } function generateServiceNames(serviceName, prefix) { return _buildNameObject(serviceName, 'service', prefix); } function generateProviderNames(providerName, prefix) { return _buildNameObject(providerName, 'provide...
function generateConfigurationNames(configurationName, prefix) { return _buildNameObject(configurationName, 'configuration', prefix);
random_line_split
configparser.ts
import * as fs from "fs"; import * as path from "path"; import { UserRights } from "./hub"; import { Binding, Config, ListenOption, LoggingOptions, NodesConfig, NormalizedConfig, UserOptions, } from "./nodeserver"; import { replaceKeyFiles } from "./tlsHelpers"; function normalizeListen(config: Config, rootDir...
// Read TLS key, cert, etc replaceKeyFiles(listenOption, rootDir); } }); return listen; } function normalizeUsers(config: Config, rootDir: string): UserOptions { // Checks if ( config.users !== undefined && typeof config.users !== "string" && typeof config.users !== "object" ) { throw new Error( ...
listenOption!.type = "websocket"; } if (listenOption.type === "websocket") {
random_line_split
configparser.ts
import * as fs from "fs"; import * as path from "path"; import { UserRights } from "./hub"; import { Binding, Config, ListenOption, LoggingOptions, NodesConfig, NormalizedConfig, UserOptions, } from "./nodeserver"; import { replaceKeyFiles } from "./tlsHelpers"; function normalizeListen(config: Config, rootDir...
(filePath: string): Config { try { return JSON.parse(fs.readFileSync(filePath, "utf8")); } catch (e) { throw new Error(`Cannot parse config file '${filePath}':` + e.message); } } // 'Normalize' config and convert paths to their contents export default function parseConfigFile(configFile: string): NormalizedConf...
readConfigFile
identifier_name
configparser.ts
import * as fs from "fs"; import * as path from "path"; import { UserRights } from "./hub"; import { Binding, Config, ListenOption, LoggingOptions, NodesConfig, NormalizedConfig, UserOptions, } from "./nodeserver"; import { replaceKeyFiles } from "./tlsHelpers"; function normalizeListen(config: Config, rootDir...
if (listenOption.type === "websocket") { // Read TLS key, cert, etc replaceKeyFiles(listenOption, rootDir); } }); return listen; } function normalizeUsers(config: Config, rootDir: string): UserOptions { // Checks if ( config.users !== undefined && typeof config.users !== "string" && typeof config....
{ // Default to WebSocket, for backward compatibility listenOption!.type = "websocket"; }
conditional_block
configparser.ts
import * as fs from "fs"; import * as path from "path"; import { UserRights } from "./hub"; import { Binding, Config, ListenOption, LoggingOptions, NodesConfig, NormalizedConfig, UserOptions, } from "./nodeserver"; import { replaceKeyFiles } from "./tlsHelpers"; function normalizeListen(config: Config, rootDir...
function normalizeRights(config: Config): UserRights { if (config.rights === undefined && config.users === undefined) { // Default rights: allow everyone to publish/subscribe. return { "": { publish: true, subscribe: true, }, }; } return config.rights || {}; } function readConfigFile(filePath:...
{ if (config.logging) { return config.logging; } else if (config.verbose === undefined || config.verbose) { return "debug"; } return "info"; }
identifier_body
borrowck-lend-flow-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn cond() -> bool { panic!() } fn produce<T>() -> T { panic!(); } fn inc(v: &mut Box<int>) { *v = box() (**v + 1); } fn loop_overarching_alias_mut() { // In this instance, the borrow encompasses the entire loop. let mut v = box 3; let mut x = &mut v; **x += 1; loop { borrow(&*v); //~...
{}
identifier_body
borrowck-lend-flow-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } } fn loop_loop_pops_scopes<'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool { // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mu...
{ break; // ...so it is not live as exit the `while` loop here }
conditional_block
borrowck-lend-flow-loop.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 ...
<'r, F>(_v: &'r mut [uint], mut f: F) where F: FnMut(&'r mut uint) -> bool { // Similar to `loop_break_pops_scopes` but for the `loop` keyword while cond() { while cond() { // this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if !f(&mut *...
loop_loop_pops_scopes
identifier_name
borrowck-lend-flow-loop.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 ...
// this borrow is limited to the scope of `r`... let r: &'r mut uint = produce(); if !f(&mut *r) { continue; // ...so it is not live as exit (and re-enter) the `while` loop here } } } } fn main() {}
random_line_split
date.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012, 2013 CERN. # # Invenio 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) any...
# of Field.process() and draft_form_process_and_validate(). self.data = self.object_data @property def json_data(self): """ Serialize data into JSON serializalbe object """ # Just use _value() to format the date into a string. if self.data: re...
random_line_split
date.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012, 2013 CERN. # # Invenio 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) any...
(self, value): """ Called when loading data from Python (incoming objects can be either datetime objects or strings, depending on if they are loaded from an JSON or Python objects). """ if isinstance(value, six.string_types): self.object_data = datetime.strpti...
process_data
identifier_name
date.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012, 2013 CERN. # # Invenio 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) any...
return None
return self.data.strftime(self.format) # pylint: disable-msg=
conditional_block
date.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012, 2013 CERN. # # Invenio 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) any...
""" Serialize data into JSON serializalbe object """ # Just use _value() to format the date into a string. if self.data: return self.data.strftime(self.format) # pylint: disable-msg= return None
identifier_body
slide-animate.directive.ts
// import {Directive, ElementRef} from "@angular/core"; // import {AnimationBuilder} from "@angular/animate";
// }, // exportAs: 'ab' // }) // export class SlideToggle { // constructor(private _ab:AnimationBuilder, private _e:Elem) { // } // // toggle(isVisible:boolean = false) { // let animation = this._ab.css(); // animation // .setDuration(1000); // // if (!isVisible) ...
// @Directive({ // selector: '[animate-box]', // host: { // '[style.background-color]': "'red'"
random_line_split
passwordui.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
def _load_password(self): '''Loads the password from the backend''' password = self.backend.get_parameters()['password'] self.password_textbox.set_invisible_char('*') self.password_textbox.set_visibility(False) self.password_textbox.set_text(password) def _connect_sign...
'''Creates the text box and the related label @param width: the width of the Gtk.Label object ''' password_label = Gtk.Label(label=_("Password:")) password_label.set_alignment(xalign=0, yalign=0.5) password_label.set_size_request(width=width, height=-1) self.pack_start(p...
identifier_body
passwordui.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
self.req.set_backend_enabled(self.backend.get_id(), False)
conditional_block
passwordui.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
@param req: a Requester @param backend: a backend object @param width: the width of the Gtk.Label object ''' super(PasswordUI, self).__init__() self.backend = backend self.req = req self._populate_gtk(width) self._load_password() self._con...
field
random_line_split
passwordui.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
(self): '''Loads the password from the backend''' password = self.backend.get_parameters()['password'] self.password_textbox.set_invisible_char('*') self.password_textbox.set_visibility(False) self.password_textbox.set_text(password) def _connect_signals(self): '''Co...
_load_password
identifier_name
test.py
(self, pos=None, # motion \ useshared=False, # arp \ cfocorrection=True, # phy \ usecsma=False, # mac \ rreqrate=None, datarate=None, #...
configure
identifier_name
test.py
agt = self.newchild('agent', Agent, dest=dest, plen=plen, \ delay=delay, mode=mode) mobi = self.newchild('motion', Motion, pos=pos) # connect ports agt.connect(net) arp.connect(net, mac) mac.connect(phy) phy.connect(cif) def r...
def read_route(options, routefile): """Read routing tables from file.""" f = file(routefile, 'r') s = f.readline() routedata = {} done = not (s) while not done: # convert s to dict try: d = eval(s) assert isinstance(d, dict) for x,y in d.item...
"""Read topology layout from file.""" f = file(topofile, 'r') s = f.readline() topo = {'border':None, 'layout':None} done = not (s) while not done: # convert s to dict (check for border and layout) try: d = eval(s) assert isinstance(d, dict) assert...
identifier_body
test.py
agt = self.newchild('agent', Agent, dest=dest, plen=plen, \ delay=delay, mode=mode) mobi = self.newchild('motion', Motion, pos=pos) # connect ports agt.connect(net) arp.connect(net, mac) mac.connect(phy) phy.connect(cif) def r...
done = not(s) f.close() return routedata def get_topology(options, numnodes): """Get/create topology.""" # load topology from file if options.usetopo: topofile = options.usetopo topo = read_topo(options, topofile) border = topo['border'] layout = topo['layout...
if d: routedata.update(d) # get next input s = f.readline()
random_line_split
test.py
t = self.newchild('agent', Agent, dest=dest, plen=plen, \ delay=delay, mode=mode) mobi = self.newchild('motion', Motion, pos=pos) # connect ports agt.connect(net) arp.connect(net, mac) mac.connect(phy) phy.connect(cif) def read...
# create monitor if options.monitor: mon = Monitor(period=stoptime/1e4) mon.start() ############################ # Run Simulation ############################ if options.usetopo: mon.log("topo", topofile=options.usetopo) mon.log("model", **chargs) mon.log("rate...
ch.add_edge(n.cif, m.cif, **chargs)
conditional_block
build.js.prod.ts
import * as gulp from 'gulp'; import * as gulpLoadPlugins from 'gulp-load-plugins'; import { join } from 'path'; import Config from '../../config'; import { makeTsProject, TemplateLocalsBuilder } from '../../utils'; const plugins = <any>gulpLoadPlugins(); const INLINE_OPTIONS = { base: Config.TMP_DIR, target: 'e...
.pipe( plugins.template( new TemplateLocalsBuilder().build(), Config.TEMPLATE_CONFIG ) ) .pipe(gulp.dest(Config.TMP_DIR)) .on('error', (e: any) => { console.log(e); }); };
random_line_split
process.py
it can mess with no-data monitoring # This cache is indexed per instance self.last_pid_cache_ts = {} self.pid_cache = {} self.pid_cache_duration = int( init_config.get( 'pid_cache_duration', DEFAULT_PID_CACHE_DURATION ) ) ...
''' Report a service check, for each process in search_string. Report as OK if the process is in the warning thresholds CRITICAL out of the critical thresholds WARNING out of the warning thresholds ''' tag = ["process:%s" % n...
identifier_body
process.py
# FIXME: namespace me correctly (6.x) io.r_bytes 'r_bytes': 'ioread_bytes', # FIXME: namespace me correctly (6.x) io.w_count 'w_bytes': 'iowrite_bytes', # FIXME: namespace me correctly (6.x) io.w_bytes 'ctx_swtch_vol': 'voluntary_ctx_switches', # FIXME: namespace me correctly (6.x),...
(self, name, pids): st = defaultdict(list) # Remove from cache the processes that are not in `pids` cached_pids = set(self.process_cache[name].keys()) pids_to_remove = cached_pids - pids for pid in pids_to_remove: del self.process_cache[name][pid] for pid in...
get_process_state
identifier_name
process.py
# FIXME: namespace me correctly (6.x) io.r_bytes 'r_bytes': 'ioread_bytes', # FIXME: namespace me correctly (6.x) io.w_count 'w_bytes': 'iowrite_bytes', # FIXME: namespace me correctly (6.x) io.w_bytes 'ctx_swtch_vol': 'voluntary_ctx_switches', # FIXME: namespace me correctly (6.x)...
if not refresh_ad_cache and proc.pid in self.ad_cache: continue found = False for string in search_string: try: # FIXME 6.x: All has been deprecated from the doc, should be removed if string == 'All': ...
for proc in psutil.process_iter(): # Skip access denied processes
random_line_split
process.py
# FIXME: namespace me correctly (6.x) io.r_bytes 'r_bytes': 'ioread_bytes', # FIXME: namespace me correctly (6.x) io.w_count 'w_bytes': 'iowrite_bytes', # FIXME: namespace me correctly (6.x) io.w_bytes 'ctx_swtch_vol': 'voluntary_ctx_switches', # FIXME: namespace me correctly (6.x),...
else: st['real'].append(None) ctxinfo = self.psutil_wrapper(p, 'num_ctx_switches', ['voluntary', 'involuntary']) st['ctx_swtch_vol'].append(ctxinfo.get('voluntary')) st['ctx_swtch_invol'].append(ctxinfo.get('involuntary')) st['thr'].append(s...
st['real'].append(meminfo['rss'] - shared_mem)
conditional_block
source_loc_macros.rs
// This test makes sure that different expansions of the file!(), line!(), // column!() macros get picked up by the incr. comp. hash. // revisions:rpass1 rpass2 // compile-flags: -Z query-dep-graph #![feature(rustc_attrs)] #[rustc_clean(cfg="rpass2")] fn line_same() { let _ = line!(); } #[rustc_clean(cfg="rpas...
() { #[cfg(rpass1)] { let _ = column!(); } #[cfg(rpass2)] { let _ = column!(); } } fn main() { line_same(); line_different(); col_same(); col_different(); file_same(); }
col_different
identifier_name
source_loc_macros.rs
// This test makes sure that different expansions of the file!(), line!(), // column!() macros get picked up by the incr. comp. hash. // revisions:rpass1 rpass2 // compile-flags: -Z query-dep-graph #![feature(rustc_attrs)] #[rustc_clean(cfg="rpass2")] fn line_same() { let _ = line!(); } #[rustc_clean(cfg="rpas...
fn col_different() { #[cfg(rpass1)] { let _ = column!(); } #[cfg(rpass2)] { let _ = column!(); } } fn main() { line_same(); line_different(); col_same(); col_different(); file_same(); }
} } #[rustc_clean(except="hir_owner_nodes,optimized_mir", cfg="rpass2")]
random_line_split
source_loc_macros.rs
// This test makes sure that different expansions of the file!(), line!(), // column!() macros get picked up by the incr. comp. hash. // revisions:rpass1 rpass2 // compile-flags: -Z query-dep-graph #![feature(rustc_attrs)] #[rustc_clean(cfg="rpass2")] fn line_same() { let _ = line!(); } #[rustc_clean(cfg="rpas...
{ line_same(); line_different(); col_same(); col_different(); file_same(); }
identifier_body
test_about.py
""" Test the about xblock """ from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from...
(self): self.setup_user() url = reverse('about_course', args=[self.course.id]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) def test_anonymous_user(self): url = reverse('about_course', args=[self.cou...
test_logged_in
identifier_name
test_about.py
"""
from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory @over...
Test the about xblock """ from django.test.utils import override_settings
random_line_split
test_about.py
""" Test the about xblock """ from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXED_MODULESTORE from...
def test_logged_in(self): self.setup_user() url = reverse('about_course', args=[self.course.id]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) def test_anonymous_user(self): url = reverse('about...
self.course = CourseFactory.create() self.about = ItemFactory.create( category="about", parent_location=self.course.location, data="OOGIE BLOOGIE", display_name="overview" )
identifier_body
addfiledialog.py
from PyQt4.QtGui import * import pypipe.formats import pypipe.basefile from pypipe.core import pipeline from widgets.combobox import ComboBox class AddFileDialog(QDialog): def __init__(self, parent=None): super(AddFileDialog, self).__init__(parent) self.formats_combo = ComboBox() self.fi...
else: self.ok_button.setEnabled(False) def open_file(self): file_name = QFileDialog.getOpenFileName(self, 'Open file') self.filename_edit.setText(file_name) def get_file(self): init = self.formats_combo.get_current_item() path = str(self.filename_edit.text(...
self.ok_button.setEnabled(True)
conditional_block
addfiledialog.py
from PyQt4.QtGui import * import pypipe.formats import pypipe.basefile from pypipe.core import pipeline from widgets.combobox import ComboBox
class AddFileDialog(QDialog): def __init__(self, parent=None): super(AddFileDialog, self).__init__(parent) self.formats_combo = ComboBox() self.filename_edit = QLineEdit() self.open_button = QPushButton('Open') self.ok_button = QPushButton('&OK') self.cancel_button ...
random_line_split
addfiledialog.py
from PyQt4.QtGui import * import pypipe.formats import pypipe.basefile from pypipe.core import pipeline from widgets.combobox import ComboBox class AddFileDialog(QDialog): def __init__(self, parent=None): super(AddFileDialog, self).__init__(parent) self.formats_combo = ComboBox() self.fi...
self.turn_ok_button() super(AddFileDialog, self).exec_()
identifier_body
addfiledialog.py
from PyQt4.QtGui import * import pypipe.formats import pypipe.basefile from pypipe.core import pipeline from widgets.combobox import ComboBox class AddFileDialog(QDialog): def
(self, parent=None): super(AddFileDialog, self).__init__(parent) self.formats_combo = ComboBox() self.filename_edit = QLineEdit() self.open_button = QPushButton('Open') self.ok_button = QPushButton('&OK') self.cancel_button = QPushButton('&Cancel') self.setWindow...
__init__
identifier_name
GetRuntimeParams.ts
import { RpcRequest } from '../RpcRequest' import { RpcResponse } from '../RpcResponse' /** * JSON-RPC request for the `getruntimeparams` command. */ export interface GetRuntimeParamsRequest extends RpcRequest { readonly method: 'getruntimeparams' readonly params?: undefined } /** * JSON-RPC response for the `...
{ return { method: 'getruntimeparams' } }
identifier_body
GetRuntimeParams.ts
import { RpcRequest } from '../RpcRequest' import { RpcResponse } from '../RpcResponse' /** * JSON-RPC request for the `getruntimeparams` command. */ export interface GetRuntimeParamsRequest extends RpcRequest { readonly method: 'getruntimeparams' readonly params?: undefined
*/ export interface GetRuntimeParamsResponse extends RpcResponse { readonly result: GetRuntimeParamsResult | null } /** * Result of the `getruntimeparams` command. */ export interface GetRuntimeParamsResult { port: number reindex: boolean rescan: boolean txindex: boolean autocombineminconf: number aut...
} /** * JSON-RPC response for the `getruntimeparams` command.
random_line_split
GetRuntimeParams.ts
import { RpcRequest } from '../RpcRequest' import { RpcResponse } from '../RpcResponse' /** * JSON-RPC request for the `getruntimeparams` command. */ export interface GetRuntimeParamsRequest extends RpcRequest { readonly method: 'getruntimeparams' readonly params?: undefined } /** * JSON-RPC response for the `...
(): GetRuntimeParamsRequest { return { method: 'getruntimeparams' } }
GetRuntimeParams
identifier_name
insert_only.rs
use std::borrow::Borrow; use std::boxed::Box; use std::cell::{Cell, UnsafeCell}; use std::cmp::Eq; use std::collections::hash_map::{self, Entry}; use std::collections::HashMap as Interior; use std::hash::{BuildHasher, Hash}; #[derive(Debug)] pub struct HashMap<K: Eq + Hash, V, S: BuildHasher = ::std::collections::hash...
} impl<K: Eq + Hash, V, S: BuildHasher> HashMap<K, V, S> { pub fn with_hasher(hash_builder: S) -> HashMap<K, V, S> { HashMap { data: UnsafeCell::new(Interior::with_hasher(hash_builder)), inserting: Cell::new(false), } } pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Hash...
{ HashMap { data: UnsafeCell::new(Interior::new()), inserting: Cell::new(false), } }
identifier_body
insert_only.rs
use std::borrow::Borrow; use std::boxed::Box; use std::cell::{Cell, UnsafeCell}; use std::cmp::Eq; use std::collections::hash_map::{self, Entry}; use std::collections::HashMap as Interior; use std::hash::{BuildHasher, Hash}; #[derive(Debug)] pub struct HashMap<K: Eq + Hash, V, S: BuildHasher = ::std::collections::hash...
} pub fn get_default<F>(&self, key: K, default_function: F) -> Option<&V> where F: FnOnce() -> Option<V>, { assert!( !self.inserting.get(), "Attempt to call get_default() on a insert_only::HashMap within the default_function \ callback for another get_default() on the same map" );...
random_line_split
insert_only.rs
use std::borrow::Borrow; use std::boxed::Box; use std::cell::{Cell, UnsafeCell}; use std::cmp::Eq; use std::collections::hash_map::{self, Entry}; use std::collections::HashMap as Interior; use std::hash::{BuildHasher, Hash}; #[derive(Debug)] pub struct HashMap<K: Eq + Hash, V, S: BuildHasher = ::std::collections::hash...
(self) -> Self::IntoIter { IntoIter { data: self.data.into_inner().into_iter(), } } }
into_iter
identifier_name
MIMEImage.py
# Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """Class representing image/* type MIME documents. """ import imghdr from email import Errors from email import Encoders from email.MIMENonMultipart import MIMENonMultipart class MIMEImage(MIMENonMultipart)...
if _subtype is None: raise TypeError, 'Could not guess image MIME subtype' MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self)
_subtype = imghdr.what(None, _imagedata)
conditional_block
MIMEImage.py
# Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """Class representing image/* type MIME documents. """ import imghdr from email import Errors from email import Encoders from email.MIMENonMultipart import MIMENonMultipart class MIMEImage(MIMENonMultipart)...
""" if _subtype is None: _subtype = imghdr.what(None, _imagedata) if _subtype is None: raise TypeError, 'Could not guess image MIME subtype' MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(...
necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
random_line_split
MIMEImage.py
# Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """Class representing image/* type MIME documents. """ import imghdr from email import Errors from email import Encoders from email.MIMENonMultipart import MIMENonMultipart class
(MIMENonMultipart): """Class for generating image/* type MIME documents.""" def __init__(self, _imagedata, _subtype=None, _encoder=Encoders.encode_base64, **_params): """Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this...
MIMEImage
identifier_name
MIMEImage.py
# Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """Class representing image/* type MIME documents. """ import imghdr from email import Errors from email import Encoders from email.MIMENonMultipart import MIMENonMultipart class MIMEImage(MIMENonMultipart)...
constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = imghdr.what(None, _imagedata) if _subtype is None: raise TypeError, 'Could not guess image MIME subtype' MIMENonMultipart.__init__(...
"""Class for generating image/* type MIME documents.""" def __init__(self, _imagedata, _subtype=None, _encoder=Encoders.encode_base64, **_params): """Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be dec...
identifier_body
21613.js
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the F...
}
}
random_line_split
21613.js
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the F...
(mode, type, selection) { if (mode == -1) { qm.dispose(); } else { if(mode == 0 && type > 0) { qm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { qm.sendN...
start
identifier_name
21613.js
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the F...
} else if (status == 3) { var em = qm.getEventManager("Aran_3rdmount"); if (em == null) { qm.sendOk("Sorry, but the 3rd mount quest (Wolves) is closed."); return; } else { var em = qm.getEventManager("Aran_3rdmount")...
{ if (mode == -1) { qm.dispose(); } else { if(mode == 0 && type > 0) { qm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { qm.sendNext("We're a pack of wol...
identifier_body
metadata.rs
use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use super::Error; use crate::Error::MalformedMetadata; #[derive(Debug)] pub struct MetadataMap<'a>(HashMap<&'a str, &'a str>); impl<'a> MetadataMap<'a> { /// Returns a string that indicates the character set. pub fn charset(&self) -> Option<&'a ...
} }
map.insert("Plural-Forms", " n_plurals = 42 ; plural = n > 10 "); assert_eq!(map.plural_forms(), (Some(42), Some("n > 10")));
random_line_split
metadata.rs
use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use super::Error; use crate::Error::MalformedMetadata; #[derive(Debug)] pub struct
<'a>(HashMap<&'a str, &'a str>); impl<'a> MetadataMap<'a> { /// Returns a string that indicates the character set. pub fn charset(&self) -> Option<&'a str> { self.get("Content-Type") .and_then(|x| x.split("charset=").nth(1)) } /// Returns the number of different plurals and the boo...
MetadataMap
identifier_name
metadata.rs
use std::collections::HashMap; use std::ops::{Deref, DerefMut}; use super::Error; use crate::Error::MalformedMetadata; #[derive(Debug)] pub struct MetadataMap<'a>(HashMap<&'a str, &'a str>); impl<'a> MetadataMap<'a> { /// Returns a string that indicates the character set. pub fn charset(&self) -> Option<&'a ...
} impl<'a> Deref for MetadataMap<'a> { type Target = HashMap<&'a str, &'a str>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'a> DerefMut for MetadataMap<'a> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub fn parse_metadata(blob: &str) -> Result<Metada...
{ self.get("Plural-Forms") .map(|f| { f.split(';').fold((None, None), |(n_pl, pl), prop| { match prop.chars().position(|c| c == '=') { Some(index) => { let (name, value) = prop.split_at(index); ...
identifier_body
ip.rs
use pktparse::{ipv4, ipv6}; use std::fmt::Display; use std::net::Ipv4Addr; pub trait IPHeader { type Addr: Display; fn source_addr(&self) -> Self::Addr; fn dest_addr(&self) -> Self::Addr; } impl IPHeader for ipv4::IPv4Header { type Addr = Ipv4Addr; #[inline] fn source_addr(&self) -> Self::Ad...
(&self) -> Self::Addr { self.dest_addr } } impl IPHeader for ipv6::IPv6Header { type Addr = String; #[inline] fn source_addr(&self) -> Self::Addr { format!("[{}]", self.source_addr) } #[inline] fn dest_addr(&self) -> Self::Addr { format!("[{}]", self.dest_addr) ...
dest_addr
identifier_name
ip.rs
use pktparse::{ipv4, ipv6};
fn source_addr(&self) -> Self::Addr; fn dest_addr(&self) -> Self::Addr; } impl IPHeader for ipv4::IPv4Header { type Addr = Ipv4Addr; #[inline] fn source_addr(&self) -> Self::Addr { self.source_addr } #[inline] fn dest_addr(&self) -> Self::Addr { self.dest_addr } }...
use std::fmt::Display; use std::net::Ipv4Addr; pub trait IPHeader { type Addr: Display;
random_line_split
ip.rs
use pktparse::{ipv4, ipv6}; use std::fmt::Display; use std::net::Ipv4Addr; pub trait IPHeader { type Addr: Display; fn source_addr(&self) -> Self::Addr; fn dest_addr(&self) -> Self::Addr; } impl IPHeader for ipv4::IPv4Header { type Addr = Ipv4Addr; #[inline] fn source_addr(&self) -> Self::Ad...
#[inline] fn dest_addr(&self) -> Self::Addr { format!("[{}]", self.dest_addr) } }
{ format!("[{}]", self.source_addr) }
identifier_body
main.rs
fn main()
"May", "June", "July", "August", "September", "October", "November", "December"]; println!("Months of the year: {:?}", months); }
{ let mut x = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); let x = x + 1; let x = x * 2; println!("The value of x is: {}", x); let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of x is: {}", x); println!("The value of...
identifier_body
main.rs
fn
() { let mut x = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); let x = x + 1; let x = x * 2; println!("The value of x is: {}", x); let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of x is: {}", x); println!("The value...
main
identifier_name
main.rs
fn main() { let mut x = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); let x = x + 1; let x = x * 2; println!("The value of x is: {}", x); let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of x is: {}", x); println!("Th...
"June", "July", "August", "September", "October", "November", "December"]; println!("Months of the year: {:?}", months); }
"April", "May",
random_line_split
index.d.ts
// Type definitions for humanparser 1.1.1 // Project: https://github.com/chovy/humanparser // Definitions by: Michał Podeszwa <https://github.com/MichalPodeszwa> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace humanparser { interface NameOutput { firstName: string; ...
salutation?: string | undefined; } interface FullerNameOutput { fullName: string; } interface AddressOutput { address: string; state: string; fullAddress: string; zip: string; city: string; } interface HumanparserStatic { parseNa...
fullName: string; suffix?: string | undefined; middleName?: string | undefined;
random_line_split
ban_string_initialized_sets_rule.ts
/** * @fileoverview Bans `new Set(<string>)` since it is a potential source of bugs * due to strings also implementing `Iterable<string>`. */ import * as ts from 'typescript'; import {Checker} from '../checker'; import {ErrorCode} from '../error_code'; import {AbstractRule} from '../rule'; const errorMsg = 'Value...
register(checker: Checker) { checker.on(ts.SyntaxKind.NewExpression, checkNewExpression, this.code); } } function checkNewExpression(checker: Checker, node: ts.NewExpression) { const typeChecker = checker.typeChecker; // Check that it's a Set which is being constructed const ctorTypeSymbol = type...
export class Rule extends AbstractRule { static readonly RULE_NAME = 'ban-string-initialized-sets'; readonly ruleName = Rule.RULE_NAME; readonly code = ErrorCode.BAN_STRING_INITIALIZED_SETS;
random_line_split
ban_string_initialized_sets_rule.ts
/** * @fileoverview Bans `new Set(<string>)` since it is a potential source of bugs * due to strings also implementing `Iterable<string>`. */ import * as ts from 'typescript'; import {Checker} from '../checker'; import {ErrorCode} from '../error_code'; import {AbstractRule} from '../rule'; const errorMsg = 'Value...
(checker: Checker) { checker.on(ts.SyntaxKind.NewExpression, checkNewExpression, this.code); } } function checkNewExpression(checker: Checker, node: ts.NewExpression) { const typeChecker = checker.typeChecker; // Check that it's a Set which is being constructed const ctorTypeSymbol = typeChecker.get...
register
identifier_name
ban_string_initialized_sets_rule.ts
/** * @fileoverview Bans `new Set(<string>)` since it is a potential source of bugs * due to strings also implementing `Iterable<string>`. */ import * as ts from 'typescript'; import {Checker} from '../checker'; import {ErrorCode} from '../error_code'; import {AbstractRule} from '../rule'; const errorMsg = 'Value...
} function checkNewExpression(checker: Checker, node: ts.NewExpression) { const typeChecker = checker.typeChecker; // Check that it's a Set which is being constructed const ctorTypeSymbol = typeChecker.getTypeAtLocation(node.expression).getSymbol(); if (!ctorTypeSymbol || ctorTypeSymbol.getEscapedName...
{ checker.on(ts.SyntaxKind.NewExpression, checkNewExpression, this.code); }
identifier_body
dirsel.js
//////////////////////////////////////////////////////////////////////////////// // Directory Selector Control // // Tree control designed specifically to display directories //////////////////////////////////////////////////////////////////////////////// /*global jQuery */ var app = app || {}; var alldirs = false; ap...
// directory expand / collapse handler // loads child directories on demand function onExpandCollapse($node, node) { var expanded = node.expanded(), empty = !hasOwnProperties(node.json()), $spinner; // acquiring sub-nodes when expanding an empty node if (expanded && empty) { $spinner = $node ...
{ var self = controls.lookup[$node.closest('.w_popup').attr('id')]; self.btnOk() .disabled({self: false}) .render(); }
identifier_body
dirsel.js
//////////////////////////////////////////////////////////////////////////////// // Directory Selector Control // // Tree control designed specifically to display directories //////////////////////////////////////////////////////////////////////////////// /*global jQuery */ var app = app || {}; var alldirs = false; ap...
($node, node) { var expanded = node.expanded(), empty = !hasOwnProperties(node.json()), $spinner; // acquiring sub-nodes when expanding an empty node if (expanded && empty) { $spinner = $node .closest('.w_popup') .find('.spinner') .show(); services.sys.dirlist(node.path().join('/'),...
onExpandCollapse
identifier_name
dirsel.js
//////////////////////////////////////////////////////////////////////////////// // Directory Selector Control // // Tree control designed specifically to display directories //////////////////////////////////////////////////////////////////////////////// /*global jQuery */ var app = app || {}; var alldirs = false; ap...
}); } } controls.dirsel = function () { var self = controls.control.create(controls.popup('centered')), base_init = self.init, tree = controls.tree(onSelect, onExpandCollapse), btnCancel = controls.button("Cancel"), btnOk = controls.button("OK").disabled({self: true}); // initial servi...
{ $spinner = $node .closest('.w_popup') .find('.spinner') .show(); services.sys.dirlist(node.path().join('/'), function (json) { $spinner.hide(); empty = !hasOwnProperties(json.data); if (empty) { // no subdirs, removing expand button $node .removeClass('expanded') ...
conditional_block
dirsel.js
//////////////////////////////////////////////////////////////////////////////// // Directory Selector Control // // Tree control designed specifically to display directories //////////////////////////////////////////////////////////////////////////////// /*global jQuery */ var app = app || {}; var alldirs = false; ap...
btnOk.appendTo(self); btnCancel.appendTo(self); return self; }; self.init = function (elem) { base_init.call(self, elem); elem .find('div.spinner') .show() .end() .find('table.status') .insertAfter(elem.find('ul.root')); }; self.contents = function () { return [ ...
////////////////////////////// // Overrides self.build = function () {
random_line_split
utils.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var makeCommandAbsolute = exports.makeCommandAbsolute = function makeCommandAbsolute(p, c) { switch (c.c) { case 'm': return { c: 'M', x: p.x + c.dx, y: p.y + c.dy }; case 'z': return { c: 'Z' }...
} return lastCommand.x === begin.x && lastCommand.y === begin.y; }; var pointEquals = exports.pointEquals = function pointEquals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; };
return true; } var lastCommand = d[d.length - 1]; if (lastCommand.c === 'Z') { return true;
random_line_split
config.js
var path = require('path'); var util = require('util'); var autoprefixer = require('autoprefixer'); var pkg = require('../package.json'); var loaders = require('./loaders'); var plugins = require('./plugins'); var DEBUG = process.env.NODE_ENV === 'development'; var TEST = process.env.NODE_ENV === 'test'; var jsBundl...
var config = { context: path.join(__dirname, '../examples'), cache: DEBUG, debug: DEBUG, target: 'web', devtool: DEBUG || TEST ? 'inline-source-map' : false, entry: entry, output: { path: path.resolve(pkg.config.buildDir), publicPath: '/', filename: jsBundle, pathinfo: false }, modul...
{ Object.keys(entry).forEach(app => { entry[app].push( util.format( 'webpack-dev-server/client?http://%s:%d', pkg.config.devHost, pkg.config.devPort ) ); entry[app].push('webpack/hot/dev-server'); }); }
conditional_block
config.js
var path = require('path'); var util = require('util'); var autoprefixer = require('autoprefixer'); var pkg = require('../package.json'); var loaders = require('./loaders'); var plugins = require('./plugins'); var DEBUG = process.env.NODE_ENV === 'development'; var TEST = process.env.NODE_ENV === 'test'; var jsBundl...
module.exports = config;
random_line_split
test_course_info.py
""" Test the course_info xblock """ import mock from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXE...
(LoginEnrollmentTestCase, ModuleStoreTestCase): # The following XML test course (which lives at common/test/data/2014) # is closed; we're testing that a course info page still appears when # the course is already closed xml_course_id = 'edX/detached_pages/2014' # this text appears in that course's ...
CourseInfoTestCaseXML
identifier_name
test_course_info.py
""" Test the course_info xblock """ import mock from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXE...
url = reverse('info', args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertNotIn("OOGIE BLOOGIE", resp.content) @override_settings(MODULESTORE=TEST_DATA_MIXED_MODULESTORE) class CourseInfoTestCaseXML(LoginEnrollmen...
url = reverse('info', args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertNotIn("You are not currently enrolled in this course", resp.content) def test_anonymous_user(self):
random_line_split
test_course_info.py
""" Test the course_info xblock """ import mock from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXE...
def test_logged_in_unenrolled(self): self.setup_user() url = reverse('info', args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertIn("OOGIE BLOOGIE", resp.content) self.assertIn("You are not cur...
self.course = CourseFactory.create() self.page = ItemFactory.create( category="course_info", parent_location=self.course.location, data="OOGIE BLOOGIE", display_name="updates" )
identifier_body
tryclient.py
.baserev)]) d.addCallback(self.readPatch, self.patchlevel) return d class MercurialExtractor(SourceStampExtractor): patchlevel = 1 vcexe = "hg" def _didvc(self, res, cmd): (stdout, stderr, code) = res if code: cs = ' '.join(['hg'] + cmd) if stderr:...
(vctype, treetop, branch=None, repository=None): if vctype == "cvs": cls = CVSExtractor elif vctype == "svn": cls = SVNExtractor elif vctype == "bzr": cls = BzrExtractor elif vctype == "hg": cls = MercurialExtractor elif vctype == "p4": cls = PerforceExtractor...
getSourceStamp
identifier_name
tryclient.py
.baserev)]) d.addCallback(self.readPatch, self.patchlevel) return d class MercurialExtractor(SourceStampExtractor): patchlevel = 1 vcexe = "hg" def _didvc(self, res, cmd): (stdout, stderr, code) = res if code: cs = ' '.join(['hg'] + cmd) if stderr:...
config = None def getBaseRevision(self): # If a branch is specified, parse out the rev it points to # and extract the local name. if self.branch: d = self.dovc(["rev-parse", self.branch]) d.addCallback(self.override_baserev) d.addCallback(self.extract...
class GitExtractor(SourceStampExtractor): patchlevel = 1 vcexe = "git"
random_line_split
tryclient.py
(remotes).split("\n"): r = l.strip() if r and self.branch.startswith(r + "/"): self.branch = self.branch[len(r) + 1:] break def readConfig(self): if self.config: return defer.succeed(self.config) d = self.dovc(["config", "-l"]) ...
vc = self.getopt("vc") if vc in ("cvs", "svn"): # we need to find the tree-top topdir = self.getopt("topdir") if topdir: treedir = os.path.expanduser(topdir) else: topfile = self.getopt("topfile") ...
conditional_block
tryclient.py
getBaseRevision(self): d = self.dovc(["changes", "-m1", "..."]) d.addCallback(self.parseStatus) return d def parseStatus(self, res): # # extract the base change number # m = re.search(br'Change (\d+)', res) if m: self.baserev = m.group(1)...
self.transport.write(unicode2bytes(self.job)) self.transport.closeStdin()
identifier_body
mi_triangles.py
import networkx as nx import itertools import matplotlib.pyplot as plt fig = plt.figure() fig.subplots_adjust(left=0.2, wspace=0.6) G = nx.Graph() G.add_edges_from([(1,2,{'w': 6}), (2,3,{'w': 3}), (3,1,{'w': 4}), (3,4,{'w': 12}), (4,5,{'w': 13})...
graph2 = fig.add_subplot(122) graph2.plot(nx.draw(G, pos=pos, node_size = [G.degree(n) for n in G.nodes()], width = [G.get_edge_data(*e)['w'] for e in G.edges()], edge_color = [G.get_edge_data(*e)['w'] for e in G.edges()] )) plt.show()
random_line_split
mi_triangles.py
import networkx as nx import itertools import matplotlib.pyplot as plt fig = plt.figure() fig.subplots_adjust(left=0.2, wspace=0.6) G = nx.Graph() G.add_edges_from([(1,2,{'w': 6}), (2,3,{'w': 3}), (3,1,{'w': 4}), (3,4,{'w': 12}), (4,5,{'w': 13})...
pos = nx.spring_layout(G) graph1 = fig.add_subplot(121) # graph1.plot(nx.draw_networkx_nodes(G, pos=pos, node_size=[G.degree(n) for n in G.nodes()], label=True, alpha=0.75), # nx.draw_networkx_edges(G, pos=pos, width=[G.get_edge_data(*e)['w'] for e in G.edges()], alpha=0.75)) graph1.plot(nx.draw(G, ...
triangles.append(vertices)
conditional_block
background.js
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable...
/** * Handles messages for the project subsystem and redirects as appropriate. * @param {!Object} request The data sent. * @param {MessageSender} sender An object containing information about the * script context that sent the request. * @param {function(!*): void} response Optional function to call when the ...
random_line_split
serial_serial.py
# Copyright (C) 2016 The BET Development Team # -*- coding: utf-8 -*- # This demonstrates how to use BET in serial to sample a serial external model. # run by calling "python serial_serial.py" import os import subprocess import scipy.io as sio import bet.sampling.basicSampling as bsam def lb_model(input_data): ...
my_sampler = bsam.sampler(lb_model) my_discretization = my_sampler.create_random_discretization(sample_type='r', input_obj=4, savefile="serial_serial_example", num_samples=100)
io_file_name = "io_file" io_mdat = dict() io_mdat['input'] = input_data # save the input to file sio.savemat(io_file_name, io_mdat) # run the model subprocess.call(['python', 'serial_model.py', io_file_name]) # read the output from file io_mdat = sio.loadmat(io_file_name) output_d...
identifier_body
serial_serial.py
# Copyright (C) 2016 The BET Development Team # -*- coding: utf-8 -*- # This demonstrates how to use BET in serial to sample a serial external model. # run by calling "python serial_serial.py" import os import subprocess import scipy.io as sio import bet.sampling.basicSampling as bsam def
(input_data): io_file_name = "io_file" io_mdat = dict() io_mdat['input'] = input_data # save the input to file sio.savemat(io_file_name, io_mdat) # run the model subprocess.call(['python', 'serial_model.py', io_file_name]) # read the output from file io_mdat = sio.loadmat(io_file_...
lb_model
identifier_name
serial_serial.py
# Copyright (C) 2016 The BET Development Team # -*- coding: utf-8 -*- # This demonstrates how to use BET in serial to sample a serial external model. # run by calling "python serial_serial.py" import os import subprocess import scipy.io as sio import bet.sampling.basicSampling as bsam def lb_model(input_data): ...
my_discretization = my_sampler.create_random_discretization(sample_type='r', input_obj=4, savefile="serial_serial_example", num_samples=100)
my_sampler = bsam.sampler(lb_model)
random_line_split
Circle.ts
export class Circle { private _radius: number; private _x: number; private _y: number; constructor(x: number, y: number, radius: number) { // SZ method and properties names should start from lower case character // SZ underscore is ok for private methods and properties. NOT for rework....
this._radius = val; } public set X(val: number) { this._x = val; } public get X(): number { return this._x; } public set Y(val: number) { this._y = val; } public get Y(): number { return this._y; } public calculateSquare(): number { ...
throw new Error("Radius should be between 0 and 100"); }
conditional_block
Circle.ts
export class Circle { private _radius: number; private _x: number; private _y: number; constructor(x: number, y: number, radius: number) { // SZ method and properties names should start from lower case character // SZ underscore is ok for private methods and properties. NOT for rework....
public calculateSquare(): number { return +(Math.PI * this._radius * this._radius).toFixed(2); } public calculateCircumference(): number { return +(2 * Math.PI * this._radius).toFixed(2); } }
return this._y; }
identifier_body
Circle.ts
export class Circle { private _radius: number; private _x: number; private _y: number; constructor(x: number, y: number, radius: number) { // SZ method and properties names should start from lower case character // SZ underscore is ok for private methods and properties. NOT for rework....
} }
public calculateCircumference(): number { return +(2 * Math.PI * this._radius).toFixed(2);
random_line_split
Circle.ts
export class Ci
private _radius: number; private _x: number; private _y: number; constructor(x: number, y: number, radius: number) { // SZ method and properties names should start from lower case character // SZ underscore is ok for private methods and properties. NOT for rework. this.Radius =...
rcle {
identifier_name
mailbase.py
#!/usr/bin/env python # coding: utf-8 import email.utils import logging import os import smtplib import threading from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart logger = logging.getLogger("maillog") class MailBase(threading.Thread): mailServerPort = 25 def __init__(self,...
subject = subject.decode("utf-8") self._do_send_mail(self.BASICS["TOLIST"], subject, content, attachment) def run(self): if not self.subject or not self.content: return self._send_mail(self.subject, self.content, self.attachment) def _do_send_mail(self, to, subject, content...
mailSettings("basic_info not a dict") def _send_mail(self, subject, content, attachment):
conditional_block
mailbase.py
#!/usr/bin/env python # coding: utf-8 import email.utils import logging import os import smtplib import threading from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart logger = logging.getLogger("maillog") class MailBase(threading.Thread): mailServerPort = 25 def __init__(self,...
msg = MIMEMultipart('related') msg['To'] = ', '.join(to) msg['From'] = email.utils.formataddr((self.BASICS["USERNAME"], self.BASICS["USERNAME"])) msg['Subject'] = subject # msgText = MIMEText(content.encode("utf-8"), "html") msgtext = MIMEText(content, "html") msg...
self._send_mail(self.subject, self.content, self.attachment) def _do_send_mail(self, to, subject, content, attachment):
identifier_body
mailbase.py
#!/usr/bin/env python # coding: utf-8 import email.utils import logging import os import smtplib import threading from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart logger = logging.getLogger("maillog") class MailBase(threading.Thread): mailServerPort = 25 def
(self, subject, content, basic_info, attachment=""): """ 多线程邮件处理类 @Params target: file or string basicInfo= { "TOLIST": ["heyu@ucweb.com"], "SERVER": "mail.ucweb.com", "PORT": 25, #25 if mis...
__init__
identifier_name
mailbase.py
#!/usr/bin/env python # coding: utf-8 import email.utils
from email.MIMEMultipart import MIMEMultipart logger = logging.getLogger("maillog") class MailBase(threading.Thread): mailServerPort = 25 def __init__(self, subject, content, basic_info, attachment=""): """ 多线程邮件处理类 @Params target: file or string ba...
import logging import os import smtplib import threading from email.mime.text import MIMEText
random_line_split
setup.py
import setuptools
requirements = f.read().splitlines() with open('cli-requirements.txt') as f: cli_requirements = f.read().splitlines() setuptools.setup( name="uwg", use_scm_version=True, setup_requires=['setuptools_scm'], author="Ladybug Tools", author_email="info@ladybug.tools", description="Python ap...
with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f:
random_line_split
admin.py
from django import forms from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.utils.translation import ugettext_lazy as _
" underscores, dashes or slashes.")) class Meta: model = FlatPage class FlatPageAdmin(admin.ModelAdmin): form = FlatpageForm fieldsets = ( (None, {'fields': ('url', 'title', 'content', 'sites')}), (_('Advanced options'), {'classes': ('collapse',), 'fields...
class FlatpageForm(forms.ModelForm): url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/]+$', help_text = _("Example: '/about/contact/'. Make sure to have leading" " and trailing slashes."), error_message = _("This value must contain only letters, numbers,"
random_line_split
admin.py
from django import forms from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.utils.translation import ugettext_lazy as _ class FlatpageForm(forms.ModelForm):
class FlatPageAdmin(admin.ModelAdmin): form = FlatpageForm fieldsets = ( (None, {'fields': ('url', 'title', 'content', 'sites')}), (_('Advanced options'), {'classes': ('collapse',), 'fields': ('enable_comments', 'registration_required', 'template_name')}), ) list_display = ('url', 'ti...
url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/]+$', help_text = _("Example: '/about/contact/'. Make sure to have leading" " and trailing slashes."), error_message = _("This value must contain only letters, numbers," " underscores, da...
identifier_body
admin.py
from django import forms from django.contrib import admin from django.contrib.flatpages.models import FlatPage from django.utils.translation import ugettext_lazy as _ class FlatpageForm(forms.ModelForm): url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/]+$', help_text = _("Example: '/a...
(admin.ModelAdmin): form = FlatpageForm fieldsets = ( (None, {'fields': ('url', 'title', 'content', 'sites')}), (_('Advanced options'), {'classes': ('collapse',), 'fields': ('enable_comments', 'registration_required', 'template_name')}), ) list_display = ('url', 'title') list_filter ...
FlatPageAdmin
identifier_name
SuperIterable.d.ts
declare class
<T> implements Iterable<T> { [Symbol.iterator]: () => Iterator<T>; constructor(iterable: Iterable<T>); map<U>(func: (x: T) => U): SuperIterable<U>; filter(func: (x: T) => boolean): SuperIterable<T>; flatMap<U>(func: (x: T) => Iterable<U>): SuperIterable<U>; forEach(f: (x: T) => void): void; ...
SuperIterable
identifier_name
SuperIterable.d.ts
declare class SuperIterable<T> implements Iterable<T> { [Symbol.iterator]: () => Iterator<T>; constructor(iterable: Iterable<T>); map<U>(func: (x: T) => U): SuperIterable<U>; filter(func: (x: T) => boolean): SuperIterable<T>; flatMap<U>(func: (x: T) => Iterable<U>): SuperIterable<U>; forEach(f: ...
count(): number; get(n: number): T; toArray(): T[]; } export = SuperIterable;
find(p: (x: T) => boolean): T; findIndex(p: (x: T) => boolean): number; indexOf(elem: T): number; includes(elem: T): boolean; concat(...others: Iterable<T>[]): SuperIterable<T>;
random_line_split
source_code_component.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
range: new this.monaco.Range( currentFocusedLineno, 1, currentFocusedLineno, lineLength + 1 ), options: { inlineClassName: 'highlight-line', }, }, ]); } if (changes['useDarkMode']) { this.mo...
{ this.editor.revealLineInCenter( currentFocusedLineno, this.monaco.editor.ScrollType.Smooth ); const lineLength = this.lines[currentFocusedLineno - 1].length; this.decorations = this.editor.deltaDecorations(this.decorations, [ { range: new this.monaco.Range( ...
conditional_block
source_code_component.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
this.editor.revealLineInCenter( currentFocusedLineno, this.monaco.editor.ScrollType.Smooth ); const lineLength = this.lines[currentFocusedLineno - 1].length; this.decorations = this.editor.deltaDecorations(this.decorations, [ { range: new this.monaco.Range( ...
if (currentFocusedLineno && this.lines) {
random_line_split
source_code_component.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
(changes: SimpleChanges): void { if (this.monaco === null) { return; } const editorNewlyCreated = changes['monaco'] && this.editor === null; if (this.editor === null) { this.editor = this.monaco.editor.create( this.codeViewerContainer.nativeElement, { value: (this....
ngOnChanges
identifier_name