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 |
|---|---|---|---|---|
store_test.py | from __future__ import absolute_import
from __future__ import unicode_literals
import io
import os.path
import sqlite3
import mock
import pytest
import six
from pre_commit.store import _get_default_directory
from pre_commit.store import Store
from pre_commit.util import cmd_output
from pre_commit.util import cwd
fro... | (store, tempdir_factory, log_info_mock):
path = git_dir(tempdir_factory)
with cwd(path):
cmd_output('git', 'commit', '--allow-empty', '-m', 'foo')
sha = get_head_sha(path)
cmd_output('git', 'commit', '--allow-empty', '-m', 'bar')
ret = store.clone(path, sha)
# Should have printe... | test_clone | identifier_name |
algorithms.py | """
File: algorithms.py
Algorithms configured for profiling.
"""
from profiler import Profiler
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1
while j < len(lyst)... |
n -= 1
def bubbleSort2(lyst, profiler):
n = len(lyst)
while n > 1:
swapped = False
i = 1
while i < n:
if lyst[i] < lyst[i - 1]: # Exchange if needed
swap(lyst, i, i - 1, profiler)
swapped = True
... | profiler.comparison()
if lyst[i] < lyst[i - 1]: # Exchange if needed
swap(lyst, i, i - 1, profiler)
i += 1 | conditional_block |
algorithms.py | """
File: algorithms.py
Algorithms configured for profiling.
"""
from profiler import Profiler
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1 | j += 1
if minIndex != i: # Exchange if needed
swap(lyst, minIndex, i, profiler)
i += 1
def bubbleSort(lyst, profiler):
n = len(lyst)
while n > 1: # Do n - 1 bubbles
i = 1 # Start each bubble
while ... | while j < len(lyst): # Start a search
profiler.comparison()
if lyst[j] < lyst[minIndex]:
minIndex = j | random_line_split |
algorithms.py | """
File: algorithms.py
Algorithms configured for profiling.
"""
from profiler import Profiler
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1
while j < len(lyst)... | (lyst, i, j, profiler):
"""Exchanges the elements at positions i and j."""
profiler.exchange()
temp = lyst[i]
lyst[i] = lyst[j]
lyst[j] = temp
| swap | identifier_name |
algorithms.py | """
File: algorithms.py
Algorithms configured for profiling.
"""
from profiler import Profiler
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1
while j < len(lyst)... |
def bubbleSort2(lyst, profiler):
n = len(lyst)
while n > 1:
swapped = False
i = 1
while i < n:
if lyst[i] < lyst[i - 1]: # Exchange if needed
swap(lyst, i, i - 1, profiler)
swapped = True
if trace: p... | n = len(lyst)
while n > 1: # Do n - 1 bubbles
i = 1 # Start each bubble
while i < n:
profiler.comparison()
if lyst[i] < lyst[i - 1]: # Exchange if needed
swap(lyst, i, i - 1, profiler)
i += 1
... | identifier_body |
NewRelatedQuestionForm.tsx | import { Components, registerComponent, getFragment } from '../../lib/vulcan-lib';
import { useMessages } from '../common/withMessages';
import React from 'react';
import { useCurrentUser } from '../common/withUser'
import { Posts } from '../../lib/collections/posts/collection'
const styles = (theme: ThemeType): JssSt... |
const QuestionSubmit = (props) => {
return <div className={classes.formSubmit}>
<SubmitToFrontpageCheckbox
{...props}
label="Hide from frontpage"
fieldName="hiddenRelatedQuestion"
tooltip={<div>
<div>
Hide this question from the home page
<... | refetch: any,
}) => {
const currentUser = useCurrentUser();
const { flash } = useMessages();
const { SubmitToFrontpageCheckbox, PostSubmit } = Components | random_line_split |
config.py | """
Config.py is a repository of the Cobbler object model
Copyright 2006-2009, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>
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 of th... | (self,collection,item):
"""
Erase item from a storage file, if neccessary rewritting the file.
"""
return serializer.serialize_delete(collection,item)
def deserialize(self):
"""
Load the object hierachy from disk, using the filenames referenced in each object.
"""
... | serialize_delete | identifier_name |
config.py | """
Config.py is a repository of the Cobbler object model
Copyright 2006-2009, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>
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 of th... | Create a new mgmtclass object...
"""
return mgmtclass.Mgmtclass(weakref.proxy(self),is_subobject=is_subobject)
def new_package(self,is_subobject=False):
"""
Create a new package object...
"""
return package.Package(weakref.proxy(self),is_subobject=is_subobject)
... | """
return image.Image(weakref.proxy(self),is_subobject=is_subobject)
def new_mgmtclass(self,is_subobject=False):
""" | random_line_split |
config.py | """
Config.py is a repository of the Cobbler object model
Copyright 2006-2009, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>
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 of th... |
return True
def deserialize_raw(self,collection_type):
"""
Get object data from disk, not objects.
"""
return serializer.deserialize_raw(collection_type)
def deserialize_item_raw(self,collection_type,obj_name):
"""
Get a raw single object.
"""
retu... | try:
if not serializer.deserialize(item): raise ""
except:
raise CX("serializer: error loading collection %s. Check /etc/cobbler/modules.conf" % item.collection_type()) | conditional_block |
config.py | """
Config.py is a repository of the Cobbler object model
Copyright 2006-2009, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>
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 of th... |
def deserialize_item_raw(self,collection_type,obj_name):
"""
Get a raw single object.
"""
return serializer.deserialize_item_raw(collection_type,obj_name)
def get_items(self,collection_type):
if collection_type == "distro":
result=self._distros
elif colle... | """
Get object data from disk, not objects.
"""
return serializer.deserialize_raw(collection_type) | identifier_body |
unboxed-closures-drop.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 ... | (&mut self) {
unsafe {
DROP_COUNT += 1
}
}
}
fn a<F:Fn(isize, isize) -> isize>(f: F) -> isize {
f(1, 2)
}
fn b<F:FnMut(isize, isize) -> isize>(mut f: F) -> isize {
f(3, 4)
}
fn c<F:FnOnce(isize, isize) -> isize>(f: F) -> isize {
f(5, 6)
}
fn test_fn() {
{
a(mo... | drop | identifier_name |
unboxed-closures-drop.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 ... | {
test_fn();
test_fn_mut();
test_fn_once();
} | identifier_body | |
unboxed-closures-drop.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 ... | let zz = Droppable::new();
c(move |a: isize, b| { z; zz; a + b });
assert_eq!(drop_count(), 9);
}
assert_eq!(drop_count(), 9);
}
fn main() {
test_fn();
test_fn_mut();
test_fn_once();
} | assert_eq!(drop_count(), 7);
{
let z = Droppable::new(); | random_line_split |
roundtrip-test.js | (str) {
return encodeXmlEntities(str)
.replace(/"/g, '"');
}
var xmlCallback = function ( env, err, results ) {
var i, result;
var prefix = ( env && env.conf && env.conf.wiki && env.conf.wiki.iwp ) || '';
var title = ( env && env.page && env.page.name ) || '';
var output = '<testsuite name="Roundtrip ar... | encodeAttribute | identifier_name | |
roundtrip-test.js | .match(/^\n?<\/[^>]+>\n?$/) )
{
// An element was implicitly closed. Fudge the orig offset
// slightly so it finds the corresponding elements which have the
// original (unclosed) DSR.
offset[0].start--;
}
// console.warn("--orig--");
var res = findMatchingNodes( body, offset[0] || {}, src.leng... | var consoleOut = function ( err, output ) {
if ( err ) {
console.log( 'ERROR: ' + err); | random_line_split | |
roundtrip-test.js | += '">';
output += DU.encodeXml( env.profile[ type ][ prop ].toString() );
output += '</perfstat>\n';
}
}
output += '</perfstats>\n';
}
output += '</testsuite>\n';
return output;
};
var findMatchingNodes = function (root, targetRange, sourceLen) {
var currentOffset = null, wasWaiting = false, wai... | if ( attribs.dsr[0] !== null && targetRange.start === start && end === targetRange.end ) {
return { done: true, nodes: [element] };
} else if ( targetRange.start === start ) {
waitingForEndMatch = true;
if (end < targetRange.end) {
// No need to walk children
return { done: false, nodes: [el... | {
var elements = [],
precedingNodes = [],
attribs = DU.getJSONAttribute(element, 'data-parsoid');
if ( attribs.dsr && attribs.dsr.length ) {
var start = attribs.dsr[0] || 0,
end = attribs.dsr[1] || sourceLen - 1;
if ( (targetRange.end - 1) < start || targetRange.start > (end - 1) ) {
return n... | identifier_body |
roundtrip-test.js | else {
for ( i = 0; i < results.length; i++ ) {
result = results[i];
output += testDivider;
if ( result.type === 'fail' ) {
output += 'Semantic difference:\n\n';
output += result.wtDiff + '\n';
output += diffDivider;
output += 'HTML diff:\n\n';
output += result.htmlDiff + '\n';
sema... | {
output += 'Parser failure!\n\n';
output += diffDivider;
output += err;
} | conditional_block | |
flock.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 ... |
Lock { handle: handle }
}
}
impl Drop for Lock {
fn drop(&mut self) {
let mut overlapped: libc::OVERLAPPED = unsafe { mem::init() };
unsafe {
UnlockFileEx(self.handle, 0, 100, 0, &mut overlapped);
libc::CloseHandle(self.handle... | {
unsafe { libc::CloseHandle(handle); }
fail!("could not lock `{}`: {}", p.display(),
os::last_os_error())
} | conditional_block |
flock.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 ... | let fd = p.with_c_str(|s| unsafe {
libc::open(s, libc::O_RDWR | libc::O_CREAT, libc::S_IRWXU)
});
assert!(fd > 0);
let flock = os::flock {
l_start: 0,
l_len: 0,
l_pid: 0,
l_whence: libc::SEEK_... |
impl Lock {
pub fn new(p: &Path) -> Lock { | random_line_split |
flock.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 ... | {
l_type: libc::c_short,
l_whence: libc::c_short,
l_start: libc::off_t,
l_len: libc::off_t,
l_pid: libc::pid_t,
// not actually here, but brings in line with freebsd
l_sysid: libc::c_int,
}
pub static F_WRLCK: libc::c... | flock | identifier_name |
03-literals-and-operators.rs | fn main() | println!("One million is written as {}", 1_000_000u);
}
| {
// Integer addition
println!("1 + 2 = {}", 1u + 2);
// Integer subtraction
println!("1 - 2 = {}", 1i - 2);
// Short-circuiting boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
// Bit... | identifier_body |
03-literals-and-operators.rs | fn | () {
// Integer addition
println!("1 + 2 = {}", 1u + 2);
// Integer subtraction
println!("1 - 2 = {}", 1i - 2);
// Short-circuiting boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true);
// ... | main | identifier_name |
03-literals-and-operators.rs | fn main() {
// Integer addition
println!("1 + 2 = {}", 1u + 2);
// Integer subtraction
println!("1 - 2 = {}", 1i - 2); |
// Bitwise operations
println!("0011 AND 0101 is {:04t}", 0b0011u & 0b0101);
println!("0011 OR 0101 is {:04t}", 0b0011u | 0b0101);
println!("0011 XOR 0101 is {:04t}", 0b0011u ^ 0b0101);
println!("1 << 5 is {}", 1u << 5);
println!("0x80 >> 2 is 0x{:x}", 0x80u >> 2);
// Use underscores to im... |
// Short-circuiting boolean logic
println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false);
println!("NOT true is {}", !true); | random_line_split |
NewDocumentDBConnectionCallout.tsx | import React, { useState } from 'react';
import { NewConnectionCalloutProps } from './Callout.properties';
import { useTranslation } from 'react-i18next';
import CustomPivot from './customPivot/CustomPivot';
import RadioButtonNoFormik from '../../../../../components/form-controls/RadioButtonNoFormik';
import { paddingS... | );
};
export default NewDocumentDBConnectionCallout; | {radioState === RadioState.custom && <CustomPivot {...props} />}
</div> | random_line_split |
UserString.py | #!/usr/bin/env python
## vim:ts=4:et:nowrap
"""A user-defined wrapper around string objects
Note: string objects have grown methods in Python 1.6
This module requires Python 1.6 or later.
"""
from types import StringType, UnicodeType
import sys
__all__ = ["UserString","MutableString"]
class UserString:
def __ini... | (self, index):
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + self.data[index+1:]
def __setslice__(self, start, end, sub):
start = max(start, 0); end = max(end, 0)
if isinstance(sub, UserString):
self.data = self.data[:start]+sub... | __delitem__ | identifier_name |
UserString.py | #!/usr/bin/env python
## vim:ts=4:et:nowrap
"""A user-defined wrapper around string objects
Note: string objects have grown methods in Python 1.6
This module requires Python 1.6 or later.
"""
from types import StringType, UnicodeType
import sys
__all__ = ["UserString","MutableString"]
class UserString:
def __ini... |
def __int__(self): return int(self.data)
def __long__(self): return long(self.data)
def __float__(self): return float(self.data)
def __complex__(self): return complex(self.data)
def __hash__(self): return hash(self.data)
def __cmp__(self, string):
if isinstance(string, UserString):
... | return repr(self.data) | identifier_body |
UserString.py | #!/usr/bin/env python
## vim:ts=4:et:nowrap
"""A user-defined wrapper around string objects
Note: string objects have grown methods in Python 1.6
This module requires Python 1.6 or later.
"""
from types import StringType, UnicodeType
import sys
__all__ = ["UserString","MutableString"]
class UserString:
def __ini... | def isupper(self): return self.data.isupper()
def join(self, seq): return self.data.join(seq)
def ljust(self, width): return self.__class__(self.data.ljust(width))
def lower(self): return self.__class__(self.data.lower())
def lstrip(self): return self.__class__(self.data.lstrip())
def replace(se... | def istitle(self): return self.data.istitle() | random_line_split |
UserString.py | #!/usr/bin/env python
## vim:ts=4:et:nowrap
"""A user-defined wrapper around string objects
Note: string objects have grown methods in Python 1.6
This module requires Python 1.6 or later.
"""
from types import StringType, UnicodeType
import sys
__all__ = ["UserString","MutableString"]
class UserString:
def __ini... |
else:
return self.__class__(self.data + str(other))
def __radd__(self, other):
if isinstance(other, StringType) or isinstance(other, UnicodeType):
return self.__class__(other + self.data)
else:
return self.__class__(str(other) + self.data)
def __iadd_... | return self.__class__(self.data + other) | conditional_block |
record_select.js | false;
});
jQuery(document).on('ajax:beforeSend', '.record-select-container', function(event, xhr) {
var rs = jQuery(this).data('recordselect'), cur = rs.current_xhr, found = jQuery(this).find('.found');
jQuery(this).find('.record, .pagination').remove();
found.html(found.data('searching'));
rs.cur... |
if (this._use_iframe_mask()) {
this.container.after('<iframe src="javascript:false;" class="record-select-mask" />');
var mask = this.container.next('iframe');
mask.css('left', this.container.css('left'))
.css('top', this.container.css('top'));
}
if (this._use_iframe_mask()) {
... | random_line_split | |
record_select.js |
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
}
/*
jQuery delayed observ... | {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
} | identifier_body | |
record_select.js | () {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.con... | Class | identifier_name | |
storn.py | 012, ICSI, 1995. http://www.icsi.berkeley.edu/~storn/TR-95-012.pdf
[3] Ingber, L. "Simulated Annealing: Practice Versus Theory" J. of
Mathematical and Computer Modeling 18(11), 29-57, 1993.
[4] Corana, A. and Marchesi, M. and Martini, C. and Ridella, S.
"Minimizing Multimodal Functions of Continuous V... | c0 = -100 * x0 | conditional_block | |
storn.py | Griewangk'
function definitions drawn from [5], and 'Zimmermann' function definitions
drawn from [6].
References::
[1] Storn, R. and Price, K. "Differential Evolution - A Simple and
Efficient Heuristic for Global Optimization over Continuous Spaces"
Journal of Global Optimization 11: 341-359, 1997.
[2... |
minimizers = [0.] #XXX: there are many periodic local minima
pass
class Zimmermann(AbstractFunction):
__doc__ = \
"""a Zimmermann function generator
A Zimmermann function [1,2,6] poses difficulty for minimizers
as the minimum is located at the corner of the constrained region.
A penalty is applied ... | """evaluates an N-dimensional Griewangk's function for a list of coeffs
f(x) = f_0(x) - f_1(x) + 1
Where:
f_0(x) = \sum_(i=0)^(N-1) x_(i)^(2) / 4000.
and:
f_1(x) = \prod_(i=0)^(N-1) \cos( x_i / (i+1)^(1/2) )
Inspect with mystic_model_plotter using::
mystic.models.griewangk -b "-10:10:.1, -10:10:.1" -d -x 5
The ... | identifier_body |
storn.py | Griewangk'
function definitions drawn from [5], and 'Zimmermann' function definitions
drawn from [6].
References::
[1] Storn, R. and Price, K. "Differential Evolution - A Simple and
Efficient Heuristic for Global Optimization over Continuous Spaces"
Journal of Global Optimization 11: 341-359, 1997.
[2... | (AbstractFunction):
__doc__ = \
"""a Griewangk's function generator
Griewangk's function [1,2,5] is a multi-dimensional cosine
function that provides several periodic local minima, with
the global minimum at the origin. The local minima are
fractionally more shallow than the global minimum, such that
when vie... | Griewangk | identifier_name |
storn.py | 'Griewangk'
function definitions drawn from [5], and 'Zimmermann' function definitions
drawn from [6].
References::
[1] Storn, R. and Price, K. "Differential Evolution - A Simple and
Efficient Heuristic for Global Optimization over Continuous Spaces"
Journal of Global Optimization 11: 341-359, 1997.
... | """a Griewangk's function generator
Griewangk's function [1,2,5] is a multi-dimensional cosine
function that provides several periodic local minima, with
the global minimum at the origin. The local minima are
fractionally more shallow than the global minimum, such that
when viewed at a very coarse scale the funct... | class Griewangk(AbstractFunction):
__doc__ = \ | random_line_split |
errors.js | const Shader = require('../')
const test = require('tape')
const GL = require('gl')
const gl = GL(256, 256)
test('kindred-shader: compiler errors', function (t) {
const valid = Shader`
attribute vec2 position;
void vert() {
gl_Position = vec4(position, 1, 1);
}
| `
const invalid = Shader`
attribute vec2 position;
void vert() {
unused_reference;
gl_Position = vec4(position, 1, 1);
}
void frag() {
gl_FragColor = vec4(1);
}
`
t.throws(function () {
invalid.bind(gl)
}, 'invalid shaders throw on binding')
t.throws(function (... | void frag() {
gl_FragColor = vec4(1);
} | random_line_split |
mimetype.rs | use std::path;
use std::io;
use std::io::{Error, ErrorKind};
use std::io::BufRead;
use std::io::BufReader;
use std::fs::File;
use server_side::utils;
#[derive(Debug)]
pub struct Mimetype {
mimetype_vec: Vec<MimetypeData>,
pub default_mimetype: String
}
#[derive(Debug)]
pub struct MimetypeData {
extension: String... | }
pub fn get_mimetype(&self) -> String {
self.mimetype.to_owned()
}
pub fn set_mimetype(&mut self, e: String) {
self.mimetype = e;
}
pub fn delete(self) {}
} | MimetypeData{extension: e, mimetype: m}
}
pub fn get_extension(&self) -> String {
self.extension.to_owned() | random_line_split |
mimetype.rs |
use std::path;
use std::io;
use std::io::{Error, ErrorKind};
use std::io::BufRead;
use std::io::BufReader;
use std::fs::File;
use server_side::utils;
#[derive(Debug)]
pub struct Mimetype {
mimetype_vec: Vec<MimetypeData>,
pub default_mimetype: String
}
#[derive(Debug)]
pub struct MimetypeData {
extension: Strin... | (&self) -> String {
self.mimetype.to_owned()
}
pub fn set_mimetype(&mut self, e: String) {
self.mimetype = e;
}
pub fn delete(self) {}
}
| get_mimetype | identifier_name |
_itertools.py | from itertools import filterfalse
from typing import (
Callable,
Iterable,
Iterator,
Optional,
Set,
TypeVar,
Union,
)
# Type and type variable definitions
_T = TypeVar('_T')
_U = TypeVar('_U')
def | (
iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
) -> Iterator[_T]:
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen: Set[Union[_T, _U]] = set()
s... | unique_everseen | identifier_name |
_itertools.py | from itertools import filterfalse
from typing import (
Callable,
Iterable,
Iterator,
Optional,
Set,
TypeVar,
Union,
)
# Type and type variable definitions
_T = TypeVar('_T')
_U = TypeVar('_U')
def unique_everseen(
iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
) -> ... | k = key(element)
if k not in seen:
seen_add(k)
yield element | conditional_block | |
_itertools.py | from itertools import filterfalse
from typing import (
Callable,
Iterable,
Iterator,
Optional,
Set,
TypeVar,
Union,
)
# Type and type variable definitions
_T = TypeVar('_T')
_U = TypeVar('_U')
def unique_everseen(
iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
) -> ... | for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element | if key is None: | random_line_split |
_itertools.py | from itertools import filterfalse
from typing import (
Callable,
Iterable,
Iterator,
Optional,
Set,
TypeVar,
Union,
)
# Type and type variable definitions
_T = TypeVar('_T')
_U = TypeVar('_U')
def unique_everseen(
iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None
) -> ... | "List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen: Set[Union[_T, _U]] = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, i... | identifier_body | |
test_netsnmp.py | # snapy - a python snmp library
#
# Copyright (C) 2009 ITA Software, Inc.
#
# 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.
#
# This program is distributed in the hope that it will be ... |
result = Result()
self.session.get(oids, set_result, result)
self.session.wait()
result = dict(result.value)
for oid in oids:
assert oid in result
assert result[oid] == "data data data data"
return self.finishGet()
def test_walk_tree(self)... | oids.append(OID((1,3,6,1,4,2,4,i))) | conditional_block |
test_netsnmp.py | # snapy - a python snmp library
#
# Copyright (C) 2009 ITA Software, Inc.
#
# 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.
#
# This program is distributed in the hope that it will be ... | (self):
self.assertRaises(SnmpError, self.session.sget, [".1.3.6.1.4.2.1.1"])
def test_get(self):
result = Result()
self.session.get([".1.3.6.1.4.2.1.1"], set_result, result)
self.session.wait()
assert isinstance(result.value, SnmpTimeout)
def tearDown(self):
se... | test_sget | identifier_name |
test_netsnmp.py | # snapy - a python snmp library
#
# Copyright (C) 2009 ITA Software, Inc.
#
# 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.
#
# This program is distributed in the hope that it will be ... | result = Result()
self.session.get([x for x,v in self.basics], set_result, result)
self.session.wait()
self.assertEquals(result.value, self.basics)
return self.finishGet()
def test_get_big(self):
oids = []
for i in xrange(1, 100):
oids.append(OID(... | self.assertEquals(result, self.basics)
return self.finishGet()
def test_get_small(self): | random_line_split |
test_netsnmp.py | # snapy - a python snmp library
#
# Copyright (C) 2009 ITA Software, Inc.
#
# 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.
#
# This program is distributed in the hope that it will be ... |
def tearDown(self):
self.session.close()
class TestTimeoutsV2c(TestTimeoutsV1):
version = "2c"
class TestOID(unittest.TestCase):
def test_oid_name(self):
oid = OID("1.3.6.1.2.1.1.1.0")
self.assertEquals(oid, OID("SNMPv2-MIB::sysDescr.0"))
self.assertEquals(oid, OID("sy... | result = Result()
self.session.get([".1.3.6.1.4.2.1.1"], set_result, result)
self.session.wait()
assert isinstance(result.value, SnmpTimeout) | identifier_body |
OfeliaDebianVMConfigurator.py | import shutil
import os
import jinja2
import string
import subprocess
import re
from xen.provisioning.HdManager import HdManager
from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEB... |
''' Public methods '''
@staticmethod
def getIdentifier():
return OfeliaDebianVMConfigurator.__name__
@staticmethod
def _configureNetworking(vm,path):
#Configure interfaces and udev settings
try:
try:
#Backup current files
shutil.copy(path+OXA_DEBIAN_INTERFACES_FILE_LOCATION,path+OXA_DEBIA... | template_name = "paraVirtualizedFileHd.pt"
template = env.get_template(template_name)
#Set vars&render
output = template.render(
kernelImg=OXA_XEN_SERVER_KERNEL,
initrdImg=OXA_XEN_SERVER_INITRD,
hdFilePath=HdManager.getHdPath(vm),
swapFilePath=HdManager.getSwapPath(vm),
vm=vm)
#... | identifier_body |
OfeliaDebianVMConfigurator.py | import shutil
import os
import jinja2
import string
import subprocess
import re
from xen.provisioning.HdManager import HdManager
from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEB... | def __configureInterfacesFile(vm,iFile):
#Loopback
iFile.write("auto lo\niface lo inet loopback\n\n")
#Interfaces
for inter in vm.xen_configuration.interfaces.interface :
if inter.ismgmt:
#is a mgmt interface
interfaceString = "auto "+inter.name+"\n"+\
"iface "+inter.name+" inet static\n"+\
... | ''' Private methods '''
@staticmethod | random_line_split |
OfeliaDebianVMConfigurator.py | import shutil
import os
import jinja2
import string
import subprocess
import re
from xen.provisioning.HdManager import HdManager
from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEB... | (vm, path):
if not path or not re.match(r'[\s]*\/\w+\/\w+\/.*', path,re.IGNORECASE): #For security, should never happen anyway
raise Exception("Incorrect vm path")
#Configure networking
OfeliaDebianVMConfigurator._configureNetworking(vm,path)
OfeliaDebianVMConfigurator.logger.info("Network configured suc... | configureVmDisk | identifier_name |
OfeliaDebianVMConfigurator.py | import shutil
import os
import jinja2
import string
import subprocess
import re
from xen.provisioning.HdManager import HdManager
from settings.settingsLoader import OXA_XEN_SERVER_KERNEL,OXA_XEN_SERVER_INITRD,OXA_DEBIAN_INTERFACES_FILE_LOCATION,OXA_DEBIAN_UDEV_FILE_LOCATION, OXA_DEBIAN_HOSTNAME_FILE_LOCATION, OXA_DEB... |
else:
raise Exception("type of file or type of virtualization not supported for the creation of xen vm configuration file")
@staticmethod
def configureVmDisk(vm, path):
if not path or not re.match(r'[\s]*\/\w+\/\w+\/.*', path,re.IGNORECASE): #For security, should never happen anyway
raise Exception("I... | OfeliaDebianVMConfigurator.__createParavirtualizationFileHdConfigFile(vm,env) | conditional_block |
bestCommonTypeObjectLiterals1.ts | /// <reference path='fourslash.ts'/>
////var a = { name: 'bob', age: 18 };
////var b = { name: 'jim', age: 20 };
////var c/*1*/ = [a, b];
////var a1 = { name: 'bob', age: 18 };
////var b1 = { name: 'jim', age: 20, dob: new Date() };
////var c1/*2*/ = [a1, b1];
|
////interface I {
//// name: string;
//// age: number;
////}
////var i: I;
////var c3/*5*/ = [a2, b2, i];
goTo.marker('1');
verify.quickInfoIs('{ name: string; age: number; }[]');
goTo.marker('2');
verify.quickInfoIs('{ name: string; age: number; }[]');
goTo.marker('3');
verify.quickInfoIs('{... | ////var a2 = { name: 'bob', age: 18, address: 'springfield' };
////var b2 = { name: 'jim', age: 20, dob: new Date() };
////var c2/*3*/ = [a2, b2];
////var c2a/*4*/ = [a2, b2, a1];
| random_line_split |
trickle.py | from copy import deepcopy
from distutils.spawn import find_executable
class Settings(object):
_upload_limit = 0
def __init__(self, settings=None):
if settings:
|
@property
def upload_limit(self):
""" Returns the value as required by the trickle command (i.e. in KBytes) """
return self._upload_limit
def upload_limit_in_kbytes(self, upload_limit):
self._upload_limit = upload_limit if upload_limit is not None else 0
def to_argument_list(... | self._upload_limit = settings.up_kbytes_sec | conditional_block |
trickle.py | from copy import deepcopy
from distutils.spawn import find_executable
class Settings(object):
_upload_limit = 0
def __init__(self, settings=None):
if settings:
self._upload_limit = settings.up_kbytes_sec
@property
def upload_limit(self):
""" Returns the value as required ... | (self):
"""
converts the setting in a list as required by the trickle command
"""
return ["-u", self._upload_limit] if self._upload_limit != 0 else []
class TrickleBwShaper(object):
_trickle_cmd = "trickle"
"""
Helper class to handle trickle (http://linux.die.net/man/1/tri... | to_argument_list | identifier_name |
trickle.py | from copy import deepcopy
from distutils.spawn import find_executable
class Settings(object):
_upload_limit = 0
def __init__(self, settings=None):
if settings:
self._upload_limit = settings.up_kbytes_sec
@property
def upload_limit(self):
""" Returns the value as required ... | """
"wraps" the call_cmd so it can be executed by subprocess.call (and related flavors) as "args" argument
:param call_cmd: original args like argument (string or sequence)
:return: a sequence with the original command "executed" under trickle
"""
if isinstance(call_cmd, bases... | identifier_body | |
trickle.py | from copy import deepcopy
from distutils.spawn import find_executable
class Settings(object):
_upload_limit = 0
def __init__(self, settings=None):
if settings:
self._upload_limit = settings.up_kbytes_sec
@property
def upload_limit(self):
""" Returns the value as required ... | Helper class to handle trickle (http://linux.die.net/man/1/trickle) usage
"""
def __init__(self, settings):
self._settings = deepcopy(settings)
self._trickle_cmd = find_executable("trickle")
if self._trickle_cmd is None:
raise RuntimeError("Couldn't find 'trickle' progra... |
""" | random_line_split |
rootnode.py | # Copyright (C) 2009 Ashley J. Wilson
# This software is licensed as described in the file COPYING in the root
# directory of this distribution.
from storenode import StoreNode
from bundlenode import BundleNode
from packagenode import PackageNode
class RootNode(StoreNode):
"""The virtual root of a Store repositor... | self.bundle_names = []
else:
self.bundle_names = [bn.strip() for bn in bundle_desc.split(',')]
if not package_desc:
self.package_prefixes = []
else:
self.package_prefixes = [pp.strip() for pp in package_desc.split(',')]
def get_entries(self):... |
if not bundle_desc: | random_line_split |
rootnode.py | # Copyright (C) 2009 Ashley J. Wilson
# This software is licensed as described in the file COPYING in the root
# directory of this distribution.
from storenode import StoreNode
from bundlenode import BundleNode
from packagenode import PackageNode
class RootNode(StoreNode):
"""The virtual root of a Store repositor... | if package_prefix == 'ALL':
for pkg in PackageNode.all(self.repos):
yield pkg
elif package_prefix != None:
for pkg in PackageNode.named_like(self.repos, package_prefix + '%'):
yield pkg | conditional_block | |
rootnode.py | # Copyright (C) 2009 Ashley J. Wilson
# This software is licensed as described in the file COPYING in the root
# directory of this distribution.
from storenode import StoreNode
from bundlenode import BundleNode
from packagenode import PackageNode
class RootNode(StoreNode):
| if not bundle_desc:
self.bundle_names = []
else:
self.bundle_names = [bn.strip() for bn in bundle_desc.split(',')]
if not package_desc:
self.package_prefixes = []
else:
self.package_prefixes = [pp.strip() for pp in package_desc.split(',')]... | """The virtual root of a Store repository.
This node has as its children the BundleNode and/or set of PackageNodes,
that are specified by the trac.ini file as the interesting part of
the Store repository. RootNodes have only the special revision 'ONLY' and
no previous or next changeset.
"""
d... | identifier_body |
rootnode.py | # Copyright (C) 2009 Ashley J. Wilson
# This software is licensed as described in the file COPYING in the root
# directory of this distribution.
from storenode import StoreNode
from bundlenode import BundleNode
from packagenode import PackageNode
class RootNode(StoreNode):
"""The virtual root of a Store repositor... | (self, repos, bundle_desc, package_desc):
"""Create a RootNode that will report the interesting subset of the Store
repository as its children.
bundle_desc is expected to be either an exact bundle name from Store, or a
comma-separated list of the same. Similarly, package_desc is either... | __init__ | identifier_name |
exercise.rs | "always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE";
const CONTEXT: usize = 2;
const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/clippy/Cargo.toml";
// Get a temporary file name that is hopefully unique to this process
#[inline]
fn temp_file() -> String {
format!("./temp_{}", process::i... | {
// The source code that is still pending completion
pub line: String,
// The line number of the source code still pending completion
pub number: usize,
// Whether or not this is important
pub important: bool,
}
// The result of compiling an exercise
pub struct CompiledExercise<'a> {
exer... | ContextLine | identifier_name |
exercise.rs | "always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE";
const CONTEXT: usize = 2;
const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/clippy/Cargo.toml";
// Get a temporary file name that is hopefully unique to this process
#[inline]
fn temp_file() -> String {
format!("./temp_{}", process::i... | .expect("Failed to compile!");
// Due to an issue with Clippy, a cargo clean is required to catch all lints.
// See https://github.com/rust-lang/rust-clippy/issues/2604
// This is already fixed on master branch. See this issue to track merging into Car... | Command::new("rustc")
.args(&[self.path.to_str().unwrap(), "-o", &temp_file()])
.args(RUSTC_COLOR_ARGS)
.output() | random_line_split |
exercise.rs | always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE";
const CONTEXT: usize = 2;
const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/clippy/Cargo.toml";
// Get a temporary file name that is hopefully unique to this process
#[inline]
fn temp_file() -> String {
format!("./temp_{}", process::id(... |
}
impl Exercise {
pub fn compile(&self) -> Result<CompiledExercise, ExerciseOutput> {
let cmd = match self.mode {
Mode::Compile => Command::new("rustc")
.args(&[self.path.to_str().unwrap(), "-o", &temp_file()])
.args(RUSTC_COLOR_ARGS)
.output(),
... | {
clean();
} | identifier_body |
exercise.rs | always"];
const I_AM_DONE_REGEX: &str = r"(?m)^\s*///?\s*I\s+AM\s+NOT\s+DONE";
const CONTEXT: usize = 2;
const CLIPPY_CARGO_TOML_PATH: &str = "./exercises/clippy/Cargo.toml";
// Get a temporary file name that is hopefully unique to this process
#[inline]
fn temp_file() -> String {
format!("./temp_{}", process::id(... | let matched_line_index = source
.lines()
.enumerate()
.filter_map(|(i, line)| if re.is_match(line) { Some(i) } else { None })
.next()
.expect("This should not happen at all");
let min_line = ((matched_line_index as i32) - (CONTEXT as i32)).max(0) ... | return State::Done;
}
| conditional_block |
module.js | import { history } from 'byebye';
import React from 'react';
import AltContainer from 'alt-container';
import { MANUAL_LOGOUT } from 'app-constants';
import { loginIfAuthorized as autoFacebookLogin } from 'managers/facebook';
import Analytics from 'instances/analytics';
import parseJWT from 'helpers/parseJWT';
import {... | if (Auth.getId()) {
const url = `/item/${itemId}`;
history.navigate(url, { trigger: true, replace: false }, { returnUrl: '/' });
return <span />;
}
Analytics.track('Email login/deeplink landing');
const tokenData = JSON.parse(decodeBase64(token));
const data = {
item_id: itemId,
user_id:... | random_line_split | |
module.js | import { history } from 'byebye';
import React from 'react';
import AltContainer from 'alt-container';
import { MANUAL_LOGOUT } from 'app-constants';
import { loginIfAuthorized as autoFacebookLogin } from 'managers/facebook';
import Analytics from 'instances/analytics';
import parseJWT from 'helpers/parseJWT';
import {... | LoginActions.loginSuccess(null, {
login_type: 'facebookautologin',
platform: 'facebook',
});
})
.catch((err) => {
if (err.type === MANUAL_LOGOUT || err.type === 'UnableToLogin') {
// Convert the force parameter to a boolean. If `true`, it forces the backend to send the
... | {
if (Auth.getId()) {
const url = `/item/${itemId}`;
history.navigate(url, { trigger: true, replace: false }, { returnUrl: '/' });
return <span />;
}
Analytics.track('Email login/deeplink landing');
const tokenData = JSON.parse(decodeBase64(token));
const data = {
item_id: itemId,
user_i... | identifier_body |
module.js | import { history } from 'byebye';
import React from 'react';
import AltContainer from 'alt-container';
import { MANUAL_LOGOUT } from 'app-constants';
import { loginIfAuthorized as autoFacebookLogin } from 'managers/facebook';
import Analytics from 'instances/analytics';
import parseJWT from 'helpers/parseJWT';
import {... | (itemId, token, force) {
if (Auth.getId()) {
const url = `/item/${itemId}`;
history.navigate(url, { trigger: true, replace: false }, { returnUrl: '/' });
return <span />;
}
Analytics.track('Email login/deeplink landing');
const tokenData = JSON.parse(decodeBase64(token));
const data = {
item... | openItemLogin | identifier_name |
module.js | import { history } from 'byebye';
import React from 'react';
import AltContainer from 'alt-container';
import { MANUAL_LOGOUT } from 'app-constants';
import { loginIfAuthorized as autoFacebookLogin } from 'managers/facebook';
import Analytics from 'instances/analytics';
import parseJWT from 'helpers/parseJWT';
import {... |
Analytics.track('Email login/deeplink landing');
const tokenData = JSON.parse(decodeBase64(token));
const data = {
item_id: itemId,
user_id: tokenData.id,
domain: tokenData.domain,
name: tokenData.name,
};
// auto login with facebook, and when FB login fails we will send you an email
aut... | {
const url = `/item/${itemId}`;
history.navigate(url, { trigger: true, replace: false }, { returnUrl: '/' });
return <span />;
} | conditional_block |
hourView.ts | import * as angular from 'angular';
import * as moment from 'moment';
import { IView, IViewItem, IDirectiveScopeInternal, IModelController } from '../definitions';
import { IProviderOptions } from '../provider';
import { isValidMoment } from '../utility';
export default class HourView implements IView {
public perLin... |
public highlightClosest(): void {
let minutes = <IViewItem[]>[], minute;
angular.forEach(this.rows, (row) => {
angular.forEach(row, (value) => {
if (Math.abs(value.minute - this.$scope.view.moment.minute()) < this.provider.minutesStep) minutes.push(value);
});
});
minute = minutes.sort((value1, val... | {
if (!minute.selectable) return;
this.$scope.view.moment.year(minute.year).month(minute.month).date(minute.date).hour(minute.hour).minute(minute.minute);
this.$scope.view.update();
this.$scope.view.change('minute');
} | identifier_body |
hourView.ts | import * as angular from 'angular';
import * as moment from 'moment';
import { IView, IViewItem, IDirectiveScopeInternal, IModelController } from '../definitions';
import { IProviderOptions } from '../provider';
import { isValidMoment } from '../utility';
export default class HourView implements IView {
public perLin... | year: minute.year(),
month: minute.month(),
date: minute.date(),
hour: minute.hour(),
minute: minute.minute(),
class: [
this.$scope.keyboard && minute.isSame(this.$scope.view.moment, 'minute') ? 'highlighted' : '',
!selectable ? 'disabled' : isValidMoment(this.$ctrl.$modelValue) && min... | label: minute.format(minutesFormat), | random_line_split |
hourView.ts | import * as angular from 'angular';
import * as moment from 'moment';
import { IView, IViewItem, IDirectiveScopeInternal, IModelController } from '../definitions';
import { IProviderOptions } from '../provider';
import { isValidMoment } from '../utility';
export default class HourView implements IView {
public perLin... | (): void {
let minutes = <IViewItem[]>[], minute;
angular.forEach(this.rows, (row) => {
angular.forEach(row, (value) => {
if (Math.abs(value.minute - this.$scope.view.moment.minute()) < this.provider.minutesStep) minutes.push(value);
});
});
minute = minutes.sort((value1, value2) => {
return Math.a... | highlightClosest | identifier_name |
wunderground-slash-command.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
import urllib.parse
import json
# Define server address and port, use localhost if you are running this on your Mattermost server.
HOSTNAME = ''
PORT = 7800
# guarantee unicode string
_u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t... |
elif key == 'user_name':
user_name = data[key]
elif key == 'channel_name':
channel_name = data[key]
responsetext = ''
print("Found command %s" % token)
if token[0] == u'<your-slash-command-token>':
if len(text) > 0:
... | team_domain = data[key] | conditional_block |
wunderground-slash-command.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
import urllib.parse
import json
# Define server address and port, use localhost if you are running this on your Mattermost server.
HOSTNAME = ''
PORT = 7800
# guarantee unicode string
_u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t... | print("Found more than 1 city")
res = u"**Available cities**:\r\n"
for c in cities["RESULTS"]:
res = u"%s* %s\r\n" % (res, c["name"])
return res
else:
print("Requesting weather info from wunderground")
res = ""
c = cities["RESULTS"][0]
r = ... | if "RESULTS" not in cities or len(cities["RESULTS"]) == 0:
print("No result")
return u"**No city found**"
elif len(cities["RESULTS"]) > 1: | random_line_split |
wunderground-slash-command.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
import urllib.parse
import json
# Define server address and port, use localhost if you are running this on your Mattermost server.
HOSTNAME = ''
PORT = 7800
# guarantee unicode string
_u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t... | (BaseHTTPRequestHandler):
def do_GET(self):
length = int(self.headers['Content-Length'])
data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
response_url = ""
text = ""
token = ""
channel_id = ""
team_id = ""
command = ""
... | PostHandler | identifier_name |
wunderground-slash-command.py | from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
import urllib.parse
import json
# Define server address and port, use localhost if you are running this on your Mattermost server.
HOSTNAME = ''
PORT = 7800
# guarantee unicode string
_u = lambda t: t.decode('UTF-8', 'replace') if isinstance(t... | elif key == 'channel_id':
channel_id = data[key]
elif key == 'team_id':
team_id = data[key]
elif key == 'command':
command = data[key]
elif key == 'team_domain':
team_domain = data[key]
elif key =... | length = int(self.headers['Content-Length'])
data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
response_url = ""
text = ""
token = ""
channel_id = ""
team_id = ""
command = ""
team_domain = ""
user_name = ""
cha... | identifier_body |
media.py | # -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along ... | """ Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError | identifier_body | |
media.py | # -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along ... | (self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a f... | delete | identifier_name |
media.py | # -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along ... | ..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def g... | inherit or override as necessary.
| random_line_split |
route.ts | import "reflect-metadata";
import { given } from "@nivinjoseph/n-defensive";
import "@nivinjoseph/n-ext";
export const appRouteSymbol = Symbol("appRoute");
// public
export function route(route: string, redirect?: string): Function
| {
given(route, "route").ensureHasValue()
.ensureIsString()
.ensure(t => !t.isEmptyOrWhiteSpace(), "cannot be empty or whitespace")
.ensure(t => t.trim().startsWith("/"), "has to begin with '/'");
given(redirect, "redirect")
.ensureIsString()
.ensure(t => !t.i... | identifier_body | |
route.ts | import "reflect-metadata";
import { given } from "@nivinjoseph/n-defensive";
import "@nivinjoseph/n-ext";
export const appRouteSymbol = Symbol("appRoute");
// public
export function route(route: string, redirect?: string): Function
{
given(route, "route").ensureHasValue()
.ensureIsString()
.en... | } | random_line_split | |
route.ts | import "reflect-metadata";
import { given } from "@nivinjoseph/n-defensive";
import "@nivinjoseph/n-ext";
export const appRouteSymbol = Symbol("appRoute");
// public
export function | (route: string, redirect?: string): Function
{
given(route, "route").ensureHasValue()
.ensureIsString()
.ensure(t => !t.isEmptyOrWhiteSpace(), "cannot be empty or whitespace")
.ensure(t => t.trim().startsWith("/"), "has to begin with '/'");
given(redirect, "redirect")
.e... | route | identifier_name |
forms.py | from django import forms
from .models import Author
class RegisterNewAuthorForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
repeated_password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = Author
fields = ['email', 'first_name', 'last_n... |
def clean(self):
cleaned_data = super(RegisterNewAuthorForm, self).clean()
password = cleaned_data.get("password")
repeated_password = cleaned_data.get("repeated_password")
if password == repeated_password:
return cleaned_data
raise forms.ValidationError("Pass... | visible.field.widget.attrs['class'] = 'form-control' | conditional_block |
forms.py | from django import forms
from .models import Author
class RegisterNewAuthorForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
repeated_password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = Author
fields = ['email', 'first_name', 'last_n... |
def clean(self):
cleaned_data = super(RegisterNewAuthorForm, self).clean()
password = cleaned_data.get("password")
repeated_password = cleaned_data.get("repeated_password")
if password == repeated_password:
return cleaned_data
raise forms.ValidationError("Pass... | super(RegisterNewAuthorForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control' | identifier_body |
forms.py | from django import forms
from .models import Author
class RegisterNewAuthorForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
repeated_password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = Author
fields = ['email', 'first_name', 'last_n... | except Author.DoesNotExist:
error_msg = "User with email {} does not exist".format(email)
raise forms.ValidationError(error_msg) | author = Author.objects.get(email=email)
if author.check_password(password):
return cleaned_data
raise forms.ValidationError("Wrong password") | random_line_split |
forms.py | from django import forms
from .models import Author
class RegisterNewAuthorForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
repeated_password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = Author
fields = ['email', 'first_name', 'last_n... | (self):
cleaned_data = super(RegisterNewAuthorForm, self).clean()
password = cleaned_data.get("password")
repeated_password = cleaned_data.get("repeated_password")
if password == repeated_password:
return cleaned_data
raise forms.ValidationError("Passwords does not ... | clean | identifier_name |
comp_table.py | #!/usr/bin/env python2
"""
COSMO TECHNICAL TESTSUITE
General purpose script to compare two files containing tables
Only lines with given table pattern are considered
"""
# built-in modules
import os, sys, string
# information
__author__ = "Xavier Lapillonne"
__maintainer__ = "xavier.lapillonne@meteoswiss.ch"
... | (file1,file2,colpattern,minval,threshold,verbose=1,maxcompline=-1):
# General purpose script to compare two files containing tables
# Only lines with given table column pattern. Column to be compared are marked with c
# column to discard with x
#init
ncomp=0
nerror=0
lerror=False
epsi... | cmp_table | identifier_name |
comp_table.py | #!/usr/bin/env python2
"""
COSMO TECHNICAL TESTSUITE
General purpose script to compare two files containing tables
Only lines with given table pattern are considered
"""
# built-in modules
import os, sys, string
# information
__author__ = "Xavier Lapillonne"
__maintainer__ = "xavier.lapillonne@meteoswiss.ch"
... |
#-----------------------------------
#execute as a script
if __name__ == "__main__":
if len(sys.argv)==6:
cmp_table(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4], \
sys.argv[5])
elif len(sys.argv)==7:
cmp_table(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4], \
sy... | if len(line)!=len(colpattern):
return False
try:
for i in range(len(colpattern)):
if colpattern[i]: f=float(line[i])
except ValueError:
return False
return True | identifier_body |
comp_table.py | #!/usr/bin/env python2
"""
COSMO TECHNICAL TESTSUITE
General purpose script to compare two files containing tables
Only lines with given table pattern are considered
"""
# built-in modules
import os, sys, string
# information
__author__ = "Xavier Lapillonne"
__maintainer__ = "xavier.lapillonne@meteoswiss.ch"
... |
#save line for first error
if not lerror:
differ=diff
linerr=il+1
colerr=ic+1
linerr1=data1[il]
linerr2... | print('Error %2.2e above %2.2e thresold at line %i, col %i' %(diff,threshold,il+1,ic+1))
print('> %s' %(file1))
print(data1[il])
print('< %s' %(file2))
print(data2[il]) | conditional_block |
comp_table.py | #!/usr/bin/env python2
"""
COSMO TECHNICAL TESTSUITE
General purpose script to compare two files containing tables
Only lines with given table pattern are considered
"""
# built-in modules
import os, sys, string
# information
__author__ = "Xavier Lapillonne"
__maintainer__ = "xavier.lapillonne@meteoswiss.ch"
... | nerror=0
lerror=False
epsilon=1e-16 #used to avoid division by zero in case minval is zero
# check file existence
if not(os.path.exists(file1)):
print('File %s does not exist' %(file1))
return -1
elif not(os.path.exists(file2)):
print('File %s does not exist' %(file2... | # Only lines with given table column pattern. Column to be compared are marked with c
# column to discard with x
#init
ncomp=0 | random_line_split |
article_simulated_estimate_mpi.py | () == 0: # @UndefinedVariable
Y,act_komp, mus, Thetas, Sigmas, P = np.array(article_simulatedata.simulate_data_v1(nCells = nCells, nPersons = nPers))
else:
Y = None
act_komp = None
#npr.seed(123546)
####
# Setting up model
####
hGMM = bm.hierarical_mixture_mpi(K = 4)
hGMM.set_data(Y)
hGMM.set_prior_param0()
hG... | f, ax = hGMM.plot_mus([0,1,2], colors =mus_colors, size_point = 5 )
if MPI.COMM_WORLD.Get_rank() == 0: # @UndefinedVariable
######################
#ordering mus
mus_true_mean = []
mus_mean = []
for k in range(hGMM.K):
mus_true_mean.append(np.array(np.ma.masked_invalid(mus[:,k,:]).mean(0)))
mus_mean.append(... | matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"]
#hGMM.plot_GMM_scatter_all([0, 1])
mus_colors = ['r','b','k','m'] | random_line_split |
article_simulated_estimate_mpi.py | () == 0: # @UndefinedVariable
Y,act_komp, mus, Thetas, Sigmas, P = np.array(article_simulatedata.simulate_data_v1(nCells = nCells, nPersons = nPers))
else:
Y = None
act_komp = None
#npr.seed(123546)
####
# Setting up model
####
hGMM = bm.hierarical_mixture_mpi(K = 4)
hGMM.set_data(Y)
hGMM.set_prior_param0()
hG... | np.set_printoptions(precision=2)
perc_theta = []
perc_Q_vec = []
for k in range(hGMM.K):
perc_ = np.percentile(theta_sim[:,col_index[k],:] - Thetas[k],[2.5,50,97.5],axis=0)
perc_theta.append(np.array(perc_).T)
#print "%d & %s & %s & %s & \\hline" %(k, np.mean(theta_sim[:,col_index[k],:],0) - Thetas[k],perc_[... | mus_true_mean = []
mus_mean = []
for k in range(hGMM.K):
mus_true_mean.append(np.array(np.ma.masked_invalid(mus[:,k,:]).mean(0)))
mus_mean.append(np.array(np.ma.masked_invalid(mus_[:,k,:].T).mean(0)))
mus_true_mean = np.array(mus_true_mean)
mus_mean = np.array(mus_mean)
ss_mat = ss.distance.cdist( mus_true_... | conditional_block |
admin.py | #To-DO:NEXT: Write the show_keys email command [admin level]
#To-Do:NEXT: Write the other templates
#To-Do:NEXT: write the connect command [user level]
#TO-DO:NEXT: Fix subject bug.
#To-DO:NEXT: Make the html emails look prettier somehow.
#listening script
from core import *
import codebase
import poplib
... | (emailid, password):
check_for_orders(emailid, password)
if orders == []:
log.append('Searching for orders...')
else:
for items in orders:
#admin command to create key -> crea [x] [MASTERKEY]
if str(items)[0:4] == 'CREA':
codebase.keys_create(int(str(items)[5:6]), str(items)[7:len(items)])
... | mainloop | identifier_name |
admin.py | #To-DO:NEXT: Write the show_keys email command [admin level]
#To-Do:NEXT: Write the other templates
#To-Do:NEXT: write the connect command [user level]
#TO-DO:NEXT: Fix subject bug.
#To-DO:NEXT: Make the html emails look prettier somehow.
#listening script
from core import *
import codebase
import poplib
... | key = str(items)[4:8]
otherstuff = str(items)[9:len(str(items))]
name = otherstuff.split('|')[0]
pricepu = otherstuff.split('|')[1]
quan = otherstuff.split('|')[2]
units = otherstuff.split('|')[3]
pkey = otherstuff.split('|')[4]
for keys in codebase.inv.keys:
if key == keys:... | if str(items)[0:3] == 'add':
log.append(items)
| random_line_split |
admin.py | #To-DO:NEXT: Write the show_keys email command [admin level]
#To-Do:NEXT: Write the other templates
#To-Do:NEXT: write the connect command [user level]
#TO-DO:NEXT: Fix subject bug.
#To-DO:NEXT: Make the html emails look prettier somehow.
#listening script
from core import *
import codebase
import poplib
... | pk = otherstuff.split('|')[2]
for keys in codebase.inv.keys:
if key == keys:
for pkeys in codebase.inv.keys:
try:
if codebase.inv.mappedkeys[key] == pk:
print 'Pkey already exists.' #nevergonnahappen
except KeyError:
codebase.inv.map_keys(key, ph, em)
... | for items in orders:
#admin command to create key -> crea [x] [MASTERKEY]
if str(items)[0:4] == 'CREA':
codebase.keys_create(int(str(items)[5:6]), str(items)[7:len(items)])
log.append(items)
print '\tKey(s) created.'
orders.remove(items)
#admin command to stop the program -> EXIT [MAST... | conditional_block |
admin.py | #To-DO:NEXT: Write the show_keys email command [admin level]
#To-Do:NEXT: Write the other templates
#To-Do:NEXT: write the connect command [user level]
#TO-DO:NEXT: Fix subject bug.
#To-DO:NEXT: Make the html emails look prettier somehow.
#listening script
from core import *
import codebase
import poplib
... |
def check_for_orders(emailid, password):
#we only check for max 10 orders every refresh
max_orders = 10
#log into pop
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user(emailid)
pop_conn.pass_(password)
#counting number of messages
msgcount = pop_conn.stat()[0]
#main loop checking the... | fromaddr = e
to = user
body = unicode(body)
msg = MIMEMultipart('alternative')
msg['From'] = str(fromaddr)
msg['To'] = str(to)
msg['Subject'] = 'EMS' #not working. Why?
chunk = MIMEText(body,'html')
msg.attach(chunk)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.log... | identifier_body |
clipboard.rs | use std::string;
use SdlResult;
use get_error;
#[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasCl... | () -> SdlResult<String> {
let result = unsafe {
let cstr = ll::SDL_GetClipboardText() as *const u8;
string::raw::from_buf(cstr)
};
if result.len() == 0 {
Err(get_error())
} else {
Ok(result)
}
}
pub fn has_clipboard_text() -> bool {
unsafe { ll::SDL_HasClipboard... | get_clipboard_text | identifier_name |
clipboard.rs | use std::string;
use SdlResult;
use get_error;
#[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasCl... | else {
Ok(())
}
}
}
pub fn get_clipboard_text() -> SdlResult<String> {
let result = unsafe {
let cstr = ll::SDL_GetClipboardText() as *const u8;
string::raw::from_buf(cstr)
};
if result.len() == 0 {
Err(get_error())
} else {
Ok(result)
}
}
... | {
Err(get_error())
} | conditional_block |
clipboard.rs | use std::string;
use SdlResult;
use get_error;
#[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasCl... |
pub fn has_clipboard_text() -> bool {
unsafe { ll::SDL_HasClipboardText() == 1 }
}
| {
let result = unsafe {
let cstr = ll::SDL_GetClipboardText() as *const u8;
string::raw::from_buf(cstr)
};
if result.len() == 0 {
Err(get_error())
} else {
Ok(result)
}
} | identifier_body |
clipboard.rs | use std::string;
use SdlResult;
use get_error; | #[allow(non_camel_case_types)]
pub mod ll {
use libc::{c_int, c_char};
pub type SDL_bool = c_int;
extern "C" {
pub fn SDL_SetClipboardText(text: *const c_char) -> c_int;
pub fn SDL_GetClipboardText() -> *const c_char;
pub fn SDL_HasClipboardText() -> SDL_bool;
}
}
pub fn set_c... | random_line_split | |
control.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 agreed t... | (self):
"""
Method required by RAVEN to run this as an ControlFunction in LogicalModel.
@ In, self, object, object to store members on
@ Out, model, str, the name of external model that
will be executed by hybrid model
"""
model = None
if self.x > 0.5 and self.y > 1.5:
model = 'poly'
els... | evaluate | identifier_name |
control.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 agreed t... | """
Method required by RAVEN to run this as an ControlFunction in LogicalModel.
@ In, self, object, object to store members on
@ Out, model, str, the name of external model that
will be executed by hybrid model
"""
model = None
if self.x > 0.5 and self.y > 1.5:
model = 'poly'
else:
mod... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.