file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
sample_file_parser.py | import json
import logging
from os import listdir, path
from typing import Dict, List
from tqdm import tqdm
TELEM_DIR_PATH = "../envs/monkey_zoo/blackbox/tests/performance/telemetry_sample"
MAX_SAME_TYPE_TELEM_FILES = 10000
LOGGER = logging.getLogger(__name__)
class SampleFileParser:
@staticmethod
def save_... |
@staticmethod
def read_telem_files() -> List[str]:
telems = []
try:
file_paths = [
path.join(TELEM_DIR_PATH, f)
for f in listdir(TELEM_DIR_PATH)
if path.isfile(path.join(TELEM_DIR_PATH, f))
]
except FileNotFoundErr... | telem_filename = telem["name"] + telem["method"]
for i in range(MAX_SAME_TYPE_TELEM_FILES):
if not path.exists(path.join(TELEM_DIR_PATH, (str(i) + telem_filename))):
telem_filename = str(i) + telem_filename
break
with open(path.join(TELEM_DIR_PATH, telem_filen... | identifier_body |
sample_file_parser.py | import json
import logging
from os import listdir, path
from typing import Dict, List
from tqdm import tqdm
TELEM_DIR_PATH = "../envs/monkey_zoo/blackbox/tests/performance/telemetry_sample"
MAX_SAME_TYPE_TELEM_FILES = 10000
LOGGER = logging.getLogger(__name__)
class SampleFileParser:
@staticmethod
def save_... | (telem: Dict):
telem_filename = telem["name"] + telem["method"]
for i in range(MAX_SAME_TYPE_TELEM_FILES):
if not path.exists(path.join(TELEM_DIR_PATH, (str(i) + telem_filename))):
telem_filename = str(i) + telem_filename
break
with open(path.join(TELE... | save_telemetry_to_file | identifier_name |
ejemplo-funciona.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
|
appname = "example"
class App(object):
def __init__(self, root=None):
if not root:
root = Tk()
self.root = root
self.initUI()
def initUI(self):
self.root.title(appname)
menubar = Menu(self.root)
self.root.config(menu=menubar)
fileMenu = Men... | import cv2
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog | random_line_split |
ejemplo-funciona.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
appname = "example"
class App(object):
def __init__(self, root=None):
if not root:
root = Tk()
self.root = root
self.initUI()
def initUI(self):
... |
def run(self):
self.root.mainloop()
def main():
root = Tk()
root.geometry("250x150+300+300")
app = App(root)
app.run()
if __name__ == '__main__':
main()
| video_capture = cv2.VideoCapture(0)
ret, frame = video_capture.read()
cv2.imshow('Video', frame)
params = list()
params.append(cv2.cv.CV_IMWRITE_PXM_BINARY)
params.append(1)
print "hola"
frame2 = cv2.cvtColor(frame, cv2.cv.CV_BGR2GRAY) # convert to grayscale
cv2.imwrite('cara2.pgm', frame2, params)
cv2.imwr... | identifier_body |
ejemplo-funciona.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
appname = "example"
class App(object):
def __init__(self, root=None):
if not root:
root = Tk()
self.root = root
self.initUI()
def initUI(self):
... | (self):
# Bloque : Tomamos la foto desde la web cam y la grabamos en formato PGM
video_capture = cv2.VideoCapture(0)
ret, frame = video_capture.read()
cv2.imshow('Video', frame)
params = list()
params.append(cv2.cv.CV_IMWRITE_PXM_BINARY)
params.append(1)
print "hola"
frame2 = cv2.cvtColor(frame, cv2.cv.CV_... | tomarFoto | identifier_name |
ejemplo-funciona.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import cv2
from Tkinter import *
from PIL import Image, ImageTk
import tkFileDialog
appname = "example"
class App(object):
def __init__(self, root=None):
if not root:
root = Tk()
self.root = root
self.initUI()
def initUI(self):
... | main() | conditional_block | |
benefit-owner.js | const UrlPathValidator = require('../../../services/validators/url-path-validator')
const referenceIdHelper = require('../../helpers/reference-id-helper')
const BenefitOwner = require('../../../services/domain/benefit-owner')
const ValidationError = require('../../../services/errors/validation-error')
const insertBenef... | dob: req.session.dobEncoded,
relationship: req.session.relationship,
benefit: req.session.benefit,
referenceId: req.session.referenceId
})
})
router.post('/apply/:claimType/new-eligibility/benefit-owner', function (req, res, next) {
UrlPathValidator(req.params)
const isValidSess... | return res.redirect(SessionHandler.getErrorPath(req.session, req.url))
}
return res.render('apply/new-eligibility/benefit-owner', {
claimType: req.session.claimType, | random_line_split |
benefit-owner.js | const UrlPathValidator = require('../../../services/validators/url-path-validator')
const referenceIdHelper = require('../../helpers/reference-id-helper')
const BenefitOwner = require('../../../services/domain/benefit-owner')
const ValidationError = require('../../../services/errors/validation-error')
const insertBenef... | else {
throw error
}
}
})
}
function renderValidationError (req, res, benefitOwnerBody, validationErrors, isDuplicateClaim) {
return res.status(400).render('apply/new-eligibility/benefit-owner', {
errors: validationErrors,
isDuplicateClaim: isDuplicateClaim,
claimType: req.session.cl... | {
return renderValidationError(req, res, benefitOwnerBody, error.validationErrors, false)
} | conditional_block |
benefit-owner.js | const UrlPathValidator = require('../../../services/validators/url-path-validator')
const referenceIdHelper = require('../../helpers/reference-id-helper')
const BenefitOwner = require('../../../services/domain/benefit-owner')
const ValidationError = require('../../../services/errors/validation-error')
const insertBenef... | {
return res.status(400).render('apply/new-eligibility/benefit-owner', {
errors: validationErrors,
isDuplicateClaim: isDuplicateClaim,
claimType: req.session.claimType,
dob: req.session.dobEncoded,
relationship: req.session.relationship,
benefit: req.session.benefit,
referenceId: req.sessi... | identifier_body | |
benefit-owner.js | const UrlPathValidator = require('../../../services/validators/url-path-validator')
const referenceIdHelper = require('../../helpers/reference-id-helper')
const BenefitOwner = require('../../../services/domain/benefit-owner')
const ValidationError = require('../../../services/errors/validation-error')
const insertBenef... | (req, res, benefitOwnerBody, validationErrors, isDuplicateClaim) {
return res.status(400).render('apply/new-eligibility/benefit-owner', {
errors: validationErrors,
isDuplicateClaim: isDuplicateClaim,
claimType: req.session.claimType,
dob: req.session.dobEncoded,
relationship: req.session.relation... | renderValidationError | identifier_name |
init.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... | let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
... | // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe { | random_line_split |
init.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... |
pub fn init_service_workers(sw_senders: SWManagerSenders) {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
}
#[allow(unsafe_code)]
pub fn init() -> JSEngineSetup {
unsafe {
proxyhandler::init();
// Create the global v... | {} | identifier_body |
init.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::RegisterBindings;
use crate::dom::bindings::proxyhandler;
use crate::script_ru... | () {
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim = libc::rlimit {
rlim_cur: 0,
rlim_max: 0... | perform_platform_specific_initialization | identifier_name |
params.py | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | oracle_driver_url = config['hostLevelParams']['oracle_jdbc_url']
mysql_driver_url = config['hostLevelParams']['mysql_jdbc_url']
ambari_server_resources = config['hostLevelParams']['jdk_location']
oracle_driver_symlink_url = format("{ambari_server_resources}oracle-jdbc-driver.jar")
mysql_driver_symlink_url = format("{am... | #db params
server_db_name = config['hostLevelParams']['db_name']
db_driver_filename = config['hostLevelParams']['db_driver_filename'] | random_line_split |
params.py | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
current_service = config['serviceName']
#security params
security_enabled = config['configurations']['cluster-env']['security_enabled']
#users and groups
has_hadoop_env = 'hadoop-env' in config['configurations']
mapred_user = config['configurations']['mapred-env']['mapred_user']
hdfs_user = config['configurations'... | mapreduce_libs_path = "/usr/iop/current/hadoop-mapreduce-client/*"
hadoop_home = stack_select.get_hadoop_dir("home")
create_lib_snappy_symlinks = False | conditional_block |
moderatorPurge.js | "use strict";
const { EffectDependency } = require("../models/effectModels");
const { EffectCategory } = require('../../../shared/effect-constants');
const logger = require('../../logwrapper');
const twitchChat = require("../../chat/twitch-chat");
const model = {
definition: {
id: "firebot:modpurge",
... |
return errors;
},
onTriggerEvent: async event => {
twitchChat.purgeUserMessages(event.effect.username);
logger.debug(event.effect.username + " was purged via the purge effect.");
return true;
}
};
module.exports = model;
| {
errors.push("Please put in a username.");
} | conditional_block |
moderatorPurge.js | "use strict";
const { EffectDependency } = require("../models/effectModels");
const { EffectCategory } = require('../../../shared/effect-constants');
const logger = require('../../logwrapper');
const twitchChat = require("../../chat/twitch-chat");
| description: "Purge a users chat messages from chat.",
icon: "fad fa-comment-slash",
categories: [EffectCategory.COMMON, EffectCategory.MODERATION],
dependencies: [EffectDependency.CHAT]
},
optionsTemplate: `
<eos-container header="Target" pad-top="true">
<div class="... | const model = {
definition: {
id: "firebot:modpurge",
name: "Purge", | random_line_split |
clarity_cli.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your... | () {
log::set_loglevel(log::LOG_DEBUG).unwrap();
let argv : Vec<String> = env::args().collect();
clarity::invoke_command(&argv[0], &argv[1..]);
}
| main | identifier_name |
clarity_cli.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack.
Blockstack is free software. You may redistribute or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your... | {
log::set_loglevel(log::LOG_DEBUG).unwrap();
let argv : Vec<String> = env::args().collect();
clarity::invoke_command(&argv[0], &argv[1..]);
} | identifier_body | |
clarity_cli.rs | /*
copyright: (c) 2013-2019 by Blockstack PBC, a public benefit corporation.
This file is part of Blockstack. | it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or
(at your option) any later version.
Blockstack is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY, including without the implied warranty of
MERCHANTABILI... |
Blockstack is free software. You may redistribute or modify | random_line_split |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object... | fn show_contents(name: &objects::Name) -> cli::Result {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree)... | cli::success()
}
| random_line_split |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object... | else if args.flag_s {
show_size(&name)
} else if args.flag_e {
check_validity(&name)
} else if args.flag_p {
show_contents(&name)
} else {
Err(cli::Error { message: "No flags specified".to_string(), status: 2 })
}
}
fn main() {
let args: Args = Docopt::new(USAGE)
... | {
show_type(&name)
} | conditional_block |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object... | (name: &objects::Name) -> cli::Result {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree) = commit.tree;
... | show_contents | identifier_name |
cat-file.rs | extern crate gitters;
extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;
use gitters::cli;
use gitters::commits;
use gitters::objects;
use gitters::revisions;
const USAGE: &'static str = "
cat-file - Provide content or type and size information for repository objects
Usage:
cat-file -t <object... |
fn dispatch_for_args(args: &Args) -> cli::Result {
let name = try!(cli::wrap_with_status(revisions::resolve(&args.arg_object), 1));
if args.flag_t {
show_type(&name)
} else if args.flag_s {
show_size(&name)
} else if args.flag_e {
check_validity(&name)
} else if args.flag_... | {
let obj = try!(cli::wrap_with_status(objects::read_object(&name), 1));
match obj {
objects::Object::Commit(commit) => {
let objects::Name(name) = commit.name;
println!("commit {}", name);
let objects::Name(tree) = commit.tree;
println!("tree : {}", ... | identifier_body |
getProvider.js | import config from 'config';
import path from 'path';
import api from '~/api/index.js';
export const PROVIDER_TYPE = {
MOVIES: 'movies',
SHOWS: 'shows'
};
const providers = {};
/**
* Get the correct API provider for a given provider type.
*
* @param {String} providerType -- PROVIDER_TYPE.MOVIES or PROVIDER_T... | try {
provider = require(path.resolve(__dirname, providerName + '.js'));
providers[providerType] = provider;
}
catch (e) {
const apis = Object.keys(api).reduce((acc, val, i, arr) => {
const isLast = i === arr.length - 1;
return acc += `${isLast ? 'and ' : ''}"${val}"${!isLa... | if (!provider) {
const providerName = config.get(`alexa-libby.${providerType}.provider`).toLowerCase();
| random_line_split |
getProvider.js | import config from 'config';
import path from 'path';
import api from '~/api/index.js';
export const PROVIDER_TYPE = {
MOVIES: 'movies',
SHOWS: 'shows'
};
const providers = {};
/**
* Get the correct API provider for a given provider type.
*
* @param {String} providerType -- PROVIDER_TYPE.MOVIES or PROVIDER_T... | (providerType) {
if (!providerType) {
throw new Error('Missing a provider type');
}
let provider = providers[providerType];
if (!provider) {
const providerName = config.get(`alexa-libby.${providerType}.provider`).toLowerCase();
try {
provider = require(path.resolve(__dirname, providerName +... | getProvider | identifier_name |
getProvider.js | import config from 'config';
import path from 'path';
import api from '~/api/index.js';
export const PROVIDER_TYPE = {
MOVIES: 'movies',
SHOWS: 'shows'
};
const providers = {};
/**
* Get the correct API provider for a given provider type.
*
* @param {String} providerType -- PROVIDER_TYPE.MOVIES or PROVIDER_T... |
return provider;
}
| {
const providerName = config.get(`alexa-libby.${providerType}.provider`).toLowerCase();
try {
provider = require(path.resolve(__dirname, providerName + '.js'));
providers[providerType] = provider;
}
catch (e) {
const apis = Object.keys(api).reduce((acc, val, i, arr) => {
cons... | conditional_block |
getProvider.js | import config from 'config';
import path from 'path';
import api from '~/api/index.js';
export const PROVIDER_TYPE = {
MOVIES: 'movies',
SHOWS: 'shows'
};
const providers = {};
/**
* Get the correct API provider for a given provider type.
*
* @param {String} providerType -- PROVIDER_TYPE.MOVIES or PROVIDER_T... | {
if (!providerType) {
throw new Error('Missing a provider type');
}
let provider = providers[providerType];
if (!provider) {
const providerName = config.get(`alexa-libby.${providerType}.provider`).toLowerCase();
try {
provider = require(path.resolve(__dirname, providerName + '.js'));
... | identifier_body | |
rAF.js | // Used exclusively for testing in PhantomJS environment.
// https://gist.github.com/paulirish/1579671
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating |
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimation... |
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license | random_line_split |
TestDataFormatterObjCNSError.py | # encoding: utf-8
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
class ObjCDataFormatterNS... | (self):
"""Test formatters for NSError."""
self.appkit_tester_impl(self.nserror_data_formatter_commands)
def nserror_data_formatter_commands(self):
self.expect(
'frame variable nserror', substrs=['domain: @"Foobar" - code: 12'])
self.expect(
'frame variable ... | test_nserror_with_run_command | identifier_name |
TestDataFormatterObjCNSError.py | # encoding: utf-8
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import * |
class ObjCDataFormatterNSError(ObjCDataFormatterTestCase):
@skipUnlessDarwin
def test_nserror_with_run_command(self):
"""Test formatters for NSError."""
self.appkit_tester_impl(self.nserror_data_formatter_commands)
def nserror_data_formatter_commands(self):
self.expect(
... | from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
| random_line_split |
TestDataFormatterObjCNSError.py | # encoding: utf-8
"""
Test lldb data formatter subsystem.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
from ObjCDataFormatterTestCase import ObjCDataFormatterTestCase
class ObjCDataFormatterNS... |
def nserror_data_formatter_commands(self):
self.expect(
'frame variable nserror', substrs=['domain: @"Foobar" - code: 12'])
self.expect(
'frame variable nserrorptr',
substrs=['domain: @"Foobar" - code: 12'])
self.expect(
'frame variable nse... | """Test formatters for NSError."""
self.appkit_tester_impl(self.nserror_data_formatter_commands) | identifier_body |
models_tests.py | from nose.tools import eq_, ok_
from django.test import TestCase
from us_ignite.snippets.models import Snippet
from us_ignite.snippets.tests import fixtures
class TestSnippetModel(TestCase):
def tearDown(self):
Snippet.objects.all().delete()
def get_instance(self):
data = {
'nam... | ok_(instance.created)
ok_(instance.modified)
eq_(instance.slug, 'featured')
ok_(instance.id)
eq_(instance.notes, '')
def test_instance_name_is_used_as_title(self):
instance = fixtures.get_snippet(name='About page')
eq_(instance.title, 'About page') | eq_(instance.is_featured, False) | random_line_split |
models_tests.py | from nose.tools import eq_, ok_
from django.test import TestCase
from us_ignite.snippets.models import Snippet
from us_ignite.snippets.tests import fixtures
class TestSnippetModel(TestCase):
def tearDown(self):
Snippet.objects.all().delete()
def | (self):
data = {
'name': 'Gigabit snippets',
'slug': 'featured',
'url': 'http://us-ignite.org/',
}
return Snippet.objects.create(**data)
def test_instance_is_created_successfully(self):
instance = self.get_instance()
eq_(instance.name, 'Gi... | get_instance | identifier_name |
models_tests.py | from nose.tools import eq_, ok_
from django.test import TestCase
from us_ignite.snippets.models import Snippet
from us_ignite.snippets.tests import fixtures
class TestSnippetModel(TestCase):
def tearDown(self):
Snippet.objects.all().delete()
def get_instance(self):
data = {
'nam... |
def test_instance_name_is_used_as_title(self):
instance = fixtures.get_snippet(name='About page')
eq_(instance.title, 'About page')
| instance = self.get_instance()
eq_(instance.name, 'Gigabit snippets')
eq_(instance.status, Snippet.DRAFT)
eq_(instance.url, 'http://us-ignite.org/')
eq_(instance.url_text, '')
eq_(instance.body, '')
eq_(instance.image, '')
eq_(instance.is_featured, False)
... | identifier_body |
is-finite-number.js | /**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
... | (a) {
return isNumber(a) && isFinite(a);
}
| isFiniteNumber | identifier_name |
is-finite-number.js | /**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
... | {
return isNumber(a) && isFinite(a);
} | identifier_body | |
is-finite-number.js | /**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
... | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SO... | * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | random_line_split |
edgeop_lsys.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
#[macro_use]
extern crate graph_annealing;
extern crate pcg;
extern crate triadic_census;
extern crate lindenmayer_system;
extern crate graph_edge_evolution;
extern crate asexp;
extern crate expression;
extern crate expression_num;
extern crate expression_clos... | {
println!("Using expr system: {}", EXPR_NAME);
let env = Env::new();
let plot = Plot::new(&env);
let mut s = String::new();
let configfile = env::args().nth(1).unwrap();
let _ = File::open(configfile).unwrap().read_to_string(&mut s).unwrap();
let expr = asexp::Sexp::parse_toplevel(&s).unwr... | identifier_body | |
edgeop_lsys.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
#[macro_use]
extern crate graph_annealing;
extern crate pcg;
extern crate triadic_census;
extern crate lindenmayer_system;
extern crate graph_edge_evolution;
extern crate asexp;
extern crate expression;
extern crate expression_num;
extern crate expression_clos... | struct Objective {
fitness_function: FitnessFunction,
threshold: f32,
}
fn parse_ops<T, I>(map: &BTreeMap<String, Sexp>, key: &str) -> Vec<(T, u32)>
where T: FromStr<Err = I> + UniformDistribution,
I: Debug
{
if let Some(&Sexp::Map(ref list)) = map.get(key) {
let mut ops: Vec<(T, u32)> = Vec:... | #[derive(Debug)] | random_line_split |
edgeop_lsys.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
#[macro_use]
extern crate graph_annealing;
extern crate pcg;
extern crate triadic_census;
extern crate lindenmayer_system;
extern crate graph_edge_evolution;
extern crate asexp;
extern crate expression;
extern crate expression_num;
extern crate expression_clos... | (w: Option<&Sexp>) -> Option<f32> {
match w {
Some(s) => s.get_float().map(|f| f as f32),
None => {
// use a default
Some(0.0)
}
}
}
fn parse_config(sexp: Sexp) -> Config {
let map = sexp.into_map().unwrap();
// number of generations
let ngen: usize ... | convert_weight | identifier_name |
htmlareaelement.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::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaEl... | }
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
... | let node: JSRef<Node> = NodeCast::from_ref(*self);
match name.as_slice() {
"href" => node.set_enabled_state(true),
_ => () | random_line_split |
htmlareaelement.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::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaEl... |
}
impl<'a> VirtualMethods for JSRef<'a, HTMLAreaElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMSt... | {
let element = HTMLAreaElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLAreaElementBinding::Wrap)
} | identifier_body |
htmlareaelement.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::HTMLAreaElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLAreaEl... | (&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLAreaElementTypeId))
}
}
impl HTMLAreaElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(HTMLAreaElemen... | is_htmlareaelement | identifier_name |
selection.directive.ts | import { AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, EventEmitter, HostBinding, Input, OnDestroy, Output, QueryList } from '@angular/core';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { SelectionItemDirective } from './selection-item.directive';
... |
}
/**
* Deselect all currently selected items
*/
deselectAll(): void {
if (this._selectionService.isEnabled) {
this._selectionService.strategy.deselectAll();
}
}
/**
* Determine if the previous selection is the same as the current selection
*/
p... | {
this._selectionService.strategy.selectAll();
} | conditional_block |
selection.directive.ts | import { AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, EventEmitter, HostBinding, Input, OnDestroy, Output, QueryList } from '@angular/core';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { SelectionItemDirective } from './selection-item.directive';
... |
constructor(private _selectionService: SelectionService<T>, private _cdRef: ChangeDetectorRef) {
_selectionService.selection$.pipe(debounceTime(0), takeUntil(this._onDestroy)).subscribe(items => {
if (this.isSelectionChanged(items)) {
this.uxSelectionChange.emit(items);
... | /** Store the previous selection so we don't emit more than we have to */
private _lastSelection: ReadonlyArray<T> = [];
/** Whether a value has been provided to the `selectionItems` input. */
private _hasExplicitDataset: boolean = false; | random_line_split |
selection.directive.ts | import { AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, EventEmitter, HostBinding, Input, OnDestroy, Output, QueryList } from '@angular/core';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { SelectionItemDirective } from './selection-item.directive';
... | (): void {
if (this._selectionService.isEnabled) {
this._selectionService.strategy.selectAll();
}
}
/**
* Deselect all currently selected items
*/
deselectAll(): void {
if (this._selectionService.isEnabled) {
this._selectionService.strategy.deselect... | selectAll | identifier_name |
selection.directive.ts | import { AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, EventEmitter, HostBinding, Input, OnDestroy, Output, QueryList } from '@angular/core';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { SelectionItemDirective } from './selection-item.directive';
... |
/**
* Deselect all currently selected items
*/
deselectAll(): void {
if (this._selectionService.isEnabled) {
this._selectionService.strategy.deselectAll();
}
}
/**
* Determine if the previous selection is the same as the current selection
*/
private... | {
if (this._selectionService.isEnabled) {
this._selectionService.strategy.selectAll();
}
} | identifier_body |
tops_sql.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# filename: tops_sql.py
# Copyright 2008-2010 Stefano Costa <steko@iosa.it>
#
# This file is part of Total Open Station.
#
# Total Open Station is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by ... | self.data = data
self.tablename = tablename
def process(self):
lines = [to_sql(e, self.tablename) for e in self.data]
lines.insert(0, 'BEGIN;\n')
lines.append('COMMIT;\n')
output = "".join(lines)
return output
if __name__ == "__main__":
TotalOpenSQL(
... |
def __init__(self, data, tablename='topsdata'): | random_line_split |
tops_sql.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# filename: tops_sql.py
# Copyright 2008-2010 Stefano Costa <steko@iosa.it>
#
# This file is part of Total Open Station.
#
# Total Open Station is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by ... | TotalOpenSQL(
[(1, 2, 3, 4, 'qwerty'),
("2.3", 42, 45, 12, 'asdfg')],
'prova') | conditional_block | |
tops_sql.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# filename: tops_sql.py
# Copyright 2008-2010 Stefano Costa <steko@iosa.it>
#
# This file is part of Total Open Station.
#
# Total Open Station is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by ... | (self):
lines = [to_sql(e, self.tablename) for e in self.data]
lines.insert(0, 'BEGIN;\n')
lines.append('COMMIT;\n')
output = "".join(lines)
return output
if __name__ == "__main__":
TotalOpenSQL(
[(1, 2, 3, 4, 'qwerty'),
("2.3", 42, 45, 12, 'asdfg')],
... | process | identifier_name |
tops_sql.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# filename: tops_sql.py
# Copyright 2008-2010 Stefano Costa <steko@iosa.it>
#
# This file is part of Total Open Station.
#
# Total Open Station is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by ... |
def process(self):
lines = [to_sql(e, self.tablename) for e in self.data]
lines.insert(0, 'BEGIN;\n')
lines.append('COMMIT;\n')
output = "".join(lines)
return output
if __name__ == "__main__":
TotalOpenSQL(
[(1, 2, 3, 4, 'qwerty'),
("2.3", 42, 45, 12, ... | self.data = data
self.tablename = tablename | identifier_body |
sizing.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! https://drafts.csswg.org/css-sizing/
use crate::style_ext::ComputedValuesExt;
use style::properties::Compute... | let border = style.border_width();
let margin = style.margin();
pbm_lengths += border.inline_sum();
let mut add = |x: LengthPercentage| {
if let Some(l) = x.to_length() {
pbm_lengths += l;
}
if let Some(p) = x.to_percentage() {
... | let mut pbm_percentages = Percentage::zero();
let padding = style.padding(); | random_line_split |
sizing.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! https://drafts.csswg.org/css-sizing/
use crate::style_ext::ComputedValuesExt;
use style::properties::Compute... | let inline = self.expect_inline();
available_size
.max(inline.min_content)
.min(inline.max_content)
}
} | identifier_body | |
sizing.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! https://drafts.csswg.org/css-sizing/
use crate::style_ext::ComputedValuesExt;
use style::properties::Compute... | () -> Self {
Self {
min_content: Length::zero(),
max_content: Length::zero(),
}
}
pub fn max_assign(&mut self, other: &Self) {
self.min_content.max_assign(other.min_content);
self.max_content.max_assign(other.max_content);
}
/// Relevant to outer... | zero | identifier_name |
webcontentedit.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Romain Bignon
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will b... | (self, line):
"""
edit ID
Edit a content with $EDITOR, then push it on the website.
"""
contents = []
for id in line.split():
_id, backend_name = self.parse_id(id)
backend_names = (backend_name,) if backend_name is not None else self.enabled_backe... | do_edit | identifier_name |
webcontentedit.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Romain Bignon
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will b... |
else:
contents.remove(content)
if len(contents) == 0:
print 'No changes. Abort.'
return
print 'Contents changed:\n%s' % ('\n'.join([' * %s' % content.id for content in contents]))
message = self.ask('Enter a commit message', default='')
... | content.content = data | conditional_block |
webcontentedit.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Romain Bignon
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will b... | APPNAME = 'webcontentedit'
VERSION = '0.4'
COPYRIGHT = 'Copyright(C) 2010 Romain Bignon'
CAPS = ICapContent
def do_edit(self, line):
"""
edit ID
Edit a content with $EDITOR, then push it on the website.
"""
contents = []
for id in line.split():
... | identifier_body | |
webcontentedit.py | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Romain Bignon | # it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# 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. Se... | #
# This program is free software; you can redistribute it and/or modify | random_line_split |
requireSource.ts | /*
This is a slightly-modified version of preconstruct's hook for use with
keystone project files in the monorepo. Importantly it doesn't accept a cwd and
sets rootMode: "upward-optional"
*/
import { addHook } from 'pirates';
import * as babel from '@babel/core';
import sourceMapSupport from 'source-map-support';
con... | (source) {
let map = sourceMaps[source];
if (map !== undefined) {
return { url: source, map };
} else {
return null;
}
},
});
needsToInstallSourceMapSupport = false;
}
try {
compiling = true;
const output = babel.tra... | retrieveSourceMap | identifier_name |
requireSource.ts | /*
This is a slightly-modified version of preconstruct's hook for use with
keystone project files in the monorepo. Importantly it doesn't accept a cwd and
sets rootMode: "upward-optional"
*/
import { addHook } from 'pirates';
import * as babel from '@babel/core';
import sourceMapSupport from 'source-map-support';
con... | ,
});
needsToInstallSourceMapSupport = false;
}
try {
compiling = true;
const output = babel.transformSync(code, {
filename,
presets: [require.resolve('next/babel')],
configFile: false,
babelrc: false,
sourceMaps: 'both',
})!;
sourceMap... | {
let map = sourceMaps[source];
if (map !== undefined) {
return { url: source, map };
} else {
return null;
}
} | identifier_body |
requireSource.ts | /*
This is a slightly-modified version of preconstruct's hook for use with
keystone project files in the monorepo. Importantly it doesn't accept a cwd and
sets rootMode: "upward-optional"
*/
import { addHook } from 'pirates';
import * as babel from '@babel/core';
import sourceMapSupport from 'source-map-support';
con... |
try {
compiling = true;
const output = babel.transformSync(code, {
filename,
presets: [require.resolve('next/babel')],
configFile: false,
babelrc: false,
sourceMaps: 'both',
})!;
sourceMaps[filename] = output.map;
return output.code!;
} fina... | {
sourceMapSupport.install({
environment: 'node',
retrieveSourceMap(source) {
let map = sourceMaps[source];
if (map !== undefined) {
return { url: source, map };
} else {
return null;
}
},
});
needsToInstallSourceM... | conditional_block |
requireSource.ts | /*
This is a slightly-modified version of preconstruct's hook for use with
keystone project files in the monorepo. Importantly it doesn't accept a cwd and
sets rootMode: "upward-optional"
*/
import { addHook } from 'pirates';
import * as babel from '@babel/core';
import sourceMapSupport from 'source-map-support'; |
const hook = () => {
let compiling = false;
let sourceMaps: Record<string, any> = {};
let needsToInstallSourceMapSupport = true;
function compileHook(code: string, filename: string) {
if (compiling) return code;
// we do this lazily because jest has its own require implementation
// which means pre... |
const EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx']; | random_line_split |
worker.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 devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom::abstractworker::{SharedRt, SimpleWor... | (address: TrustedWorkerAddress) {
let worker = address.root();
worker.upcast().fire_event(atom!("error"));
}
}
impl WorkerMethods for Worker {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-worker-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message... | dispatch_simple_error | identifier_name |
worker.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 devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom::abstractworker::{SharedRt, SimpleWor... |
let global = worker.global();
let target = worker.upcast();
let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get());
rooted!(in(global.get_cx()) let mut message = UndefinedValue());
data.read(&global, message.handle_mut());
MessageEven... | {
return;
} | conditional_block |
worker.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 devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
use dom::abstractworker::{SharedRt, SimpleWor... |
pub fn new(global: &GlobalScope,
sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
closing: Arc<AtomicBool>) -> DomRoot<Worker> {
reflect_dom_object(Box::new(Worker::new_inherited(sender, closing)),
global,
WorkerBin... | random_line_split | |
interlis_model.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
import re
from hub.formats import Format, Formatter
from hub.structures.file import File
from hub.structures.frame import OdhType
class InterlisModelFormat(Format):
name = 'INTERLIS1Model'
label = 'INTERLIS 1 Modell'
description... | self, name, tables):
self.name = sanitize_name(name)
self.tables = tables
def get_topic_definition(self):
result = 'TOPIC {} = \n\n'.format(self.name)
for table in self.tables:
result += table.get_table_definition()
result += '\nEND {}.\n'.format(self.name)
... | _init__( | identifier_name |
interlis_model.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
import re
from hub.formats import Format, Formatter
from hub.structures.file import File
from hub.structures.frame import OdhType
class InterlisModelFormat(Format):
name = 'INTERLIS1Model'
label = 'INTERLIS 1 Modell'
description... |
result += '\nMODEL {}\n\n'.format(self.name)
for topic in self.topics:
result += topic.get_topic_definition()
result += '\nEND {}.\n\n'.format(self.name)
result += 'FORMAT FREE;\n\n'
result += '\nCODE\n\tBLANK = DEFAULT, UNDEFINED = DEFAULT, CONTINUE = DEFAULT;\n... | esult += 'DOMAIN\n\n'
for k, v in domain.iteritems():
result += '\t{} = {};\n'.format(k, v)
| conditional_block |
interlis_model.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
import re
from hub.formats import Format, Formatter
from hub.structures.file import File
from hub.structures.frame import OdhType
class InterlisModelFormat(Format):
name = 'INTERLIS1Model'
label = 'INTERLIS 1 Modell'
description... |
class Table(object):
def __init__(self, name, df):
self.name = sanitize_name(name)
self.df = df
self.fields, self.domain = self.get_fields()
def get_table_definition(self):
result = '\tTABLE {} = \n'.format(self.name)
for field in self.fields:
result += '\... | ef __init__(self, name, tables):
self.name = sanitize_name(name)
self.tables = tables
def get_topic_definition(self):
result = 'TOPIC {} = \n\n'.format(self.name)
for table in self.tables:
result += table.get_table_definition()
result += '\nEND {}.\n'.format(se... | identifier_body |
interlis_model.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import math
import re
from hub.formats import Format, Formatter
from hub.structures.file import File
from hub.structures.frame import OdhType
class InterlisModelFormat(Format):
name = 'INTERLIS1Model'
label = 'INTERLIS 1 Modell'
description... | def get_model_definition(self):
result = 'TRANSFER {}; \n\n'.format(self.name)
result += '!! ACHTUNG: Dies ist ein automatisch generiertes Modell und sollte nicht ohne Anpassungen \n'
result += '!! verwendet werden.\n\n'
domain = {}
for topic in self.topics:
for ... | self.name = sanitize_name(name)
self.topics = topics
| random_line_split |
tag_utils.py | #
# Copyright 2003-2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version... | self.srcid = None
def tag_to_python(tag):
""" Convert a stream tag to a Python-readable object """
newtag = PythonTag()
newtag.offset = tag.offset
newtag.key = pmt.to_python(tag.key)
newtag.value = pmt.to_python(tag.value)
newtag.srcid = pmt.to_python(tag.srcid)
return newtag
def ... | self.key = None
self.value = None | random_line_split |
tag_utils.py | #
# Copyright 2003-2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version... | (object):
" Python container for tags "
def __init__(self):
self.offset = None
self.key = None
self.value = None
self.srcid = None
def tag_to_python(tag):
""" Convert a stream tag to a Python-readable object """
newtag = PythonTag()
newtag.offset = tag.offset
... | PythonTag | identifier_name |
tag_utils.py | #
# Copyright 2003-2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version... |
def tag_to_python(tag):
""" Convert a stream tag to a Python-readable object """
newtag = PythonTag()
newtag.offset = tag.offset
newtag.key = pmt.to_python(tag.key)
newtag.value = pmt.to_python(tag.value)
newtag.srcid = pmt.to_python(tag.srcid)
return newtag
def tag_to_pmt(tag):
""" C... | " Python container for tags "
def __init__(self):
self.offset = None
self.key = None
self.value = None
self.srcid = None | identifier_body |
overloaded-deref-count.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
self.count_mut += 1;
&mut self.value
}
}
pub fn main() {
let mut n = DerefCounter::new(0i);
let mut v = DerefCounter::new(Vec:... |
impl<T> Deref<T> for DerefCounter<T> {
fn deref(&self) -> &T { | random_line_split |
overloaded-deref-count.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> (uint, uint) {
(self.count_imm.get(), self.count_mut)
}
}
impl<T> Deref<T> for DerefCounter<T> {
fn deref(&self) -> &T {
self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
... | counts | identifier_name |
overloaded-deref-count.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
impl<T> Deref<T> for DerefCounter<T> {
fn deref(&self) -> &T {
self.count_imm.set(self.count_imm.get() + 1);
&self.value
}
}
impl<T> DerefMut<T> for DerefCounter<T> {
fn deref_mut(&mut self) -> &mut T {
self.count_mut += 1;
&mut self.value
}
}
pub fn main() {
le... | {
(self.count_imm.get(), self.count_mut)
} | identifier_body |
grql-test.js | const chai = require('chai')
const expect = chai.expect
const path = require('path')
const fs = require('fs')
const os = require('os')
const YAML = require('yamljs')
const pkg = require('../package') | describe('grql', () => {
let config, grql, sampleServer
before(() => {
process.env['NODE_ENV'] = 'test'
config = require('../lib/config')
config.configFile = path.join(os.tmpdir(), `.${pkg.name}.yml`)
grql = require('../lib/grql')
sampleServer = require('./sample-server')
process.stdin.isTT... | random_line_split | |
grql-test.js | const chai = require('chai')
const expect = chai.expect
const path = require('path')
const fs = require('fs')
const os = require('os')
const YAML = require('yamljs')
const pkg = require('../package')
describe('grql', () => {
let config, grql, sampleServer
before(() => {
process.env['NODE_ENV'] = 'test'
co... |
fs.unlinkSync(config.configFile)
})
describe('exec', () => {
it('should return an error if no argument', async () => {
try {
await grql.exec()
throw new Error('should not return a result')
} catch (err) {
expect(err).to.be.an('error')
expect(err).to.have.proper... | {
return
} | conditional_block |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<... | else {
None
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
match self.vec.len() {
len if len > self.pos => {
let diff = len - self.pos;
(diff, Some(diff))
},
_ => (0, None),
}
}
... | {
Some(self.vec.get(self.pos))
} | conditional_block |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<... | (self) -> usize {
self.size_hint().0
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Block> {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a ... | count | identifier_name |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<... |
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a NbitsVec<N, Block> where N: Unsigned + NonZero, Block: PrimInt {
type Item = Block;
type IntoIter = Iter<'a, N, Block>;
fn into_iter(self) -> Iter<'a, N, Block> {
Iter {
vec: self,
pos: 0,
}
}
}
#[cfg(test)]
mo... | {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
} | identifier_body |
iter.rs | use ::NbitsVec;
use num::PrimInt;
use typenum::NonZero;
use typenum::uint::Unsigned;
pub struct Iter<'a, N:'a, Block: 'a> where N: Unsigned + NonZero, Block: PrimInt {
vec: &'a NbitsVec<N, Block>,
pos: usize,
}
impl<'a, N:'a, Block: 'a> Iter<'a, N, Block> where N: Unsigned + NonZero, Block: PrimInt {
}
impl<... | #[inline]
fn nth(&mut self, n: usize) -> Option<Block> {
self.pos += n;
if self.vec.len() > self.pos {
Some(self.vec.get(self.pos))
} else {
None
}
}
}
impl<'a, N:'a, Block: 'a> IntoIterator for &'a NbitsVec<N, Block> where N: Unsigned + NonZero, Bloc... | #[inline]
fn count(self) -> usize {
self.size_hint().0
}
| random_line_split |
varinput.js | // varinput.js
// Javascript routines to handle variable rendering
// $Id: //dev/EPS/js/varinput.js#48 $
function inspect()
|
// global variable used for items that submit on change or selection
var autosubmit = '';
var autopublish = '';
var workspaceByPass = false;
function valueChanged(ident) {
var theField = document.getElementById('form1').variablechanged;
if (theField != null) {
theField.value = (theField.value == '') ? ',' + ... | {
form1.xml.value = '1';
SubmitFormSpecial('table');
} | identifier_body |
varinput.js | // varinput.js
// Javascript routines to handle variable rendering
// $Id: //dev/EPS/js/varinput.js#48 $
function inspect()
{
form1.xml.value = '1';
SubmitFormSpecial('table');
}
// global variable used for items that submit on change or selection
var autosubmit = '';
var autopublish = '';
var workspaceByPass = f... | (ident) {
var theField = document.getElementById('form1').variablechanged;
if (theField != null) {
if (theField.value.indexOf(ident + ',') > -1) {
theField.value = theField.value.replace(ident + ',', '');
}
}
}
function processCmt(obj, ident) {
obj.value = obj.value.substring(0, 1999);
var theF... | valueUnChanged | identifier_name |
varinput.js | // varinput.js
// Javascript routines to handle variable rendering
// $Id: //dev/EPS/js/varinput.js#48 $
function inspect()
{
form1.xml.value = '1';
SubmitFormSpecial('table');
}
// global variable used for items that submit on change or selection
var autosubmit = '';
var autopublish = '';
var workspaceByPass = f... | form1.act.value = s;
form1.submit();
form1.target = '_self';
form1.act.value = '';
}
function ReturnComment() {
PostSubmit();
}
function SubmitFormSpecialOnValue(field,s) {
if (field.value.length > 0) {
SubmitFormSpecial(s);
field.selectedIndex = 0;
}
}
function currTime() {
var now = new Dat... | random_line_split | |
rec-align-u64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}};
// Send it through the shape code
let y = fmt!("%?", x);
debug!("align inner = %?", rusti::min_align_of::<Inner>());
debug!("size outer = %?", sys::size_of::<Outer>());
debug!("y = %s", y);
... | }
}
| random_line_split |
rec-align-u64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "android")]
mod m {
#[cfg(target_arch = "arm")]
pub mod m {
pub fn align() -> uint { 4u }
pub fn size() -> uint { 12u }
}
}
pub fn main() {
unsafe {
let x = Outer {c8: 22u8, t: Inner {c64: 44u64}}... | align | identifier_name |
rec-align-u64.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn size() -> uint { 12u }
}
#[cfg(target_arch = "x86_64")]
mod m {
pub fn align() -> uint { 8u }
pub fn size() -> uint { 16u }
}
}
#[cfg(target_os = "win32")]
mod m {
#[cfg(target_arch = "x86")]
pub mod m {
pub fn align() -> uint { 8u }
pub fn size(... | { 4u } | identifier_body |
skia_gold_properties.py | # Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for storing Skia Gold comparison properties.
Examples:
* git revision being tested
* Whether the test is being run locally or on a bot
* What the co... |
@property
def bypass_skia_gold_functionality(self):
return self._bypass_skia_gold_functionality
@staticmethod
def _GetGitOriginMainHeadSha1():
raise NotImplementedError()
def _GetGitRevision(self):
if not self._git_revision:
# Automated tests should always pass the revision, so assume we... | return self._patchset | identifier_body |
skia_gold_properties.py | # Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for storing Skia Gold comparison properties.
Examples:
* git revision being tested
* Whether the test is being run locally or on a bot
* What the co... | (self):
if self._local_pixel_tests is None:
# Look for the presence of the SWARMING_SERVER environment variable as a
# heuristic to determine whether we're running on a workstation or a bot.
# This should always be set on swarming, but would be strange to be set on
# a workstation.
sel... | _IsLocalRun | identifier_name |
skia_gold_properties.py | # Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for storing Skia Gold comparison properties.
Examples:
* git revision being tested
* Whether the test is being run locally or on a bot
* What the co... | if hasattr(args, 'bypass_skia_gold_functionality'):
self._bypass_skia_gold_functionality = args.bypass_skia_gold_functionality
if hasattr(args, 'code_review_system'):
self._code_review_system = args.code_review_system
if hasattr(args, 'continuous_integration_system'):
self._continuous_in... | random_line_split | |
skia_gold_properties.py | # Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for storing Skia Gold comparison properties.
Examples:
* git revision being tested
* Whether the test is being run locally or on a bot
* What the co... |
revision = self._GetGitOriginMainHeadSha1()
if not revision or len(revision) != 40:
raise RuntimeError(
'--git-revision not passed and unable to determine from git')
self._git_revision = revision
return self._git_revision
def _IsLocalRun(self):
if self._local_pixel_test... | raise RuntimeError(
'--git-revision was not passed when running on a bot') | conditional_block |
0004_unique_together_sort.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-29 19:01
from __future__ import unicode_literals
from django.db import migrations
class | (migrations.Migration):
dependencies = [
('books', '0003_initial_subjects_languages_creatortypes'),
]
operations = [
migrations.AlterModelOptions(
name='creatortype',
options={'ordering': ['name']},
),
migrations.AlterModelOptions(
name='... | Migration | identifier_name |
0004_unique_together_sort.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-29 19:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
| dependencies = [
('books', '0003_initial_subjects_languages_creatortypes'),
]
operations = [
migrations.AlterModelOptions(
name='creatortype',
options={'ordering': ['name']},
),
migrations.AlterModelOptions(
name='language',
option... | identifier_body | |
0004_unique_together_sort.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-29 19:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('books', '0003_initial_subjects_languages_creatortypes'),
]
operations = [
migration... | options={'ordering': ['name']},
),
migrations.AlterModelOptions(
name='owninginstitution',
options={'ordering': ['name']},
),
migrations.AlterModelOptions(
name='personbookrelationshiptype',
options={'ordering': ['name']},
... | random_line_split | |
test-fb-hgext-diff-since-last-submit-t.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
from __future__ import absolute_import
from testutil.dott import feature, sh, testtmp # noqa: F401
# Load extensions
(
sh % "cat"
<< r"""... | sh % "hg diff --since-last-submit" == r"""
abort: local changeset is not associated with a differential revision
[255]"""
sh % "hg log -r 'lastsubmitted(.)' -T '{node} {desc}\\n'" == r"""
abort: local changeset is not associated with a differential revision
[255]"""
# Fake a diff
sh % "echo bleet" > ... | random_line_split | |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//sha... |
fn convert_to_str(x: &str) -> &str{
x
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("shipload.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
//*************************... | {
Command::new("xterm")
.arg("-hold")
.arg("-e")
.arg("cd ".to_string() + location + " && " + command + " " + arguments)
.spawn()
.expect("Failed to run command");
} | identifier_body |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//sha... | (location: &String, command: &String, arguments: &String){
Command::new("xterm")
.arg("-hold")
.arg("-e")
.arg("cd ".to_string() + location + " && " + command + " " + arguments)
.spawn()
.expect("Failed to run command");
}
fn convert_to_str(x: &str) -> &str{
x
}
fn main() {
if gtk::ini... | execute_command | identifier_name |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//sha... | pref_window.hide();
}));
//Cargo
cargo_build.connect_clicked(clone!(cargo_build_folder, cargo_build_arguments => move |_|{
let argument_string: String = gtk_converter::text_from_entry(&cargo_build_arguments);
let locationstr: String = gtk_converter::path_from_filechooser(&cargo_build_... | //Hide, with save
pref_save.connect_clicked(clone!(pref_window => move |_| { | random_line_split |
main.rs | //Test File gtk_test
extern crate gtk;
//Custom mods
mod system_io;
mod gtk_converter;
pub mod m_config;
//Os interaction
use std::process::Command;
use std::process::ChildStdout;
use std::io;
use std::io::prelude::*;
use gtk::Builder;
use gtk::prelude::*;
// make moving clones into closures more convenient
//sha... |
let glade_src = include_str!("shipload.glade");
let builder = Builder::new();
builder.add_from_string(glade_src).unwrap();
//**********************************************
//Crucial
let configuration = m_config::create_config();
//Main
//Get Window
let window: gtk::Window = builder.get_object(... | {
println!("Failed to initialize GTK.");
return;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.