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 |
|---|---|---|---|---|
impl_gcd.py | __author__ = 'Nishanth'
from juliabox.cloud import JBPluginCloud
from juliabox.jbox_util import JBoxCfg, retry_on_errors
from googleapiclient.discovery import build | from oauth2client.client import GoogleCredentials
import threading
class JBoxGCD(JBPluginCloud):
provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JBP_DNS_GCD]
threadlocal = threading.local()
INSTALLID = None
REGION = None
DOMAIN = None
@staticmethod
def configure():
cloud_host = JB... | random_line_split | |
impl_gcd.py | __author__ = 'Nishanth'
from juliabox.cloud import JBPluginCloud
from juliabox.jbox_util import JBoxCfg, retry_on_errors
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
import threading
class JBoxGCD(JBPluginCloud):
provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JB... | cname = resp['rrsets'][0]['rrdatas'][0]
ttl = resp['rrsets'][0]['ttl']
JBoxGCD.connect().changes().create(
project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION,
body={'kind': 'dns#change',
'deletions': [
{'rrdatas':... | conditional_block | |
impl_gcd.py | __author__ = 'Nishanth'
from juliabox.cloud import JBPluginCloud
from juliabox.jbox_util import JBoxCfg, retry_on_errors
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
import threading
class JBoxGCD(JBPluginCloud):
provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JB... | (name):
resp = JBoxGCD.connect().resourceRecordSets().list(
project=JBoxGCD.INSTALLID, managedZone=JBoxGCD.REGION,
name=name, type='A').execute()
if len(resp['rrsets']) == 0:
JBoxGCD.log_debug('No prior dns registration found for %s', name)
else:
c... | delete_cname | identifier_name |
impl_gcd.py | __author__ = 'Nishanth'
from juliabox.cloud import JBPluginCloud
from juliabox.jbox_util import JBoxCfg, retry_on_errors
from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
import threading
class JBoxGCD(JBPluginCloud):
provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JB... |
@staticmethod
def domain():
if JBoxGCD.DOMAIN is None:
JBoxGCD.configure()
return JBoxGCD.DOMAIN
@staticmethod
def connect():
c = getattr(JBoxGCD.threadlocal, 'conn', None)
if c is None:
JBoxGCD.configure()
creds = GoogleCredentials.... | cloud_host = JBoxCfg.get('cloud_host')
JBoxGCD.INSTALLID = cloud_host['install_id']
JBoxGCD.REGION = cloud_host['region']
JBoxGCD.DOMAIN = cloud_host['domain'] | identifier_body |
test_vxlan.py | #!/usr/bin/env python
import socket
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCas... | (self, pkt, vni):
"""
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
UDP(... | encapsulate | identifier_name |
test_vxlan.py | #!/usr/bin/env python
|
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCase):
""" VXLAN Test Case """
def __init__(self, *args):
BridgeDomain.__init__(self)
VppTestCase.__init__(self, *arg... | import socket
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain | random_line_split |
test_vxlan.py | #!/usr/bin/env python
import socket
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCas... |
# Verify VXLAN tunnel source IP is VPP_IP and destination IP is MY_IP.
self.assertEqual(pkt[IP].src, self.pg0.local_ip4)
if not local_only:
self.assertEqual(pkt[IP].dst, self.pg0.remote_ip4)
# Verify UDP destination port is VXLAN 4789, source UDP port could be
# arb... | self.assertEqual(pkt[Ether].dst, self.pg0.remote_mac) | conditional_block |
test_vxlan.py | #!/usr/bin/env python
import socket
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCas... |
@classmethod
def del_mcast_load(cls):
cls.add_del_mcast_load(is_add=0)
# Class method to start the VXLAN test case.
# Overrides setUpClass method in VppTestCase class.
# Python try..except statement is used to ensure that the tear down of
# the class will be executed even if except... | cls.add_del_mcast_load(is_add=1) | identifier_body |
test_vmware_methods.py | """This module contains tests that exercise the canned VMware Automate stuff."""
from textwrap import dedent
import fauxfactory
import pytest
from widgetastic.widget import View
from widgetastic_patternfly import Dropdown
from cfme import test_requirements
from cfme.common import BaseLoggedInPage
from cfme.infrastruc... | (
appliance, request, testing_group, testing_vm, domain, cls):
"""Tests hot adding a disk to vmware vm. This test exercises the `VMware_HotAdd_Disk` method,
located in `/Integration/VMware/VimApi`
Polarion:
assignee: ghubale
initialEstimate: 1/8h
casecomponent: Automate
... | test_vmware_vimapi_hotadd_disk | identifier_name |
test_vmware_methods.py | """This module contains tests that exercise the canned VMware Automate stuff."""
from textwrap import dedent
import fauxfactory
import pytest
from widgetastic.widget import View
from widgetastic_patternfly import Dropdown
from cfme import test_requirements
from cfme.common import BaseLoggedInPage
from cfme.infrastruc... |
def test_vmware_vimapi_hotadd_disk(
appliance, request, testing_group, testing_vm, domain, cls):
"""Tests hot adding a disk to vmware vm. This test exercises the `VMware_HotAdd_Disk` method,
located in `/Integration/VMware/VimApi`
Polarion:
assignee: ghubale
initialEstimate: 1... | collection = provider.appliance.provider_based_collection(provider)
try:
template_name = provider.data['templates']['full_template']['name']
except KeyError:
pytest.skip('Unable to identify full_template for provider: {}'.format(provider))
vm = collection.instantiate(
random_vm_name... | identifier_body |
test_vmware_methods.py | """This module contains tests that exercise the canned VMware Automate stuff."""
from textwrap import dedent
import fauxfactory
import pytest
from widgetastic.widget import View
from widgetastic_patternfly import Dropdown
from cfme import test_requirements
from cfme.common import BaseLoggedInPage
from cfme.infrastruc... |
@pytest.fixture(scope="module")
def cls(domain):
original_class = domain.parent\
.instantiate(name='ManageIQ')\
.namespaces.instantiate(name='System')\
.classes.instantiate(name='Request')
original_class.copy_to(domain=domain)
return domain.namespaces.instantiate(name='System').cla... | random_line_split | |
constants.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::file_format::{Constant, SignatureToken};
use move_core_types::account_address::AccountAddress;
use proptest::{
arbitrary::any,
collection::{btree_set, vec, SizeRange},
strategy::Strategy,
};
// A `ConstantPoolGen... | (
address_count: impl Into<SizeRange>,
byte_array_count: impl Into<SizeRange>,
) -> impl Strategy<Value = Self> {
// get unique sets of addresses and vector<U8> (empty vector allowed)
(
btree_set(any::<AccountAddress>(), address_count),
btree_set(vec(any::<u8>... | strategy | identifier_name |
constants.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::file_format::{Constant, SignatureToken};
use move_core_types::account_address::AccountAddress;
use proptest::{
arbitrary::any,
collection::{btree_set, vec, SizeRange},
strategy::Strategy,
};
// A `ConstantPoolGen... | })
}
// Return the `ConstantPool`
pub fn constant_pool(self) -> Vec<Constant> {
let mut constants = vec![];
for address in self.addresses {
constants.push(Constant {
type_: SignatureToken::Address,
data: address.to_vec(),
}... | .prop_map(|(addresses, byte_arrays)| Self {
addresses: addresses.into_iter().collect(),
byte_arrays: byte_arrays.into_iter().collect(), | random_line_split |
constants.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::file_format::{Constant, SignatureToken};
use move_core_types::account_address::AccountAddress;
use proptest::{
arbitrary::any,
collection::{btree_set, vec, SizeRange},
strategy::Strategy,
};
// A `ConstantPoolGen... |
byte_array.push(byte_array.len() as u8);
byte_array.reverse();
constants.push(Constant {
type_: SignatureToken::Vector(Box::new(SignatureToken::U8)),
data: byte_array,
});
}
constants
}
}
| {
continue;
} | conditional_block |
free.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (a... | /// Create an empty `Cell`.
pub fn cell(&self) -> Cell {
Cell::empty(self.empty.clone())
}
/// Reuse or create a new `Row`.
pub fn pop(&mut self, cols: usize) -> Row {
match self.inner.pop_front() {
Some(mut row) => {
row.wrapped = false;
row.resize(cols, Cell::empty(self.empty.clone()));
for ... | self.empty.clone()
}
| identifier_body |
free.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (a... | mut self, cols: usize) -> Row {
match self.inner.pop_front() {
Some(mut row) => {
row.wrapped = false;
row.resize(cols, Cell::empty(self.empty.clone()));
for cell in row.iter_mut().filter(|c| !c.is_default()) {
cell.make_empty(self.empty.clone());
}
row
}
None => {
Row {
... | p(& | identifier_name |
free.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (a... |
/// Get the empty `Style`.
pub fn style(&self) -> Rc<Style> {
self.empty.clone()
}
/// Create an empty `Cell`.
pub fn cell(&self) -> Cell {
Cell::empty(self.empty.clone())
}
/// Reuse or create a new `Row`.
pub fn pop(&mut self, cols: usize) -> Row {
match self.inner.pop_front() {
Some(mut row) => {... | random_line_split | |
HtmlWorker.ts | import { Annotation } from "../editor/Annotation";
import { Mirror } from "./Mirror";
import { SAXParser } from "../mode//html/SAXParser";
import { WorkerCallback } from "./WorkerCallback";
// Map certain codes from the SAXParser into an Annotation type.
// Everything else gets mapped to an "error" type.
const codeToA... |
else {
parser.parse(value);
}
}
this.emitAnnotations(annotations);
}
}
| {
parser.parseFragment(value, this.context);
} | conditional_block |
HtmlWorker.ts | import { Annotation } from "../editor/Annotation";
import { Mirror } from "./Mirror";
import { SAXParser } from "../mode//html/SAXParser";
import { WorkerCallback } from "./WorkerCallback";
// Map certain codes from the SAXParser into an Annotation type.
// Everything else gets mapped to an "error" type.
const codeToA... | /**
*
*/
setOptions(options?: { context }) {
if (options) {
this.context = options.context;
}
else {
this.context = void 0;
}
if (this.doc.getValue()) {
this.deferredUpdate.schedule(100);
}
}
/**
*
*... | random_line_split | |
HtmlWorker.ts | import { Annotation } from "../editor/Annotation";
import { Mirror } from "./Mirror";
import { SAXParser } from "../mode//html/SAXParser";
import { WorkerCallback } from "./WorkerCallback";
// Map certain codes from the SAXParser into an Annotation type.
// Everything else gets mapped to an "error" type.
const codeToA... | (options?: { context }) {
if (options) {
this.context = options.context;
}
else {
this.context = void 0;
}
if (this.doc.getValue()) {
this.deferredUpdate.schedule(100);
}
}
/**
*
*/
protected onUpdate(): void {
... | setOptions | identifier_name |
HtmlWorker.ts | import { Annotation } from "../editor/Annotation";
import { Mirror } from "./Mirror";
import { SAXParser } from "../mode//html/SAXParser";
import { WorkerCallback } from "./WorkerCallback";
// Map certain codes from the SAXParser into an Annotation type.
// Everything else gets mapped to an "error" type.
const codeToA... |
/**
*
*/
protected onUpdate(): void {
const annotations: Annotation[] = [];
const value = this.doc.getValue();
if (!value) {
this.emitAnnotations(annotations);
return;
}
const parser = new SAXParser();
if (parser) {
... | {
if (options) {
this.context = options.context;
}
else {
this.context = void 0;
}
if (this.doc.getValue()) {
this.deferredUpdate.schedule(100);
}
} | identifier_body |
main.js | .png',
'res/game_music.mp3',
'res/bullet.mp3',
'res/enemy1_down.mp3' | ]
, function() {
/**
* 游戏场景
* @type {void|*}
*/
var GameScene = cc.Scene.extend({
_enemies: [],//敌机列表
_enemyBullets: [],//敌机子弹
_plane: null,//我方飞机
_planeBullets: [],//我房子弹
_gameLayer: null,
_hitCount: 0,
life: 10,
updateGame: function() {
//我方子弹... | random_line_split | |
main.js | .png',
'res/game_music.mp3',
'res/bullet.mp3',
'res/enemy1_down.mp3'
]
, function() {
/**
* 游戏场景
* @type {void|*}
*/
var GameScene = cc.Scene.extend({
_enemies: [],//敌机列表
_enemyBullets: [],//敌机子弹
_plane: null,//我方飞机
_planeBullets: [],//我房子弹
_gameLayer: n... | this.setPosition(this.getPosition().x, this.getPosition().y + planeBulletSpeed);
if (this.getPosition().x < 0 || this.getPosition().x > 320 - 5 / 2 || this.getPosition().y > 504) {
_this._planeBullets.splice(_this._planeBullets.indexOf(this), 1);
_this._gameLayer.removeChild(this);
}
... | dule(function() {
| conditional_block |
camelize.js | // suites/camelize
require('../../../lib/node/monad');
var camelize = define.camelize;
var assert = require('assert');
/* TESTS START HERE */
suite('camelize');
test('exists', function () {
assert(typeof camelize == 'function');
});
test('path/to/file', function () {
assert(camelize('path/to/file') === 'file'... | assert(camelize('path/to/null') === 'null');
});
test('path/to/""', function () {
assert(camelize('path/to/""') === '""');
});
test('path/to/0', function () {
assert(camelize('path/to/0') === '0');
});
test('path/to/""', function () {
assert(camelize('path/to/-1') === '-1');
});
test('path/to/true', functio... | });
test('path/to/null', function () { | random_line_split |
jquery.flot.time.js | "Dec"];
}
if (dayNames == null) {
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
var hours12;
if (hours > 12) {
hours12 = hours - 12;
} else if (hours == 0) {
hours12 = 12;
} else {
hours12 = hours;
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case '... | (d) {
function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
sourceObj[sourceMethod] = function() {
return targetObj[targetMethod].apply(targetObj, arguments);
};
};
var utc = {
date: d
};
// support strftime, if found
if (d.strftime != undefined) {
addProxyMethod(utc, "strftime", d, "strftime"... | makeUtcWrapper | identifier_name |
jquery.flot.time.js | 'H': c = leftPad(hours); break;
case 'I': c = leftPad(hours12); break;
case 'l': c = leftPad(hours12, " "); break;
case 'm': c = leftPad(d.getMonth() + 1); break;
case 'M': c = leftPad(d.getMinutes()); break;
// quarters not in Open Group's strftime specification
case 'q':
c = "" + (Math.floor(d.getMonth() / 3) + 1); ... | {
prev = v;
v = d.getTime();
ticks.push(v);
if (unit == "month" || unit == "quarter") {
if (tickSize < 1) {
// a bit complicated - we'll divide the
// month/quarter up but we need to take
// care of fractions so we don't end up in
// the middle of a day
d.setDate(1);
var start = d.getTime();
d.setMonth(d.getMonth()... | conditional_block | |
jquery.flot.time.js | "Dec"];
}
if (dayNames == null) {
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
var hours12;
if (hours > 12) {
hours12 = hours - 12;
} else if (hours == 0) {
hours12 = 12;
} else {
hours12 = hours;
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case '... |
// map of app. size of time units in milliseconds
var timeUnitSize = {
"second": 1000,
"minute": 60 * 1000,
"hour": 60 * 60 * 1000,
"day": 24 * 60 * 60 * 1000,
"month": 30 * 24 * 60 * 60 * 1000,
"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
"year": 365.2425 * 24 * 60 * 60 * 1000
};
// the allowed tick sizes, after 1 yea... | {
if (opts.timezone == "browser") {
return new Date(ts);
} else if (!opts.timezone || opts.timezone == "utc") {
return makeUtcWrapper(new Date(ts));
} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
var d = new timezoneJS.Date();
// timezone-js is fickle, so be sure to set the time... | identifier_body |
jquery.flot.time.js | ", "Dec"];
}
if (dayNames == null) {
dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
}
var hours12;
if (hours > 12) {
hours12 = hours - 12;
} else if (hours == 0) {
hours12 = 12;
} else {
hours12 = hours;
}
for (var i = 0; i < fmt.length; ++i) {
var c = fmt.charAt(i);
if (escape) {
switch (c) {
case... | case 'l': c = leftPad(hours12, " "); break;
case 'm': c = leftPad(d.getMonth() + 1); break;
case 'M': c = leftPad(d.getMinutes()); break;
// quarters not in Open Group's strftime specification
case 'q':
c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
case 'S': c = leftPad(d.getSeconds()); break;
case 'y': c = leftP... | case 'h': // For back-compat with 0.7; remove in 1.0
case 'H': c = leftPad(hours); break;
case 'I': c = leftPad(hours12); break; | random_line_split |
api-bus-raw.js | /**
* This module provides our external API functionality.
* | *
*/
var septa = require("../lib/septa/bus/main.js");
var util = require("util");
/**
* This function is our main entry point.
*/
exports.go = function(request, response) {
var retval = "";
septa.getRawData().then( (in_data) => {
var data = {};
data["data"] = in_data;
data["_comment"] = "Raw bus data fro... | * @author Douglas Muth <http://www.dmuth.org/> | random_line_split |
NodeRowGroup.tsx | import {
createStyles,
makeStyles,
TableCell,
TableRow,
Theme,
} from "@material-ui/core";
import AddIcon from "@material-ui/icons/Add";
import RemoveIcon from "@material-ui/icons/Remove";
import classNames from "classnames";
import React, { useState } from "react";
import { NodeInfoResponse } from "../../../... | </TableCell>
</TableRow>
)}
{workerFeatureData.map((featureData, index: number) => {
return (
<NodeWorkerRow
key={index}
features={features.map(
(feature) => feature.WorkerFeatureRenderFn,
... | random_line_split | |
file.py | from collections import namedtuple
import fcntl
import os
import shutil
from pcs.common.tools import format_os_error
# TODO add logging (logger / debug reports ?) to the RawFile class; be aware
# the class is used both in pcs.cli and pcs.lib packages
FileMetadata = namedtuple(
"FileMetadata",
[
"file... | (self, fail_if_file_not_found=True):
get_raw_file_error = lambda e: RawFileError(
self.metadata, RawFileError.ACTION_REMOVE, format_os_error(e)
)
try:
os.remove(self.metadata.path)
except FileNotFoundError as e:
if fail_if_file_not_found:
... | remove | identifier_name |
file.py | from collections import namedtuple
import fcntl
import os
import shutil
from pcs.common.tools import format_os_error
# TODO add logging (logger / debug reports ?) to the RawFile class; be aware
# the class is used both in pcs.cli and pcs.lib packages
FileMetadata = namedtuple(
"FileMetadata",
[
"file... | def exists(self):
# Returns False if the file is not accessible, does not raise.
return os.path.exists(self.metadata.path)
def read(self):
try:
mode = "rb" if self.metadata.is_binary else "r"
with open(self.metadata.path, mode) as my_file:
# the l... | class RawFile(RawFileInterface): | random_line_split |
file.py | from collections import namedtuple
import fcntl
import os
import shutil
from pcs.common.tools import format_os_error
# TODO add logging (logger / debug reports ?) to the RawFile class; be aware
# the class is used both in pcs.cli and pcs.lib packages
FileMetadata = namedtuple(
"FileMetadata",
[
"file... |
# Write file data
my_file.write(
file_data
if self.metadata.is_binary
else file_data.decode("utf-8")
)
except FileExistsError as e:
raise FileAlreadyExists(self.metadata) from e
excep... | try:
os.chmod(my_file.fileno(), self.metadata.permissions)
except OSError as e:
raise RawFileError(
self.metadata,
RawFileError.ACTION_CHMOD,
format_os_error(e),
... | conditional_block |
file.py | from collections import namedtuple
import fcntl
import os
import shutil
from pcs.common.tools import format_os_error
# TODO add logging (logger / debug reports ?) to the RawFile class; be aware
# the class is used both in pcs.cli and pcs.lib packages
FileMetadata = namedtuple(
"FileMetadata",
[
"file... | try:
shutil.chown(
self.metadata.path,
self.metadata.owner_user_name,
self.metadata.owner_group_name,
)
except LookupError as e:
... | try:
mode = "{write_mode}{binary_mode}".format(
write_mode="w" if can_overwrite else "x",
binary_mode="b" if self.metadata.is_binary else "",
)
# It seems pylint cannot process constructing the mode variable and
# gives a false positive.
... | identifier_body |
candlestick.d.ts | import { OhclData } from './ohcl';
export interface CandlestickData {
type: 'candlestick';
name: OhclData['name'];
/**
* @default true
*/
visible: OhclData['visible'];
/**
* @default true
*/
showlegend: OhclData['showlegend'];
/**
* number between 0 and 1
* ... | line: { width?: number | undefined };
increasing: {
line?: {
color?: string | undefined;
width?: number | undefined;
} | undefined;
};
decreasing: {
line?: {
color?: string | undefined;
width?: number | undefined;
} | unde... | */ | random_line_split |
base.py | #
# Author: Endre Karlson <endre.karlson@gmail.com>
#
# 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 o... |
class CreateCommand(Command, ShowOne):
action = 'create'
def post_execute(self, results):
return results.keys(), results.values()
class UpdateCommand(Command, ShowOne):
action = 'update'
def post_execute(self, results):
return results.keys(), results.values()
class DeleteCommand... | action = 'get'
def post_execute(self, results):
return results.keys(), results.values() | identifier_body |
base.py | #
# Author: Endre Karlson <endre.karlson@gmail.com>
#
# 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 o... | (Command):
action = 'delete'
__all__ = ["Command", "ListCommand", "GetCommand", "CreateCommand",
"UpdateCommand", "DeleteCommand"]
| DeleteCommand | identifier_name |
base.py | #
# Author: Endre Karlson <endre.karlson@gmail.com>
#
# 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 o... |
else:
return [], ()
class GetCommand(Command, ShowOne):
action = 'get'
def post_execute(self, results):
return results.keys(), results.values()
class CreateCommand(Command, ShowOne):
action = 'create'
def post_execute(self, results):
return results.keys(), resu... | columns = utils.get_columns(results)
data = [utils.get_item_properties(i, columns) for i in results]
return columns, data | conditional_block |
base.py | #
# Author: Endre Karlson <endre.karlson@gmail.com>
#
# 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 o... |
class DeleteCommand(Command):
action = 'delete'
__all__ = ["Command", "ListCommand", "GetCommand", "CreateCommand",
"UpdateCommand", "DeleteCommand"] | action = 'update'
def post_execute(self, results):
return results.keys(), results.values() | random_line_split |
Xml.js | /**
* @author Ed Spencer
* @class Ext.data.writer.Xml
This class is used to write {@link Ext.data.Model} data to the server in an XML format.
The {@link #documentRoot} property is used to specify the root element in the XML document.
The {@link #record} option is used to specify the element name for each record that... | output.push('>');
output.push.apply(output, subOutput);
// Output any embedded nodes that were specified by child element mappings like "SystemInfo>SystemName"
if (subObjects) {
for (key in subObjects) {
datum = subObjects[key];
this.objectToE... | }
} | random_line_split |
Xml.js | /**
* @author Ed Spencer
* @class Ext.data.writer.Xml
This class is used to write {@link Ext.data.Model} data to the server in an XML format.
The {@link #documentRoot} property is used to specify the root element in the XML document.
The {@link #record} option is used to specify the element name for each record that... | subOutput.push('<', key, '>', datum, '</', key, '>');
}
}
}
}
output.push('>');
output.push.apply(output, subOutput);
// Output any embedded nodes that were specified by child element mappings like "SystemInfo>Syst... | {
// Object properties become child elements
if (typeof datum === 'object') {
this.objectToElement(key, datum, subOutput);
} else {
// Is it a selector?
subKeys = key.match(this.selectorRe);
... | conditional_block |
files.py | from functools import lru_cache
import os
import rethinkdb as r
from sondra.document.schema_parser import ValueHandler
try:
from werkzeug.utils import secure_filename
except ImportError:
import re
def secure_filename(name):
name = re.sub(r'\s+', '-', name) # Replace white space with dash
... | (self, collection):
return collection.application.connection
@lru_cache()
def _table_name(self, collection):
return "_sondra_files__{collection}".format(collection=collection.name)
@lru_cache()
def _table(self, collection):
db = self._db(collection)
conn = self._conn(co... | _conn | identifier_name |
files.py | from functools import lru_cache
import os
import rethinkdb as r
from sondra.document.schema_parser import ValueHandler
try:
from werkzeug.utils import secure_filename
except ImportError:
import re
def secure_filename(name):
name = re.sub(r'\s+', '-', name) # Replace white space with dash
... |
class FileHandler(ValueHandler):
def __init__(self, storage_service, key, content_type='application/octet-stream'):
self._storage_service = storage_service
self._key = key
self._content_type = content_type
def post_save(self, document):
self._storage_service.assoc(document, d... | return '/'.join(_strip_slashes(p) for p in paths) | identifier_body |
files.py | from functools import lru_cache
import os
import rethinkdb as r
from sondra.document.schema_parser import ValueHandler
try:
from werkzeug.utils import secure_filename
except ImportError:
import re
def secure_filename(name):
name = re.sub(r'\s+', '-', name) # Replace white space with dash
... |
else:
return self._storage_service.store(
document=document,
key=self._key,
original_filename=getattr(value, "filename", "uploaded-file.dat"),
content_type=self._content_type,
stream=value
)
class FileStor... | return super().to_rql_repr(value, document) | conditional_block |
files.py | from functools import lru_cache
import os
import rethinkdb as r
from sondra.document.schema_parser import ValueHandler
try:
from werkzeug.utils import secure_filename
except ImportError:
import re
def secure_filename(name):
name = re.sub(r'\s+', '-', name) # Replace white space with dash
... | app, coll, pk = url[self._path_start:].split('/', 2)
pk, ext = os.path.splitext(pk)
collection = self._suite[app][coll]
record = self._table(collection).get(pk).run(self._conn(collection))
in_stream = self.stream_file(collection, pk + ext)
return {
"content_ty... | .delete()\
.run(self._conn(document.collection))
def stream(self, url): | random_line_split |
client.py | import aioamqp
import asyncio
import umsgpack as msgpack
import logging
from functools import wraps
from uuid import uuid4
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class RemoteException(Exception):
pass
class Client(object):
def __init__(se... |
self._response = None
self._corr_id = str(uuid4())
payload = msgpack.packb((method, args, kwargs))
logger.info(f'Publishing to {self._queue}: {method} ({self._corr_id})')
await self._channel.basic_publish(
payload=payload,
exchange_name='',
r... | await self._connect(host=self._host, port=self._port, ssl=self._ssl) | conditional_block |
client.py | import aioamqp
import asyncio
import umsgpack as msgpack
import logging
from functools import wraps
from uuid import uuid4
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class RemoteException(Exception):
pass
class Client(object):
def __init__(se... | (self, channel, body, envelope, properties):
if self._corr_id == properties.correlation_id:
self._response = body
logger.info(f'Received response for {self._corr_id}')
self._waiter.set()
async def __call__(self, method, *args, **kwargs):
if not self._protocol:
... | _on_response | identifier_name |
client.py | import aioamqp
import asyncio
import umsgpack as msgpack
import logging
from functools import wraps
from uuid import uuid4
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class RemoteException(Exception):
pass
class Client(object):
def __init__(se... |
async def __call__(self, method, *args, **kwargs):
if not self._protocol:
await self._connect(host=self._host, port=self._port, ssl=self._ssl)
self._response = None
self._corr_id = str(uuid4())
payload = msgpack.packb((method, args, kwargs))
logger.info(f'Publi... | if self._corr_id == properties.correlation_id:
self._response = body
logger.info(f'Received response for {self._corr_id}')
self._waiter.set() | identifier_body |
client.py | import aioamqp
import asyncio
import umsgpack as msgpack
import logging
from functools import wraps
from uuid import uuid4
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class RemoteException(Exception):
pass
class Client(object):
def __init__(se... | await self._waiter.wait()
await self._protocol.close()
try:
exc, result = msgpack.unpackb(self._response)
except Exception as err:
logger.error(f'Could not unpack response: {err}')
return None
if exc is not None:
raise RemoteExcept... | 'correlation_id': self._corr_id,
},
)
logger.info(f'Waiting for response on queue {self._callback_queue} ({self._corr_id})') | random_line_split |
kasmir.success.js | import { assert, expect } from 'chai';
import Kasmir from '../../src/kasmir';
import config from '../fixtures/config/test.config';
describe('Kasmir - successful test', () => {
let k;
let r; | k = new Kasmir(config);
k.initReady().then(done);
});
it('should report no error', (done) => {
k.run(["Open success", "End"]).then(() => {
r = k.getReport();
expect(typeof r).to.equal('object');
expect(typeof r.taskSummary).to.equal('object');
expect(r.taskSummary.length).to.equ... |
// Initialize kasmir with some test actions and the
// default config
beforeEach('initialize kasmir instance', (done) => { | random_line_split |
to_csv.py | """Export Module"""
import csv
import io
import logging
import zipfile
import bpy
import bpy_extras
from .. import model
from .. import pam
logger = logging.getLogger(__package__)
def getUVs(object, particle_system):
""" returns a numpy-array of uv - coordinates for a given particle-system
on a given obj... | :param numpy.Array matrix: a matrix
"""
output = io.StringIO()
writer = csv.writer(
output,
delimiter=";",
quoting=csv.QUOTE_NONNUMERIC
)
for row in matrix:
writer.writerow(row)
file.writestr("%s.csv" % (name), output.getvalue())
def csv_write_matrices(file... | :param str name: name of file | random_line_split |
to_csv.py | """Export Module"""
import csv
import io
import logging
import zipfile
import bpy
import bpy_extras
from .. import model
from .. import pam
logger = logging.getLogger(__package__)
def getUVs(object, particle_system):
""" returns a numpy-array of uv - coordinates for a given particle-system
on a given obj... | (filepath):
"""Export connection and distance-informations
:param str filepath: export filename
.. note::
* cmatrices: list of connection matrices
* dmatrices: list of distance matrices
* nglist: list of neural groups
* connection_list: list of layer-based connections
... | export_connections | identifier_name |
to_csv.py | """Export Module"""
import csv
import io
import logging
import zipfile
import bpy
import bpy_extras
from .. import model
from .. import pam
logger = logging.getLogger(__package__)
def getUVs(object, particle_system):
""" returns a numpy-array of uv - coordinates for a given particle-system
on a given obj... |
def get_mapping_names():
"""Return names of mappings
:return: names of mappings
:rtype: list
"""
m = bpy.context.scene.pam_mapping
return [s.name for s in m.sets]
class PAMModelExportCSV(bpy.types.Operator, bpy_extras.io_utils.ExportHelper):
"""Export model to csv"""
bl_idname = ... | output = io.StringIO()
writer = csv.writer(
output,
delimiter=";",
quoting=csv.QUOTE_NONNUMERIC
)
for row in matrix:
writer.writerow(row)
file.writestr("%i_%s.csv" % (i, suffix), output.getvalue()) | conditional_block |
to_csv.py | """Export Module"""
import csv
import io
import logging
import zipfile
import bpy
import bpy_extras
from .. import model
from .. import pam
logger = logging.getLogger(__package__)
def getUVs(object, particle_system):
""" returns a numpy-array of uv - coordinates for a given particle-system
on a given obj... | """Call upon module unregister"""
pass | identifier_body | |
handlebars.d.ts | // Type definitions for Handlebars 1.0
// Project: http://handlebarsjs.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Use either HandlebarsStatic or HandlebarsRuntimeStatic
declare var Handlebars: HandlebarsStatic;
//declare var... | type: string;
}
class ProgramNode extends NodeBase {
statements: NodeBase[];
}
class IdNode extends NodeBase {
original: string;
parts: string[];
string: string;
depth: number;
idName: string;
... | lastColumn: number;
lastLine: number; | random_line_split |
handlebars.d.ts | // Type definitions for Handlebars 1.0
// Project: http://handlebarsjs.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Use either HandlebarsStatic or HandlebarsRuntimeStatic
declare var Handlebars: HandlebarsStatic;
//declare var... | extends NodeBase {
strip: IStripInfo;
escaped: boolean;
sexpr: SexprNode;
}
class BlockNode extends NodeBase {
mustache: MustacheNode;
program: ProgramNode;
inverse: ProgramNode;
strip: IStripInfo;
isInver... | MustacheNode | identifier_name |
details.polyfill.js | // <details> polyfill
// http://caniuse.com/#feat=details
// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737
// http://www.sitepoint.com/fixing-the-details-element/
;(function() {
'use strict'
var NATIVE_DETAILS = typeof document.createElement('details').ope... | (summary) {
var expanded = summary.__details.__summary.getAttribute('aria-expanded') === 'true'
var hidden = summary.__details.__content.getAttribute('aria-hidden') === 'true'
summary.__details.__summary.setAttribute('aria-expanded', expanded ? 'false' : 'true')
summary.__details.__content.setA... | statechange | identifier_name |
details.polyfill.js | // <details> polyfill
// http://caniuse.com/#feat=details
// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737
// http://www.sitepoint.com/fixing-the-details-element/
;(function() {
'use strict'
var NATIVE_DETAILS = typeof document.createElement('details').ope... | // Save shortcuts to the inner summary and content elements
details.__summary = details.getElementsByTagName('summary').item(0)
details.__content = details.getElementsByTagName('div').item(0)
// If the content doesn't have an ID, assign it one now
// which we'll need for the summary's ari... | {
// If this has already happened, just return
// else set the flag so it doesn't happen again
if (started) {
return
}
started = true
// Get the collection of details elements, but if that's empty
// then we don't need to bother with the rest of the scripting
if ((list = document.... | identifier_body |
details.polyfill.js | // <details> polyfill
// http://caniuse.com/#feat=details
// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737
// http://www.sitepoint.com/fixing-the-details-element/
;(function() {
'use strict'
var NATIVE_DETAILS = typeof document.createElement('details').ope... | if (e.preventDefault) {
e.preventDefault()
} else {
e.returnValue = false
}
}
}
})
// When the key comes up - check if it is enter(13) or space(32)
addEvent(node, 'keyup', function(e, target) {
if (e.keyCode === 13 || e.keyCode === 32... | // Prevent space(32) from scrolling the page
addEvent(node, 'keypress', function(e, target) {
if (target.nodeName === 'SUMMARY') {
if (e.keyCode === 32) { | random_line_split |
details.polyfill.js | // <details> polyfill
// http://caniuse.com/#feat=details
// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737
// http://www.sitepoint.com/fixing-the-details-element/
;(function() {
'use strict'
var NATIVE_DETAILS = typeof document.createElement('details').ope... | details.__summary.setAttribute('aria-controls', details.__content.id)
// Set tabIndex so the summary is keyboard accessible for non-native elements
// http://www.saliences.com/browserBugs/tabIndex.html
if (!NATIVE_DETAILS) {
details.__summary.tabIndex = 0
}
// Detect initia... | {
var details = list[i]
// Save shortcuts to the inner summary and content elements
details.__summary = details.getElementsByTagName('summary').item(0)
details.__content = details.getElementsByTagName('div').item(0)
// If the content doesn't have an ID, assign it one now
// which w... | conditional_block |
test_addresses.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import six
from django.core.exceptions import Validat... |
assert value in string_repr, "Field %s is not represented in %r" % (field, string_repr)
assert address.is_european_union, "Dog Fort, UK is in the EU"
assert list(address.split_name) == ["Dog", "Hello"], "Names split correctly"
assert address.first_name == "Dog", "Names split correctly"
assert ... | continue | conditional_block |
test_addresses.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import six
from django.core.exceptions import Validat... | ():
# We can save an address...
address = get_address()
address.save()
# mutate it...
address.name = u"Dog Hi"
# Then set it as immutable...
immutable_address = address.to_immutable()
immutable_address.save()
# And when we try to save it again, it fails...
immutable_address.name... | test_address_saving_retrieving_and_immutability | identifier_name |
test_addresses.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import six
from django.core.exceptions import Validat... | immutable_address.save()
# But to mutate the address, we can copy it...
address_copy = address.to_mutable()
assert not address_copy.pk
address_copy.save()
assert address_copy.pk != address.pk, "new address was saved as another entity"
@pytest.mark.django_db
def test_address_ownership(admi... | random_line_split | |
test_addresses.py | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
import six
from django.core.exceptions import Validat... |
@pytest.mark.django_db
def test_immutable_address():
address = get_address()
new_immutable = address.to_immutable()
# New address should be saved
assert new_immutable.pk != None
assert isinstance(new_immutable, ImmutableAddress)
assert get_data_dict(address).items() == get_data_dict(new_immu... | test_data = {
"name": "Test name",
"street": "Test street",
"postal_code": "1234567",
"city": "Test city",
"country": "US"
}
immutable_address = ImmutableAddress.from_data(test_data)
test_data.pop("postal_code")
# Since test_data does not include postal code from_... | identifier_body |
devtools.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::d... | (
documents: &Documents,
pipeline: PipelineId,
marker_types: Vec<TimelineMarkerType>,
) {
if let Some(window) = documents.find_window(pipeline) {
window.drop_devtools_timeline_markers(marker_types);
}
}
pub fn handle_request_animation_frame(documents: &Documents, id: PipelineId, actor_name:... | handle_drop_timeline_markers | identifier_name |
devtools.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::d... | EvaluateJSReply::StringValue(String::from(jsstring_to_str(*cx, rval.to_string())))
} else if rval.is_null() {
EvaluateJSReply::NullValue
} else {
assert!(rval.is_object());
rooted!(in(*cx) let obj = rval.to_object());
let class_name = CStr::fr... | {
// global.get_cx() returns a valid `JSContext` pointer, so this is safe.
let result = unsafe {
let cx = global.get_cx();
let _ac = enter_realm(global);
rooted!(in(*cx) let mut rval = UndefinedValue());
global.evaluate_js_on_global_with_result(&eval, rval.handle_mut());
... | identifier_body |
devtools.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::d... |
}
pub fn handle_request_animation_frame(documents: &Documents, id: PipelineId, actor_name: String) {
if let Some(doc) = documents.find_document(id) {
doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_name });
}
}
pub fn handle_reload(documents: &Documents, id: Pipeline... | {
window.drop_devtools_timeline_markers(marker_types);
} | conditional_block |
devtools.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use crate::d... | reply: IpcSender<Option<NodeInfo>>,
) {
let info = documents
.find_document(pipeline)
.and_then(|document| document.GetDocumentElement())
.map(|element| element.upcast::<Node>().summarize());
reply.send(info).unwrap();
}
fn find_node_by_unique_id(
documents: &Documents,
pipe... |
pub fn handle_get_document_element(
documents: &Documents,
pipeline: PipelineId, | random_line_split |
droidbox_compatible.py | )
self.apk_name = os.path.abspath(apk_name)
self.application = Application(apk_name)
ret = self.application.processAPK()
# Error during the APK processing?
if ret == 0:
print("Failed to analyze the APK. Terminate the analysis.")
sys.exit(1)
mai... | (self, duration=0):
droidbox_thread = threading.Thread(target=self.start_blocked, args=(duration,))
droidbox_thread.start()
def stop(self):
self.enabled = False
if self.timer and self.timer.isAlive():
self.timer.cancel()
if self.adb is not None:
self.... | start_unblocked | identifier_name |
droidbox_compatible.py | os.system("adb shell screencap -p | sed 's/\r$//' > %s" % os.path.join(self.output_dir, "screen") \
+ "_$(date +%Y-%m-%d_%H%M%S).png")
self.lastScreenshot = time.time()
logcatInput = self.adb.stdout.readline()
if not logcatInput:
... | """
Mark to stop this thread
"""
self.stop = True | identifier_body | |
droidbox_compatible.py |
else:
#Posibility that no output-files is generated
self.output_dir = None
def set_apk(self, apk_name):
if not self.enabled:
return
if apk_name is None:
return
# APK existing?
if not os.path.isfile(apk_name):
print... | os.mkdir(self.output_dir) | conditional_block | |
droidbox_compatible.py | )
self.apk_name = os.path.abspath(apk_name)
self.application = Application(apk_name)
ret = self.application.processAPK()
# Error during the APK processing?
if ret == 0:
print("Failed to analyze the APK. Terminate the analysis.")
sys.exit(1)
mai... | log_content['DataLeak']['path'] = self.accessedfiles[log_content['DataLeak']['id']]
if log_content['DataLeak']['operation'] == 'write':
log_content['DataLeak']['type'] = 'file write'
else:
... | self.sendnet[my_time] = log_content['DataLeak']
count.increaseCount()
elif log_content['DataLeak']['sink'] == 'File': | random_line_split |
server.rs | // You have to ctrl-C after running this benchmark, since there is no way to kill
// a rust-http server.
extern crate http;
extern crate hyper;
extern crate test;
use test::Bencher;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use http::server::Server;
use hyper::server::{Request, Response};
static PHRASE: &'stati... | (b: &mut Bencher) {
if unsafe { !created_http } {
spawn(proc() { HttpServer.serve_forever() });
unsafe { created_http = true }
// Mega hack because there is no way to wait for serve_forever to start:
std::io::timer::sleep(std::time::duration::Duration::seconds(1));
}
let url... | bench_http | identifier_name |
server.rs | // You have to ctrl-C after running this benchmark, since there is no way to kill
// a rust-http server.
extern crate http;
extern crate hyper;
extern crate test;
use test::Bencher;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use http::server::Server;
use hyper::server::{Request, Response};
static PHRASE: &'stati... |
#[bench]
fn bench_hyper(b: &mut Bencher) {
let server = hyper::Server::http(Ipv4Addr(127, 0, 0, 1), 0);
let mut listener = server.listen(hyper_handle).unwrap();
let url = hyper::Url::parse(format!("http://{}", listener.socket).as_slice()).unwrap();
b.iter(|| request(url.clone()));
listener.close(... | {
let mut res = res.start().unwrap();
res.write(PHRASE).unwrap();
res.end().unwrap();
} | identifier_body |
server.rs | // You have to ctrl-C after running this benchmark, since there is no way to kill
// a rust-http server.
extern crate http;
extern crate hyper;
extern crate test;
use test::Bencher;
use std::io::net::ip::{SocketAddr, Ipv4Addr}; |
fn request(url: hyper::Url) {
let req = hyper::client::Request::get(url).unwrap();
req.start().unwrap().send().unwrap().read_to_string().unwrap();
}
fn hyper_handle(_: Request, res: Response) {
let mut res = res.start().unwrap();
res.write(PHRASE).unwrap();
res.end().unwrap();
}
#[bench]
fn bench... |
use http::server::Server;
use hyper::server::{Request, Response};
static PHRASE: &'static [u8] = b"Benchmarking hyper vs others!"; | random_line_split |
server.rs | // You have to ctrl-C after running this benchmark, since there is no way to kill
// a rust-http server.
extern crate http;
extern crate hyper;
extern crate test;
use test::Bencher;
use std::io::net::ip::{SocketAddr, Ipv4Addr};
use http::server::Server;
use hyper::server::{Request, Response};
static PHRASE: &'stati... |
let url = hyper::Url::parse("http://localhost:4000").unwrap();
b.iter(|| request(url.clone()));
}
| {
spawn(proc() { HttpServer.serve_forever() });
unsafe { created_http = true }
// Mega hack because there is no way to wait for serve_forever to start:
std::io::timer::sleep(std::time::duration::Duration::seconds(1));
} | conditional_block |
chartDatasource.d.ts | import { BeanStub, CellRange, Column, IAggFunc } from "@ag-grid-community/core";
import { ColState } from "./chartDataModel";
export interface ChartDatasourceParams {
dimensionCols: ColState[];
grouping: boolean;
pivoting: boolean;
crossFiltering: boolean;
valueCols: Column[];
startRow: number;
... | extends BeanStub {
private readonly gridRowModel;
private readonly valueService;
private readonly columnController;
private readonly rowNodeSorter;
private sortController;
private readonly aggregationStage;
getData(params: ChartDatasourceParams): IData;
private extractRowsFromGridRowMod... | ChartDatasource | identifier_name |
chartDatasource.d.ts | import { BeanStub, CellRange, Column, IAggFunc } from "@ag-grid-community/core";
import { ColState } from "./chartDataModel";
export interface ChartDatasourceParams {
dimensionCols: ColState[];
grouping: boolean;
pivoting: boolean;
crossFiltering: boolean;
valueCols: Column[];
startRow: number;
... | private sortController;
private readonly aggregationStage;
getData(params: ChartDatasourceParams): IData;
private extractRowsFromGridRowModel;
private aggregateRowsByDimension;
private updatePivotKeysForSSRM;
private extractPivotKeySeparator;
private static getGroupLabels;
private ge... | private readonly rowNodeSorter; | random_line_split |
transcribe.rs | diagnostic::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{Eof, DocComment, Interpolated, MatchNt, SubstNt};
use parse::token::{Token, NtIdent};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use std::ops::Add;
use std::collections::HashMap... | }
} else { /* repeat */
*r.repeat_idx.last_mut().unwrap() += 1u;
r.stack.last_mut().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
... | r.repeat_idx.pop();
r.repeat_len.pop(); | random_line_split |
transcribe.rs | ::SpanHandler;
use ext::tt::macro_parser::{NamedMatch, MatchedSeq, MatchedNonterminal};
use parse::token::{Eof, DocComment, Interpolated, MatchNt, SubstNt};
use parse::token::{Token, NtIdent};
use parse::token;
use parse::lexer::TokenAndSpan;
use std::rc::Rc;
use std::ops::Add;
use std::collections::HashMap;
///an un... | (t: &TokenTree, r: &TtReader) -> LockstepIterSize {
match *t {
TtDelimited(_, ref delimed) => {
delimed.tts.iter().fold(LisUnconstrained, |size, tt| {
size + lockstep_iter_size(tt, r)
})
},
TtSequence(_, ref seq) => {
seq.tts.iter().fold(Li... | lockstep_iter_size | identifier_name |
virtual-scroll-viewport.ts | viewport',
templateUrl: 'virtual-scroll-viewport.html',
styleUrls: ['virtual-scroll-viewport.css'],
host: {
'class': 'cdk-virtual-scroll-viewport',
'[class.cdk-virtual-scroll-orientation-horizontal]': 'orientation === "horizontal"',
'[class.cdk-virtual-scroll-orientation-vertical]': 'orientation === "... | random_line_split | ||
virtual-scroll-viewport.ts | */
@Input() orientation: 'horizontal' | 'vertical' = 'vertical';
/** The element that wraps the rendered content. */
@ViewChild('contentWrapper') _contentWrapper: ElementRef;
/** A stream that emits whenever the rendered range changes. */
renderedRangeStream: Observable<ListRange> = this._renderedRangeSubj... | {
const viewportEl = this.elementRef.nativeElement;
this._viewportSize = this.orientation === 'horizontal' ?
viewportEl.clientWidth : viewportEl.clientHeight;
} | identifier_body | |
virtual-scroll-viewport.ts | viewport that virtualizes it's scrolling with the help of `CdkVirtualForOf`. */
@Component({
moduleId: module.id,
selector: 'cdk-virtual-scroll-viewport',
templateUrl: 'virtual-scroll-viewport.html',
styleUrls: ['virtual-scroll-viewport.css'],
host: {
'class': 'cdk-virtual-scroll-viewport',
'[class.c... |
}
/** Sets the currently rendered range of indices. */
setRenderedRange(range: ListRange) {
if (!rangesEqual(this._renderedRange, range)) {
this._renderedRangeSubject.next(this._renderedRange = range);
this._markChangeDetectionNeeded(() => this._scrollStrategy.onContentRendered());
}
}
... | {
this._totalContentSize = size;
this._markChangeDetectionNeeded();
} | conditional_block |
virtual-scroll-viewport.ts | (r1: ListRange, r2: ListRange): boolean {
return r1.start == r2.start && r1.end == r2.end;
}
/** A viewport that virtualizes it's scrolling with the help of `CdkVirtualForOf`. */
@Component({
moduleId: module.id,
selector: 'cdk-virtual-scroll-viewport',
templateUrl: 'virtual-scroll-viewport.html',
styleUrls... | rangesEqual | identifier_name | |
test_security.py | # 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/.
from firefox_puppeteer import PuppeteerMixin
from firefox_puppeteer.errors import NoCertificateError
from marionette_har... | with self.marionette.using_context(self.marionette.CONTEXT_CONTENT):
self.marionette.navigate(url)
cert = self.browser.tabbar.tabs[0].certificate
self.assertIn(cert['commonName'], url)
self.assertEqual(cert['organization'], 'Mozilla Corporation')
self.assertEqual(cer... | def test_get_address_from_certificate(self):
url = 'https://ssl-ev.mozqa.com'
| random_line_split |
test_security.py | # 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/.
from firefox_puppeteer import PuppeteerMixin
from firefox_puppeteer.errors import NoCertificateError
from marionette_har... | (self):
url_http = self.marionette.absolute_url('layout/mozilla.html')
url_https = 'https://ssl-ev.mozqa.com'
# Test EV certificate
with self.marionette.using_context(self.marionette.CONTEXT_CONTENT):
self.marionette.navigate(url_https)
cert = self.browser.tabbar.tab... | test_get_certificate | identifier_name |
test_security.py | # 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/.
from firefox_puppeteer import PuppeteerMixin
from firefox_puppeteer.errors import NoCertificateError
from marionette_har... |
def test_get_certificate(self):
url_http = self.marionette.absolute_url('layout/mozilla.html')
url_https = 'https://ssl-ev.mozqa.com'
# Test EV certificate
with self.marionette.using_context(self.marionette.CONTEXT_CONTENT):
self.marionette.navigate(url_https)
... | url = 'https://ssl-ev.mozqa.com'
with self.marionette.using_context(self.marionette.CONTEXT_CONTENT):
self.marionette.navigate(url)
cert = self.browser.tabbar.tabs[0].certificate
self.assertIn(cert['commonName'], url)
self.assertEqual(cert['organization'], 'Mozilla Corporat... | identifier_body |
upgrade_room.rs | //! [POST /_matrix/client/r0/rooms/{roomId}/upgrade](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-rooms-roomid-upgrade)
use ruma_api::ruma_api;
use ruma_identifiers::RoomId;
ruma_api! {
metadata {
description: "Upgrades a room to a particular version.",
method: POST,
... | } | }
error: crate::Error | random_line_split |
cli.ts | import * as fs from "fs";
import * as path from "path";
import * as commander from "commander";
import { ConsoleLogger } from "@akashic/akashic-cli-commons";
import { promiseExportHTML } from "./exportHTML";
import { promiseExportAtsumaru } from "./exportAtsumaru";
interface CommandParameterObject {
cwd?: string;
so... | identifier_body | ||
cli.ts | import * as fs from "fs";
import * as path from "path";
import * as commander from "commander";
import { ConsoleLogger } from "@akashic/akashic-cli-commons";
import { promiseExportHTML } from "./exportHTML";
import { promiseExportAtsumaru } from "./exportAtsumaru";
interface CommandParameterObject {
cwd?: string;
so... | strip?: boolean;
hashFilename?: number | boolean;
minify?: boolean;
bundle?: boolean;
magnify?: boolean;
injects?: string[];
atsumaru?: boolean;
}
function cli(param: CommandParameterObject): void {
const logger = new ConsoleLogger({ quiet: param.quiet });
const exportParam = {
cwd: !param.cwd ? process.cwd... | output?: string;
exclude?: string[]; | random_line_split |
cli.ts | import * as fs from "fs";
import * as path from "path";
import * as commander from "commander";
import { ConsoleLogger } from "@akashic/akashic-cli-commons";
import { promiseExportHTML } from "./exportHTML";
import { promiseExportAtsumaru } from "./exportAtsumaru";
interface CommandParameterObject {
cwd?: string;
so... | > !/^(-s|--strip)$/.test(v));
if (argv.length !== filteredArgv.length) {
console.log("WARN: --strip option is deprecated. strip is applied by default.");
console.log("WARN: If you do not need to apply it, use --no-strip option.");
}
return filteredArgv;
}
function inject(val: string, injects: string[]): string[... | = argv.filter(v = | identifier_name |
cli.ts | import * as fs from "fs";
import * as path from "path";
import * as commander from "commander";
import { ConsoleLogger } from "@akashic/akashic-cli-commons";
import { promiseExportHTML } from "./exportHTML";
import { promiseExportAtsumaru } from "./exportAtsumaru";
interface CommandParameterObject {
cwd?: string;
so... | else {
return promiseExportHTML(exportParam);
}
})
.then(() => logger.info("Done!"))
.catch((err: any) => {
logger.error(err);
process.exit(1);
});
}
const ver = JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8")).version;
commander
.version(ver);
commander
.des... | {
return promiseExportAtsumaru(exportParam);
} | conditional_block |
archive-config-test.js | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "Lice... | // Handle any actions with this.on('myAction', function(val) { ... });"
this.render(hbs`{{archive-config}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:"
this.render(hbs`
{{#archive-config}}
template block text
{{/archive-config}}
`);
assert.equal(this.$().text().... | integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value'); | random_line_split |
reserved-prefixes-migration.rs | // check-pass
// run-rustfix
// compile-flags: -Z unstable-options --edition 2018
#![warn(rust_2021_prefixes_incompatible_syntax)]
macro_rules! m2 {
($a:tt $b:tt) => {};
}
macro_rules! m3 {
($a:tt $b:tt $c:tt) => {};
}
fn main() |
macro_rules! quote {
(# name = # kind # value) => {};
}
quote! {
#name = #kind#value
//~^ WARNING prefix `kind` is unknown [rust_2021_prefixes_incompatible_syntax]
//~| WARNING hard error in Rust 2021
}
| {
m2!(z"hey");
//~^ WARNING prefix `z` is unknown [rust_2021_prefixes_incompatible_syntax]
//~| WARNING hard error in Rust 2021
m2!(prefix"hey");
//~^ WARNING prefix `prefix` is unknown [rust_2021_prefixes_incompatible_syntax]
//~| WARNING hard error in Rust 2021
m3!(hey#123);
//~^ WARNI... | identifier_body |
reserved-prefixes-migration.rs | // check-pass
// run-rustfix
// compile-flags: -Z unstable-options --edition 2018
#![warn(rust_2021_prefixes_incompatible_syntax)]
macro_rules! m2 {
($a:tt $b:tt) => {};
}
macro_rules! m3 {
($a:tt $b:tt $c:tt) => {};
}
fn main() {
m2!(z"hey");
//~^ WARNING prefix `z` is unknown [rust_2021_prefixes_i... |
macro_rules! quote {
(# name = # kind # value) => {};
}
quote! {
#name = #kind#value
//~^ WARNING prefix `kind` is unknown [rust_2021_prefixes_incompatible_syntax]
//~| WARNING hard error in Rust 2021
} | } | random_line_split |
reserved-prefixes-migration.rs | // check-pass
// run-rustfix
// compile-flags: -Z unstable-options --edition 2018
#![warn(rust_2021_prefixes_incompatible_syntax)]
macro_rules! m2 {
($a:tt $b:tt) => {};
}
macro_rules! m3 {
($a:tt $b:tt $c:tt) => {};
}
fn | () {
m2!(z"hey");
//~^ WARNING prefix `z` is unknown [rust_2021_prefixes_incompatible_syntax]
//~| WARNING hard error in Rust 2021
m2!(prefix"hey");
//~^ WARNING prefix `prefix` is unknown [rust_2021_prefixes_incompatible_syntax]
//~| WARNING hard error in Rust 2021
m3!(hey#123);
//~^ WA... | main | identifier_name |
urls.py | """template_III URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | 1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app import views as app_views # new
urlpatterns = [
url(r'^admin/', admin.site.urls),
... | Including another URLconf | random_line_split |
closure-reform.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 ... | call_it(proc(s) format!("{}{}", greeting, s));
let greeting = "How's life, ".to_string();
call_it(proc(s: String) -> String {
format!("{}{}", greeting, s)
});
// Closures
call_a_thunk(|| println!("Hello world!"));
call_this(|s| println!("{}", s));
call_that(|x, y| *x + *y);
... | format!("{}{}", greeting, s)
});
let greeting = "Goodbye ".to_string(); | random_line_split |
closure-reform.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 ... | (f: |&str|:Send) {
f("Hello!");
}
fn call_that(f: <'a>|&'a int, &'a int| -> int) {
let (ten, forty_two) = (10, 42);
println!("Your lucky number is {}", f(&ten, &forty_two));
}
fn call_cramped(f:||->uint,g:<'a>||->&'a uint) {
let number = f();
let other_number = *g();
println!("Ticket {} wins a... | call_this | identifier_name |
closure-reform.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 call_a_thunk(f: ||) {
f();
}
fn call_this(f: |&str|:Send) {
f("Hello!");
}
fn call_that(f: <'a>|&'a int, &'a int| -> int) {
let (ten, forty_two) = (10, 42);
println!("Your lucky number is {}", f(&ten, &forty_two));
}
fn call_cramped(f:||->uint,g:<'a>||->&'a uint) {
let number = f();
let ... | {
println!("{}", f("Fred".to_string()))
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.