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 |
|---|---|---|---|---|
encoders.py | # coding: utf-8
import math
try:
long_int = long
except NameError:
long_int = int
def rshift(val, n):
|
def str_to_longs(e):
t = []
pad = len(e) % 4
if pad != 0:
e = e + (4 - pad) * '\x00'
array_len = math.ceil(len(e)/4.0)
r = 0
while r < array_len:
t.append(
ord(e[4*r]) +
(ord(e[4*r + 1]) << 8) +
(ord(e[4*r + 2]) << 16) +
(or... | if val >= 0:
val2 = val >> n
else:
val2 = val + 0x100000000 >> n
return val2 | identifier_body |
03-coffee-work-spec.js | 'use strict';
var assert = require('assert');
var runProcess = require('./../../lib/util/run-process').runProcess;
var resolve = require('path').resolve;
var Q = require('q');
var readFile = Q.denodeify(require('fs').readFile);
var CONFIG_PATH = require('./../../package.json').CONFIG_PATH;
var splitInPairs, config;
d... | })
.done(done);
});
}); | return /---- WORK [A-Z]{4,5} ----/.test(item);
});
assert.equal(result.length, 2); | random_line_split |
setup.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 Thomas Jost and the Contributors
#
# This file is part of git-annex-remote-hubic.
#
# git-annex-remote-hubic 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, ei... | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Programming Language :: Python :: 2",
"Topic :: System :: Archiving",
],
) | },
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Plugins", | random_line_split |
flow.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later ve... |
fn execute_queue(&mut self) {
let current_time = time::precise_time_ns();
let events = self.queue
.iter()
.filter(|&(_, due_at)| *due_at < current_time)
.map(|(event, _)| event.clone())
.collect::<Vec<QueuedEvent>>();
for event in events {
... | } | random_line_split |
flow.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later ve... |
}
fn reset_view(&mut self) {
let buffer = self.buffers.selected_item();
self.frame.print(&mut buffer.with_lines(&self.lines), None);
}
fn reset_view_or_redo_search(&mut self) {
self.reset_view();
if self.frame.navigation.state == NavigationState::Search {
... | {
let offset = self.frame.rendered_lines.last_lines_height(count);
self.scroll(Offset::Line(offset));
} | conditional_block |
flow.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later ve... | (&mut self) {
self.reset_view();
if self.frame.navigation.state == NavigationState::Search {
self.perform_search(Highlight::Current);
}
}
fn enqueue(&mut self, event: QueuedEvent, offset_time: u64) {
let entry = self.queue.entry(event).or_insert(0);
*entry =... | reset_view_or_redo_search | identifier_name |
flow.rs | /**
* Flow - Realtime log analyzer
* Copyright (C) 2016 Daniel Mircea
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later ve... | let pending_lines = mutex_guarded_lines.drain(..).collect();
self.append_incoming_lines(pending_lines);
}
}
};
}
}
fn select_menu_item(&mut self, direction: Direction) {
match direction {
... | {
while running!() {
match self.frame.watch() {
Event::SelectMenuItem(direction) => self.select_menu_item(direction),
Event::ScrollContents(offset) => self.scroll(offset),
Event::Navigation(state) => {
if self.frame.navigation.chang... | identifier_body |
hmr-accept.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import {
ApplicationRef,
PlatformRef,
Type,
isD... | case 'date':
case 'datetime-local':
case 'email':
case 'hidden':
case 'month':
case 'number':
case 'password':
case 'range':
case 'search':
case 'tel':
case 'text':
case 'textarea':
case 'time':
case 'url':
... | // Restore input that are not hidden
const newInputs = document.querySelectorAll('input:not([type="hidden"]), textarea');
if (newInputs.length && newInputs.length === oldInputs.length) {
console.log('[NG HMR] Restoring input/textarea values.');
for (let index = 0; index < newInputs.length; index++) {
... | identifier_body |
hmr-accept.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import {
ApplicationRef,
PlatformRef,
Type,
isD... |
if (!ng.getInjector) {
// View Engine
return;
}
// Reset JIT compiled components cache
ɵresetCompiledComponents();
const appRoot = getAppRoot();
if (!appRoot) {
return;
}
const appRef = getApplicationRef(appRoot);
if (!appRef) {
return;
}
// Inputs... | } | random_line_split |
hmr-accept.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import {
ApplicationRef,
PlatformRef,
Type,
isD... | ldInputs: any[], oldOptions: any[]): void {
// Restore input that are not hidden
const newInputs = document.querySelectorAll('input:not([type="hidden"]), textarea');
if (newInputs.length && newInputs.length === oldInputs.length) {
console.log('[NG HMR] Restoring input/textarea values.');
for (let index = ... | storeFormValues(o | identifier_name |
ship.ts | /// <reference path="/usr/local/lib/node_modules/@types/easeljs/index.d.ts" />
/// <reference path="./map.ts" />
class Ship {
x: number;
y: number;
map: HexMap;
sizeX: number; sizeY: number;
shipBitmap: createjs.Bitmap;
constructor(stage: createjs.Stage, map: HexMap){
this.map = map;
this.ship... | () {
return new createjs.Point(this.x, this.y);
}
}
| getPosition | identifier_name |
ship.ts | /// <reference path="/usr/local/lib/node_modules/@types/easeljs/index.d.ts" />
/// <reference path="./map.ts" />
class Ship {
x: number;
y: number;
map: HexMap;
sizeX: number; sizeY: number;
shipBitmap: createjs.Bitmap;
constructor(stage: createjs.Stage, map: HexMap) |
setPosition(x: number, y: number){
this.x = x;
this.y = y;
let point = this.map.getCenterOfPoolInPixels(x, y);
this.shipBitmap.x = point.x - this.sizeX/2;
this.shipBitmap.y = point.y - this.sizeY/2;
// console.log(this.sizeX + ", " + this.sizeY + " size of ship");
// console.log(this.shi... | {
this.map = map;
this.shipBitmap = new createjs.Bitmap("ship.png");
this.shipBitmap.image.onload = this.handleImage;
stage.addChild(this.shipBitmap);
} | identifier_body |
ship.ts | /// <reference path="/usr/local/lib/node_modules/@types/easeljs/index.d.ts" />
/// <reference path="./map.ts" />
class Ship {
x: number;
y: number;
map: HexMap;
sizeX: number; sizeY: number;
shipBitmap: createjs.Bitmap;
constructor(stage: createjs.Stage, map: HexMap){
this.map = map;
this.ship... | this.shipBitmap.y = point.y - this.sizeY/2;
// console.log(this.sizeX + ", " + this.sizeY + " size of ship");
// console.log(this.shipBitmap.scale + " scale");
// console.log("pool: " + this.x + ", " + this.y);
// console.log(this.shipBitmap.x + "::" + this.shipBitmap.y + " px");
}
handleImage ... | this.x = x;
this.y = y;
let point = this.map.getCenterOfPoolInPixels(x, y);
this.shipBitmap.x = point.x - this.sizeX/2; | random_line_split |
generate-seeds.py | #!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... | (g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname)
first = True
for line in f:
comment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not first:... | process_nodes | identifier_name |
generate-seeds.py | #!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
first = False
(host,port) = parse_spec(line, defaultport)
hoststr = ','.join(('0x%02x' % b) for b in host)
g.write(' {{%s}, %i}' % (hoststr, port))
g.write('\n};\n')
def main():
if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), fil... | g.write(',\n') | conditional_block |
generate-seeds.py | #!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
static SeedSpec6 pnSeed6_main[]={
...
}
static SeedSpec6 pnSeed6_test[]={
...
}
These should be pasted into `src/chainparamsseeds.h`.
'''
from __future__ import print_function, division
from base64 import b32decode
from binascii import a2b_hex
import sys, os
import re
# ipv4 in ipv6... | <onion>.onion
0xDDBBCCAA (IPv4 little-endian old pnSeeds format)
The output will be two data structures with the peers in binary format:
| random_line_split |
generate-seeds.py | #!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
if __name__ == '__main__':
main()
| if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef H_CHAINPARAMSSEEDS\n')
g.write('#define H_CHAINPARAMSSEEDS\n')
g.write('// List of fixed seed nodes for the bitcoin network\n... | identifier_body |
vec_pad_left.rs | use malachite_base::vecs::vec_pad_left;
use malachite_base_test_util::bench::bucketers::triple_1_vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_vec_unsigned_... | println!(
"xs := {:?}; vec_pad_left(&mut xs, {}, {}); xs = {:?}",
old_xs, pad_size, pad_value, xs
);
}
}
fn benchmark_vec_pad_left(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"vec_pad_left(&mut [T], usize, T)",
Benchmar... | .take(limit)
{
let old_xs = xs.clone();
vec_pad_left(&mut xs, pad_size, pad_value); | random_line_split |
vec_pad_left.rs | use malachite_base::vecs::vec_pad_left;
use malachite_base_test_util::bench::bucketers::triple_1_vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_vec_unsigned_... | (gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"vec_pad_left(&mut [T], usize, T)",
BenchmarkType::Single,
unsigned_vec_unsigned_unsigned_triple_gen_var_1::<u8, usize, u8>().get(gm, &config),
gm.name(),
limit,
file_name,
&tripl... | benchmark_vec_pad_left | identifier_name |
vec_pad_left.rs | use malachite_base::vecs::vec_pad_left;
use malachite_base_test_util::bench::bucketers::triple_1_vec_len_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::generators::unsigned_vec_unsigned_... |
fn benchmark_vec_pad_left(gm: GenMode, config: GenConfig, limit: usize, file_name: &str) {
run_benchmark(
"vec_pad_left(&mut [T], usize, T)",
BenchmarkType::Single,
unsigned_vec_unsigned_unsigned_triple_gen_var_1::<u8, usize, u8>().get(gm, &config),
gm.name(),
limit,
... | {
for (mut xs, pad_size, pad_value) in
unsigned_vec_unsigned_unsigned_triple_gen_var_1::<u8, usize, u8>()
.get(gm, &config)
.take(limit)
{
let old_xs = xs.clone();
vec_pad_left(&mut xs, pad_size, pad_value);
println!(
"xs := {:?}; vec_pad_left(... | identifier_body |
updatefromcrowdin.py | the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software ... | (lncode,fmodule=""):
" treats a single language"
if lncode == "en":
# never treat "english" translation... For now :)
return
mods = []
if fmodule:
for l in locations:
if l[0].upper() == fmodule.upper():
mods = [l]
else:
mods = locations
... | doLanguage | identifier_name |
updatefromcrowdin.py | the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software ... | inputzip = ""
| sys.exit()
# checking on the options
inputdir = "" | random_line_split |
updatefromcrowdin.py | the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software ... |
# find the latest qm line
pos = None
for i in range(len(resources)):
if ".qm" in resources[i]:
pos = i
if pos == None:
print "No existing .qm file in this resource. Appending to the end position"
for i in range(len(resources)):
if "</qresource>" in resour... | "updates a qrc file with the given translation entry"
print "opening " + qrcpath + "..."
# getting qrc file contents
if not os.path.exists(qrcpath):
print "ERROR: Resource file " + qrcpath + " doesn't exist"
sys.exit()
f = open(qrcpath,"ro")
resources = []
for l in f.readli... | identifier_body |
updatefromcrowdin.py | a single module to update with -m.
You can also run the script without any language code, in which case all the
languages contained in the archive or directory will be added.
'''
import sys, os, shutil, tempfile, zipfile, getopt, StringIO, re
crowdinpath = "http://crowdin.net/download/project/freecad.zip"
# locati... | args = default_languages.split() | conditional_block | |
di_spec.ts | '../../src/render3/di';
import {ɵɵdefineDirective, ɵɵdirectiveInject, ɵɵelement, ɵɵelementEnd, ɵɵelementStart, ɵɵtext} from '../../src/render3/index';
import {TNODE} from '../../src/render3/interfaces/injector';
import {TNodeType} from '../../src/render3/interfaces/node';
import {isProceduralRenderer} from '../../src/... | ld inject the Renderer2 used by the application', () => {
const rendererFactory = getRendererFactory2(document);
const fixture = new ComponentFixture(MyComp, {rendererFactory: rendererFactory});
expect(isProceduralRenderer(fixture.component.renderer)).toBeTruthy();
});
it('should throw when i... | }
}
});
}
it('shou | conditional_block |
di_spec.ts | '../../src/render3/di';
import {ɵɵdefineDirective, ɵɵdirectiveInject, ɵɵelement, ɵɵelementEnd, ɵɵelementStart, ɵɵtext} from '../../src/render3/index';
import {TNODE} from '../../src/render3/interfaces/injector';
import {TNodeType} from '../../src/render3/interfaces/node';
import {isProceduralRenderer} from '../../src/... | EMENT_ID__ = 198;
}
class Dir231 {
/** @internal */ static __NG_ELEMENT_ID__ = 231;
}
it('should add values', () => {
bloomAdd(0, mockTView, Dir0);
expect(bloomState()).toEqual([0, 0, 0, 0, 0, 0, 0, 1]);
bloomAdd(0, mockTView, Dir33);
expect(bloomState())... | _NG_EL | identifier_name |
di_spec.ts | '../../src/render3/di';
import {ɵɵdefineDirective, ɵɵdirectiveInject, ɵɵelement, ɵɵelementEnd, ɵɵelementStart, ɵɵtext} from '../../src/render3/index';
import {TNODE} from '../../src/render3/interfaces/injector';
import {TNodeType} from '../../src/render3/interfaces/node';
import {isProceduralRenderer} from '../../src/... | if (rf & RenderFlags.Create) {
ɵɵtext(0, 'Foo');
}
}
});
}
it('should inject the Renderer2 used by the application', () => {
const rendererFactory = getRendererFactory2(document);
const fixture = new ComponentFixture(MyComp, {rendererFactory: rendererFa... | template: function(rf: RenderFlags, ctx: MyComp) { | random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_logo = 'i... | random_line_split | |
service.effects.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | {
@Effect()
loadAll$: Observable<Action> = this.actions$
.ofType(taskActions.LOAD_ALL)
.debounceTime(300)
.map((action: taskActions.LoadAllAction) => action.payload)
.switchMap(() => {
const nextSearch$ = this.actions$.ofType(taskActions.LOAD_ALL).skip(1);
return this.customerService.... | TasksApiEffects | identifier_name |
service.effects.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | .catch(() => of(new taskActions.LoadAllCompleteAction([])));
});
@Effect()
createTask$: Observable<Action> = this.actions$
.ofType(taskActions.CREATE)
.map((action: taskActions.CreateTaskAction) => action.payload)
.mergeMap(payload =>
this.customerService.createTask(payload.task)
... |
return this.customerService.fetchTasks()
.takeUntil(nextSearch$)
.map(taskPage => new taskActions.LoadAllCompleteAction(taskPage)) | random_line_split |
lib.rs | // Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Emulates virtual and hardware devices.
mod bus;
mod cmos;
#[cfg(feature = "direct")]
pub mod direct_io;
#[cfg(feature = "direct")]
pub mod direct_... | {
NoIommu,
VirtioIommu,
CoIommu,
}
use std::str::FromStr;
impl FromStr for IommuDevType {
type Err = ParseIommuDevTypeResult;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"off" => Ok(IommuDevType::NoIommu),
"viommu" => Ok(IommuDevType::VirtioIommu),
... | IommuDevType | identifier_name |
lib.rs | // Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Emulates virtual and hardware devices.
mod bus;
mod cmos;
#[cfg(feature = "direct")]
pub mod direct_io;
#[cfg(feature = "direct")]
pub mod direct_... | #[derive(Copy, Clone, Eq, PartialEq)]
pub enum IommuDevType {
NoIommu,
VirtioIommu,
CoIommu,
}
use std::str::FromStr;
impl FromStr for IommuDevType {
type Err = ParseIommuDevTypeResult;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"off" => Ok(IommuDevType::NoIomm... | pub enum ParseIommuDevTypeResult {
NoSuchType,
}
| random_line_split |
lib.rs | #![feature(type_ascription)]
mod problem27 {
// palindrome detector for Strings
pub fn palindrome(s: &str) -> bool {
let c = s.chars();
// c.collect::<Vec<_>>() == c.rev().collect::<Vec<_>>()
c.clone().eq(c.rev())
}
}
mod problem28 {
// flatten for vectors
#[derive(Debug,Cl... | };
// ["a", ["b", "c"], "d"]
let s1 = Seq::Sequence(vec![Seq::Item("a"), Seq::Sequence(vec![Seq::Item("b"), Seq::Item("c")]), Seq::Item("d")]);
println!("flatten({:?}) = {:?}", s1, flatten(s1.clone()));
assert_eq!(flatten(s1),
vec!["a", "b", "c", "d"])
}
#[tes... | tten, Seq | identifier_name |
lib.rs | #![feature(type_ascription)]
mod problem27 {
// palindrome detector for Strings
pub fn palindrome(s: &str) -> bool {
let c = s.chars();
// c.collect::<Vec<_>>() == c.rev().collect::<Vec<_>>()
c.clone().eq(c.rev())
}
}
mod problem28 {
// flatten for vectors
#[derive(Debug,Cl... |
inner(s, &mut res);
res
}
}
mod problem29 {
// Given a string, keep its capital letters:
// "Hello World!" -> "HW"
fn is_capital(&c: &char) -> bool {
c >= 'A' && c <= 'Z'
}
pub fn capitals(s:&str) -> String {
s.chars().filter(is_capital).collect()
}
}
mod ... | {
match s {
Seq::Item(a) => acc.push(a),
Seq::Sequence(ss) => { for i in ss { inner(i, acc) } },
}
} | identifier_body |
lib.rs | #![feature(type_ascription)]
mod problem27 {
// palindrome detector for Strings
pub fn palindrome(s: &str) -> bool {
let c = s.chars();
// c.collect::<Vec<_>>() == c.rev().collect::<Vec<_>>()
c.clone().eq(c.rev())
}
}
mod problem28 {
// flatten for vectors | pub enum Seq<T> {
Item(T),
Sequence(Vec<Seq<T>>)
}
pub fn flatten<T>(s: Seq<T>) -> Vec<T> {
let mut res = vec![];
fn inner<T>(s: Seq<T>, acc: &mut Vec<T>) {
match s {
Seq::Item(a) => acc.push(a),
Seq::Sequence(ss) => { for i in ss ... | #[derive(Debug,Clone)] | random_line_split |
wavpack.py | # A WavPack reader/tagger
#
# Copyright 2006 Joe Wreschnig <piman@sacredchao.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# $Id: wavpack.py 4153 2007-08-05 07:07:49Z piman ... |
def pprint(self):
return "WavPack, %.2f seconds, %d Hz" % (self.length, self.sample_rate)
class WavPack(APEv2File):
_Info = WavPackInfo
_mimes = ["audio/x-wavpack"]
def score(filename, fileobj, header):
return header.startswith("wvpk") * 2
score = staticmethod(score)
| header = fileobj.read(28)
if len(header) != 28 or not header.startswith("wvpk"):
raise WavPackHeaderError("not a WavPack file")
samples = cdata.uint_le(header[12:16])
flags = cdata.uint_le(header[24:28])
self.version = cdata.short_le(header[8:10])
self.channels = bool... | identifier_body |
wavpack.py | # A WavPack reader/tagger
#
# Copyright 2006 Joe Wreschnig <piman@sacredchao.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# $Id: wavpack.py 4153 2007-08-05 07:07:49Z piman ... | (filename, fileobj, header):
return header.startswith("wvpk") * 2
score = staticmethod(score)
| score | identifier_name |
wavpack.py | # A WavPack reader/tagger
#
# Copyright 2006 Joe Wreschnig <piman@sacredchao.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# $Id: wavpack.py 4153 2007-08-05 07:07:49Z piman ... |
samples = cdata.uint_le(header[12:16])
flags = cdata.uint_le(header[24:28])
self.version = cdata.short_le(header[8:10])
self.channels = bool(flags & 4) or 2
self.sample_rate = RATES[(flags >> 23) & 0xF]
self.length = float(samples) / self.sample_rate
def pprint(self... | raise WavPackHeaderError("not a WavPack file") | conditional_block |
wavpack.py | # A WavPack reader/tagger
#
# Copyright 2006 Joe Wreschnig <piman@sacredchao.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# $Id: wavpack.py 4153 2007-08-05 07:07:49Z piman ... | length - file length in seconds, as a float
sample_rate - audio sampling rate in Hz
version - WavPack stream version
"""
def __init__(self, fileobj):
header = fileobj.read(28)
if len(header) != 28 or not header.startswith("wvpk"):
raise WavPackHeaderError("not a WavPack ... | """WavPack stream information.
Attributes:
channels - number of audio channels (1 or 2) | random_line_split |
RatingsService.js | /**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco | * (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have receive... | *
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or | random_line_split |
RatingsService.js | /**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at ... |
},
/**
* Removes a rating
*
* @instance
* @param {object} payload
*/
onRemoveRating: function alfresco_services_RatingsService__onRemoveRating(payload) {
var alfTopic = payload.alfResponseTopic || this.onRemoveRating;
var nodeRefUri = lang.... | {
var url = this.getAddRatingsUrl(nodeRefUri);
var data = {
rating: 1,
ratingScheme: "likesRatingScheme"
};
this.serviceXhr({url : url,
alfTopic: alfTopic,
data: data,
... | conditional_block |
serverList.py | #| This file is part of pyCAF. |
#| |
#| pyCAF is free software: you can redistribute it and/or modify |
#| it under the terms of the GNU General Public License as published by |
#| t... |
else:
print "Server not found"
def __str__(self):
"""
Print the list of server with their ident value
"""
# print self.label_interface_list()
for identityNb, server in self.dict.items():
print "{}".format(server),
print i... | return self.dict[ident] | conditional_block |
serverList.py | #| This file is part of pyCAF. |
#| |
#| pyCAF is free software: you can redistribute it and/or modify |
#| it under the terms of the GNU General Public License as published by |
#| t... |
def __str__(self):
"""
Print the list of server with their ident value
"""
# print self.label_interface_list()
for identityNb, server in self.dict.items():
print "{}".format(server),
print identityNb
return ""
| """
Return a server corresponding to the ident value
@param ident : the number corresponding to the server
"""
if ident in self.dict.keys():
return self.dict[ident]
else:
print "Server not found" | identifier_body |
serverList.py | #| This file is part of pyCAF. |
#| |
#| pyCAF is free software: you can redistribute it and/or modify |
#| it under the terms of the GNU General Public License as published by |
#| t... | self.dict = {}
self.counter=0
def add_server(self, server):
"""
Add a server at the server dictionnary
Dictionnary model : [counter,server]
@param server : the server to store
"""
self.counter += 1
self.dict[self.counter]=server
... | """
def __init__(self): | random_line_split |
serverList.py | #| This file is part of pyCAF. |
#| |
#| pyCAF is free software: you can redistribute it and/or modify |
#| it under the terms of the GNU General Public License as published by |
#| t... | (self, server):
"""
Add a server at the server dictionnary
Dictionnary model : [counter,server]
@param server : the server to store
"""
self.counter += 1
self.dict[self.counter]=server
def get_server(self, ident):
"""
Return a... | add_server | identifier_name |
process.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | """A Process View
This view displays process models defined by
:class:`openstack.common.report.models.process.ProcessModel`
"""
VIEW_TEXT = (
"Process {{ pid }} (under {{ parent_pid }}) "
"[ run by: {{ username }} ({{ uids.real|default('unknown uid') }}),"
" state: {{ state }} ... | identifier_body | |
process.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | (jv.JinjaView):
"""A Process View
This view displays process models defined by
:class:`openstack.common.report.models.process.ProcessModel`
"""
VIEW_TEXT = (
"Process {{ pid }} (under {{ parent_pid }}) "
"[ run by: {{ username }} ({{ uids.real|default('unknown uid') }}),"
"... | ProcessView | identifier_name |
process.py | # Copyright 2014 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | "{% for child in children %}"
" {{ child }}"
"{% endfor %}"
) | " state: {{ state }} ]\n" | random_line_split |
auth.configuration.ts | import { Injectable } from '@angular/core';
@Injectable()
export class AuthConfiguration {
// The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) MUST exactly match the value of the iss (issuer) Claim.
public iss = 'http://robustidentity.tmentorsinc.com'; //identity se... | public post_logout_redirect_uri = 'http://robust.tmentorsinc/Unauthorized';
} |
public scope = 'openid profile RobustAPI';
| random_line_split |
auth.configuration.ts | import { Injectable } from '@angular/core';
@Injectable()
export class | {
// The Issuer Identifier for the OpenID Provider (which is typically obtained during Discovery) MUST exactly match the value of the iss (issuer) Claim.
public iss = 'http://robustidentity.tmentorsinc.com'; //identity server
public server = 'http://robustidentity.tmentorsinc.com';//identity server
... | AuthConfiguration | identifier_name |
signTx.js | import { showConfirmationDialog, escape } from "./dialog";
const outputRow = (output) => [
"<li>",
"<samp>",
escape(output.address),
": </samp> ",
'<samp class="amount">',
{ atoms: output.amount },
"</samp>",
"</li>"
];
export default (totalOutAmount, outputs) =>
showConfirmationDialog({
ti... | id: "confDialog.signTx.title",
m: "Sign Transaction"
},
content: [
"<p>",
{
id: "confDialog.signTransaction.message",
m: "Really sign the given transaction?"
},
"</p>",
"<p>",
{
id: "confDialog.signTransaction.totalOutLabel",
m: "... | random_line_split | |
url-link.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | }
public description (): undefined | string {
return this.payload.description
}
}
function wechatifyUrlLink (_: any): typeof UrlLink {
return UrlLink
}
export {
UrlLink,
wechatifyUrlLink,
} | }
public thumbnailUrl (): undefined | string {
return this.payload.thumbnailUrl | random_line_split |
url-link.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | public readonly payload: UrlLinkPayload,
) {
log.verbose('UrlLink', 'constructor()')
}
public toString (): string {
return `UrlLink<${this.payload.url}>`
}
public url (): string {
return this.payload.url
}
public title (): string {
return this.payload.title
}
public thumbnailUrl (... | uctor (
| identifier_name |
url-link.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | }
if (Array.isArray(meta.title)) {
title = meta.title[0]
} else {
title = meta.title
}
if (Array.isArray(meta.description)) {
description = meta.description[0]
} else if (meta.description) {
description = meta.description
} else {
description = title
}
... | log.verbose('UrlLink', 'create(%s)', url)
const meta = await openGraph(url)
let description: string | undefined
let imageUrl: string | undefined
let title: string
if (meta.image) {
if (typeof meta.image === 'string') {
imageUrl = meta.image
} else if (Array.isArray(meta.image)... | identifier_body |
url-link.ts | /**
* Wechaty Chatbot SDK - https://github.com/wechaty/wechaty
*
* @copyright 2016 Huan LI (李卓桓) <https://github.com/huan>, and
* Wechaty Contributors <https://github.com/wechaty>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in ... | if (Array.isArray(meta.image)) {
imageUrl = meta.image[0]
} else {
if (Array.isArray(meta.image.url)) {
imageUrl = meta.image.url[0]
} else if (meta.image.url) {
imageUrl = meta.image.url
}
}
}
if (Array.isArray(meta.title)) {
title = meta.t... | imageUrl = meta.image
} else | conditional_block |
conftest.py | """
pytest hooks and fixtures used for our unittests.
Please note that there should not be any Django/Olympia related imports
on module-level, they should instead be added to hooks or fixtures directly.
"""
import os
import uuid
import warnings
import pytest
import responses
import six
@pytest.fixture(autouse=True)... | (admin_group, settings):
"""Create a "Mozilla User"."""
from olympia.access.models import GroupUser
from olympia.users.models import UserProfile
user = UserProfile.objects.create(pk=settings.TASK_USER_ID,
email='admin@mozilla.com',
... | mozilla_user | identifier_name |
conftest.py | """
pytest hooks and fixtures used for our unittests.
Please note that there should not be any Django/Olympia related imports
on module-level, they should instead be added to hooks or fixtures directly.
"""
import os
import uuid
import warnings
import pytest
import responses
import six
@pytest.fixture(autouse=True)... | try:
if not marker:
responses.stop()
responses.reset()
except RuntimeError:
# responses patcher was already uninstalled
pass
@pytest.fixture(autouse=True)
def mock_basket(settings):
"""Mock Basket in tests by default.
Tests that do need basket to work s... | random_line_split | |
conftest.py | """
pytest hooks and fixtures used for our unittests.
Please note that there should not be any Django/Olympia related imports
on module-level, they should instead be added to hooks or fixtures directly.
"""
import os
import uuid
import warnings
import pytest
import responses
import six
@pytest.fixture(autouse=True)... |
@pytest.yield_fixture(autouse=True)
def test_pre_setup(request, tmpdir, settings):
from django.core.cache import caches
from django.utils import translation
from olympia import amo, core
from olympia.translations.hold import clean_translations
from waffle.utils import get_cache as waffle_get_cach... | """Make sure each test starts with a default URL prefixer."""
from django import http
from olympia import amo
request = http.HttpRequest()
request.META['SCRIPT_NAME'] = ''
prefixer = amo.urlresolvers.Prefixer(request)
prefixer.app = settings.DEFAULT_APP
prefixer.locale = settings.LANGUAGE_C... | identifier_body |
conftest.py | """
pytest hooks and fixtures used for our unittests.
Please note that there should not be any Django/Olympia related imports
on module-level, they should instead be added to hooks or fixtures directly.
"""
import os
import uuid
import warnings
import pytest
import responses
import six
@pytest.fixture(autouse=True)... |
except RuntimeError:
# responses patcher was already uninstalled
pass
@pytest.fixture(autouse=True)
def mock_basket(settings):
"""Mock Basket in tests by default.
Tests that do need basket to work should disable `responses`
and add a passthrough.
"""
USER_TOKEN = u'13f64f64-1... | responses.stop()
responses.reset() | conditional_block |
server.js | var fs = require('fs');
var os=require('os');
var express = require('express'),
// wine = require('./routes/wines');
user = require('./services/user');
contact = require('./services/contact');
inbox = require('./services/inbox');
outbox = require('./services/outbox');
device = require('./services/devic... | //device service
app.post('/services/devices', device.addDevice);
app.get('/services/devices', device.getAllDevices);
app.get('/services/devices/byuserid/:id', device.getAllDevicesByUserId);
app.delete('/services/devices', device.deleteAllDevices);
//audio service
app.post('/upload', audio.uploadAudio);
app.ge... | app.post('/services/outboxs', outbox.addOutbox);
app.get('/services/outboxs', outbox.findAllInboxs);
app.get('/services/outboxs/byuserid/:id', outbox.findOutboxByUserId);
app.delete('/services/outboxs', outbox.deleteAllOutboxs);
| random_line_split |
server.js | var fs = require('fs');
var os=require('os');
var express = require('express'),
// wine = require('./routes/wines');
user = require('./services/user');
contact = require('./services/contact');
inbox = require('./services/inbox');
outbox = require('./services/outbox');
device = require('./services/devic... | (str,strrm){
var newstr = str.replace(strrm,"");
return newstr;
}
GLOBAL.__staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk");
var audioDir = GLOBAL.__staticDir + "/staticserver/public/audio/";
var soundlib = new GLOBAL.Sound;
soundlib.convertWavToMp3(audioDir + "24.wav",audioDir + "test... | removeSubstring | identifier_name |
server.js | var fs = require('fs');
var os=require('os');
var express = require('express'),
// wine = require('./routes/wines');
user = require('./services/user');
contact = require('./services/contact');
inbox = require('./services/inbox');
outbox = require('./services/outbox');
device = require('./services/devic... |
GLOBAL.__staticDir = removeSubstring(GLOBAL.__dirname,"/vivuserver/trunk");
var audioDir = GLOBAL.__staticDir + "/staticserver/public/audio/";
var soundlib = new GLOBAL.Sound;
soundlib.convertWavToMp3(audioDir + "24.wav",audioDir + "testout1.mp3");
res.send("Ok");
});
/************************end test***... | {
var newstr = str.replace(strrm,"");
return newstr;
} | identifier_body |
app.js | 'use strict';
// Declare app level module which depends on filters, and services
var tdfTeamsApp = angular.module('tdfTeams', [
'ngRoute',
'ngSanitize',
'tdfTeams.filters',
'tdfTeams.services',
'tdfTeams.directives', | 'tdfTeams.controllers',
'tdfRiders.controllers'
]);
tdfTeamsApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/teams', {
templateUrl: 'partials/team-list.html',
controller: 'TeamListCtrl'
}).
when('/teams/:teamId', {
templateUrl: 'partials/team-detailed.html',
contro... | random_line_split | |
baseClone.js | /**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="node" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investiga... | (value, isDeep, callback, stackA, stackB) {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
// inspect [[Class]]
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className] || (!... | baseClone | identifier_name |
baseClone.js | /**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="node" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investiga... |
}
// inspect [[Class]]
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) {
return value;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case ... | {
return result;
} | conditional_block |
baseClone.js | /**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="node" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investiga... | var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object Str... |
/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;
/** `Object#toString` result shortcuts */ | random_line_split |
baseClone.js | /**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="node" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investiga... | case numberClass:
case stringClass:
return new ctor(value);
case regexpClass:
result = ctor(value.source, reFlags.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
} else {
return value;
}
var isArr = isArray(value);
if (isDeep) {
/... | {
if (callback) {
var result = callback(value);
if (typeof result != 'undefined') {
return result;
}
}
// inspect [[Class]]
var isObj = isObject(value);
if (isObj) {
var className = toString.call(value);
if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) {
... | identifier_body |
dustParticles_jQueryPlugin.js | (function($) {
$.fn.extend({
dustParticles: function(particlesNumber, opacity) {
return this.each(function() {
//Generate a 'canvas' with size of element selected from the DOM .
var width = $(this).width();
var height = $(this).height();
... |
function live() {
//We repainted the canvas to create the sensation of movement.
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(function(element, index) {
ctx.beginPath();
v... | {
this.speed = {
x: Math.random() * 3 - 0.5,
y: Math.random() * 3 - 0.5
};
this.radius = Math.random() * (10 - 1) + 1;
console.log(this.radius)
this.opacity = opacity / thi... | identifier_body |
dustParticles_jQueryPlugin.js | (function($) {
$.fn.extend({
dustParticles: function(particlesNumber, opacity) {
return this.each(function() {
//Generate a 'canvas' with size of element selected from the DOM .
var width = $(this).width();
var height = $(this).height();
... | () {
//We repainted the canvas to create the sensation of movement.
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(function(element, index) {
ctx.beginPath();
var gradient = ctx.createRadialG... | live | identifier_name |
dustParticles_jQueryPlugin.js | (function($) {
$.fn.extend({
dustParticles: function(particlesNumber, opacity) {
return this.each(function() {
//Generate a 'canvas' with size of element selected from the DOM .
var width = $(this).width();
var height = $(this).height();
... | if (element.y > canvas.height + 50) element.y = -50;
});
}
setInterval(live, 33);
});
}
});
})(jQuery) | if (element.y < -50) element.y = canvas.height + 50;
if (element.x > canvas.width + 50) element.x = -50; | random_line_split |
_management_link_client.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
class ManagementLinkClient:
"""Azure resources can be linked together to form logical relationships. You can establish links between resources belonging to different resource groups. However, all the linked resources must belong to the same subscription. Each resource can be linked to 50 other resources. If any o... | from azure.core.credentials import TokenCredential | conditional_block |
_management_link_client.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | (self):
# type: () -> ManagementLinkClient
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
| __enter__ | identifier_name |
_management_link_client.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
def __enter__(self):
# type: () -> ManagementLinkClient
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details)
| self._client.close() | identifier_body |
_management_link_client.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | :param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
:param base_url: Service URL. Default value is 'https://management.azure.com'.
... | random_line_split | |
test_rich_string03.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | italic = workbook.add_format({'italic': 1})
worksheet.write('A1', 'Foo', bold)
worksheet.write('A2', 'Bar', italic)
worksheet.write_rich_string('A3', bold, 'abc', 'defg')
workbook.close()
self.assertExcelEqual() | random_line_split | |
test_rich_string03.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | (self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
italic = workbook.add_format({'italic': 1})
worksheet.write('A1', 'Foo', bold)
work... | test_create_file | identifier_name |
test_rich_string03.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
| workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
italic = workbook.add_format({'italic': 1})
worksheet.write('A1', 'Foo', bold)
worksheet.write('A2', 'Bar', italic)
worksheet.write_rich_string('... | """
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'rich_string03.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir +... | identifier_body |
urls.py | """heroku_blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views | 1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
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 djan... | 1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views | random_line_split |
hejbejse.py | # -*- coding: UTF-8 -*-
#/*
# * Copyright (C) 2011 Ivo Brhel
# *
# *
# * This Program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2, or (at your option)
# * any later version.
#... | item['title'] = title
item['url'] = uri
result.append(item)
return result
def resolve(self,item,captcha_cb=None,select_cb=None):
item = item.copy()
url = self._url(item['url'])
page = util.parse_html(url)
result = []
data=str(page.select('div.entry3 > center')[0])
resolved = resolver.findstrea... | page = util.parse_html(url)
result = []
for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]:
item = self.video_item() | random_line_split |
hejbejse.py | # -*- coding: UTF-8 -*-
#/*
# * Copyright (C) 2011 Ivo Brhel
# *
# *
# * This Program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2, or (at your option)
# * any later version.
#... | (self, url):
url = self._url(url)
page = util.parse_html(url)
result = []
for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]:
item = self.video_item()
item['title'] = title
item['url'] = uri
result.append(item)
return result
def resolve(self,item,ca... | list | identifier_name |
hejbejse.py | # -*- coding: UTF-8 -*-
#/*
# * Copyright (C) 2011 Ivo Brhel
# *
# *
# * This Program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2, or (at your option)
# * any later version.
#... |
return result
def list(self, url):
url = self._url(url)
page = util.parse_html(url)
result = []
for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]:
item = self.video_item()
item['title'] = title
item['url'] = uri
result.append(item)
return result
... | item = self.dir_item()
item['title'] = title
item['url'] = uri
result.append(item) | conditional_block |
hejbejse.py | # -*- coding: UTF-8 -*-
#/*
# * Copyright (C) 2011 Ivo Brhel
# *
# *
# * This Program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2, or (at your option)
# * any later version.
#... |
def list(self, url):
url = self._url(url)
page = util.parse_html(url)
result = []
for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]:
item = self.video_item()
item['title'] = title
item['url'] = uri
result.append(item)
return result
def resolve(s... | page = util.parse_html('http://www.kynychova-tv.cz/index.php?id=5')
result = []
for title,uri in [(x.h3.text,x.h3.a['href']) for x in page.select('div.entry5') if x.h3]:
item = self.dir_item()
item['title'] = title
item['url'] = uri
result.append(item)
return result | identifier_body |
gc.rs | None;
}
type Visitor<'self> = &'self fn(root: **Word, tydesc: *Word) -> bool;
// Walks the list of roots for the given safe point, and calls visitor
// on each root.
unsafe fn _walk_safe_point(fp: *Word, sp: SafePoint, visitor: Visitor) -> bool {
let fp_bytes: *u8 = cast::transmute(fp);
let sp_meta: *u32 = c... | {
unsafe {
// Abort when GC is disabled.
if get_safe_point_count() == 0 {
return;
}
// Leave a sentinel on the stack to mark the current frame. The
// stack walker will ignore any frames above the sentinel, thus
// avoiding collecting any memory being use... | identifier_body | |
gc.rs | GC-based cleanup is a replacement for landing pads which relies on the
GC infrastructure to find pointers on the stack to cleanup. Whereas
the normal GC needs to walk task-local heap allocations, the cleanup
code needs to walk exchange heap allocations and stack-allocations
with destructors.
*/
use cast;
use containe... | () -> uint {
let module_meta = rustrt::rust_gc_metadata();
return *module_meta;
}
struct SafePoint {
sp_meta: *Word,
fn_meta: *Word,
}
// Returns the safe point metadata for the given program counter, if
// any.
unsafe fn is_safe_point(pc: *Word) -> Option<SafePoint> {
let module_meta = rustrt::ru... | get_safe_point_count | identifier_name |
gc.rs | GC-based cleanup is a replacement for landing pads which relies on the
GC infrastructure to find pointers on the stack to cleanup. Whereas
the normal GC needs to walk task-local heap allocations, the cleanup
code needs to walk exchange heap allocations and stack-allocations
with destructors.
*/
use cast;
use containe... |
rri += 1;
}
return true;
}
#[cfg(stage0)]
unsafe fn walk_safe_point(fp: *Word, sp: SafePoint, visitor: Visitor) {
_walk_safe_point(fp, sp, visitor);
}
#[cfg(not(stage0))]
unsafe fn walk_safe_point(fp: *Word, sp: SafePoint, visitor: Visitor) -> bool {
_walk_safe_point(fp, sp, visitor)
}
// Is ... | {
// FIXME(#2997): Need to find callee saved registers on the stack.
} | conditional_block |
gc.rs | GC-based cleanup is a replacement for landing pads which relies on the
GC infrastructure to find pointers on the stack to cleanup. Whereas
the normal GC needs to walk task-local heap allocations, the cleanup
code needs to walk exchange heap allocations and stack-allocations
with destructors.
*/
use cast;
use containe... | let mut spi = 0;
while spi < num_safe_points {
let sp: **Word = bump(safe_points, spi*3);
let sp_loc = *sp;
if sp_loc == pc {
return Some(SafePoint {
sp_meta: *bump(sp, 1),
fn_meta: *bump(sp, 2),
});
}
spi += 1;
... | // FIXME (#2997): Use binary rather than linear search. | random_line_split |
binary_util.py | _import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
import posixpath
from contextlib import contextmanager
from twitter.common.collections import OrderedSet
from pants.base.build_environment import get_buildroot
from pants.b... | logger.info('Fetched {name} binary from: {url} .'.format(name=name, url=url))
downloaded_successfully = True
dest.seek(0)
yield lambda: dest.read()
break
except (IOError, Fetcher.Error, ValueError) as e:
accumulated_errors.append('Failed to fetch binary fr... | timeout_secs=self._timeout_secs) | random_line_split |
binary_util.py | , division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
import posixpath
from contextlib import contextmanager
from twitter.common.collections import OrderedSet
from pants.base.build_environment import get_buildroot
from pants.base.exc... |
try:
middle_path = self._path_by_id[os_id]
except KeyError:
raise self.MissingMachineInfo('Update --binaries-path-by-id to find binaries for {!r}'
.format(os_id))
return os.path.join(supportdir, *(middle_path + (version, name)))
def __init__(self, baseurl... | raise self.MissingMachineInfo('Pants has no binaries for {}'.format(' '.join(uname_func()))) | conditional_block |
binary_util.py | safe_open
from pants.util.osutil import get_os_id
_DEFAULT_PATH_BY_ID = {
('linux', 'x86_64'): ('linux', 'x86_64'),
('linux', 'amd64'): ('linux', 'x86_64'),
('linux', 'i386'): ('linux', 'i386'),
('linux', 'i686'): ('linux', 'i386'),
('darwin', '9'): ('mac', '10.5'),
('darwin', '10'): ('mac', '10.6'),
(... | bootstrap_dir = os.path.realpath(os.path.expanduser(self._pants_bootstrapdir))
bootstrapped_binary_path = os.path.join(bootstrap_dir, binary_path)
if not os.path.exists(bootstrapped_binary_path):
downloadpath = bootstrapped_binary_path + '~'
try:
with self._select_binary_stream(name, binary_... | identifier_body | |
binary_util.py | , division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
import posixpath
from contextlib import contextmanager
from twitter.common.collections import OrderedSet
from pants.base.build_environment import get_buildroot
from pants.base.exc... | (self, supportdir, version, name):
"""Selects a platform-independent script.
:param string supportdir: The path the `name` scripts are stored under.
:param string version: The version number of the script to select.
:param string name: The name of the script to fetch.
:raises: :class:`pants.binary_... | select_script | identifier_name |
CCComRender.js | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Sof... | return com;
}
return null;
}; | ccs.ComRender.create = function (node, comName) {
var com = new ccs.ComRender(node, comName);
if (com && com.init()) {
| random_line_split |
CCComRender.js | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Sof... |
},
onExit: function () {
this._render = null;
},
/**
* Node getter
* @returns {cc.Node}
*/
getNode: function () {
return this._render;
},
/**
* Node setter
* @param {cc.Node} node
*/
setNode: function (node) {
... | {
this._owner.addChild(this._render);
} | conditional_block |
supervisord.py | # stdlib
from collections import defaultdict
import itertools
import re
import socket
import time
import xmlrpclib
# 3p
import supervisor.xmlrpc
# project
from checks import AgentCheck
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = '9001'
DEFAULT_SOCKET_IP = 'http://127.0.0.1'
DD_STATUS = {
'STOPPED': AgentCheck.CRI... |
# Collect information on each monitored process
monitored_processes = []
# monitor all processes if no filters were specified
if len(proc_regex) == 0 and len(proc_names) == 0:
monitored_processes = processes
for pattern, process in itertools.product(proc_regex, pr... | raise Exception("Empty or invalid proc_names.") | conditional_block |
supervisord.py | # stdlib
from collections import defaultdict
import itertools
import re
import socket
import time
import xmlrpclib
# 3p
import supervisor.xmlrpc
# project
from checks import AgentCheck
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = '9001'
DEFAULT_SOCKET_IP = 'http://127.0.0.1'
DD_STATUS = {
'STOPPED': AgentCheck.CRI... | Description: %(description)s
Error log file: %(stderr_logfile)s
Stdout log file: %(stdout_logfile)s
Log file: %(logfile)s
State: %(statename)s
Start time: %(start_str)s
Stop time: %(stop_str)s
Exit Status: %(exitstatus)s""" % proc | random_line_split | |
supervisord.py | # stdlib
from collections import defaultdict
import itertools
import re
import socket
import time
import xmlrpclib
# 3p
import supervisor.xmlrpc
# project
from checks import AgentCheck
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = '9001'
DEFAULT_SOCKET_IP = 'http://127.0.0.1'
DD_STATUS = {
'STOPPED': AgentCheck.CRI... | (proc):
start, now = int(proc['start']), int(proc['now'])
status = proc['statename']
active_state = status in ['BACKOFF', 'RUNNING', 'STOPPING']
return now - start if active_state else 0
@staticmethod
def _build_message(proc):
start, stop, now = int(proc['start']), int(p... | _extract_uptime | identifier_name |
supervisord.py | # stdlib
from collections import defaultdict
import itertools
import re
import socket
import time
import xmlrpclib
# 3p
import supervisor.xmlrpc
# project
from checks import AgentCheck
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = '9001'
DEFAULT_SOCKET_IP = 'http://127.0.0.1'
DD_STATUS = {
'STOPPED': AgentCheck.CRI... | sock = instance.get('socket')
if sock is None:
msg = 'Cannot connect to http://%s:%s. ' \
'Make sure supervisor is running and XML-RPC ' \
'inet interface is enabled.' % (host, port)
else:
msg = 'Cannot conne... | server_name = instance.get('name')
if not server_name or not server_name.strip():
raise Exception("Supervisor server name not specified in yaml configuration.")
server_service_check_tags = ['%s:%s' % (SERVER_TAG, server_name)]
supe = self._connect(instance)
count_by_status ... | identifier_body |
sessions.py | from core import messages
from core.weexceptions import FatalException
from mako import template
from core.config import sessions_path, sessions_ext
from core.loggers import log, stream_handler
from core.module import Status
import os
import yaml
import glob
import logging
import urlparse
import atexit
import ast
prin... | atexit.register(self._session_save_atexit)
self.update(sessiondb)
return
# If no session was found, create a new one with first available filename
index = 0
while True:
dbpath = os.path.join(
hostfold... | try:
sessiondb = yaml.load(open(dbpath, 'r').read())
except Exception as e:
log.warn(
messages.generic.error_loading_file_s_s %
(dbpath, str(e)))
else:
saved_url = sessiondb.get('url')
saved_p... | conditional_block |
sessions.py | from core import messages | from core.config import sessions_path, sessions_ext
from core.loggers import log, stream_handler
from core.module import Status
import os
import yaml
import glob
import logging
import urlparse
import atexit
import ast
print_filters = [
'debug',
'channel'
]
set_filters = [
'debug',
'channel'
]
class S... | from core.weexceptions import FatalException
from mako import template | random_line_split |
sessions.py | from core import messages
from core.weexceptions import FatalException
from mako import template
from core.config import sessions_path, sessions_ext
from core.loggers import log, stream_handler
from core.module import Status
import os
import yaml
import glob
import logging
import urlparse
import atexit
import ast
prin... |
def print_to_user(self, module_filter = ''):
for mod_name, mod_value in self.items():
if isinstance(mod_value, dict):
mod_args = mod_value.get('stored_args')
# Is a module, print all the storable stored_arguments
for argument, arg_value in mod... | yaml.dump(
dict(self),
open(self['path'], 'w'),
default_flow_style = False
) | identifier_body |
sessions.py | from core import messages
from core.weexceptions import FatalException
from mako import template
from core.config import sessions_path, sessions_ext
from core.loggers import log, stream_handler
from core.module import Status
import os
import yaml
import glob
import logging
import urlparse
import atexit
import ast
prin... | (self, dbpath, volatile = False):
try:
sessiondb = yaml.load(open(dbpath, 'r').read())
except Exception as e:
log.warn(
messages.generic.error_loading_file_s_s %
(dbpath, str(e)))
raise FatalException(messages.sessions.error_loading_se... | __init__ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.