file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
sha1.rs | // Implements http://rosettacode.org/wiki/SHA-1
// straight port from golang crypto/sha1
// library implementation
#![feature(core)]
use std::num::Wrapping as wr;
use std::slice::bytes::copy_memory;
use std::io::{Write, Result};
// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
// The blocksize of SHA... | assert!(self.x.len() >= ln);
copy_memory(buf_m, &mut self.x);
self.nx = ln;
}
Ok(())
}
fn flush(&mut self) -> Result<()> { Ok(()) }
}
#[test]
fn known_sha1s() {
let input_output = [
(
"His money is twice tainted: 'taint yours and 'tain... | buf_m = &buf_m[n..];
}
let ln=buf_m.len();
if ln > 0 { | random_line_split |
sha1.rs | // Implements http://rosettacode.org/wiki/SHA-1
// straight port from golang crypto/sha1
// library implementation
#![feature(core)]
use std::num::Wrapping as wr;
use std::slice::bytes::copy_memory;
use std::io::{Write, Result};
// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
// The blocksize of SHA... |
Ok(())
}
fn flush(&mut self) -> Result<()> { Ok(()) }
}
#[test]
fn known_sha1s() {
let input_output = [
(
"His money is twice tainted: 'taint yours and 'taint mine.",
[0x59u8, 0x7f, 0x6a, 0x54, 0x0, 0x10, 0xf9, 0x4c,
0x15, 0xd7, 0x18, 0x6, 0xa9, 0x9a... | {
assert!(self.x.len() >= ln);
copy_memory(buf_m, &mut self.x);
self.nx = ln;
} | conditional_block |
sha1.rs | // Implements http://rosettacode.org/wiki/SHA-1
// straight port from golang crypto/sha1
// library implementation
#![feature(core)]
use std::num::Wrapping as wr;
use std::slice::bytes::copy_memory;
use std::io::{Write, Result};
// The size of a SHA1 checksum in bytes.
const SIZE: usize = 20;
// The blocksize of SHA... | (&mut self) -> Result<()> { Ok(()) }
}
#[test]
fn known_sha1s() {
let input_output = [
(
"His money is twice tainted: 'taint yours and 'taint mine.",
[0x59u8, 0x7f, 0x6a, 0x54, 0x0, 0x10, 0xf9, 0x4c,
0x15, 0xd7, 0x18, 0x6, 0xa9, 0x9a, 0x2c, 0x87, 0x10,
... | flush | identifier_name |
alignment-gep-tup-like-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <A,B> {
a: A, b: B
}
fn f<A:Copy + 'static>(a: A, b: u16) -> @fn() -> (A, u16) {
let result: @fn() -> (A, u16) = || (copy a, b);
result
}
pub fn main() {
let (a, b) = f(22_u64, 44u16)();
info!("a=%? b=%?", a, b);
assert_eq!(a, 22u64);
assert_eq!(b, 44u16);
}
| pair | identifier_name |
alignment-gep-tup-like-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn main() {
let (a, b) = f(22_u64, 44u16)();
info!("a=%? b=%?", a, b);
assert_eq!(a, 22u64);
assert_eq!(b, 44u16);
} | }
| random_line_split |
CreateSelectable.tsx | import React, { Component, ComponentType } from 'react'
import { getBoundsForNode, TComputedBounds, TGetBoundsForNodeArgs } from './utils'
import { TSelectableItemState, TSelectableItemProps } from './Selectable.types'
import { SelectableGroupContext } from './SelectableGroup.context'
type TAddedProps = Partial<Pick<... | () {
this.context.selectable.unregister(this)
}
updateBounds = (containerScroll?: TGetBoundsForNodeArgs) => {
this.bounds = getBoundsForNode(this.node!, containerScroll)
}
getSelectableRef = (ref: HTMLElement | null) => {
this.node = ref
}
render() {
return (
<... | componentWillUnmount | identifier_name |
CreateSelectable.tsx | import React, { Component, ComponentType } from 'react'
import { getBoundsForNode, TComputedBounds, TGetBoundsForNodeArgs } from './utils'
import { TSelectableItemState, TSelectableItemProps } from './Selectable.types'
import { SelectableGroupContext } from './SelectableGroup.context'
type TAddedProps = Partial<Pick<... |
updateBounds = (containerScroll?: TGetBoundsForNodeArgs) => {
this.bounds = getBoundsForNode(this.node!, containerScroll)
}
getSelectableRef = (ref: HTMLElement | null) => {
this.node = ref
}
render() {
return (
<WrappedComponent {...this.props} {...this.state} selectab... | {
this.context.selectable.unregister(this)
} | identifier_body |
CreateSelectable.tsx | import React, { Component, ComponentType } from 'react'
import { getBoundsForNode, TComputedBounds, TGetBoundsForNodeArgs } from './utils'
import { TSelectableItemState, TSelectableItemProps } from './Selectable.types'
import { SelectableGroupContext } from './SelectableGroup.context'
type TAddedProps = Partial<Pick<... | isSelecting: false,
}
node: HTMLElement | null = null
bounds: TComputedBounds[] | null = null
componentDidMount() {
this.updateBounds()
this.context.selectable.register(this)
}
componentWillUnmount() {
this.context.selectable.unregister(this)
}
updateBounds =... | isSelected: this.props.isSelected, | random_line_split |
main.py | # https://github.com/Naish21/themostat
'''
* The MIT License (MIT)
*
* Copyright (c) 2016 Jorge Aranda Moro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, inclu... | (server=SERVER, topic="/cultivo", dato=None):
try:
c = MQTTClient(CLIENT_ID, server)
c.connect()
c.publish(topic, dato)
sleep_ms(200)
c.disconnect()
#led.value(1)
except Exception as e:
pass
#led.value(0)
state = 0
def sub_cb(topic, msg):
glo... | envioMQTT | identifier_name |
main.py | # https://github.com/Naish21/themostat
'''
* The MIT License (MIT)
*
* Copyright (c) 2016 Jorge Aranda Moro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, inclu... |
elif msg == b"off":
led.value(1)
state = 0
def recepcionMQTT(server=SERVER, topic=TOPIC3):
c = MQTTClient(CLIENT_ID, server)
# Subscribed messages will be delivered to this callback
c.set_callback(sub_cb)
c.connect()
c.subscribe(topic)
print("Connected to %s, subscribed to ... | led.value(0)
state = 1 | conditional_block |
main.py | # https://github.com/Naish21/themostat
'''
* The MIT License (MIT)
*
* Copyright (c) 2016 Jorge Aranda Moro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, inclu... |
#---End DHT22---
#---Main Program---
sleep_ms(10000)
while True:
(tem,hum) = medirTemHum()
envioMQTT(SERVER,TOPIC1,str(tem))
envioMQTT(SERVER,TOPIC2,str(hum))
recepcionMQTT()
sleep_ms(10000)
#---END Main Program---
| try:
ds.measure()
tem = ds.temperature()
hum = ds.humidity()
#ed.value(1)
return (tem,hum)
except Exception as e:
#led.value(0)
return (-1,-1) | identifier_body |
main.py | # https://github.com/Naish21/themostat
'''
* The MIT License (MIT)
*
* Copyright (c) 2016 Jorge Aranda Moro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, inclu... | #---End DHT22---
#---Main Program---
sleep_ms(10000)
while True:
(tem,hum) = medirTemHum()
envioMQTT(SERVER,TOPIC1,str(tem))
envioMQTT(SERVER,TOPIC2,str(hum))
recepcionMQTT()
sleep_ms(10000)
#---END Main Program--- | #led.value(0)
return (-1,-1)
| random_line_split |
CSM.js | /**
* @author vHawk / https://github.com/vHawk/
*/
import {
Vector2,
Vector3,
DirectionalLight,
MathUtils,
ShaderChunk,
Matrix4,
Box3
} from '../../../build/three.module.js';
import Frustum from './Frustum.js';
import Shader from './Shader.js';
const _cameraToLightMatrix = new Matrix4();
const _lightSpaceFru... |
updateFrustums() {
this.getBreaks();
this.initCascades();
this.updateShadowBounds();
this.updateUniforms();
}
remove() {
for ( let i = 0; i < this.lights.length; i ++ ) {
this.parent.remove( this.lights[ i ] );
}
}
dispose() {
const shaders = this.shaders;
shaders.forEach( function ( ... | {
while ( target.length < this.breaks.length ) {
target.push( new Vector2() );
}
target.length = this.breaks.length;
for ( let i = 0; i < this.cascades; i ++ ) {
let amount = this.breaks[ i ];
let prev = this.breaks[ i - 1 ] || 0;
target[ i ].x = prev;
target[ i ].y = amount;
}
} | identifier_body |
CSM.js | /**
* @author vHawk / https://github.com/vHawk/
*/
import {
Vector2,
Vector3,
DirectionalLight,
MathUtils,
ShaderChunk,
Matrix4,
Box3
} from '../../../build/three.module.js';
import Frustum from './Frustum.js';
import Shader from './Shader.js';
const _cameraToLightMatrix = new Matrix4();
const _lightSpaceFru... | () {
const frustums = this.frustums;
for ( let i = 0; i < frustums.length; i ++ ) {
const light = this.lights[ i ];
const shadowCam = light.shadow.camera;
const frustum = this.frustums[ i ];
// Get the two points that represent that furthest points on the frustum assuming
// that's either the diag... | updateShadowBounds | identifier_name |
CSM.js | /**
* @author vHawk / https://github.com/vHawk/
*/
import {
Vector2,
Vector3,
DirectionalLight,
MathUtils,
ShaderChunk,
Matrix4,
Box3
} from '../../../build/three.module.js';
import Frustum from './Frustum.js';
import Shader from './Shader.js';
const _cameraToLightMatrix = new Matrix4();
const _lightSpaceFru... |
target.push( 1 );
}
function logarithmicSplit( amount, near, far, target ) {
for ( let i = 1; i < amount; i ++ ) {
target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
}
target.push( 1 );
}
function practicalSplit( amount, near, far, lambda, target ) {
_uniformArray.le... | {
target.push( ( near + ( far - near ) * i / amount ) / far );
} | conditional_block |
CSM.js | /**
* @author vHawk / https://github.com/vHawk/
*/
import {
Vector2,
Vector3,
DirectionalLight,
MathUtils,
ShaderChunk,
Matrix4,
Box3
} from '../../../build/three.module.js';
import Frustum from './Frustum.js';
import Shader from './Shader.js';
const _cameraToLightMatrix = new Matrix4();
const _lightSpaceFru... | squaredBBWidth += margin;
}
shadowCam.left = - squaredBBWidth / 2;
shadowCam.right = squaredBBWidth / 2;
shadowCam.top = squaredBBWidth / 2;
shadowCam.bottom = - squaredBBWidth / 2;
shadowCam.updateProjectionMatrix();
}
}
getBreaks() {
const camera = this.camera;
const far = Math.min... | random_line_split | |
glyph.rs | // This whole file is strongly inspired by: https://github.com/jeaye/q3/blob/master/src/client/ui/ttf/glyph.rs
// available under the BSD-3 licence.
// It has been modified to work with gl-rs, nalgebra, and rust-freetype
use na::Vector2;
/// A ttf glyph.
pub struct | {
#[doc(hidden)]
pub tex: Vector2<f32>,
#[doc(hidden)]
pub advance: Vector2<f32>,
#[doc(hidden)]
pub dimensions: Vector2<f32>,
#[doc(hidden)]
pub offset: Vector2<f32>,
#[doc(hidden)]
pub buffer: Vec<u8>,
}
impl Glyph {
/// Creates a new empty glyph.
pub fn new(
... | Glyph | identifier_name |
glyph.rs | // This whole file is strongly inspired by: https://github.com/jeaye/q3/blob/master/src/client/ui/ttf/glyph.rs
// available under the BSD-3 licence.
// It has been modified to work with gl-rs, nalgebra, and rust-freetype
use na::Vector2;
/// A ttf glyph.
pub struct Glyph {
#[doc(hidden)]
pub tex: Vector2<f32>... |
}
| {
Glyph {
tex,
advance,
dimensions,
offset,
buffer,
}
} | identifier_body |
glyph.rs | // This whole file is strongly inspired by: https://github.com/jeaye/q3/blob/master/src/client/ui/ttf/glyph.rs
// available under the BSD-3 licence.
// It has been modified to work with gl-rs, nalgebra, and rust-freetype
use na::Vector2;
/// A ttf glyph.
pub struct Glyph {
#[doc(hidden)]
pub tex: Vector2<f32>... | }
}
} | random_line_split | |
ChartBtnView.js | define([ 'backbone', 'metro', 'highcharts' ], function(Backbone, Metro, Highcharts) {
var ChartBtnView = Backbone.View.extend({
className: 'chart-btn-view menu-btn',
events: {
'click': 'toggle',
'mouseover': 'over',
'mouseout': 'out',
},
initialize: function(){
//ensure correct scope
... | toggleMetroDialog('#chart_dialog');
},
over: function() {
$(this.el).addClass('expand');
},
out: function() {
$(this.el).removeClass('expand');
},
setInfo: function(content) {
this.dialog.append(content);
}
});
return ChartBtnView;
}); |
toggle: function() { | random_line_split |
config.example.js | 'use strict';
exports.port = process.env.PORT || 3000;
exports.mongodb = {
uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'localhost/lulucrawler'
};
exports.getThisUrl = '';
exports.companyName = '';
exports.projectName = 'luluCrawler';
exports.systemEmail = 'your@email.addy';
exports.cryptoKey = 'k3yb0... | credentials: {
user: process.env.SMTP_USERNAME || 'your@email.addy',
password: process.env.SMTP_PASSWORD || 'bl4rg!',
host: process.env.SMTP_HOST || 'smtp.gmail.com',
ssl: true
}
}; | name: process.env.SMTP_FROM_NAME || exports.projectName +' Website',
address: process.env.SMTP_FROM_ADDRESS || 'your@email.addy'
}, | random_line_split |
address.ts | import { ADDRESS_STATUS, ADDRESS_TYPE, RECEIVE_ADDRESS, SEND_ADDRESS } from '../constants';
import { Address, Recipient } from '../interfaces';
import { ContactEmail } from '../interfaces/contacts';
import { canonizeInternalEmail } from './email';
import { unary } from './function';
export const getIsAddressDisabled =... | address.Send === SEND_ADDRESS.SEND_YES
);
};
export const getActiveAddresses = (addresses: Address[]): Address[] => {
return addresses.filter(unary(getIsAddressActive));
};
export const hasAddresses = (addresses: Address[] | undefined): boolean => {
return Array.isArray(addresses) && addresses.len... | random_line_split | |
address.ts | import { ADDRESS_STATUS, ADDRESS_TYPE, RECEIVE_ADDRESS, SEND_ADDRESS } from '../constants';
import { Address, Recipient } from '../interfaces';
import { ContactEmail } from '../interfaces/contacts';
import { canonizeInternalEmail } from './email';
import { unary } from './function';
export const getIsAddressDisabled =... |
const canonicalUserEmail = canonizeInternalEmail(userEmail);
return addresses.find(({ Email }) => canonizeInternalEmail(Email) === canonicalUserEmail);
};
| {
return undefined;
} | conditional_block |
admin.py | # -*- coding: utf-8 -*-
import os
from django.contrib import admin
from django import forms
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.conf.urls import url, patterns
from django.shortcuts import render
from django.contrib.... | context['examiners'].append(examiner)
return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
def queryset(self, request):
qs = super(SubmissionAdmin, self).queryset(request)
if not request.user.is_superuser:
qs = qs.filter(examiners = req... | exercise_id in assignment.exercises:
if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
examiner['todo'] += 1
| conditional_block |
admin.py | # -*- coding: utf-8 -*-
import os
from django.contrib import admin
from django import forms
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.conf.urls import url, patterns
from django.shortcuts import render
from django.contrib.... |
exercise_id = str(exercise['id'])
answer = answers[exercise_id]
if exercise['type'] == 'open':
if isinstance(answer, list):
toret = ''
for part in answer:
field = get_option(exercise['fields'], part['id'])
toret += '- %s:\n\n%s\n\n' % (field[... | for option in options:
if option['id'] == int(id):
return option | identifier_body |
admin.py | # -*- coding: utf-8 -*-
import os
from django.contrib import admin
from django import forms
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.conf.urls import url, patterns
from django.shortcuts import render
from django.contrib.... | (answers, exercise):
def get_option(options, id):
for option in options:
if option['id'] == int(id):
return option
exercise_id = str(exercise['id'])
answer = answers[exercise_id]
if exercise['type'] == 'open':
if isinstance(answer, list):
toret = ... | get_open_answer | identifier_name |
admin.py | # -*- coding: utf-8 -*-
import os
from django.contrib import admin
from django import forms
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.core.urlresolvers import reverse
from django.conf.urls import url, patterns
from django.shortcuts import render
from django.contrib.... | if value:
a_tag = '<a href="%s">%s</a>' % (value, value)
else:
a_tag = 'brak'
return mark_safe(('<input type="hidden" name="%s" value="%s"/>' % (name, value)) + a_tag)
class SubmissionFormBase(forms.ModelForm):
class Meta:
model = Submission
exclude =... |
readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
class AttachmentWidget(forms.Widget):
def render(self, name, value, *args, **kwargs): | random_line_split |
index.ts | import * as S from './addTodo.css';
import { ITodo } from '../../../../interfaces/ITodo';
export const AddTodoComponent: angular.IComponentOptions = {
template: `
<form ng-submit="$ctrl.addTodo()">
<input class="${S['new-todo']}" placeholder="What needs to be done?" ng-model="$ctrl.newTodo" au... |
toggleAll(e: MouseEvent) {
this.onToggleAll({ completed: (<HTMLInputElement>e.target).checked });
}
}
};
| {
this.onAdd({ todo: this.newTodo });
this.newTodo = '';
} | identifier_body |
index.ts | import * as S from './addTodo.css';
import { ITodo } from '../../../../interfaces/ITodo';
export const AddTodoComponent: angular.IComponentOptions = {
template: `
<form ng-submit="$ctrl.addTodo()">
<input class="${S['new-todo']}" placeholder="What needs to be done?" ng-model="$ctrl.newTodo" au... |
onAdd: { (todo: { todo: string; }): void; };
onToggleAll: { (completed: { completed: boolean; }): void; };
newTodo: string = '';
isAllCompleted: boolean;
constructor() { }
$onChanges(changes: { list: angular.IChangesObject<Array<ITodo>> }) {
this.isAllComp... | onAdd: '&',
onToggleAll: '&'
},
controller: class implements angular.IController { | random_line_split |
index.ts | import * as S from './addTodo.css';
import { ITodo } from '../../../../interfaces/ITodo';
export const AddTodoComponent: angular.IComponentOptions = {
template: `
<form ng-submit="$ctrl.addTodo()">
<input class="${S['new-todo']}" placeholder="What needs to be done?" ng-model="$ctrl.newTodo" au... | () {
this.onAdd({ todo: this.newTodo });
this.newTodo = '';
}
toggleAll(e: MouseEvent) {
this.onToggleAll({ completed: (<HTMLInputElement>e.target).checked });
}
}
};
| addTodo | identifier_name |
main_with_threads.py | #!/usr/bin/env python3
import re
import json
from threading import Thread
from rx import Observable
import APIReaderTwitter as Twitter
emoji_re = re.compile(u'['
u'\U0001F300-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF\u2700-\u27BF]+',
re.UNICODE)
# Util
def process_stream(... | (element):
return len(element['entities']['hashtags']) > 0
# Tests
def tweet_has_more_than_two_emojis(element):
return count_emoji(element['text']) > 2
# https://dev.twitter.com/overview/api/tweets
def original_tweet_has_less_than_50_retweets(element):
return element['retweeted_status']['retweet_count'] ... | has_hashtags | identifier_name |
main_with_threads.py | #!/usr/bin/env python3
import re
import json
from threading import Thread
from rx import Observable
import APIReaderTwitter as Twitter
emoji_re = re.compile(u'['
u'\U0001F300-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF\u2700-\u27BF]+',
re.UNICODE)
# Util
def process_stream(... |
def is_retweet(element):
return 'retweeted_status' in element
def is_spanish_tweet(element):
return element['lang'] == 'es'
def is_japanese_tweet(element):
return element['lang'] == 'ja'
def has_hashtags(element):
return len(element['entities']['hashtags']) > 0
# Tests
def tweet_has_more_than_two_... |
# Filters
def is_tweet(element):
return set(('favorited', 'favorite_count', 'retweeted', 'retweet_count')) <= element.keys() | random_line_split |
main_with_threads.py | #!/usr/bin/env python3
import re
import json
from threading import Thread
from rx import Observable
import APIReaderTwitter as Twitter
emoji_re = re.compile(u'['
u'\U0001F300-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF\u2700-\u27BF]+',
re.UNICODE)
# Util
def process_stream(... | stream = Observable.from_(Twitter.get_iterable())
tweets = stream.filter(is_tweet)
# Keep only retweets
retweeted_tweets = tweets.filter(is_retweet)
# Keep only tweets in japanese
in_japanese_tweets = tweets.filter(is_japanese_tweet)
# Keep all tweets in spanish that contain a hashtag
spa... | conditional_block | |
main_with_threads.py | #!/usr/bin/env python3
import re
import json
from threading import Thread
from rx import Observable
import APIReaderTwitter as Twitter
emoji_re = re.compile(u'['
u'\U0001F300-\U0001F64F'
u'\U0001F680-\U0001F6FF'
u'\u2600-\u26FF\u2700-\u27BF]+',
re.UNICODE)
# Util
def process_stream(... |
def is_spanish_tweet(element):
return element['lang'] == 'es'
def is_japanese_tweet(element):
return element['lang'] == 'ja'
def has_hashtags(element):
return len(element['entities']['hashtags']) > 0
# Tests
def tweet_has_more_than_two_emojis(element):
return count_emoji(element['text']) > 2
# ht... | return 'retweeted_status' in element | identifier_body |
peripheral.rs | use bare_metal::{CriticalSection, Mutex};
use once_cell::unsync::OnceCell;
static PERIPHERALS: Mutex<OnceCell<At2XtPeripherals>> = Mutex::new(OnceCell::new());
pub struct At2XtPeripherals {
pub port: msp430g2211::PORT_1_2,
pub timer: msp430g2211::TIMER_A2,
}
impl AsRef<msp430g2211::PORT_1_2> for At2XtPeriphe... |
impl At2XtPeripherals {
pub fn init(self, cs: &CriticalSection) -> Result<(), ()> {
// We want to consume our Peripherals struct so interrupts
// and the main thread can access the peripherals; OnceCell
// returns the data to you on error.
PERIPHERALS.borrow(*cs).set(self).map_err(|... | }
} | random_line_split |
peripheral.rs | use bare_metal::{CriticalSection, Mutex};
use once_cell::unsync::OnceCell;
static PERIPHERALS: Mutex<OnceCell<At2XtPeripherals>> = Mutex::new(OnceCell::new());
pub struct | {
pub port: msp430g2211::PORT_1_2,
pub timer: msp430g2211::TIMER_A2,
}
impl AsRef<msp430g2211::PORT_1_2> for At2XtPeripherals {
fn as_ref(&self) -> &msp430g2211::PORT_1_2 {
&self.port
}
}
impl AsRef<msp430g2211::TIMER_A2> for At2XtPeripherals {
fn as_ref(&self) -> &msp430g2211::TIMER_A2 {... | At2XtPeripherals | identifier_name |
base.js | import BN from "../../../bn.js";
import * as utils from "../utils";
'use strict';
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;
function BaseCurve(type, conf) {
this.type = type;
this.p = new BN(conf.p, 16);
// Use Montgomery, when there is no fast reduction for the prime
... |
if (!zero)
break;
k++;
i--;
}
if (i >= 0)
k++;
acc = acc.dblp(k);
if (i < 0)
break;
for (j = 0; j < len; j++) {
var z = tmp[j];
p;
if (z === 0)
continu... | {
tmp[j] = naf[j][i] | 0;
if (tmp[j] !== 0)
zero = false;
} | conditional_block |
base.js | import BN from "../../../bn.js";
import * as utils from "../utils";
'use strict';
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;
function BaseCurve(type, conf) |
BaseCurve.prototype.point = function point() {
throw new Error('Not implemented');
};
BaseCurve.prototype.validate = function validate() {
throw new Error('Not implemented');
};
BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
assert(p.precomputed);
var doubles = p._getDoubles();
va... | {
this.type = type;
this.p = new BN(conf.p, 16);
// Use Montgomery, when there is no fast reduction for the prime
this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
// Useful for many curves
this.zero = new BN(0).toRed(this.red);
this.one = new BN(1).toRed(this.red);
this.two ... | identifier_body |
base.js | import BN from "../../../bn.js";
import * as utils from "../utils";
'use strict';
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;
function | (type, conf) {
this.type = type;
this.p = new BN(conf.p, 16);
// Use Montgomery, when there is no fast reduction for the prime
this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
// Useful for many curves
this.zero = new BN(0).toRed(this.red);
this.one = new BN(1).toRed(this.red);
... | BaseCurve | identifier_name |
base.js | import BN from "../../../bn.js";
import * as utils from "../utils";
'use strict';
var getNAF = utils.getNAF;
var getJSF = utils.getJSF;
var assert = utils.assert;
function BaseCurve(type, conf) {
this.type = type;
this.p = new BN(conf.p, 16);
// Use Montgomery, when there is no fast reduction for the prime
... | var naf = getNAF(k, 1, this._bitLength);
var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
I /= 3;
// Translate into more windowed form
var repr = [];
var j;
var nafW;
for (j = 0; j < naf.length; j += doubles.step) {
nafW = 0;
for (var l = j + doubles.... | BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
assert(p.precomputed);
var doubles = p._getDoubles(); | random_line_split |
ocrRegion.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | {
/**
* Create a OcrRegion.
* @member {string} [boundingBox] Bounding box of a recognized region. The
* four integers represent the x-coordinate of the left edge, the
* y-coordinate of the top edge, width, and height of the bounding box, in
* the coordinate system of the input image, after it has been... | OcrRegion | identifier_name |
ocrRegion.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... |
/**
* Defines the metadata of OcrRegion
*
* @returns {object} metadata of OcrRegion
*
*/
mapper() {
return {
required: false,
serializedName: 'OcrRegion',
type: {
name: 'Composite',
className: 'OcrRegion',
modelProperties: {
boundingBox: {
... | {
} | identifier_body |
ocrRegion.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | };
}
}
module.exports = OcrRegion; | random_line_split | |
paper-tests.ts | import paper = require('paper');
var canvas = document.createElement('canvas')
paper.setup(canvas);
| // Circle
var path = new paper.Path.Circle({
center: [80, 50],
radius: 35,
fillColor: 'red'
});
// Dotted Line Tool
var dottedLinePath: paper.Path;
var dottedLineTool = new paper.Tool();
dottedLineTool.onMouseDown = function(event: any) {
new paper.Layer().activate();
dottedLinePath = new paper.Path();
... | random_line_split | |
dst-rvalue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let _x: Box<str> = box *"hello world";
//~^ ERROR E0161
//~^^ ERROR cannot move out of borrowed content
let array: &[isize] = &[1, 2, 3];
let _x: Box<[isize]> = box *array;
//~^ ERROR E0161
//~^^ ERROR cannot move out of borrowed content
}
| main | identifier_name |
dst-rvalue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //~^ ERROR E0161
//~^^ ERROR cannot move out of borrowed content
let array: &[isize] = &[1, 2, 3];
let _x: Box<[isize]> = box *array;
//~^ ERROR E0161
//~^^ ERROR cannot move out of borrowed content
} | random_line_split | |
dst-rvalue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let _x: Box<str> = box *"hello world";
//~^ ERROR E0161
//~^^ ERROR cannot move out of borrowed content
let array: &[isize] = &[1, 2, 3];
let _x: Box<[isize]> = box *array;
//~^ ERROR E0161
//~^^ ERROR cannot move out of borrowed content
} | identifier_body | |
main.py | # -*- coding: utf-8 -*-
#
# AWL simulator - Dummy hardware interface
#
# Copyright 2013-2014 Michael Buesch <m@bues.ch>
#
# 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 ... | (self):
pass # Do nothing
def directReadInput(self, accessWidth, accessOffset):
if accessOffset < self.inputAddressBase:
return None
# Just read the current value from the CPU and return it.
return self.sim.cpu.fetch(AwlOperator(AwlOperator.MEM_E,
accessWidth,
AwlOffset(accessOffset... | writeOutputs | identifier_name |
main.py | # -*- coding: utf-8 -*-
#
# AWL simulator - Dummy hardware interface
#
# Copyright 2013-2014 Michael Buesch <m@bues.ch>
#
# 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 ... |
# Just read the current value from the CPU and return it.
return self.sim.cpu.fetch(AwlOperator(AwlOperator.MEM_E,
accessWidth,
AwlOffset(accessOffset)))
def directWriteOutput(self, accessWidth, accessOffset, data):
if accessOffset < self.outputAddressBase:
return False
# Just pret... | return None | conditional_block |
main.py | # -*- coding: utf-8 -*-
#
# AWL simulator - Dummy hardware interface
#
# Copyright 2013-2014 Michael Buesch <m@bues.ch>
#
# 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 ... |
def readInputs(self):
pass # Do nothing
def writeOutputs(self):
pass # Do nothing
def directReadInput(self, accessWidth, accessOffset):
if accessOffset < self.inputAddressBase:
return None
# Just read the current value from the CPU and return it.
return self.sim.cpu.fetch(AwlOperator(AwlOperator.MEM... | pass # Do nothing | identifier_body |
main.py | # -*- coding: utf-8 -*-
#
# AWL simulator - Dummy hardware interface
#
# Copyright 2013-2014 Michael Buesch <m@bues.ch>
#
# 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 ... | parameters = parameters)
def doStartup(self):
pass # Do nothing
def doShutdown(self):
pass # Do nothing
def readInputs(self):
pass # Do nothing
def writeOutputs(self):
pass # Do nothing
def directReadInput(self, accessWidth, accessOffset):
if accessOffset < self.inputAddressBase:
return ... | def __init__(self, sim, parameters={}):
AbstractHardwareInterface.__init__(self,
sim = sim, | random_line_split |
textattributes.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | use gtk::ffi;
pub struct TextAttributes {
pointer: *mut ffi::C_GtkTextAttributes
}
impl TextAttributes {
pub fn new() -> Option<TextAttributes> {
let tmp_pointer = unsafe { ffi::gtk_text_attributes_new() };
if tmp_pointer.is_null() {
None
} else {
Some(TextAttr... |
//! GtkTextTag — A tag that can be applied to text in a GtkTextBuffer
| random_line_split |
textattributes.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | }
}
impl_GObjectFunctions!(TextAttributes, C_GtkTextAttributes) | Some(TextAttributes { pointer : tmp_pointer })
}
| conditional_block |
textattributes.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | self) -> Option<TextAttributes> {
let tmp_pointer = unsafe { ffi::gtk_text_attributes_ref(self.pointer) };
if tmp_pointer.is_null() {
None
} else {
Some(TextAttributes { pointer : tmp_pointer })
}
}
}
impl_GObjectFunctions!(TextAttributes, C_GtkTextAttribute... | ef(& | identifier_name |
validator.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# 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 applica... |
for s in strings:
if not isinstance(getattr(event, s), basestring):
raise SynapseError(400, "Not '%s' a string type" % (s,))
if event.type == EventTypes.Member:
if "membership" not in event.content:
raise SynapseError(400, "Content has not membe... | strings.append("state_key") | conditional_block |
validator.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# 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 applica... | (self, event):
EventID.from_string(event.event_id)
RoomID.from_string(event.room_id)
required = [
# "auth_events",
"content",
# "hashes",
"origin",
# "prev_events",
"sender",
"type",
]
for k in ... | validate | identifier_name |
validator.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# 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 applica... | UserID.from_string(event.sender)
if event.type == EventTypes.Message:
strings = [
"body",
"msgtype",
]
self._ensure_strings(event.content, strings)
elif event.type == EventTypes.Topic:
self._ensure_strings(event.c... | random_line_split | |
validator.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# 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 applica... | def validate(self, event):
EventID.from_string(event.event_id)
RoomID.from_string(event.room_id)
required = [
# "auth_events",
"content",
# "hashes",
"origin",
# "prev_events",
"sender",
"type",
]
... | identifier_body | |
FastBloomFilter.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from FastBitSet import FastBitSet
import math
import mmh3
class FastBloomFilter(object):
mask32 = 0xffffffff
mask64 = 0xffffffffffffffff
mask128 = 0xffffffffffffffffffffffffffffffff
seeds = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29, ... |
return hashs
def hashs2(self, s, k):
bitSetLength = self.bitSetLength
mask = self.mask32
hashs = []
hash1 = mmh3.hash64(s, 0)
hash2 = mmh3.hash64(s, hash1)
for i in k:
hashs.append(((hash1 + i * hash2) % bitSetLength) & ma... | hashs.append((mmh3.hash128(s, seeds[i]) & mask) % bitSetLength) | conditional_block |
FastBloomFilter.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from FastBitSet import FastBitSet
import math
import mmh3
class FastBloomFilter(object):
mask32 = 0xffffffff
mask64 = 0xffffffffffffffff
mask128 = 0xffffffffffffffffffffffffffffffff
seeds = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29, ... |
def hashs2(self, s, k):
bitSetLength = self.bitSetLength
mask = self.mask32
hashs = []
hash1 = mmh3.hash64(s, 0)
hash2 = mmh3.hash64(s, hash1)
for i in k:
hashs.append(((hash1 + i * hash2) % bitSetLength) & mask)
return ha... | bitSetLength = self.bitSetLength
#mask = self.mask32
mask = self.mask128
seeds = self.seeds
hashs = []
for i in range(k):
#print(mmh3.hash64(s, seeds[i]))
#hashs.append((mmh3.hash(s, seeds[i]) & mask) % bitSetLength)
hashs.app... | identifier_body |
FastBloomFilter.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from FastBitSet import FastBitSet
import math
import mmh3
class FastBloomFilter(object):
mask32 = 0xffffffff
mask64 = 0xffffffffffffffff
mask128 = 0xffffffffffffffffffffffffffffffff
seeds = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29, ... | (self, n, fpr=0.00001):
m = -1 * math.log(fpr, math.e) * n / math.pow(math.log(2, math.e), 2)
k = (m / n) * math.log(2, math.e)
self.n = int(math.ceil(n))
self.fpr = fpr
self.m = int(math.ceil(m))
self.k = int(k)
self.bsUnitSize = 64
... | __init__ | identifier_name |
FastBloomFilter.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from FastBitSet import FastBitSet
import math
import mmh3
class FastBloomFilter(object):
mask32 = 0xffffffff
mask64 = 0xffffffffffffffff
mask128 = 0xffffffffffffffffffffffffffffffff
seeds = [2, 3, 5, 7, 11,
13, 17, 19, 23, 29, ... | self.n = int(math.ceil(n))
self.fpr = fpr
self.m = int(math.ceil(m))
self.k = int(k)
self.bsUnitSize = 64
self.bsCap = int(math.ceil(self.m / 64))
self.bitSet = FastBitSet(self.bsCap, self.bsUnitSize)
self.bitSetLength = self.bitSet.length
... | random_line_split | |
react-docgen-test.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*global ja... | (args, stdin) {
return new Promise(resolve => {
var docgen = spawn( // eslint-disable-line camelcase
path.join(__dirname, '../react-docgen.js'),
args
);
var stdout = '';
var stderr = '';
docgen.stdout.on('data', data => stdout += data);
docgen.stderr.on('data', data => stderr += da... | run | identifier_name |
react-docgen-test.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*global ja... | expect(stdout).toContain('Component');
expect(stderr).toContain('NoComponent');
}
);
});
pit('reads directories provided as command line arguments', () => {
tempDir = createTempfiles();
return run([tempDir]).then(([stdout, stderr]) => {
expect(stdout).toContain('Component');... | ([stdout, stderr]) => { | random_line_split |
react-docgen-test.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*global ja... |
afterEach(() => {
if (tempDir) {
rimraf.sync(tempDir);
}
tempDir = null;
tempComponents.length = 0;
tempNoComponents.length = 0;
});
pit('reads from stdin', () => {
return run([], component).then(([stdout, stderr]) => {
expect(stdout.length > 0).toBe(true);
expect(stde... | {
if (!tempDir) {
tempDir = temp.mkdirSync();
}
if (!dir) {
dir = tempDir;
} else {
dir = path.join(tempDir, dir);
try {
fs.mkdirSync(dir);
} catch(error) {
if (error.message.indexOf('EEXIST') === -1) {
throw error;
}
}
}
if (... | identifier_body |
react-docgen-test.js | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/*global ja... |
if (!dir) {
dir = tempDir;
} else {
dir = path.join(tempDir, dir);
try {
fs.mkdirSync(dir);
} catch(error) {
if (error.message.indexOf('EEXIST') === -1) {
throw error;
}
}
}
if (!suffix) {
suffix = 'js';
}
var componentPath ... | {
tempDir = temp.mkdirSync();
} | conditional_block |
managers.py | # -*- coding: utf-8 -*-
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
from django.contrib.gis.db import models
class AOIManager(models.GeoManager):
def ... |
def unassigned(self):
"""
Returns unassigned AOIs.
"""
return self.add_filters(status='Unassigned')
def assigned(self):
"""
Returns assigned AOIs.
"""
return self.add_filters(status='Assigned')
def in_work(self):
"""
Returns... | """
Returns the queryset with new filters
"""
return super(AOIManager, self).get_query_set().filter(**kwargs) | identifier_body |
managers.py | # -*- coding: utf-8 -*-
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
from django.contrib.gis.db import models
class AOIManager(models.GeoManager):
def ... | Returns AOIs in work.
"""
return self.add_filters(status='In Work')
def submitted(self):
"""
Returns submitted AOIs.
"""
return self.add_filters(status='Submitted')
def completed(self):
"""
Returns completed AOIs.
"""
retu... |
def in_work(self):
""" | random_line_split |
managers.py | # -*- coding: utf-8 -*-
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
from django.contrib.gis.db import models
class AOIManager(models.GeoManager):
def ... | (self):
"""
Returns completed AOIs.
"""
return self.add_filters(status='Completed')
| completed | identifier_name |
collection-test.js | /* file : collection-test.js
MIT License
Copyright (c) 2016 Thomas Minier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy... | }); | random_line_split | |
models.py | import logging
import os
import datetime
import six
import humanfriendly
from pathlib import Path
from django.db import models
from django.utils.html import format_html
from django.utils.encoding import uri_to_iri
from django.core.management import call_command
from django.utils.safestring import mark_safe
from django.... | video_format.short_description = '视频文件格式'
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = uuslug(instance.title, instance=instance)
def post_init_receiver(sender, instance, *args, **kwargs):
pass
pre_save.connect(pre_save_post_receiver, send... | color_code,
suffix
)
| random_line_split |
models.py | import logging
import os
import datetime
import six
import humanfriendly
from pathlib import Path
from django.db import models
from django.utils.html import format_html
from django.utils.encoding import uri_to_iri
from django.core.management import call_command
from django.utils.safestring import mark_safe
from django.... | = '是否激活'
def video_format(self):
suffix = Path(self.video.name).suffix
color_code = 'green' if suffix in ['.mp4', '.m3u8'] else 'red'
return format_html(
'<span style="color:{};">{}</span>',
color_code,
suffix
)
video_format.short_description... | t_description | identifier_name |
models.py | import logging
import os
import datetime
import six
import humanfriendly
from pathlib import Path
from django.db import models
from django.utils.html import format_html
from django.utils.encoding import uri_to_iri
from django.core.management import call_command
from django.utils.safestring import mark_safe
from django.... | image.path):
return mark_safe('<img src="%s" width="160" height="90" />' % (self.image.url))
else:
return mark_safe('<img src="#" width="160" height="90" />')
else:
return mark_safe('<img src="%s" width="160" height="90" />' % (settings.DEFAULT_IMAGE_SRC))... | if self.image is not None and str(self.image) != "":
if os.path.exists(self. | conditional_block |
models.py | import logging
import os
import datetime
import six
import humanfriendly
from pathlib import Path
from django.db import models
from django.utils.html import format_html
from django.utils.encoding import uri_to_iri
from django.core.management import call_command
from django.utils.safestring import mark_safe
from django.... | l == 2:
return '--'.join([self.subset.first().name, base_name])
else:
return base_name
def save(self, *args, **kwargs):
super(VideoCategory, self).save(*args, **kwargs)
def colored_level(self):
color_code = 'red' if self.level == 1 else 'green'
return fo... | str(' (level %d)' % (self.level))
if self.subset.first() and self.leve | identifier_body |
ais_pg_monthhistogram.py | #!/usr/bin/env python
__version__ = '$Revision: 4791 $'.split()[1]
__date__ = '$Date: 2007-01-04 $'.split()[1]
__author__ = 'Kurt Schwehr'
__doc__="""
Count the transits by ship type for each month. A transit is
associated with the first month that the vessel is observed.
@requires: U{epydoc<http://epydoc.sourcefor... |
workbook.save(options.basename+'.xls')
| col=0
ws_row+=1
ws.write(ws_row,col,category); col+=1
for i in range(1,13):
# FIX: double check that we want to be using integers
ws.write(ws_row,col,int(catCounts[category][i])); col+=1 | conditional_block |
ais_pg_monthhistogram.py | #!/usr/bin/env python
__version__ = '$Revision: 4791 $'.split()[1]
__date__ = '$Date: 2007-01-04 $'.split()[1]
__author__ = 'Kurt Schwehr'
__doc__="""
Count the transits by ship type for each month. A transit is
associated with the first month that the vessel is observed.
@requires: U{epydoc<http://epydoc.sourcefor... | if options.useNM:
sys.exit('ERROR: can not specify nm units when not in distance mode')
import psycopg2 as psycopg
connectStr = "dbname='"+options.databaseName+"' user='"+options.databaseUser+"' host='"+options.databaseHost+"'"
if verbose:
sys.stderr.write('CONNECT: '+connectS... | else:
options.basename+='-dist-km'
else: | random_line_split |
storage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary ... |
return value
if __name__ == '__main__':
import doctest
doctest.testmod()
| try:
value = cast(value)
except (ValueError, TypeError):
from http import HTTP, redirect
if otherwise is None:
raise HTTP(404)
elif isinstance(otherwise, str):
redirect(otherwise)
elif cal... | conditional_block |
storage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds | - Storage; like dictionary allowing also for `obj.foo` for `obj['foo']`
"""
try:
import cPickle as pickle
except:
import pickle
import copy_reg
import gluon.portalocker as portalocker
__all__ = ['List', 'Storage', 'Settings', 'Messages',
'StorageList', 'load_storage', 'save_storage']
DEFAULT = lam... | random_line_split | |
storage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary ... |
def getfirst(self, key, default=None):
"""
Returns the first value of a list or the value itself when given a
`request.vars` style key.
If the value is a list, its first item will be returned;
otherwise, the value will be returned as-is.
Example output for a query... | """
Returns a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, `[value]` will be returned.
Example output for a query string of `?x=abc&y=abc&y=def`::
>>> request = Storage()
... | identifier_body |
storage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary ... | (self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
def __getattr__(self, key):
return getattr(self, key) if key in self else None
def __getitem__(self, key):
return dict.get(self, key, None)
def copy(self):
self.__dict__ = {}
... | __init__ | identifier_name |
f10-read-timeout.rs | /// Figure 10.10: Calling read with a timeout
///
/// Takeaway: First I tried with the regular `signal` function of libc
/// only to find out that the alarm signal does not interrupt the read
/// call. Digging into the C code it got obvious that the signal function
/// gets overriden by `lib/signal.c` which is a "relia... |
alarm(0);
write(STDOUT_FILENO, as_void!(line), n as _);
}
}
| {
println!("read error!");
exit(1);
} | conditional_block |
f10-read-timeout.rs | /// Figure 10.10: Calling read with a timeout
///
/// Takeaway: First I tried with the regular `signal` function of libc
/// only to find out that the alarm signal does not interrupt the read
/// call. Digging into the C code it got obvious that the signal function | /// using POSIX sigaction()". But this function gets only introduced in
/// Figure 10.18. This was quite misleading IMO.
///
/// $ f10-read-timeout 2>&1
/// read error!
/// ERROR: return code 1
extern crate libc;
#[macro_use(as_void)]
extern crate apue;
use libc::{STDOUT_FILENO, STDIN_FILENO, SIGALRM, SIG_ERR, c_int}... | /// gets overriden by `lib/signal.c` which is a "reliable version of signal(), | random_line_split |
f10-read-timeout.rs | /// Figure 10.10: Calling read with a timeout
///
/// Takeaway: First I tried with the regular `signal` function of libc
/// only to find out that the alarm signal does not interrupt the read
/// call. Digging into the C code it got obvious that the signal function
/// gets overriden by `lib/signal.c` which is a "relia... | {
unsafe {
let line: [u8; MAXLINE] = std::mem::uninitialized();
if signal(SIGALRM, sig_alrm) == SIG_ERR {
panic!("signal(SIGALRM) error");
}
alarm(1);
let n = read(STDIN_FILENO, as_void!(line), MAXLINE);
if n < 0 {
println!("read error!");
... | identifier_body | |
f10-read-timeout.rs | /// Figure 10.10: Calling read with a timeout
///
/// Takeaway: First I tried with the regular `signal` function of libc
/// only to find out that the alarm signal does not interrupt the read
/// call. Digging into the C code it got obvious that the signal function
/// gets overriden by `lib/signal.c` which is a "relia... | () {
unsafe {
let line: [u8; MAXLINE] = std::mem::uninitialized();
if signal(SIGALRM, sig_alrm) == SIG_ERR {
panic!("signal(SIGALRM) error");
}
alarm(1);
let n = read(STDIN_FILENO, as_void!(line), MAXLINE);
if n < 0 {
println!("read error!");
... | main | identifier_name |
lookups.rs | /// this is a table lookup for all "flush" hands (e.g. both
/// flushes and straight-flushes. entries containing a zero
/// mean that combination is not possible with a five-card
/// flush hand.
pub const FLUSHES : [u16; 7937] = include!("snip/flushes.snip");
/// this is a table lookup for all non-flush hands consis... | [ 0, 1, 2, 4, 5 ],
[ 0, 1, 2, 4, 6 ],
[ 0, 1, 2, 5, 6 ],
[ 0, 1, 3, 4, 5 ],
[ 0, 1, 3, 4, 6 ],
[ 0, 1, 3, 5, 6 ],
[ 0, 1, 4, 5, 6 ],
[ 0, 2, 3, 4, 5 ],
[ 0, 2, 3, 4, 6 ],
[ 0, 2, 3, 5, 6 ],
[ 0, 2, 4, 5, 6 ],
[ 0, 3, 4, 5, 6 ],
[ 1, 2, 3, 4, 5 ],
[ 1, 2, 3, 4, 6 ],
[ 1, 2, 3, 5, 6 ],
[ 1... | [ 0, 1, 2, 3, 6 ], | random_line_split |
test.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
pub use crate::dom::bindings::str::{ByteString, DOMString};
pub use crate::dom::headers::normalize_value;
// For... | }
pub fn Node() -> usize {
size_of::<Node>()
}
pub fn Text() -> usize {
size_of::<Text>()
}
}
pub mod srcset {
pub use crate::dom::htmlimageelement::{parse_a_srcset_attribute, Descriptor, ImageSource};
}
pub mod timeranges {
pub use crate::dom::timeranges::TimeRangesConta... | pub fn HTMLSpanElement() -> usize {
size_of::<HTMLSpanElement>() | random_line_split |
test.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
pub use crate::dom::bindings::str::{ByteString, DOMString};
pub use crate::dom::headers::normalize_value;
// For... | () -> usize {
size_of::<HTMLSpanElement>()
}
pub fn Node() -> usize {
size_of::<Node>()
}
pub fn Text() -> usize {
size_of::<Text>()
}
}
pub mod srcset {
pub use crate::dom::htmlimageelement::{parse_a_srcset_attribute, Descriptor, ImageSource};
}
pub mod timeranges {
... | HTMLSpanElement | identifier_name |
test.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
pub use crate::dom::bindings::str::{ByteString, DOMString};
pub use crate::dom::headers::normalize_value;
// For... |
}
pub mod srcset {
pub use crate::dom::htmlimageelement::{parse_a_srcset_attribute, Descriptor, ImageSource};
}
pub mod timeranges {
pub use crate::dom::timeranges::TimeRangesContainer;
}
| {
size_of::<Text>()
} | identifier_body |
k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.py | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class K8sIoApi... |
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return sel... | result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
)) | conditional_block |
k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.py | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class K8sIoApi... | """
swagger_types = {
'paths': 'list[str]'
}
attribute_map = {
'paths': 'paths'
}
def __init__(self, paths=None):
"""
K8sIoApimachineryPkgApisMetaV1RootPaths - a model defined in Swagger
"""
self._paths = None
self.paths = paths
@p... | attribute_map (dict): The key is attribute name
and the value is json key in definition. | random_line_split |
k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.py | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class K8sIoApi... |
@property
def paths(self):
"""
Gets the paths of this K8sIoApimachineryPkgApisMetaV1RootPaths.
paths are the paths available at root.
:return: The paths of this K8sIoApimachineryPkgApisMetaV1RootPaths.
:rtype: list[str]
"""
return self._paths
@path... | """
K8sIoApimachineryPkgApisMetaV1RootPaths - a model defined in Swagger
"""
self._paths = None
self.paths = paths | identifier_body |
k8s_io_apimachinery_pkg_apis_meta_v1_root_paths.py | # coding: utf-8
"""
KubeVirt API
This is KubeVirt API an add-on for Kubernetes.
OpenAPI spec version: 1.0.0
Contact: kubevirt-dev@googlegroups.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class K8sIoApi... | (self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if ... | to_dict | identifier_name |
ReportController.js | angular.module('ReportModule', ['ngRoute']).
// config(['$locationProvider', function($locationProvider) {
// $locationProvider.html5Mode(true);
// }]).
controller('ReportController', ['$scope', '$http', '$location', function($scope, $http, $location) {
$scope.leasing = [];
$scope.service = [];
$scope.defaulter... | () {
$http.get('../res/php/reports.php?action=getRentDefaultersReport&selectedMonth='+lastMonth).
success(function(data) {
$scope.defaulter = data;
});
};
initLeasing();
initDefaulters();
initService();
}]); | initService | identifier_name |
ReportController.js | angular.module('ReportModule', ['ngRoute']).
// config(['$locationProvider', function($locationProvider) {
// $locationProvider.html5Mode(true);
// }]).
controller('ReportController', ['$scope', '$http', '$location', function($scope, $http, $location) {
$scope.leasing = [];
$scope.service = [];
$scope.defaulter... | ;
function initDefaulters() {
$http.get('../res/php/reports.php?action=getServiceReport&firstMonth='+firstMonth+"&lastMonth="+lastMonth).
success(function(data) {
$scope.service = data;
});
};
function initService() {
$http.get('../res/php/reports.php?action=getRentDefaultersReport&selectedMonth='+lastM... | {
$http.get('../res/php/reports.php?action=getLeasingReport&firstMonth='+(date.getMonth() - 5)+"&lastMonth="+(date.getMonth() + 1)).
success(function(data) {
$scope.leasing = data;
});
} | identifier_body |
ReportController.js | angular.module('ReportModule', ['ngRoute']).
// config(['$locationProvider', function($locationProvider) {
// $locationProvider.html5Mode(true);
// }]).
controller('ReportController', ['$scope', '$http', '$location', function($scope, $http, $location) {
$scope.leasing = [];
$scope.service = [];
$scope.defaulter... |
function initService() {
$http.get('../res/php/reports.php?action=getRentDefaultersReport&selectedMonth='+lastMonth).
success(function(data) {
$scope.defaulter = data;
});
};
initLeasing();
initDefaulters();
initService();
}]); | $scope.service = data;
});
}; | random_line_split |
queue_alt.rs | /*!
Heterogeneous Queue (alternative)
This version is hand-written (no macros) but has a simpler architecture
that allows implicit consumption by deconstruction on assignment.
# Example
```rust
use heterogene::queue_alt::{Q0,Q1,Q2};
let q = ();
let q = q.append(1u);
let q = q.append('c');
le... | (t1,(t2,()))
}
}
pub trait Q2<T1,T2> {
fn append<T3>(self, t3: T3) -> (T1,(T2,(T3,())));
}
impl<T1,T2> Q2<T1,T2> for (T1,(T2,())) {
fn append<T3>(self, t3: T3) -> (T1,(T2,(T3,()))) {
let(t1,(t2,_)) = self;
(t1,(t2,(t3,())))
}
} | fn append<T2>(self, t2: T2) -> (T1,(T2,())) {
let (t1,_) = self; | random_line_split |
queue_alt.rs | /*!
Heterogeneous Queue (alternative)
This version is hand-written (no macros) but has a simpler architecture
that allows implicit consumption by deconstruction on assignment.
# Example
```rust
use heterogene::queue_alt::{Q0,Q1,Q2};
let q = ();
let q = q.append(1u);
let q = q.append('c');
le... | <T2>(self, t2: T2) -> (T1,(T2,())) {
let (t1,_) = self;
(t1,(t2,()))
}
}
pub trait Q2<T1,T2> {
fn append<T3>(self, t3: T3) -> (T1,(T2,(T3,())));
}
impl<T1,T2> Q2<T1,T2> for (T1,(T2,())) {
fn append<T3>(self, t3: T3) -> (T1,(T2,(T3,()))) {
let(t1,(t2,_)) = self;
(t1,(t2,(t3,(... | append | identifier_name |
queue_alt.rs | /*!
Heterogeneous Queue (alternative)
This version is hand-written (no macros) but has a simpler architecture
that allows implicit consumption by deconstruction on assignment.
# Example
```rust
use heterogene::queue_alt::{Q0,Q1,Q2};
let q = ();
let q = q.append(1u);
let q = q.append('c');
le... |
}
pub trait Q2<T1,T2> {
fn append<T3>(self, t3: T3) -> (T1,(T2,(T3,())));
}
impl<T1,T2> Q2<T1,T2> for (T1,(T2,())) {
fn append<T3>(self, t3: T3) -> (T1,(T2,(T3,()))) {
let(t1,(t2,_)) = self;
(t1,(t2,(t3,())))
}
}
| {
let (t1,_) = self;
(t1,(t2,()))
} | identifier_body |
CutterPI.js | /**
* OpenEyes
*
* (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
* (C) OpenEyes Foundation, 2011-2013
* This file is part of OpenEyes.
* OpenEyes 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,... | * @class CutterPI
* @property {String} className Name of doodle subclass
* @param {Drawing} _drawing
* @param {Object} _parameterJSON
*/
ED.CutterPI = function(_drawing, _parameterJSON) {
// Set classname
this.className = "CutterPI";
// Saved parameters
this.savedParameterArray = ['rotation'];
// Call supe... | * | random_line_split |
transaction_map.rs | use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied,Vacant};
use primitive::{UInt256,Transaction};
#[derive(PartialEq)]
pub enum TransactionIndexStatus {
Init = 0,
Get = 1,
}
pub struct TransactionIndex {
status: TransactionIndexStatus,
hash: UInt256,
transaction: Option<... | pub fn get_hash(&self) -> &UInt256 { &self.hash }
pub fn get_transaction(&self) -> &Option<Transaction> { &self.transaction }
pub fn set_transaction(&mut self, transaction: Transaction) {
self.transaction = Some(transaction);
self.status = TransactionIndexStatus::Get;
}
pub fn ad... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.