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 |
|---|---|---|---|---|
lib.rs | // Copyright (C) 2020 Natanael Mojica <neithanmo@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later versio... |
gst_plugin_define!(
csound,
env!("CARGO_PKG_DESCRIPTION"),
plugin_init,
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
"MIT/X11",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_REPOSITORY"),
env!("BUILD_REL_DATE")
);
| {
filter::register(plugin)?;
Ok(())
} | identifier_body |
material.ts | import { Theme } from '../../themes/default';
import { StyleProps } from './default';
export const style = ({
theme,
main,
}: ThemedStyledProps<StyleProps, Theme>) => css`
display: flex;
flex: 0 0 1;
padding-left: 1px;
background-color: ${theme.base01};
width: 100%;
overflow: hidden;
${!main &&
`
... | import { css, ThemedStyledProps } from 'styled-components';
import { ripple } from '../../utils/animations'; | random_line_split | |
constantOverloadFunctionNoSubtypeError.js | //// [constantOverloadFunctionNoSubtypeError.ts]
class Base { foo() { } }
class Derived1 extends Base { bar() { } }
class Derived2 extends Base { baz() { } }
class Derived3 extends Base { biz() { } }
function foo(tagName: 'canvas'): Derived3;
function foo(tagName: 'div'): Derived2;
function foo(tagName: 'span'): Der... | var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Base = (function () {
function Base() {
}
Base.prototype.foo = function () {
... | random_line_split | |
constantOverloadFunctionNoSubtypeError.js | //// [constantOverloadFunctionNoSubtypeError.ts]
class Base { foo() { } }
class Derived1 extends Base { bar() { } }
class Derived2 extends Base { baz() { } }
class Derived3 extends Base { biz() { } }
function foo(tagName: 'canvas'): Derived3;
function foo(tagName: 'div'): Derived2;
function foo(tagName: 'span'): Der... | () { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var Base = (function () {
function Base() {
}
Base.prototype.foo = function () {
};
return Base;
})();
var Derived1 = (function (_super) {
__extends(Derived1, _super);
function Derived1()... | __ | identifier_name |
constantOverloadFunctionNoSubtypeError.js | //// [constantOverloadFunctionNoSubtypeError.ts]
class Base { foo() { } }
class Derived1 extends Base { bar() { } }
class Derived2 extends Base { baz() { } }
class Derived3 extends Base { biz() | }
function foo(tagName: 'canvas'): Derived3;
function foo(tagName: 'div'): Derived2;
function foo(tagName: 'span'): Derived1;
function foo(tagName: number): Base;
function foo(tagName: any): Base {
return null;
}
//// [constantOverloadFunctionNoSubtypeError.js]
var __extends = this.__extends || function (d... | { } | identifier_body |
nimbus_prod.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | (self, env, upgrade_type=None):
import params
env.set_params(params)
supervisord_service("nimbus", action="stop")
def status(self, env):
supervisord_check_status("nimbus")
def get_log_folder(self):
import params
return params.log_dir
def get_user(self):
import params
retu... | stop | identifier_name |
nimbus_prod.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
def start(self, env, upgrade_type=None):
import params
env.set_params(params)
self.configure(env)
supervisord_service("nimbus", action="start")
def stop(self, env, upgrade_type=None):
import params
env.set_params(params)
supervisord_service("nimbus", action="stop")
def status(sel... | import params
env.set_params(params)
if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version):
conf_select.select(params.stack_name, "storm", params.version)
stack_select.select("storm-client", params.version)
stack_select.select("storm-nimbus", params.version) | identifier_body |
nimbus_prod.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | Nimbus().execute() | conditional_block | |
nimbus_prod.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | stack_select.select("storm-nimbus", params.version)
def start(self, env, upgrade_type=None):
import params
env.set_params(params)
self.configure(env)
supervisord_service("nimbus", action="start")
def stop(self, env, upgrade_type=None):
import params
env.set_params(params)
super... | env.set_params(params)
if params.version and check_stack_feature(StackFeature.ROLLING_UPGRADE, params.version):
conf_select.select(params.stack_name, "storm", params.version)
stack_select.select("storm-client", params.version) | random_line_split |
__init__.py | """Support for Xiaomi Gateways."""
from datetime import timedelta
import logging
import voluptuous as vol
from xiaomi_gateway import XiaomiGateway, XiaomiGatewayDiscovery
from homeassistant import config_entries, core
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_ID,
ATTR_VOLTAGE,
... | (event):
"""Stop Xiaomi Socket."""
_LOGGER.debug("Shutting down Xiaomi Gateway Listener")
gateway_discovery.stop_listen()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_xiaomi)
gateway_discovery.gateways[entry.data[CONF_HOST]] = xiaomi_gateway
_LOGGER.deb... | stop_xiaomi | identifier_name |
__init__.py | """Support for Xiaomi Gateways."""
from datetime import timedelta
import logging
import voluptuous as vol
from xiaomi_gateway import XiaomiGateway, XiaomiGatewayDiscovery
from homeassistant import config_entries, core
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_ID,
ATTR_VOLTAGE,
... | if xiaomi_data is not None:
gateways = list(xiaomi_data[GATEWAYS_KEY].values())
# If the user has only 1 gateway, make it the default for services.
if len(gateways) == 1:
kwargs["default"] = gateways[0].sid
return schema.extend({vol.Required(ATTR_GW_MAC, **kwargs): gateway}... |
kwargs = {}
xiaomi_data = hass.data.get(DOMAIN) | random_line_split |
__init__.py | """Support for Xiaomi Gateways."""
from datetime import timedelta
import logging
import voluptuous as vol
from xiaomi_gateway import XiaomiGateway, XiaomiGatewayDiscovery
from homeassistant import config_entries, core
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_ID,
ATTR_VOLTAGE,
... |
def stop_ringtone_service(call):
"""Service to stop playing ringtone on Gateway."""
gateway = call.data.get(ATTR_GW_MAC)
gateway.write_to_hub(gateway.sid, mid=10000)
def add_device_service(call):
"""Service to add a new sub-device within the next 30 seconds."""
gateway... | """Service to play ringtone through Gateway."""
ring_id = call.data.get(ATTR_RINGTONE_ID)
gateway = call.data.get(ATTR_GW_MAC)
kwargs = {"mid": ring_id}
ring_vol = call.data.get(ATTR_RINGTONE_VOL)
if ring_vol is not None:
kwargs["vol"] = ring_vol
gateway.wr... | identifier_body |
__init__.py | """Support for Xiaomi Gateways."""
from datetime import timedelta
import logging
import voluptuous as vol
from xiaomi_gateway import XiaomiGateway, XiaomiGatewayDiscovery
from homeassistant import config_entries, core
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
ATTR_DEVICE_ID,
ATTR_VOLTAGE,
... |
raise vol.Invalid(f"Unknown gateway sid {sid}")
kwargs = {}
xiaomi_data = hass.data.get(DOMAIN)
if xiaomi_data is not None:
gateways = list(xiaomi_data[GATEWAYS_KEY].values())
# If the user has only 1 gateway, make it the default for services.
if len(gateways) == 1:
... | if gateway.sid == sid:
return gateway | conditional_block |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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 ap... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// TypeScript Version: 2.0
/**
* Boolean indicating if the current environment is a touch device.
*
* @example
* var bool = IS_TOUCH_DEVI... | * distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
views.py | from django.shortcuts import render
# Create your views here.
from .models import Course, Student, StudentCourse
from .serializers import CourseSerializer, StudentSerialiser
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response... |
return Response({'success': True})
class CourseViewSet(viewsets.ModelViewSet):
queryset = Course.objects.all()
serializer_class = CourseSerializer
def get_queryset(self):
result = super(CourseViewSet, self).get_queryset()
username = self.request.GET.get('username', None)
... | Student.objects.get_or_create(nickname=username) | conditional_block |
views.py | from django.shortcuts import render
# Create your views here.
from .models import Course, Student, StudentCourse
from .serializers import CourseSerializer, StudentSerialiser
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response... | (self, request, pk=None):
username = request.GET.get('username', None)
user = Student.objects.get(nickname=username)
course = Course.objects.get(id=pk)
student_course, created = StudentCourse.objects.get_or_create(student=user, course=course)
StudentCourse.objects.filter(student=... | start | identifier_name |
views.py | from django.shortcuts import render
|
from .serializers import CourseSerializer, StudentSerialiser
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = Student... | # Create your views here.
from .models import Course, Student, StudentCourse | random_line_split |
views.py | from django.shortcuts import render
# Create your views here.
from .models import Course, Student, StudentCourse
from .serializers import CourseSerializer, StudentSerialiser
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response... | username = request.GET.get('username', None)
user = Student.objects.get(nickname=username)
course = Course.objects.get(id=pk)
student_course, created = StudentCourse.objects.get_or_create(student=user, course=course)
StudentCourse.objects.filter(student=user).update(active=False)
... | identifier_body | |
spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... | (object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
... | FakeSecHead | identifier_name |
spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... | print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_walle... | address_summary = list_available(bitcoind)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1: | random_line_split |
spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... |
def create_tx(bitcoind, fromaddresses, toaddress, amount, fee):
all_coins = list_available(bitcoind)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coi... | outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed) | identifier_body |
spendfrom.py | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... |
rawtx = bitcoind.createrawtransaction(inputs, outputs)
signed_rawtx = bitcoind.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(bitcoind, txinfo)... | change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount) | conditional_block |
ne.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// macro_rules! partial_eq_impl {
// ($($t:ty)*) => ($(
// #[stable(feature = "rust1", since = "1.0.0")]
// impl PartialEq for $t {
// #[inline]
// fn eq(&self, othe... | () {
let v1: bool = false;
{
let result: bool = v1.ne(&v1);
assert_eq!(result, false);
}
let v2: bool = true;
{
let result: bool = v1.ne(&v2);
assert_eq!(result, true);
}
}
#[test]
fn ne_test2() {
ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 };
}
}
| ne_test1 | identifier_name |
ne.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// macro_rules! partial_eq_impl {
// ($($t:ty)*) => ($(
// #[stable(feature = "rust1", since = "1.0.0")]
// impl PartialEq for $t {
// #[inline]
// fn eq(&self, othe... | let v2: $t = 100 as $t;
{
let result: bool = v1.ne(&v2);
assert_eq!(result, true);
}
})*)
}
#[test]
fn ne_test1() {
let v1: bool = false;
{
let result: bool = v1.ne(&v1);
assert_eq!(result, false);
}
let v2: bool = true;
{
let result: bool = v1.ne(&v2);
assert_... | {
let result: bool = v1.ne(&v1);
assert_eq!(result, false);
}
| random_line_split |
ne.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
// macro_rules! partial_eq_impl {
// ($($t:ty)*) => ($(
// #[stable(feature = "rust1", since = "1.0.0")]
// impl PartialEq for $t {
// #[inline]
// fn eq(&self, othe... |
}
| {
ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 };
} | identifier_body |
editor-socketio-server.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var TextOperation = require('./text-operation');
var WrappedOperation = require('./wrapped-operation');
var Server = require('./server');
var Selection = require('./selection');
var util = require('util');
var LZString = require('lz-string');
var logger... |
util.inherits(EditorSocketIOServer, Server);
extend(EditorSocketIOServer.prototype, EventEmitter.prototype);
function extend(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
EditorSocketIOServer.prototype.addClient = f... | {
EventEmitter.call(this);
Server.call(this, document, operations);
this.users = {};
this.docId = docId;
this.mayWrite = mayWrite || function (_, cb) {
cb(true);
};
this.operationCallback = operationCallback;
} | identifier_body |
editor-socketio-server.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var TextOperation = require('./text-operation');
var WrappedOperation = require('./wrapped-operation');
var Server = require('./server');
var Selection = require('./selection');
var util = require('util');
var LZString = require('lz-string');
var logger... | (target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
EditorSocketIOServer.prototype.addClient = function (socket) {
var self = this;
socket.join(this.docId);
var docOut = {
str: this.document,
rev... | extend | identifier_name |
editor-socketio-server.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var TextOperation = require('./text-operation');
var WrappedOperation = require('./wrapped-operation');
var Server = require('./server');
var Selection = require('./selection');
var util = require('util');
var LZString = require('lz-string');
var logger... |
self.updateSelection(socket, obj && Selection.fromJSON(obj));
});
});
socket.on('disconnect', function () {
//console.log("Disconnect");
socket.leave(self.docId);
self.onDisconnect(socket);
/*
if (socket.manager && socket.manager.sockets.clients(self.... | {
console.log("User doesn't have the right to edit.");
return;
} | conditional_block |
editor-socketio-server.js | 'use strict';
var EventEmitter = require('events').EventEmitter;
var TextOperation = require('./text-operation');
var WrappedOperation = require('./wrapped-operation');
var Server = require('./server');
var Selection = require('./selection');
var util = require('util');
var LZString = require('lz-string');
var logger... | module.exports = EditorSocketIOServer; | var clientId = socket.id;
delete this.users[clientId];
socket.broadcast.to(this.docId).emit('client_left', clientId);
};
| random_line_split |
webpack.config.js | const webpack = require('atool-build/lib/webpack');
module.exports = function (webpackConfig, env) {
webpackConfig.babel.plugins.push('transform-runtime');
webpackConfig.babel.plugins.push(['import', {
libraryName: 'antd',
style: 'css' // if true, use less
}]);
// Support hmr
if (env === 'developmen... |
if (loader.test.toString() === '/\\.module\\.css$/') {
loader.exclude = /node_modules/;
loader.test = /\.css$/;
}
});
return webpackConfig;
};
| {
loader.include = /node_modules/;
loader.test = /\.css$/;
} | conditional_block |
webpack.config.js | const webpack = require('atool-build/lib/webpack');
module.exports = function (webpackConfig, env) {
webpackConfig.babel.plugins.push('transform-runtime');
webpackConfig.babel.plugins.push(['import', {
libraryName: 'antd',
style: 'css' // if true, use less
}]);
// Support hmr
if (env === 'developmen... | return webpackConfig;
}; | random_line_split | |
mod.rs | extern crate rmp;
use std;
quick_error! {
#[derive(Debug)]
pub enum DBError {
Protocol(err: String) {
description("Protocol error")
display("Protocol error: {}", err)
}
FileFormat(err: String) {
description("File fromat error")
display("F... | description("IO error")
display("IO error: {}", err)
from()
cause(err)
}
}
} | random_line_split | |
if-check-panic.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 ... | else {
return even(x - 2);
}
}
fn foo(x: usize) {
if even(x) {
println!("{}", x);
} else {
panic!("Number is odd");
}
}
fn main() {
foo(3);
}
| {
return true;
} | conditional_block |
if-check-panic.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 ... | println!("{}", x);
} else {
panic!("Number is odd");
}
}
fn main() {
foo(3);
} |
fn foo(x: usize) {
if even(x) { | random_line_split |
if-check-panic.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 ... | (x: usize) {
if even(x) {
println!("{}", x);
} else {
panic!("Number is odd");
}
}
fn main() {
foo(3);
}
| foo | identifier_name |
if-check-panic.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 ... |
fn foo(x: usize) {
if even(x) {
println!("{}", x);
} else {
panic!("Number is odd");
}
}
fn main() {
foo(3);
}
| {
if x < 2 {
return false;
} else if x == 2 {
return true;
} else {
return even(x - 2);
}
} | identifier_body |
selectnav.js | /*
JavaScript Dynamic Select Navigation v1.0.0
by Todd Motto: http://www.toddmotto.com
Latest version: https://github.com/toddmotto/selectnav
Copyright 2013 Todd Motto
Licensed under the MIT license
http://www.opensource.org/licenses/mit-license.php
Dynamically creates a select menu with nested capab... | () {
var select = document.createElement('select');
var first = document.createElement('option');
first.innerHTML = 'Navigation';
first.setAttribute('selected', 'selected');
select.setAttribute('id', 'mobile');
select.appendChild(first);
var nav = document.getElementById('nav');
var loadLinks = fu... | selectnav | identifier_name |
selectnav.js | /*
JavaScript Dynamic Select Navigation v1.0.0
by Todd Motto: http://www.toddmotto.com
Latest version: https://github.com/toddmotto/selectnav
Copyright 2013 Todd Motto
Licensed under the MIT license
http://www.opensource.org/licenses/mit-license.php
Dynamically creates a select menu with nested capab... | } | random_line_split | |
selectnav.js | /*
JavaScript Dynamic Select Navigation v1.0.0
by Todd Motto: http://www.toddmotto.com
Latest version: https://github.com/toddmotto/selectnav
Copyright 2013 Todd Motto
Licensed under the MIT license
http://www.opensource.org/licenses/mit-license.php
Dynamically creates a select menu with nested capab... |
} | {
if(mobile.addEventListener) {
mobile.addEventListener('change', function () {
window.location.href = mobile.options[mobile.selectedIndex].value;
});
} else if(mobile.attachEvent) {
mobile.attachEvent('onchange', function () {
window.location.href = mobile.options[mobile.selectedIndex].valu... | conditional_block |
selectnav.js | /*
JavaScript Dynamic Select Navigation v1.0.0
by Todd Motto: http://www.toddmotto.com
Latest version: https://github.com/toddmotto/selectnav
Copyright 2013 Todd Motto
Licensed under the MIT license
http://www.opensource.org/licenses/mit-license.php
Dynamically creates a select menu with nested capab... | {
var select = document.createElement('select');
var first = document.createElement('option');
first.innerHTML = 'Navigation';
first.setAttribute('selected', 'selected');
select.setAttribute('id', 'mobile');
select.appendChild(first);
var nav = document.getElementById('nav');
var loadLinks = funct... | identifier_body | |
get_unique.py | """
get_unique.py
USAGE: get_unique.py [-h] [--sarcastic_path SARCASTIC_PATH]
[--non_sarcastic_path NON_SARCASTIC_PATH]
Create one json file with unique tweets
optional arguments:
-h, --help show this help message and exit
--sarcastic_path
path to directory... |
if args.non_sarcastic_path:
if not os.path.exists(args.non_sarcastic_path):
raise Exception("Invalid path: {}".format(args.non_sarcastic_path))
top_lvl_paths_lst.append(args.non_sarcastic_path)
# set static filenames
FN_HASH = "hash_dict.json"
FN_UNIQUE = "unique.json"
... | if not os.path.exists(args.sarcastic_path):
raise Exception("Invalid path: {}".format(args.sarcastic_path))
top_lvl_paths_lst.append(args.sarcastic_path) | conditional_block |
get_unique.py | """
get_unique.py
USAGE: get_unique.py [-h] [--sarcastic_path SARCASTIC_PATH]
[--non_sarcastic_path NON_SARCASTIC_PATH]
Create one json file with unique tweets
optional arguments:
-h, --help show this help message and exit
--sarcastic_path
path to directory... | --non_sarcastic_path
path to directory of non sarcastic tweet jsons. Needs
trailing "/"
"""
import glob
import json
import os
import argparse
from json_io import list_to_json, list_from_json
if __name__ == "__main__":
# Setup CLA parser
parser = argparse.Argu... | trailing "/" | random_line_split |
mail.py | #
# Sending emails in combination
# with Motion surveillance software
#
# (c) Dr. Yves J. Hilpisch
# The Python Quants GmbH
#
import smtplib
from datetime import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def prompt(prompt):
|
fromaddr = 'rpi@hilpisch.com' # prompt("From: ")
toaddrs = 'yves@hilpisch.com' # prompt("To: ")
subject = 'Security Alert.' # prompt("Subject: ")
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = subject
# Add the From: and To: headers at the start!
# msg = ("From: %s\r\nTo: %s\r\n... | return raw_input(prompt).strip() | identifier_body |
mail.py | #
# Sending emails in combination
# with Motion surveillance software
#
# (c) Dr. Yves J. Hilpisch
# The Python Quants GmbH
#
import smtplib
from datetime import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def | (prompt):
return raw_input(prompt).strip()
fromaddr = 'rpi@hilpisch.com' # prompt("From: ")
toaddrs = 'yves@hilpisch.com' # prompt("To: ")
subject = 'Security Alert.' # prompt("Subject: ")
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = subject
# Add the From: and To: headers ... | prompt | identifier_name |
mail.py | #
# Sending emails in combination
# with Motion surveillance software
#
# (c) Dr. Yves J. Hilpisch
# The Python Quants GmbH
#
import smtplib
from datetime import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
def prompt(prompt):
return raw_input(prompt).strip()
fromad... | print text | random_line_split | |
twitter.js | social.addModule("twitter", null, {
name: "twitter",
oauth: {
version: '1.0',
authorize_uri: 'api.twitter.com/oauth/authorize',
reg_oauth_token: /oauth_token=([^&]+)(?:&oauth_verifier=([^&]+))?/,
request_token_uri: 'api.twitter.com/oauth/request_token',
access_token_uri: ... | scope: true
};
},
me: function(){
return this.verify_credential(true, false);
}
}
}); | screen_name: screenName,
include_entities: includeEntities || false
}, | random_line_split |
password_based_encryption.rs | extern crate rustc_serialize;
extern crate rncryptor;
use rustc_serialize::hex::FromHex;
use rncryptor::v3::types::{IV, Salt};
use rncryptor::v3::encryptor::Encryptor;
struct TestVector {
password: &'static str,
encryption_salt: &'static str,
hmac_salt: &'static str,
iv: &'static str,
plain_text: ... | encryption_salt: "0203040506070001",
hmac_salt: "0304050607080102",
iv: "0405060708090a0b0c0d0e0f00010203",
plain_text: "0123456789abcdef 01234567",
cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \
0203e01b bda5df2c a8a... | #[test]
fn more_than_one_block() {
test_vector(TestVector {
password: "thepassword", | random_line_split |
password_based_encryption.rs | extern crate rustc_serialize;
extern crate rncryptor;
use rustc_serialize::hex::FromHex;
use rncryptor::v3::types::{IV, Salt};
use rncryptor::v3::encryptor::Encryptor;
struct | {
password: &'static str,
encryption_salt: &'static str,
hmac_salt: &'static str,
iv: &'static str,
plain_text: &'static str,
cipher_text: &'static str,
}
fn test_vector(vector: TestVector) {
let encryption_salt = Salt(vector.encryption_salt.from_hex().unwrap());
let hmac_salt = Salt(v... | TestVector | identifier_name |
password_based_encryption.rs | extern crate rustc_serialize;
extern crate rncryptor;
use rustc_serialize::hex::FromHex;
use rncryptor::v3::types::{IV, Salt};
use rncryptor::v3::encryptor::Encryptor;
struct TestVector {
password: &'static str,
encryption_salt: &'static str,
hmac_salt: &'static str,
iv: &'static str,
plain_text: ... |
#[test]
fn multibyte_password() {
test_vector(TestVector {
password: "中文密码",
encryption_salt: "0304050607000102",
hmac_salt: "0405060708010203",
iv: "05060708090a0b0c0d0e0f0001020304",
plain_text: "23456789abcdef 0123456701",
cipher_text: "03010304 05060700 01020405... | {
test_vector(TestVector {
password: "thepassword",
encryption_salt: "0203040506070001",
hmac_salt: "0304050607080102",
iv: "0405060708090a0b0c0d0e0f00010203",
plain_text: "0123456789abcdef 01234567",
cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809... | identifier_body |
trait-bounds-sugar.rs | // Copyright 2013 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 ... | (_x: Box<Foo+Send>) {
}
fn b(_x: &'static Foo) { // should be same as &'static Foo+'static
}
fn c(x: Box<Foo+Share>) {
a(x); //~ ERROR expected bounds `Send`
}
fn d(x: &'static Foo+Share) {
b(x); //~ ERROR expected bounds `'static`
}
fn main() {}
| a | identifier_name |
trait-bounds-sugar.rs | // Copyright 2013 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 ... |
fn b(_x: &'static Foo) { // should be same as &'static Foo+'static
}
fn c(x: Box<Foo+Share>) {
a(x); //~ ERROR expected bounds `Send`
}
fn d(x: &'static Foo+Share) {
b(x); //~ ERROR expected bounds `'static`
}
fn main() {} | trait Foo {}
fn a(_x: Box<Foo+Send>) {
} | random_line_split |
trait-bounds-sugar.rs | // Copyright 2013 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 ... |
fn d(x: &'static Foo+Share) {
b(x); //~ ERROR expected bounds `'static`
}
fn main() {}
| {
a(x); //~ ERROR expected bounds `Send`
} | identifier_body |
controller-v2.ts | import { v4 as uuid } from "uuid";
import axios from "axios";
import Brakes from "brakes";
const stripeChargeUrl = "http://localhost:8099/charge";
const brake = new Brakes(chargeCreditCard, {
timeout: 150
});
// /api/payment/v2
export const routev2 = async (_, res) => {
const traceId = uuid();
const customerId... | {
const response = await axios.post(stripeChargeUrl, {
amount,
customerId,
traceId
});
return response.data.transactionId;
} | identifier_body | |
controller-v2.ts | import { v4 as uuid } from "uuid";
import axios from "axios";
import Brakes from "brakes";
const stripeChargeUrl = "http://localhost:8099/charge";
const brake = new Brakes(chargeCreditCard, {
timeout: 150
});
// /api/payment/v2
export const routev2 = async (_, res) => {
const traceId = uuid();
const customerId... | ({ amount, customerId, traceId }) {
const response = await axios.post(stripeChargeUrl, {
amount,
customerId,
traceId
});
return response.data.transactionId;
}
| chargeCreditCard | identifier_name |
controller-v2.ts | import { v4 as uuid } from "uuid";
import axios from "axios"; | timeout: 150
});
// /api/payment/v2
export const routev2 = async (_, res) => {
const traceId = uuid();
const customerId = "0815";
const amount = 15;
brake
.exec({ customerId, amount, traceId })
.then(() => res.json({ status: "completed", traceId }))
.catch(e => res.status(503).json({ error: e.me... | import Brakes from "brakes";
const stripeChargeUrl = "http://localhost:8099/charge";
const brake = new Brakes(chargeCreditCard, { | random_line_split |
Attachment.ts | /******************************************************************************
* Spine Runtimes Software License
* Version 2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install,... |
}
}
| {
return this == sourceAttachment;
} | identifier_body |
Attachment.ts | /******************************************************************************
* Spine Runtimes Software License
* Version 2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install,... | * use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete... | random_line_split | |
Attachment.ts | /******************************************************************************
* Spine Runtimes Software License
* Version 2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install,... | (slot: Slot, start: number, count: number, worldVertices: ArrayLike<number>, offset: number) {
count += offset;
let skeleton = slot.bone.skeleton;
let deformArray = slot.attachmentVertices;
let vertices = this.vertices;
let bones = this.bones;
if (... | computeWorldVerticesWith | identifier_name |
index.js | import React from 'react';
import { createElement } from 'react-faux-dom';
import {
event as lastEvent,
select,
svg,
time
} from 'd3';
import {
createUniqueID,
reduce,
calculateMargin,
createValueGenerator,
createDomainRangeGenerator,
defaultColors,
defaultStyles,
getAxisStyles,
createCircular... |
if (yTicks) {
axis.ticks(yTicks);
}
const group = root
.append('g')
.attr('class', 'y axis')
.attr('transform',
(yAxisOrientRight)
? `translate(${w}, 0)`
: 'translate(0, 0)');
group
.call(axis);
if (label) {
group
.append('... | {
axis
.tickPadding(10);
} | conditional_block |
index.js | import React from 'react';
import { createElement } from 'react-faux-dom';
import {
event as lastEvent,
select,
svg,
time
} from 'd3';
import {
createUniqueID,
reduce,
calculateMargin,
createValueGenerator,
createDomainRangeGenerator,
defaultColors,
defaultStyles,
getAxisStyles,
createCircular... |
createPoints({ root, x, y, colors }) {
const {
data,
xType,
yType,
mouseOverHandler,
mouseOutHandler,
mouseMoveHandler,
clickHandler
} = this.props;
/*
* We don't really need to do this, but it
* avoids obscure "this" below
*/
const calculateD... | random_line_split | |
index.js | import React from 'react';
import { createElement } from 'react-faux-dom';
import {
event as lastEvent,
select,
svg,
time
} from 'd3';
import {
createUniqueID,
reduce,
calculateMargin,
createValueGenerator,
createDomainRangeGenerator,
defaultColors,
defaultStyles,
getAxisStyles,
createCircular... | () {
return {
width: 200,
height: 150,
datePattern: '%d-%b-%y',
interpolate: 'linear',
axes: false,
xType: 'linear',
yType: 'linear',
lineColors: [],
axisLabels: {
x: '',
y: ''
},
mouseOverHandler: () => {},
mouseOutHandler: () ... | defaultProps | identifier_name |
index.js | import React from 'react';
import { createElement } from 'react-faux-dom';
import {
event as lastEvent,
select,
svg,
time
} from 'd3';
import {
createUniqueID,
reduce,
calculateMargin,
createValueGenerator,
createDomainRangeGenerator,
defaultColors,
defaultStyles,
getAxisStyles,
createCircular... |
createStyle() {
const {
style,
grid,
verticalGrid,
yAxisOrientRight
} = this.props;
const uid = this.uid;
const scope = `.line-chart-${uid}`;
const axisStyles = getAxisStyles(grid, verticalGrid, yAxisOrientRight);
const rules = merge({}, defaultStyles, style, axisSty... | {
const {
data,
xType,
yType,
mouseOverHandler,
mouseOutHandler,
mouseMoveHandler,
clickHandler
} = this.props;
/*
* We don't really need to do this, but it
* avoids obscure "this" below
*/
const calculateDate = (v) => this.parseDate(v);
con... | identifier_body |
B_Frame.py | from DemoFramework import DemoFramework
from LUIVerticalLayout import LUIVerticalLayout
from LUIFrame import LUIFrame
from LUILabel import LUILabel
from LUIButton import LUIButton
from LUIObject import LUIObject
import random
f = DemoFramework()
f.prepare_demo("LUIFrame") | # Constructor
f.add_constructor_parameter("width", "200")
f.add_constructor_parameter("height", "200")
f.add_constructor_parameter("innerPadding", "5")
f.add_constructor_parameter("scrollable", "False")
f.add_constructor_parameter("style", "UIFrame.Raised")
# Functions
# Events
f.construct_sourcecode("LUIFrame")
# C... | random_line_split | |
action.js | /**
* @author Krzysztof Winiarski
* @copyright (c) 2014 Krzysztof Winiarski
* @license MIT
*/
'use strict';
var support = require('../support');
var actionWrapper = require('./action-wrapper');
function validateTypeOfArrayRecords(array, name, type) {
if (!array || !array instanceof Array) {
throw new TypeE... |
}
function validateAction(config) {
if (!config.id || typeof config.id !== 'string' && config.id.length > 0) {
throw new TypeError('ResourceAction(config.id) needs to be a non empty string');
}
if (!config.handler || typeof config.handler !== 'function') {
throw new TypeError('ResourceAction(config.ha... | {
for (var i = 0, j = array.length; i < j; i++) {
if (typeof array[i] !== type) {
throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a ' + type);
}
}
} | conditional_block |
action.js | /**
* @author Krzysztof Winiarski
* @copyright (c) 2014 Krzysztof Winiarski
* @license MIT
*/
'use strict';
var support = require('../support');
var actionWrapper = require('./action-wrapper');
function validateTypeOfArrayRecords(array, name, type) |
function validateAction(config) {
if (!config.id || typeof config.id !== 'string' && config.id.length > 0) {
throw new TypeError('ResourceAction(config.id) needs to be a non empty string');
}
if (!config.handler || typeof config.handler !== 'function') {
throw new TypeError('ResourceAction(config.hand... | {
if (!array || !array instanceof Array) {
throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array');
} else {
for (var i = 0, j = array.length; i < j; i++) {
if (typeof array[i] !== type) {
throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a... | identifier_body |
action.js | /**
* @author Krzysztof Winiarski
* @copyright (c) 2014 Krzysztof Winiarski
* @license MIT
*/
'use strict';
var support = require('../support');
var actionWrapper = require('./action-wrapper');
function validateTypeOfArrayRecords(array, name, type) {
if (!array || !array instanceof Array) {
throw new TypeE... | * ResourceAction represents single action for selected resource. For example
* POST /resource/mount-path/action-path. Action must have handler function
* (from blueprints or user defined, eventually 404 NotImplemented error handler).
* Additionally ResourceAction may have policies registered.
* @param handler
* @... | random_line_split | |
action.js | /**
* @author Krzysztof Winiarski
* @copyright (c) 2014 Krzysztof Winiarski
* @license MIT
*/
'use strict';
var support = require('../support');
var actionWrapper = require('./action-wrapper');
function | (array, name, type) {
if (!array || !array instanceof Array) {
throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array');
} else {
for (var i = 0, j = array.length; i < j; i++) {
if (typeof array[i] !== type) {
throw new TypeError('ResourceAction(config.' + name + '[' + i... | validateTypeOfArrayRecords | identifier_name |
const-int-saturating-arith.rs | // run-pass
const INT_U32_NO: u32 = (42 as u32).saturating_add(2);
const INT_U32: u32 = u32::MAX.saturating_add(1);
const INT_U128: u128 = u128::MAX.saturating_add(1); | const INT_I128: i128 = i128::MAX.saturating_add(1);
const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1);
const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2);
const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2);
const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2);
const INT_I32_NEG_SUB: i32 = i32::MI... | random_line_split | |
const-int-saturating-arith.rs | // run-pass
const INT_U32_NO: u32 = (42 as u32).saturating_add(2);
const INT_U32: u32 = u32::MAX.saturating_add(1);
const INT_U128: u128 = u128::MAX.saturating_add(1);
const INT_I128: i128 = i128::MAX.saturating_add(1);
const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1);
const INT_U32_NO_SUB: u32 = (42 as u32).s... | {
assert_eq!(INT_U32_NO, 44);
assert_eq!(INT_U32, u32::MAX);
assert_eq!(INT_U128, u128::MAX);
assert_eq!(INT_I128, i128::MAX);
assert_eq!(INT_I128_NEG, i128::MIN);
assert_eq!(INT_U32_NO_SUB, 40);
assert_eq!(INT_U32_SUB, 0);
assert_eq!(INT_I32_NO_SUB, -44);
assert_eq!(INT_I32_NEG_SUB... | identifier_body | |
const-int-saturating-arith.rs | // run-pass
const INT_U32_NO: u32 = (42 as u32).saturating_add(2);
const INT_U32: u32 = u32::MAX.saturating_add(1);
const INT_U128: u128 = u128::MAX.saturating_add(1);
const INT_I128: i128 = i128::MAX.saturating_add(1);
const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1);
const INT_U32_NO_SUB: u32 = (42 as u32).s... | () {
assert_eq!(INT_U32_NO, 44);
assert_eq!(INT_U32, u32::MAX);
assert_eq!(INT_U128, u128::MAX);
assert_eq!(INT_I128, i128::MAX);
assert_eq!(INT_I128_NEG, i128::MIN);
assert_eq!(INT_U32_NO_SUB, 40);
assert_eq!(INT_U32_SUB, 0);
assert_eq!(INT_I32_NO_SUB, -44);
assert_eq!(INT_I32_NEG_... | main | identifier_name |
mod.rs | //! Seat handling and managing.
use std::cell::RefCell;
use std::rc::Rc;
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1;
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPoint... | if let Some(text_input_manager) = self.text_input_manager.as_ref() {
if seat_data.defunct {
seat_info.text_input = None;
} else if seat_info.text_input.is_none() {
seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager));
}
... |
// Handle text input. | random_line_split |
mod.rs | //! Seat handling and managing.
use std::cell::RefCell;
use std::rc::Rc;
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1;
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPoint... | else {
seat_info.keyboard = None;
}
// Handle touch.
if seat_data.has_touch && !seat_data.defunct {
if seat_info.touch.is_none() {
seat_info.touch = Some(Touch::new(&seat));
}
} else {
seat_info.touch = None;
}
... | {
if seat_info.keyboard.is_none() {
seat_info.keyboard = Keyboard::new(
&seat,
self.loop_handle.clone(),
seat_info.modifiers_state.clone(),
);
}
} | conditional_block |
mod.rs | //! Seat handling and managing.
use std::cell::RefCell;
use std::rc::Rc;
use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1;
use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPoint... | (&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) {
let detached_seat = seat.detach();
let position = self.seats.iter().position(|si| si.seat == detached_seat);
let index = position.unwrap_or_else(|| {
self.seats.push(SeatInfo::new(detached_seat));
self.seats.le... | process_seat_update | identifier_name |
folder_detector.py | import os
import numpy as np
import torch
from ..core import FaceDetector
class FolderDetector(FaceDetector):
'''This is a simple helper module that assumes the faces were detected already
(either previously or are provided as ground truth).
The class expects to find the bounding boxe... |
elif os.path.isfile(base_name + '.t7'):
detected_faces = torch.load(base_name + '.t7')
elif os.path.isfile(base_name + '.pth'):
detected_faces = torch.load(base_name + '.pth')
else:
raise FileNotFoundError
if not isinstance(detected_faces, li... | detected_faces = np.load(base_name + '.npy') | conditional_block |
folder_detector.py | import os
import numpy as np
import torch
from ..core import FaceDetector
class FolderDetector(FaceDetector):
'''This is a simple helper module that assumes the faces were detected already
(either previously or are provided as ground truth).
The class expects to find the bounding boxe... | (self):
return 0
| reference_y_shift | identifier_name |
folder_detector.py | import os
import numpy as np
import torch
from ..core import FaceDetector
class FolderDetector(FaceDetector):
'''This is a simple helper module that assumes the faces were detected already
(either previously or are provided as ground truth).
The class expects to find the bounding boxe... |
@property
def reference_x_shift(self):
return 0
@property
def reference_y_shift(self):
return 0
| return 195 | identifier_body |
folder_detector.py | import os
import numpy as np
import torch
from ..core import FaceDetector
class FolderDetector(FaceDetector):
'''This is a simple helper module that assumes the faces were detected already
(either previously or are provided as ground truth).
The class expects to find the bounding boxe... |
return detected_faces
@property
def reference_scale(self):
return 195
@property
def reference_x_shift(self):
return 0
@property
def reference_y_shift(self):
return 0 | if not isinstance(detected_faces, list):
raise TypeError
| random_line_split |
4_advanced.py | """
Advanced Examples
=================
In this section, we demonstrate how to go from the inner product to the
discrete approximation for some special cases. We also show how all
necessary operators are constructed for each case.
"""
####################################################
#
# Import Packages
# -... | # Constitive Relations and Differential Operators
# -----------------------------------------------
#
# Where :math:`\psi` and :math:`\phi` are scalar quantities,
# :math:`\vec{u}` and :math:`\vec{v}` are vector quantities, and
# :math:`\sigma` defines a constitutive relationship, we may need to derive
# discrete appro... | import matplotlib.pyplot as plt
##################################################### | random_line_split |
dns.js | // ___ ____ __ __
// / _ `/ _ \\ \ /
// \_,_/ .__/_\_\
// /_/
//
// 過去は未来によって変えられる。
//
// Copyright (c) 2014 Kenan Sulayman aka apx
//
// Based on third-party code:
//
// Copyright (c) 2010 Tom Hughes-Croucher
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
... | }); | });
})
process.stdout.write("\nStarted server: " + host + revlookup + ", using port " + port + "."); | random_line_split |
models.py | from contextlib import contextmanager
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.core import validators
from django.db import models
from django.utils import translation
from django.utils.encoding import sm... | (amo.models.ModelBase):
user = models.ForeignKey(UserProfile, related_name='notifications')
notification_id = models.IntegerField()
enabled = models.BooleanField(default=False)
class Meta:
db_table = 'users_notifications'
@staticmethod
def update_or_create(update={}, **kwargs):
... | UserNotification | identifier_name |
models.py | from contextlib import contextmanager
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.core import validators
from django.db import models
from django.utils import translation
from django.utils.encoding import sm... |
def get_url_path(self, src=None):
# See: bug 880767.
return '#'
def my_apps(self, n=8):
"""Returns n apps"""
qs = self.addons.filter(type=amo.ADDON_WEBAPP)
qs = order_by_translation(qs, 'name')
return qs[:n]
@amo.cached_property
def is_developer(self):... | return False | identifier_body |
models.py | from contextlib import contextmanager
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.core import validators
from django.db import models
from django.utils import translation
from django.utils.encoding import sm... |
self.save()
def purchase_ids(self):
"""
I'm special casing this because we use purchase_ids a lot in the site
and we are not caching empty querysets in cache-machine.
That means that when the site is first launched we are having a
lot of empty queries hit.
... | log.debug(u"User (%s) failed to log in" % self)
if self.failed_login_attempts < 16777216:
self.failed_login_attempts += 1 | conditional_block |
models.py | from contextlib import contextmanager
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.core import validators
from django.db import models
from django.utils import translation
from django.utils.encoding import sm... |
class UserForeignKey(models.ForeignKey):
"""
A replacement for models.ForeignKey('users.UserProfile').
This field uses UserEmailField to make form fields key off the user's email
instead of the primary key id. We also hook up autocomplete automatically.
"""
def __init__(self, *args, **kw):
... | from mkt.translations.query import order_by_translation
log = commonware.log.getLogger('z.users')
| random_line_split |
create_bidder_level_filter_set.py | #!/usr/bin/python
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def environment_type(s):
if s not in _VALID_ENVIRONMENTS:
raise argparse.ArgumentTypeError(
f'Invalid Environment specified: "{s}".')
return s
def format_type(s):
if s not in _VALID_FORMATS:
raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".')
return s
def... | raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity '
f'specified: "{s}".')
return s | random_line_split |
create_bidder_level_filter_set.py | #!/usr/bin/python
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | (s):
if s not in _VALID_PLATFORMS:
raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".')
return s
def valid_date(s):
try:
return datetime.strptime(s, _DATE_FORMAT).date()
except ValueError:
raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".')
pars... | platform_type | identifier_name |
create_bidder_level_filter_set.py | #!/usr/bin/python
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def environment_type(s):
if s not in _VALID_ENVIRONMENTS:
raise argparse.ArgumentTypeError(
f'Invalid Environment specified: "{s}".')
return s
def format_type(s):
if s not in _VALID_FORMATS:
raise argparse.ArgumentTypeError(f'Invalid Format specified: "{s}".')
return s
de... | if s not in _VALID_TIME_SERIES_GRANULARITIES:
raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity '
f'specified: "{s}".')
return s | identifier_body |
create_bidder_level_filter_set.py | #!/usr/bin/python
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
return s
def valid_date(s):
try:
return datetime.strptime(s, _DATE_FORMAT).date()
except ValueError:
raise argparse.ArgumentTypeError(f'Invalid date specified: "{s}".')
parser = argparse.ArgumentParser(
description=('Creates a bidder-level filter set with the specified '
... | raise argparse.ArgumentTypeError(f'Invalid Platform specified: "{s}".') | conditional_block |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, PipeTransform} from '@angular/core';
import {getPluralCategory, NgLocalization} from '../i18n/localiz... |
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale);
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
}
}
| {
throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
} | conditional_block |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, PipeTransform} from '@angular/core';
import {getPluralCategory, NgLocalization} from '../i18n/localiz... | * ### Example
*
* {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
*
* @publicApi
*/
@Pipe({name: 'i18nPlural', pure: true})
export class I18nPluralPipe implements PipeTransform {
constructor(private _localization: NgLocalization) {}
/**
* @param value the number to be formatted
... | * Maps a value to a string that pluralizes the value according to locale rules.
*
* @usageNotes
* | random_line_split |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, PipeTransform} from '@angular/core';
import {getPluralCategory, NgLocalization} from '../i18n/localiz... | (value: number, pluralMap: {[count: string]: string}, locale?: string): string {
if (value == null) return '';
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
const key = getPluralCategory(value, Object.keys(pluralMap), this... | transform | identifier_name |
global-position-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PositionStrategy} from './position-strategy';
import {OverlayRef} from '../overlay-ref';
/**
* A strategy ... | this._wrapper!.appendChild(element);
}
let styles = element.style;
let parentStyles = (element.parentNode as HTMLElement).style;
styles.position = this._cssPosition;
styles.marginTop = this._topOffset;
styles.marginLeft = this._leftOffset;
styles.marginBottom = this._bottomOffset;
... | if (!this._wrapper && element.parentNode) {
this._wrapper = this._document.createElement('div');
this._wrapper!.classList.add('cdk-global-overlay-wrapper');
element.parentNode.insertBefore(this._wrapper!, element); | random_line_split |
global-position-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PositionStrategy} from './position-strategy';
import {OverlayRef} from '../overlay-ref';
/**
* A strategy ... |
let styles = element.style;
let parentStyles = (element.parentNode as HTMLElement).style;
styles.position = this._cssPosition;
styles.marginTop = this._topOffset;
styles.marginLeft = this._leftOffset;
styles.marginBottom = this._bottomOffset;
styles.marginRight = this._rightOffset;
st... | {
this._wrapper = this._document.createElement('div');
this._wrapper!.classList.add('cdk-global-overlay-wrapper');
element.parentNode.insertBefore(this._wrapper!, element);
this._wrapper!.appendChild(element);
} | conditional_block |
global-position-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PositionStrategy} from './position-strategy';
import {OverlayRef} from '../overlay-ref';
/**
* A strategy ... | implements PositionStrategy {
/** The overlay to which this strategy is attached. */
private _overlayRef: OverlayRef;
private _cssPosition: string = 'static';
private _topOffset: string = '';
private _bottomOffset: string = '';
private _leftOffset: string = '';
private _rightOffset: string = '';
priva... | GlobalPositionStrategy | identifier_name |
global-position-strategy.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PositionStrategy} from './position-strategy';
import {OverlayRef} from '../overlay-ref';
/**
* A strategy ... |
/**
* Centers the overlay horizontally with an optional offset.
* Clears any previously set horizontal position.
*
* @param offset Overlay offset from the horizontal center.
*/
centerHorizontally(offset: string = ''): this {
this.left(offset);
this._justifyContent = 'center';
return thi... | {
this._height = value;
// When the height is 100%, we should reset the `top` and the offset,
// in order to ensure that the element is flush against the viewport edge.
if (value === '100%') {
this.top('0px');
}
return this;
} | identifier_body |
offlinequeue.py | # -*- coding: utf-8 -*-
"""
wakatime.offlinequeue
~~~~~~~~~~~~~~~~~~~~~
Queue for saving heartbeats while offline.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from time import sleep
from .compat import json
from .constants import ... | db_file = '.wakatime.db'
table_name = 'heartbeat_2'
args = None
configs = None
def __init__(self, args, configs):
self.args = args
self.configs = configs
def connect(self):
conn = sqlite3.connect(self._get_db_file(), isolation_level=None)
c = conn.cursor()
... | identifier_body | |
offlinequeue.py | # -*- coding: utf-8 -*-
"""
wakatime.offlinequeue
~~~~~~~~~~~~~~~~~~~~~
Queue for saving heartbeats while offline.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from time import sleep
from .compat import json
from .constants import ... | (object):
db_file = '.wakatime.db'
table_name = 'heartbeat_2'
args = None
configs = None
def __init__(self, args, configs):
self.args = args
self.configs = configs
def connect(self):
conn = sqlite3.connect(self._get_db_file(), isolation_level=None)
c = conn.cur... | Queue | identifier_name |
offlinequeue.py | # -*- coding: utf-8 -*-
"""
wakatime.offlinequeue
~~~~~~~~~~~~~~~~~~~~~
Queue for saving heartbeats while offline.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from time import sleep
from .compat import json
from .constants import ... | c.execute('SELECT * FROM {0} LIMIT 1'.format(self.table_name))
row = c.fetchone()
if row is not None:
id = row[0]
heartbeat = Heartbeat(json.loads(row[1]), self.args, self.configs, _clone=True)
c.execute('DELETE ... | c.execute('BEGIN IMMEDIATE') | random_line_split |
offlinequeue.py | # -*- coding: utf-8 -*-
"""
wakatime.offlinequeue
~~~~~~~~~~~~~~~~~~~~~
Queue for saving heartbeats while offline.
:copyright: (c) 2014 Alan Hamlett.
:license: BSD, see LICENSE for more details.
"""
import logging
import os
from time import sleep
from .compat import json
from .constants import ... |
heartbeats = []
count = 0
while count < limit:
heartbeat = self.pop()
if not heartbeat:
break
heartbeats.append(heartbeat)
count += 1
if count % HEARTBEATS_PER_REQUEST == 0:
yield heartbeats
... | limit = DEFAULT_SYNC_OFFLINE_ACTIVITY | conditional_block |
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from viaspider.settings import SUMMARY_LIMIT
class ViaspiderItem(scrapy.Item):
# define the fields for your item here like:
url = scrapy.Field()... | def __init__(self, source, response, seperator, bloginfo):
self.source = source
self.response = response
self.seperator = seperator
self.bloginfo = " " + self.seperator + " " + bloginfo
@property
def url(self):
return self.response.url
@property
... | identifier_body | |
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from viaspider.settings import SUMMARY_LIMIT
class ViaspiderItem(scrapy.Item):
# define the fields for your item here like:
url = scrapy.Field()... | self.bloginfo = " " + self.seperator + " " + bloginfo
@property
def url(self):
return self.response.url
@property
def title(self):
result = self.response.xpath('//head/title/text()').extract()[0].encode('utf-8')
if result.endswith(self.bloginfo):
... | class ItemParser(object):
def __init__(self, source, response, seperator, bloginfo):
self.source = source
self.response = response
self.seperator = seperator | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.