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 |
|---|---|---|---|---|
admin.py | from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
# Register your models here.
from accounts.models import (User,
ValidSMSCod... |
return user
class UserChangeForm(forms.ModelForm):
"""
A form for updating users. Includes all the fields on
the user, but replaces the password field with admin
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
field... | user.save() | conditional_block |
Logger.ts | import { EventEmitter } from 'events';
import {
Logger as BunyanLogger,
createLogger,
Stream,
LoggerOptions
} from 'bunyan';
import * as _ from 'lodash';
export type LogLevels = 'debug' | 'info' | 'warn' | 'error' | 'fatal'
function buildDevOpts(level?: LogLevels): Stream[] | null {
try {
let PrettyStre... | (msg: string, meta?: Object) {
this.log('error', msg, meta);
}
fatal(msg: string, meta?: Object) {
this.log('fatal', msg, meta);
}
log(level: LogLevels, msg: string, meta?: Object) {
if (meta) {
this.logger[level](meta, msg);
} else {
this.logger[level](msg);
}
}
}
export cl... | error | identifier_name |
Logger.ts | import { EventEmitter } from 'events';
import {
Logger as BunyanLogger,
createLogger,
Stream,
LoggerOptions
} from 'bunyan';
import * as _ from 'lodash';
export type LogLevels = 'debug' | 'info' | 'warn' | 'error' | 'fatal'
function buildDevOpts(level?: LogLevels): Stream[] | null {
try {
let PrettyStre... | }
info(msg: string, meta?: Object) {
this.log('info', msg, meta);
}
warn(msg: string, meta?: Object) {
this.log('warn', msg, meta);
}
error(msg: string, meta?: Object) {
this.log('error', msg, meta);
}
fatal(msg: string, meta?: Object) {
this.log('fatal', msg, meta);
}
log(level... | }
}
debug(msg: string, meta?: Object) {
this.log('debug', msg, meta); | random_line_split |
Logger.ts | import { EventEmitter } from 'events';
import {
Logger as BunyanLogger,
createLogger,
Stream,
LoggerOptions
} from 'bunyan';
import * as _ from 'lodash';
export type LogLevels = 'debug' | 'info' | 'warn' | 'error' | 'fatal'
function buildDevOpts(level?: LogLevels): Stream[] | null {
try {
let PrettyStre... |
warn(msg: string, meta?: Object) {
this.log('warn', msg, meta);
}
error(msg: string, meta?: Object) {
this.log('error', msg, meta);
}
fatal(msg: string, meta?: Object) {
this.log('fatal', msg, meta);
}
log(level: LogLevels, msg: string, meta?: Object) {
if (meta) {
this.logger[l... | {
this.log('info', msg, meta);
} | identifier_body |
Logger.ts | import { EventEmitter } from 'events';
import {
Logger as BunyanLogger,
createLogger,
Stream,
LoggerOptions
} from 'bunyan';
import * as _ from 'lodash';
export type LogLevels = 'debug' | 'info' | 'warn' | 'error' | 'fatal'
function buildDevOpts(level?: LogLevels): Stream[] | null {
try {
let PrettyStre... | else {
this.logger = createLogger({name});
}
}
debug(msg: string, meta?: Object) {
this.log('debug', msg, meta);
}
info(msg: string, meta?: Object) {
this.log('info', msg, meta);
}
warn(msg: string, meta?: Object) {
this.log('warn', msg, meta);
}
error(msg: string, meta?: Obje... | {
let streams = buildDevOpts(loggerOpts.level);
let opts: LoggerOptions = {name};
if (streams) {
opts.streams = streams;
}
this.logger = createLogger(opts);
} | conditional_block |
wav2png.py | #!/usr/bin/env python
#
# Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA
#
# Freesound is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | (percentage):
sys.stdout.write(str(percentage) + "% ")
sys.stdout.flush()
# process all files so the user can use wildcards like *.wav
def genimages(input_file, output_file_w, output_file_s, output_file_m, options):
args = (input_file, output_file_w, output_file_s, output_file_m, options.image_width,... | progress_callback | identifier_name |
wav2png.py | #!/usr/bin/env python
#
# Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA
#
# Freesound is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... |
def genimages(input_file, output_file_w, output_file_s, output_file_m, options):
args = (input_file, output_file_w, output_file_s, output_file_m, options.image_width, options.image_height,
options.fft_size, progress_callback, options.f_min, options.f_max, options.scale_exp, options.pallete)
print... | sys.stdout.write(str(percentage) + "% ")
sys.stdout.flush()
# process all files so the user can use wildcards like *.wav | identifier_body |
wav2png.py | #!/usr/bin/env python
#
# Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA
#
# Freesound is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | #
# Authors:
# See AUTHORS file.
#
# 03/10/2013: Modified from original code
import sys
from compmusic.extractors.imagelib.MelSpectrogramImage import create_wave_images
from processing import AudioProcessingException
'''
parser = optparse.OptionParser("usage: %prog [options] input-filename", conflict_handler="r... | #
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
netcopy.py | #!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt... |
def recieveInt(size, conn):
data = conn.recv(size)
b = bytearray(data)
if len(b) != size:
raise ValueError("Received invalid data")
value = 0
for i in range(0,size):
value = value << 8
value += b[i]
return value
def recieveString(conn):
s = ""
ch = ''
while True:
ch = conn.recv(1)
if ch == b'\x00'... | return s+b'\x00' | identifier_body |
netcopy.py | #!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt... | client.close()
def recieve():
port = DEFAULT_PORT
i = 2
while i < len(sys.argv):
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = int(sys.argv[i+1])
except ValueError:
printError("Invalid port: "+sys.argv[i+1])
return
i+=1
... | client.sendall(bytebuf)
size -= BUFSIZE
f.close()
| random_line_split |
netcopy.py | #!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt... | ():
print("Usage:\n"
"\t{0} -s [-p port] [receiver] [files...]\t- Send files to receiver\n"
"\t{0} -r [-p port]\t\t\t\t- Receive files"
.format(sys.argv[0][sys.argv[0].rfind(sep)+1:]))
if __name__ == "__main__":
main()
| usage | identifier_name |
netcopy.py | #!/usr/bin/env python
#Protocol:
# num_files:uint(4)
# repeat num_files times:
# filename:string
# size:uint(8)
# data:bytes(size)
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt... |
f.close()
client.close()
def recieve():
port = DEFAULT_PORT
i = 2
while i < len(sys.argv):
if sys.argv[i]=='-p':
if i+1 >= len(sys.argv):
printError("Expecting port after '-p'")
return
try:
port = int(sys.argv[i+1])
except ValueError:
printError("Invalid port: "+sys.argv[i+1])
... | bytebuf = bytearray(f.read(BUFSIZE))
client.sendall(bytebuf)
size -= BUFSIZE | conditional_block |
postPictureRatingHandler.ts | import Router from '@koa/router';
import { SQL } from 'sql-template-strings';
import { pool } from '../../database';
import { bodySchemaValidator } from '../../requestValidators';
import { authenticator } from '../../authenticator'; | router.post(
'/pictures/:id/rating',
authenticator(true),
bodySchemaValidator(
{
type: 'object',
required: ['stars'],
properties: {
stars: {
type: 'integer',
minimum: 1,
maximum: 5,
},
},
},
true,
... |
export function attachPostPictureRatingHandler(router: Router) { | random_line_split |
postPictureRatingHandler.ts | import Router from '@koa/router';
import { SQL } from 'sql-template-strings';
import { pool } from '../../database';
import { bodySchemaValidator } from '../../requestValidators';
import { authenticator } from '../../authenticator';
export function | (router: Router) {
router.post(
'/pictures/:id/rating',
authenticator(true),
bodySchemaValidator(
{
type: 'object',
required: ['stars'],
properties: {
stars: {
type: 'integer',
minimum: 1,
maximum: 5,
},
},
... | attachPostPictureRatingHandler | identifier_name |
postPictureRatingHandler.ts | import Router from '@koa/router';
import { SQL } from 'sql-template-strings';
import { pool } from '../../database';
import { bodySchemaValidator } from '../../requestValidators';
import { authenticator } from '../../authenticator';
export function attachPostPictureRatingHandler(router: Router) | {
router.post(
'/pictures/:id/rating',
authenticator(true),
bodySchemaValidator(
{
type: 'object',
required: ['stars'],
properties: {
stars: {
type: 'integer',
minimum: 1,
maximum: 5,
},
},
},
true,
... | identifier_body | |
fs.py | import os
import sys
import errno
import itertools
import logging
import stat
import threading
from fuse import FuseOSError, Operations
from . import exceptions, utils
from .keys import Key
from .logs import Log
from .views import View
logger = logging.getLogger('basefs.fs')
class ViewToErrno():
def __enter__... |
if exc_type is exceptions.Exists:
raise FuseOSError(errno.EEXIST)
class FileSystem(Operations):
def __init__(self, view, serf=None, serf_agent=None, init_function=None):
self.view = view
self.cache = {}
self.dirty = {}
self.loaded = view.log.loaded
self... | raise FuseOSError(errno.ENOENT) | conditional_block |
fs.py | import os
import sys
import errno
import itertools
import logging
import stat
import threading
from fuse import FuseOSError, Operations
from . import exceptions, utils
from .keys import Key
from .logs import Log
from .views import View
logger = logging.getLogger('basefs.fs')
class ViewToErrno():
def __enter__... |
# def fsync(self, path, fdatasync, fh):
# return self.flush(path, fh)
# return None
| content = self.cache.pop(path, None)
dirty = self.dirty.pop(path, False)
if content is not None and dirty:
# TODO raise permission denied should happen in write() create().... not here
with ViewToErrno():
node = self.view.write(path, content)
self.... | identifier_body |
fs.py | import os
import sys
import errno
import itertools
import logging
import stat
import threading
from fuse import FuseOSError, Operations
from . import exceptions, utils
from .keys import Key
from .logs import Log
from .views import View
logger = logging.getLogger('basefs.fs')
class ViewToErrno():
def | (self):
return self
def __exit__(self, exc_type, exc, exc_tb):
if exc_type is exceptions.PermissionDenied:
raise FuseOSError(errno.EACCES)
if exc_type is exceptions.DoesNotExist:
raise FuseOSError(errno.ENOENT)
if exc_type is exceptions.Exists:
... | __enter__ | identifier_name |
fs.py | import os
import sys
import errno
import itertools
import logging
import stat
import threading
from fuse import FuseOSError, Operations
from . import exceptions, utils
from .keys import Key
from .logs import Log
from .views import View
logger = logging.getLogger('basefs.fs')
class ViewToErrno():
def __enter__... | def get_node(self, path):
# check if logfile has been modified
if self.loaded != self.view.log.loaded:
logger.debug('-> %s rebuild', path)
self.view.build()
self.loaded = self.view.log.loaded
with ViewToErrno():
node = self.view.get(path)
... | def destroy(self, path):
super().destroy(path)
if self.serf_agent:
self.serf_agent.stop()
| random_line_split |
worldlyPosition.js | worldlyPosition = {
config: {
topLongitude: 10000
, leftLatitude: 20000
, bottomLongitude: 14000
, rightLatitude: 26000
}
, field: {}
, calcVars: function () {
var self = this
// Measured from left to right
self.field.width = self.config.rightLatitude - self.config.leftLatitude
self.field.... | return worldlyPosition.latitudeToPercent(latitude)
}) | random_line_split | |
application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative pat... | // compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery-ui-1.9.2.js
//= require jquery_ujs
//= require jquery_mods
//= require jquery.mobile.custom.js
//= require jquery.waypoints.js... | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the | random_line_split |
restoration_status.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity. | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of t... |
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | random_line_split |
restoration_status.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | {
/// No restoration.
Inactive,
/// Ongoing restoration.
Ongoing {
/// Total number of state chunks.
state_chunks: u32,
/// Total number of block chunks.
block_chunks: u32,
/// Number of state chunks completed.
state_chunks_done: u32,
/// Number of block chunks completed.
block_chunks_done: u32,
}... | RestorationStatus | identifier_name |
kendo.culture.ha-Latn-NG.js | /**
* Copyright 2014 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or a... | symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "N"
}
},
calendars: {
st... | groupSize: [3],
| random_line_split |
framework.py | import numpy as np
import tensorflow as tf
from agent.forward import Forward
from config import *
_EPSILON = 1e-6 # avoid nan
# local network for advantage actor-critic which are also know as A2C
class Framework(object):
def __init__(self, access, state_size, action_size, scope_name):
self.Access = acc... | for gv, lv in zip(global_actor_params, local_actor_params):
assign_list.append(tf.assign(lv, gv))
for gv, lv in zip(global_critic_params, local_critic_params):
assign_list.append(tf.assign(lv, gv))
self.update_local = assign_list
def get_trainable(self):
retu... | assign_list = [] | random_line_split |
framework.py | import numpy as np
import tensorflow as tf
from agent.forward import Forward
from config import *
_EPSILON = 1e-6 # avoid nan
# local network for advantage actor-critic which are also know as A2C
class Framework(object):
def __init__(self, access, state_size, action_size, scope_name):
self.Access = acc... |
def get_deterministic_policy_action(self, sess, inputs):
# get deterministic action for test
return sess.run(self.greedy_action,
{self.inputs: np.expand_dims(inputs, axis=0)})
def get_value(self, sess, inputs):
return sess.run(self.value, {self.inputs: inputs})... | if np.random.uniform() < epsilon:
policy = sess.run(self.policy_step,
{self.inputs: np.expand_dims(inputs, axis=0)})
return np.random.choice(self.action_space, 1, p=policy)[0]
else:
return np.random.randint(self.action_size) | identifier_body |
framework.py | import numpy as np
import tensorflow as tf
from agent.forward import Forward
from config import *
_EPSILON = 1e-6 # avoid nan
# local network for advantage actor-critic which are also know as A2C
class Framework(object):
def __init__(self, access, state_size, action_size, scope_name):
self.Access = acc... |
for gv, lv in zip(global_critic_params, local_critic_params):
assign_list.append(tf.assign(lv, gv))
self.update_local = assign_list
def get_trainable(self):
return [self.actor.get_variables(), self.critic.get_variables()]
def get_policy(self, sess, inputs):
return ... | assign_list.append(tf.assign(lv, gv)) | conditional_block |
framework.py | import numpy as np
import tensorflow as tf
from agent.forward import Forward
from config import *
_EPSILON = 1e-6 # avoid nan
# local network for advantage actor-critic which are also know as A2C
class Framework(object):
def __init__(self, access, state_size, action_size, scope_name):
self.Access = acc... | (self):
global_actor_params, global_critic_params = self.Access.get_trainable()
local_actor_params, local_critic_params = self.get_trainable()
actor_grads = tf.gradients(self.actor_loss, list(local_actor_params))
critic_grads = tf.gradients(self.critic_loss, list(local_critic_params))
... | _build_async_interface | identifier_name |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2020 Didotech S.r.l. (<http://www.didotech.com/>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
#... | "name": "Purchase Order Lines With Combined Discounts",
"author": "Didotech.com",
"version": "1.0.0",
"category": "Generic Modules/Sales & Purchases",
'description': """ """,
"depends": [
"stock",
'product',
"purchase",
"purchase_discount",
],
"data": [
... | #
##############################################################################
{ | random_line_split |
platform.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
export const setTimeout = _globals.setTimeout.bind(_globals);
export const clearTimeout = _globals.clearTimeout.bind(_globals);
export const setInterval = _globals.setInterval.bind(_globals);
export const clearInterval = _globals.clearInterval.bind(_globals); | {
return typeof _globals.Worker !== 'undefined';
} | identifier_body |
platform.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
export const isWindows = _isWindows;
export const isMacintosh = _isMacintosh;
export const isLinux = _isLinux;
export const isRootUser = _isRootUser;
export const isNative = _isNative;
export const isWeb = _isWeb;
export const isQunit = _isQunit;
export const platform = _platform;
/**
* The language used for the use... | }
} | random_line_split |
platform.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): boolean {
return typeof _globals.Worker !== 'undefined';
}
export const setTimeout = _globals.setTimeout.bind(_globals);
export const clearTimeout = _globals.clearTimeout.bind(_globals);
export const setInterval = _globals.setInterval.bind(_globals);
export const clearInterval = _globals.clearInterval.bind(_globa... | hasWebWorkerSupport | identifier_name |
platform.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
_isNative = true;
} else if (typeof navigator === 'object') {
let userAgent = navigator.userAgent;
_isWindows = userAgent.indexOf('Windows') >= 0;
_isMacintosh = userAgent.indexOf('Macintosh') >= 0;
_isLinux = userAgent.indexOf('Linux') >= 0;
_isWeb = true;
_locale = navigator.language;
_language = _locale;
_... | {
try {
let nlsConfig: NLSConfig = JSON.parse(rawNlsConfig);
let resolved = nlsConfig.availableLanguages['*'];
_locale = nlsConfig.locale;
// VSCode's default language is 'en'
_language = resolved ? resolved : LANGUAGE_DEFAULT;
} catch (e) {
}
} | conditional_block |
update_api_docs.py | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import platform
import sys
import subprocess
DIR_OF_THIS_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_DOCS = os.path.... | GenerateApiDocs() | conditional_block | |
update_api_docs.py | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import platform
import sys
import subprocess
DIR_OF_THIS_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_DOCS = os.path.... | ():
return platform.system() == 'Windows'
# On Windows, distutils.spawn.find_executable only works for .exe files
# but .bat and .cmd files are also executables, so we use our own
# implementation.
def FindExecutable( executable ):
# Executable extensions used on Windows
WIN_EXECUTABLE_EXTS = [ '.exe', '.bat', ... | OnWindows | identifier_name |
update_api_docs.py | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import platform
import sys
import subprocess
DIR_OF_THIS_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_DOCS = os.path.... | return executable_name
return None
def GenerateApiDocs():
npm = FindExecutable( 'npm' )
if not npm:
sys.exit( 'ERROR: NPM is required to generate API docs.' )
os.chdir( os.path.join( DIR_OF_DOCS ) )
subprocess.call( [ npm, 'install', '--production' ] )
bootprint = FindExecutable( os.path.join(... | else: | random_line_split |
update_api_docs.py | #!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import platform
import sys
import subprocess
DIR_OF_THIS_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_DOCS = os.path.... |
def GenerateApiDocs():
npm = FindExecutable( 'npm' )
if not npm:
sys.exit( 'ERROR: NPM is required to generate API docs.' )
os.chdir( os.path.join( DIR_OF_DOCS ) )
subprocess.call( [ npm, 'install', '--production' ] )
bootprint = FindExecutable( os.path.join( DIR_OF_DOCS, 'node_modules',
... | WIN_EXECUTABLE_EXTS = [ '.exe', '.bat', '.cmd' ]
paths = os.environ[ 'PATH' ].split( os.pathsep )
base, extension = os.path.splitext( executable )
if OnWindows() and extension.lower() not in WIN_EXECUTABLE_EXTS:
extensions = WIN_EXECUTABLE_EXTS
else:
extensions = [ '' ]
for extension in extensions:... | identifier_body |
s_pcap.py | import dpkt
import socket
import logging
l = logging.getLogger("simuvex.s_pcap")
class PCAP(object):
def | (self,path, ip_port_tup, init=True):
self.path = path
self.packet_num = 0
self.pos = 0
self.in_streams = []
self.out_streams = []
#self.in_buf = ''
self.ip = ip_port_tup[0]
self.port = ip_port_tup[1]
if init:
self.initialize(self.path)
... | __init__ | identifier_name |
s_pcap.py | import dpkt
import socket
import logging
l = logging.getLogger("simuvex.s_pcap")
class PCAP(object):
def __init__(self,path, ip_port_tup, init=True):
self.path = path
self.packet_num = 0
self.pos = 0
self.in_streams = []
self.out_streams = []
#self.in_buf = ''
... |
else:
if (self.pos + length) >= plength:
rest = plength-self.pos
length = rest
self.packet_num += 1
packet_data = pdata[self.pos:plength]
if self.packet_num is not initial_packet:
self.pos = 0
return packet_da... | if plength > length:
temp = length
else:
self.packet_num += 1
packet_data = pdata[self.pos:length]
self.pos += temp | conditional_block |
s_pcap.py | import dpkt
import socket
import logging
l = logging.getLogger("simuvex.s_pcap")
class PCAP(object):
def __init__(self,path, ip_port_tup, init=True):
self.path = path
self.packet_num = 0
self.pos = 0
self.in_streams = []
self.out_streams = []
#self.in_buf = ''
... |
def recv(self, length):
#import ipdb;ipdb.set_trace()
temp = 0
#import ipdb;ipdb.set_trace()
#pcap = self.pcap
initial_packet = self.packet_num
plength, pdata = self.in_streams[self.packet_num]
length = min(length, plength)
if self.pos is 0:
... | f = open(path)
pcap = dpkt.pcap.Reader(f)
for _,buf in pcap:
#data = dpkt.ethernet.Ethernet(buf).ip.data.data
ip = dpkt.ethernet.Ethernet(buf).ip
tcp = ip.data
myip = socket.inet_ntoa(ip.dst)
if myip is self.ip and tcp.dport is self.port and le... | identifier_body |
s_pcap.py | import dpkt
import socket
import logging
l = logging.getLogger("simuvex.s_pcap")
class PCAP(object):
def __init__(self,path, ip_port_tup, init=True):
self.path = path
self.packet_num = 0
self.pos = 0
self.in_streams = []
self.out_streams = []
#self.in_buf = ''
... | new_pcap.in_streams = self.in_streams
new_pcap.out_streams = self.out_streams
return new_pcap | random_line_split | |
index.tsx | import {
Badge,
Box,
Flex,
Heading,
Stack,
Tab,
TabList,
TabPanel,
TabPanels,
Tabs
} from '@chakra-ui/react'
import useSWR from 'swr'
import {API} from 'lib/constants'
import JobDashboard from 'lib/components/admin-job-dashboard'
import TextLink from 'lib/components/text-link' | import WorkerList from 'lib/components/admin-worker-list'
import withAuth from 'lib/with-auth'
// Refresh every five seconds
const refreshInterval = 5000
// Fetcher
const fetcher = (url, user) =>
fetch(url, {
headers: {
Authorization: `bearer ${user.idToken}`,
'X-Conveyal-Access-Group': user.adminTe... | random_line_split | |
get_iframes_content.js | /*
* get_iframes_content.js
*
* -> returns as a string all innerHTML from current document
* as well as from all iframes present in the document
*/
var phantom_iframes = document.getElementsByTagName('frame'),
iframes_content = '',
iframe_content,
ph_i, ph_j;
if (!phantom_iframes.length) {
phanto... | return iframes_content; | }
}
} | random_line_split |
get_iframes_content.js | /*
* get_iframes_content.js
*
* -> returns as a string all innerHTML from current document
* as well as from all iframes present in the document
*/
var phantom_iframes = document.getElementsByTagName('frame'),
iframes_content = '',
iframe_content,
ph_i, ph_j;
if (!phantom_iframes.length) {
phanto... |
return iframes_content;
| {
if ("contentDocument" in phantom_iframes[ph_i]) {
iframe_content = phantom_iframes[ph_i].contentDocument.childNodes;
} else {
iframe_content = phantom_iframes[ph_i].childNodes;
}
if (iframe_content) {
for (ph_j=0; ph_j<iframe_content.length; ph_j++) {
if (iframe_content[ph_j] && "innerHTML" ... | conditional_block |
middleware.py | import json
from json_url_rewriter import config
from json_url_rewriter.rewrite import URLRewriter
class HeaderToPathPrefixRewriter(object):
"""
A rewriter to take the value of a header and prefix any path.
"""
def __init__(self, keys, base, header_name):
self.keys = keys
self.base =... |
return resp
def json_url_rewriter_filter_factory(global_conf, *args, **kw):
print(global_conf, args, kw)
raise Exception('Blastoff')
| return [self.rewrite(resp, environ)] | conditional_block |
middleware.py | import json
from json_url_rewriter import config
from json_url_rewriter.rewrite import URLRewriter
class HeaderToPathPrefixRewriter(object):
"""
A rewriter to take the value of a header and prefix any path.
"""
def __init__(self, keys, base, header_name):
self.keys = keys
self.base =... | (self, environ, start_response):
# Set a local variable for the request
self.do_rewrite = False
# Our request local start response wrapper to grab the
# response headers
def sr(status, response_headers, exc_info=None):
if self.ok(status) and self.is_json(response_hea... | __call__ | identifier_name |
middleware.py | import json
from json_url_rewriter import config
from json_url_rewriter.rewrite import URLRewriter
class HeaderToPathPrefixRewriter(object):
"""
A rewriter to take the value of a header and prefix any path.
"""
def __init__(self, keys, base, header_name):
self.keys = keys
self.base =... |
class RewriteMiddleware(object):
def __init__(self, app, rewriter):
self.app = app
self.rewriter = rewriter
@staticmethod
def content_type(headers):
return dict([(k.lower(), v) for k, v in headers]).get('content-type')
def is_json(self, headers):
return 'json' in se... | key = self.header()
if not key in environ:
return doc
prefix = environ[key]
def replacement(match):
base, path = match.groups()
return '%s/%s%s' % (base, prefix, path)
rewriter = URLRewriter(self.keys, self.regex, replacement)
return rewrite... | identifier_body |
middleware.py | import json
from json_url_rewriter import config
from json_url_rewriter.rewrite import URLRewriter
class HeaderToPathPrefixRewriter(object):
"""
A rewriter to take the value of a header and prefix any path.
"""
def __init__(self, keys, base, header_name):
self.keys = keys
self.base =... | class RewriteMiddleware(object):
def __init__(self, app, rewriter):
self.app = app
self.rewriter = rewriter
@staticmethod
def content_type(headers):
return dict([(k.lower(), v) for k, v in headers]).get('content-type')
def is_json(self, headers):
return 'json' in self.... | random_line_split | |
search-builder.testpage.component.ts | import { Component } from '@angular/core';
import { SearchBuilderQuery, SearchBuilderComponentDefinition, SearchTextComponent, SearchDateRangeComponent, SearchDateRangeConfig, SearchTextConfig, SearchSelectComponent, SearchSelectConfig, SearchDateComponent, SearchDateConfig } from '@ux-aspects/ux-aspects';
@Component(... | name: 'text',
component: SearchTextComponent,
config: {
placeholder: 'Enter text'
} as SearchTextConfig
},
{
name: 'date',
component: SearchDateComponent,
config: {
label: 'Date',
... | { | random_line_split |
search-builder.testpage.component.ts | import { Component } from '@angular/core';
import { SearchBuilderQuery, SearchBuilderComponentDefinition, SearchTextComponent, SearchDateRangeComponent, SearchDateRangeConfig, SearchTextConfig, SearchSelectComponent, SearchSelectConfig, SearchDateComponent, SearchDateConfig } from '@ux-aspects/ux-aspects';
@Component(... | (): void {
this.query.keywords.push({ type: 'text', value: null });
}
addAny(): void {
this.query.any.push({ type: 'date', value: new Date() });
}
addAll(): void {
this.query.all.push({ type: 'date-range', value: null });
}
addNone(): void {
this.query.none.pus... | addKeyword | identifier_name |
search-builder.testpage.component.ts | import { Component } from '@angular/core';
import { SearchBuilderQuery, SearchBuilderComponentDefinition, SearchTextComponent, SearchDateRangeComponent, SearchDateRangeConfig, SearchTextConfig, SearchSelectComponent, SearchSelectConfig, SearchDateComponent, SearchDateConfig } from '@ux-aspects/ux-aspects';
@Component(... |
return custodians;
}
setQuery(): void {
this.query = {
keywords: [
{
type: 'text',
value: 'Hello Protractor!'
}
],
any: [
{
type: 'date',
... | {
custodians.push(`User ${idx}`);
} | conditional_block |
search-builder.testpage.component.ts | import { Component } from '@angular/core';
import { SearchBuilderQuery, SearchBuilderComponentDefinition, SearchTextComponent, SearchDateRangeComponent, SearchDateRangeConfig, SearchTextConfig, SearchSelectComponent, SearchSelectConfig, SearchDateComponent, SearchDateConfig } from '@ux-aspects/ux-aspects';
@Component(... |
setQuery(): void {
this.query = {
keywords: [
{
type: 'text',
value: 'Hello Protractor!'
}
],
any: [
{
type: 'date',
value: '2017-12-06T12:27:... | {
const custodians: string[] = [];
for (let idx = 0; idx < 20; idx++) {
custodians.push(`User ${idx}`);
}
return custodians;
} | identifier_body |
models.py | from django.db import models
from simple_history.models import HistoricalRecords as AuditTrail
from edc_base.model.models import BaseUuidModel
from getresults_order.models import Utestid, OrderPanel
class SenderModel(BaseUuidModel):
"""A class for the model or make of a sending device, e.g. FACSCalibur."""
... |
class Meta:
app_label = 'getresults_sender'
db_table = 'getresults_sender'
ordering = ('serial_number', )
class SenderPanel(BaseUuidModel):
"""A class for the panel of results associated with a sending model/make."""
name = models.CharField(max_length=25, unique=True)
order... | def save(self, *args, **kwargs):
if not self.name:
self.name = self.serial_number
super(Sender, self).save(*args, **kwargs) | random_line_split |
models.py | from django.db import models
from simple_history.models import HistoricalRecords as AuditTrail
from edc_base.model.models import BaseUuidModel
from getresults_order.models import Utestid, OrderPanel
class SenderModel(BaseUuidModel):
"""A class for the model or make of a sending device, e.g. FACSCalibur."""
... |
super(Sender, self).save(*args, **kwargs)
class Meta:
app_label = 'getresults_sender'
db_table = 'getresults_sender'
ordering = ('serial_number', )
class SenderPanel(BaseUuidModel):
"""A class for the panel of results associated with a sending model/make."""
name = mode... | self.name = self.serial_number | conditional_block |
models.py | from django.db import models
from simple_history.models import HistoricalRecords as AuditTrail
from edc_base.model.models import BaseUuidModel
from getresults_order.models import Utestid, OrderPanel
class SenderModel(BaseUuidModel):
"""A class for the model or make of a sending device, e.g. FACSCalibur."""
... | (BaseUuidModel):
"""A class for a specific sender device identified by serial number that links to a sender panel."""
name = models.CharField(max_length=25, null=True, blank=True)
sender_model = models.ForeignKey(SenderModel)
serial_number = models.CharField(
max_length=25,
unique=Tr... | Sender | identifier_name |
models.py | from django.db import models
from simple_history.models import HistoricalRecords as AuditTrail
from edc_base.model.models import BaseUuidModel
from getresults_order.models import Utestid, OrderPanel
class SenderModel(BaseUuidModel):
"""A class for the model or make of a sending device, e.g. FACSCalibur."""
... |
class Meta:
app_label = 'getresults_sender'
db_table = 'getresults_sendermodel'
ordering = ('name', )
class Sender(BaseUuidModel):
"""A class for a specific sender device identified by serial number that links to a sender panel."""
name = models.CharField(max_length=25, null=Tr... | return self.name | identifier_body |
router.js | define(['views/Index','views/Cart','views/CategoryEdit','views/Categories','views/Product','views/Products','views/ProductEdit','views/ProductDetail','views/admin/Index','models/Product','models/Category','models/CartCollection','models/ProductCollection','models/CategoryCollection'], function(IndexView,CartView,Catego... | },
productEdit: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new ProductEditView({model: product}));
product.fetch();
},
productView: function(id){
var product = new Product();
product.url = '/products/' + id;
this.changeView(new Pr... | var productModel = new Product({
main_cat_id: cid,
});
this.changeView(new ProductEditView({model: productModel})); | random_line_split |
router.js | define(['views/Index','views/Cart','views/CategoryEdit','views/Categories','views/Product','views/Products','views/ProductEdit','views/ProductDetail','views/admin/Index','models/Product','models/Category','models/CartCollection','models/ProductCollection','models/CategoryCollection'], function(IndexView,CartView,Catego... |
this.currentView = view;
this.currentView.render();
},
index: function(){
this.changeView(new IndexView());
},
myCart: function(){
var cartCollection = new CartCollection();
cartCollection.url = '/cart';
this.changeView(new CartView({collection:cartCollection}));
cartCollection.fetch();
... | {
this.currentView.undelegateEvents();
} | conditional_block |
test_commands_prime.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015, 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in... |
def test_prime_ran_twice_is_a_noop(self):
fake_logger = fixtures.FakeLogger(level=logging.INFO)
self.useFixture(fake_logger)
parts = self.make_snapcraft_yaml()
main(['prime'])
self.assertEqual(
'Preparing to pull prime0 \n'
'Pulling prime0 \n'
... | self.assertFalse(os.path.exists(parts[i]['part_dir']),
'Pulled wrong part')
self.assertFalse(os.path.exists(parts[i]['state_dir']),
'Expected for only to be a state file for build1') | conditional_block |
test_commands_prime.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015, 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in... | description: if the prime is succesful the state file will be updated
confinement: strict
parts:
{parts}"""
yaml_part = """ prime{:d}:
plugin: nil"""
def make_snapcraft_yaml(self, n=1):
parts = '\n'.join([self.yaml_part.format(i) for i in range(n)])
super().make_snapcraft_yaml(self.yaml_... | version: 1.0
summary: test prime | random_line_split |
test_commands_prime.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015, 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in... |
def test_prime_invalid_part(self):
fake_logger = fixtures.FakeLogger(level=logging.ERROR)
self.useFixture(fake_logger)
self.make_snapcraft_yaml()
with self.assertRaises(SystemExit) as raised:
main(['prime', 'no-prime', ])
self.assertEqual(1, raised.exception.c... | parts = '\n'.join([self.yaml_part.format(i) for i in range(n)])
super().make_snapcraft_yaml(self.yaml_template.format(parts=parts))
parts = []
for i in range(n):
part_dir = os.path.join(self.parts_dir, 'prime{}'.format(i))
state_dir = os.path.join(part_dir, 'state')
... | identifier_body |
test_commands_prime.py | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015, 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in... | (self):
fake_logger = fixtures.FakeLogger(level=logging.ERROR)
self.useFixture(fake_logger)
parts = self.make_snapcraft_yaml(n=3)
main(['prime', 'prime1'])
self.assertFalse(
os.path.exists(
os.path.join(self.snap_dir, 'meta', 'snap.yaml')),
... | test_prime_one_part_only_from_3 | identifier_name |
client.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... |
def printOutput(self, text):
if '\r' in text:
text = text.replace('\r', '\n')
lines = text.split('\n')
for one_line in lines:
if len(one_line) > 0:
print self.formatLine(one_line)
def formatLine(self, line):
words = line.split()
... | self.checkForMessages() | conditional_block |
client.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... |
network = 'irc.freenode.net'
port = 6667
nick = 'lolasuketo'
uname = 'jinna'
host = 'jlei-laptop'
server = 'comcast'
realname = 'python irc bot'
channel = '#kamtest'
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
sock.connect ( ( network, port ) )
sock.send ('NICK %s \r\n' % nick )
sock.send ( 'USER... | words = line.split()
sender = ""
if line[0] == ':' and len(words) >= 2:
sender = line[1:line.find('!')]
words = words[1:]
tag = words[0].upper()
if tag == 'PRIVMSG':
return '%s: %s' % (sender, words[2])
else:
return line | identifier_body |
client.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... | host = 'jlei-laptop'
server = 'comcast'
realname = 'python irc bot'
channel = '#kamtest'
sock = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
sock.connect ( ( network, port ) )
sock.send ('NICK %s \r\n' % nick )
sock.send ( 'USER %s %s %s :%s r\n' % (uname, host, server, realname))
sock.send ( 'JOIN #kamtest\r\... | uname = 'jinna' | random_line_split |
client.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... | (self):
while not done:
self.checkForMessages()
def printOutput(self, text):
if '\r' in text:
text = text.replace('\r', '\n')
lines = text.split('\n')
for one_line in lines:
if len(one_line) > 0:
print self.formatLine(one_line)
... | run | identifier_name |
serialization.py | from __future__ import division, print_function
import json
from collections import Iterable, OrderedDict, namedtuple
import numpy as np
from six import string_types
def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_field... |
raise TypeError("Type %s not data-serializable" % type(data))
def restore(dct):
if "py/dict" in dct:
return dict(dct["py/dict"])
if "py/tuple" in dct:
return tuple(dct["py/tuple"])
if "py/set" in dct:
return set(dct["py/set"])
if "py/collections.namedtuple" in dct:
... | return {"py/numpy.ndarray": {
"values": data.tolist(),
"dtype": str(data.dtype)}} | conditional_block |
serialization.py | from __future__ import division, print_function
import json
from collections import Iterable, OrderedDict, namedtuple
import numpy as np
from six import string_types
def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_field... | if isinstance(data, set):
return {"py/set": [serialize(val) for val in data]}
if isinstance(data, np.ndarray):
return {"py/numpy.ndarray": {
"values": data.tolist(),
"dtype": str(data.dtype)}}
raise TypeError("Type %s not data-serializable" % type(data))
def restore... | return {k: serialize(v) for k, v in data.items()}
return {"py/dict": [[serialize(k), serialize(v)] for k, v in data.items()]}
if isinstance(data, tuple):
return {"py/tuple": [serialize(val) for val in data]} | random_line_split |
serialization.py | from __future__ import division, print_function
import json
from collections import Iterable, OrderedDict, namedtuple
import numpy as np
from six import string_types
def isnamedtuple(obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_field... | return json.loads(s, object_hook=restore) | identifier_body | |
serialization.py | from __future__ import division, print_function
import json
from collections import Iterable, OrderedDict, namedtuple
import numpy as np
from six import string_types
def | (obj):
"""Heuristic check if an object is a namedtuple."""
return isinstance(obj, tuple) \
and hasattr(obj, "_fields") \
and hasattr(obj, "_asdict") \
and callable(obj._asdict)
def serialize(data):
if data is None or isinstance(data, (bool, int, float, str, string_types)):
... | isnamedtuple | identifier_name |
motion.rs | use super::*;
impl Editor {
/// Convert an instruction to a motion (new coordinate). Returns None if the instructions given
/// either is invalid or has no movement.
///
/// A motion is a namespace (i.e. non mode-specific set of commands), which represents
/// movements. These are useful for comman... | (&mut self, Inst(n, cmd): Inst) -> Option<(usize, usize)> {
use super::Key::*;
match cmd.key {
Char('h') => Some(self.left(n.d())),
Char('l') => Some(self.right(n.d())),
Char('j') => Some(self.down(n.d())),
Char('k') => Some(self.up(n.d())),
Ch... | to_motion | identifier_name |
motion.rs | use super::*;
impl Editor {
/// Convert an instruction to a motion (new coordinate). Returns None if the instructions given
/// either is invalid or has no movement.
///
/// A motion is a namespace (i.e. non mode-specific set of commands), which represents
/// movements. These are useful for comman... |
},
Char(c) => {
self.status_bar.msg = format!("Motion not defined: '{}'", c);
self.redraw_status_bar();
None
},
_ => {
self.status_bar.msg = format!("Motion not defined");
None
},... | {
None
} | conditional_block |
motion.rs | /// either is invalid or has no movement.
///
/// A motion is a namespace (i.e. non mode-specific set of commands), which represents
/// movements. These are useful for commands which takes a motion as post-parameter, such as d.
/// d deletes the text given by the motion following. Other commands ca... | use super::*;
impl Editor {
/// Convert an instruction to a motion (new coordinate). Returns None if the instructions given | random_line_split | |
motion.rs | use super::*;
impl Editor {
/// Convert an instruction to a motion (new coordinate). Returns None if the instructions given
/// either is invalid or has no movement.
///
/// A motion is a namespace (i.e. non mode-specific set of commands), which represents
/// movements. These are useful for comman... |
}
| {
use super::Key::*;
match cmd.key {
Char('h') => Some(self.left_unbounded(n.d())),
Char('l') => Some(self.right_unbounded(n.d())),
Char('j') => Some(self.down_unbounded(n.d())),
Char('k') => Some(self.up_unbounded(n.d())),
Char('g') => Some((0... | identifier_body |
rock_paper_scissors_test.py | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets 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 appl... | (tfds_test.DatasetBuilderTestCase):
DATASET_CLASS = rock_paper_scissors.RockPaperScissors
SPLITS = {
'train': 3,
'test': 3,
}
DL_EXTRACT_RESULT = ['rps_train.zip', 'rps_test.zip']
if __name__ == '__main__':
tfds_test.test_main()
| RockPaperScissorsTest | identifier_name |
rock_paper_scissors_test.py | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets 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 appl... | tfds_test.test_main() | conditional_block | |
rock_paper_scissors_test.py | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
# | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing ... | # 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 | random_line_split |
rock_paper_scissors_test.py | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets 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 appl... |
if __name__ == '__main__':
tfds_test.test_main()
| DATASET_CLASS = rock_paper_scissors.RockPaperScissors
SPLITS = {
'train': 3,
'test': 3,
}
DL_EXTRACT_RESULT = ['rps_train.zip', 'rps_test.zip'] | identifier_body |
App.js | var App = function() {
if(!App.supportsWebGL) {
document.body.className = 'app--broken';
return;
}
THREE.ImageUtils.crossOrigin = 'Anonymous';
this.camera = this.getCamera();
this.gravitationPoints = this.getGravitationPoints();
this.isInside = true;
this.renderer = new THREE.WebGLRenderer({ ant... |
var geo = new THREE.Geometry();
var mat = new THREE.ParticleSystemMaterial({
blending: THREE.AdditiveBlending,
depthBuffer: false,
depthTest: false,
map: map,
transparent: true,
vertexColors: true,
size: size
});
var p;
while(particles--) {
p = new ... | {
map = THREE.ImageUtils.loadTexture('assets/textures/particle-low.png');
size = 0.25;
} | conditional_block |
App.js | var App = function() {
if(!App.supportsWebGL) {
document.body.className = 'app--broken';
return;
}
THREE.ImageUtils.crossOrigin = 'Anonymous';
this.camera = this.getCamera();
this.gravitationPoints = this.getGravitationPoints();
this.isInside = true;
this.renderer = new THREE.WebGLRenderer({ ant... | * RENDER LOOP
********************************/
App.prototype.update = function() {
this.updateParticleSystem(this.particles);
this.updateMovingGravitationPoint(this.gravitationPoints[0]);
};
App.prototype.updateParticleSystem = function(ps) {
var geo = ps.geometry;
var i = geo.vertices.length;
var ... | this.resize();
};
/********************************
| random_line_split |
DragAndDrop.tsx | import React from 'react'
import { ComponentType } from 'react'
import { Difference } from 'utils/types'
export type DraggingInfo<T> = {
x: number
y: number
distanceX: number
distanceY: number
value: T
}
type DraggableProps<T> = {
onDrag: () => T
children?: React.ReactNode
}
type DropZoneProps<T> = {... | () {
this.setState({ nextDrag: undefined, dragInfo: undefined })
document.body.style.cursor = ""
}
draggable = (props: DraggableProps<T>) => (
<div
onMouseDown={e => {
e.stopPropagation()
e.preventDefault()
// We don't want to fire the drag event right now, and we at leas... | reset | identifier_name |
DragAndDrop.tsx | import React from 'react'
import { ComponentType } from 'react'
import { Difference } from 'utils/types'
export type DraggingInfo<T> = {
x: number
y: number
distanceX: number
distanceY: number
value: T
}
type DraggableProps<T> = {
onDrag: () => T
children?: React.ReactNode
}
type DropZoneProps<T> = {... |
draggable = (props: DraggableProps<T>) => (
<div
onMouseDown={e => {
e.stopPropagation()
e.preventDefault()
// We don't want to fire the drag event right now, and we at least wait
// for a next event to be fired
this.setState({
nextDrag: () => props.onDra... | {
this.setState({ nextDrag: undefined, dragInfo: undefined })
document.body.style.cursor = ""
} | identifier_body |
DragAndDrop.tsx | import React from 'react'
import { ComponentType } from 'react'
import { Difference } from 'utils/types'
export type DraggingInfo<T> = {
x: number
y: number
distanceX: number
distanceY: number
value: T
}
type DraggableProps<T> = {
onDrag: () => T
children?: React.ReactNode
}
type DropZoneProps<T> = {... |
render() {
return (
<DragAndDrop<T> renderDraggedElement={ (props) => renderDraggedElement(props) } >
{ (Draggable, DropZone, dragInfo) =>
<ComponentFix Draggable={ Draggable } DropZone={ DropZone } dragInfo={ dragInfo } {...this.props} />
}
</DragAndDrop>
... | ): ComponentType<Difference<PROPS, WithDragAndDrop<T>>> => {
const ComponentFix = Component as ComponentType<any> // TODO remove when React is fixed
return class extends React.Component<Difference<PROPS, WithDragAndDrop<T>>, S> { | random_line_split |
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! # ConfigParser
//!
//! ConfigParser is a utility to parse hgrc-like config files.
//!
//! ## Features
//!
//! - Parse valid hgrc-like con... | //! %include path/to/another/hgrc.d
//! ```
//!
//! The include path is relative to the directory of the current config
//! file being parsed. If it's a directory, files with names ending
//! with `.rc` in it will be read.
//!
//! ### Unset a config
//!
//! Use `%unset` to unset a config:
//!
//! ```plain,ignore
//! [s... | random_line_split | |
index.ts | import URL from 'url';
import * as packageCache from '../../util/cache/package';
import { GitlabHttp } from '../../util/http/gitlab';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import type { GitlabTag } from './types';
const gitlabApi = new GitlabHttp();
export const id = 'gitlab-tags';
export ... | {
const cachedResult = await packageCache.get<ReleaseResult>(
cacheNamespace,
getCacheKey(depHost, repo)
);
// istanbul ignore if
if (cachedResult) {
return cachedResult;
}
const urlEncodedRepo = encodeURIComponent(repo);
// tag
const url = URL.resolve(
depHost,
`/api/v4/projects/$... | identifier_body | |
index.ts | import URL from 'url';
import * as packageCache from '../../util/cache/package';
import { GitlabHttp } from '../../util/http/gitlab';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import type { GitlabTag } from './types';
const gitlabApi = new GitlabHttp();
export const id = 'gitlab-tags';
export ... |
const urlEncodedRepo = encodeURIComponent(repo);
// tag
const url = URL.resolve(
depHost,
`/api/v4/projects/${urlEncodedRepo}/repository/tags?per_page=100`
);
const gitlabTags = (
await gitlabApi.getJson<GitlabTag[]>(url, {
paginate: true,
})
).body;
const dependency: ReleaseRes... | {
return cachedResult;
} | conditional_block |
index.ts | import URL from 'url';
import * as packageCache from '../../util/cache/package';
import { GitlabHttp } from '../../util/http/gitlab';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import type { GitlabTag } from './types';
const gitlabApi = new GitlabHttp();
export const id = 'gitlab-tags';
export ... | ({
registryUrl: depHost,
lookupName: repo,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
const cachedResult = await packageCache.get<ReleaseResult>(
cacheNamespace,
getCacheKey(depHost, repo)
);
// istanbul ignore if
if (cachedResult) {
return cachedResult;
}
const urlEncodedRepo =... | getReleases | identifier_name |
index.ts | import URL from 'url';
import * as packageCache from '../../util/cache/package';
import { GitlabHttp } from '../../util/http/gitlab';
import type { GetReleasesConfig, ReleaseResult } from '../types';
import type { GitlabTag } from './types';
const gitlabApi = new GitlabHttp();
export const id = 'gitlab-tags';
export ... | const cacheNamespace = 'datasource-gitlab';
function getCacheKey(depHost: string, repo: string): string {
const type = 'tags';
return `${depHost}:${repo}:${type}`;
}
export async function getReleases({
registryUrl: depHost,
lookupName: repo,
}: GetReleasesConfig): Promise<ReleaseResult | null> {
const cache... | random_line_split | |
conf.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 'reno.sphinxext'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General info... |
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'oslosphinx', | random_line_split |
express.js | var express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
passport = require('passport');
module.exports = function (app, config) {
app.set('views', config.rootPath, '/server/views');
a... | err.status = 404;
next(err);
});
}; | var err = new Error('Not Found'); | random_line_split |
checks.py | import json
import time
import git
import discord
import os
import aiohttp
from cogs.utils.dataIO import dataIO
from urllib.parse import quote as uriquote
try:
from lxml import etree
except ImportError:
from bs4 import BeautifulSoup
from urllib.parse import parse_qs, quote_plus
#from cogs.utils i... | (message):
g = git.cmd.Git(working_dir=os.getcwd())
branch = g.execute(["git", "rev-parse", "--abbrev-ref", "HEAD"])
g.execute(["git", "fetch", "origin", branch])
update = g.execute(["git", "remote", "show", "origin"])
if ('up to date' in update or 'fast-forward' in update) and message:
... | update_bot | identifier_name |
checks.py | import json
import time
import git
import discord
import os
import aiohttp
from cogs.utils.dataIO import dataIO
from urllib.parse import quote as uriquote
try:
from lxml import etree
except ImportError:
from bs4 import BeautifulSoup
from urllib.parse import parse_qs, quote_plus
#from cogs.utils i... |
else:
return discord.Status.invisible
def user_post(key_users, user):
if time.time() - float(key_users[user][0]) < float(key_users[user][1]):
return False, [time.time(), key_users[user][1]]
else:
log = dataIO.load_json("settings/log.json")
now = time.time()
... | return discord.Status.dnd | conditional_block |
checks.py | import json
import time
import git
import discord
import os
import aiohttp
from cogs.utils.dataIO import dataIO
from urllib.parse import quote as uriquote
try:
from lxml import etree
except ImportError:
from bs4 import BeautifulSoup
from urllib.parse import parse_qs, quote_plus
#from cogs.utils i... |
def game_time_check(oldtime, interval):
if time.time() - float(interval) < oldtime:
return False
return time.time()
def avatar_time_check(oldtime, interval):
if time.time() - float(interval) < oldtime:
return False
return time.time()
def update_bot(message):
g ... | if time.time() - 3600.0 < gc_time:
return False
return time.time() | identifier_body |
checks.py | import json
import time
import git
import discord
import os
import aiohttp
from cogs.utils.dataIO import dataIO
from urllib.parse import quote as uriquote
try:
from lxml import etree
except ImportError:
from bs4 import BeautifulSoup
from urllib.parse import parse_qs, quote_plus
#from cogs.utils i... | elif text.startswith("<#") and text.endswith(">"):
found_channel = discord.utils.get(channel_list,
id=text.replace("<", "").replace(">", "").replace("#", ""))
else:
found_channel = discord.utils.get(channel_list, name=text)
return found_channel
... | random_line_split | |
fetch_currencies.py | # -*- coding: utf-8 -*-
import json
import re
import unicodedata
import string
from urllib import urlencode
from requests import get
languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'}
url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclai... |
def wdq_query(query):
url = url_wmflabs_template + query
htmlresponse = get(url)
jsonresponse = json.loads(htmlresponse.content)
qlist = map(add_q, jsonresponse.get('items', {}))
error = jsonresponse.get('status', {}).get('error', None)
if error != None and error != 'OK':
print "... | if len(wikidata_ids) > 50:
fetch_data(wikidata_ids[0:49])
wikidata_ids = wikidata_ids[50:]
else:
fetch_data(wikidata_ids)
wikidata_ids = [] | conditional_block |
fetch_currencies.py | # -*- coding: utf-8 -*-
import json
import re
import unicodedata
import string
from urllib import urlencode
from requests import get
languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'}
url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclai... | (wikidata_ids):
while len(wikidata_ids) > 0:
if len(wikidata_ids) > 50:
fetch_data(wikidata_ids[0:49])
wikidata_ids = wikidata_ids[50:]
else:
fetch_data(wikidata_ids)
wikidata_ids = []
def wdq_query(query):
url = url_wmflabs_template + query... | fetch_data_batch | identifier_name |
fetch_currencies.py | # -*- coding: utf-8 -*-
import json
import re
import unicodedata
import string
from urllib import urlencode
from requests import get
languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'}
url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclai... |
def add_currency_name(name, iso4217):
global db
db_names = db['names']
if not isinstance(iso4217, basestring):
print "problem", name, iso4217
return
name = normalize_name(name)
if name == '':
print "name empty", iso4217
return
iso4217_set = db_names.get(n... | return re.sub(' +',' ', remove_accents(name.lower()).replace('-', ' ')) | identifier_body |
fetch_currencies.py | # -*- coding: utf-8 -*-
import json
import re
import unicodedata
import string
from urllib import urlencode
from requests import get
languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'}
url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclai... | aliases = data.get('aliases', {})
for language in aliases:
for i in range(0, len(aliases[language])):
alias = aliases[language][i].get('value', None)
add_currency_name(alias, iso4217)
def fetch_data(wikidata_ids):
url = url_template.format(query=urlenco... | random_line_split | |
llvm-asm-in-moved.rs | // run-pass
#![feature(llvm_asm)] | #[repr(C)]
struct NoisyDrop<'a>(&'a Cell<&'static str>);
impl<'a> Drop for NoisyDrop<'a> {
fn drop(&mut self) {
self.0.set("destroyed");
}
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn main() {
let status = Cell::new("alive");
{
let _y: Box<NoisyDrop>;
let x = Bo... | #![allow(deprecated)] // llvm_asm!
#![allow(dead_code)]
use std::cell::Cell;
| random_line_split |
llvm-asm-in-moved.rs | // run-pass
#![feature(llvm_asm)]
#![allow(deprecated)] // llvm_asm!
#![allow(dead_code)]
use std::cell::Cell;
#[repr(C)]
struct | <'a>(&'a Cell<&'static str>);
impl<'a> Drop for NoisyDrop<'a> {
fn drop(&mut self) {
self.0.set("destroyed");
}
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn main() {
let status = Cell::new("alive");
{
let _y: Box<NoisyDrop>;
let x = Box::new(NoisyDrop(&status));... | NoisyDrop | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.