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 |
|---|---|---|---|---|
validators.py | PROJECT_DEFAULTS = 'Project Defaults'
PATHS = 'Paths'
_from_config = {
'author': None,
'email': None,
'license': None,
'language': None,
'type': None,
'parent': None,
'vcs': None,
'footprints': None
}
_from_args = {
'name': None,
'author': None,
'email': None,
'license'... |
def footprint_requires(merged):
required = ['name', 'parent']
passed = 0
pass_requires = len(required)
for r in required:
if r in merged.keys():
if merged[r] is not None:
passed += 1
return passed == pass_requires
def solo_args_requires(args):
required = ... | merged = configged.copy()
for key in argged.keys():
if True in [key == k for k in configged.keys()]:
# We only care about a None val if the key exists in configged
# this will overwrite the config so that args take percedence
if argged[key] is not None:
me... | identifier_body |
validators.py | PROJECT_DEFAULTS = 'Project Defaults'
PATHS = 'Paths'
_from_config = {
'author': None,
'email': None,
'license': None,
'language': None,
'type': None,
'parent': None,
'vcs': None,
'footprints': None
}
_from_args = {
'name': None,
'author': None,
'email': None,
'license'... | merged[key] = argged[key]
else:
# If the key is not already here, then it must be 'footprint', in
# which case we definitely want to include it since that is our
# highest priority and requires less args to generate a project
merged[key] = argged[k... | if True in [key == k for k in configged.keys()]:
# We only care about a None val if the key exists in configged
# this will overwrite the config so that args take percedence
if argged[key] is not None: | random_line_split |
version.py | #!/usr/bin/env python
# Copyright (c) 2010-2016, Daniel S. Standage and CONTRIBUTORS
#
# The AEGeAn Toolkit is distributed under the ISC License. See
# the 'LICENSE' file in the AEGeAn source code distribution or
# online at https://github.com/standage/AEGeAn/blob/master/LICENSE.
from __future__ import print_function... |
print('#ifndef AEGEAN_VERSION_H')
print('#define AEGEAN_VERSION_H')
print('#define AGN_SEMANTIC_VERSION "%s"' % semver)
print('#define AGN_VERSION_STABILITY "%s"' % stability)
print('#define AGN_VERSION_HASH "%s"' % sha1)
print('#define AGN_VERSION_HASH_SLUG "%s"' % sha1slug)
print('#define AGN_VERSION_LINK ... | sha1match = re.search('commit (\S+)', logout)
assert sha1match, 'could not find latest commit SHA1 hash'
sha1 = sha1match.group(1)
sha1slug = sha1[:10]
link = 'https://github.com/standage/AEGeAn/tree/' + sha1
yearmatch = re.search('Date:\s+.+(\d{4}) ', logout)
assert yearmatch, 'could not find ... | conditional_block |
version.py | #!/usr/bin/env python
# Copyright (c) 2010-2016, Daniel S. Standage and CONTRIBUTORS
#
# The AEGeAn Toolkit is distributed under the ISC License. See
# the 'LICENSE' file in the AEGeAn source code distribution or
# online at https://github.com/standage/AEGeAn/blob/master/LICENSE.
from __future__ import print_function... | sha1slug = sha1[:10]
link = 'https://github.com/standage/AEGeAn/tree/' + sha1
yearmatch = re.search('Date:\s+.+(\d{4}) ', logout)
assert yearmatch, 'could not find year of latest commit'
year = yearmatch.group(1)
print('#ifndef AEGEAN_VERSION_H')
print('#define AEGEAN_VERSION_H')
print('#define AG... | sha1match = re.search('commit (\S+)', logout)
assert sha1match, 'could not find latest commit SHA1 hash'
sha1 = sha1match.group(1) | random_line_split |
issue-3350.ts | import "reflect-metadata";
import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
import {Connection} from "../../../src/connection/Connection";
import {Category} from "./entity/Category";
import {Post} from "./entity/Post";
import {expect} from "chai";
descri... | let connections: Connection[];
before(async () => connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
subscribers: [__dirname + "/subscriber/*{.js,.ts}"],
enabledDrivers: ["mysql"],
}));
beforeEach(() => reloadTestingDatabases(connections)... | random_line_split | |
debugLauncher.ts | import { inject, injectable, named } from 'inversify';
import * as path from 'path';
import { DebugConfiguration, Uri, WorkspaceFolder } from 'vscode';
import { IApplicationShell, IDebugService, IWorkspaceService } from '../../common/application/types';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
impo... | (options: LaunchOptions) {
if (options.token && options.token.isCancellationRequested) {
return;
}
const workspaceFolder = this.resolveWorkspaceFolder(options.cwd);
const launchArgs = await this.getLaunchArgs(
options,
workspaceFolder,
thi... | launchDebugger | identifier_name |
debugLauncher.ts | import { inject, injectable, named } from 'inversify';
import * as path from 'path';
import { DebugConfiguration, Uri, WorkspaceFolder } from 'vscode';
import { IApplicationShell, IDebugService, IWorkspaceService } from '../../common/application/types';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
impo... |
if (!cfg.env) {
cfg.env = {};
}
if (!cfg.envFile) {
cfg.envFile = configSettings.envFile;
}
if (cfg.stopOnEntry === undefined) {
cfg.stopOnEntry = false;
}
cfg.showReturnValue = cfg.showReturnValue !== false;
if (cfg.r... | {
cfg.cwd = workspaceFolder.uri.fsPath;
} | conditional_block |
debugLauncher.ts | import { inject, injectable, named } from 'inversify';
import * as path from 'path';
import { DebugConfiguration, Uri, WorkspaceFolder } from 'vscode';
import { IApplicationShell, IDebugService, IWorkspaceService } from '../../common/application/types';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
impo... |
private getTestLauncherScript(testProvider: TestProvider) {
switch (testProvider) {
case 'unittest': {
return internalScripts.visualstudio_py_testlauncher;
}
case 'pytest': {
return internalScripts.testlauncher;
}
... | {
if (testProvider === 'unittest') {
return args.filter((item) => item !== '--debug');
} else {
return args;
}
} | identifier_body |
debugLauncher.ts | import { inject, injectable, named } from 'inversify';
import * as path from 'path';
import { DebugConfiguration, Uri, WorkspaceFolder } from 'vscode';
import { IApplicationShell, IDebugService, IWorkspaceService } from '../../common/application/types';
import { EXTENSION_ROOT_DIR } from '../../common/constants';
impo... | return [];
}
}
private resolveWorkspaceFolder(cwd: string): WorkspaceFolder {
if (!this.workspaceService.hasWorkspaceFolders) {
throw new Error('Please open a workspace');
}
const cwdUri = cwd ? Uri.file(cwd) : undefined;
let workspaceFolder = thi... | traceError('could not get debug config', exc);
const appShell = this.serviceContainer.get<IApplicationShell>(IApplicationShell);
await appShell.showErrorMessage(
'Could not load unit test config from launch.json as it is missing a field',
); | random_line_split |
day4.rs | // thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7
// for the optimizations
use crypto::md5::Md5;
use crypto::digest::Digest;
const INPUT: &'static str = "iwrupvqb";
pub fn | () -> u64 {
calculate_part1(INPUT.as_bytes())
}
pub fn part2() -> u64 {
calculate_part2(INPUT.as_bytes())
}
fn calculate_part1(input: &[u8]) -> u64 {
let mut hasher = Md5::new();
for i in 0..::std::u64::MAX {
hasher.input(input);
hasher.input(i.to_string().as_bytes());
let mu... | part1 | identifier_name |
day4.rs | // thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7
// for the optimizations
use crypto::md5::Md5;
use crypto::digest::Digest;
const INPUT: &'static str = "iwrupvqb";
pub fn part1() -> u64 {
calculate_part1(INPUT.as_bytes())
}
pub fn part2() -> u64 {
calculate_part2(INPUT.as_bytes())
}
fn calcu... |
hasher.reset();
}
panic!("The mining operation has failed!");
}
fn calculate_part2(input: &[u8]) -> u64 {
let mut hasher = Md5::new();
for i in 0..::std::u64::MAX {
hasher.input(input);
hasher.input(i.to_string().as_bytes());
let mut output = [0; 16];
hasher... | {
return i
} | conditional_block |
day4.rs | // thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7
// for the optimizations
use crypto::md5::Md5;
use crypto::digest::Digest;
const INPUT: &'static str = "iwrupvqb";
pub fn part1() -> u64 {
calculate_part1(INPUT.as_bytes())
}
pub fn part2() -> u64 {
calculate_part2(INPUT.as_bytes())
}
fn calcu... | fn test1() {
assert_eq!(609043, super::calculate_part1("abcdef".as_bytes()));
}
#[test]
fn test2() {
assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes()));
}
} |
#[cfg(test)]
mod tests {
#[test] | random_line_split |
day4.rs | // thanks to https://gist.github.com/gkbrk/2e4835e3a17b3fb6e1e7
// for the optimizations
use crypto::md5::Md5;
use crypto::digest::Digest;
const INPUT: &'static str = "iwrupvqb";
pub fn part1() -> u64 {
calculate_part1(INPUT.as_bytes())
}
pub fn part2() -> u64 {
calculate_part2(INPUT.as_bytes())
}
fn calcu... |
}
| {
assert_eq!(1048970, super::calculate_part1("pqrstuv".as_bytes()));
} | identifier_body |
navigation.js | /* IIPMooViewer Navigation Widget
Copyright (c) 2007-2013 Ruven Pillay <ruven@users.sourceforge.net>
IIPImage: http://iipimage.sourceforge.net
--------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify
it under the terms of ... |
var border = this.zone.offsetHeight - this.zone.clientHeight;
// Move the zone to the new size and position
this.zone.morph({
fps: 30,
left: pleft,
top: (this.standalone) ? ptop : ptop + 8, // 8 is the height of toolbar
width: (width-border>0)? width - border : 1, // Watch out for ... | random_line_split | |
list.js | /*global jQuery, window*/
$(document).ready(function () {
$('#addreview').on('click', '#btn-addreview', function (e) {
e.preventDefault();
var $form = $('#form-addreview');
if (!$form.valid || $form.valid()) {
$.post($form.attr('action'), $form.serializeArray())
... | });
$('#reviews').on('click', '.btn-view-review-replies', function (e) {
var $parent = $(this).parent();
$(this).addClass('d-none');
$parent.find('.review-replies').removeClass('d-none');
$parent.find('.btn-hide-review-replies').removeClass('d-none');
});
$('#reviews').o... | $.post($form.attr('action'), $form.serializeArray())
.done(function (result) {
$(that).closest('.add-review-reply').html(result);
});
}
| conditional_block |
list.js | /*global jQuery, window*/
$(document).ready(function () {
$('#addreview').on('click', '#btn-addreview', function (e) {
e.preventDefault();
var $form = $('#form-addreview');
if (!$form.valid || $form.valid()) {
$.post($form.attr('action'), $form.serializeArray())
... | var $parent = $(this).parent();
$(this).addClass('d-none');
$parent.find('.review-replies').addClass('d-none');
$parent.find('.btn-view-review-replies').removeClass('d-none');
});
$('#reviews').on('click', '.btn-add-review-reply', function (e) {
$('.add-review-reply').ad... | $parent.find('.btn-hide-review-replies').removeClass('d-none');
});
$('#reviews').on('click', '.btn-hide-review-replies', function (e) { | random_line_split |
flag_changer.py | # Copyright (c) 2012 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.
import logging
from devil.android import device_errors
class FlagChanger(object):
"""Changes the flags Chrome runs with.
There are two different ... |
elif not within_quotations and (c is ' ' or c is '\t'):
if current_flag is not "":
tokenized_flags.append(current_flag)
current_flag = ""
else:
current_flag += c
# Tack on the last flag.
if not current_flag:
if within_quotations:
logging.warn('Unte... | within_quotations = not within_quotations
current_flag += c | conditional_block |
flag_changer.py | # Copyright (c) 2012 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.
import logging
from devil.android import device_errors
class FlagChanger(object):
"""Changes the flags Chrome runs with.
There are two different ... | else:
tokenized_flags.append(current_flag)
# Return everything but the program name.
return tokenized_flags[1:] | random_line_split | |
flag_changer.py | # Copyright (c) 2012 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.
import logging
from devil.android import device_errors
class FlagChanger(object):
"""Changes the flags Chrome runs with.
There are two different ... | (self, flags):
"""Replaces all flags on the current command line with the flags given.
Args:
flags: A list of flags to set, eg. ['--single-process'].
"""
if flags:
assert flags[0] != 'chrome'
self._current_flags = flags
self._UpdateCommandLineFile()
def AddFlags(self, flags):
... | Set | identifier_name |
flag_changer.py | # Copyright (c) 2012 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.
import logging
from devil.android import device_errors
class FlagChanger(object):
"""Changes the flags Chrome runs with.
There are two different ... |
def _UpdateCommandLineFile(self):
"""Writes out the command line to the file, or removes it if empty."""
logging.info('Current flags: %s', self._current_flags)
# Root is not required to write to /data/local/tmp/.
use_root = '/data/local/tmp/' not in self._cmdline_file
if self._current_flags:
... | """Restores the flags to their original state."""
self._current_flags = self._TokenizeFlags(self._orig_line)
self._UpdateCommandLineFile() | identifier_body |
app.module.ts | // #docplaster
import { NgModule } from '@angular/core';
// #docregion animations-module
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// #enddocregion animations-module
import { HeroTeamBuilderComponent } from './hero-team-bu... | HeroListEnterLeaveComponent,
HeroListEnterLeaveStatesComponent,
HeroListAutoComponent,
HeroListTimingsComponent,
HeroListMultistepComponent,
HeroListGroupsComponent
],
bootstrap: [ HeroTeamBuilderComponent ]
// #docregion animations-module
})
export class AppModule { }
// #enddocregion anima... | random_line_split | |
app.module.ts | // #docplaster
import { NgModule } from '@angular/core';
// #docregion animations-module
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// #enddocregion animations-module
import { HeroTeamBuilderComponent } from './hero-team-bu... | { }
// #enddocregion animations-module
| AppModule | identifier_name |
annoyer.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... | elf):
Middleware.stop(self)
if self._thread:
self._running = False
self._thread.join()
self._thread = None
def _run(self):
self._initial = datetime.datetime.utcnow()
self._running = True
while self._running:
delta = ... | op(s | identifier_name |
annoyer.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... | lf._initial = datetime.datetime.utcnow()
self._running = True
while self._running:
delta = datetime.datetime.utcnow() - self._initial
delta_s = self.owner._format_delta(delta)
message = "Uptime => %s | Connections => %d\n" %\
(delta_s, len(self.o... | identifier_body | |
annoyer.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... | lta = datetime.datetime.utcnow() - self._initial
delta_s = self.owner._format_delta(delta)
message = "Uptime => %s | Connections => %d\n" %\
(delta_s, len(self.owner.connections))
sys.stdout.write(message)
sys.stdout.flush()
time.sleep(se... | conditional_block | |
annoyer.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2020 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foun... |
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2020 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import sys
import time
import datetime
import threa... | __revision__ = "$LastChangedRevision$"
""" The revision number of the module """
| random_line_split |
config.py | # Copyright 2012 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 agre... | config.register_agent_state_opts_helper(cfg.CONF)
config.register_root_helper(cfg.CONF) | ]
cfg.CONF.register_opts(ovs_opts, "OVS")
cfg.CONF.register_opts(agent_opts, "AGENT") | random_line_split |
specified_value_info.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/. */
//! Value information for devtools.
use servo_arc::Arc;
use std::ops::Range;
use std::sync::Arc as StdArc;
/// T... | macro_rules! impl_generic_specified_value_info {
($ty:ident<$param:ident>) => {
impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> {
const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES;
fn collect_completion_keywords(f: KeywordsCollectFn) {
$param::co... | }
}
| random_line_split |
specified_value_info.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/. */
//! Value information for devtools.
use servo_arc::Arc;
use std::ops::Range;
use std::sync::Arc as StdArc;
/// T... | (f: KeywordsCollectFn) {
T::collect_completion_keywords(f);
}
}
macro_rules! impl_generic_specified_value_info {
($ty:ident<$param:ident>) => {
impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> {
const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES;
fn c... | collect_completion_keywords | identifier_name |
specified_value_info.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/. */
//! Value information for devtools.
use servo_arc::Arc;
use std::ops::Range;
use std::sync::Arc as StdArc;
/// T... |
}
macro_rules! impl_generic_specified_value_info {
($ty:ident<$param:ident>) => {
impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> {
const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES;
fn collect_completion_keywords(f: KeywordsCollectFn) {
$param... | {
T::collect_completion_keywords(f);
} | identifier_body |
events.rs | //! Contains `XmlEvent` datatype, instances of which are emitted by the parser.
use std::fmt;
use name::OwnedName;
use attribute::OwnedAttribute;
use common::{HasPosition, XmlVersion};
use common::Error as CommonError;
use namespace::Namespace;
/// An element of an XML input stream.
///
/// Items of this... |
/// XML standalone declaration.
///
/// If XML document is not present or does not contain `standalone` attribute,
/// defaults to `None`. This field is currently used for no other purpose than
/// informational.
standalone: Option<bool>
},
/// Denotes ... | encoding: String,
| random_line_split |
events.rs | //! Contains `XmlEvent` datatype, instances of which are emitted by the parser.
use std::fmt;
use name::OwnedName;
use attribute::OwnedAttribute;
use common::{HasPosition, XmlVersion};
use common::Error as CommonError;
use namespace::Namespace;
/// An element of an XML input stream.
///
/// Items of this... |
}
| {
match *self {
XmlEvent::StartDocument { version, ref encoding, standalone } =>
Some(::writer::events::XmlEvent::StartDocument {
version: version,
encoding: Some(encoding.as_slice()),
standalone: standalone
... | identifier_body |
events.rs | //! Contains `XmlEvent` datatype, instances of which are emitted by the parser.
use std::fmt;
use name::OwnedName;
use attribute::OwnedAttribute;
use common::{HasPosition, XmlVersion};
use common::Error as CommonError;
use namespace::Namespace;
/// An element of an XML input stream.
///
/// Items of this... | <'a>(&'a self) -> Option<::writer::events::XmlEvent<'a>> {
match *self {
XmlEvent::StartDocument { version, ref encoding, standalone } =>
Some(::writer::events::XmlEvent::StartDocument {
version: version,
encoding: Some(encoding.as_slice()... | as_writer_event | identifier_name |
filemanager_thread.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::create_embedder_proxy;
use embedder_traits::FilterPattern;
use ipc_channel::ipc;
use net::filemanager_... | {
let pool = CoreResourceThreadPool::new(1);
let pool_handle = Arc::new(pool);
let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle));
set_pref!(dom.testing.html_input_element.select_files.enabled, true);
// Try to open a dummy file "components/net/tests/test.jpeg... | identifier_body | |
filemanager_thread.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::create_embedder_proxy;
use embedder_traits::FilterPattern;
use ipc_channel::ipc;
use net::filemanager_... |
}
// Delete the id
{
let (tx2, rx2) = ipc::channel().unwrap();
filemanager.handle(FileManagerThreadMsg::DecRef(
selected.id.clone(),
origin.clone(),
tx2,
));
let ret = rx2.recv().expect("Broken cha... | {
panic!("Invalid FileManager reply");
} | conditional_block |
filemanager_thread.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::create_embedder_proxy;
use embedder_traits::FilterPattern;
use ipc_channel::ipc;
use net::filemanager_... | );
},
}
}
}
} | assert!(
false,
"Get unexpected response after deleting the id: {:?}",
other | random_line_split |
filemanager_thread.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::create_embedder_proxy;
use embedder_traits::FilterPattern;
use ipc_channel::ipc;
use net::filemanager_... | () {
let pool = CoreResourceThreadPool::new(1);
let pool_handle = Arc::new(pool);
let filemanager = FileManager::new(create_embedder_proxy(), Arc::downgrade(&pool_handle));
set_pref!(dom.testing.html_input_element.select_files.enabled, true);
// Try to open a dummy file "components/net/tests/test.j... | test_filemanager | identifier_name |
client.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | sc.set_incarnation(incarnation);
sc.set_encrypted(encrypted);
self.send(sc)
}
/// Create a service file and send it to the server.
pub fn send_service_file<S: Into<String>>(
&mut self,
service_group: ServiceGroup,
filename: S,
incarnation: u64,
... | config: Vec<u8>,
encrypted: bool,
) -> Result<()> {
let mut sc = ServiceConfig::new("butterflyclient", service_group, config); | random_line_split |
client.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... | {
socket: zmq::Socket,
ring_key: Option<SymKey>,
}
impl Client {
/// Connect this client to the address, and optionally encrypt the traffic.
pub fn new<A>(addr: A, ring_key: Option<SymKey>) -> Result<Client>
where
A: ToString,
{
let socket = (**ZMQ_CONTEXT)
.as_mut(... | Client | identifier_name |
client.rs | // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// 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
//
// Unl... |
/// Send any `Rumor` to the server.
pub fn send<T: Rumor>(&mut self, rumor: T) -> Result<()> {
let bytes = rumor.write_to_bytes()?;
let wire_msg = message::generate_wire(bytes, self.ring_key.as_ref())?;
self.socket.send(&wire_msg, 0).map_err(Error::ZmqSendError)
}
}
| {
let mut sf = ServiceFile::new("butterflyclient", service_group, filename, body);
sf.set_incarnation(incarnation);
sf.set_encrypted(encrypted);
self.send(sf)
} | identifier_body |
lowerupper_pipe.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 {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {... | (value: string) { this.value = value; }
}
// #enddocregion
| change | identifier_name |
confirmpopup.ts | import {NgModule ,Component, ChangeDetectionStrategy, ViewEncapsulation, ElementRef, ChangeDetectorRef, OnDestroy, Input, EventEmitter, Renderer2} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Confirmation, ConfirmationService, PrimeNGConfig, TranslationKeys} from 'primeng/api';
import {Su... | () {
if (this.confirmation.acceptEvent) {
this.confirmation.acceptEvent.emit();
}
this.hide();
}
reject() {
if (this.confirmation.rejectEvent) {
this.confirmation.rejectEvent.emit();
}
this.hide();
}
bindListeners() {
th... | accept | identifier_name |
confirmpopup.ts | import {NgModule ,Component, ChangeDetectionStrategy, ViewEncapsulation, ElementRef, ChangeDetectorRef, OnDestroy, Input, EventEmitter, Renderer2} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Confirmation, ConfirmationService, PrimeNGConfig, TranslationKeys} from 'primeng/api';
import {Su... |
onAnimationStart(event: AnimationEvent) {
if (event.toState === 'open') {
this.container = event.element;
document.body.appendChild(this.container);
this.align();
this.bindListeners();
}
}
onAnimationEnd(event: AnimationEvent) {
swit... | {
this.subscription = this.confirmationService.requireConfirmation$.subscribe(confirmation => {
if (!confirmation) {
this.hide();
return;
}
if (confirmation.key === this.key) {
this.confirmation = confirmation;
... | identifier_body |
confirmpopup.ts | import {NgModule ,Component, ChangeDetectionStrategy, ViewEncapsulation, ElementRef, ChangeDetectorRef, OnDestroy, Input, EventEmitter, Renderer2} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Confirmation, ConfirmationService, PrimeNGConfig, TranslationKeys} from 'primeng/api';
import {Su... |
}
unsubscribeConfirmationSubscriptions() {
if (this.confirmation) {
if (this.confirmation.acceptEvent) {
this.confirmation.acceptEvent.unsubscribe();
}
if (this.confirmation.rejectEvent) {
this.confirmation.rejectEvent.unsubscribe();... | {
this.scrollHandler.unbindScrollListener();
} | conditional_block |
confirmpopup.ts | import {NgModule ,Component, ChangeDetectionStrategy, ViewEncapsulation, ElementRef, ChangeDetectorRef, OnDestroy, Input, EventEmitter, Renderer2} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Confirmation, ConfirmationService, PrimeNGConfig, TranslationKeys} from 'primeng/api';
import {Su... | (@animation.start)="onAnimationStart($event)" (@animation.done)="onAnimationEnd($event)">
<div #content class="p-confirm-popup-content">
<i [ngClass]="'p-confirm-popup-icon'" [class]="confirmation.icon" *ngIf="confirmation.icon"></i>
<span class="p-confirm-popup-m... | <div *ngIf="visible" [ngClass]="'p-confirm-popup p-component'" [ngStyle]="style" [class]="styleClass"
[@animation]="{value: 'open', params: {showTransitionParams: showTransitionOptions, hideTransitionParams: hideTransitionOptions}}" | random_line_split |
castep_interface.py | #!/usr/bin/python
"""Simple shallow test of the CASTEP interface"""
import os
import shutil
import tempfile
import traceback
from ase.test import NotAvailable
# check if CASTEP_COMMAND is set a environment variable
if not os.environ.has_key('CASTEP_COMMAND'):
print("WARNING: Environment variable CASTEP_COMMAND ... | param_fn = os.path.join(tmp_dir, 'myParam.param')
param = open(param_fn,'w')
param.write('XC_FUNCTIONAL : PBE #comment\n')
param.write('XC_FUNCTIONAL : PBE #comment\n')
param.write('#comment\n')
param.write('CUT_OFF_ENERGY : 450.\n')
param.close()
try:
c.merge_param(param_fn)
except Exception, e:
traceback.prin... | print(e)
assert False, "Cannot create castep_keywords, this usually means a bug"\
+ " in the interface or the castep binary cannot be called"
| random_line_split |
castep_interface.py | #!/usr/bin/python
"""Simple shallow test of the CASTEP interface"""
import os
import shutil
import tempfile
import traceback
from ase.test import NotAvailable
# check if CASTEP_COMMAND is set a environment variable
if not os.environ.has_key('CASTEP_COMMAND'):
print("WARNING: Environment variable CASTEP_COMMAND ... |
c.prepare_input_files(lattice)
os.chdir(cwd)
shutil.rmtree(tmp_dir)
print("Test finished without errors") | print("Dryrun is ok") | conditional_block |
impl.ts | import LogaryPlugin, { PluginAPI } from "./plugin"
import RuntimeInfo from './runtimeInfo'
import { ensureMessageId, adaptLogFunction } from './utils'
import { Config } from './config'
import { EventFunction, SetUserPropertyFunction, IdentifyUserFunction, ForgetUserFunction, ValueOf } from './types'
import { ForgetUser... |
identify: IdentifyUserFunction = (...args: unknown[]) => {
// @ts-ignore TO CONSIDER: passing along user id
const m = createIdentifyMessage(null, ...args)
this.log(LogLevel.info, m)
}
forgetUser: ForgetUserFunction = (...args: unknown[]) => {
const uId = args[0] as st... | setUserProperty: SetUserPropertyFunction = (userId: string, key: string, value: unknown) => {
const m = new SetUserPropertyMessage(userId, key, value, this.name, getTimestamp())
this.log(LogLevel.info, m)
} | random_line_split |
impl.ts | import LogaryPlugin, { PluginAPI } from "./plugin"
import RuntimeInfo from './runtimeInfo'
import { ensureMessageId, adaptLogFunction } from './utils'
import { Config } from './config'
import { EventFunction, SetUserPropertyFunction, IdentifyUserFunction, ForgetUserFunction, ValueOf } from './types'
import { ForgetUser... |
/**
* Gets the configured application id for this app.
*/
get appId() {
return this.config.appId
}
/**
* Gets the current Logary state: 'initial' | 'started' | 'closed'
*/
get state() {
return this._state
}
}
| {
return this.config.debug
} | identifier_body |
impl.ts | import LogaryPlugin, { PluginAPI } from "./plugin"
import RuntimeInfo from './runtimeInfo'
import { ensureMessageId, adaptLogFunction } from './utils'
import { Config } from './config'
import { EventFunction, SetUserPropertyFunction, IdentifyUserFunction, ForgetUserFunction, ValueOf } from './types'
import { ForgetUser... | () {
return Array.isArray(this.config.serviceName)
? this.config.serviceName
: [ this.config.serviceName ]
}
get serviceVersion() {
return this.config.serviceVersion
}
get targets() {
return this.config.targets
}
/**
* Gets the lowest level of logs that Logary send to the backe... | serviceName | identifier_name |
recycle.rs | //! Recycle allocator
//! Uses freed frames if possible, then uses inner allocator
use alloc::Vec;
use paging::PhysicalAddress;
use super::{Frame, FrameAllocator};
pub struct RecycleAllocator<T: FrameAllocator> {
inner: T,
noncore: bool,
free: Vec<(usize, usize)>,
}
impl<T: FrameAllocator> RecycleAlloc... | (&mut self, count: usize) -> Option<Frame> {
let mut small_i = None;
{
let mut small = (0, 0);
for i in 0..self.free.len() {
let free = self.free[i];
// Later entries can be removed faster
if free.1 >= count {
if... | allocate_frames | identifier_name |
recycle.rs | //! Recycle allocator
//! Uses freed frames if possible, then uses inner allocator
use alloc::Vec;
use paging::PhysicalAddress;
use super::{Frame, FrameAllocator};
pub struct RecycleAllocator<T: FrameAllocator> {
inner: T,
noncore: bool,
free: Vec<(usize, usize)>,
}
impl<T: FrameAllocator> RecycleAlloc... | // Later entries can be removed faster
if free.1 >= count {
if free.1 <= small.1 || small_i.is_none() {
small_i = Some(i);
small = free;
}
}
}
}
if let Som... | for i in 0..self.free.len() {
let free = self.free[i]; | random_line_split |
recycle.rs | //! Recycle allocator
//! Uses freed frames if possible, then uses inner allocator
use alloc::Vec;
use paging::PhysicalAddress;
use super::{Frame, FrameAllocator};
pub struct RecycleAllocator<T: FrameAllocator> {
inner: T,
noncore: bool,
free: Vec<(usize, usize)>,
}
impl<T: FrameAllocator> RecycleAlloc... |
return true;
}
}
false
}
}
impl<T: FrameAllocator> FrameAllocator for RecycleAllocator<T> {
fn set_noncore(&mut self, noncore: bool) {
self.noncore = noncore;
}
fn free_frames(&self) -> usize {
self.inner.free_frames() + self.free_count()
... | {
self.free.remove(i);
} | conditional_block |
recycle.rs | //! Recycle allocator
//! Uses freed frames if possible, then uses inner allocator
use alloc::Vec;
use paging::PhysicalAddress;
use super::{Frame, FrameAllocator};
pub struct RecycleAllocator<T: FrameAllocator> {
inner: T,
noncore: bool,
free: Vec<(usize, usize)>,
}
impl<T: FrameAllocator> RecycleAlloc... |
fn deallocate_frames(&mut self, frame: Frame, count: usize) {
if self.noncore {
let address = frame.start_address().get();
if ! self.merge(address, count) {
self.free.push((address, count));
}
} else {
//println!("Could not save frame... | {
let mut small_i = None;
{
let mut small = (0, 0);
for i in 0..self.free.len() {
let free = self.free[i];
// Later entries can be removed faster
if free.1 >= count {
if free.1 <= small.1 || small_i.is_none() {
... | identifier_body |
zepto.touch.js | define(function(require, exports, module) {
require('vendor/zepto/zepto');
var $ = window.Zepto;
// Zepto.js
// (c) 2010-2014 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var touch = {},
touchTimeout,
tapTimeout,
swipeTimeout,
longTa... | () {
if (touchTimeout) clearTimeout(touchTimeout);
if (tapTimeout) clearTimeout(tapTimeout);
if (swipeTimeout) clearTimeout(swipeTimeout);
if (longTapTimeout) clearTimeout(longTapTimeout);
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
touch = {}
}
... | cancelAll | identifier_name |
zepto.touch.js | define(function(require, exports, module) {
require('vendor/zepto/zepto');
var $ = window.Zepto;
// Zepto.js
// (c) 2010-2014 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var touch = {},
touchTimeout,
tapTimeout,
swipeTimeout,
longTa... |
}
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout);
longTapTimeout = null;
}
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout);
if (tapTimeout) clearTimeout(tapTimeout);
if (swipeTimeout) clearTimeout(swipeTimeout);
... | {
touch.el.trigger('longTap');
touch = {}
} | conditional_block |
zepto.touch.js | define(function(require, exports, module) {
require('vendor/zepto/zepto');
var $ = window.Zepto;
// Zepto.js
// (c) 2010-2014 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var touch = {},
touchTimeout,
tapTimeout,
swipeTimeout,
longTa... | }
function cancelLongTap() {
if (longTapTimeout) clearTimeout(longTapTimeout);
longTapTimeout = null;
}
function cancelAll() {
if (touchTimeout) clearTimeout(touchTimeout);
if (tapTimeout) clearTimeout(tapTimeout);
if (swipeTimeout) clearTimeout(swipeTimeout);
... | touch = {}
} | random_line_split |
zepto.touch.js | define(function(require, exports, module) {
require('vendor/zepto/zepto');
var $ = window.Zepto;
// Zepto.js
// (c) 2010-2014 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
var touch = {},
touchTimeout,
tapTimeout,
swipeTimeout,
longTa... |
function isPrimaryTouch(event) {
return (event.pointerType == 'touch' ||
event.pointerType == event.MSPOINTER_TYPE_TOUCH)
&& event.isPrimary;
}
function isPointerEventType(e, type) {
return (e.type == 'pointer' + type ||
e.type.toLowerCase() == 'mspoint... | {
if (touchTimeout) clearTimeout(touchTimeout);
if (tapTimeout) clearTimeout(tapTimeout);
if (swipeTimeout) clearTimeout(swipeTimeout);
if (longTapTimeout) clearTimeout(longTapTimeout);
touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null;
touch = {}
} | identifier_body |
ontology.py | # This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | return client.call(
messages.OntologySignOntIdAddAttributes(
address_n=address_n, transaction=t, ont_id_add_attributes=a
)
) | identifier_body | |
ontology.py | # This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | from . import messages
from .tools import expect
#
# Ontology functions
#
@expect(messages.OntologyAddress, field="address")
def get_address(client, address_n, show_display=False):
return client.call(
messages.OntologyGetAddress(address_n=address_n, show_display=show_display)
)
@expect(messages.Ont... | random_line_split | |
ontology.py | # This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | (client, address_n, t, tr):
return client.call(
messages.OntologySignTransfer(address_n=address_n, transaction=t, transfer=tr)
)
@expect(messages.OntologySignedWithdrawOng)
def sign_withdrawal(client, address_n, t, w):
return client.call(
messages.OntologySignWithdrawOng(
addre... | sign_transfer | identifier_name |
decoder.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def _create_zero_outputs(size, dtype, batch_size):
"""Create a zero outputs Tensor structure."""
def _t(s):
return (s if isinstance(s, ops.Tensor) else constant_op.constant(
tensor_shape.TensorShape(s).as_list(),
dtype=dtypes.int32,
name="zero_suffix_shape"))
def _create(s, d):
... | raise NotImplementedError | identifier_body |
decoder.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (s, d):
return tensor_array_ops.TensorArray(
dtype=d,
size=0,
dynamic_size=True,
element_shape=_shape(decoder.batch_size, s))
initial_outputs_ta = nest.map_structure(_create_ta, decoder.output_size,
decoder.output_dtype)
... | _create_ta | identifier_name |
decoder.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out),
outputs_ta, emit)
return (time + 1, outputs_ta, next_state, next_inputs, next_finished,
next_sequence_lengths)
res = control_flow_ops.while_loop(
condition,
body,
... | next_state = decoder_state | conditional_block |
decoder.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | next_state = decoder_state
outputs_ta = nest.map_structure(lambda ta, out: ta.write(time, out),
outputs_ta, emit)
return (time + 1, outputs_ta, next_state, next_inputs, next_finished,
next_sequence_lengths)
res = control_flow_ops.while_loop(
... |
if impute_finished:
next_state = nest.map_structure(
_maybe_copy_state, decoder_state, state)
else: | random_line_split |
webhook.py | #!/usr/bin/env python
"""
Copyright (C) 2012 Bo Zhu http://zhuzhu.org
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rig... | (tornado.web.RequestHandler):
def post(self):
if self.request.remote_ip not in GitHub_POST_IPs:
self.send_error(status_code=403)
return
self.finish() # is this necessary?
payload = json_decode(self.get_argument('payload'))
repo_name = payload['repository'][... | GithubHookHandler | identifier_name |
webhook.py | #!/usr/bin/env python
"""
Copyright (C) 2012 Bo Zhu http://zhuzhu.org
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rig... |
if __name__ == "__main__":
application.listen(80)
import tornado.ioloop
ioloop = tornado.ioloop.IOLoop.instance()
import tornado.autoreload
tornado.autoreload.start(ioloop)
ioloop.start() | ]) | random_line_split |
webhook.py | #!/usr/bin/env python
"""
Copyright (C) 2012 Bo Zhu http://zhuzhu.org
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rig... |
self.finish() # is this necessary?
payload = json_decode(self.get_argument('payload'))
repo_name = payload['repository']['name']
deploy.deploy(repo_name)
application = tornado.web.Application([
(r"/", GithubHookHandler)
])
if __name__ == "__main__":
application.listen(80)... | self.send_error(status_code=403)
return | conditional_block |
webhook.py | #!/usr/bin/env python
"""
Copyright (C) 2012 Bo Zhu http://zhuzhu.org
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rig... |
application = tornado.web.Application([
(r"/", GithubHookHandler)
])
if __name__ == "__main__":
application.listen(80)
import tornado.ioloop
ioloop = tornado.ioloop.IOLoop.instance()
import tornado.autoreload
tornado.autoreload.start(ioloop)
ioloop.start()
| if self.request.remote_ip not in GitHub_POST_IPs:
self.send_error(status_code=403)
return
self.finish() # is this necessary?
payload = json_decode(self.get_argument('payload'))
repo_name = payload['repository']['name']
deploy.deploy(repo_name) | identifier_body |
go.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd... |
return {
startState: function(basecolumn) {
return {
tokenize: null,
context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
indented: 0,
startOfLine: true
};
},
token: function(stream, state) {
var ctx = state.context;
... | }
// Interface
| random_line_split |
go.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd... | (stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'" || ch == "`") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
}
if (/[\d\.]/.test(ch)) {
if (ch == ".") {
stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
} else if (ch == "... | tokenBase | identifier_name |
go.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd... |
function Context(indented, column, type, align, prev) {
this.indented = indented;
this.column = column;
this.type = type;
this.align = align;
this.prev = prev;
}
function pushContext(state, col, type) {
return state.context = new Context(state.indented, col, type, null, state.c... | {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return "comment";
} | identifier_body |
PerformanceCounter.ts |
// tslint:disable-next-line:interface-name
export interface PerformanceObservedCounters {
StartedAt: Date; FinishedAt?: Date; ElapsedTime: number; Name: string|symbol;
}
export class PerformanceCounter {
private static timers = new Map<string|symbol, PerformanceObservedCounters>();
// tslint:disable-next-... |
// tslint:disable-next-line:member-ordering
public static finish(id: string|symbol): PerformanceObservedCounters {
const pt = PerformanceCounter.timers.get(id);
if (pt) {
pt.FinishedAt = new Date();
pt.ElapsedTime = pt.FinishedAt.getTime() - pt.StartedAt.getTime();
... | {
// tslint:disable-next-line:new-parens
const pt = {StartedAt: new Date, Name: id, ElapsedTime: 0};
PerformanceCounter.timers.set(id, pt);
return pt;
} | identifier_body |
PerformanceCounter.ts |
// tslint:disable-next-line:interface-name
export interface PerformanceObservedCounters {
StartedAt: Date; FinishedAt?: Date; ElapsedTime: number; Name: string|symbol;
}
export class PerformanceCounter {
private static timers = new Map<string|symbol, PerformanceObservedCounters>();
// tslint:disable-next-... |
return pt;
}
}
| {
pt.FinishedAt = new Date();
pt.ElapsedTime = pt.FinishedAt.getTime() - pt.StartedAt.getTime();
PerformanceCounter.timers.delete(id);
} | conditional_block |
PerformanceCounter.ts |
// tslint:disable-next-line:interface-name
export interface PerformanceObservedCounters {
StartedAt: Date; FinishedAt?: Date; ElapsedTime: number; Name: string|symbol;
}
export class PerformanceCounter {
private static timers = new Map<string|symbol, PerformanceObservedCounters>();
// tslint:disable-next-... | (id: string|symbol): PerformanceObservedCounters {
// tslint:disable-next-line:new-parens
const pt = {StartedAt: new Date, Name: id, ElapsedTime: 0};
PerformanceCounter.timers.set(id, pt);
return pt;
}
// tslint:disable-next-line:member-ordering
public static finish(id: strin... | start | identifier_name |
PerformanceCounter.ts | // tslint:disable-next-line:interface-name
export interface PerformanceObservedCounters {
StartedAt: Date; FinishedAt?: Date; ElapsedTime: number; Name: string|symbol;
}
export class PerformanceCounter {
private static timers = new Map<string|symbol, PerformanceObservedCounters>();
// tslint:disable-next-l... | pt.ElapsedTime = pt.FinishedAt.getTime() - pt.StartedAt.getTime();
PerformanceCounter.timers.delete(id);
}
return pt;
}
} | if (pt) {
pt.FinishedAt = new Date(); | random_line_split |
drcProcess.js | /**
* drcProcess
* Created by dcorns on 1/2/15.
*/
'use strict';
var RunApp = require('./runApp');
var Server = require('./server');
var parseInput = require('./parseInput');
var CommandList = require('./commandList');
var runApp = new RunApp();
var cmds = new CommandList();
cmds.add(['ls', 'pwd', 'service', 'ps']);... | cnn.write('Valid commands: ' + cmds.listCommands());
}
}
}
});
});
}); | random_line_split | |
drcProcess.js | /**
* drcProcess
* Created by dcorns on 1/2/15.
*/
'use strict';
var RunApp = require('./runApp');
var Server = require('./server');
var parseInput = require('./parseInput');
var CommandList = require('./commandList');
var runApp = new RunApp();
var cmds = new CommandList();
cmds.add(['ls', 'pwd', 'service', 'ps']);... |
else{
cnn.write('Valid commands: ' + cmds.listCommands());
}
}
}
});
});
});
| {
runApp.run(obj.params, cnn, obj.cmd);
} | conditional_block |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
from spack import *
class Guidance(MakefilePackage):
"""Guidance: Accurate detection of unreliable alig... |
def install(self, spac, prefix):
mkdir(prefix.bin)
install_tree('libs', prefix.bin.libs)
install_tree('programs', prefix.bin.programs)
install_tree('www', prefix.bin.www)
with working_dir(join_path('www', 'Guidance')): # copy without suffix
install('guidance.pl... | for dir in 'Guidance', 'Selecton', 'bioSequence_scripts_and_constants':
with working_dir(join_path('www', dir)):
files = glob.iglob('*.pl')
for file in files:
perl = FileFilter(file)
perl.filter('#!/usr/bin/perl -w', '#!/usr/bin/env per... | identifier_body |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
from spack import *
class Guidance(MakefilePackage):
"""Guidance: Accurate detection of unreliable alig... |
version('2.02', sha256='825e105dde526759fb5bda1cd539b24db0b90b8b586f26b1df74d9c5abaa7844')
depends_on('perl', type=('build', 'run'))
depends_on('perl-bioperl', type=('build', 'run'))
depends_on('ruby')
depends_on('prank')
depends_on('clustalw')
depends_on('mafft')
depends_on('muscle')
... |
homepage = "http://guidance.tau.ac.il/ver2/"
url = "http://guidance.tau.ac.il/ver2/guidance.v2.02.tar.gz" | random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
from spack import *
class Guidance(MakefilePackage):
"""Guidance: Accurate detection of unreliable alig... | (self, env):
env.prepend_path('PATH', prefix.bin.www.Guidance)
| setup_run_environment | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import glob
from spack import *
class Guidance(MakefilePackage):
"""Guidance: Accurate detection of unreliable alig... |
def install(self, spac, prefix):
mkdir(prefix.bin)
install_tree('libs', prefix.bin.libs)
install_tree('programs', prefix.bin.programs)
install_tree('www', prefix.bin.www)
with working_dir(join_path('www', 'Guidance')): # copy without suffix
install('guidance.pl... | with working_dir(join_path('www', dir)):
files = glob.iglob('*.pl')
for file in files:
perl = FileFilter(file)
perl.filter('#!/usr/bin/perl -w', '#!/usr/bin/env perl') | conditional_block |
test_autoupdate.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# Copyright 2015-2018 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>:
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
#... | def test_constructor(qapp):
client = autoupdate.PyPIVersionClient()
assert isinstance(client._client, httpclient.HTTPClient)
def test_get_version_success(qtbot):
"""Test get_version() when success is emitted."""
http_stub = HTTPGetStub(success=True)
client = autoupdate.PyPIVersionClient(client=htt... | self.success.emit(self._json)
else:
self.error.emit("error")
| random_line_split |
test_autoupdate.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# Copyright 2015-2018 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>:
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
#... | (qtbot):
"""Test get_version() when success is emitted."""
http_stub = HTTPGetStub(success=True)
client = autoupdate.PyPIVersionClient(client=http_stub)
with qtbot.assertNotEmitted(client.error):
with qtbot.waitSignal(client.success):
client.get_version('test')
assert http_stub... | test_get_version_success | identifier_name |
test_autoupdate.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# Copyright 2015-2018 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>:
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
#... |
def get(self, url):
self.url = url
if self._success:
self.success.emit(self._json)
else:
self.error.emit("error")
def test_constructor(qapp):
client = autoupdate.PyPIVersionClient()
assert isinstance(client._client, httpclient.HTTPClient)
def test_get_ve... | self._json = '{"info": {"version": "test"}}' | conditional_block |
test_autoupdate.py | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# Copyright 2015-2018 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>:
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
#... |
def test_get_version_success(qtbot):
"""Test get_version() when success is emitted."""
http_stub = HTTPGetStub(success=True)
client = autoupdate.PyPIVersionClient(client=http_stub)
with qtbot.assertNotEmitted(client.error):
with qtbot.waitSignal(client.success):
client.get_versio... | client = autoupdate.PyPIVersionClient()
assert isinstance(client._client, httpclient.HTTPClient) | identifier_body |
row.rs | use fallible_iterator::FallibleIterator;
use fallible_streaming_iterator::FallibleStreamingIterator;
use std::convert;
use super::{Error, Result, Statement};
use crate::types::{FromSql, FromSqlError, ValueRef};
/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless cons... |
#[cfg(feature = "i128_blob")]
FromSqlError::InvalidI128Size(_) => Error::InvalidColumnType(
idx,
self.stmt.column_name_unwrap(idx).into(),
value.data_type(),
),
#[cfg(feature = "uuid")]
FromSqlError::InvalidUuid... | {
Error::FromSqlConversionFailure(idx as usize, value.data_type(), err)
} | conditional_block |
row.rs | use fallible_iterator::FallibleIterator;
use fallible_streaming_iterator::FallibleStreamingIterator;
use std::convert;
use super::{Error, Result, Statement};
use crate::types::{FromSql, FromSqlError, ValueRef};
/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless cons... | #[inline]
fn advance(&mut self) -> Result<()> {
match self.stmt {
Some(ref stmt) => match stmt.step() {
Ok(true) => {
self.row = Some(Row { stmt });
Ok(())
}
Ok(false) => {
self.reset(... | type Item = Row<'stmt>;
| random_line_split |
row.rs | use fallible_iterator::FallibleIterator;
use fallible_streaming_iterator::FallibleStreamingIterator;
use std::convert;
use super::{Error, Result, Statement};
use crate::types::{FromSql, FromSqlError, ValueRef};
/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless cons... | <'stmt> {
pub(crate) stmt: Option<&'stmt Statement<'stmt>>,
row: Option<Row<'stmt>>,
}
impl<'stmt> Rows<'stmt> {
#[inline]
fn reset(&mut self) {
if let Some(stmt) = self.stmt.take() {
stmt.reset();
}
}
/// Attempt to get the next row from the query. Returns `Ok(Some... | Rows | identifier_name |
row.rs | use fallible_iterator::FallibleIterator;
use fallible_streaming_iterator::FallibleStreamingIterator;
use std::convert;
use super::{Error, Result, Statement};
use crate::types::{FromSql, FromSqlError, ValueRef};
/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless cons... |
/// Renamed to [`get_ref`](Row::get_ref).
#[deprecated = "Use [`get_ref`](Row::get_ref) instead."]
#[inline]
pub fn get_raw_checked<I: RowIndex>(&self, idx: I) -> Result<ValueRef<'_>> {
self.get_ref(idx)
}
/// Renamed to [`get_ref_unwrap`](Row::get_ref_unwrap).
#[deprecated = "Use... | {
self.get_ref(idx).unwrap()
} | identifier_body |
markdown_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def test_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actua... | (object):
@pytest.mark.parametrize(
"text,expected",
[
(
'<a href="https://example.org">example</a>',
'<a href="https://example.org" rel="nofollow noopener" target="_blank">example</a>',
),
# Don't add rel and target attrs to mailto... | TestSanitize | identifier_name |
markdown_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def test_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actua... | assert actual == expected | random_line_split | |
markdown_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def test_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actua... | actual = markdown.sanitize('<a href="https://example.org">Hello</a>')
expected = '<a href="https://example.org" rel="nofollow noopener" target="_blank">Hello</a>'
assert actual == expected | identifier_body | |
markdown_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def test_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actua... |
assert markdown.sanitize(text) == expected
@pytest.mark.parametrize(
"text,expected",
[
("<script>evil()</script>", "<script>evil()</script>"),
(
'<a href="#" onclick="evil()">foobar</a>',
'<a href="#" rel="nofollow noope... | expected = text | conditional_block |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# try:
# from setuptools import setup
# except ImportError:
# from distutils.core import setup
#from setuptools import setup
#from setuptools import Extension
from numpy.distutils.core import setup
from numpy.distutils.extension import Extension
import os |
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'sphinx',
'sphinx-fortran',
'numpy',
'scipy',
'pandas',
'matplotlib',
'PyYAML',
'utm'
]
test_requirements = [
'tox',
'pytest',
'coverall',
]
setup(
name='fusedwake',
versi... | import glob
with open('README.rst') as readme_file:
readme = readme_file.read() | random_line_split |
cast-enum-with-dtor.rs | // Copyright 2015 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 ... | {
assert_eq!(FLAG.load(Ordering::SeqCst), 0);
{
let e = E::C;
assert_eq!(e as u32, 2);
assert_eq!(FLAG.load(Ordering::SeqCst), 0);
}
assert_eq!(FLAG.load(Ordering::SeqCst), 1);
} | identifier_body | |
cast-enum-with-dtor.rs | // Copyright 2015 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 ... | enum E {
A = 0,
B = 1,
C = 2
}
static FLAG: atomic::AtomicUsize = atomic::AtomicUsize::new(0);
impl Drop for E {
fn drop(&mut self) {
// avoid dtor loop
unsafe { mem::forget(mem::replace(self, E::B)) };
FLAG.store(FLAG.load(Ordering::SeqCst)+1, Ordering::SeqCst);
}
}
fn m... |
use std::sync::atomic;
use std::sync::atomic::Ordering;
use std::mem;
| random_line_split |
cast-enum-with-dtor.rs | // Copyright 2015 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 ... | () {
assert_eq!(FLAG.load(Ordering::SeqCst), 0);
{
let e = E::C;
assert_eq!(e as u32, 2);
assert_eq!(FLAG.load(Ordering::SeqCst), 0);
}
assert_eq!(FLAG.load(Ordering::SeqCst), 1);
}
| main | identifier_name |
mod.rs | pub mod spout;
pub mod bolt;
use rustc_serialize::json;
use tokio_core::net::TcpStream;
use tokio_io;
use futures::Future;
use std;
use tokio_uds::UnixStream;
pub struct ComponentConfig{
pub sock_file: String,
pub component_id: String
}
#[derive(Debug)]
#[derive(RustcEncodable, RustcDecodable)]
pub enum Mes... | (&self, stream: tokio_io::io::WriteHalf<UnixStream>) -> Box<Future<Item = (tokio_io::io::WriteHalf<UnixStream>), Error = std::io::Error > + Send> {
Box::new(tokio_io::io::write_all(stream, self.encoded()).and_then(|c| Ok(c.0)))
}
pub fn encoded(&self) -> Vec<u8>{
let message = json::encode(... | to_half_uds | identifier_name |
mod.rs | pub mod spout;
pub mod bolt;
use rustc_serialize::json;
use tokio_core::net::TcpStream;
use tokio_io;
use futures::Future;
use std;
use tokio_uds::UnixStream;
pub struct ComponentConfig{
pub sock_file: String,
pub component_id: String
}
#[derive(Debug)]
#[derive(RustcEncodable, RustcDecodable)]
pub enum Mes... |
} | {
Message::Tuple(stream.to_string(), value.to_string())
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.