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 |
|---|---|---|---|---|
data.py | digest())
def Bits2Target(bits):
return struct.unpack('<L', bits[:3] + b'\0')[0] * 2**(8*(bits[3] - 3))
class ChecksummedType(pack.Type):
def __init__(self, inner, checksum_func=lambda data: hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]):
self.inner = inner
self.checksum_func = ch... |
res = {}
for chain_id in chain_ids:
pos = (1103515245 * chain_id + 1103515245 * 12345 + 12345) % size
if pos in res:
break
res[pos] = chain_id
else:
return res, size
raise AssertionError()
# merkle trees
merkle_record_type = ... | continue | conditional_block |
data.py | digest())
def Bits2Target(bits):
return struct.unpack('<L', bits[:3] + b'\0')[0] * 2**(8*(bits[3] - 3))
class ChecksummedType(pack.Type):
def __init__(self, inner, checksum_func=lambda data: hashlib.sha256(hashlib.sha256(data).digest()).digest()[:4]):
self.inner = inner
self.checksum_func = ch... |
address_type = pack.ComposedType([
('services', pack.IntType(64)),
('address', pack.IPV6AddressType()),
('port', pack.IntType(16, 'big')),
])
tx_type = pack.ComposedType([
('version', pack.IntType(32)),
('tx_ins', pack.ListType(pack.ComposedType([
('previous_output', pack.PossiblyNoneType... | return self._inner.write(file, item.bits) | identifier_body |
elastic.py | .JSONSerializer):
"""Customize the JSON serializer used in Elastic"""
def default(self, value):
"""Convert mongo.ObjectId."""
if isinstance(value, ObjectId):
return str(value)
return super(ElasticJSONSerializer, self).default(value)
class ElasticCursor(object):
"""Searc... |
elif schema['type'] == 'string' and schema.get('unique'):
return {'type': 'string', 'index': 'not_analyzed'}
def create_index(self, index=None):
if index is None:
index = self.index
try:
get_indices(self.es).create(self.index)
except elasticsearc... | return {'type': 'date'} | conditional_block |
elastic.py | .JSONSerializer):
"""Customize the JSON serializer used in Elastic"""
def default(self, value):
"""Convert mongo.ObjectId."""
if isinstance(value, ObjectId):
return str(value)
return super(ElasticJSONSerializer, self).default(value)
class ElasticCursor(object):
"""Searc... | try:
return self.es.delete(id=lookup.get('_id'), refresh=True, **args)
except elasticsearch.NotFoundError:
return
else:
query = {'query': {'match_all': {}}}
return self.es.delete_by_query(body=query, **args)
def is_empty(self, ... | def remove(self, resource, lookup=None):
args = self._es_args(resource)
if lookup: | random_line_split |
elastic.py | def extra(self, response):
"""Add extra info to response."""
if 'facets' in self.hits:
response['_facets'] = self.hits['facets']
if 'aggregations' in self.hits:
response['_aggregations'] = self.hits['aggregations']
def set_filters(query, base_filters):
"""Put to... | _default_sort | identifier_name | |
elastic.py | .JSONSerializer):
"""Customize the JSON serializer used in Elastic"""
def default(self, value):
"""Convert mongo.ObjectId."""
if isinstance(value, ObjectId):
return str(value)
return super(ElasticJSONSerializer, self).default(value)
class ElasticCursor(object):
"""Searc... |
def update(self, resource, id_, updates):
args = self._es_args(resource, refresh=True)
return self.es.update(id=id_, body={'doc': updates}, **args)
def replace(self, resource, id_, document):
args = self._es_args(resource, refresh=True)
return self.es.index(body=document, id=i... | ids = []
kwargs.update(self._es_args(resource))
for doc in doc_or_docs:
doc.update(self.es.index(body=doc, id=doc.get('_id'), **kwargs))
ids.append(doc['_id'])
get_indices(self.es).refresh(self.index)
return ids | identifier_body |
jquery.ibutton.js | $([$input[0], $container[0]]).unbind(".iButton");
$(document).unbind(".iButton_" + id);
// move the checkbox to it's original location
$container.after($input).remove();
// kill the reference
$.data($input[0], "iButton", null);
// run callback
if( $.isFunction(options.destroy) ) options.destroy.ap... | {
// disable text selection in IE, other browsers are controlled via CSS
$container.find("*").andSelf().attr("unselectable", "on");
// IE needs to register to the "click" event to make changes immediately (the change event only occurs on blur)
$input.bind("click.iButton", function (){ $input.triggerHandler(... | conditional_block | |
jquery.ibutton.js | else {
result = r;
// since we're a non-jQuery item, just cancel processing further items
return false;
}
// keep adding jQuery objects to the results
} else if( !!r && !!r.jquery ){
result = result.add(r);
}
});
// return either the results (which could be a jQ... | $container[toggle ? "addClass" : "removeClass"](options.classDisabled);
// run callback
if( $.isFunction(options.disable) ) options.disable.apply(self, [disabled, $input, options]);
};
// repaint the button
this.repaint = function (){
positionHandle();
};
// this will destroy the iButton sty... | $input.attr("disabled", toggle);
// set the diabled styles | random_line_split |
helpers.js | Text.substring(0, lastEltText.length - 1);
coloredParts[coloredParts.length - 1] = new types.ColoredPart(lastEltText,
coloredParts[coloredParts.length-1].location);
}
return coloredParts;
}
// listRef for locationList.
var getLocation = function(pos) {
var locs = locatio... | {
return types.jsObject('array', x);
} | conditional_block | |
helpers.js |
var result = formatStr.replace(pattern, f);
if (buffer.length > 0) {
throwFormatError();
}
return result;
};
// forEachK: CPS( array CPS(array -> void) (error -> void) -> void )
// Iterates through an array and applies f to each element using CPS
// If an error is thrown, it catches the error and call... | {
if (s == "~~") {
return "~";
} else if (s == '~n' || s == '~%') {
return "\n";
} else if (s == '~s' || s == "~S") {
if (buffer.length == 0) {
throwFormatError();
}
return types.toWrittenString(buffer.shift());
} else if (s == '~a' || s == "~A") {
if (buffer.length == 0) {
... | identifier_body | |
helpers.js | (s) {
if (s == "~~") {
return "~";
} else if (s == '~n' || s == '~%') {
return "\n";
} else if (s == '~s' || s == "~S") {
if (buffer.length == 0) {
throwFormatError();
}
return types.toWrittenString(buffer.shift());
} else if (s == '~a' || s == "~A") {
if (buffer.length == 0) {
... | f | identifier_name | |
helpers.js | raise( types.incompleteExn(types.exnFailContract,
helpers.format(errorFormatStr, [details.functionName, details.typeName , details.actualValue]),
[]));
}
};
var throwColoredCheckError = function(aState, details, pos, args){
var positionStack =
state.captureCurrentContinuationMar... | return result;
} else {
return x;
} | random_line_split | |
inheritance.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/. */
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{Deri... |
}
}
| {
None
} | conditional_block |
inheritance.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/. */
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{Deri... |
}
| {
if self.is::<T>() {
Some(unsafe { mem::transmute(self) })
} else {
None
}
} | identifier_body |
inheritance.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/. */
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{Deri... | <T>(&self) -> Option<&T>
where T: DerivedFrom<Self>
{
if self.is::<T>() {
Some(unsafe { mem::transmute(self) })
} else {
None
}
}
}
| downcast | identifier_name |
inheritance.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 |
//! The `Castable` trait.
pub use dom::bindings::codegen::InheritTypes::*;
use dom::bindings::conversions::{DerivedFrom, IDLInterface};
use dom::bindings::conversions::get_dom_class;
use dom::bindings::reflector::DomObject;
use std::mem;
/// A trait to hold the cast functions of IDL interfaces that either derive
//... | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
__init__.py | """
SMQTK Web Applications
"""
import inspect
import logging
import os
import flask
import smqtk.utils
from smqtk.utils import plugin
class SmqtkWebApp (flask.Flask, smqtk.utils.Configurable, plugin.Pluggable):
"""
Base class for SMQTK web applications
"""
@classmethod
def impl_directory(cls):... | Within a module, we first look for a helper variable by the name
``APPLICATION_CLASS``, which can either be a single class object or
an iterable of class objects, to be exported. If the variable is set to
None, we skip that module and do not import anything. If the variable is not
present, we look f... | random_line_split | |
__init__.py | """
SMQTK Web Applications
"""
import inspect
import logging
import os
import flask
import smqtk.utils
from smqtk.utils import plugin
class SmqtkWebApp (flask.Flask, smqtk.utils.Configurable, plugin.Pluggable):
"""
Base class for SMQTK web applications
"""
@classmethod
def impl_directory(cls):... | :rtype: dict[str, type]
"""
import os
from smqtk.utils.plugin import get_plugins
this_dir = os.path.abspath(os.path.dirname(__file__))
env_var = "APPLICATION_PATH"
helper_var = "APPLICATION_CLASS"
return get_plugins(__name__, this_dir, env_var, helper_var, SmqtkWebApp,
... | """
Discover and return SmqtkWebApp implementation classes found in the plugin
directory. Keys in the returned map are the names of the discovered classes
and the paired values are the actual class type objects.
We look for modules (directories or files) that start with and alphanumeric
character (... | identifier_body |
__init__.py | """
SMQTK Web Applications
"""
import inspect
import logging
import os
import flask
import smqtk.utils
from smqtk.utils import plugin
class SmqtkWebApp (flask.Flask, smqtk.utils.Configurable, plugin.Pluggable):
"""
Base class for SMQTK web applications
"""
@classmethod
def impl_directory(cls):... | (reload_modules=False):
"""
Discover and return SmqtkWebApp implementation classes found in the plugin
directory. Keys in the returned map are the names of the discovered classes
and the paired values are the actual class type objects.
We look for modules (directories or files) that start with and ... | get_web_applications | identifier_name |
__init__.py | """
SMQTK Web Applications
"""
import inspect
import logging
import os
import flask
import smqtk.utils
from smqtk.utils import plugin
class SmqtkWebApp (flask.Flask, smqtk.utils.Configurable, plugin.Pluggable):
"""
Base class for SMQTK web applications
"""
@classmethod
def impl_directory(cls):... |
#
# Security
#
self.secret_key = self.config['SECRET_KEY']
def get_config(self):
return self.json_config
@property
def log(self):
return logging.getLogger('.'.join((self.__module__,
self.__class__.__name__)))
... | self.config[k] = self.json_config['flask_app'][k] | conditional_block |
AT-RoundCorners.py | #FLM: AT ChrisCorner
"""Round selected corners:
RADIUS is a Point instance that represents the x and y radius of the corner
HANDLELENGTH is a number between 0. and 1. that determines how long the
bezier handles should be, affecting the steepness of the curve
"""
import math
def getContourRange(nid,g):
cID = g.... |
def normalizeVector(p):
m = getMagnitude(p);
if m != 0:
return p*(1/m)
else:
return Point(0,0)
def getMagnitude(p):
return math.sqrt(p.x*p.x + p.y*p.y)
def roundCorner(g,nid,_radius,handleLength = .7):
handleLength = 1 - handleLength
radius = Point()
if isinstance(_radius,int):
radius.x = _radius
r... | cStart,cEnd = getContourRange(nid,g)
if nid == cStart:
return g[cEnd]
else:
return g[nid - 1] | identifier_body |
AT-RoundCorners.py | #FLM: AT ChrisCorner
"""Round selected corners:
RADIUS is a Point instance that represents the x and y radius of the corner
HANDLELENGTH is a number between 0. and 1. that determines how long the
bezier handles should be, affecting the steepness of the curve
"""
import math
def getContourRange(nid,g):
cID = g.... | (nid,g):
cStart,cEnd = getContourRange(nid,g)
if nid == cEnd:
return g[cStart]
else:
return g[nid + 1]
def getPrevNode(nid,g):
cStart,cEnd = getContourRange(nid,g)
if nid == cStart:
return g[cEnd]
else:
return g[nid - 1]
def normalizeVector(p):
m = getMagnitude(p);
if m != 0:
return p*(1/m)
else:
... | getNextNode | identifier_name |
AT-RoundCorners.py | #FLM: AT ChrisCorner
"""Round selected corners:
RADIUS is a Point instance that represents the x and y radius of the corner
HANDLELENGTH is a number between 0. and 1. that determines how long the
bezier handles should be, affecting the steepness of the curve
"""
import math
def getContourRange(nid,g):
cID = g.... |
n1.x += int(nOffset.x)
n1.y += int(nOffset.y)
n1[1].x = p.x + round(pVect.x * radius.x * handleLength)
n1[1].y = p.y + round(pVect.y * radius.y * handleLength)
n1[2].x = p.x + round(nVect.x * radius.x * handleLength)
n1[2].y = p.y + round(nVect.y * radius.y * handleLength)
# RADIUS allows the x and the y radiu... |
g.Insert(Node(nCURVE,Point(p.x,p.y)), nid+1)
n1 = g[nid+1] | random_line_split |
AT-RoundCorners.py | #FLM: AT ChrisCorner
"""Round selected corners:
RADIUS is a Point instance that represents the x and y radius of the corner
HANDLELENGTH is a number between 0. and 1. that determines how long the
bezier handles should be, affecting the steepness of the curve
"""
import math
def getContourRange(nid,g):
cID = g.... |
n = g[nid]
p = Point(n.x, n.y)
nn = getNextNode(nid, g)
pn = getPrevNode(nid, g)
nVect = normalizeVector(Point(-p.x + nn.x, -p.y + nn.y))
pVect = normalizeVector(Point(-p.x + pn.x, -p.y + pn.y))
pOffset = Point(round(pVect.x * radius.x), round(pVect.y * radius.y))
nOffset = Point(round(nVect.x * radius.x)... | radius = _radius | conditional_block |
item_view.js | Noted.ItemView = Ember.View.extend({
templateName: "item_static",
didInsertElement: function() {
if (this.listItem.get("isEditing") === true) {
this._toEditingView();
}
else if (this.get("listItem.isActive")) {
this._updateScrollPosition();
}
},
editingObserver: function() {
if... | else {
if (this.get("listItem.isEditing")) {
this.set("listItem.isEditing", false);
}
}
}.observes('listItem.isActive'),
click: function(e) {
if (this.get("listItem.isEditing")) {
if ($(e.target).prop("tagName") != "TEXTAREA") {
this.set('listItem.isEditing', false);
... | } | random_line_split |
item_view.js | Noted.ItemView = Ember.View.extend({
templateName: "item_static",
didInsertElement: function() {
if (this.listItem.get("isEditing") === true) {
this._toEditingView();
}
else if (this.get("listItem.isActive")) {
this._updateScrollPosition();
}
},
editingObserver: function() {
if... |
else {
this.set('listItem.isEditing', false);
this.set('listItem.text', value);
}
Noted.store.commit();
}
else {
if (this.get("oldValue") === "") {
this.get('controller').deleteItem(this.get('listItem'));
this.get("parentView")._changeActiveByOffset(-1);... | {
this.get('controller').deleteItem(this.get('listItem'));
this.get("parentView")._changeActiveByOffset(-1);
} | conditional_block |
message.service.ts | import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';
| OPEN_WEBHOOKS_DIALOG, // all webhooks
EDIT_WEBHOOK,
WEBHOOK_UPDATED,
OPEN_QUICK_START,
OPEN_HTTP_REQUESTS_WINDOW, // on file/dir right click
SET_TAB_CONTENT,
ARGS_CHANGED, // fired when args changed in args-window by user
SET_ARGS, // instructs args-window to set arguments embedded to the message
TIM... | export enum MESSAGE_TYPE {
// webhooks | random_line_split |
message.service.ts | import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';
export enum MESSAGE_TYPE {
// webhooks
OPEN_WEBHOOKS_DIALOG, // all webhooks
EDIT_WEBHOOK,
WEBHOOK_UPDATED,
OPEN_QUICK_START,
OPEN_HTTP_REQUESTS_WINDOW, // on file/dir right click
SET_TAB_CON... | (): Observable<any> {
return this.subject.asObservable();
}
}
| getMessage | identifier_name |
intrinsic-return-address.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
fn main() {
let mut intrinsic_reported_address = 0;
let pt = f(&mut intrinsic_reported_address);
let actual_address = &pt as *const Point as uint;
assert_eq!(intrinsic_reported_address, actual_address);
}
| {
unsafe {
*result = return_address() as uint;
Point {
x: 1.0,
y: 2.0,
z: 3.0,
}
}
} | identifier_body |
intrinsic-return-address.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
fn main() {
let mut intrinsic_reported_address = 0;
let pt = f(&mut intrinsic_reported_address);
let actual_address = &pt as *const Point as uint;
assert_eq!(intrinsic_reported_address, actual_address);
} | y: 2.0,
z: 3.0,
}
}
| random_line_split |
intrinsic-return-address.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
x: f32,
y: f32,
z: f32,
}
extern "rust-intrinsic" {
fn return_address() -> *const u8;
}
fn f(result: &mut uint) -> Point {
unsafe {
*result = return_address() as uint;
Point {
x: 1.0,
y: 2.0,
z: 3.0,
}
}
}
fn main() {
let mut... | Point | identifier_name |
picker.ts | /*
* Copyright 2019 gRPC authors.
*
* 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... | * A standard picker representing a load balancer in the TRANSIENT_FAILURE
* state. Always responds to every pick request with an UNAVAILABLE status.
*/
export class UnavailablePicker implements Picker {
private status: StatusObject;
constructor(status?: StatusObject) {
if (status !== undefined) {
this.... |
/** | random_line_split |
picker.ts | /*
* Copyright 2019 gRPC authors.
*
* 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... |
}
pick(pickArgs: PickArgs): TransientFailurePickResult {
return {
pickResultType: PickResultType.TRANSIENT_FAILURE,
subchannel: null,
status: this.status,
extraFilterFactories: [],
onCallStarted: null,
};
}
}
/**
* A standard picker representing a load balancer in the IDLE... | {
this.status = {
code: Status.UNAVAILABLE,
details: 'No connection established',
metadata: new Metadata(),
};
} | conditional_block |
picker.ts | /*
* Copyright 2019 gRPC authors.
*
* 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... | {
private calledExitIdle = false;
// Constructed with a load balancer. Calls exitIdle on it the first time pick is called
constructor(private loadBalancer: LoadBalancer) {}
pick(pickArgs: PickArgs): QueuePickResult {
if (!this.calledExitIdle) {
process.nextTick(() => {
this.loadBalancer.exit... | QueuePicker | identifier_name |
vault_certificate.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | """
_attribute_map = {
'certificate_url': {'key': 'certificateUrl', 'type': 'str'},
'certificate_store': {'key': 'certificateStore', 'type': 'str'},
}
def __init__(self, **kwargs):
super(VaultCertificate, self).__init__(**kwargs)
self.certificate_url = kwargs.get('certi... | """Describes a single certificate reference in a Key Vault, and where the
certificate should reside on the VM.
:param certificate_url: This is the URL of a certificate that has been
uploaded to Key Vault as a secret. For adding a secret to the Key Vault,
see [Add a key or secret to the key
vault... | identifier_body |
vault_certificate.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (Model):
"""Describes a single certificate reference in a Key Vault, and where the
certificate should reside on the VM.
:param certificate_url: This is the URL of a certificate that has been
uploaded to Key Vault as a secret. For adding a secret to the Key Vault,
see [Add a key or secret to the k... | VaultCertificate | identifier_name |
vault_certificate.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | from msrest.serialization import Model
class VaultCertificate(Model):
"""Describes a single certificate reference in a Key Vault, and where the
certificate should reside on the VM.
:param certificate_url: This is the URL of a certificate that has been
uploaded to Key Vault as a secret. For adding a ... | # --------------------------------------------------------------------------
| random_line_split |
api.py | import datetime
import re
import requests
from django.conf import settings
from django.utils.timezone import make_aware, utc
from raven.contrib.django.raven_compat.models import client as sentry_client
def get_articles_data(count=8):
payload = {
'consumer_key': settings.POCKET_CONSUMER_KEY,
'acce... |
check_article_image(article)
def check_article_image(article):
"""Determine if external image is available"""
# sanity check to make sure image provided by API actually exists and is https
if article['image_src'] and re.match(r'^https://', article['image_src'], flags=re.I):
try:
... | del article['excerpt']
del article['id']
del article['quote'] | random_line_split |
api.py | import datetime
import re
import requests
from django.conf import settings
from django.utils.timezone import make_aware, utc
from raven.contrib.django.raven_compat.models import client as sentry_client
def get_articles_data(count=8):
payload = {
'consumer_key': settings.POCKET_CONSUMER_KEY,
'acce... |
else:
article['image_src'] = None
| try:
resp = requests.get(article['image_src'])
resp.raise_for_status()
except Exception:
sentry_client.captureException()
article['image_src'] = None | conditional_block |
api.py | import datetime
import re
import requests
from django.conf import settings
from django.utils.timezone import make_aware, utc
from raven.contrib.django.raven_compat.models import client as sentry_client
def get_articles_data(count=8):
payload = {
'consumer_key': settings.POCKET_CONSUMER_KEY,
'acce... |
def check_article_image(article):
"""Determine if external image is available"""
# sanity check to make sure image provided by API actually exists and is https
if article['image_src'] and re.match(r'^https://', article['image_src'], flags=re.I):
try:
resp = requests.get(article['imag... | for _, article in articles:
# id from API should be moved to pocket_id to not conflict w/DB's id
article['pocket_id'] = article['id']
# convert time_shared from unix timestamp to datetime
article['time_shared'] = make_aware(datetime.datetime.fromtimestamp(int(article['time_shared'])), u... | identifier_body |
api.py | import datetime
import re
import requests
from django.conf import settings
from django.utils.timezone import make_aware, utc
from raven.contrib.django.raven_compat.models import client as sentry_client
def get_articles_data(count=8):
payload = {
'consumer_key': settings.POCKET_CONSUMER_KEY,
'acce... | (articles):
for _, article in articles:
# id from API should be moved to pocket_id to not conflict w/DB's id
article['pocket_id'] = article['id']
# convert time_shared from unix timestamp to datetime
article['time_shared'] = make_aware(datetime.datetime.fromtimestamp(int(article['ti... | complete_articles_data | identifier_name |
utils.ts | // Downcast because Algolia doesn't guarantee an _id field, but our schema does
resolve(content as {results: Array<AlgoliaDocument>});
}
});
});
}
export async function algoliaDoSearch(algoliaIndex: algoliasearch.Index, query: algoliasearch.QueryParameters) {
return new Promise((resolve,r... | {
const response: any = await algoliaDeleteIds(algoliaIndex, algoliaIdsToDelete);
await algoliaWaitForTask(algoliaIndex, response.taskID);
} | conditional_block | |
utils.ts | ({
...algoliaMetaInfo,
objectID: post._id + "_0",
body: ""
}));
}
return postBatch;
}
Tags.toAlgolia = async (tag: DbTag): Promise<Array<AlgoliaTag>|null> => {
if (tag.deleted) return null;
if (tag.adminOnly) return null;
let description = ""
if (tag.description?.originalContents?.... | getHighestGroupIndexInGroup | identifier_name | |
utils.ts | let result: any = await algoliaSetIndexSettings(algoliaIndex, settings);
await algoliaWaitForTask(algoliaIndex, result.taskID);
}
export async function algoliaGetAllDocuments(algoliaIndex: algoliasearch.Index): Promise<Array<AlgoliaDocument>> {
return new Promise((resolve,reject) => {
let results: Array<Algol... | {
const document = await collection.findOne({_id: documentId});
if (document) {
await algoliaDocumentExport({ documents: [document], collection });
}
} | identifier_body | |
utils.ts | user.groups,
af: user.groups && user.groups.includes('alignmentForum')
}
return [algoliaUser];
}
// TODO: Refactor this to no longer by this insane parallel code path, and instead just make a graphQL query and use all the relevant data
Posts.toAlgolia = async (post: DbPost): Promise<Array<AlgoliaPost>|null> =... | // Do algoliaIndex.waitTask as an async function rather than a
// callback-accepting function.
async function algoliaWaitForTask(algoliaIndex: algoliasearch.Index, taskID: number) {
return new Promise<void>((resolve,reject) => {
algoliaIndex.waitTask(taskID, (err) => {
if (err) reject(err);
else resol... | random_line_split | |
linker.rs | &Path);
fn framework_path(&mut self, path: &Path);
fn output_filename(&mut self, path: &Path);
fn add_object(&mut self, path: &Path);
fn gc_sections(&mut self, is_dylib: bool);
fn position_independent_executable(&mut self);
fn optimize(&mut self);
fn debuginfo(&mut self);
fn no_default_... |
self.cmd.arg("-Wl,-Bstatic");
}
fn hint_dynamic(&mut self) {
if !self.takes_hints() { return }
self.cmd.arg("-Wl,-Bdynamic");
}
fn export_symbols(&mut self, _: &Session, _: &CrateTranslation, _: &Path) {
// noop, visibility in object files takes care of this
}
}
p... | { return } | conditional_block |
linker.rs | fn whole_archives(&mut self);
fn no_whole_archives(&mut self);
fn export_symbols(&mut self, sess: &Session, trans: &CrateTranslation,
tmpdir: &Path);
}
pub struct GnuLinker<'a> {
pub cmd: &'a mut Command,
pub sess: &'a Session,
}
impl<'a> GnuLinker<'a> {
fn takes_hints(&self... | } | random_line_split | |
linker.rs | &Path);
fn framework_path(&mut self, path: &Path);
fn output_filename(&mut self, path: &Path);
fn add_object(&mut self, path: &Path);
fn gc_sections(&mut self, is_dylib: bool);
fn position_independent_executable(&mut self);
fn optimize(&mut self);
fn debuginfo(&mut self);
fn no_default_... |
fn export_symbols(&mut self, _: &Session, _: &CrateTranslation, _: &Path) {
// noop, visibility in object files takes care of this
}
}
pub struct MsvcLinker<'a> {
pub cmd: &'a mut Command,
pub sess: &'a Session,
}
impl<'a> Linker for MsvcLinker<'a> {
fn link_rlib(&mut self, lib: &Path) {... | {
if !self.takes_hints() { return }
self.cmd.arg("-Wl,-Bdynamic");
} | identifier_body |
linker.rs | &Path);
fn framework_path(&mut self, path: &Path);
fn output_filename(&mut self, path: &Path);
fn add_object(&mut self, path: &Path);
fn gc_sections(&mut self, is_dylib: bool);
fn position_independent_executable(&mut self);
fn optimize(&mut self);
fn debuginfo(&mut self);
fn no_default_... | (&mut self, args: &[String]) { self.cmd.args(args); }
fn build_dylib(&mut self, _out_filename: &Path) { self.cmd.arg("/DLL"); }
fn gc_sections(&mut self, _is_dylib: bool) { self.cmd.arg("/OPT:REF,ICF"); }
fn link_dylib(&mut self, lib: &str) {
self.cmd.arg(&format!("{}.lib", lib));
}
fn lin... | args | identifier_name |
2112013.js | var status = -1;
function | (mode, type, selection) {
var em = cm.getEventManager("Juliet");
if (em == null) {
cm.dispose();
return;
}
if (!cm.canHold(4001131,1)) {
cm.sendOk("I will need 1 ETC space.");
cm.dispose();
return;
}
if (cm.getPlayer().getMapId() == 926110000) { //just first stage
if (java.lang.Math.random... | action | identifier_name |
2112013.js | var status = -1;
function action(mode, type, selection) {
var em = cm.getEventManager("Juliet");
if (em == null) {
cm.dispose();
return;
}
if (!cm.canHold(4001131,1)) |
if (cm.getPlayer().getMapId() == 926110000) { //just first stage
if (java.lang.Math.random() < 0.1) {
if (em.getProperty("stage1").equals("0")) {
em.setProperty("stage1", "1");
cm.getMap().setReactorState();
}
} else if (java.lang.Math.random() < 0.05) {
if (em.getProperty("stage").equals("0")... | {
cm.sendOk("I will need 1 ETC space.");
cm.dispose();
return;
} | conditional_block |
2112013.js | var status = -1;
function action(mode, type, selection) | }
}
}
cm.dispose();
} | {
var em = cm.getEventManager("Juliet");
if (em == null) {
cm.dispose();
return;
}
if (!cm.canHold(4001131,1)) {
cm.sendOk("I will need 1 ETC space.");
cm.dispose();
return;
}
if (cm.getPlayer().getMapId() == 926110000) { //just first stage
if (java.lang.Math.random() < 0.1) {
if (em.... | identifier_body |
2112013.js | var status = -1; |
function action(mode, type, selection) {
var em = cm.getEventManager("Juliet");
if (em == null) {
cm.dispose();
return;
}
if (!cm.canHold(4001131,1)) {
cm.sendOk("I will need 1 ETC space.");
cm.dispose();
return;
}
if (cm.getPlayer().getMapId() == 926110000) { //just first stage
if (java.... | random_line_split | |
dropck.rs | _are_implied_by_item_defn(
tcx,
dtor_predicates,
adt_def.did.expect_local(),
self_to_impl_substs,
)
}
_ => {
// Destructors only work on nominal types. This was
// already checked by coherence, but compi... | // to take on a structure that is roughly an alpha-renaming of
// the generic parameters of the item definition.)
// This path now just checks *all* predicates via an instantiation of
// the `SimpleEqRelation`, which simply forwards to the `relate` machinery
// after taking care... | // expressions etc because the Drop impls are already forced | random_line_split |
dropck.rs | )
}
_ => {
// Destructors only work on nominal types. This was
// already checked by coherence, but compilation may
// not have been terminated.
let span = tcx.def_span(drop_impl_did);
tcx.sess.delay_span_bug(
span,
... | {
relator.relate(predicate.rebind(ty_a), p.rebind(ty_b)).is_ok()
&& relator.relate(predicate.rebind(lt_a), p.rebind(lt_b)).is_ok()
} | conditional_block | |
dropck.rs | &format!(
"use the same sequence of generic type, lifetime and const parameters \
as the {} definition",
self_descr,
),
)
.emit();
return Err(ErrorReported);
}
... | {
SimpleEqRelation { tcx, param_env }
} | identifier_body | |
dropck.rs | to be simply more
// conservative. -nmatsakis
let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
infcx.resolve_regions_and_report_errors(
drop_impl_did.to_def_id(),
&outlives_env,
RegionckMode::default(),
);
Ok(())
})
}
... | tys | identifier_name | |
Hook.py | # Copyright (C) 2012-2020 Jonathan Vasquez <jon@xyinn.org>
#
# 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... | """Returns the list of man page files for this hook."""
return cls._man | identifier_body | |
Hook.py | # Copyright (C) 2012-2020 Jonathan Vasquez <jon@xyinn.org>
#
# 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... | (cls, vFile):
"""Deletes a required file from the hook."""
try:
cls._files.remove(vFile)
except ValueError:
Tools.Fail('The file "' + vFile + '" was not found on the list!')
@classmethod
def PrintFiles(cls):
"""Prints the required files in this hook."""
... | RemoveFile | identifier_name |
Hook.py | # Copyright (C) 2012-2020 Jonathan Vasquez <jon@xyinn.org>
#
# 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... | @classmethod
def PrintFiles(cls):
"""Prints the required files in this hook."""
for file in cls.GetFiles():
print("File: " + file)
@classmethod
def GetFiles(cls):
"""Returns the list of required files."""
return cls._files
@classmethod
def GetOptiona... | cls._files.remove(vFile)
except ValueError:
Tools.Fail('The file "' + vFile + '" was not found on the list!')
| random_line_split |
Hook.py | # Copyright (C) 2012-2020 Jonathan Vasquez <jon@xyinn.org>
#
# 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... |
@classmethod
def GetFiles(cls):
"""Returns the list of required files."""
return cls._files
@classmethod
def GetOptionalFiles(cls):
"""Returns the list of optional files."""
return cls._optional_files
@classmethod
def GetDirectories(cls):
"""Returns th... | print("File: " + file) | conditional_block |
echo_io.py | import question_template
game_type = 'input_output'
source_language = 'C'
| ]
tuple_list = [
['echo_io_forward_',['a','b','c',None,None,None]],
]
global_code_template = '''\
d #include <stdio.h>
x #include <stdio.h>
dx
'''
main_code_template = '''\
dx int i;
dx
dx for (i = 1; i < argc; i++)
dx printf("%s\\n", argv[i]);
'''
argv_template = '$x0 $x1 $x2'
stdin_template = '''\
'''
s... | parameter_list = [
['$x0','string'],['$x1','string'],['$x2','string'],
['$y0','string'],['$y1','string'],['$y2','string'] | random_line_split |
__init__.py | #################################################################################
# Copyright (c) 2013, Pacific Biosciences of California, Inc.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# ... | # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#################################################################################
__VERSION__ = "0.7.1" | random_line_split | |
test_idaho.py | '''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Idaho class
'''
from gbdxtools import Interface
from gbdxtools.idaho import Idaho
from auth_mock import get_mock_gbdx_session
import vcr
from os.path import join, isfile, dirname, realpath
import tempfile
impor... | (self):
i = Idaho(self.gbdx)
catid = '10400100203F1300'
aoi_wkt = "POLYGON ((-105.0207996368408345 39.7338828628182839, -105.0207996368408345 39.7365972921260067, -105.0158751010894775 39.7365972921260067, -105.0158751010894775 39.7338828628182839, -105.0207996368408345 39.7338828628182839))"
... | test_idaho_get_images_by_catid_and_aoi | identifier_name |
test_idaho.py | '''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Idaho class
'''
from gbdxtools import Interface
from gbdxtools.idaho import Idaho
from auth_mock import get_mock_gbdx_session
import vcr
from os.path import join, isfile, dirname, realpath
import tempfile
impor... | def setUpClass(cls):
mock_gbdx_session = get_mock_gbdx_session(token='dymmytoken')
cls.gbdx = Interface(gbdx_connection=mock_gbdx_session)
cls._temp_path = tempfile.mkdtemp()
print("Created: {}".format(cls._temp_path))
def test_init(self):
c = Idaho(self.gbdx)
se... | random_line_split | |
test_idaho.py | '''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Idaho class
'''
from gbdxtools import Interface
from gbdxtools.idaho import Idaho
from auth_mock import get_mock_gbdx_session
import vcr
from os.path import join, isfile, dirname, realpath
import tempfile
impor... |
@vcr.use_cassette('tests/unit/cassettes/test_idaho_get_images_by_catid.yaml', filter_headers=['authorization'])
def test_idaho_get_images_by_catid(self):
i = Idaho(self.gbdx)
catid = '10400100203F1300'
results = i.get_images_by_catid(catid=catid)
assert len(results['results']) ... | i = Idaho(self.gbdx)
catid = '10400100203F1300'
aoi_wkt = "POLYGON ((-105.0207996368408345 39.7338828628182839, -105.0207996368408345 39.7365972921260067, -105.0158751010894775 39.7365972921260067, -105.0158751010894775 39.7338828628182839, -105.0207996368408345 39.7338828628182839))"
results = ... | identifier_body |
InfiniteScrollArtworksGrid.tsx | ?: number
/** A component to render at the top of all items */
HeaderComponent?: React.ComponentType<any> | React.ReactElement<any>
/** A component to render at the bottom of all items */
FooterComponent?: React.ComponentType<any> | React.ReactElement<any>
/** Pass true if artworks should have a Box wrappe... | }
})
re
turn sectionedArtworks
}
renderSections() {
const spacerStyle = {
height: this.props.itemMargin,
}
const artworks = extractNodes(this.props.connection)
const sectionedArtworks = this.sectionedArtworks()
const sections: JSX.Element[] = []
const columnCount = thi... | nd section with lowest *inverted* aspect ratio sum, which is the shortest column.
let lowestRatioSum = Number.MAX_VALUE // Start higher, so we always find a
let sectionIndex: number | null = null
for (let j = 0; j < sectionRatioSums.length; j++) {
const ratioSum = sectionRatioSums[j]
... | conditional_block |
InfiniteScrollArtworksGrid.tsx | Margin?: number
/** A component to render at the top of all items */
HeaderComponent?: React.ComponentType<any> | React.ReactElement<any>
/** A component to render at the bottom of all items */
FooterComponent?: React.ComponentType<any> | React.ReactElement<any>
/** Pass true if artworks should have a Box ... | () {
const sectionRatioSums: number[] = []
const artworks = extractNodes(this.props.connection)
const sectionedArtworks: Array<typeof artworks> = []
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
for (let i = 0; i... | sectionedArtworks | identifier_name |
InfiniteScrollArtworksGrid.tsx | Margin?: number
/** A component to render at the top of all items */
HeaderComponent?: React.ComponentType<any> | React.ReactElement<any>
/** A component to render at the bottom of all items */
FooterComponent?: React.ComponentType<any> | React.ReactElement<any>
/** Pass true if artworks should have a Box ... |
getSectionDimension(width: number | null | undefined) {
// Setting the dimension to 1 for tests to avoid adjusting the screen width
if (__TEST__) {
return 1
}
if (width) {
// This is the sum of all margins in between sections, so do not count to the right of last column.
const sec... | {
// tslint:disable:no-console
if (__DEV__ && originalXMLHttpRequest !== undefined) {
const groupName = "Infinite scroll request"
const c: any = console
c.groupCollapsed(groupName, "color:" + (response ? "black" : "red") + ";")
console.log("Query:\n", query)
if (response) {
... | identifier_body |
InfiniteScrollArtworksGrid.tsx | import { createFragmentContainer, RelayPaginationProp } from "react-relay"
import { graphql } from "relay-runtime"
import ParentAwareScrollView from "../ParentAwareScrollView"
import Artwork, { ArtworkProps } from "./ArtworkGridItem"
/**
* TODO:
* - currently all the code assumes column layout
* - do no invert as... | StyleSheet,
View,
ViewStyle,
} from "react-native" | random_line_split | |
redir_assignment_parser.py | from vint.ast.traversing import traverse, register_traverser_extension
from vint.ast.parsing import Parser
from vint.ast.node_type import NodeType
REDIR_CONTENT = 'VINT:redir_content'
class RedirAssignmentParser(object):
""" A class to make redir assignment parseable. """
def process(self, ast):
... | if not is_redir_command:
return
redir_cmd_str = node['str']
is_redir_assignment = '=>' in redir_cmd_str
if not is_redir_assignment:
return
parser = Parser()
redir_content_node = parser.parse_redir(node)
... |
is_redir_command = node['ea']['cmd'].get('name') == 'redir' | random_line_split |
redir_assignment_parser.py | from vint.ast.traversing import traverse, register_traverser_extension
from vint.ast.parsing import Parser
from vint.ast.node_type import NodeType
REDIR_CONTENT = 'VINT:redir_content'
class RedirAssignmentParser(object):
""" A class to make redir assignment parseable. """
def process(self, ast):
... | if REDIR_CONTENT not in node:
return
traverse(node[REDIR_CONTENT], on_enter=on_enter, on_leave=on_leave) | identifier_body | |
redir_assignment_parser.py | from vint.ast.traversing import traverse, register_traverser_extension
from vint.ast.parsing import Parser
from vint.ast.node_type import NodeType
REDIR_CONTENT = 'VINT:redir_content'
class RedirAssignmentParser(object):
""" A class to make redir assignment parseable. """
def process(self, ast):
... |
parser = Parser()
redir_content_node = parser.parse_redir(node)
node[REDIR_CONTENT] = redir_content_node
traverse(ast, on_enter=enter_handler)
return ast
def get_redir_content(node):
return node.get(REDIR_CONTENT)
@register_traverser_extension
def travers... | return | conditional_block |
redir_assignment_parser.py | from vint.ast.traversing import traverse, register_traverser_extension
from vint.ast.parsing import Parser
from vint.ast.node_type import NodeType
REDIR_CONTENT = 'VINT:redir_content'
class RedirAssignmentParser(object):
""" A class to make redir assignment parseable. """
def | (self, ast):
def enter_handler(node):
node_type = NodeType(node['type'])
if node_type is not NodeType.EXCMD:
return
is_redir_command = node['ea']['cmd'].get('name') == 'redir'
if not is_redir_command:
return
redir_cmd_... | process | identifier_name |
supplier.js |
$(document).ready(function () {
//selecting supplier
// $('body').off('click','supplier_id.select_popup').on('click','supplier_id.select_popup' ,function () {
// void window.open('select.php?class_name=supplier', '_blank',
// 'width=1200,height=1000,TOOLBAR=no,MENUBAR=no,SCROLLBARS=yes,RESIZABLE=yes,LOCATION... |
});
});
| {
if (confirm("Do you want to create a new supplier site?")) {
$(this).replaceWith('<input id="supplier_site_name" class="textfield supplier_site_name" type="text" size="25" maxlength="50" name="supplier_site_name[]">');
$(".show.supplier_site_id").hide();
$("#supplier_site_id").val("");
$("#supplier... | conditional_block |
supplier.js | $(document).ready(function () {
//selecting supplier
// $('body').off('click','supplier_id.select_popup').on('click','supplier_id.select_popup' ,function () {
// void window.open('select.php?class_name=supplier', '_blank',
// 'width=1200,height=1000,TOOLBAR=no,MENUBAR=no,SCROLLBARS=yes,RESIZABLE=yes,LOCATION=... | }); | random_line_split | |
user-resolver.ts | /*
* Copyright (c) 2015-2017 IPT-Intellectual Products & Technologies (IPT).
* All rights reserved.
*
* This file is licensed under terms of GNU GENERAL PUBLIC LICENSE Version 3
* (GPL v3). The full text of GPL v3 license is providded in file named LICENSE,
* residing in the root folder of this project.
*
*/
i... |
@Injectable()
export class UserResolver implements Resolve<User | undefined> {
constructor(private service: UserService, private router: Router) { }
public resolve(route: ActivatedRouteSnapshot) {
const id = route.params['userId'];
return this.service.findById(id).pipe(
take(1),
map(user => {
... | random_line_split | |
user-resolver.ts | /*
* Copyright (c) 2015-2017 IPT-Intellectual Products & Technologies (IPT).
* All rights reserved.
*
* This file is licensed under terms of GNU GENERAL PUBLIC LICENSE Version 3
* (GPL v3). The full text of GPL v3 license is providded in file named LICENSE,
* residing in the root folder of this project.
*
*/
i... |
}),
catchError(() => {
this.router.navigate(['/users']);
return throwError(`User with ID:${id} not found.`);
})
);
}
}
| { // id not found
this.router.navigate(['/users']);
return undefined;
} | conditional_block |
user-resolver.ts | /*
* Copyright (c) 2015-2017 IPT-Intellectual Products & Technologies (IPT).
* All rights reserved.
*
* This file is licensed under terms of GNU GENERAL PUBLIC LICENSE Version 3
* (GPL v3). The full text of GPL v3 license is providded in file named LICENSE,
* residing in the root folder of this project.
*
*/
i... | (private service: UserService, private router: Router) { }
public resolve(route: ActivatedRouteSnapshot) {
const id = route.params['userId'];
return this.service.findById(id).pipe(
take(1),
map(user => {
if (user) {
return user;
} else { // id not found
this.... | constructor | identifier_name |
pwm1.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM1
// FIXME doesn't seem to work :-(
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
ex... | let tim1 = TIM1.access(prio, thr);
let pwm = Pwm(&*tim1);
pwm.init(FREQUENCY.invert(), afio, gpioa, rcc);
let duty = pwm.get_max_duty() / 16;
const CHANNELS: [Channel; 4] =
[Channel::_1, Channel::_2, Channel::_3, Channel::_4];
for c in &CHANNELS {
pwm.set_duty(*c, duty);
... | let rcc = &RCC.access(prio, thr); | random_line_split |
pwm1.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM1
// FIXME doesn't seem to work :-(
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
ex... |
// TASKS
tasks!(stm32f103xx, {});
| {
// Sleep
loop {
rtfm::wfi();
}
} | identifier_body |
pwm1.rs | //! Output a PWM with a duty cycle of ~6% on all the channels of TIM1
// FIXME doesn't seem to work :-(
#![deny(warnings)]
#![feature(const_fn)]
#![feature(used)]
#![no_std]
extern crate blue_pill;
extern crate embedded_hal as hal;
// version = "0.2.3"
extern crate cortex_m_rt;
// version = "0.1.0"
#[macro_use]
ex... | (ref prio: P0, thr: &TMax) {
let afio = &AFIO.access(prio, thr);
let gpioa = &GPIOA.access(prio, thr);
let rcc = &RCC.access(prio, thr);
let tim1 = TIM1.access(prio, thr);
let pwm = Pwm(&*tim1);
pwm.init(FREQUENCY.invert(), afio, gpioa, rcc);
let duty = pwm.get_max_duty() / 16;
const ... | init | identifier_name |
p007_ten_thousand_first_prime.py | __author__ = 'tilmannbruckhaus'
from collections import defaultdict
class TenThousandFirstPrime:
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
LIMIT = 1000000
TARGET = 10... |
@staticmethod
def find():
prime_count = 0
t = TenThousandFirstPrime
for i in range(2, t.LIMIT):
if not t.prime_dict[i]:
continue
prime_count += 1
if prime_count == t.TARGET:
return i
for j in range(i + ... | pass | identifier_body |
p007_ten_thousand_first_prime.py | __author__ = 'tilmannbruckhaus'
from collections import defaultdict
class TenThousandFirstPrime:
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
LIMIT = 1000000
TARGET = 10... |
if __name__ == '__main__':
print "The 10,001st prime is", TenThousandFirstPrime.find()
| if not t.prime_dict[i]:
continue
prime_count += 1
if prime_count == t.TARGET:
return i
for j in range(i + i, t.LIMIT, i):
t.prime_dict[j] = False | conditional_block |
p007_ten_thousand_first_prime.py | __author__ = 'tilmannbruckhaus'
from collections import defaultdict
class TenThousandFirstPrime:
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
LIMIT = 1000000
TARGET = 10... | ():
prime_count = 0
t = TenThousandFirstPrime
for i in range(2, t.LIMIT):
if not t.prime_dict[i]:
continue
prime_count += 1
if prime_count == t.TARGET:
return i
for j in range(i + i, t.LIMIT, i):
... | find | identifier_name |
p007_ten_thousand_first_prime.py | __author__ = 'tilmannbruckhaus'
from collections import defaultdict
class TenThousandFirstPrime:
# 10001st prime
# Problem 7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
LIMIT = 1000000
TARGET = 10... | if __name__ == '__main__':
print "The 10,001st prime is", TenThousandFirstPrime.find() |
for j in range(i + i, t.LIMIT, i):
t.prime_dict[j] = False
| random_line_split |
SingleLineTextField.tsx | import * as React from 'react';
import { FormControl, FormGroup, ControlLabel, Col } from 'react-bootstrap';
import { IField, IFieldError, IFieldBuilderProps, IFieldInputProps } from '../../../../src/data';
interface IState {
}
export default class SingleLineTextField extends React.PureComponent<IFieldInputProps & IF... | () {
const error = this.validate(this.props.value);
if (this.props.onValueChange) {
this.props.onValueChange(this.props.field, this.props.value, error);
}
}
public render() {
const { label } = this.props.field;
const { hint, required } = this.props.field.opti... | componentDidMount | identifier_name |
SingleLineTextField.tsx | import * as React from 'react';
import { FormControl, FormGroup, ControlLabel, Col } from 'react-bootstrap';
import { IField, IFieldError, IFieldBuilderProps, IFieldInputProps } from '../../../../src/data';
interface IState {
}
export default class SingleLineTextField extends React.PureComponent<IFieldInputProps & IF... |
return null;
}
} | {
if (value.trim() === '') {
return {
error: true,
errorMsg: "required"
};
}
} | conditional_block |
SingleLineTextField.tsx | import * as React from 'react';
import { FormControl, FormGroup, ControlLabel, Col } from 'react-bootstrap';
import { IField, IFieldError, IFieldBuilderProps, IFieldInputProps } from '../../../../src/data';
interface IState {
}
export default class SingleLineTextField extends React.PureComponent<IFieldInputProps & IF... |
private validate(value: string): IFieldError {
if (this.props.field.options && this.props.field.options.required) {
if (value.trim() === '') {
return {
error: true,
errorMsg: "required"
};
}
}
... | {
const value = event.target.value;
const error = this.validate(value);
this.props.onValueChange(this.props.field, value, error);
} | identifier_body |
SingleLineTextField.tsx | import * as React from 'react';
import { FormControl, FormGroup, ControlLabel, Col } from 'react-bootstrap';
import { IField, IFieldError, IFieldBuilderProps, IFieldInputProps } from '../../../../src/data';
interface IState {
}
export default class SingleLineTextField extends React.PureComponent<IFieldInputProps & IF... |
private validate(value: string): IFieldError {
if (this.props.field.options && this.props.field.options.required) {
if (value.trim() === '') {
return {
error: true,
errorMsg: "required"
};
}
}
r... | private onTextFieldChange(event: any) {
const value = event.target.value;
const error = this.validate(value);
this.props.onValueChange(this.props.field, value, error);
} | random_line_split |
api.js | /*
* NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link ... | () {
return this._name;
}
/**
* Get version of the component
*
* @return {string}
*/
getVersion() {
return this._version;
}
/**
* Get variables
*
* @return {Object}
*/
getVariables() {
return this._variables;
}
/**
* Get variable value
*
* @param {string} ... | getName | identifier_name |
api.js | /*
* NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link ... |
const {metadata, 'payload': reply} = this._component._commandReply.getMessage(this);
this._component._replyWith(metadata, reply);
}
/**
*
* @param {String} action Name of the action callback
* @param {Number} timeout Maximum allowed execution time, in milliseconds
* @protected
*/
_setCa... | {
clearTimeout(this._parentRequest._callbackTimeout);
} | conditional_block |
api.js | /*
* NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link ... |
/**
* Get user source file path
*
* @return {string}
*/
getPath() {
return this._path;
}
/**
* Get name of the component
*
* @return {string}
*/
getName() {
return this._name;
}
/**
* Get version of the component
*
* @return {string}
*/
getVersion() {
... | {
return this._frameworkVersion;
} | identifier_body |
api.js | /*
* NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link ... | &&
semver.satisfies(definition.schema.getVersion(), version)
);
if (service) {
return service.schema;
}
throw new Error(`Cannot resolve schema for Service: ${name} (${version})`);
}
/**
*
* @param {*} value
* @return {boolean}
*/
log(value, level) {
return this... | throw new Error('Cannot get service schema. No mapping provided');
}
const service = this._component.servicesMapping.find((definition) =>
name === definition.schema.getName() | random_line_split |
test_yaml_utils.py | import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
|
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("do... | ---
herp: 1
derp: 2
""" | random_line_split |
test_yaml_utils.py | import pytest
from apispec import yaml_utils
def | ():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_fr... | test_load_yaml_from_docstring | identifier_name |
test_yaml_utils.py | import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
|
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
ass... | def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2} | identifier_body |
glusterfs.py | , self.configuration.glusterfs_mount_point_base)
def check_for_setup_error(self):
"""Just to override parent behavior."""
pass
def _local_volume_dir(self, volume):
hashed = self._get_hash_str(volume['provider_location'])
path = '%s/%s' % (self.configuration.glusterfs_mount_poin... | greatest_share = glusterfs_share
greatest_size = capacity | conditional_block | |
glusterfs.py | GlusterFS'
VERSION = '1.3.0'
def __init__(self, execute=processutils.execute, *args, **kwargs):
self._remotefsclient = None
super(GlusterfsDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(volume_opts)
root_helper = utils.get_root_helper()
s... | if not os.path.exists(config):
msg = (_("Gluster config file at %(config)s doesn't exist") %
{'config': config})
LOG.warning(msg)
raise exception.GlusterfsException(msg)
self.shares = {}
try:
self._execute('mount.glusterfs', ch... | random_line_split | |
glusterfs.py | GlusterFS'
VERSION = '1.3.0'
def __init__(self, execute=processutils.execute, *args, **kwargs):
self._remotefsclient = None
super(GlusterfsDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(volume_opts)
root_helper = utils.get_root_helper()
s... | (self, snapshot, volume, volume_size):
"""Copy data from snapshot to destination volume.
This is done with a qemu-img convert to raw/qcow2 from the snapshot
qcow2.
"""
LOG.debug("snapshot: %(snap)s, volume: %(vol)s, "
"volume_size: %(size)s",
... | _copy_volume_from_snapshot | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.