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 |
|---|---|---|---|---|
lib.rs | pub fn to_bytes(values: &[u32]) -> Vec<u8> { | let mut per_stream_vec = Vec::new();
let mut per_byte_vec: Vec<u8> = Vec::new();
for value in values {
rb = *value;
loop {
let mut b = rb & 0x7F;
if idx == 0 {
b &= 0x7F;
} else {
b |= 0x80;
}
per_by... | let mut idx = 0;
let mut rb: u32; | random_line_split |
lib.rs | pub fn to_bytes(values: &[u32]) -> Vec<u8> {
let mut idx = 0;
let mut rb: u32;
let mut per_stream_vec = Vec::new();
let mut per_byte_vec: Vec<u8> = Vec::new();
for value in values {
rb = *value;
loop {
let mut b = rb & 0x7F;
if idx == 0 {
b &=... | else {
incomplete_byte_seq = false;
no_bytes += 1;
// check for overflow
if no_bytes > 4 {
return Err("value overflowed!");
}
u32_val |= (byte & 0x7F) as u32;
v.push(u32_val);
u32_val = 0;
no_byt... | {
incomplete_byte_seq = true;
no_bytes += 1;
u32_val |= (byte & 0x7F) as u32;
u32_val <<= 7;
} | conditional_block |
lib.rs | pub fn to_bytes(values: &[u32]) -> Vec<u8> {
let mut idx = 0;
let mut rb: u32;
let mut per_stream_vec = Vec::new();
let mut per_byte_vec: Vec<u8> = Vec::new();
for value in values {
rb = *value;
loop {
let mut b = rb & 0x7F;
if idx == 0 {
b &=... | v.push(u32_val);
u32_val = 0;
no_bytes = 0;
}
}
if incomplete_byte_seq {
return Err("incomplete sequence!");
}
Ok(v)
}
| {
let mut v: Vec<u32> = Vec::new();
let mut no_bytes = 0;
let mut u32_val = 0u32;
let mut incomplete_byte_seq = false;
for byte in bytes {
if byte & 0x80 != 0 {
incomplete_byte_seq = true;
no_bytes += 1;
u32_val |= (byte & 0x7F) as u32;
u32_va... | identifier_body |
lib.rs | pub fn | (values: &[u32]) -> Vec<u8> {
let mut idx = 0;
let mut rb: u32;
let mut per_stream_vec = Vec::new();
let mut per_byte_vec: Vec<u8> = Vec::new();
for value in values {
rb = *value;
loop {
let mut b = rb & 0x7F;
if idx == 0 {
b &= 0x7F;
... | to_bytes | identifier_name |
distributed_discrete_gaussian_query_test.py | # Copyright 2021, Google LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | from distributed_dp import distributed_discrete_gaussian_query
ddg_sum_query = distributed_discrete_gaussian_query.DistributedDiscreteGaussianSumQuery
def silence_tf_error_messages(func):
"""Decorator that temporarily changes the TF logging levels."""
def wrapper(*args, **kwargs):
cur_verbosity = tf.compat.... | from distributed_dp import discrete_gaussian_utils | random_line_split |
distributed_discrete_gaussian_query_test.py | # Copyright 2021, Google LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | tf.test.main() | conditional_block | |
distributed_discrete_gaussian_query_test.py | # Copyright 2021, Google LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | (*args, **kwargs):
cur_verbosity = tf.compat.v1.logging.get_verbosity()
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.FATAL)
func(*args, **kwargs)
tf.compat.v1.logging.set_verbosity(cur_verbosity) # Reset verbosity.
return wrapper
class DistributedDiscreteGaussianQueryTest(tf.test.TestCa... | wrapper | identifier_name |
distributed_discrete_gaussian_query_test.py | # Copyright 2021, Google LLC. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
class DistributedDiscreteGaussianQueryTest(tf.test.TestCase,
parameterized.TestCase):
def test_sum_no_noise(self):
with self.cached_session() as sess:
record1 = tf.constant([2, 0], dtype=tf.int32)
record2 = tf.constant([-1, 1], dtype=tf.int32)
quer... | """Decorator that temporarily changes the TF logging levels."""
def wrapper(*args, **kwargs):
cur_verbosity = tf.compat.v1.logging.get_verbosity()
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.FATAL)
func(*args, **kwargs)
tf.compat.v1.logging.set_verbosity(cur_verbosity) # Reset verbosity.... | identifier_body |
glucoseStore.js | import alt from '../lib/AltInstance';
import GlucoseActions from '../actions/glucoseAction';
import ImmutableStore from 'alt/utils/ImmutableUtil';
import constants from '../constants/constants';
class GlucoseStore {
constructor() {
this.disconnected = this.disconnected.bind(this);
this.connected = ... | }
export default alt.createStore(ImmutableStore(GlucoseStore), 'GlucoseStore'); | random_line_split | |
glucoseStore.js | import alt from '../lib/AltInstance';
import GlucoseActions from '../actions/glucoseAction';
import ImmutableStore from 'alt/utils/ImmutableUtil';
import constants from '../constants/constants';
class GlucoseStore {
constructor() {
this.disconnected = this.disconnected.bind(this);
this.connected = ... | (state) {
var currState = this.state;
currState.data = true;
if (currState.history) {
var history = currState.history;
history = _.sortBy(history, 'time').reverse().filter(function(g) {
var unixTime = new Date(g.time).getTime();
if (unixTim... | update | identifier_name |
glucoseStore.js | import alt from '../lib/AltInstance';
import GlucoseActions from '../actions/glucoseAction';
import ImmutableStore from 'alt/utils/ImmutableUtil';
import constants from '../constants/constants';
class GlucoseStore {
constructor() {
this.disconnected = this.disconnected.bind(this);
this.connected = ... |
}
}
initialized(state) {
state.data = true;
this.setState(state);
}
update(state) {
var currState = this.state;
currState.data = true;
if (currState.history) {
var history = currState.history;
history = _.sortBy(history, 'time').... | {
self.disconnected();
} | conditional_block |
tabs.d.ts | import { ModuleWithProviders, NgZone, QueryList } from '@angular/core';
import { MdTabLabel } from './tab-label';
import { MdTabContent } from './tab-content';
import { MdTabLabelWrapper } from './tab-label-wrapper';
import { MdInkBar } from './ink-bar';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/op... | {
private _zone;
_tabs: QueryList<MdTab>;
_labelWrappers: QueryList<MdTabLabelWrapper>;
_inkBar: QueryList<MdInkBar>;
private _isInitialized;
private _selectedIndex;
selectedIndex: number;
/**
* Determines if an index is valid. If the tabs are not ready yet, we assume that the use... | MdTabGroup | identifier_name |
tabs.d.ts | import { ModuleWithProviders, NgZone, QueryList } from '@angular/core';
import { MdTabLabel } from './tab-label';
import { MdTabContent } from './tab-content';
import { MdTabLabelWrapper } from './tab-label-wrapper';
import { MdInkBar } from './ink-bar';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/op... | label: MdTabLabel;
content: MdTabContent;
private _disabled;
disabled: boolean;
}
/**
* Material design tab-group component. Supports basic tab pairs (label + content) and includes
* animated ink-bar, keyboard navigation, and screen reader.
* See: https://www.google.com/design/spec/components/tabs.h... | export declare class MdTabChangeEvent {
index: number;
tab: MdTab;
}
export declare class MdTab { | random_line_split |
env.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 version.... | use uint::Uint;
/// Vm environment.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Env {
/// Address.
#[serde(rename="currentCoinbase")]
pub author: Address,
/// Difficulty
#[serde(rename="currentDifficulty")]
pub difficulty: Uint,
/// Gas limit.
#[serde(rename="currentGasLimit")]
pub gas_limit: Uint,
/... | random_line_split | |
env.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 version.... | () {
let s = r#"{
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "0x0100",
"currentGasLimit" : "0x0f4240",
"currentNumber" : "0x00",
"currentTimestamp" : "0x01"
}"#;
let _deserialized: Env = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}... | env_deserialization | identifier_name |
env.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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 version.... |
}
| {
let s = r#"{
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "0x0100",
"currentGasLimit" : "0x0f4240",
"currentNumber" : "0x00",
"currentTimestamp" : "0x01"
}"#;
let _deserialized: Env = serde_json::from_str(s).unwrap();
// TODO: validate all fields
} | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
Red => "red",
Yellow => "yellow",
Blue => "blue",
};
write!(f, "{}", str)
}
}
#[derive(Copy)]
struct CreatureInfo {
name: uint,
color: Color
}
fn show_color_list(set: Vec<Co... | fmt | identifier_name |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | to_rendezvous_log);
});
to_creature
}).collect();
let mut creatures_met = 0;
// set up meetings...
for _ in 0..nn {
let fst_creature = from_creatures.recv().unwrap();
let snd_creature = from_creatures.recv().unwrap();
creatu... | {
// these ports will allow us to hear from the creatures
let (to_rendezvous, from_creatures) = channel::<CreatureInfo>();
// these channels will be passed to the creatures so they can talk to us
let (to_rendezvous_log, from_creatures_log) = channel::<String>();
// these channels will allow us to ... | identifier_body |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | println!("{}", show_color_list(set));
// print each creature's stats
drop(to_rendezvous_log);
for rep in from_creatures_log.iter() {
println!("{}", rep);
}
// print the total number of creatures met
println!("{:?}\n", Number(creatures_met));
}
fn main() {
let nn = if std::env:... | drop(to_creature);
// print each color in the set | random_line_split |
shootout-chameneos-redux.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted... | else {
std::env::args()
.nth(1)
.and_then(|arg| arg.parse().ok())
.unwrap_or(600)
};
print_complements();
println!("");
rendezvous(nn, vec!(Blue, Red, Yellow));
rendezvous(nn,
vec!(Blue, Red, Yellow, Red, Yellow... | {
200000
} | conditional_block |
command_utils.py | """ | """
from django.core.management.base import CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
def get_mutually_exclusive_required_option(options, *selections):
"""
Validates that exactly one of the 2 given options is specified.
Returns the name of the found ... | Useful utilities for management commands. | random_line_split |
command_utils.py | """
Useful utilities for management commands.
"""
from django.core.management.base import CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
def get_mutually_exclusive_required_option(options, *selections):
"""
Validates that exactly one of the 2 given options is... |
def parse_course_keys(course_key_strings):
"""
Parses and returns a list of CourseKey objects from the given
list of course key strings.
"""
try:
return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings]
except InvalidKeyError as error:
rais... | """
Validates that option_1 is specified if dependent_option is specified.
"""
if options.get(dependent_option) and not options.get(depending_on_option):
raise CommandError(f'Option --{dependent_option} requires option --{depending_on_option}.') | identifier_body |
command_utils.py | """
Useful utilities for management commands.
"""
from django.core.management.base import CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
def get_mutually_exclusive_required_option(options, *selections):
"""
Validates that exactly one of the 2 given options is... | (course_key_strings):
"""
Parses and returns a list of CourseKey objects from the given
list of course key strings.
"""
try:
return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings]
except InvalidKeyError as error:
raise CommandError('Invalid ... | parse_course_keys | identifier_name |
command_utils.py | """
Useful utilities for management commands.
"""
from django.core.management.base import CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
def get_mutually_exclusive_required_option(options, *selections):
"""
Validates that exactly one of the 2 given options is... |
def parse_course_keys(course_key_strings):
"""
Parses and returns a list of CourseKey objects from the given
list of course key strings.
"""
try:
return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings]
except InvalidKeyError as error:
rais... | raise CommandError(f'Option --{dependent_option} requires option --{depending_on_option}.') | conditional_block |
main.js | (function () {
var canvas;
var canvasContext;
var scale;
var controlSet;
var keyCodeTouched = null;
var resizeBuffer = $('<canvas width="128" height="128">')[0];
var resizeBufferContext = resizeBuffer.getContext('2d');
disableSmoothing(resizeBufferContext);
RuneWizard.setDispla... |
$(window).load(function () {
RuneWizard.graphics = $('#graphics')[0];
canvas = $('canvas')[0];
$(window).resize();
$(document).keydown(function (event) {
RuneWizard.display.keyPressed(event.which);
});
$(document).keyup(function (event... | {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
} | identifier_body |
main.js | (function () {
var canvas;
var canvasContext;
var scale;
var controlSet;
var keyCodeTouched = null;
var resizeBuffer = $('<canvas width="128" height="128">')[0];
var resizeBufferContext = resizeBuffer.getContext('2d');
disableSmoothing(resizeBufferContext);
RuneWizard.setDispla... | });
function disableSmoothing(context) {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
}
$(window).load(function () {
RuneWizard.graphics = $('#graphics')[0];
canvas = $('canvas... | canvasContext.drawImage(resizeBuffer, 0, 0);
}
canvas.style.left = ($(window).width() - canvas.width) / 2 + 'px';
canvas.style.top = (availableHeight - canvas.height) / 2 + 'px'; | random_line_split |
main.js | (function () {
var canvas;
var canvasContext;
var scale;
var controlSet;
var keyCodeTouched = null;
var resizeBuffer = $('<canvas width="128" height="128">')[0];
var resizeBufferContext = resizeBuffer.getContext('2d');
disableSmoothing(resizeBufferContext);
RuneWizard.setDispla... | (context) {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
}
$(window).load(function () {
RuneWizard.graphics = $('#graphics')[0];
canvas = $('canvas')[0];
$(window).resize();
... | disableSmoothing | identifier_name |
main.js | (function () {
var canvas;
var canvasContext;
var scale;
var controlSet;
var keyCodeTouched = null;
var resizeBuffer = $('<canvas width="128" height="128">')[0];
var resizeBufferContext = resizeBuffer.getContext('2d');
disableSmoothing(resizeBufferContext);
RuneWizard.setDispla... |
if (newControlSet != controlSet) {
$('#' + controlSet + 'ControlSet').hide();
$('#' + newControlSet + 'ControlSet').show();
controlSet = newControlSet;
}
RuneWizard.display.run();
RuneWizard.display.paint(canvasContext);
... | {
newControlSet = 'disabled';
} | conditional_block |
MMM-MovieListings.js | refreshInterval: 1000 * 60 * 60 * 24, //Once a day
baseUrl: 'https://api.themoviedb.org/3/movie/now_playing',
animationSpeed: 2.5 * 1000,
pageChangeInterval: 30 * 1000
},
getStyles: function() {
return ['MMM-MovieListings.css'];
},
getTranslations: function() {
return {
en: "translat... | getDom: function() {
var wrapper = document.createElement('div')
var header = document.createElement('header');
header.innerHTML = this.config.header;
wrapper.appendChild(header);
// No movies fetched yet
if (!this.moviesToDisplay && !this.posterToDisplay) {
var loadingPlaceholder = docu... | random_line_split | |
MMM-MovieListings.js | refreshInterval: 1000 * 60 * 60 * 24, //Once a day
baseUrl: 'https://api.themoviedb.org/3/movie/now_playing',
animationSpeed: 2.5 * 1000,
pageChangeInterval: 30 * 1000
},
getStyles: function() {
return ['MMM-MovieListings.css'];
},
getTranslations: function() {
return {
en: "translat... |
// Add all details
detailsContainer.appendChild(detailsRatingContainer);
detailsContainer.appendChild(runtimeContent);
detailsContainer.appendChild(creditsContainer);
// Set up details => table
var detailsTable = document.createElement('table');
detailsTable.className = 'xsMarginTop';... | {
var genres = '';
for (var i = 0; i <= movie.genres.length -1; i++) {
genres += movie.genres[i].name;
if (i < movie.genres.length - 1) {
genres += ', ';
}
}
} | conditional_block |
sessions.py | # Rekall Memory Forensics
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 the License, or (at
# your option) any later v... | (self, hint, ttys):
for entity in ttys:
file_identity = None
session_identity = None
tty = entity["Struct/base"]
session = tty.t_session.deref()
vnode = session.s_ttyvp
if session:
session_identity = self.manager.identify(... | collect | identifier_name |
sessions.py | # Rekall Memory Forensics
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 the License, or (at
# your option) any later v... | yield definitions.Struct(base=vnode,
type="vnode")
file_identity = self.manager.identify({
"Struct/base": vnode})
# Yield just the stubs of the input and output ring buffers.
# DarwinClistParser will gr... | outputs = ["Terminal", "Struct/type=vnode", "Struct/type=clist",
"Buffer/purpose=terminal_input",
"Buffer/purpose=terminal_output"]
collect_args = dict(ttys="Struct/type is 'tty'")
def collect(self, hint, ttys):
for entity in ttys:
file_identity = None
... | identifier_body |
sessions.py | # Rekall Memory Forensics
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 the License, or (at
# your option) any later v... |
session_identity = entity.identity
if session.s_ttyp:
yield definitions.Struct(
base=session.s_ttyp,
type="tty")
if session.s_leader and session.s_leader.validate():
yield definitions.Struct(
... | session = entity["Struct/base"]
# Have to sanitize the usernames to prevent issues when comparing
# them later.
username = str(session.s_login).replace("\x00", "")
if username:
user_identity = self.manager.identify({
"User/username": u... | conditional_block |
sessions.py | # Rekall Memory Forensics
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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 the License, or (at
# your option) any later v... | definitions.Terminal(
session=session_identity,
file=file_identity)]
class DarwinSessionParser(common.DarwinEntityCollector):
"""Collects session entities from the memory objects."""
_name = "sessions"
outputs = ["Session",
... | yield [entity.identity, | random_line_split |
v1_server_address_by_client_cidr.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
@server_address.setter
def server_address(self, server_address):
"""Sets the server_address of this V1ServerAddressByClientCIDR.
Address of this server, suitable for a client that matches the above CIDR. This can be a hostname, hostname:port, IP or IP:port. # noqa: E501
:param serve... | """Gets the server_address of this V1ServerAddressByClientCIDR. # noqa: E501
Address of this server, suitable for a client that matches the above CIDR. This can be a hostname, hostname:port, IP or IP:port. # noqa: E501
:return: The server_address of this V1ServerAddressByClientCIDR. # noqa: E501
... | identifier_body |
v1_server_address_by_client_cidr.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | The CIDR with which clients can match their IP to figure out the server address that they should use. # noqa: E501
:param client_cidr: The client_cidr of this V1ServerAddressByClientCIDR. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and c... | def client_cidr(self, client_cidr):
"""Sets the client_cidr of this V1ServerAddressByClientCIDR.
| random_line_split |
v1_server_address_by_client_cidr.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... |
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are... | result[attr] = value | conditional_block |
v1_server_address_by_client_cidr.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | (self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ServerAddressByClientCIDR):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(o... | __eq__ | identifier_name |
setup.py | from __future__ import absolute_import
########################################################################
# File based on https://github.com/Blosc/bcolz
########################################################################
#
# License: BSD
# Created: October 5, 2015
# Author: Carst Vaartjes - cva... | from setuptools import setup, Extension, find_packages
from os.path import abspath
from sys import version_info as v
from setuptools.command.build_ext import build_ext as _build_ext
# Check this Python version is supported
if any([v < (2, 6), (3,) < v < (3, 5)]):
raise Exception("Unsupported Python version %d.%d.... | ########################################################################
import codecs
import os
| random_line_split |
setup.py | from __future__ import absolute_import
########################################################################
# File based on https://github.com/Blosc/bcolz
########################################################################
#
# License: BSD
# Created: October 5, 2015
# Author: Carst Vaartjes - cva... |
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include())
HERE = os.path.abspa... | raise Exception("Unsupported Python version %d.%d. Requires Python >= 2.7 "
"or >= 3.5." % v[:2]) | conditional_block |
setup.py | from __future__ import absolute_import
########################################################################
# File based on https://github.com/Blosc/bcolz
########################################################################
#
# License: BSD
# Created: October 5, 2015
# Author: Carst Vaartjes - cva... |
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f:
return f.read()
def get_version()... | _build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include()) | identifier_body |
setup.py | from __future__ import absolute_import
########################################################################
# File based on https://github.com/Blosc/bcolz
########################################################################
#
# License: BSD
# Created: October 5, 2015
# Author: Carst Vaartjes - cva... | (self):
_build_ext.finalize_options(self)
# Prevent numpy from thinking it is still in its setup process:
__builtins__.__NUMPY_SETUP__ = False
import numpy
self.include_dirs.append(numpy.get_include())
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""... | finalize_options | identifier_name |
mod.rs | mod parse;
use std::cmp::min;
#[derive(Debug)]
pub struct | {
name: String,
speed: u32,
fly_time: u32,
rest_time: u32
}
impl Reindeer {
fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer {
Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, rest_time: rest_time }
}
pub fn parse(input: &str) -> Reinde... | Reindeer | identifier_name |
mod.rs | mod parse;
use std::cmp::min;
| #[derive(Debug)]
pub struct Reindeer {
name: String,
speed: u32,
fly_time: u32,
rest_time: u32
}
impl Reindeer {
fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer {
Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, rest_time: rest_time }
}
... | random_line_split | |
mod.rs | mod parse;
use std::cmp::min;
#[derive(Debug)]
pub struct Reindeer {
name: String,
speed: u32,
fly_time: u32,
rest_time: u32
}
impl Reindeer {
fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer {
Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, r... |
}
#[cfg(test)]
mod tests {
use super::Reindeer;
#[test]
fn test_parse_reindeer() {
let reindeer = Reindeer::parse("Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.");
assert_eq!(reindeer.speed, 16);
assert_eq!(reindeer.fly_time, 11);
assert_eq!(re... | {
self.name.clone()
} | identifier_body |
mod.rs | mod parse;
use std::cmp::min;
#[derive(Debug)]
pub struct Reindeer {
name: String,
speed: u32,
fly_time: u32,
rest_time: u32
}
impl Reindeer {
fn new(name: &str, speed: u32, fly_time: u32, rest_time: u32) -> Reindeer {
Reindeer { name: name.to_string(), speed: speed, fly_time: fly_time, r... |
time_left -= self.fly_time + self.rest_time;
}
distance
}
pub fn name(&self) -> String {
self.name.clone()
}
}
#[cfg(test)]
mod tests {
use super::Reindeer;
#[test]
fn test_parse_reindeer() {
let reindeer = Reindeer::parse("Dancer can fly 16 km/s... | {
break;
} | conditional_block |
utils.py | import numpy as np
import shapely.affinity
import cv2
from collections import defaultdict
from shapely.geometry import MultiPolygon, Polygon
class Utils: | @staticmethod
def multi_polygon_to_pixel_mask(polygon, image_size):
mask = np.zeros(image_size, np.uint8)
int_coords = lambda x: np.array(x).round().astype(np.int32)
exteriors = [int_coords(poly.exterior.coords) for poly in polygon]
interiors = [int_coords(pi.coords) for poly in polygon for pi in po... | random_line_split | |
utils.py | import numpy as np
import shapely.affinity
import cv2
from collections import defaultdict
from shapely.geometry import MultiPolygon, Polygon
class Utils:
@staticmethod
def | (polygon, image_size):
mask = np.zeros(image_size, np.uint8)
int_coords = lambda x: np.array(x).round().astype(np.int32)
exteriors = [int_coords(poly.exterior.coords) for poly in polygon]
interiors = [int_coords(pi.coords) for poly in polygon for pi in poly.interiors]
cv2.fillPoly(mask, exteriors, 1... | multi_polygon_to_pixel_mask | identifier_name |
utils.py | import numpy as np
import shapely.affinity
import cv2
from collections import defaultdict
from shapely.geometry import MultiPolygon, Polygon
class Utils:
@staticmethod
def multi_polygon_to_pixel_mask(polygon, image_size):
|
@staticmethod
def pixel_mask_to_image(mask, r, g, b):
return np.stack([
np.multiply(mask, r),
np.multiply(mask, g),
np.multiply(mask, b)
]).transpose([1, 2, 0])
@staticmethod
def scale_multi_polygon(polygon, x_scale, y_scale):
return shapely.affinity.scale(polygon, xfact=x_sca... | mask = np.zeros(image_size, np.uint8)
int_coords = lambda x: np.array(x).round().astype(np.int32)
exteriors = [int_coords(poly.exterior.coords) for poly in polygon]
interiors = [int_coords(pi.coords) for poly in polygon for pi in poly.interiors]
cv2.fillPoly(mask, exteriors, 1)
cv2.fillPoly(mask, in... | identifier_body |
utils.py | import numpy as np
import shapely.affinity
import cv2
from collections import defaultdict
from shapely.geometry import MultiPolygon, Polygon
class Utils:
@staticmethod
def multi_polygon_to_pixel_mask(polygon, image_size):
mask = np.zeros(image_size, np.uint8)
int_coords = lambda x: np.array(x).round().asty... |
# approximating polygons might have created invalid ones, fix them
all_polygons = MultiPolygon(all_polygons)
if not all_polygons.is_valid:
all_polygons = all_polygons.buffer(0)
# Sometimes buffer() converts a simple Multipolygon to just a Polygon,
# need to keep it a Multi throughout
... | assert cnt.shape[1] == 1
poly = Polygon(
shell=cnt[:, 0, :],
holes=[c[:, 0, :] for c in cnt_children.get(idx, [])
if cv2.contourArea(c) >= min_area])
all_polygons.append(poly) | conditional_block |
prosemirror-state-tests.ts | import * as state from 'prosemirror-state';
import * as model from 'prosemirror-model';
import * as transform from 'prosemirror-transform';
let plugin: state.Plugin;
plugin = new state.Plugin({});
plugin = new state.Plugin({
props: {}
});
// Verify that Transaction (that extends Transform) has the correct return... | transaction = transaction.replace(0, 0);
transaction = transaction.replaceWith(0, 0, node);
transaction = transaction.insert(0, node);
transaction = transaction.lift(nodeRange, 0);
transaction = transaction.wrap(nodeRange, []);
transaction = transaction.setBlockType(0, 0, node.type);
transaction = transaction.setNodeMa... | transaction = transaction.deleteRange(0, 0);
transaction = transaction.delete(0, 0); | random_line_split |
Blockly.js | /**
* This file contains a Dojo AMD port of the Blockly library
* @author Chris Jackson
*/
define([
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/array",
"dojo/dom-geometry",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/layout/Acco... | if (this.blockly.blocks != null && this.blockly.blocks != "")
this.setBlocks(this.blockly.blocks);
// If a change listener is specified, add it
this.resize();
},
setBlocks: function (blocks) {
// Clear any exis... | // Load the design into the workspace | random_line_split |
forge.rs | use atom::header::AtomType;
use atom::types::{AtomSequence, UnknownAtomSequence};
use urid::{URID, URIDCache, URIDCacheMapping};
use std::slice;
use units::Unit;
use std::marker::PhantomData;
use atom::header::Atom;
use atom::into::ToAtom;
use std::mem;
pub trait Forger<'c, C: 'c> : Sized{
fn cache(&self) -> &'c ... |
impl<'c, C: URIDCache> Forge<'c, C> {
#[inline]
pub fn new(buffer: &'c mut [u8], cache: &'c C) -> Forge<'c, C> {
Forge {
buffer, cache, position: 0
}
}
#[inline]
pub fn begin_sequence<'a, U: Unit + 'c>(&'a mut self) -> ForgeSequence<'a, 'c, C, U, Self> where C: URIDCac... | {
let size = atom.get_total_size() as usize;
let data = atom as *const A as *const u8;
&mut *(forge.write_raw_padded(data, size) as *mut A)
} | identifier_body |
forge.rs | use atom::header::AtomType;
use atom::types::{AtomSequence, UnknownAtomSequence};
use urid::{URID, URIDCache, URIDCacheMapping};
use std::slice;
use units::Unit;
use std::marker::PhantomData;
use atom::header::Atom;
use atom::into::ToAtom;
use std::mem;
pub trait Forger<'c, C: 'c> : Sized{
fn cache(&self) -> &'c ... | <'b, U2: Unit + 'c>(&'b mut self, time: &U) -> ForgeSequence<'b, 'c, C, U2, Self>
where C: URIDCacheMapping<U2> + URIDCacheMapping<UnknownAtomSequence> + 'b
{
unsafe {
self.write_raw_padded(time as *const U as *const u8, mem::size_of::<U>());
}
ForgeSequence::new(self)
... | begin_sequence | identifier_name |
forge.rs | use atom::header::AtomType;
use atom::types::{AtomSequence, UnknownAtomSequence};
use urid::{URID, URIDCache, URIDCacheMapping};
use std::slice;
use units::Unit;
use std::marker::PhantomData;
use atom::header::Atom;
use atom::into::ToAtom;
use std::mem;
pub trait Forger<'c, C: 'c> : Sized{
fn cache(&self) -> &'c ... | pub struct ForgeSequence<'a, 'c, C: 'c, U: Unit, F: Forger<'c, C> + 'a> {
parent: &'a mut F,
atom: &'a mut Atom,
_unit_type: PhantomData<U>,
_cache_type: PhantomData<&'c C>
}
impl<'a, 'c, C: URIDCache + 'c, U: Unit + 'c, F: Forger<'c, C> + 'a> ForgeSequence<'a, 'c, C, U, F> {
#[inline]
fn new<'... | }
| random_line_split |
starter.py | #!/usr/bin/python
""" README
This script is deprecated. Please use https://github.com/device42/servicenow_device42_mapping
This script reads CIs from Servicenow and uploads them to Device42.
It has 2 modes:
1. Full migration - when the TIMEFRAME is set to 0
2. Synchronization - when the TIMEFRAME... |
snow.get_adapters()
snow.get_ips()
snow.upload_adapters()
sys.exit()
| snow.get_computers(table) | conditional_block |
starter.py | #!/usr/bin/python
""" README
This script is deprecated. Please use https://github.com/device42/servicenow_device42_mapping
This script reads CIs from Servicenow and uploads them to Device42.
It has 2 modes:
1. Full migration - when the TIMEFRAME is set to 0
2. Synchronization - when the TIMEFRAME... | USERNAME = 'admin'
PASSWORD = 'admin123'
BASE_URL = 'https://dev13852.service-now.com/api/now/table/'
LIMIT = 1000000 # number of CIs to retrieve from ServiceNow
HEADERS = {"Content-Type":"application/json","Accept":"application/json"}
TABLES = ['cmdb_ci_server' , 'cmdb_ci_computer', 'cmdb_ci_ap... | random_line_split | |
application.py | from flask import Flask
from flask import make_response
from flask import request
from flask import render_template
from flask import redirect
from flask import url_for
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
@app.route('/')
def index():
app.logger.info('index')
... |
else:
return render_template('login.html')
@app.route('/logout')
def logout():
app.logger.info('logout')
resp = make_response(redirect(url_for('index')))
resp.set_cookie('username', '', expires=0)
return resp
def validate_credentials(username, password):
return username == password
... | if validate_credentials(request.form['username'], request.form['password']):
resp = make_response(redirect(url_for('index')))
resp.set_cookie('username', request.form['username'])
return resp
else:
return render_template('login.html', error='Invalid username or p... | conditional_block |
application.py | from flask import Flask
from flask import make_response
from flask import request
from flask import render_template
from flask import redirect
from flask import url_for
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
@app.route('/')
def index():
app.logger.info('index')
... |
def validate_credentials(username, password):
return username == password
if __name__ == '__main__':
handler = RotatingFileHandler('todo.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
app.run()
| app.logger.info('logout')
resp = make_response(redirect(url_for('index')))
resp.set_cookie('username', '', expires=0)
return resp | identifier_body |
application.py | from flask import Flask | from flask import make_response
from flask import request
from flask import render_template
from flask import redirect
from flask import url_for
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
@app.route('/')
def index():
app.logger.info('index')
username = request.cooki... | random_line_split | |
application.py | from flask import Flask
from flask import make_response
from flask import request
from flask import render_template
from flask import redirect
from flask import url_for
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
@app.route('/')
def | ():
app.logger.info('index')
username = request.cookies.get('username')
if (username == None):
return redirect(url_for('login'))
else:
return render_template('index.html', username=username)
@app.route('/login', methods=['GET','POST'])
def login():
app.logger.info('login')
if re... | index | identifier_name |
auth-service.js | 'use strict';
const request = require('request');
const EventEmitter = require('events').EventEmitter;
class AuthService extends EventEmitter {
constructor(appId, appSecret, options) {
super();
this._appId = appId;
this._appSecret = appSecret;
options = options |... |
callback(null, body);
});
}
_setNewToken(err, data, callback) {
this._renewingToken = false;
if (err) {
this.emit('token', err);
return callback(err);
}
const response = JSON.parse(data);
thi... | {
return callback(new Error(`Received error ${response.statusCode}: ${response.statusMessage}.`));
} | conditional_block |
auth-service.js | 'use strict';
const request = require('request');
const EventEmitter = require('events').EventEmitter;
class AuthService extends EventEmitter {
constructor(appId, appSecret, options) {
super();
this._appId = appId;
this._appSecret = appSecret;
options = options |... | (callback) {
const content = {
client_id: this._appId,
client_secret: this._appSecret,
grant_type: 'client_credentials',
scope: this._scope
};
request.post(this._oAuthUrl, {
form: content
}, (err, response, body) => {
... | _renewToken | identifier_name |
auth-service.js | 'use strict';
const request = require('request');
const EventEmitter = require('events').EventEmitter;
class AuthService extends EventEmitter {
constructor(appId, appSecret, options) {
super();
this._appId = appId;
this._appSecret = appSecret;
options = options |... | this._renewingToken = true;
this._renewToken((err, data) => {
this._setNewToken(err, data, callback);
});
}
}
}
_renewToken(callback) {
const content = {
client_id: this._appId,
client_se... | } else {
if (this._renewingToken) {
this.once('token', callback);
} else { | random_line_split |
lib.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | clippy::redundant_field_names,
clippy::too_many_arguments
)]
// Default isn't as big a deal as people seem to think it is.
#![allow(clippy::new_without_default, clippy::new_ret_no_self)]
// Arc<Mutex> can be more clear than needing to grok Orderings:
#![allow(clippy::mutex_atomic)]
use std::sync::Arc;
use parking... | // It is often more clear to show that nothing is being moved.
#![allow(clippy::match_ref_pats)]
// Subjective style.
#![allow(
clippy::len_without_is_empty, | random_line_split |
lib.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... |
///
/// Mark this latch triggered, releasing all threads that are waiting for it to trigger.
///
/// All calls to trigger after the first one are noops.
///
pub fn trigger(&self) {
// To trigger the latch, we drop the Sender.
self.sender.lock().take();
}
///
/// Wait for another thread to t... | {
let (sender, receiver) = watch::channel(());
AsyncLatch {
sender: Arc::new(Mutex::new(Some(sender))),
receiver,
}
} | identifier_body |
lib.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | (&self) {
// To see whether the latch is triggered, we clone the receiver, and then wait for our clone to
// return None, indicating that the Sender has been dropped.
let mut receiver = self.receiver.clone();
while receiver.recv().await.is_some() {}
}
///
/// Return true if the latch has been tri... | triggered | identifier_name |
featuresDuck.ts | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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... | .ofType(CONNECTION_SUCCESS)
.mergeMap(() => {
return new Promise(async (resolve, reject) => {
try {
const supportsMultiDb = await bolt.hasMultiDbSupport()
const res = await bolt.routedReadTransaction(
'CALL dbms.procedures YIELD name',
{},
{
... | export const featuresDiscoveryEpic = (action$: any, store: any) => {
return action$ | random_line_split |
app.js | let express = require('express');
let path = require('path');
let logger = require('morgan');
let bodyParser = require('body-parser');
let index = require('./routes/index');
let semanticui = require('./routes/semanticui');
let foundation = require('./routes/foundation');
let test = require('./routes/test-post');
let he... |
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app; | // set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {}; | random_line_split |
index.ts | /** | * 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
*/
import { strings } from '@angular-devkit/core';
import {
Rule,
Tree,
apply,
applyTemplates,
chain,
filter,
mergeWith,
... | * @license | random_line_split |
index.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
*/
import { strings } from '@angular-devkit/core';
import {
Rule,
Tree,
apply,
applyTemplates,
chain,
filter... |
const parsedPath = parseName(options.path, options.name);
options.name = parsedPath.name;
options.path = parsedPath.path;
const templateSource = apply(url('./files'), [
options.skipTests ? filter((path) => !path.endsWith('.spec.ts.template')) : noop(),
applyTemplates({
...strings,... | {
options.path = await createDefaultPath(host, options.project as string);
} | conditional_block |
notify.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.actions import BaseNotify
from c7n import utils
from c7n.resolver import ValuesFrom
from c7n_gcp.provider import resources as gcp_resources
class Notify(BaseNotify):
"""
:example:
.. code-block:: yaml
poli... |
@classmethod
def register_resource(cls, registry, resource_class):
resource_class.action_registry.register('notify', Notify)
gcp_resources.subscribe(Notify.register_resource)
| """Publish message to a GCP pub/sub topic
"""
return client.execute_command('publish', {
'topic': self.data['transport']['topic'],
'body': {
'messages': {
'data': self.pack(message)
}
}
}) | identifier_body |
notify.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.actions import BaseNotify
from c7n import utils
from c7n.resolver import ValuesFrom
from c7n_gcp.provider import resources as gcp_resources
class Notify(BaseNotify):
"""
:example:
.. code-block:: yaml
poli... |
# Methods to handle GCP Pub Sub topic publishing
def publish_message(self, message, client):
"""Publish message to a GCP pub/sub topic
"""
return client.execute_command('publish', {
'topic': self.data['transport']['topic'],
'body': {
'messages':... | message['resources'] = batch
self.publish_message(message, client) | conditional_block |
notify.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.actions import BaseNotify
from c7n import utils
from c7n.resolver import ValuesFrom
from c7n_gcp.provider import resources as gcp_resources
class Notify(BaseNotify):
"""
:example:
.. code-block:: yaml
poli... | (self, message, client):
"""Publish message to a GCP pub/sub topic
"""
return client.execute_command('publish', {
'topic': self.data['transport']['topic'],
'body': {
'messages': {
'data': self.pack(message)
}
... | publish_message | identifier_name |
notify.py | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from c7n.actions import BaseNotify
from c7n import utils
from c7n.resolver import ValuesFrom
from c7n_gcp.provider import resources as gcp_resources
class Notify(BaseNotify):
"""
:example:
.. code-block:: yaml
poli... | }}],
},
}
}
schema_alias = True
permissions = ('pubsub.topics.publish',)
def process(self, resources, event=None):
session = utils.local_session(self.manager.session_factory)
client = session.client('pubsub', 'v1', 'projects.topics')
pro... | 'topic': {'type': 'string'},
'type': {'enum': ['pubsub']}, | random_line_split |
Ext.ux.upload.LogPanel.js | /*
** Ext.ux.upload.LogPanel.js for Ext.ux.upload
**
** Made by Gary van Woerkens
** Contact <gary@chewam.com>
**
** Started on Fri Jun 4 19:01:47 2010 Gary van Woerkens
** Last update Mon Jun 21 13:48:39 2010 Gary van Woerkens
*/
Ext.ns('Ext.ux.upload');
/**
* @class Ext.ux.upload.LogPanel
* @extends Ext.Panel
... | this.on({added:this.bindContainer});
}
/**
*
*/
,bindContainer:function(logpanel, ctn, index) {
Ext.apply(ctn, {
addProgress:this.addProgress.createDelegate(this)
,updateProgress:this.updateProgress.createDelegate(this)
,setStatus:this.setStatus.createDelegate(this)
});
}
... | });
Ext.ux.upload.LogPanel.superclass.initComponent.call(this);
| random_line_split |
ok.py | """
Source: https://github.com/txt/mase/blob/master/src/ok.md
# Unit tests in Python
Python has some great unit testing tools. The one
shown below is a "less-is-more" approach and is
based on [Kent Beck video on how to write a test engine in just a
few lines of code](https://www.youtube.com/watch?v=nIonZ6-4nuU).
Fo... | except Exception,e:
unittest.fails += 1
i.report(test)
def report(i,test):
import traceback
print traceback.format_exc()
print unittest.score(),':',test.__name__ | def __init__(i,test):
unittest.tries += 1
try:
test() | random_line_split |
ok.py | """
Source: https://github.com/txt/mase/blob/master/src/ok.md
# Unit tests in Python
Python has some great unit testing tools. The one
shown below is a "less-is-more" approach and is
based on [Kent Beck video on how to write a test engine in just a
few lines of code](https://www.youtube.com/watch?v=nIonZ6-4nuU).
Fo... | (i,test):
unittest.tries += 1
try:
test()
except Exception,e:
unittest.fails += 1
i.report(test)
def report(i,test):
import traceback
print traceback.format_exc()
print unittest.score(),':',test.__name__ | __init__ | identifier_name |
ok.py | """
Source: https://github.com/txt/mase/blob/master/src/ok.md
# Unit tests in Python
Python has some great unit testing tools. The one
shown below is a "less-is-more" approach and is
based on [Kent Beck video on how to write a test engine in just a
few lines of code](https://www.youtube.com/watch?v=nIonZ6-4nuU).
Fo... |
return one
class unittest:
tries = fails = 0 # tracks the record so far
@staticmethod
def score():
t = unittest.tries
f = unittest.fails
return "# TRIES= %s FAIL= %s %%PASS = %s%%" % (
t,f,int(round(t*100/(t+f+0.001))))
def __init__(i,test):
unittest.tries += 1
try:
test()... | unittest(one) | conditional_block |
ok.py | """
Source: https://github.com/txt/mase/blob/master/src/ok.md
# Unit tests in Python
Python has some great unit testing tools. The one
shown below is a "less-is-more" approach and is
based on [Kent Beck video on how to write a test engine in just a
few lines of code](https://www.youtube.com/watch?v=nIonZ6-4nuU).
Fo... |
class unittest:
tries = fails = 0 # tracks the record so far
@staticmethod
def score():
t = unittest.tries
f = unittest.fails
return "# TRIES= %s FAIL= %s %%PASS = %s%%" % (
t,f,int(round(t*100/(t+f+0.001))))
def __init__(i,test):
unittest.tries += 1
try:
test()
except E... | print "### ",lst[0].__name__
for one in lst: unittest(one)
return one | identifier_body |
jquery.inputmask.phone.extensions.js | /*!
* jquery.inputmask.phone.extensions.js
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2014 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.29
*/
!function(factory) {
"function" == typeof define && define.amd ? define([ ... | }), $.fn.inputmask;
}); | return (processedValue.indexOf("32") > 1 || -1 == processedValue.indexOf("32")) && (processedValue = "32" + processedValue),
processedValue;
}
} | random_line_split |
base.py | from math import sqrt
from datetime import datetime
from dexter.models import db, Document, Person
from sqlalchemy.sql import func
from sqlalchemy.orm import joinedload
class BaseAnalyser(object):
"""
Base for analyser objects that handles a collection of
documents to analyse, based on either document i... | (self):
"""
The date range is the range of publication dates for the given
documents.
"""
if not self.start_date or not self.end_date:
if self.doc_ids is None:
raise ValueError("Need either doc_ids, or both start_date and end_date")
row = ... | _calculate_date_range | identifier_name |
base.py | from math import sqrt
from datetime import datetime
from dexter.models import db, Document, Person
from sqlalchemy.sql import func
from sqlalchemy.orm import joinedload
class BaseAnalyser(object):
"""
Base for analyser objects that handles a collection of
documents to analyse, based on either document i... | if std == 0:
return x - avg
else:
return (x - avg) / std
else:
# fold it in
avg = avg * decay + (1.0-decay) * x
sq_avg = sq_avg * decay + (1.0-decay) * (x ** 2) | sq_avg = float(x ** 2)
elif i == last:
# basic std deviation
std = sqrt(sq_avg - avg ** 2) | random_line_split |
base.py | from math import sqrt
from datetime import datetime
from dexter.models import db, Document, Person
from sqlalchemy.sql import func
from sqlalchemy.orm import joinedload
class BaseAnalyser(object):
"""
Base for analyser objects that handles a collection of
documents to analyse, based on either document i... | self.days = max((self.end_date - self.start_date).days, 1)
def _fetch_doc_ids(self):
if self.doc_ids is None:
rows = db.session.query(Document.id)\
.filter(Document.published_at >= self.start_date.strftime('%Y-%m-%d 00:00:00'))\
.filter(Document.publishe... | """
The date range is the range of publication dates for the given
documents.
"""
if not self.start_date or not self.end_date:
if self.doc_ids is None:
raise ValueError("Need either doc_ids, or both start_date and end_date")
row = db.session.query... | identifier_body |
base.py | from math import sqrt
from datetime import datetime
from dexter.models import db, Document, Person
from sqlalchemy.sql import func
from sqlalchemy.orm import joinedload
class BaseAnalyser(object):
"""
Base for analyser objects that handles a collection of
documents to analyse, based on either document i... |
def _lookup_people(self, ids):
query = Person.query \
.options(joinedload(Person.affiliation)) \
.filter(Person.id.in_(ids))
return dict([p.id, p] for p in query.all())
def moving_weighted_avg_zscore(obs, decay=0.8):
"""
Calculate a moving-weighted average z-scor... | rows = db.session.query(Document.id)\
.filter(Document.published_at >= self.start_date.strftime('%Y-%m-%d 00:00:00'))\
.filter(Document.published_at <= self.end_date.strftime('%Y-%m-%d 23:59:59'))\
.all()
self.doc_ids = [r[0] for r in rows] | conditional_block |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe... | (self: Box<WorkerEventHandler>) {
let this = *self;
Worker::dispatch_simple_error(this.addr);
}
}
pub struct WorkerErrorHandler {
addr: TrustedWorkerAddress,
msg: DOMString,
file_name: DOMString,
line_num: u32,
col_num: u32,
}
impl WorkerErrorHandler {
pub fn new(addr: Trus... | handler | identifier_name |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe... | // https://www.whatwg.org/html/#dom-worker
pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
// Step 2-4.
let worker_url = match UrlParser::new().base_url(&global.get_url()).parse(&script_url) {
Ok(url) => url,
Err(_) => return Err(S... | reflect_dom_object(box Worker::new_inherited(global, sender),
global,
WorkerBinding::Wrap)
}
| random_line_split |
worker.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerBinding;
use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMe... |
}
| {
let this = *self;
Worker::handle_error_message(this.addr, this.msg, this.file_name, this.line_num, this.col_num);
} | identifier_body |
file.rs | use nix::unistd;
use std::os::unix::io::RawFd;
#[derive(Debug)]
pub struct Fd {
pub raw_fd: RawFd,
is_closed: bool,
}
impl Fd {
/// Wraps an existing `fd` in our file descriptor object
pub fn new(fd: RawFd) -> Fd |
/// Duplicates the file descriptor
pub fn dup(fd: RawFd) -> Result<Fd, String> {
let new_fd = try!(unistd::dup(fd).or(Err(format!("{}: bad file descriptor", fd))));
Ok(Fd::new(new_fd))
}
pub fn close(&mut self) {
if self.is_closed {
return;
}
unist... | {
Fd {
raw_fd: fd,
is_closed: false,
}
} | identifier_body |
file.rs | use nix::unistd;
use std::os::unix::io::RawFd;
#[derive(Debug)]
pub struct Fd {
pub raw_fd: RawFd,
is_closed: bool,
}
impl Fd {
/// Wraps an existing `fd` in our file descriptor object
pub fn new(fd: RawFd) -> Fd {
Fd {
raw_fd: fd,
is_closed: false,
}
} | }
pub fn close(&mut self) {
if self.is_closed {
return;
}
unistd::close(self.raw_fd).unwrap();
self.is_closed = true;
}
}
impl Drop for Fd {
fn drop(&mut self) {
// Don't automatically drop any of the default file descriptors
if self.raw_fd ... |
/// Duplicates the file descriptor
pub fn dup(fd: RawFd) -> Result<Fd, String> {
let new_fd = try!(unistd::dup(fd).or(Err(format!("{}: bad file descriptor", fd))));
Ok(Fd::new(new_fd)) | random_line_split |
file.rs | use nix::unistd;
use std::os::unix::io::RawFd;
#[derive(Debug)]
pub struct Fd {
pub raw_fd: RawFd,
is_closed: bool,
}
impl Fd {
/// Wraps an existing `fd` in our file descriptor object
pub fn new(fd: RawFd) -> Fd {
Fd {
raw_fd: fd,
is_closed: false,
}
}
... | (&mut self) {
if self.is_closed {
return;
}
unistd::close(self.raw_fd).unwrap();
self.is_closed = true;
}
}
impl Drop for Fd {
fn drop(&mut self) {
// Don't automatically drop any of the default file descriptors
if self.raw_fd > 2 && !self.is_closed ... | close | identifier_name |
file.rs | use nix::unistd;
use std::os::unix::io::RawFd;
#[derive(Debug)]
pub struct Fd {
pub raw_fd: RawFd,
is_closed: bool,
}
impl Fd {
/// Wraps an existing `fd` in our file descriptor object
pub fn new(fd: RawFd) -> Fd {
Fd {
raw_fd: fd,
is_closed: false,
}
}
... |
unistd::close(self.raw_fd).unwrap();
self.is_closed = true;
}
}
impl Drop for Fd {
fn drop(&mut self) {
// Don't automatically drop any of the default file descriptors
if self.raw_fd > 2 && !self.is_closed {
self.close();
}
}
}
| {
return;
} | conditional_block |
pipe.rs | WaitForSingleObject in tandem with CancelIo
// to figure out if we should indeed get the result.
let ms = if deadline == 0 {
libc::INFINITE as u64
} else {
let now = timer::now();
if deadline < now {0} else {deadline - now}
};
let ret = unsafe {
c::WaitForMultipleObj... | {
if self.write.is_none() {
self.write = Some(try!(Event::new(true, false)));
}
let mut offset = 0;
let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() };
overlapped.hEvent = self.write.as_ref().unwrap().handle();
while offset < buf.len() {
... | identifier_body | |
pipe.rs | ,
write_closed: atomic::AtomicBool,
}
impl Inner {
fn new(handle: libc::HANDLE) -> Inner {
Inner {
handle: handle,
lock: unsafe { mutex::NativeMutex::new() },
read_closed: atomic::AtomicBool::new(false),
write_closed: atomic::AtomicBool::new(false),
... |
pub fn handle(&self) -> libc::HANDLE { self.inner.handle }
fn read_closed(&self) -> bool {
self.inner.read_closed.load(atomic::SeqCst)
}
fn write_closed(&self) -> bool {
self.inner.write_closed.load(atomic::SeqCst)
}
fn cancel_io(&self) -> IoResult<()> {
match unsafe ... | }
}
}
} | random_line_split |
pipe.rs | (libc::HANDLE);
impl Event {
fn new(manual_reset: bool, initial_state: bool) -> IoResult<Event> {
let event = unsafe {
libc::CreateEventW(ptr::null_mut(),
manual_reset as libc::BOOL,
initial_state as libc::BOOL,
... | Event | identifier_name | |
pipe.rs | ,
write_closed: atomic::AtomicBool,
}
impl Inner {
fn new(handle: libc::HANDLE) -> Inner {
Inner {
handle: handle,
lock: unsafe { mutex::NativeMutex::new() },
read_closed: atomic::AtomicBool::new(false),
write_closed: atomic::AtomicBool::new(false),
... |
// Issue a nonblocking requests, succeeding quickly if it happened to
// succeed.
let ret = unsafe {
libc::ReadFile(self.handle(),
buf.as_ptr() as libc::LPVOID,
buf.len() as libc::DWORD,
&mut bytes_rea... | {
return Err(eof())
} | conditional_block |
index.d.ts | // Type definitions for node-sql-parser 1.0
// Project: https://github.com/taozhi8833998/node-sql-parser#readme
// Definitions by: taozhi8833998 <https://github.com/taozhi8833998>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export interface With {
name: string;
stm... | {
constructor();
parse(sql: string): TableColumnAst;
astify(sql: string): AST[] | AST;
sqlify(ast: AST[] | AST): string;
whiteListCheck(sql: string, whiteList: string[], type?: WhilteListCheckMode): Error | undefined;
tableList(sql: string): string[];
columnList(sql: string): string[];
}
| Parser | identifier_name |
index.d.ts | // Type definitions for node-sql-parser 1.0
// Project: https://github.com/taozhi8833998/node-sql-parser#readme
// Definitions by: taozhi8833998 <https://github.com/taozhi8833998>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
export interface With {
name: string;
stm... | type: 'delete';
tables: any;
from: Array<From | Dual>;
where: any;
}
export type AST = Select | Insert_Replace | Update | Delete;
export class Parser {
constructor();
parse(sql: string): TableColumnAst;
astify(sql: string): AST[] | AST;
sqlify(ast: AST[] | AST): string;
whiteListCheck(sql: string... | }
export interface Delete { | random_line_split |
programs.ts | import type {
EpisodeCounts,
IDBStoreUpgrade,
ProgramEpisodeCounts,
ProgramsStore,
ProgramsStoreObject,
TVManagerDB
} from "stores";
import type {
ModelType,
PersistedProgram
} from "models";
import type { IDBPDatabase } from "idb";
const upgradeTo: IDBStoreUpgrade<TVManagerDB>[] = [
// Version 1
(db: IDBPDa... | expectedCount
}: ProgramEpisodeCounts = series.reduce((counts: ProgramEpisodeCounts, seriesCounts: EpisodeCounts): ProgramEpisodeCounts => {
counts.seriesCount++;
counts.episodeCount += seriesCounts.episodeCount;
counts.watchedCount += seriesCounts.watchedCount;
... | {
const tx = db.transaction(["programs", "series", "episodes"]),
txProgramsStore = tx.objectStore("programs"),
txSeriesStore = tx.objectStore("series"),
txEpisodesStore = tx.objectStore("episodes"),
programs: PersistedProgram[] = await Promise.all((await txProgramsStore.index("name").getAll... | identifier_body |
programs.ts | import type {
EpisodeCounts,
IDBStoreUpgrade,
ProgramEpisodeCounts,
ProgramsStore,
ProgramsStoreObject,
TVManagerDB
} from "stores";
import type {
ModelType,
PersistedProgram
} from "models";
import type { IDBPDatabase } from "idb";
const upgradeTo: IDBStoreUpgrade<TVManagerDB>[] = [
// Version 1
(db: IDBPDa... | (id): Promise<PersistedProgram | undefined> {
const { id: ProgramID, name: Name } = await db.get("programs", id) as ProgramsStoreObject;
return {
ProgramID,
Name
};
},
async count(): Promise<number> {
return db.count("programs");
},
async removeAll(): Promise<void> {
return db.clear("p... | find | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.