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
packed-struct-transmute.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let foo = Foo { bar: 1, baz: 10 }; unsafe { let oof: Oof = mem::transmute(foo); println!("{}", oof); } }
identifier_body
admin.rs
extern crate bytes; extern crate futures; extern crate rustygear; extern crate rustygeard; use std::sync::{Arc, Mutex}; use std::collections::BTreeMap; use bytes::Bytes; use rustygear::constants::*; use rustygear::job::Job; use rustygeard::admin::{admin_command_status, admin_command_workers}; use rustygeard::queues...
assert_eq!(expected, response); }
wbci.insert(11, worker); } let packet = admin_command_workers(workers_by_conn_id); let response = String::from_utf8(packet.data.to_vec()).unwrap(); let expected = String::from("10 127.0.0.1:37337 hacker1 : hack\n11 127.0.0.1:33333 - :\n.\n");
random_line_split
admin.rs
extern crate bytes; extern crate futures; extern crate rustygear; extern crate rustygeard; use std::sync::{Arc, Mutex}; use std::collections::BTreeMap; use bytes::Bytes; use rustygear::constants::*; use rustygear::job::Job; use rustygeard::admin::{admin_command_status, admin_command_workers}; use rustygeard::queues...
#[test] fn admin_command_workers_with2() { let workers_by_conn_id: WorkersByConnId = Arc::new(Mutex::new(BTreeMap::new())); { let mut wbci = workers_by_conn_id.lock().unwrap(); let worker = Arc::new(Mutex::new(Worker::new("127.0.0.1:37337".parse().unwrap(), Bytes::from("hacker1")))); {...
{ let workers_by_conn_id = Arc::new(Mutex::new(BTreeMap::new())); let packet = admin_command_workers(workers_by_conn_id); assert_eq!(b".\n", &packet.data[..]); }
identifier_body
admin.rs
extern crate bytes; extern crate futures; extern crate rustygear; extern crate rustygeard; use std::sync::{Arc, Mutex}; use std::collections::BTreeMap; use bytes::Bytes; use rustygear::constants::*; use rustygear::job::Job; use rustygeard::admin::{admin_command_status, admin_command_workers}; use rustygeard::queues...
() { let workers_by_conn_id: WorkersByConnId = Arc::new(Mutex::new(BTreeMap::new())); { let mut wbci = workers_by_conn_id.lock().unwrap(); let worker = Arc::new(Mutex::new(Worker::new("127.0.0.1:37337".parse().unwrap(), Bytes::from("hacker1")))); { let mut worker = worker.loc...
admin_command_workers_with2
identifier_name
stdio.rs
standard I/O streams. // // After this day, the world split into four factions: // // 1. Unix with stdout on a terminal. // 2. Unix with stdout redirected. // 3. Windows with stdout on a terminal. // 4. Windows with stdout redirected. // // Many years passed, and then one day the nation of libuv decided to unify this ...
() -> StdReader { src(libc::STDIN_FILENO, true, |src| StdReader { inner: src }) } /// Creates a line-buffered handle to the stdout of the current process. /// /// Note that this is a fairly expensive operation in that at least one memory /// allocation is performed. Additionally, this must be called from a runtime...
stdin_raw
identifier_name
stdio.rs
't like // 64k reads on stdin. See #13304 for details, but the idea is that on // windows we use a slightly smaller buffer that's been seen to be // acceptable. if cfg!(windows) { BufferedReader::with_capacity(8 * 1024, stdin_raw()) } else { BufferedReader::new(stdin_raw()) } } ...
} impl Writer for StdWriter {
random_line_split
util.py
read, write, Sequence, DNA logger = getLogger(__name__) def convert(in_f, in_fmt, out_f, out_fmt): '''convert between file formats Parameters ---------- in_fmt : str input file format out_fmt : str output file format in_f : str input file path out_f: str ...
def split(is_another, construct=None, ignore=None, **kwargs): '''Return a function to yield record. Parameters ---------- is_another : callable accept a string and return a bool indicating if the current line starts a new record or not. construct : callable (optional) acc...
'''Test if two database files have the same contents.''' with connect(db1) as o, connect(db2) as e: co = o.cursor() ce = e.cursor() # compare each table for table, in e.execute( "SELECT name FROM sqlite_master WHERE type='table'"): ...
identifier_body
util.py
read, write, Sequence, DNA logger = getLogger(__name__) def convert(in_f, in_fmt, out_f, out_fmt): '''convert between file formats Parameters ---------- in_fmt : str input file format out_fmt : str output file format in_f : str input file path out_f: str ...
if lines: yield lines return parse def split_head(line, is_head=lambda line: line.startswith('>')): ''' Examples -------- >>> import io >>> s = """>seq1 ... ATGC ... >seq2 ... A ... T ... """ >>> f = io.StringIO(s) >>> gen = split(split_head, co...
if construct is not None: line = construct(line) lines.append(line)
random_line_split
util.py
read, write, Sequence, DNA logger = getLogger(__name__) def convert(in_f, in_fmt, out_f, out_fmt): '''convert between file formats Parameters ---------- in_fmt : str input file format out_fmt : str output file format in_f : str input file path out_f: str ...
for i in imd.query(metadata={'partial': '10'}): i.drop() imd.write(out, seq_id=seq_id, format='gff3') class _DBTest(TestCase): def _test_eq_db(self, db1, db2): '''Test if two database files have the same contents.''' with connect(db1) as o, connect(db2) as ...
i.drop()
conditional_block
util.py
read, write, Sequence, DNA logger = getLogger(__name__) def convert(in_f, in_fmt, out_f, out_fmt): '''convert between file formats Parameters ---------- in_fmt : str input file format out_fmt : str output file format in_f : str input file path out_f: str ...
(in_seq, in_fmt=None, discard=lambda s: len(s) < 500): '''Validate and filter input seq file. 1. filter seq; 2. validate seq IDs (no duplicates) 3. remove gaps in the sequence if there is any Parameters ---------- in_seq : str or Iterable of ``Sequence`` objects input seq file path...
check_seq
identifier_name
test_bandb_sampler.py
from __future__ import print_function import IMP import IMP.test import IMP.domino
class TrivialParticleStates(IMP.domino.ParticleStates): def __init__(self, n): IMP.domino.ParticleStates.__init__(self) self.key = IMP.IntKey("hi") self.n = n def get_number_of_particle_states(self): return self.n def load_particle_state(self, i, p): if p.has_attr...
import IMP.core
random_line_split
test_bandb_sampler.py
from __future__ import print_function import IMP import IMP.test import IMP.domino import IMP.core class TrivialParticleStates(IMP.domino.ParticleStates): def __init__(self, n): IMP.domino.ParticleStates.__init__(self) self.key = IMP.IntKey("hi") self.n = n def
(self): return self.n def load_particle_state(self, i, p): if p.has_attribute(self.key): p.set_value(self.key, i) else: p.add_attribute(self.key, i) def do_show(self, stream): pass class Tests(IMP.test.TestCase): def test_global_min1(self): ...
get_number_of_particle_states
identifier_name
test_bandb_sampler.py
from __future__ import print_function import IMP import IMP.test import IMP.domino import IMP.core class TrivialParticleStates(IMP.domino.ParticleStates):
class Tests(IMP.test.TestCase): def test_global_min1(self): """Testing branch and bound sampler""" m = IMP.Model() m.set_log_level(IMP.SILENT) IMP.set_log_level(IMP.VERBOSE) ps = [] ns = 5 np = 4 for i in range(0, np): ps.append(IMP.Par...
def __init__(self, n): IMP.domino.ParticleStates.__init__(self) self.key = IMP.IntKey("hi") self.n = n def get_number_of_particle_states(self): return self.n def load_particle_state(self, i, p): if p.has_attribute(self.key): p.set_value(self.key, i) ...
identifier_body
test_bandb_sampler.py
from __future__ import print_function import IMP import IMP.test import IMP.domino import IMP.core class TrivialParticleStates(IMP.domino.ParticleStates): def __init__(self, n): IMP.domino.ParticleStates.__init__(self) self.key = IMP.IntKey("hi") self.n = n def get_number_of_particle...
cs = dsst.create_sample() self.assertEqual(cs.get_number_of_configurations(), ns ** len(ps)) all_states = [] for i in range(0, cs.get_number_of_configurations()): cs.load_configuration(i) s = [] for p in ps: s.append(p.get_value(IMP.In...
pst.set_particle_states(p, TrivialParticleStates(ns))
conditional_block
lib.rs
//! SeaHash: A blazingly fast, portable hash function with proven statistical guarantees. //! //! SeaHash is a hash function with performance better than (around 3-20% improvement) xxHash and //! MetroHash. Furthermore, SeaHash has mathematically provable statistical guarantees. //! //! SeaHash is a portable hash funct...
//! //! If the diffusion function (f) was cryptographically secure, it would pass cryptoanalysis //! trivially. This might seem irrelevant, as it clearly isn't cryptographically secure, but it //! tells us something about the inner semantics. In particular, any diffusion function with //! sufficient statistical quality...
//! The advantage of having four completely segregated (note that there is no mix round, so they're //! entirely independent) states is that fast parallelism is possible. For example, if I were to //! hash 1 TB, I can spawn up four threads which can run independently without _any_ //! intercommunication or synchronizat...
random_line_split
test_requirement_exporter.py
# pylint: disable=missing-docstring,redefined-outer-name,no-self-use,protected-access import copy import os from collections import OrderedDict import pytest from dump2polarion.exceptions import Dump2PolarionException, NothingToDoException from dump2polarion.exporters.requirements_exporter import RequirementExport f...
def test_export(self, config_cloudtp): req_exp = RequirementExport(REQ_DATA, config_cloudtp) complete = req_exp.export() fname = "requirement_complete.xml" with open(os.path.join(conf.DATA_PATH, fname), encoding="utf-8") as input_xml: parsed = input_xml.read() ass...
random_line_split
test_requirement_exporter.py
# pylint: disable=missing-docstring,redefined-outer-name,no-self-use,protected-access import copy import os from collections import OrderedDict import pytest from dump2polarion.exceptions import Dump2PolarionException, NothingToDoException from dump2polarion.exporters.requirements_exporter import RequirementExport f...
: def test_export(self, config_cloudtp): req_exp = RequirementExport(REQ_DATA, config_cloudtp) complete = req_exp.export() fname = "requirement_complete.xml" with open(os.path.join(conf.DATA_PATH, fname), encoding="utf-8") as input_xml: parsed = input_xml.read() a...
TestRequirement
identifier_name
test_requirement_exporter.py
# pylint: disable=missing-docstring,redefined-outer-name,no-self-use,protected-access import copy import os from collections import OrderedDict import pytest from dump2polarion.exceptions import Dump2PolarionException, NothingToDoException from dump2polarion.exporters.requirements_exporter import RequirementExport f...
def test_invalid_lookup(self, config_cloudtp): new_config = copy.deepcopy(config_cloudtp) new_config["requirements_import_properties"] = {"lookup-method": "inv"} req_exp = RequirementExport(REQ_DATA, new_config) with pytest.raises(Dump2PolarionException) as excinfo: req...
req_exp = RequirementExport(REQ_DATA, config_cloudtp) complete = req_exp.export() fname = "requirement_complete.xml" with open(os.path.join(conf.DATA_PATH, fname), encoding="utf-8") as input_xml: parsed = input_xml.read() assert complete == parsed
identifier_body
GroupFlatFeed.tsx
import { Col } from '@tlon/indigo-react'; import React, { useEffect } from 'react'; import { Route, Switch, useHistory } from 'react-router-dom'; import { resourceFromPath } from '~/logic/lib/group'; import useGraphState, { useGraphTimesentMap } from '~/logic/state/graph'; import { useGroup } from '~/logic/state/grou...
const graphTimesentMap = useGraphTimesentMap(graphRid.ship, graphRid.name); const pendingSize = Object.keys(graphTimesentMap || {}).length; const relativePath = path => baseUrl + path; const history = useHistory(); const getDeepOlderThan = useGraphState(s => s.getDeepOlderThan); useEffect(() => { // ...
const graphRid = graphPath ? resourceFromPath(graphPath) : resourceFromPath('/ship/~zod/null'); const association = useAssocForGraph(graphPath);
random_line_split
GroupFlatFeed.tsx
import { Col } from '@tlon/indigo-react'; import React, { useEffect } from 'react'; import { Route, Switch, useHistory } from 'react-router-dom'; import { resourceFromPath } from '~/logic/lib/group'; import useGraphState, { useGraphTimesentMap } from '~/logic/state/graph'; import { useGroup } from '~/logic/state/grou...
return ( <Col width="100%" height="100%" display="flex" overflow="hidden" position="relative" alignItems="center" > <GroupFeedHeader baseUrl={baseUrl} history={history} vip={vip} graphResource={graphRid} /> <Switch> ...
{ return <Loading />; }
conditional_block
index.js
// Include Endpoints configuration = require('./configuration'), db = require('./db'), mail = require('./mail'), notifications = require('./notifications'), posts = require('./posts'), roles = require('./roles'), settings = require('./settings...
http, formatHttpErrors, addHeaders, cacheInvalidationHeader, locationHeader, contentDispositionHeader, init; /** * ### Init * Initialise the API - populate the settings cache * @return {Promise(Settings)} Resolves to Settings Collection */ init = function () { return settings.update...
random_line_split
index.js
// Include Endpoints configuration = require('./configuration'), db = require('./db'), mail = require('./mail'), notifications = require('./notifications'), posts = require('./posts'), roles = require('./roles'), settings = require('./settings...
}); ops.push(contentDisposition); } return Promise.all(ops); }; /** * ### HTTP * * Decorator for API functions which are called via an HTTP request. Takes the API method and wraps it so that it gets * data from the request and returns a sensible JSON response. * * @public * @param ...
{ res.set({ 'Content-Disposition': header }); }
conditional_block
flash_jlink.py
#!/usr/bin/env python3 # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=logging-fstring-interpolation """Flashes firmware using Segger J-Link. This script requires Segger hardware at...
logging.error('Ensure that JLinkRemoteServerCLExe is running.') return 1 cmd.extend(['-ip', remote]) cmd.extend([ '-device', device, '-if', interface, '-speed', 'auto', '-autoconnect', '1', '-CommandFile', cmd_file, ]) logging.debu...
logging.error( f"JLink server doesn't seem to be listening on {remote}.")
random_line_split
flash_jlink.py
#!/usr/bin/env python3 # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=logging-fstring-interpolation """Flashes firmware using Segger J-Link. This script requires Segger hardware at...
: """Board configuration.""" def __init__(self, interface, device, flash_address): self.interface = interface self.device = device self.flash_address = flash_address SWD_INTERFACE = 'SWD' STM32_DEFAULT_FLASH_ADDRESS = '0x8000000' DRAGONCLAW_CONFIG = BoardConfig(interface=SWD_INTERFACE,...
BoardConfig
identifier_name
flash_jlink.py
#!/usr/bin/env python3 # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=logging-fstring-interpolation """Flashes firmware using Segger J-Link. This script requires Segger hardware at...
f'Given remote port "{remote_components[1]}" is malformed.') return 1 remote = f'{ip}:{port}' logging.debug(f'Checking connection to {remote}.') if not is_tcp_port_open(ip, port): logging.error( f"JLink server doesn't seem to be l...
logging.debug(f'Connecting to J-Link over TCP/IP {remote}.') remote_components = remote.split(':') if len(remote_components) not in [1, 2]: logging.debug(f'Given remote "{remote}" is malformed.') return 1 host = remote_components[0] try: ip = socket.g...
conditional_block
flash_jlink.py
#!/usr/bin/env python3 # Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=logging-fstring-interpolation """Flashes firmware using Segger J-Link. This script requires Segger hardware at...
# TCP/IP (127.0.0.1, port 19020) time.sleep(0.5) return True def create_jlink_command_file(firmware_file, config): tmp = tempfile.NamedTemporaryFile() tmp.write(JLINK_COMMANDS.format(FIRMWARE=firmware_file, FLASH_ADDRESS=config.flash_address).encode( ...
"""Checks if the TCP host port is open.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(2) # 2 Second Timeout try: sock.connect((host, tcp_port)) sock.shutdown(socket.SHUT_RDWR) except ConnectionRefusedError: return False except socket.timeout: ...
identifier_body
styleguide.loader.js
var fs = require('fs'); var path = require('path'); var glob = require('glob'); var prettyjson = require('prettyjson'); var _ = require('lodash'); var config = require('../src/utils/config'); function processComponent(filepath) { var examplesFile = config.getExampleFilename(filepath); var hasExamples = !!fs.existsSy...
if (config.verbose) { console.log(); console.log('Loading components:'); console.log(prettyjson.render(componentSources)); console.log(); } var specPath; var specId; var components = componentSources.map(function(item){ specPath = config.getExampleFilename(item); specId = path.dirname(specPath.repl...
{ componentSources = glob.sync(path.join(config.rootDir, config.components)); }
conditional_block
styleguide.loader.js
var fs = require('fs'); var path = require('path'); var glob = require('glob'); var prettyjson = require('prettyjson'); var _ = require('lodash'); var config = require('../src/utils/config'); function processComponent(filepath) { var examplesFile = config.getExampleFilename(filepath); var hasExamples = !!fs.existsSy...
var componentSources; if (typeof config.components === 'function') { componentSources = config.components(config, glob); } else { componentSources = glob.sync(path.join(config.rootDir, config.components)); } if (config.verbose) { console.log(); console.log('Loading components:'); console.log(prettyjson...
this.cacheable && this.cacheable();
random_line_split
styleguide.loader.js
var fs = require('fs'); var path = require('path'); var glob = require('glob'); var prettyjson = require('prettyjson'); var _ = require('lodash'); var config = require('../src/utils/config'); function processComponent(filepath) { var examplesFile = config.getExampleFilename(filepath); var hasExamples = !!fs.existsSy...
module.exports = function() {}; module.exports.pitch = function() { this.cacheable && this.cacheable(); var componentSources; if (typeof config.components === 'function') { componentSources = config.components(config, glob); } else { componentSources = glob.sync(path.join(config.rootDir, config.components))...
{ return 'require(' + JSON.stringify(filepath) + ')'; }
identifier_body
styleguide.loader.js
var fs = require('fs'); var path = require('path'); var glob = require('glob'); var prettyjson = require('prettyjson'); var _ = require('lodash'); var config = require('../src/utils/config'); function
(filepath) { var examplesFile = config.getExampleFilename(filepath); var hasExamples = !!fs.existsSync(examplesFile); return '{' + [ 'filepath: ' + JSON.stringify(filepath), 'relativePath: ' + JSON.stringify(path.relative(config.rootDir, filepath)), 'module: ' + requireIt(filepath), 'examples: ' + (hasEx...
processComponent
identifier_name
paste.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'paste', function( editor ) { var lang = editor.lang.clipboard; var isCustomDomain = CKEDITOR.env.isCustomDomain(); function
( win ) { var doc = new CKEDITOR.dom.document( win.document ), docElement = doc.$; var script = doc.getById( 'cke_actscrpt' ); script && script.remove(); CKEDITOR.env.ie ? docElement.body.contentEditable = "true" : docElement.designMode = "on"; // IE before version 8 will leave cursor...
onPasteFrameLoad
identifier_name
paste.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'paste', function( editor ) { var lang = editor.lang.clipboard; var isCustomDomain = CKEDITOR.env.isCustomDomain(); function onPasteFrameLo...
var script = doc.getById( 'cke_actscrpt' ); script && script.remove(); CKEDITOR.env.ie ? docElement.body.contentEditable = "true" : docElement.designMode = "on"; // IE before version 8 will leave cursor blinking inside the document after // editor blurred unless we clean up the selection. (#...
{ var doc = new CKEDITOR.dom.document( win.document ), docElement = doc.$;
random_line_split
paste.js
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'paste', function( editor ) { var lang = editor.lang.clipboard; var isCustomDomain = CKEDITOR.env.isCustomDomain(); function onPasteFrameLo...
doc.on( "keydown", function( e ) { var domEvent = e.data, key = domEvent.getKeystroke(), processed; switch( key ) { case 27 : this.hide(); processed = 1; break; case 9 : case CKEDITOR.SHIFT + 9 : this.changeFocus( true ); processed = 1; }...
{ var doc = new CKEDITOR.dom.document( win.document ), docElement = doc.$; var script = doc.getById( 'cke_actscrpt' ); script && script.remove(); CKEDITOR.env.ie ? docElement.body.contentEditable = "true" : docElement.designMode = "on"; // IE before version 8 will leave cursor blinking ...
identifier_body
CoFactor.py
from base.iterativeRecommender import IterativeRecommender import numpy as np from util import config from collections import defaultdict from math import log,exp from scipy.sparse import * from scipy import * class CoFactor(IterativeRecommender): def __init__(self, conf, trainingSet=None, testSet=None, fold='[1]'...
self.c = np.random.rand(self.num_items) / 10 # bias value of context self.G = np.random.rand(self.num_items, self.emb_size) / 10 # context embedding print('training...') epoch = 0 while epoch < self.maxEpoch: self.loss = 0 YtY = self.Y.T.dot(self.Y) ...
def buildModel(self): self.X=self.P*10 #Theta self.Y=self.Q*10 #Beta self.w = np.random.rand(self.num_items) / 10 # bias value of item
random_line_split
CoFactor.py
from base.iterativeRecommender import IterativeRecommender import numpy as np from util import config from collections import defaultdict from math import log,exp from scipy.sparse import * from scipy import * class CoFactor(IterativeRecommender): def __init__(self, conf, trainingSet=None, testSet=None, fold='[1]'...
def initModel(self): super(CoFactor, self).initModel() #constructing SPPMI matrix self.SPPMI = defaultdict(dict) print('Constructing SPPMI matrix...') #for larger data set has many items, the process will be time consuming occurrence = defaultdict(dict) i=0 ...
super(CoFactor, self).printAlgorConfig() print('Specified Arguments of', self.config['model.name'] + ':') print('k: %d' % self.negCount) print('regR: %.5f' %self.regR) print('filter: %d' %self.filter) print('=' * 80)
identifier_body
CoFactor.py
from base.iterativeRecommender import IterativeRecommender import numpy as np from util import config from collections import defaultdict from math import log,exp from scipy.sparse import * from scipy import * class CoFactor(IterativeRecommender): def
(self, conf, trainingSet=None, testSet=None, fold='[1]'): super(CoFactor, self).__init__(conf, trainingSet, testSet, fold) def readConfiguration(self): super(CoFactor, self).readConfiguration() extraSettings = config.OptionConf(self.config['CoFactor']) self.negCount = int(extraSetti...
__init__
identifier_name
CoFactor.py
from base.iterativeRecommender import IterativeRecommender import numpy as np from util import config from collections import defaultdict from math import log,exp from scipy.sparse import * from scipy import * class CoFactor(IterativeRecommender): def __init__(self, conf, trainingSet=None, testSet=None, fold='[1]'...
self.SPPMI[item1][item2] = val self.SPPMI[item2][item1] = self.SPPMI[item1][item2] #normalize for item1 in self.SPPMI: for item2 in self.SPPMI[item1]: self.SPPMI[item1][item2] = self.SPPMI[item1][item2]/maxVal def buildModel(sel...
maxVal = val
conditional_block
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codege...
(&self) -> bool { self.stop_propagation.get() } #[inline] pub fn stop_immediate(&self) -> bool { self.stop_immediate.get() } #[inline] pub fn bubbles(&self) -> bool { self.bubbles.get() } #[inline] pub fn dispatching(&self) -> bool { self.dispatchin...
stop_propagation
identifier_name
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codege...
#[inline] pub fn type_id<'a>(&'a self) -> &'a EventTypeId { &self.type_id } #[inline] pub fn clear_current_target(&self) { self.current_target.clear(); } #[inline] pub fn set_current_target(&self, val: JSRef<EventTarget>) { self.current_target.assign(Some(val)...
{ let bubbles = if init.bubbles { EventBubbles::Bubbles } else { EventBubbles::DoesNotBubble }; let cancelable = if init.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; Ok(Event::new(global, type_, bubbles, cancelable)) }
identifier_body
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codege...
} fn InitEvent(self, type_: DOMString, bubbles: bool, cancelable: bool) { if self.dispatching.get() { return; } self.initialized.set(true); self.stop_propagation.set(false); self.stop_immediate.set(false); ...
random_line_split
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codege...
else { EventBubbles::DoesNotBubble }; let cancelable = if init.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; Ok(Event::new(global, type_, bubbles, cancelable)) } #[inline] pub fn type_id<'a>(&'a self) -> &'a EventTypeId { &self.type_id } ...
{ EventBubbles::Bubbles }
conditional_block
factory.py
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template # from country_update_demo.extensions import ( # #add as needed
def asset_path_context_processor(): return {'asset_path': '/static/'} def create_app(config_filename): ''' An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ ''' app = Flask(__name__) app.config.from_object(config_filename) register_errorhand...
# )
random_line_split
factory.py
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template # from country_update_demo.extensions import ( # #add as needed # ) def asset_path_context_processor(): return {'asset_path': '/static/'} def create_app(config_filename): ''' An ap...
for errcode in [401, 404, 500]: app.errorhandler(errcode)(render_error) return None def register_blueprints(app): from country_update_demo.frontend.views import frontend app.register_blueprint(frontend) # def register_extensions(app): # pass
error_code = getattr(error, 'code', 500) return render_template("{0}.html".format(error_code)), error_code
identifier_body
factory.py
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template # from country_update_demo.extensions import ( # #add as needed # ) def asset_path_context_processor(): return {'asset_path': '/static/'} def
(config_filename): ''' An application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/ ''' app = Flask(__name__) app.config.from_object(config_filename) register_errorhandlers(app) register_blueprints(app) app.context_processor(asset_path_context_process...
create_app
identifier_name
factory.py
# -*- coding: utf-8 -*- '''The app module, containing the app factory function.''' from flask import Flask, render_template # from country_update_demo.extensions import ( # #add as needed # ) def asset_path_context_processor(): return {'asset_path': '/static/'} def create_app(config_filename): ''' An ap...
return None def register_blueprints(app): from country_update_demo.frontend.views import frontend app.register_blueprint(frontend) # def register_extensions(app): # pass
app.errorhandler(errcode)(render_error)
conditional_block
fn_type.py
from core_types import IncompatibleTypes, ImmutableT class FnT(ImmutableT): """Type of a typed function""" def __init__(self, input_types, return_type): self.input_types = tuple(input_types) self.return_type = return_type self._hash = hash(self.input_types + (return_type,)) def __str__(self): ...
(input_types, return_type): input_types = tuple(input_types) key = input_types, return_type if key in _fn_type_cache: return _fn_type_cache[key] else: t = FnT(input_types, return_type) _fn_type_cache[key] = t return t
make_fn_type
identifier_name
fn_type.py
from core_types import IncompatibleTypes, ImmutableT class FnT(ImmutableT): """Type of a typed function""" def __init__(self, input_types, return_type): self.input_types = tuple(input_types) self.return_type = return_type self._hash = hash(self.input_types + (return_type,)) def __str__(self): ...
t = FnT(input_types, return_type) _fn_type_cache[key] = t return t
conditional_block
fn_type.py
from core_types import IncompatibleTypes, ImmutableT class FnT(ImmutableT): """Type of a typed function""" def __init__(self, input_types, return_type): self.input_types = tuple(input_types) self.return_type = return_type self._hash = hash(self.input_types + (return_type,)) def __str__(self): ...
def combine(self, other): if self == other: return self else: raise IncompatibleTypes(self, other) def __hash__(self): return self._hash _fn_type_cache = {} def make_fn_type(input_types, return_type): input_types = tuple(input_types) key = input_types, return_type if key in _fn_typ...
return other.__class__ is FnT and \ self.return_type == other.return_type and \ len(self.input_types) == len(other.input_types) and \ all(t1 == t2 for (t1, t2) in zip(self.input_types, other.input_types))
identifier_body
fn_type.py
from core_types import IncompatibleTypes, ImmutableT class FnT(ImmutableT): """Type of a typed function""" def __init__(self, input_types, return_type): self.input_types = tuple(input_types) self.return_type = return_type self._hash = hash(self.input_types + (return_type,)) def __str__(self): ...
return t
t = FnT(input_types, return_type) _fn_type_cache[key] = t
random_line_split
render3.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Wraps a function in a new function which sets up document and HTML for running a test. * * This function is in...
savedDocument = (global as any).document; (global as any).window = window; (global as any).document = window.document; // Trick to avoid Event patching from // https://github.com/angular/angular/blob/7cf5e95ac9f0f2648beebf0d5bd9056b79946970/packages/platform-browser/src/dom/events/dom_events.ts#L112...
export function ensureDocument(): void { if (domino) { // we are in node.js. const window = domino.createWindow('', 'http://localhost');
random_line_split
render3.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Wraps a function in a new function which sets up document and HTML for running a test. * * This function is in...
let savedDocument: Document|undefined = undefined; let savedRequestAnimationFrame: ((callback: FrameRequestCallback) => number)|undefined = undefined; let savedNode: typeof Node|undefined = undefined; let requestAnimationFrameCount = 0; /** * System.js uses regexp to look for `require` statements. `domino` has to b...
{ return function(done: DoneFn) { ensureDocument(); if (typeof blockFn === 'function') { document.body.innerHTML = html; const blockReturn = blockFn(); if (blockReturn instanceof Promise) { blockReturn.then(done, done.fail); } else { done(); } } } as any; }
identifier_body
render3.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Wraps a function in a new function which sets up document and HTML for running a test. * * This function is in...
(): void { if (domino) { // we are in node.js. const window = domino.createWindow('', 'http://localhost'); savedDocument = (global as any).document; (global as any).window = window; (global as any).document = window.document; // Trick to avoid Event patching from // https://github.com/angu...
ensureDocument
identifier_name
render3.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Wraps a function in a new function which sets up document and HTML for running a test. * * This function is in...
} } as any; } let savedDocument: Document|undefined = undefined; let savedRequestAnimationFrame: ((callback: FrameRequestCallback) => number)|undefined = undefined; let savedNode: typeof Node|undefined = undefined; let requestAnimationFrameCount = 0; /** * System.js uses regexp to look for `require` statement...
{ done(); }
conditional_block
finders.py
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage, Storage, FileSystemStorage from django.utils.datastructures import SortedDict from django.utils.functional import memoize, LazyObject from django.utils.importlib impo...
def find(path, all=False): """ Find a static file with the given path using all enabled finders. If ``all`` is ``False`` (default), return the first matching absolute path (or ``None`` if no match). Otherwise return a list. """ matches = [] for finder in get_finders(): result = fin...
random_line_split
finders.py
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage, Storage, FileSystemStorage from django.utils.datastructures import SortedDict from django.utils.functional import memoize, LazyObject from django.utils.importlib impo...
def _get_finder(import_path): """ Imports the staticfiles finder class described by import_path, where import_path is the full Python path to the class. """ module, attr = import_path.rsplit('.', 1) try: mod = import_module(module) except ImportError, e: raise ImproperlyCon...
for finder_path in settings.STATICFILES_FINDERS: yield get_finder(finder_path)
identifier_body
finders.py
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage, Storage, FileSystemStorage from django.utils.datastructures import SortedDict from django.utils.functional import memoize, LazyObject from django.utils.importlib impo...
class BaseStorageFinder(BaseFinder): """ A base static files finder to be used to extended with an own storage class. """ storage = None def __init__(self, storage=None, *args, **kwargs): if storage is not None: self.storage = storage if self.storage is None: ...
return matched_path
conditional_block
finders.py
import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage, Storage, FileSystemStorage from django.utils.datastructures import SortedDict from django.utils.functional import memoize, LazyObject from django.utils.importlib impo...
(self, ignore_patterns): """ List all files of the storage. """ for path in utils.get_files(self.storage, ignore_patterns): yield path, self.storage class DefaultStorageFinder(BaseStorageFinder): """ A static files finder that uses the default storage backend. ""...
list
identifier_name
DatabaseHandler.py
import MySQLdb class DatabaseHandler: def __init__(self): pass def
(self, tableName): reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tableName, name) if isIdentical == 0: isDeleteFlag = 0 brea...
is_delete
identifier_name
DatabaseHandler.py
import MySQLdb class DatabaseHandler: def __init__(self): pass def is_delete(self, tableName): reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tab...
print 'clean database1' db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName) cursor = db.cursor() cursor.execute("Show Tables from " + databaseName) result = cursor.fetchall() for record in result: tableName = record[0] ...
isDeleteFlag = 0 break return isDeleteFlag def Clean_Database(self, hostUrl, account, password, databaseName):
random_line_split
DatabaseHandler.py
import MySQLdb class DatabaseHandler: def __init__(self): pass def is_delete(self, tableName):
def Clean_Database(self, hostUrl, account, password, databaseName): print 'clean database1' db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName) cursor = db.cursor() cursor.execute("Show Tables from " + databaseName) result = cursor.fetcha...
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tableName, name) if isIdentical == 0: isDeleteFlag = 0 break return isDeleteFl...
identifier_body
DatabaseHandler.py
import MySQLdb class DatabaseHandler: def __init__(self): pass def is_delete(self, tableName): reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"] isDeleteFlag = 1 for name in reservedTableNameList: isIdentical = cmp(tab...
return isDeleteFlag def Clean_Database(self, hostUrl, account, password, databaseName): print 'clean database1' db = MySQLdb.connect(host=hostUrl, user=account, passwd=password, db=databaseName) cursor = db.cursor() cursor.execute("Show Tables from " + databaseName) ...
isDeleteFlag = 0 break
conditional_block
color-sequence.js
$(function () { var linearPeriodDefaults = { step: 1, start: 0, increasing: true }; interference.LinearPeriod = function (options) { var settings = $.extend({}, linearPeriodDefaults, options); this._floor = settings.floor; this._ceiling = settings.ceiling; this._step = settings.step; this._c...
else { this._current = this._ceiling; this.next = this._decrease; } return this._current; }; interference.LinearPeriod.prototype._decrease = function () { if (this._current >= this._floor + this._step) { this._current -= this._step; } else { this._current = this._floor; this.next = this._...
{ this._current += this._step; }
conditional_block
color-sequence.js
$(function () { var linearPeriodDefaults = { step: 1, start: 0, increasing: true }; interference.LinearPeriod = function (options) { var settings = $.extend({}, linearPeriodDefaults, options); this._floor = settings.floor; this._ceiling = settings.ceiling; this._step = settings.step; this._c...
}; var greySequenceDefaults = { invert: false }; interference.GreySequence = function (options) { var settings = $.extend({}, greySequenceDefaults, options); this._normalize = settings.invert ? this._subtractGrey : this._addGrey; this._valueSequence = new interference.Sine(settings); }; interfe...
return 'rgb(' + value + ',' + value + ',' + value + ')';
random_line_split
app.module.ts
import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { IonicImageLoader } from 'ionic-image-loader'; import { MarkdownModule } from 'ngx-markdown'; import { NgxTextOverflowClampModule } from 'ngx-text-overflow-clamp'; import { C...
() { return new InterpolatedTranslateParser(); } export class InterpolatedTranslateParser extends TranslateDefaultParser { public templateMatcher: RegExp = /{\s?([^{}\s]*)\s?}/g; } export class MyMissingTranslationHandler implements MissingTranslationHandler { public parser: TranslateParser = translateParserFac...
translateParserFactory
identifier_name
app.module.ts
import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { IonicImageLoader } from 'ionic-image-loader'; import { MarkdownModule } from 'ngx-markdown'; import { NgxTextOverflowClampModule } from 'ngx-text-overflow-clamp'; import { C...
ModalTranslateEnterTransition ); this.config.setTransition( 'modal-translate-up-leave', ModalTranslateLeaveTransition ); } }
random_line_split
addon.test.ts
import fetchMock from 'jest-fetch-mock'; import noLogger from '../../test/fixtures/no-logger'; import SlackAddon from './slack';
test('Retries if fetch throws', async () => { const url = 'https://test.some.com'; jest.useFakeTimers('modern'); const addon = new SlackAddon({ getLogger: noLogger, unleashUrl: url, }); fetchMock.mockIf('https://test.some.com', 'OK', { status: 201, statusText: 'ACCEP...
beforeEach(() => { fetchMock.resetMocks(); });
random_line_split
redcube.webgpu.ts
/// <reference path='../index.d.ts'/> /// <reference types="@webgpu/types" /> import { Container } from './container'; import { Renderer } from './renderer'; import { Scene, Camera, Light, SkinnedMesh } from './objects/index'; import { Events } from './events'; import { Env } from './env.webgpu'; import { Parse } from...
(cb) { const ioc = new Container(); this.ioc = ioc; try { const WebGPU = await this.webgpuInit(); ioc.register('canvas', this.canvas); ioc.register('gl', WebGPU); ioc.register('scene', Scene); ioc.register('light', Light, [], { ...
init
identifier_name
redcube.webgpu.ts
/// <reference path='../index.d.ts'/> /// <reference types="@webgpu/types" /> import { Container } from './container'; import { Renderer } from './renderer'; import { Scene, Camera, Light, SkinnedMesh } from './objects/index'; import { Events } from './events'; import { Env } from './env.webgpu'; import { Parse } from...
mesh.pipeline = create(WebGPU.device, WebGPU.glslang, mesh.material.uniformBindGroup1, mesh.defines); mesh.uniformBindGroup1 = WebGPU.device.createBindGroup({ layout: mesh.pipeline.getBindGroupLayout(0), entries: [...mesh.geometry.uniformBindGrou...
{ for (const join of this.parse.skins[mesh.skin].jointNames) { walk(this.scene, this.buildBones.bind(this, join, this.parse.skins[mesh.skin])); } mesh.geometry.uniformBindGroup1.push(mesh.setSkinWebGPU(WebGPU, this.parse.skins[mesh.skin...
conditional_block
redcube.webgpu.ts
/// <reference path='../index.d.ts'/> /// <reference types="@webgpu/types" /> import { Container } from './container'; import { Renderer } from './renderer'; import { Scene, Camera, Light, SkinnedMesh } from './objects/index'; import { Events } from './events'; import { Env } from './env.webgpu'; import { Parse } from...
redraw(type, coordsStart, coordsMove) { if (type === 'zoom') { this.camera.zoom(coordsStart); this.renderer.needUpdateView = true; this.renderer.needUpdateProjection = true; } if (type === 'rotate') { this.camera.rotate(coordsStart, coordsMov...
{ this.camera.props.aspect = this.canvas.offsetWidth / this.canvas.offsetHeight; this.canvas.width = this.canvas.offsetWidth * devicePixelRatio; this.canvas.height = this.canvas.offsetHeight * devicePixelRatio; const z = this.camera.modelSize; if (this.camera.props.isInitial) {...
identifier_body
redcube.webgpu.ts
/// <reference path='../index.d.ts'/> /// <reference types="@webgpu/types" /> import { Container } from './container'; import { Renderer } from './renderer'; import { Scene, Camera, Light, SkinnedMesh } from './objects/index'; import { Events } from './events'; import { Env } from './env.webgpu'; import { Parse } from...
setVariant() { console.warn('Not implemented'); } draw() { console.warn('Not implemented'); } getState() { return { camera: this.camera, light: this.light, needUpdateView: this.renderer.needUpdateView, needUpdateProjection: t...
}
random_line_split
05_coffee_regions.js
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('coffee_regions').del() .then(function () { // Inserts seed entries return knex('coffee_regions').insert([ { id: 1, coffee_id: 1, region_id: 1, created_at: new Date('2...
created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') }, { id: 3, coffee_id: 3, region_id: 3, created_at: new Date('2017-06-23 14:56:16 UTC'), updated_at: new Date('2017-06-23 14:56:16 UTC') ...
random_line_split
autosubmit.js
var AutoSubmit = { setupAutoSubmit: function(field, button) { $(field).keypress(function(evt) { if (AutoSubmit.isEnter(evt)) { return false; } }); $(field).keydown(function(evt) {
return true; }); $(field).bind("focus", function() { $(button).addClass("autoselect"); }); $(field).bind("blur", function() { $(button).removeClass("autoselect"); }); }, isEnter: function(evt) { var key = 0; if (evt && evt.keyCode) { key = evt.keyCode; } else if (evt && evt.whic...
if (AutoSubmit.isEnter(evt)) { $(button).click(); return false; }
random_line_split
autosubmit.js
var AutoSubmit = { setupAutoSubmit: function(field, button) { $(field).keypress(function(evt) { if (AutoSubmit.isEnter(evt)) { return false; } }); $(field).keydown(function(evt) { if (AutoSubmit.isEnter(evt)) { $(button).click(); return false; } return true; }); $(fiel...
else if (evt && evt.which) { key = evt.which; } if (key == 13) { return true; } return false; } };
{ key = evt.keyCode; }
conditional_block
index.js
isStreams2 = isWritable(this._stream); // // We need to listen for drain events when // write() returns false. This can make node // mad at times. // this._stream.setMaxListeners(Infinity); } else { throw new Error('Cannot log to file without filename or stream.');
// // Internal state variables representing the number // of files this instance has created and the current // size (in bytes) of the current logfile. // this._size = 0; this._created = 0; this._buffer = []; this._draining = false; }; // // Inherit from `winston.Transport`. // util.inherits(...
} this.maxsize = options.maxsize || null; this.maxFiles = options.maxFiles || null;
random_line_split
index.js
isStreams2 = isWritable(this._stream); // // We need to listen for drain events when // write() returns false. This can make node // mad at times. // this._stream.setMaxListeners(Infinity); } else { throw new Error('Cannot log to file without filename or stream.'); } this.maxsize ...
function push(log) { if (options.rows && results.length >= options.rows) { if (stream.readable) { stream.destroy(); } return; } if (options.fields) { var obj = {}; options.fields.forEach(function (key) { obj[key] = log[key]; }); log = obj; }...
{ try { var log = JSON.parse(buff); if (check(log)) push(log); } catch (e) { if (!attempt) { stream.emit('error', e); } } }
identifier_body
index.js
aining = false; }; // // Inherit from `winston.Transport`. // util.inherits(WinstonSumoLogic, Transport); // // Expose the name of this Transport on the prototype // WinstonSumoLogic.prototype.name = 'winstonSumoLogic'; // // ### function log (level, msg, [meta], callback) // #### @level {string} Level at which to l...
createAndFlush
identifier_name
issue-8860.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} fn f(ref _s: S) {} struct T { i: int } impl Drop for T { fn drop(&mut self) { unsafe { DROP_T += 1; DROP += 1; } } } fn g(ref _t: T) {} fn main() { let s = S; f(s); unsafe { assert_eq!(1, DROP); assert_eq!(1, DROP_S); } let t = T {...
{ unsafe { DROP_S += 1; DROP += 1; } }
identifier_body
issue-8860.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} ret } struct S; impl Drop for S { fn drop(&mut self) { unsafe { DROP_S += 1; DROP += 1; } } } fn f(ref _s: S) {} struct T { i: int } impl Drop for T { fn drop(&mut self) { unsafe { DROP_T += 1; DROP += 1; } } } f...
let ret = green::start(argc, argv, green::basic::event_loop, main); unsafe { assert_eq!(2, DROP); assert_eq!(1, DROP_S); assert_eq!(1, DROP_T);
random_line_split
issue-8860.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self) { unsafe { DROP_T += 1; DROP += 1; } } } fn g(ref _t: T) {} fn main() { let s = S; f(s); unsafe { assert_eq!(1, DROP); assert_eq!(1, DROP_S); } let t = T { i: 1 }; g(t); unsafe { assert_eq!(1, DROP_T); } }
drop
identifier_name
__init__.py
from __future__ import absolute_import from .activation_maximization import visualize_activation_with_losses from .activation_maximization import visualize_activation from .saliency import visualize_saliency_with_losses from .saliency import visualize_saliency from .saliency import visualize_cam_with_losses from .sa...
return (array1 * alpha + array2 * (1. - alpha)).astype(array1.dtype)
raise ValueError('`array1` and `array2` must have the same shapes')
conditional_block
__init__.py
from __future__ import absolute_import from .activation_maximization import visualize_activation_with_losses from .activation_maximization import visualize_activation from .saliency import visualize_saliency_with_losses from .saliency import visualize_saliency from .saliency import visualize_cam_with_losses from .sa...
(layer): """Determines the number of filters within the given `layer`. Args: layer: The keras layer to use. Returns: Total number of filters within `layer`. For `keras.layers.Dense` layer, this is the total number of outputs. """ # Handle layers with no channels. if K.n...
get_num_filters
identifier_name
__init__.py
from __future__ import absolute_import from .activation_maximization import visualize_activation_with_losses from .activation_maximization import visualize_activation from .saliency import visualize_saliency_with_losses from .saliency import visualize_saliency from .saliency import visualize_cam_with_losses from .sa...
def overlay(array1, array2, alpha=0.5): """Overlays `array1` onto `array2` with `alpha` blending. Args: array1: The first numpy array. array2: The second numpy array. alpha: The alpha value of `array1` as overlayed onto `array2`. This value needs to be between [0, 1], wit...
"""Determines the number of filters within the given `layer`. Args: layer: The keras layer to use. Returns: Total number of filters within `layer`. For `keras.layers.Dense` layer, this is the total number of outputs. """ # Handle layers with no channels. if K.ndim(layer.out...
identifier_body
__init__.py
from __future__ import absolute_import from .activation_maximization import visualize_activation_with_losses from .activation_maximization import visualize_activation from .saliency import visualize_saliency_with_losses from .saliency import visualize_saliency from .saliency import visualize_cam_with_losses from .sa...
with 0 being `array2` only to 1 being `array1` only (Default value = 0.5). Returns: The `array1`, overlayed with `array2` using `alpha` blending. """ if alpha < 0. or alpha > 1.: raise ValueError("`alpha` needs to be between [0, 1]") if array1.shape != array2.shape: ...
Args: array1: The first numpy array. array2: The second numpy array. alpha: The alpha value of `array1` as overlayed onto `array2`. This value needs to be between [0, 1],
random_line_split
urls.py
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailsearch import urls as wagtailsearch_urls from wagtail.wagtaildocs import urls a...
from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import RedirectView urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ url(r'^favicon\.ico$', RedirectView.as_vi...
conditional_block
urls.py
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from wagtail.wagtailadmin import urls as wagtailadmin_urls from wagtail.wagtailsearch import urls as wagtailsearch_urls from wagtail.wagtaildocs import urls a...
url(r'', include(wagtail_urls)), ) if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import RedirectView urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ur...
# Wagtail's serving mechanism
random_line_split
virt_addr.rs
// SPDX-License-Identifier: Unlicense //! Type-checked virtual addresses. //! //! ```rust //! let a = 3; //! ``` use super::{Addr, AddrRange, PhysAddr, PhysAddrRange, PAGESIZE_BYTES}; use core::fmt::{Debug, Error, Formatter}; /// A local (if kernel range), or a cluster-wide (if low range) virtual address. #[derive(...
} /// Construct bottom of virtual address range. pub const fn null() -> Self { Self(0) } /// Create a virtual address from a physical address. /// /// UNSAFE: virtual address can only be derefed when identity mapping is in place /// before paging is enabled or if physical memor...
Self(sym as usize)
random_line_split
virt_addr.rs
// SPDX-License-Identifier: Unlicense //! Type-checked virtual addresses. //! //! ```rust //! let a = 3; //! ``` use super::{Addr, AddrRange, PhysAddr, PhysAddrRange, PAGESIZE_BYTES}; use core::fmt::{Debug, Error, Formatter}; /// A local (if kernel range), or a cluster-wide (if low range) virtual address. #[derive(...
fn length(&self) -> usize { self.length } } impl VirtAddrRange { /// Create a range from static refs. pub fn from_linker_symbols(sym_base: *const u8, sym_top: *const u8) -> Self { let base = VirtAddr::from_linker_symbol(sym_base); let top = VirtAddr::from_linker_symbol(sym_top...
{ self.base }
identifier_body
virt_addr.rs
// SPDX-License-Identifier: Unlicense //! Type-checked virtual addresses. //! //! ```rust //! let a = 3; //! ``` use super::{Addr, AddrRange, PhysAddr, PhysAddrRange, PAGESIZE_BYTES}; use core::fmt::{Debug, Error, Formatter}; /// A local (if kernel range), or a cluster-wide (if low range) virtual address. #[derive(...
(&self) -> usize { self.0 } } impl VirtAddr { /// Const for compile-time constant pub const fn fixed(addr: usize) -> Self { Self(addr) } /// Construct from a reference to a linker symbol. pub fn from_linker_symbol(sym: *const u8) -> Self { Self(sym as usize) } ...
get
identifier_name
controllers.py
# -*- coding: utf-8 -*- from os import path from gluon import current from gluon.html import * from s3 import s3_represent_facilities, s3_register_validation # ============================================================================= class index(): """ Custom Home Page """ def __call__(self): ...
else: s3.scripts.append("/%s/static/scripts/jquery.validate.min.js" % appname) if request.env.request_method == "POST": post_script = \ '''$('#register_form').removeClass('hide') $('#login_form').addClass('hide')''' else: ...
s3.scripts.append("/%s/static/scripts/jquery.validate.js" % appname)
conditional_block
controllers.py
# -*- coding: utf-8 -*- from os import path from gluon import current from gluon.html import * from s3 import s3_represent_facilities, s3_register_validation # ============================================================================= class index():
from gluon.http import HTTP raise HTTP("404", "Unable to open Custom View: %s" % view) title = settings.get_system_name() response.title = title # flag for the link change # (condition, warehouse_id) flag = (False, 0) # change o...
""" Custom Home Page """ def __call__(self): T = current.T auth = current.auth db = current.db s3db = current.s3db request = current.request appname = request.application response = current.response s3 = response.s3 settings = current.deploym...
identifier_body
controllers.py
# -*- coding: utf-8 -*- from os import path from gluon import current from gluon.html import * from s3 import s3_represent_facilities, s3_register_validation # ============================================================================= class index(): """ Custom Home Page """ def __call__(self): ...
$('#login-btn').click(function(){ $('#register_form').addClass('hide') $('#login_form').removeClass('hide') })''' % post_script s3.jquery_ready.append(register_script) # Provide a login box on front page request.args = ["login"] auth.messages.submit_button = T("Log...
%s $('#register-btn').click(function(){ $('#register_form').removeClass('hide') $('#login_form').addClass('hide') })
random_line_split
controllers.py
# -*- coding: utf-8 -*- from os import path from gluon import current from gluon.html import * from s3 import s3_represent_facilities, s3_register_validation # ============================================================================= class
(): """ Custom Home Page """ def __call__(self): T = current.T auth = current.auth db = current.db s3db = current.s3db request = current.request appname = request.application response = current.response s3 = response.s3 settings = current...
index
identifier_name
ReactTestRenderer.js
node: ReactTestInstance) => ?boolean; const defaultTestOptions = { createNodeMock: function() { return null; }, }; function toJSON(inst: Instance | TextInstance): ReactTestRendererNode | null { if (inst.isHidden) { // Omit timed out children from output entirely. This seems like the least // surpris...
// Throws if this component has been unmounted. const fiber = findCurrentFiberUsingSlowPath(this._fiber); invariant( fiber !== null, "Can't read from currently-mounting component. This error is likely " + 'caused by a bug in React. Please file an issue.', ); return fiber; } ...
random_line_split
ReactTestRenderer.js
: ReactTestInstance) => ?boolean; const defaultTestOptions = { createNodeMock: function() { return null; }, }; function toJSON(inst: Instance | TextInstance): ReactTestRendererNode | null { if (inst.isHidden) { // Omit timed out children from output entirely. This seems like the least // surprising ...
node = (node.return: any); } (node.sibling: any).return = node.return; node = (node.sibling: any); } return children; } class ReactTestInstance { _fiber: Fiber; _currentFiber(): Fiber { // Throws if this component has been unmounted. const fiber = findCurrentFiberUsingSlowPath(this....
{ break outer; }
identifier_body
ReactTestRenderer.js
case Fragment: case ContextProvider: case ContextConsumer: case Mode: case Profiler: case ForwardRef: case MemoComponent: case IncompleteClassComponent: case ScopeComponent: return childrenToTree(node.child); default: invariant( false, 'toTree() does not ...
{ // Normally, we skip the root and just give you the child. return children[0]; }
conditional_block
ReactTestRenderer.js
node: ReactTestInstance) => ?boolean; const defaultTestOptions = { createNodeMock: function() { return null; }, }; function toJSON(inst: Instance | TextInstance): ReactTestRendererNode | null { if (inst.isHidden) { // Omit timed out children from output entirely. This seems like the least // surpris...
(props: Object): ReactTestInstance { return expectOne( this.findAllByProps(props, {deep: false}), `with props: ${JSON.stringify(props)}`, ); } findAll( predicate: Predicate, options: ?FindOptions = null, ): Array<ReactTestInstance> { return findAll(this, predicate, options); } ...
findByProps
identifier_name
player.js
position: { type: String }, marketValue: { type: Number }, jerseyNumber: { type: Number }, dateOfBirth: { type: Date }, contractedUntil: { type: Date }, club_id: { type: Schema.Types.ObjectId, ref: 'Club' }, nation_name: { type: String, ref: 'Nation' }, attributes: { physical: { Acceleration: ...
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var schema = new Schema({ name: { type: String, required: true },
random_line_split
ErrorStatus.js
// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P. var React = require('react'); var ErrorStatus = React.createClass({ render: function() { var className = 'status-icon status-icon-error'; if (this.props.className) { className += ' ' + this.props.className; } return ( ...
); } }); module.exports = ErrorStatus;
random_line_split
ErrorStatus.js
// (C) Copyright 2014-2015 Hewlett-Packard Development Company, L.P. var React = require('react'); var ErrorStatus = React.createClass({ render: function() { var className = 'status-icon status-icon-error'; if (this.props.className)
return ( <svg className={className} viewBox="0 0 24 24" version="1.1"> <g className={"status-icon__base"} stroke="none"> <path d="M12,0 L24,12 L12,24 L0,12 Z"></path> </g> <g className={"status-icon__detail"} fill="none"> <path d="M8,8 L16,16" strokeWidth="2"></pat...
{ className += ' ' + this.props.className; }
conditional_block
window.js
/** * A debounce method that has a sliding window, there's a minimum and maximum wait time **/ module.exports = function (cb, min, max, settings) { var ctx, args, next, limit, timeout; if (!settings) { settings = {}; } function fire() { limit = null; cb.apply(settings.context || ctx, args); } function ...
fn.active = function () { return !!limit; }; return fn; };
random_line_split