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
seenShow.js
$( document ).ready(function() { "use strict"; firebase.auth().onAuthStateChanged(firebaseUser =>{ if (firebaseUser)
}); } }); });
{ var rootRef = firebase.database().ref().child("users").child(firebaseUser.uid).child("movies").child("seen"); rootRef.on("child_added", snap =>{ var movieId = snap.child("movieId").val(); var moviename = snap.child("moviename").val(); var poster = snap.child("poster").val(); var poster...
conditional_block
bootstrap-datepicker.th.js
/** * Thai translation for bootstrap-datepicker * Suchau Jiraprapot <seroz24@gmail.com> */ ;(function ($) {
$.fn.datepicker.dates['th'] = { days: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"], daysShort: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"], daysMin: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"], months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภ...
random_line_split
app.js
/* ----------------------------------------------- /* How to use? : Check the GitHub README /* ----------------------------------------------- */ /* To load a config file (particles.json) you need to host this demo (MAMP/WAMP/local)... */ /* particlesJS.load('particles-js', 'particles.json', function() { console.log...
"enable": true, "distance": 150, "color": "#777", "opacity": 0.4, "width": 1 }, "move": { "enable": true, "speed": 6, "direction": "none", "random": false, "straight": false, "out_mode": "out", "attract": { ...
"size_min": 0.1, "sync": false } }, "line_linked": {
random_line_split
pipeline-hetero-lr-normal.py
# # Copyright 2019 The FATE 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 appli...
"random_seed": None }, "cv_param": { "n_splits": 5, "shuffle": False, "random_seed": 103, "need_cv": False }, "callback_param": { "callbacks": ["ModelCheckpoint"], "save_freq": "epoch" } } ...
if isinstance(config, str): config = load_job_config(config) lr_param = { "name": "hetero_lr_0", "penalty": "L2", "optimizer": "rmsprop", "tol": 0.0001, "alpha": 0.01, "max_iter": 30, "early_stop": "diff", "batch_size": 320, "learning_...
identifier_body
pipeline-hetero-lr-normal.py
# # Copyright 2019 The FATE 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 appli...
(config="../../config.yaml", namespace=""): # obtain config if isinstance(config, str): config = load_job_config(config) lr_param = { "name": "hetero_lr_0", "penalty": "L2", "optimizer": "rmsprop", "tol": 0.0001, "alpha": 0.01, "max_iter": 30, ...
main
identifier_name
pipeline-hetero-lr-normal.py
# # Copyright 2019 The FATE 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 appli...
lr_param = { "name": "hetero_lr_0", "penalty": "L2", "optimizer": "rmsprop", "tol": 0.0001, "alpha": 0.01, "max_iter": 30, "early_stop": "diff", "batch_size": 320, "learning_rate": 0.15, "init_param": { "init_method": "zer...
config = load_job_config(config)
conditional_block
pipeline-hetero-lr-normal.py
# # Copyright 2019 The FATE 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
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License....
# # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
counter.rs
//! A wrapper which counts the number of records pushed past and updates a shared count map. use std::rc::Rc;
use std::cell::RefCell; use progress::CountMap; use dataflow::channels::Content; use Push; /// A wrapper which updates shared `counts` based on the number of records pushed. pub struct Counter<T, D, P: Push<(T, Content<D>)>> { pushee: P, counts: Rc<RefCell<CountMap<T>>>, phantom: ::std::marker::PhantomDat...
random_line_split
counter.rs
//! A wrapper which counts the number of records pushed past and updates a shared count map. use std::rc::Rc; use std::cell::RefCell; use progress::CountMap; use dataflow::channels::Content; use Push; /// A wrapper which updates shared `counts` based on the number of records pushed. pub struct Counter<T, D, P: Push<...
// only propagate `None` if dirty (indicates flush) if message.is_some() || self.counts.borrow().len() > 0 { self.pushee.push(message); } } } impl<T, D, P: Push<(T, Content<D>)>> Counter<T, D, P> where T : Eq+Clone+'static { /// Allocates a new `Counter` from a...
{ self.counts.borrow_mut().update(time, data.len() as i64); }
conditional_block
counter.rs
//! A wrapper which counts the number of records pushed past and updates a shared count map. use std::rc::Rc; use std::cell::RefCell; use progress::CountMap; use dataflow::channels::Content; use Push; /// A wrapper which updates shared `counts` based on the number of records pushed. pub struct Counter<T, D, P: Push<...
(pushee: P, counts: Rc<RefCell<CountMap<T>>>) -> Counter<T, D, P> { Counter { pushee: pushee, counts: counts, phantom: ::std::marker::PhantomData, } } /// Extracts shared counts into `updates`. /// /// It is unclear why this method exists at the same t...
new
identifier_name
counter.rs
//! A wrapper which counts the number of records pushed past and updates a shared count map. use std::rc::Rc; use std::cell::RefCell; use progress::CountMap; use dataflow::channels::Content; use Push; /// A wrapper which updates shared `counts` based on the number of records pushed. pub struct Counter<T, D, P: Push<...
}
{ while let Some((ref time, delta)) = self.counts.borrow_mut().pop() { updates.update(time, delta); } }
identifier_body
gr-change-status_test.ts
/** * @license * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0
* * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the Licen...
random_line_split
users.js
import resource from 'resource-router-middleware'; import model from '../models/users'; export default ({ config, db }) => resource({ /** Property name to store preloaded entity on `request`. */ id : 'user', mergeParams: true, /** For requests with an `id`, you can auto-load the entity. * Errors terminat...
({ facet }, res) { facets.splice(facets.indexOf(facet), 1); res.sendStatus(204); }, });
delete
identifier_name
users.js
import resource from 'resource-router-middleware'; import model from '../models/users'; export default ({ config, db }) => resource({ /** Property name to store preloaded entity on `request`. */ id : 'user', mergeParams: true, /** For requests with an `id`, you can auto-load the entity. * Errors terminat...
if(!params.query.sort) { params.query.sort = 'id'; } if(params.query.sort) { params.query.sort = params.query.sort; } for(var key in params.query) { if(!isNaN(parseFloat((params.query[key])))) { params.query[key] = parseInt(params.query[key]); } } if(param...
{ params.query.limit = config.pagination; }
conditional_block
users.js
import resource from 'resource-router-middleware'; import model from '../models/users'; export default ({ config, db }) => resource({ /** Property name to store preloaded entity on `request`. */ id : 'user', mergeParams: true, /** For requests with an `id`, you can auto-load the entity. * Errors terminat...
} } //we ensure we only search for proper active/inactive records let activeQuery = { 'active': urlQuery.active } queryArray.push(activeQuery); urlQuery = { $and: queryArray, }; } model.paginate( urlQuery ,params.query, function(err, result) {...
if( (searchable.indexOf(property) > -1) ) { let userSearch = new RegExp(parsed[property], 'i'); let tempObj = {}; tempObj[property] = userSearch; queryArray.push(tempObj);
random_line_split
users.js
import resource from 'resource-router-middleware'; import model from '../models/users'; export default ({ config, db }) => resource({ /** Property name to store preloaded entity on `request`. */ id : 'user', mergeParams: true, /** For requests with an `id`, you can auto-load the entity. * Errors terminat...
params.query.limit = config.pagination; } if(!params.query.sort) { params.query.sort = 'id'; } if(params.query.sort) { params.query.sort = params.query.sort; } for(var key in params.query) { if(!isNaN(parseFloat((params.query[key])))) { params.query[key] = parse...
{ let urlQuery = {}; let searchable = ['fullName', 'email', 'workPhone', 'personalPhone']; params.query.select = { '_id': 0, 'id': 1, 'fullName': 1, 'email': 1, 'workPhone': 1, 'personalPhone': 1 }; if(!params.query.active || params.query.active === 'false') { ...
identifier_body
environment.py
# -*- coding:utf-8 -*- # @version: 1.0 # @author: # @date: '14-4-10' import os import logging import threading from ConfigParser import ConfigParser from ConfigParser import NoSectionError, InterpolationMissingOptionError, Error import simplejson as json from utils.logger import Logger _lock = ...
ection(section) if type(value) == dict: value = json.dumps(value) self._configure_parser.set(section, key, value) with file(self._config_path, "w") as fp: self._configure_parser.write(fp) _lock.release() def _parse_start_file_name(self, start_file_nam...
figure_parser.add_s
identifier_name
environment.py
# -*- coding:utf-8 -*- # @version: 1.0 # @author: # @date: '14-4-10' import os import logging import threading from ConfigParser import ConfigParser from ConfigParser import NoSectionError, InterpolationMissingOptionError, Error import simplejson as json from utils.logger import Logger _lock = ...
def _get_configure_value(self, section, key): value = None try: value = self._configure_parser.get(section, key) return value except NoSectionError, e: logging.error(e.message) return None except InterpolationMissingOptionError,...
random_line_split
environment.py
# -*- coding:utf-8 -*- # @version: 1.0 # @author: # @date: '14-4-10' import os import logging import threading from ConfigParser import ConfigParser from ConfigParser import NoSectionError, InterpolationMissingOptionError, Error import simplejson as json from utils.logger import Logger _lock = ...
ry_crawler.py", 1)
identifier_body
environment.py
# -*- coding:utf-8 -*- # @version: 1.0 # @author: # @date: '14-4-10' import os import logging import threading from ConfigParser import ConfigParser from ConfigParser import NoSectionError, InterpolationMissingOptionError, Error import simplejson as json from utils.logger import Logger _lock = ...
print Environment.get_instance()._parse_start_file_name( "F:\\newgit\\nluData\\query-crawler\\crawler\\query_crawler.py", 1)
conditional_block
_pgsql.py
elif isinstance(conn, pgCursor): conn=conn.conn.conn adapter.prepare(conn) return adapter.getquoted() class SqlException(adm.ServerException): def __init__(self, sql, error): logger.querylog(sql, error=error) self.error=error self.sql=sql Exception.__init__(self, sql, error) def ...
conn=conn.conn
conditional_block
_pgsql.py
[i] if isinstance(val, str): return val.decode('utf8') return val def __getitem__(self, colName): try: if isinstance(colName, (str, unicode)): i=self.colNames.index(colName) else: i=colName return self.getItem(i) except Exception as _e: logger.debug("Colu...
def ServerVersion(self): if not self.connections: return None v=self.connections[0].conn.server_version
random_line_split
_pgsql.py
(adm.mainframe) if self.conn and self.conn.closed: self.disconnect() if self.trapSqlException: raise SqlException(cmd, errlines) else: raise exception def isRunning(self): return self.conn.poll() != psycopg2.extensions.POLL_OK def GetCursor(self): return pgCursor(self) #####...
if where: if val: where="%s=%s" % (quoteIdent(where), quoteValue(val)) self.where.append(where)
identifier_body
_pgsql.py
") self.cursor=self.conn.cursor() def disconnect(self): self.cursor=None if self.conn: self.conn.close() self.conn=None if self.pool: self.pool.RemoveConnection(self) def wait(self, spot=""): if self.conn.async: while self.conn.isexecuting(): try: ...
pgQuery
identifier_name
2.js
var fs = require('fs'); fs.readFile('input.txt', 'utf8', function(err, contents) { var lines = contents.split('\n'); var packageStrings = []; // ensure we don't get any empty lines (like a trailing newline) lines.forEach(function(line) { if (line.length)
; }); calculateWrappingPaper(packageStrings); }); var calculateWrappingPaper = function(packageStrings) { var packages = []; packageStrings.forEach(function(pkgString) { packages.push(parseDimensions(pkgString)); }); console.log('Square Feet of Wrapping Paper: ' + sumAreas(packages)); console.log(...
{ packageStrings.push(line) }
conditional_block
2.js
var fs = require('fs'); fs.readFile('input.txt', 'utf8', function(err, contents) { var lines = contents.split('\n'); var packageStrings = []; // ensure we don't get any empty lines (like a trailing newline) lines.forEach(function(line) { if (line.length) { packageStrings.push(line) }; }); calculateWr...
var sum = 0; packages.forEach(function(box) { sum += box.wrappingArea; }); return sum; }; // sum the required ribbonLength of all packages sumRibbonLength = function(packages) { var sum = 0; packages.forEach(function(box) { sum += box.ribbonLength; }); return sum; }
random_line_split
instructors_activity.py
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' ...
for_real=send_for_real, django_mailing=django_mailing) if self.verbosity >= 1: self.stdout.write('Sent {} emails.\n'.format(len(results)))
send_for_real = options['send_out_for_real'] # by default include only instructors who have `may_contact==True` no_may_contact_only = options['no_may_contact_only'] # use mailing options from settings.py or the `mail` system command? django_mailing = options['django_mailing'] ...
identifier_body
instructors_activity.py
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' ...
else: command = 'mail -s "{subject}" -r {sender} {recipient}'.format( subject=subject, sender=sender, recipient=recipient, ) writer = os.popen(command, 'w') writer.write(message) ...
send_mail(subject, message, sender, [recipient])
conditional_block
instructors_activity.py
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' ...
(self, tasks, person, roles): """List of other instructors' tasks, per event.""" return [ task.event.task_set.filter(role__in=roles) .exclude(person=person) .select_related('person') for task in tasks ] de...
foreign_tasks
identifier_name
instructors_activity.py
import os import logging from django.core.management.base import BaseCommand from django.core.mail import send_mail from django.template.loader import get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' ...
instructors = instructors.exclude(email__isnull=True) if may_contact_only: instructors = instructors.exclude(may_contact=False) # let's get some things faster instructors = instructors.select_related('airport') \ .prefetch_related('task_set',...
instructors = Person.objects.filter(badges__in=instructor_badges)
random_line_split
UrlTypeTest.ts
import UrlType from 'tinymce/themes/inlite/core/UrlType'; import { UnitTest, assert } from '@ephox/bedrock'; UnitTest.test('atomic.themes.core.UrlTypeTest', function () { const testIsDomainLike = function () { const mostUsedTopLevelDomains = [ 'com', 'org', 'edu', 'gov', 'uk', 'net', 'ca', 'de', 'jp', ...
const testIsAbsoluteUrl = function () { assert.eq(UrlType.isAbsolute('http://www.site.com'), true); assert.eq(UrlType.isAbsolute('https://www.site.com'), true); assert.eq(UrlType.isAbsolute('www.site.com'), false); assert.eq(UrlType.isAbsolute('file.gif'), false); }; testIsDomainLike(); testIs...
}); assert.eq(UrlType.isDomainLike('/a/b'), false); };
random_line_split
echo.rs
#[macro_use] extern crate log; #[macro_use] extern crate rux; extern crate num_cpus; extern crate env_logger; use rux::{RawFd, Reset}; use rux::buf::ByteBuffer; use rux::handler::*; use rux::mux::*; use rux::epoll::*; use rux::sys::socket::*; use rux::prop::server::*; use rux::daemon::*; const BUF_SIZE: usize = 2048;...
EPOLL_BUF_CAP, EPOLL_LOOP_MS, MAX_CONN); let config = ServerConfig::tcp(("127.0.0.1", 9999)) .unwrap() .max_conn(MAX_CONN) .io_threads(1) // .io_threads(::std::cmp::max(1, ::num_cpus::get() / 2)) .epoll_config(EpollConfig { loop_ms: EPOLL_LOOP_MS, buffer_capaci...
::env_logger::init().unwrap(); info!("BUF_SIZE: {}; EPOLL_BUF_CAP: {}; EPOLL_LOOP_MS: {}; MAX_CONN: {}", BUF_SIZE,
random_line_split
echo.rs
#[macro_use] extern crate log; #[macro_use] extern crate rux; extern crate num_cpus; extern crate env_logger; use rux::{RawFd, Reset}; use rux::buf::ByteBuffer; use rux::handler::*; use rux::mux::*; use rux::epoll::*; use rux::sys::socket::*; use rux::prop::server::*; use rux::daemon::*; const BUF_SIZE: usize = 2048;...
(&mut self, _: EpollFd) { } } impl Reset for EchoHandler { fn reset(&mut self) {} } #[derive(Clone, Debug)] struct EchoFactory; impl<'a> HandlerFactory<'a, EchoHandler, ByteBuffer> for EchoFactory { fn new_resource(&self) -> ByteBuffer { ByteBuffer::with_capacity(BUF_SIZE) } fn new_handler(&mut self...
with_epfd
identifier_name
echo.rs
#[macro_use] extern crate log; #[macro_use] extern crate rux; extern crate num_cpus; extern crate env_logger; use rux::{RawFd, Reset}; use rux::buf::ByteBuffer; use rux::handler::*; use rux::mux::*; use rux::epoll::*; use rux::sys::socket::*; use rux::prop::server::*; use rux::daemon::*; const BUF_SIZE: usize = 2048;...
MuxCmd::Keep } fn on_next(&mut self, event: MuxEvent<'a, ByteBuffer>) { let fd = event.fd; let events = event.events; let buffer = event.resource; if events.contains(EPOLLHUP) { trace!("socket's fd {}: EPOLLHUP", fd); self.closed = true; return; } if events.contai...
{ return MuxCmd::Close; }
conditional_block
echo.rs
#[macro_use] extern crate log; #[macro_use] extern crate rux; extern crate num_cpus; extern crate env_logger; use rux::{RawFd, Reset}; use rux::buf::ByteBuffer; use rux::handler::*; use rux::mux::*; use rux::epoll::*; use rux::sys::socket::*; use rux::prop::server::*; use rux::daemon::*; const BUF_SIZE: usize = 2048;...
fn with_epfd(&mut self, _: EpollFd) { } } impl Reset for EchoHandler { fn reset(&mut self) {} } #[derive(Clone, Debug)] struct EchoFactory; impl<'a> HandlerFactory<'a, EchoHandler, ByteBuffer> for EchoFactory { fn new_resource(&self) -> ByteBuffer { ByteBuffer::with_capacity(BUF_SIZE) } fn new_h...
{ EPOLLIN | EPOLLOUT | EPOLLET }
identifier_body
router-config-base-manager.ts
// Copyright (c) 2018 Göran Gustafsson. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. import extend from 'extend'; import { RouterUrlParams, RouterQueryParams, RouterStateData } from './router-types'; import { RouterConfig } from './router-ty...
} }
const configPathPart = configPathParts[n]; const configs = parentConfig.configs || {}; let currentConfig = configs[configPathPart]; if(!currentConfig) { currentConfig = { configs: {} }; configs[configPat...
conditional_block
router-config-base-manager.ts
// Copyright (c) 2018 Göran Gustafsson. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. import extend from 'extend'; import { RouterUrlParams, RouterQueryParams, RouterStateData } from './router-types'; import { RouterConfig } from './router-ty...
constructor() { this.root = { unrouted: true, configs: {} }; } protected internalAddConfig(configPathParts: string[], config: RouterConfig<UP, QP, SD, CX>): void { let parentConfig: RouterConfig<UP, QP, SD, CX> = this.root; for(let n = 0; n < configPa...
protected root: RouterConfig<UP, QP, SD, CX>;
random_line_split
router-config-base-manager.ts
// Copyright (c) 2018 Göran Gustafsson. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. import extend from 'extend'; import { RouterUrlParams, RouterQueryParams, RouterStateData } from './router-types'; import { RouterConfig } from './router-ty...
) { this.root = { unrouted: true, configs: {} }; } protected internalAddConfig(configPathParts: string[], config: RouterConfig<UP, QP, SD, CX>): void { let parentConfig: RouterConfig<UP, QP, SD, CX> = this.root; for(let n = 0; n < configPathParts.length; ...
onstructor(
identifier_name
router-config-base-manager.ts
// Copyright (c) 2018 Göran Gustafsson. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. import extend from 'extend'; import { RouterUrlParams, RouterQueryParams, RouterStateData } from './router-types'; import { RouterConfig } from './router-ty...
}
let parentConfig: RouterConfig<UP, QP, SD, CX> = this.root; for(let n = 0; n < configPathParts.length; n++) { const configPathPart = configPathParts[n]; const configs = parentConfig.configs || {}; let currentConfig = configs[configPathPart]; if(!currentCo...
identifier_body
batch.rs
//! # `batch` - batches of files to marshal. //! //! A `Batch` represents a collection of files which are being marshalled and a stream of hashed //! output objects. For a single `Batch`, there should correspond a set of valid marshalled files //! and a stream of valid hashed objects produced from marshalling/hashing t...
pub fn marshal_subtree<P: AsRef<Path>>( &mut self, path: P, ) -> Box<Future<Item = ObjectHash, Error = Error> + Send> { let result = self.load_subtree(path) .map(|tree| { let tree_total = tree.total(); self.len += tree_total; ...
{ let tree = DataTree::load(chunked.to_vec().into_iter().map(SmallRecord::from)); let tree_total = tree.total(); self.len += tree_total; let marshal = tree.marshal(Hasher::with_trace( self.marshal_tx.clone(), self.trace.on_marshal(tree_total), )); ...
identifier_body
batch.rs
//! # `batch` - batches of files to marshal. //! //! A `Batch` represents a collection of files which are being marshalled and a stream of hashed //! output objects. For a single `Batch`, there should correspond a set of valid marshalled files //! and a stream of valid hashed objects produced from marshalling/hashing t...
} Ok(dir_tree) } /// Marshal a chunked file into a tree of objects, returning the marshalled objects along with /// the hash of the root object. pub fn marshal_file( &mut self, chunked: Chunked, ) -> Box<Future<Item = ObjectHash, Error = Error> + Send> { le...
{ dir_tree.insert(entry_path, self.load_file(&path)?); }
conditional_block
batch.rs
//! # `batch` - batches of files to marshal. //! //! A `Batch` represents a collection of files which are being marshalled and a stream of hashed //! output objects. For a single `Batch`, there should correspond a set of valid marshalled files //! and a stream of valid hashed objects produced from marshalling/hashing t...
let entry_path = path.strip_prefix(path_ref).unwrap(); if path.is_dir() { dir_tree.insert(entry_path, self.load_subtree(&path)?); } else { dir_tree.insert(entry_path, self.load_file(&path)?); } } Ok(dir_tree) } //...
let path = entry.path();
random_line_split
batch.rs
//! # `batch` - batches of files to marshal. //! //! A `Batch` represents a collection of files which are being marshalled and a stream of hashed //! output objects. For a single `Batch`, there should correspond a set of valid marshalled files //! and a stream of valid hashed objects produced from marshalling/hashing t...
<P: AsRef<Path>>(&mut self, path: P) -> Result<Chunked> { let slice = self.read_path(path)?; let mut trace = self.trace.on_split(slice.len() as u64); let chunked = split::chunk_with_trace(slice, &mut trace); Ok(chunked) } pub fn load_file<P: AsRef<Path>>(&mut self, path: P) -> ...
chunk_file
identifier_name
config.py
# Copyright (c) 2013 OpenStack Foundation # 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 ...
help=_("List of networking mechanism driver entrypoints to " "be loaded from the neutron.ml2.mechanism_drivers " "namespace.")), ] cfg.CONF.register_opts(ml2_opts, "ml2") cfg.CONF.register_opts(scheduler.AGENTS_SCHEDULER_OPTS)
help=_("Ordered list of network_types to allocate as tenant " "networks.")), cfg.ListOpt('mechanism_drivers', default=[],
random_line_split
hero.ts
export class Hero { public id:number constructor( public firstName:string, public lastName?:string, public birthdate?:Date, public url?:string, public rate:number = 100, id?:number) { this.id = id != null ? id : Hero.nextId++; } static clone({firstName, lastName, birthdate, url...
static MockHeroes = [ new Hero( 'Hercules', 'Son of Zeus', new Date(1970, 1, 25), 'http://www.imdb.com/title/tt0065832/', 325), new Hero('eenie', 'toe'), new Hero('Meanie', 'Toe'), new Hero('Miny', 'Toe'), new Hero('Moe', 'Toe') ]; }
static nextId = 1;
random_line_split
hero.ts
export class
{ public id:number constructor( public firstName:string, public lastName?:string, public birthdate?:Date, public url?:string, public rate:number = 100, id?:number) { this.id = id != null ? id : Hero.nextId++; } static clone({firstName, lastName, birthdate, url, rate, id} : Her...
Hero
identifier_name
hero.ts
export class Hero { public id:number constructor( public firstName:string, public lastName?:string, public birthdate?:Date, public url?:string, public rate:number = 100, id?:number) { this.id = id != null ? id : Hero.nextId++; } static clone({firstName, lastName, birthdate, url...
static nextId = 1; static MockHeroes = [ new Hero( 'Hercules', 'Son of Zeus', new Date(1970, 1, 25), 'http://www.imdb.com/title/tt0065832/', 325), new Hero('eenie', 'toe'), new Hero('Meanie', 'Toe'), new Hero('Miny', 'Toe'), new Hero('Moe', 'Toe') ]; }
{return `${this.firstName} ${this.lastName}`;}
identifier_body
label.py
# coding=utf-8 from __future__ import unicode_literals, print_function from datetime import datetime from celery import group from urlobject import URLObject from webhookdb import db, celery from webhookdb.process import process_label from webhookdb.models import IssueLabel, Repository, Mutex from webhookdb.exceptions...
) except IntegrityError as exc: # multiple workers tried to insert the same label simulataneously. Retry! self.retry(exc=exc) return label.name @celery.task(bind=True) def sync_page_of_labels(self, owner, repo, children=False, requestor_id=None, per_page=100, p...
label_url = "/repos/{owner}/{repo}/labels/{name}".format( owner=owner, repo=repo, name=name, ) try: resp = fetch_url_from_github(label_url, requestor_id=requestor_id) except NotFound: # add more context msg = "Label {name} on {owner}/{repo} not found".format( name...
identifier_body
label.py
# coding=utf-8 from __future__ import unicode_literals, print_function from datetime import datetime from celery import group from urlobject import URLObject from webhookdb import db, celery from webhookdb.process import process_label from webhookdb.models import IssueLabel, Repository, Mutex from webhookdb.exceptions...
label_page_url = ( "/repos/{owner}/{repo}/labels?" "per_page={per_page}&page={page}" ).format( owner=owner, repo=repo, per_page=per_page, page=page ) resp = fetch_url_from_github(label_page_url, requestor_id=requestor_id) fetched_at = datetime.now() label_data_lis...
per_page=100, page=1):
random_line_split
label.py
# coding=utf-8 from __future__ import unicode_literals, print_function from datetime import datetime from celery import group from urlobject import URLObject from webhookdb import db, celery from webhookdb.process import process_label from webhookdb.models import IssueLabel, Repository, Mutex from webhookdb.exceptions...
(self, owner, repo, children=False, requestor_id=None, per_page=100, page=1): label_page_url = ( "/repos/{owner}/{repo}/labels?" "per_page={per_page}&page={page}" ).format( owner=owner, repo=repo, per_page=per_page, page=page ) resp = fetch_url_fro...
sync_page_of_labels
identifier_name
label.py
# coding=utf-8 from __future__ import unicode_literals, print_function from datetime import datetime from celery import group from urlobject import URLObject from webhookdb import db, celery from webhookdb.process import process_label from webhookdb.models import IssueLabel, Repository, Mutex from webhookdb.exceptions...
# delete the mutex lock_name = LOCK_TEMPLATE.format(owner=owner, repo=repo_name) Mutex.query.filter_by(name=lock_name).delete() logger.info("Lock {name} deleted".format(name=lock_name)) db.session.commit() @celery.task() def spawn_page_tasks_for_labels(owner, repo, children=False, ...
query = ( Label.query.filter_by(repo_id=repo.id) .filter(Label.last_replicated_at < prev_scan_at) ) query.delete()
conditional_block
jquery.datepick-ur.js
/* http://keith-wood.name/datepick.html Urdu localisation for jQuery Datepicker. Mansoor Munib -- mansoormunib@gmail.com <http://www.mansoor.co.nr/mansoor.html> Thanks to Habib Ahmed, ObaidUllah Anwar. */ (function($) { $.datepick.regionalOptions.ur = { monthNames: ['جنوری','فروری','مارچ','اپریل','مئی','جو...
})(jQuery);
}; $.datepick.setDefaults($.datepick.regionalOptions.ur);
random_line_split
views.py
import json import logging import pytz import datetime import dateutil.parser from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import redirect from django.conf import settings from mitxmako.shortcuts import render_to_response from django_future.csrf ...
(event): """Write tracking event to log file, and optionally to TrackingLog model.""" event_str = json.dumps(event) log.info(event_str[:settings.TRACK_MAX_EVENT]) if settings.MITX_FEATURES.get('ENABLE_SQL_TRACKING_LOGS'): event['time'] = dateutil.parser.parse(event['time']) tldat = Track...
log_event
identifier_name
views.py
import json import logging import pytz import datetime import dateutil.parser from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import redirect from django.conf import settings from mitxmako.shortcuts import render_to_response from django_future.csrf ...
"agent": agent, "page": request.REQUEST['page'], "time": datetime.datetime.now(UTC).isoformat(), "host": request.META['SERVER_NAME'], } log_event(event) return HttpResponse('success') def server_track(request, event_type, event, page=None): """Log events related to ser...
"event_source": "browser", "event_type": request.REQUEST['event_type'], "event": request.REQUEST['event'],
random_line_split
views.py
import json import logging import pytz import datetime import dateutil.parser from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import redirect from django.conf import settings from mitxmako.shortcuts import render_to_response from django_future.csrf ...
def user_track(request): """ Log when POST call to "event" URL is made by a user. Uses request.REQUEST to allow for GET calls. GET or POST call should provide "event_type", "event", and "page" arguments. """ try: # TODO: Do the same for many of the optional META parameters username ...
event['time'] = dateutil.parser.parse(event['time']) tldat = TrackingLog(**dict((x, event[x]) for x in LOGFIELDS)) try: tldat.save() except Exception as err: log.exception(err)
conditional_block
views.py
import json import logging import pytz import datetime import dateutil.parser from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import redirect from django.conf import settings from mitxmako.shortcuts import render_to_response from django_future.csrf ...
agent = '' event = { "username": username, "session": scookie, "ip": request.META['REMOTE_ADDR'], "event_source": "browser", "event_type": request.REQUEST['event_type'], "event": request.REQUEST['event'], "agent": agent, "page": request.REQUES...
""" Log when POST call to "event" URL is made by a user. Uses request.REQUEST to allow for GET calls. GET or POST call should provide "event_type", "event", and "page" arguments. """ try: # TODO: Do the same for many of the optional META parameters username = request.user.username exce...
identifier_body
upload_training_data.py
import json import os import glob import sys import logging from watson_developer_cloud import WatsonException if '__file__' in globals(): sys.path.insert(0, os.path.join(os.path.abspath(__file__), 'scripts')) else: sys.path.insert(0, os.path.join(os.path.abspath(os.getcwd()), 'scripts')) from discovery_setup...
# set the TRAINING_PATH to the location of the training data relative # to the 'data' directory # by default, evaluates to <DATA_TYPE>/training TRAINING_PATH = os.path.join(DATA_TYPE, 'training') DATA_DIRECTORY = os.path.abspath(os.path.join(curdir, '..', 'data')) TRAINING_DIRECTORY = os.path.join(DATA_DIRECTORY, TRA...
# set the DATA_TYPE the same to what was downloaded DATA_TYPE = 'travel'
random_line_split
upload_training_data.py
import json import os import glob import sys import logging from watson_developer_cloud import WatsonException if '__file__' in globals(): sys.path.insert(0, os.path.join(os.path.abspath(__file__), 'scripts')) else: sys.path.insert(0, os.path.join(os.path.abspath(os.getcwd()), 'scripts')) from discovery_setup...
(training_directory): print("Training directory: %s" % training_directory) files = glob.glob(os.path.join(training_directory, '*.json')) total_files = len(files) print("Number of files to process: %d" % total_files) training_data_uploaded = 0 done_percent = 0 write_progress(training_data_u...
upload_training_data
identifier_name
upload_training_data.py
import json import os import glob import sys import logging from watson_developer_cloud import WatsonException if '__file__' in globals(): sys.path.insert(0, os.path.join(os.path.abspath(__file__), 'scripts')) else:
from discovery_setup_utils import ( # noqa discovery, curdir, get_constants, write_progress ) # set the DATA_TYPE the same to what was downloaded DATA_TYPE = 'travel' # set the TRAINING_PATH to the location of the training data relative # to the 'data' directory # by default, evaluates to <DATA_TYPE>/traini...
sys.path.insert(0, os.path.join(os.path.abspath(os.getcwd()), 'scripts'))
conditional_block
upload_training_data.py
import json import os import glob import sys import logging from watson_developer_cloud import WatsonException if '__file__' in globals(): sys.path.insert(0, os.path.join(os.path.abspath(__file__), 'scripts')) else: sys.path.insert(0, os.path.join(os.path.abspath(os.getcwd()), 'scripts')) from discovery_setup...
done_percent) logging.info("Finished uploading %d files", total_files) print("\nFinished uploading %d files" % total_files) print('Retrieving environment and collection constants...') """ retrieve the following: { environment_id: env_id, collection_id: { tra...
print("Training directory: %s" % training_directory) files = glob.glob(os.path.join(training_directory, '*.json')) total_files = len(files) print("Number of files to process: %d" % total_files) training_data_uploaded = 0 done_percent = 0 write_progress(training_data_uploaded, total_files) ...
identifier_body
test_compute_code.py
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import unittest from bs4 import BeautifulSoup from compute.code import CodeExtractor logging.basicConfig(level=logging.INFO, format="%(message)s") class ExtractCodeTest(unittest.TestCase): def setUp(self): ...
def test_skip_whitespace_only(self): document = self._make_document_with_body("<code>\t \n</code>") snippets = self.code_extractor.extract(document) self.assertEqual(len(snippets), 0) # In practice I don't expect the next two scenarios to come up. But the expected behavior of # t...
document = self._make_document_with_body("<code>npm install package</code>") snippets = self.code_extractor.extract(document) self.assertEqual(len(snippets), 0)
identifier_body
test_compute_code.py
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import unittest from bs4 import BeautifulSoup from compute.code import CodeExtractor logging.basicConfig(level=logging.INFO, format="%(message)s") class ExtractCodeTest(unittest.TestCase): def setUp(self): ...
])) def test_extract_multiple_blocks(self): document = self._make_document_with_body('\n'.join([ "<code>var i = 0;</code>", "<code>i = i + 1;</code>", ])) snippets = self.code_extractor.extract(document) self.assertEqual(len(snippets), 2) self...
random_line_split
test_compute_code.py
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import logging import unittest from bs4 import BeautifulSoup from compute.code import CodeExtractor logging.basicConfig(level=logging.INFO, format="%(message)s") class ExtractCodeTest(unittest.TestCase): def setUp(self): ...
(self): # In the past, some parsers I have used have had trouble parsing with whitespace # surrounding the parsed content. This is a sanity test to make sure that the # backend parser will still detect JavaScript padded with whitespace. document = self._make_document_with_body("<code>\n...
test_extract_valid_javascript_with_padding
identifier_name
minimatch.js
// normalizes slashes. var slashSplit = /\/+/ minimatch.filter = filter function filter (pattern, options) { options = options || {} return function (p, i, list) { return minimatch(p, pattern, options) } } function ext (a, b) { a = a || {} b = b || {} var t = {} Object.keys(b).for...
{ return s.split('').reduce(function (set, c) { set[c] = true return set }, {}) }
identifier_body
minimatch.js
return false } // "" only matches "" if (pattern.trim() === '') return p === '' return new Minimatch(pattern, options).match(p) } function Minimatch (pattern, options) { if (!(this instanceof Minimatch)) { return new Minimatch(pattern, options) } if (typeof pattern !== 'string') ...
if (!options) options = {} // shortcut: comments match nothing. if (!options.nocomment && pattern.charAt(0) === '#') {
random_line_split
minimatch.js
') // must match entire pattern // ending in a * or ** will make it less strict. re = '^(?:' + re + ')$' // can match anything, as long as it's not this. if (this.negate) re = '^(?!' + re + ').*$' try { this.regexp = new RegExp(re, flags) } catch (ex) { this.regexp = false } r...
regExpEscape
identifier_name
tracked_services.py
policies.save() if self.id in storage.policies: del storage.policies[self.id] if config.get("general", "firewall") and fw: security.regenerate_firewall(get()) @property def as_dict(self): """Return policy metadata as dict.""" return { ...
try: upnpc.deleteportmapping(port[1], port[0].upper()) except: pass
conditional_block
tracked_services.py
policies.append( "custom", {"id": self.id, "name": self.name, "icon": self.icon, "ports": self.ports, "policy": self.policy} ) else: policies.set(self.type, self.id, self.policy) policies.save() storage.policies...
(): logger.debug("TrSv", "Attempting to connect to uPnP IGD") upnpc = miniupnpc.UPnP() upnpc.discoverdelay = 3000 devs = upnpc.discover() if devs == 0: msg = "Failed to connect to uPnP IGD: no devices found" logger.warning("TrSv", msg) return try: upnpc.selectigd(...
_upnp_igd_connect
identifier_name
tracked_services.py
policies.append( "custom", {"id": self.id, "name": self.name, "icon": self.icon, "ports": self.ports, "policy": self.policy} ) else: policies.set(self.type, self.id, self.policy) policies.save() storage.policies...
def initialize_upnp(svcs): """ Initialize uPnP port forwarding with the IGD. :param SecurityPolicy svcs: SecurityPolicies to open """ upnpc = _upnp_igd_connect() if not upnpc: return for svc in svcs: if svc.policy != 2: continue for protocol, port in s...
""" Remove forwarding of a port with the local uPnP IGD. :param tuple port: Port protocol and number """ upnpc = _upnp_igd_connect() if not upnpc: return if upnpc.getspecificportmapping(port[1], port[0].upper()): try: upnpc.deleteportmapping(port[1], port[0].upper())...
identifier_body
tracked_services.py
policies.append( "custom", {"id": self.id, "name": self.name, "icon": self.icon, "ports": self.ports, "policy": self.policy} ) else: policies.set(self.type, self.id, self.policy) policies.save() storage.policies...
:param str id: Website or app ID :param bool fw: Regenerate the firewall after save? """ for x in get(type=type): if not id: x.remove(fw=False) elif x.id == id: x.remove(fw=False) break if config.get("general", "firewall") and fw: security....
""" Deregister a security policy. :param str type: Policy type ('website', 'app', etc)
random_line_split
runner.py
# # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
(self): return self._result def getErrors(self): return self._error def getReturnCode(self): return self._process.returncode def stop(self): return utils.killProcess(self._process) def createScript(self, module, cls, method, args): command_template = "import {...
getResults
identifier_name
runner.py
# # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
def getErrors(self): return self._error def getReturnCode(self): return self._process.returncode def stop(self): return utils.killProcess(self._process) def createScript(self, module, cls, method, args): command_template = "import {m}; {m}.{c}().{method}{args}" ...
return self._result
identifier_body
runner.py
# # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
super(PythonMethodRunner, self).__init__(group=None) logger = logging.getLogger() self._log_adapter = utils.RequestAdapter( logger, {'method': 'PythonMethodRunner', 'request_id': request_id}) self._path = path self._result = None se...
class PythonMethodRunner(Thread): def __init__(self, path, module, cls, method, args, request_id=''):
random_line_split
runner.py
# # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
if error: self._error = error except Exception as ex: self._error = ex if self._error: self._log_adapter.error("script %s got error %s" % (self._script, self._error)) def getResults(self): return self....
self._error = "Unable to parse result: %s" \ " got error : %s " % (result, ex)
conditional_block
captcha.py
3 of the License, #or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #See the GNU General Public License for more details. # #You should have rece...
if pixels[x + 1, y] != 255: count += 1 if pixels[x + 1, y-1] != 255: count += 1 if pixels[x, y-1] != 255: count += 1 except: pass # not enough...
count += 1
conditional_block
captcha.py
of the License, #or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #See the GNU General Public License for more details. # #You should have recei...
def run(self, command): """Run a command""" popen = subprocess.Popen(command, bufsize = -1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) popen.wait() output = popen.stdout.read() +" | "+ popen.stderr.read() popen.stdout.close() popen.stderr.close() self....
self.image = self.image.point(lambda a: a * value + 10)
identifier_body
captcha.py
of the License, #or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #See the GNU General Public License for more details. # #You should have recei...
(self, image): self.image = Image.open(image) self.pixels = self.image.load() self.result_captcha = '' def unload(self): """delete all tmp images""" pass def threshold(self, value): self.image = self.image.point(lambda a: a * value + 10) def run(self, comma...
load_image
identifier_name
captcha.py
3 of the License, #or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #See the GNU General Public License for more details. # #You should have rece...
bottomY = y if y < topY: topY = y if x > lastX: lastX = x black_pixel_in_col = True if black_pixel_in_col is False and started is True: rect = (firstX, topY, ...
random_line_split
iss118-spec.js
/** @babel */ /* eslint-env jasmine, atomtest */ /* This file contains verifying specs for: https://github.com/sindresorhus/atom-editorconfig/issues/118 */ import fs from 'fs'; import path from 'path'; const testPrefix = path.basename(__filename).split('-').shift(); const projectRoot = path.join(__dirname, 'fixt...
const textWithManyTrailingWhitespaces = 'I \t \nam \t \nProvidence.'; beforeEach(() => { waitsForPromise(() => Promise.all([ atom.packages.activatePackage('editorconfig'), atom.workspace.open(filePath) ]).then(results => { textEditor = results[1]; }) ); }); afterEach(() => { // remo...
const textWithoutTrailingWhitespaces = 'I\nam\nProvidence.';
random_line_split
iss118-spec.js
/** @babel */ /* eslint-env jasmine, atomtest */ /* This file contains verifying specs for: https://github.com/sindresorhus/atom-editorconfig/issues/118 */ import fs from 'fs'; import path from 'path'; const testPrefix = path.basename(__filename).split('-').shift(); const projectRoot = path.join(__dirname, 'fixt...
}); }); waitsFor(() => { try { return fs.statSync(filePath).isFile() === false; } catch (err) { return true; } }, 5000, `removed ${filePath}`); }); describe('Atom being set to remove trailing whitespaces', () => { beforeEach(() => { // eslint-disable-next-line camelcase textEditor...
{ fs.unlink(filePath); }
conditional_block
htmldivelement.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::codegen::Bindings::HTMLDivElementBinding::{self, HTMLDivElementMethods}; use dom::bindings::js:...
}
random_line_split
htmldivelement.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::codegen::Bindings::HTMLDivElementBinding::{self, HTMLDivElementMethods}; use dom::bindings::js:...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDivElement> { Node::reflect_node(box HTMLDivElement::new_inherited(local_name, prefix, document), document, HTMLDivElementBinding::Wrap) } }...
new
identifier_name
config.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. //! Storage configuration. use crate::server::ttl::TTLCheckerTask; use crate::server::CONFIG_ROCKSDB_GAUGE; use configuration::{ConfigChange, ConfigManager, ConfigValue, Configuration, Result as CfgResult}; use engine_rocks::raw::{Cache, LRUCacheOptio...
}, "" => {} other => { warn!( "Memory allocator {} is not supported, continue with default allocator", other ); } } }; None } }
{ warn!( "Create jemalloc nodump allocator for block cache failed: {}, continue with default allocator", e ); }
conditional_block
config.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. //! Storage configuration. use crate::server::ttl::TTLCheckerTask; use crate::server::CONFIG_ROCKSDB_GAUGE; use configuration::{ConfigChange, ConfigManager, ConfigValue, Configuration, Result as CfgResult}; use engine_rocks::raw::{Cache, LRUCacheOptio...
"TiKV has optimized latch since v4.0, so it is not necessary to set large schedule \ concurrency. To save memory, change it from {:?} to {:?}", self.scheduler_concurrency, MAX_SCHED_CONCURRENCY ); self.scheduler_concurrency = MAX_SCHED_CONCURRENCY;...
if self.data_dir != DEFAULT_DATA_DIR { self.data_dir = config::canonicalize_path(&self.data_dir)? } if self.scheduler_concurrency > MAX_SCHED_CONCURRENCY { warn!(
random_line_split
config.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. //! Storage configuration. use crate::server::ttl::TTLCheckerTask; use crate::server::CONFIG_ROCKSDB_GAUGE; use configuration::{ConfigChange, ConfigManager, ConfigValue, Configuration, Result as CfgResult}; use engine_rocks::raw::{Cache, LRUCacheOptio...
() -> Config { let cpu_num = SysQuota::new().cpu_cores_quota(); Config { data_dir: DEFAULT_DATA_DIR.to_owned(), gc_ratio_threshold: DEFAULT_GC_RATIO_THRESHOLD, max_key_size: DEFAULT_MAX_KEY_SIZE, scheduler_concurrency: DEFAULT_SCHED_CONCURRENCY, ...
default
identifier_name
shared.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 */ import {Parser as ExpressionParser} from '../expression_parser/parser'; import {StringWrapper, isBlank, isPresent} f...
(ast: HtmlExpansionCaseAst, context: any): any { return null; } private _join(strs: string[], str: string): string { return strs.filter(s => s.length > 0).join(str); } }
visitExpansionCase
identifier_name
shared.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 */ import {Parser as ExpressionParser} from '../expression_parser/parser'; import {StringWrapper, isBlank, isPresent} f...
} return null; } export function meaning(i18n: string): string { if (isBlank(i18n) || i18n == '') return null; return i18n.split('|')[0]; } export function description(i18n: string): string { if (isBlank(i18n) || i18n == '') return null; let parts = i18n.split('|', 2); return parts.length > 1 ? parts[1...
{ return attrs[i]; }
conditional_block
shared.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 */ import {Parser as ExpressionParser} from '../expression_parser/parser'; import {StringWrapper, isBlank, isPresent} f...
visitExpansion(ast: HtmlExpansionAst, context: any): any { return null; } visitExpansionCase(ast: HtmlExpansionCaseAst, context: any): any { return null; } private _join(strs: string[], str: string): string { return strs.filter(s => s.length > 0).join(str); } }
{ return ''; }
identifier_body
shared.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 */ import {Parser as ExpressionParser} from '../expression_parser/parser'; import {StringWrapper, isBlank, isPresent} f...
usedNames.set(name, 1); return name; } /** * Convert a list of nodes to a string message. * */ export function stringifyNodes( nodes: HtmlAst[], expressionParser: ExpressionParser, interpolationConfig: InterpolationConfig): string { const visitor = new _StringifyVisitor(expressionParser, interpolation...
random_line_split
main.rs
_string(), charnum.to_string(), m.filepath.to_str().unwrap(), m.mtype, m.contextstr), } } else { error!("Could not resolve file coords for match {:?}", m); } } #[cfg(not(test))] fn co...
Config {fqn: m.value_of("fqn").map(ToOwned::to_owned), ..Default::default() } } } #[cfg(not(test))] fn build_cli<'a, 'b, 'c, 'd, 'e, 'f>() -> App<'a, 'b, 'c
{ let cfg = Config { charnum: value_t_or_exit!(m.value_of("charnum"), usize), fn_name: m.value_of("path").map(PathBuf::from), substitute_file: m.value_of("substitute_file").map(PathBuf::from), ..Default::default() }; ...
conditional_block
main.rs
.to_string(), charnum.to_string(), m.filepath.to_str().unwrap(), m.mtype, m.contextstr), } } else { error!("Could not resolve file coords for match {:?}", m); } } #[cfg(not(test))] fn...
(cfg: &Config, print_type: CompletePrinter) { let fn_path = &*cfg.fn_name.as_ref().unwrap(); let substitute_file = cfg.substitute_file.as_ref().unwrap_or(fn_path); let cache = core::FileCache::new(); let session = core::Session::from_path(&cache, fn_path, substitute_file); let src = session.load_fi...
run_the_complete_fn
identifier_name
main.rs
of a rust checkout - e.g. \"/home/foouser/src/rust/src\".", srcpaths); std::process::exit(1); } else if !path_exists(f.join("libstd")) { println!("Unable to find libstd under RUST_SRC_PATH. N.B. RUST_SRC_PATH variable needs to point to the *src* directory inside a rust check...
{ // make sure we get a stack trace ifwe panic ::std::env::set_var("RUST_BACKTRACE","1"); env_logger::init().unwrap(); check_rust_src_env_var(); let matches = build_cli().get_matches(); let interface = match matches.value_of("interface") { Some("text") => Interface::Text, ...
identifier_body
main.rs
.to_string(), charnum.to_string(), m.filepath.to_str().unwrap(), m.mtype, m.contextstr), } } else { error!("Could not resolve file coords for match {:?}", m); } } #[cfg(not(test))] fn...
} #[cfg(not(test))] impl Default for Interface { fn default() -> Self { Interface::Text } } #[cfg(not(test))] #[derive(Default)] struct Config { fqn: Option<String>, linenum: usize, charnum: usize, fn_name: Option<PathBuf>, substitute_file: Option<PathBuf>, interface: Interface, } #[cfg(n...
random_line_split
mod.rs
//! Provides dedicated `system` pipelines inside OrbTk. //! //! System pipelines are modules, that handle specific tasks when //! iteratively walking the widget tree. Because each widget //! implements the `state` trait, all system modules are accessible. //! Pipelines are connected in a logical order. E.g. the `InitSy...
mod init_system; mod layout_system; mod post_layout_state_system; mod render_system;
mod cleanup_system; mod event_state_system;
random_line_split
session.rs
//! This exposes `Session`, the struct stored in the `Alloy`. use std::sync::Arc; use super::SessionStore; /// A session which provides basic CRUD operations.
key: K, store: Arc<Box<SessionStore<K, V> + 'static + Send + Sync>> } impl<K, V> Session<K, V> { /// Create a new session pub fn new(key: K, store: Box<SessionStore<K, V> + 'static + Send + Sync>) -> Session<K, V> { Session { key: key, store: Arc::new(store) } ...
pub struct Session<K, V> {
random_line_split
session.rs
//! This exposes `Session`, the struct stored in the `Alloy`. use std::sync::Arc; use super::SessionStore; /// A session which provides basic CRUD operations. pub struct Session<K, V> { key: K, store: Arc<Box<SessionStore<K, V> + 'static + Send + Sync>> } impl<K, V> Session<K, V> { /// Create a new sessi...
(&self, value: V) -> Option<V> { self.store.swap(&self.key, value) } /// Insert value, if not yet set, or update the current value of this session. /// /// Returns an owned copy of the set (current) value of this session. /// /// This is analagous to the `insert_or_update_with` method of...
swap
identifier_name
session.rs
//! This exposes `Session`, the struct stored in the `Alloy`. use std::sync::Arc; use super::SessionStore; /// A session which provides basic CRUD operations. pub struct Session<K, V> { key: K, store: Arc<Box<SessionStore<K, V> + 'static + Send + Sync>> } impl<K, V> Session<K, V> { /// Create a new sessi...
/// Swap the given value with the current value of this session. /// /// Returns the value being replaced. /// Returns `None` if this session was not yet set. pub fn swap(&self, value: V) -> Option<V> { self.store.swap(&self.key, value) } /// Insert value, if not yet set, or update ...
{ self.store.find(&self.key) }
identifier_body
isMatch.ts
/** * Performs a partial deep comparison between object and source to * determine if object contains equivalent property values. * * Partial comparisons will match empty array and empty object * source values against any array or object value, respectively. * * @category Language * * First version: July 14, 20...
* * @export * @param {object} input * @param {object} source * @returns {boolean} */ import { isEqual } from './isEqual'; import { keysIn } from './keysIn'; export function isMatch(input: object, source: object): boolean { const sourceKey: PropertyKey[] = keysIn({ source, goDeep: true, enumOnly: true });...
* Last updated : July 14, 2017
random_line_split
isMatch.ts
/** * Performs a partial deep comparison between object and source to * determine if object contains equivalent property values. * * Partial comparisons will match empty array and empty object * source values against any array or object value, respectively. * * @category Language * * First version: July 14, 20...
}
{ const sourceKey: PropertyKey[] = keysIn({ source, goDeep: true, enumOnly: true }); if (sourceKey.length === 0) return true; const inputKey: PropertyKey[] = keysIn({ source: input, goDeep: true, enumOnly: true }); if (sourceKey.length > inputKey.length) return false; let key: PropertyKey; for ...
identifier_body
isMatch.ts
/** * Performs a partial deep comparison between object and source to * determine if object contains equivalent property values. * * Partial comparisons will match empty array and empty object * source values against any array or object value, respectively. * * @category Language * * First version: July 14, 20...
(input: object, source: object): boolean { const sourceKey: PropertyKey[] = keysIn({ source, goDeep: true, enumOnly: true }); if (sourceKey.length === 0) return true; const inputKey: PropertyKey[] = keysIn({ source: input, goDeep: true, enumOnly: true }); if (sourceKey.length > inputKey.length) retu...
isMatch
identifier_name