file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
utils.tsx | import { useDispatch } from 'react-redux';
import { useAsync } from 'react-use';
import { formValueSelector, reduxForm } from 'redux-form';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import {
loadFlavors,
loadSecurityGroups,
loadFloatingIps,
loadSubnets,... | label: formatSubnet(subnet),
value: subnet.url,
})),
],
floatingIps: [
{
value: SKIP_FLOATING_IP_ASSIGNMENT,
label: translate('Skip floating IP assignment'),
},
{
value: AUTO_ASSIGN_FLOATING_IP,
label: translate('Auto-assign floating IP'),
... | value: '',
},
...subnets.map((subnet) => ({ | random_line_split |
hosts.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 parse_hosts::HostsFile;
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::fs::File;
... | () -> Option<HashMap<String, IpAddr>> {
let path = env::var_os("HOST_FILE")?;
let file = File::open(&path).ok()?;
let mut reader = BufReader::new(file);
let mut lines = String::new();
reader.read_to_string(&mut lines).ok()?;
Some(parse_hostsfile(&lines))
}
pub fn replace_host_table(table: Ha... | create_host_table | identifier_name |
hosts.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 parse_hosts::HostsFile;
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::fs::File;
... |
pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
HostsFile::read_buffered(hostsfile_content.as_bytes())
.pairs()
.filter_map(Result::ok)
.collect()
}
pub fn replace_host(host: &str) -> Cow<str> {
HOST_TABLE.lock().unwrap().as_ref()
.and_then(|table|... | {
*HOST_TABLE.lock().unwrap() = Some(table);
} | identifier_body |
hosts.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 parse_hosts::HostsFile;
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::fs::File;
... |
pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
HostsFile::read_buffered(hostsfile_content.as_bytes())
.pairs()
.filter_map(Result::ok)
.collect()
}
pub fn replace_host(host: &str) -> Cow<str> {
HOST_TABLE.lock().unwrap().as_ref()
.and_then(|table| ... |
pub fn replace_host_table(table: HashMap<String, IpAddr>) {
*HOST_TABLE.lock().unwrap() = Some(table);
} | random_line_split |
mod.rs | /*
* 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.
*/
// Containers for Mercurial data, stored in the blob store.
mod changeset_envelope;
mod file_envelope;
mod manifest_envelope;
pub use sel... | (Bytes);
impl From<BlobstoreBytes> for HgEnvelopeBlob {
#[inline]
fn from(bytes: BlobstoreBytes) -> HgEnvelopeBlob {
HgEnvelopeBlob(bytes.into_bytes())
}
}
impl From<HgEnvelopeBlob> for BlobstoreBytes {
#[inline]
fn from(blob: HgEnvelopeBlob) -> BlobstoreBytes {
BlobstoreBytes::fro... | HgEnvelopeBlob | identifier_name |
mod.rs | /*
* 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.
*/
// Containers for Mercurial data, stored in the blob store.
mod changeset_envelope;
mod file_envelope;
mod manifest_envelope;
pub use sel... | #[inline]
fn from(blob: HgEnvelopeBlob) -> BlobstoreBytes {
BlobstoreBytes::from_bytes(blob.0)
}
}
impl From<BlobstoreGetData> for HgEnvelopeBlob {
#[inline]
fn from(blob_val: BlobstoreGetData) -> HgEnvelopeBlob {
HgEnvelopeBlob(blob_val.into_raw_bytes())
}
}
impl From<HgEnvelo... |
impl From<HgEnvelopeBlob> for BlobstoreBytes { | random_line_split |
nx-match_8h.js | 4628ed401aa0b146d32eb4", null ],
[ "mf_format_subfield", "nx-match_8h.html#a8e69b40cba0525f4e9b37d30ffe334a9", null ],
[ "mf_from_nxm_header", "nx-match_8h.html#a3491473078cf8cf4743324ff1e38739f", null ],
[ "mf_nxm_header", "nx-match_8h.html#a3aca29180485ec2d1c6940304cb5e219", null ],
[ "mf_parse_subfie... | [ "nxm_reg_move_check", "nx-match_8h.html#a804547b4d214a56356ec2bd4cd3777d5", null ],
[ "nxm_stack_pop_check", "nx-match_8h.html#a9d23d18ef8e93402296c4beac6918d2e", null ],
[ "nxm_stack_push_check", "nx-match_8h.html#a69ce503c23638231ce94e87d75599b1b", null ],
[ "oxm_bitmap_from_mf_bitmap", "nx-match_8h... | [ "nxm_put__", "nx-match_8h.html#a12fbcbfba944e5885bd90e4266a3414f", null ],
[ "nxm_reg_load", "nx-match_8h.html#ace73c6c66fee11a74176a5b4210fd07c", null ], | random_line_split |
keyboard.d.ts | import { Observable } from 'rxjs/Observable';
/**
* @name Keyboard
* @description
* @usage
* ```typescript
* import { Keyboard } from 'ionic-native';
*
*
*
* ```
*/
export declare class Keyboard {
/**
* Hide the keyboard accessory bar with the next, previous and done buttons.
* @param hide {bool... | */
static onKeyboardShow(): Observable<any>;
/**
* Creates an observable that notifies you when the keyboard is hidden. Unsubscribe to observable to cancel event watch.
* @returns {Observable<any>}
*/
static onKeyboardHide(): Observable<any>;
} | * @returns {Observable<any>} | random_line_split |
keyboard.d.ts | import { Observable } from 'rxjs/Observable';
/**
* @name Keyboard
* @description
* @usage
* ```typescript
* import { Keyboard } from 'ionic-native';
*
*
*
* ```
*/
export declare class | {
/**
* Hide the keyboard accessory bar with the next, previous and done buttons.
* @param hide {boolean}
*/
static hideKeyboardAccessoryBar(hide: boolean): void;
/**
* Force keyboard to be shown.
*/
static show(): void;
/**
* Close the keyboard if open.
*/
st... | Keyboard | identifier_name |
incident-sk.ts | pre>
* detail {
* key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sen... | (): TemplateResult {
if (this.state.active) {
return html``;
}
return html`<tr><th>Last Seen</th><td title=${new Date(this.state.last_seen * 1000).toLocaleString()}>${diffDate(this.state.last_seen * 1000)}</td></tr>`;
}
private duration(): TemplateResult {
if (this.state.active) {
retur... | lastSeen | identifier_name |
incident-sk.ts | pre>
* detail {
* key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sen... |
export class IncidentSk extends HTMLElement {
private silences: Silence[] = [];
private displaySilencesWithComments: boolean = false;
private flaky: boolean = false;
private recently_expired_silence: boolean = false;
private state: State = {
key: '',
id: '',
params: {},
start: 0,
last... | random_line_split | |
incident-sk.ts | >
* detail {
* key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sent w... |
set incident_has_recently_expired_silence(val: boolean) {
// No need to render again if value is same as old value.
if (val !== this.recently_expired_silence) {
this.recently_expired_silence = val;
this._render();
}
}
/** @prop flaky Whether this incident has been flaky. */
get incide... | { return this.recently_expired_silence; } | identifier_body |
incident-sk.ts | >
* detail {
* key: "12312123123",
* index: 0,
* }
* </pre>
*
* @evt take Sent when the user wants the incident assigned to themselves.
* The detail includes the key of the incident.
*
* <pre>
* detail {
* key: "12312123123",
* }
* </pre>
*
* @evt assign Sent w... |
return '';
}
private table(): TemplateResult[] {
const params = this.state.params;
const keys = Object.keys(params);
keys.sort();
return keys.filter((k) => !k.startsWith('__')).map((k) => html`
<tr>
<th>${k}</th>
<td>
${linkify(params[k])}
${this.maybe... | {
return 'assigned';
} | conditional_block |
overload-index-operator.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 ... | {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
} | identifier_body | |
overload-index-operator.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() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
} | random_line_split | |
overload-index-operator.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 ... |
}
fail!(fmt!("No value found for key: %?", index));
}
}
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(li... | {
return copy pair.value;
} | conditional_block |
overload-index-operator.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 ... | (&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for self.pairs.each |pair| {
if pair.key == *index {
return copy pair.value;
... | push | identifier_name |
with_asan.py | #!/usr/bin/env vpython
# Copyright 2019 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 argparse
import contextlib
import logging
import os
import subprocess
import sys
_SRC_ROOT = os.path.abspath(
os.path.joi... | def _LogDevicesOnFailure(msg):
try:
yield
except base_error.BaseError:
logging.exception(msg)
logging.error('Devices visible to adb:')
for entry in adb_wrapper.AdbWrapper.Devices(desired_state=None,
long_list=True):
logging.error(' %s: %s',
... | random_line_split | |
with_asan.py | #!/usr/bin/env vpython
# Copyright 2019 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 argparse
import contextlib
import logging
import os
import subprocess
import sys
_SRC_ROOT = os.path.abspath(
os.path.joi... | (raw_args):
parser = argparse.ArgumentParser()
logging_common.AddLoggingArguments(parser)
parser.add_argument(
'--adb', type=os.path.realpath, required=True,
help='Path to adb binary.')
parser.add_argument(
'--device',
help='Device serial.')
parser.add_argument(
'--lib', type=os.... | main | identifier_name |
with_asan.py | #!/usr/bin/env vpython
# Copyright 2019 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 argparse
import contextlib
import logging
import os
import subprocess
import sys
_SRC_ROOT = os.path.abspath(
os.path.joi... |
raise
@contextlib.contextmanager
def Asan(args):
env = os.environ.copy()
env['ADB'] = args.adb
try:
with _LogDevicesOnFailure('Failed to set up the device.'):
device = device_utils.DeviceUtils.HealthyDevices(
device_arg=args.device)[0]
disable_verity = device.build_version_sdk >=... | logging.error(' %s: %s',
entry[0].GetDeviceSerial(),
' '.join(entry[1:])) | conditional_block |
with_asan.py | #!/usr/bin/env vpython
# Copyright 2019 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 argparse
import contextlib
import logging
import os
import subprocess
import sys
_SRC_ROOT = os.path.abspath(
os.path.joi... | device.EnableRoot()
setup_cmd = [_SCRIPT_PATH, '--lib', args.lib]
if args.device:
setup_cmd += ['--device', args.device]
subprocess.check_call(setup_cmd, env=env)
yield
finally:
with _LogDevicesOnFailure('Failed to tear down the device.'):
device.EnableRoot()
tear... | env = os.environ.copy()
env['ADB'] = args.adb
try:
with _LogDevicesOnFailure('Failed to set up the device.'):
device = device_utils.DeviceUtils.HealthyDevices(
device_arg=args.device)[0]
disable_verity = device.build_version_sdk >= version_codes.MARSHMALLOW
if disable_verity:
... | identifier_body |
fakes.ts | import { ISizeSettings } from "gamestartr/lib/IGameStartr";
import { stub } from "sinon";
import { FullScreenPokemon } from "../../src/FullScreenPokemon";
/**
* Creates a stubbed instance of the FullScreenPokemon class.
*
* @param settings Size settings, if not a default small window size.
* @returns A new inst... | {
const fsp: FullScreenPokemon = stubFullScreenPokemon(settings);
fsp.itemsHolder.setItem("name", "Test".split(""));
fsp.maps.setMap("Blank");
fsp.maps.addPlayer(0, 0);
return fsp;
} | identifier_body | |
fakes.ts | import { ISizeSettings } from "gamestartr/lib/IGameStartr";
import { stub } from "sinon";
import { FullScreenPokemon } from "../../src/FullScreenPokemon";
/**
* Creates a stubbed instance of the FullScreenPokemon class.
*
* @param settings Size settings, if not a default small window size.
* @returns A new inst... | (settings?: ISizeSettings): FullScreenPokemon {
const fsp: FullScreenPokemon = stubFullScreenPokemon(settings);
fsp.itemsHolder.setItem("name", "Test".split(""));
fsp.maps.setMap("Blank");
fsp.maps.addPlayer(0, 0);
return fsp;
}
| stubBlankGame | identifier_name |
fakes.ts | import { ISizeSettings } from "gamestartr/lib/IGameStartr";
import { stub } from "sinon";
import { FullScreenPokemon } from "../../src/FullScreenPokemon";
/**
* Creates a stubbed instance of the FullScreenPokemon class.
* | width: 256,
height: 256
};
const fsp = new FullScreenPokemon({
moduleSettings: {
audio: {
fileTypes: []
}
},
...settings
});
stub(fsp.audioPlayer, "play");
stub(fsp.audioPlayer, "playLocal");
stub(fsp.audioPlayer, ... | * @param settings Size settings, if not a default small window size.
* @returns A new instance of the FullScreenPokemon class.
*/
export function stubFullScreenPokemon(settings?: ISizeSettings): FullScreenPokemon {
settings = settings || { | random_line_split |
setup.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | (self):
"""Finalize pytest."""
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
"""Run tests."""
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
... | finalize_options | identifier_name |
setup.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | 'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Development Status :: 1 - Planning',
],
cmdclass={'test': PyTest},
) | 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3', | random_line_split |
setup.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... |
# Get the version string. Cannot be done with import!
g = {}
with open(os.path.join('invenio', 'version.py'), 'rt') as fp:
exec(fp.read(), g)
version = g['__version__']
setup(
name='invenio3',
version=version,
description=__doc__,
long_description=readme + '\n\n' + history,
keywords='Inve... | """Run tests."""
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno) | identifier_body |
setup.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... |
setup_requires = [
'Babel>=1.3',
]
install_requires = [
]
packages = find_packages()
class PyTest(TestCommand):
"""PyTest Test."""
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
"""Init pytest."""
TestCommand.initialize_option... | extras_require['all'].extend(reqs) | conditional_block |
2d.fillStyle.parse.css-color-4-rgb-4.worker.js | // DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py.
// OffscreenCanvas test in a worker:2d.fillStyle.parse.css-color-4-rgb-4
// Description:
// Note:<p class="notes">
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");
var t = async_test("");... | ctx.fillStyle = '#f00';
ctx.fillStyle = 'rgb(0 255 0)';
ctx.fillRect(0, 0, 100, 50);
_assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255");
t.done();
});
done(); |
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
| random_line_split |
realmUser.js | var cutX;
var cutY;
var cutW;
var cutH;
var imgWidth;
var imgHeight;
function fileChange(imgSrc) {
$("#target").attr("src", "../../images/nohead.png");
var filepath = $("#uploadFile").val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
... | cutY = Math.round(picH * coords.y / 350);
cutW = Math.round(picH * coords.w / 350);
cutH = Math.round(picH * coords.h / 350);
} else {
cutX = coords.x;
cutY = coords.y;
cutW = coords.w;
cutH = coo... | var rx = $("#preview_box").width() / coords.w;
var ry = $("#preview_box").height() / coords.h;
//通过比例值控制图片的样式与显示
$("#crop_preview").css({
width : Math.round(rx * $("#target").width()) + "px", //预览图片宽度为计算比例值与原图片宽度的乘积
height : Math.round(rx * $... | conditional_block |
realmUser.js | var cutX;
var cutY;
var cutW;
var cutH;
var imgWidth;
var imgHeight;
function | (imgSrc) {
$("#target").attr("src", "../../images/nohead.png");
var filepath = $("#uploadFile").val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".JPG") {
alert("请选择为(.jpg)的图片文件!");
//$("#target").attr(... | fileChange | identifier_name |
realmUser.js | var cutX;
var cutY;
var cutW;
var cutH;
var imgWidth;
var imgHeight;
function fileChange(imgSrc) |
$("#target").load(function() {
imgWidth = $("#target").width();
imgHeight = $("#target").height();
if (imgWidth > imgHeight) {
var showH = Math.round(imgHeight * 350 / imgWidth) + "px";
... | {
$("#target").attr("src", "../../images/nohead.png");
var filepath = $("#uploadFile").val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
if (ext != ".JPG") {
alert("请选择为(.jpg)的图片文件!");
//$("#target").attr("src", ".... | identifier_body |
realmUser.js | var cutX;
var cutY;
var cutW;
var cutH;
var imgWidth;
var imgHeight;
function fileChange(imgSrc) {
$("#target").attr("src", "../../images/nohead.png");
var filepath = $("#uploadFile").val();
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length).toUpperCase();
... | });
}
});
}
}
//function loadImage(src){
// var render = new FileReader();
// reader.onload = function(e){
// render(e.target.result);
// };
// render.readAsDataURL(src);
//}
function jcropImg() {
$("#target").Jcrop({
onChange : showPreview,
onSelect : show... | random_line_split | |
test_component.py | # -*- coding: utf-8 -*-
import unittest
import datetime
from cwr.parser.encoder.dictionary import ComponentDictionaryEncoder
from cwr.work import ComponentRecord
"""
ComponentRecord to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__stat... |
def test_encoded(self):
data = ComponentRecord(record_type='COM',
transaction_sequence_n=3,
record_sequence_n=15,
title='TITLE',
writer_1_last_name='LAST NAME 1',
... | elf._encoder = ComponentDictionaryEncoder()
| identifier_body |
test_component.py | # -*- coding: utf-8 -*-
import unittest
import datetime
from cwr.parser.encoder.dictionary import ComponentDictionaryEncoder
from cwr.work import ComponentRecord
"""
ComponentRecord to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__stat... | self):
self._encoder = ComponentDictionaryEncoder()
def test_encoded(self):
data = ComponentRecord(record_type='COM',
transaction_sequence_n=3,
record_sequence_n=15,
title='TITLE',
... | etUp( | identifier_name |
test_component.py | # -*- coding: utf-8 -*-
import unittest
import datetime
from cwr.parser.encoder.dictionary import ComponentDictionaryEncoder
from cwr.work import ComponentRecord
"""
ComponentRecord to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__stat... | self.assertEqual('TITLE', encoded['title'])
self.assertEqual('LAST NAME 1', encoded['writer_1_last_name'])
self.assertEqual('ABCD123', encoded['submitter_work_n'])
self.assertEqual('FIRST NAME 1', encoded['writer_1_first_name'])
self.assertEqual('FIRST NAME 2', encoded['writer_2_... | encoded = self._encoder.encode(data)
self.assertEqual('COM', encoded['record_type'])
self.assertEqual(3, encoded['transaction_sequence_n'])
self.assertEqual(15, encoded['record_sequence_n']) | random_line_split |
Utils.py | __author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
import string
import random
class | :
@staticmethod
def get_random_text(length_text=10, space_number=1, with_upper_case=True):
results = []
while len(results) < length_text:
char = random.choice(string.ascii_letters[:26])
results.append(char)
if with_upper_case:
results[0] = results[0].u... | Utils | identifier_name |
Utils.py | __author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
import string
import random
class Utils:
@staticmethod
def get_random_text(length_text=10, space_number=1, with_upper_case=True):
results = []
while len(results) < length_text:
char = random.choice(string.ascii_letters[:26]... | def get_ios_id(length=10):
results = []
while len(results) < length:
char = random.choice(string.digits + string.ascii_letters)
results.append(char)
results[3] = "-"
results[6] = "-"
return ''.join(results)
@staticmethod
def get_android_id(... |
return ''.join(results)
@staticmethod | random_line_split |
Utils.py | __author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
import string
import random
class Utils:
| return ''.join(results)
@staticmethod
def get_ios_id(length=10):
results = []
while len(results) < length:
char = random.choice(string.digits + string.ascii_letters)
results.append(char)
results[3] = "-"
results[6] = "-"
return ''.join(... | @staticmethod
def get_random_text(length_text=10, space_number=1, with_upper_case=True):
results = []
while len(results) < length_text:
char = random.choice(string.ascii_letters[:26])
results.append(char)
if with_upper_case:
results[0] = results[0].upper()... | identifier_body |
Utils.py | __author__ = 'Tony Beltramelli - www.tonybeltramelli.com'
import string
import random
class Utils:
@staticmethod
def get_random_text(length_text=10, space_number=1, with_upper_case=True):
results = []
while len(results) < length_text:
char = random.choice(string.ascii_letters[:26]... |
results[space_pos] = " "
if with_upper_case:
results[space_pos + 1] = results[space_pos - 1].upper()
current_spaces.append(space_pos)
return ''.join(results)
@staticmethod
def get_ios_id(length=10):
results = []
while len(results) ... | break | conditional_block |
check_cfg.rs | use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
... |
let end = cfg.basic_blocks[pos].end;
insert_positions.push(end);
}
}
}
}
}
for pos in insert_positions.iter() {
cfg.insert_statement(function, *pos, Statement::Return(None));
}
} | } else {
| random_line_split |
check_cfg.rs | use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
... | )
} else {
let end = cfg.basic_blocks[pos].end;
insert_positions.push(end);
}
}
}
}
}
for pos in insert_positions.iter() {
cfg.insert_statement(func... | {
if function.has_attribute(FunctionAttribute::External) {
return;
}
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
if adjacencies.contains(&Adjacency::End) {
let bb = &cfg.basic_blocks[pos];
ma... | identifier_body |
check_cfg.rs | use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
... |
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
if adjacencies.contains(&Adjacency::End) {
let bb = &cfg.basic_blocks[pos];
match function.statements[bb.end-1] {
Statement::Return(_) => (), // OK
... | {
return;
} | conditional_block |
check_cfg.rs | use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
... | (
function: &mut Function,
cfg: &mut CFG,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) {
if function.has_attribute(FunctionAttribute::External) {
return;
}
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
... | check_function | identifier_name |
trait-bounds-on-structs-and-enums.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 ... | //~^ ERROR not implemented
a: Foo<isize>,
}
enum Boo {
//~^ ERROR not implemented
Quux(Bar<usize>),
}
struct Badness<U> {
//~^ ERROR not implemented
b: Foo<U>,
}
enum MoreBadness<V> {
//~^ ERROR not implemented
EvenMoreBadness(Bar<V>),
}
trait PolyTrait<T> {
fn whatever() {}
}
struct Struct;
i... | //~^ ERROR the trait `Trait` is not implemented
fn uhoh() {}
}
struct Baz { | random_line_split |
trait-bounds-on-structs-and-enums.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 ... | () {}
}
fn main() {
}
| whatever | identifier_name |
borrowck-move-out-of-vec-tail.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 ... | }
pub fn main() {
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] => {
match tail {
[Foo { string: a }, //~ ERROR cann... |
#[deriving(Clone)]
struct Foo {
string: String | random_line_split |
borrowck-move-out-of-vec-tail.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 ... | {
string: String
}
pub fn main() {
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] => {
match tail {
[Foo { strin... | Foo | identifier_name |
borrowck-move-out-of-vec-tail.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 ... | println!("{:?}", z);
}
_ => {
unreachable!();
}
}
}
| {
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] => {
match tail {
[Foo { string: a }, //~ ERROR cannot move out of de... | identifier_body |
borrowck-move-out-of-vec-tail.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 ... |
_ => {
unreachable!();
}
}
}
| {
match tail {
[Foo { string: a }, //~ ERROR cannot move out of dereference of `&`-pointer
Foo { string: b }] => {
//~^^ NOTE attempting to move value to here
//~^^ NOTE and here
}
_ => {
... | conditional_block |
do_proxy_barix_status.py | import BaseHTTPServer
import logging
import os
import sys
import threading
import time
from chirp.common.conf import (BARIX_STATUS_HOST, BARIX_STATUS_PORT,
BARIX_HOST, BARIX_PORT)
from chirp.stream import barix
_TIMEOUT_S = 2
_POLLING_FREQUENCY_S = 5
_STATUS_PAGE = """<html><head>... | self.wfile.write(response_str)
def log_message(self, format, *args):
pass # Throw away log messages for now.
def handle_requests(srv, done):
while not done.isSet():
try:
srv.handle_request()
except Exception, err:
logging.exception("Swallowed e... | self.end_headers() | random_line_split |
do_proxy_barix_status.py |
import BaseHTTPServer
import logging
import os
import sys
import threading
import time
from chirp.common.conf import (BARIX_STATUS_HOST, BARIX_STATUS_PORT,
BARIX_HOST, BARIX_PORT)
from chirp.stream import barix
_TIMEOUT_S = 2
_POLLING_FREQUENCY_S = 5
_STATUS_PAGE = """<html><head... | (b_obj, log_fh):
try:
if not b_obj.ping():
return
level_history.append(
(float(b_obj.left_level), float(b_obj.right_level)))
if len(level_history) > LEVEL_HISTORY_MAX_SIZE:
level_history.pop(0)
if log_fh:
now = int(b_obj.last_update_t... | poll_barix | identifier_name |
do_proxy_barix_status.py |
import BaseHTTPServer
import logging
import os
import sys
import threading
import time
from chirp.common.conf import (BARIX_STATUS_HOST, BARIX_STATUS_PORT,
BARIX_HOST, BARIX_PORT)
from chirp.stream import barix
_TIMEOUT_S = 2
_POLLING_FREQUENCY_S = 5
_STATUS_PAGE = """<html><head... |
if log_fh:
log_fh.close()
done.set()
th.join() # Wait for the serving thread to settle.
if __name__ == "__main__":
main()
| log_path = os.path.join(os.environ["HOME"], "live365_connection.log")
log_fh = open(log_path, "a")
_RequestHandler.barix = barix.Barix(BARIX_HOST, BARIX_PORT)
srv = BaseHTTPServer.HTTPServer((BARIX_STATUS_HOST, BARIX_STATUS_PORT),
_RequestHandler)
srv.socket.settime... | identifier_body |
do_proxy_barix_status.py |
import BaseHTTPServer
import logging
import os
import sys
import threading
import time
from chirp.common.conf import (BARIX_STATUS_HOST, BARIX_STATUS_PORT,
BARIX_HOST, BARIX_PORT)
from chirp.stream import barix
_TIMEOUT_S = 2
_POLLING_FREQUENCY_S = 5
_STATUS_PAGE = """<html><head... |
def poll_barix(b_obj, log_fh):
try:
if not b_obj.ping():
return
level_history.append(
(float(b_obj.left_level), float(b_obj.right_level)))
if len(level_history) > LEVEL_HISTORY_MAX_SIZE:
level_history.pop(0)
if log_fh:
now = int(b_... | try:
srv.handle_request()
except Exception, err:
logging.exception("Swallowed exception") | conditional_block |
mod.rs | pub type c_long = i32;
pub type c_ulong = u32;
pub type nlink_t = u32;
s! {
pub struct pthread_attr_t {
__size: [u32; 9]
}
pub struct sigset_t {
__val: [::c_ulong; 32],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg... | } else if #[cfg(any(target_arch = "arm"))] {
mod arm;
pub use self::arm::*;
} else if #[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))] {
// For the time being asmjs and wasm32 are the same, and both
// backed by identical emscripten runtimes
mod asmjs;
p... | random_line_split | |
iconSentry.tsx | import React from 'react';
import SvgIcon from './svgIcon';
type Props = React.ComponentProps<typeof SvgIcon>;
| ) {
return (
<SvgIcon {...props} ref={ref}>
<path d="M15.8,14.57a1.53,1.53,0,0,0,0-1.52L9.28,1.43a1.46,1.46,0,0,0-2.56,0L4.61,5.18l.54.32A10.43,10.43,0,0,1,8.92,9.39a10.84,10.84,0,0,1,1.37,4.67H8.81a9.29,9.29,0,0,0-1.16-3.91A9,9,0,0,0,4.41,6.81L3.88,6.5,1.91,10l.53.32a5.12,5.12,0,0,1,2.42,3.73H1.48a.25.25,0... | const IconSentry = React.forwardRef(function IconSentry(
props: Props,
ref: React.Ref<SVGSVGElement> | random_line_split |
test_auth.py | # -*- coding: utf-8 -*-
"""Test suite for the TG app's models"""
from __future__ import unicode_literals
from nose.tools import eq_
from wiki20 import model
from wiki20.tests.models import ModelTest | """Unit test case for the ``Group`` model."""
klass = model.Group
attrs = dict(
group_name = "test_group",
display_name = "Test Group"
)
class TestUser(ModelTest):
"""Unit test case for the ``User`` model."""
klass = model.User
attrs = dict(
user_name = "ig... |
class TestGroup(ModelTest): | random_line_split |
test_auth.py | # -*- coding: utf-8 -*-
"""Test suite for the TG app's models"""
from __future__ import unicode_literals
from nose.tools import eq_
from wiki20 import model
from wiki20.tests.models import ModelTest
class TestGroup(ModelTest):
"""Unit test case for the ``Group`` model."""
klass = model.Group
attrs = dict(... | (self):
"""The obj constructor must set the user name right"""
eq_(self.obj.user_name, "ignucius")
def test_obj_creation_email(self):
"""The obj constructor must set the email right"""
eq_(self.obj.email_address, "ignucius@example.org")
def test_no_permissions_by_default(self):... | test_obj_creation_username | identifier_name |
test_auth.py | # -*- coding: utf-8 -*-
"""Test suite for the TG app's models"""
from __future__ import unicode_literals
from nose.tools import eq_
from wiki20 import model
from wiki20.tests.models import ModelTest
class TestGroup(ModelTest):
"""Unit test case for the ``Group`` model."""
klass = model.Group
attrs = dict(... |
def test_obj_creation_email(self):
"""The obj constructor must set the email right"""
eq_(self.obj.email_address, "ignucius@example.org")
def test_no_permissions_by_default(self):
"""User objects should have no permission by default."""
eq_(len(self.obj.permissions), 0)
d... | """The obj constructor must set the user name right"""
eq_(self.obj.user_name, "ignucius") | identifier_body |
task_executor.py | self._module_loader = module_loader
def run(self):
'''
The main executor entrypoint, where we determine if the specified
task requires looping and either runs the task with
'''
debug("in run()")
try:
# lookup plugins need to know if this task is exe... |
def _run_loop(self, items):
'''
Runs the task with the loop items specified and collates the result
into an array named 'results' which is inserted into the final result
along with the item for which the loop ran.
'''
results = []
# make copies of the job ... | '''
Loads a lookup plugin to handle the with_* portion of a task (if specified),
and returns the items result.
'''
items = None
if self._task.loop and self._task.loop in lookup_loader:
loop_terms = listify_lookup_plugin_terms(terms=self._task.loop_args, variables=sel... | identifier_body |
task_executor.py | msg=str(e)))
continue
# now we swap the internal task with the copy, execute,
# and swap them back so we can do the next iteration cleanly
(self._task, tmp_task) = (tmp_task, self._task)
res = self._execute(variables=task_vars)
(self._task, t... | _compute_delegate | identifier_name | |
task_executor.py | job_vars
# fields set from the play/task may be based on variables, so we have to
# do the same kind of post validation step on it here before we use it
self._connection_info.post_validate(variables=variables, loader=self._loader)
# get the connection and the handler for this execution... | # this is useful if delegated host is not defined in the inventory
#if delegate['private_key_file'] is None:
# delegate['private_key_file'] = remote_inject.get('ansible_ssh_private_key_file', None)
| random_line_split | |
task_executor.py | ._module_loader = module_loader
def run(self):
'''
The main executor entrypoint, where we determine if the specified
task requires looping and either runs the task with
'''
debug("in run()")
try:
# lookup plugins need to know if this task is executin... |
else:
return items
def _execute(self, variables=None):
'''
The primary workhorse of the executor system, this runs the task
on the specified host (which may be the delegated_to host) and handles
the retry/until and block rescue/always execution
'''
... | final_items = []
for item in items:
variables['item'] = item
if self._task.evaluate_conditional(variables):
final_items.append(item)
return [",".join(final_items)] | conditional_block |
test_python_ctools.py | #! /usr/bin/env python
# ==========================================================================
# This scripts performs unit tests for the ctools package
#
# Copyright (C) 2012-2017 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | (installed=False):
"""
Perform unit testing for ctools.
Parameters
----------
installed : bool, optional
Flag indicating whether the script has been installed or not
"""
# If we have an installed version then create a temporary
# directory and copy over all information that is n... | test | identifier_name |
test_python_ctools.py | #! /usr/bin/env python
# ==========================================================================
# This scripts performs unit tests for the ctools package
#
# Copyright (C) 2012-2017 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... |
# Create a local "pfiles" directory and set PFILES environment variable
try:
os.mkdir('pfiles')
except:
pass
os.environ['PFILES'] = 'pfiles'
# Copy the ctools parameter files into the "pfiles" directory. For a
# non-installed test we copy the parameter files from the respectiv... | os.environ['CALDB'] = '%s/caldb' % (os.environ['TEST_SRCDIR']) | conditional_block |
test_python_ctools.py | #! /usr/bin/env python
# ==========================================================================
# This scripts performs unit tests for the ctools package
#
# Copyright (C) 2012-2017 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | except:
pass
os.environ['PFILES'] = 'pfiles'
# Copy the ctools parameter files into the "pfiles" directory. For a
# non-installed test we copy the parameter files from the respective
# source directories into the "pfiles" directory, for an installed version
# we get all parameter files ... | try:
os.mkdir('pfiles') | random_line_split |
test_python_ctools.py | #! /usr/bin/env python
# ==========================================================================
# This scripts performs unit tests for the ctools package
#
# Copyright (C) 2012-2017 Juergen Knoedlseder
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General P... | dirname = os.path.dirname(testdir)
# Copy test data in "data" directory
os.system('cp -r %s %s' % (dirname+'/data', 'data'))
# Set test data environment variable
os.environ['TEST_DATA'] = 'data'
# ... otherwise set the calibration database to the one shipped with the
#... | """
Perform unit testing for ctools.
Parameters
----------
installed : bool, optional
Flag indicating whether the script has been installed or not
"""
# If we have an installed version then create a temporary
# directory and copy over all information that is needed
if installed:... | identifier_body |
class-method-cross-crate.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
let nyan : cat = cat(52u, 99);
let kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak();
} | identifier_body | |
class-method-cross-crate.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let nyan : cat = cat(52u, 99);
let kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak();
}
| main | identifier_name |
class-method-cross-crate.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | nyan.speak();
} | random_line_split | |
ad.js | // Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// You can use CoffeeScript in this file: http://coffeescript.org/
angular.module('receta',['wu.masonry', 'ui.bootstrap', 'ui-rangeSlider'])
.controller('DemoCtrl', functi... | $scope.priceRange.max = Math.max.apply(Math,data.map(function(o){return o.price;}))
$scope.priceRange.defaultMax = $scope.priceRange.max;
console.log($scope.priceRange.defaultMax);
for(var i = 0; i < 15; i++){
ad = data[Math.floor(Math.random() * data.length)];
consol... | $http.get('/ads/all')
.success(function(data, status){
$scope.ads = JSON.stringify(data);
$scope.bricks = []; | random_line_split |
ad.js | // Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
// You can use CoffeeScript in this file: http://coffeescript.org/
angular.module('receta',['wu.masonry', 'ui.bootstrap', 'ui-rangeSlider'])
.controller('DemoCtrl', functi... |
return;
for(var i = 0; i < data.length; i++){
ad = data[i];
$scope.bricks.push({
src: '/assets/' + ad.image + '.jpg?=' + i,
gender: 'F',
name: ad.name,
description: ad.description,
category_id: ad.category_i... | {
ad = data[Math.floor(Math.random() * data.length)];
console.log(ad);
$scope.bricks.push({
src: '/assets/' + ad.image + '.jpg?=' + i,
name: ad.name,
price:ad.price,
description: ad.description,
category_id: ad.category_id || '',
... | conditional_block |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-21 12:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| migrations.CreateModel(
name='GroupMember',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to=... | initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Group',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-21 12:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Group',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, seria... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-21 12:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | ('description_html', models.TextField(blank=True, default='', editable=False)),
],
options={
'ordering': ['name'],
},
),
migrations.CreateModel(
name='GroupMember',
fields=[
('id', models.AutoFiel... | fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, unique=True)),
('slug', models.SlugField(allow_unicode=True, unique=True)),
('description', mo... | random_line_split |
__init__.py | # -*- coding: UTF-8 -*-
#
# (c) 2010 Mandriva, http://www.mandriva.com/
#
# This file is part of Mandriva Server Setup | # (at your option) any later version.
#
# MSS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU G... | #
# MSS is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or | random_line_split |
lib.rs | //! The runtime for writing applications for [Ice](https://github.com/losfair/IceCore),
//! an efficient, reliable and asynchronous platform for building modern backend applications
//! in WebAssembly.
//!
//! At a high level, `ia` (which stands for "Ice App") provides a few major components (based on
//! the underlyin... | //! extern crate ia;
//! extern crate futures_await as futures;
//!
//! use futures::prelude::*;
//! use ia::net::{TcpListener, TcpConnection};
//! use ia::error::IoResult;
//!
//! #[async]
//! fn handle_connection(incoming: TcpConnection) -> IoResult<()> {
//! #[async]
//! fn forward(from: TcpConnection, to:... | //! ```no_run
//! #![feature(proc_macro, generators)]
//!
//! #[macro_use] | random_line_split |
load-dt-options-with-promise.component.spec.ts | import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientModule } from '@angular/common/http';
import { NO_ERRORS_SCHEMA, SecurityContext } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { DataTableDirective, DataTablesModule } from... | }); | });
| random_line_split |
config.rs | use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::option::Option;
use std::path::{Path, PathBuf};
use std::result::Result;
use std::thread;
use git2::Repository;
use rustc_serialize::{Decodable, Decoder};
use toml;
use ::Args;
#[derive(RustcDecodable)]
pub str... | {
basedir: Option<String>,
repos: Option<HashMap<String, RepoConfig>>,
}
impl Config {
pub fn from_args(args: &Args) -> Config {
let path = Path::new(&args.flag_config);
// opening file
let mut file = match File::open(&path) {
Ok(file) => file,
Err(why) => ... | Config | identifier_name |
config.rs | use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::option::Option;
use std::path::{Path, PathBuf};
use std::result::Result;
use std::thread;
use git2::Repository;
use rustc_serialize::{Decodable, Decoder};
use toml;
use ::Args;
#[derive(RustcDecodable)]
pub str... | }
} | Err(_) => Repository::clone(&url, &path), | random_line_split |
test_reference_resolver.py | # Copyright 2017 AT&T Intellectual Property. All other 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... | @responses.activate
def test_resolve_http_basicauth_url(self):
"""Test the resolver will resolve http URLs w/ basic auth."""
url = 'http://user:pass@foo.com/test.yaml'
auth_header = "Basic %s" % base64.b64encode(
"user:pass".encode('utf-8')).decode('utf-8')
responses.... | def test_resolve_file_url(self, input_files):
"""Test that the resolver will resolve file URLs."""
input_file = input_files.join("fullsite.yaml")
url = 'file://%s' % str(input_file)
content = ReferenceResolver.resolve_reference(url)
assert len(content) > 0
@responses.activ... | identifier_body |
test_reference_resolver.py | # Copyright 2017 AT&T Intellectual Property. All other 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... | (self):
"""Test that the resolver will resolve http URLs."""
url = 'http://foo.com/test.yaml'
responses.add(responses.GET, url)
ReferenceResolver.resolve_reference(url)
assert len(responses.calls) == 1
assert responses.calls[0].request.url == url
@responses.activat... | test_resolve_http_url | identifier_name |
test_reference_resolver.py | # Copyright 2017 AT&T Intellectual Property. All other 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... | content = ReferenceResolver.resolve_reference(url)
assert len(content) > 0
@responses.activate
def test_resolve_http_url(self):
"""Test that the resolver will resolve http URLs."""
url = 'http://foo.com/test.yaml'
responses.add(responses.GET, url)
ReferenceReso... | url = 'file://%s' % str(input_file)
| random_line_split |
ranges.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <rolfmorel@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct | {
pub low: uint,
pub high: uint,
}
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range> {
use std::uint::MAX;
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then... | Range | identifier_name |
ranges.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <rolfmorel@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct Range {
pub lo... |
(Some(n), Some(m)) => {
match (from_str::<uint>(n), from_str::<uint>(m)) {
(Some(low), Some(high)) if low > 0 && low <= high => {
Some(Range { low: low, high: high })
}
_ => None
}
... | {
from_str::<uint>(m).and_then(|high| if high >= 1 { Some(high) } else { None })
.map(|high| Range { low: 1, high: high })
} | conditional_block |
ranges.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <rolfmorel@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct Range {
pub lo... | (Some(low), Some(high)) if low > 0 && low <= high => {
Some(Range { low: low, high: high })
}
_ => None
}
}
_ => unreachable!()
}
}
}
impl Range {
pub fn from_list(list: &str) ->... | {
use std::uint::MAX;
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
... | identifier_body |
ranges.rs | /*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <rolfmorel@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct Range {
pub lo... |
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
}
(Some(n... | }
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range> {
use std::uint::MAX; | random_line_split |
PaletteFile.py | #
# Python Imaging Library
# $Id$
#
# stuff to read simple, teragon-style palette files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from PIL._binary import o8 | class PaletteFile(object):
rawmode = "RGB"
def __init__(self, fp):
self.palette = [(i, i, i) for i in range(256)]
while True:
s = fp.readline()
if not s:
break
if s[0:1] == b"#":
continue
if len(s) > 100:
... |
##
# File handler for Teragon-style palette files.
| random_line_split |
PaletteFile.py | #
# Python Imaging Library
# $Id$
#
# stuff to read simple, teragon-style palette files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from PIL._binary import o8
##
# File h... | except ValueError:
[i, r] = v
g = b = r
if 0 <= i <= 255:
self.palette[i] = o8(r) + o8(g) + o8(b)
self.palette = b"".join(self.palette)
def getpalette(self):
return self.palette, self.rawmode
| rawmode = "RGB"
def __init__(self, fp):
self.palette = [(i, i, i) for i in range(256)]
while True:
s = fp.readline()
if not s:
break
if s[0:1] == b"#":
continue
if len(s) > 100:
raise SyntaxError("ba... | identifier_body |
PaletteFile.py | #
# Python Imaging Library
# $Id$
#
# stuff to read simple, teragon-style palette files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from PIL._binary import o8
##
# File h... |
if s[0:1] == b"#":
continue
if len(s) > 100:
raise SyntaxError("bad palette file")
v = [int(x) for x in s.split()]
try:
[i, r, g, b] = v
except ValueError:
[i, r] = v
g = b = r
... | break | conditional_block |
PaletteFile.py | #
# Python Imaging Library
# $Id$
#
# stuff to read simple, teragon-style palette files
#
# History:
# 97-08-23 fl Created
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from PIL._binary import o8
##
# File h... | (self, fp):
self.palette = [(i, i, i) for i in range(256)]
while True:
s = fp.readline()
if not s:
break
if s[0:1] == b"#":
continue
if len(s) > 100:
raise SyntaxError("bad palette file")
v =... | __init__ | identifier_name |
purge.py | # Copyright (c) 2013 Matthieu Huguet
# 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
# to use, copy, modify, merge, publish, dist... |
def weekly_backup_days(days, dow, retention):
weekly_days = [day for day in days if day.isoweekday() == dow]
return weekly_days[:retention]
def monthly_backup_days(days, dom, retention):
monthly_days = [day for day in days if day.day == dom]
return monthly_days[:retention]
| return days[:retention] | identifier_body |
purge.py | # Copyright (c) 2013 Matthieu Huguet
# 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
# to use, copy, modify, merge, publish, dist... | (days, dow, retention):
weekly_days = [day for day in days if day.isoweekday() == dow]
return weekly_days[:retention]
def monthly_backup_days(days, dom, retention):
monthly_days = [day for day in days if day.day == dom]
return monthly_days[:retention]
| weekly_backup_days | identifier_name |
purge.py | # Copyright (c) 2013 Matthieu Huguet
# 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
# to use, copy, modify, merge, publish, dist... | remove all your backup files according to your retention rules.
""")
return 1
def get_backup_collection(backup_dir):
daily_backups = BackupCollection()
for file in os.listdir(backup_dir):
fpath = os.path.join(backup_dir, file)
if not os.path.islink(fpath) and os.path.isfile(fpath):
... |
If you really know what you are doing, you can use option --force to | random_line_split |
purge.py | # Copyright (c) 2013 Matthieu Huguet
# 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
# to use, copy, modify, merge, publish, dist... |
def get_backup_collection(backup_dir):
daily_backups = BackupCollection()
for file in os.listdir(backup_dir):
fpath = os.path.join(backup_dir, file)
if not os.path.islink(fpath) and os.path.isfile(fpath):
backup = Backup.from_path(fpath)
daily_backups.add(backup)
r... | sys.stderr.write("""
WARNING : With the specified retention rules, all the files in the specified
directory will be deleted. If you only specified -m and / or -w, it means that
there is no file in the directory that match your retention rules. Please look
at --day-of-week or --day-of-month options.
If you really know ... | conditional_block |
e621.py | # The MIT License (MIT)
# Copyright (c) 2016 HeyItsShuga
# 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
# to use, copy, modify,... |
def import_submission(self, submission: praw.objects.Submission) -> dict:
"""Import a submission from e621.
This function will define the following values in its return data:
- author: simply "an anonymous user on e621"
- source: The url of the submission
- importer_displa... | """Initialize the e621 importer.
:param useragent: The useragent to use for querying e621.
:param options: Other options in the configuration. Ignored.
"""
self.log = logging.getLogger('lapis.e621')
self.headers = {'User-Agent': useragent}
self.regex = re.compile(
... | identifier_body |
e621.py | # The MIT License (MIT)
# Copyright (c) 2016 HeyItsShuga
# 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
# to use, copy, modify,... | (self, submission: praw.objects.Submission) -> dict:
"""Import a submission from e621.
This function will define the following values in its return data:
- author: simply "an anonymous user on e621"
- source: The url of the submission
- importer_display/header
- import_u... | import_submission | identifier_name |
e621.py | # The MIT License (MIT)
# Copyright (c) 2016 HeyItsShuga
# 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
# to use, copy, modify,... |
endpoint = 'http://e926.net/post/show.json?id=' + post_id
service = match.group('service')
self.log.debug('Will use API endpoint at %s', endpoint)
# We will use the e621 API to get the image URL.
callapi = requests.get(endpoint)
json = callapi.jso... | self.log.debug('No CDN used, md5 retrieval not neccesary.')
# For non-CDN links, the plugin attempts to get the post_id
# out of the URL using regex.
post_id = match.group('post_id') | conditional_block |
e621.py | # The MIT License (MIT)
# Copyright (c) 2016 HeyItsShuga
# 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
# to use, copy, modify,... | - source: The url of the submission
- importer_display/header
- import_urls
After we define that, we need to get the image. Since e621 has an
API, we use that to try to get the image if the image is a non-CDN URL.
If it is a CDN URL, we take the image directory and uploa... |
This function will define the following values in its return data:
- author: simply "an anonymous user on e621" | random_line_split |
TftpContexts.py | .0
log.debug("TftpMetrics.compute: kbps is %s", self.kbps)
for key in self.dups:
self.dupcount += self.dups[key]
def add_dup(self, pkt):
"""This method adds a dup for a packet to the metrics."""
log.debug("Recording a dup of %s", pkt)
s = str(pkt)
if s in... | (self):
log.info("Sending tftp upload request to %s" % self.host)
log.info(" filename -> %s" % self.file_to_transfer)
log.info(" options -> %s" % self.options)
self.metrics.start_time = time.time()
log.debug("Set metrics.start_time to %s" % self.metrics.start_time)
... | start | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.