src stringlengths 721 1.04M |
|---|
# coding=utf-8
# Earthquake
from safe.impact_functions.earthquake.earthquake_building\
.impact_function import EarthquakeBuildingFunction
from safe.impact_functions.earthquake.itb_earthquake_fatality_model\
.impact_function import ITBFatalityFunction
from safe.impact_functions.earthquake.pager_earthquake_fatal... |
from django import forms
class registration(forms.Form):
username = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'class': 'form-control',
'placeholder' : 'Username'}))
nom = forms.CharField(max_length=100,
... |
#!/usr/bin/env python3
# -*- mode:python; tab-width:4; c-basic-offset:4; intent-tabs-mode:nil; -*-
# ex: filetype=python tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent smartindent
#
# Universal Password Changer (UPwdChg)
# Copyright (C) 2014-2018 Cedric Dufour <http://cedric.dufour.name>
# Author: Cedric Du... |
import json
from nltk.stem.wordnet import WordNetLemmatizer
from ppp_questionparsing_grammatical import Word, DependenciesTree, TreeGenerator, computeTree
import data
from unittest import TestCase
class DependenciesTreeTests(TestCase):
########
# Word #
########
def testBasicWordConstructor1(self):
... |
# -*- coding: utf-8 -*-
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.utils.decorators import available_attrs
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.contrib ... |
#!/usr/env python
#############################################################################################
#
# This code produces plots of average signal and heatmaps around motifs under peaks.
# Also produces clusters of peaks, and outputs heatmap
#
###############################################################... |
# -*- coding: utf-8 -
#
# This file is part of offset. See the NOTICE for more information.
import errno
from .util import fd_
from .. import syscall
from ..syscall import select
class PollerBase(object):
POLL_IMPL = None
def __init__(self):
self.poll = self.POLL_IMPL()
self.fds = {}
... |
"""
Created on 30 Dec 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Global positioning system fix data
$xxGGA,time,lat,NS,long,EW,quality,numSV,HDOP,alt,M,sep,M,diffAge,diffStation*cs
example sentence:
$GPGGA,092725.00,4717.11399,N,00833.91590,E,1,08,1.01,499.6,M,48.0,M,,*5B
example values:
GPGGA:... |
# standard modules
import logging
import os
import traceback
# 3rd party modules
import dateutil
import numpy
import matplotlib.pyplot as plt
import pylab
import scipy
import statsmodels.api as sm
# PFP modules
from scripts import constants as c
from scripts import pfp_io
from scripts import pfp_ts
from scripts import ... |
# Copyright 2018 The TensorFlow Authors. 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 by applica... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('activitydb', '0034_auto_20151027_1851'),
]
operations = [
migrations.AddField(
model_name='projectagreement',
... |
"""Module for retrieving gateway state from API."""
from pyvlx.dataobjects import DtoState
from .api_event import ApiEvent
from .frames import FrameGetStateConfirmation, FrameGetStateRequest
class GetState(ApiEvent):
"""Class for retrieving gateway state from API."""
def __init__(self, pyvlx):
"""In... |
# Copyright 2020 Google LLC
#
# 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, ... |
from typing import *
from pros.common.ui.interactive.parameters import BooleanParameter
from .component import Component
class Container(Component):
"""
A Container has multiple Components, possibly a title, and possibly a description
"""
def __init__(self, *elements: Component,
tit... |
#!/usr/bin/env python
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# Based on openvswitch agent.
#
# Copyright 2011 VMware, 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 ma... |
#!/usr/bin/env python2
from __future__ import absolute_import, division, print_function
import argparse
import datetime
import os.path as path
def print_tests(tests):
print('\n'.join([test_tostr(t) for t in tests]))
def read_tests(f):
basename, _ = path.splitext(path.basename(f))
tests = []
for lin... |
# coding: utf-8
# In[1]:
from __future__ import print_function
import numpy as np
import theano
import theano.tensor as T
import lasagne
from process import load_data
#x = T.tensor4()
N_HIDDEN = 100
LEARNING_RATE = .001
GRAD_CLIP = 100
NUM_EPOCHS = 20
BATCH_SIZE = 200
vocab_size = 9
inp_t,inp_v,output_t,o... |
#!/Library/Frameworks/Python.framework/Versions/3.1/bin/python3
# -*- coding: utf-8 -*-
import os, sys
import xml.etree.ElementTree as ET
sys.path.append(os.getcwd().split('projects')[0]+'projects/slps/shared/python')
import BGF3
from functools import reduce
debug = False
#debug = True
defaults = {'definition-separat... |
# Abstract syntax tree for CODA IDL
# ============================================================================
# Scopes
# ============================================================================
class DefScope:
'Mixin class for descriptors which are also scopes.'
def __init__(self):
self.structs = []
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2013 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Andrew Klychkov (@Andersson007) <aaklychkov@mail.ru>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {... |
#!/usr/bin/python3.4
from src.merge_utils import *
import portage
cur_name = sys.argv[1]
cur_tree = "/var/git/meta-repo/kits/" + cur_name
cur_overlay = GitTree(cur_name, root=cur_tree)
env = os.environ.copy()
env['PORTAGE_DEPCACHEDIR'] = '/var/cache/edb/%s-%s-meta' % (cur_overlay.name, cur_overlay.branch)
env['PORTA... |
# Copyright (C) 2015-2021 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from rbnics.sampling.distributions.distribution import Distribution
from rbnics.sampling.distributions.equispaced_distribution import EquispacedDistribution
class CompositeDistribution(Dist... |
from django.conf import settings
from django.db import connection, migrations, models
import django.db.models.deletion
import patchwork.fields
def migrate_data(apps, schema_editor):
if connection.vendor == 'postgresql':
schema_editor.execute(
"""
UPDATE patchwork_submission
... |
#!/usr/bin/python
# Copyright 2014 Google.
#
# 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... |
from django.contrib import admin
from translations.admin import TranslationInline
from .models import Ladder, LadderTranslation
class LadderTranslationAdmin(TranslationInline):
model = LadderTranslation
class LadderAdmin(admin.ModelAdmin):
inlines = [LadderTranslationAdmin]
fieldsets = (
(None,... |
import getpass
import os
import pytest
from cloudify_agent.api.pm.base import Daemon
from cloudify_agent.api import exceptions
def get_daemon(ssl_cert, params=None):
if not params:
params = {
'rest_host': '127.0.0.1',
'broker_ip': '127.0.0.1',
}
params['queue'] = 'que... |
""" Test script that uses two GPUs, one per sub-process,
via the Python multiprocessing module. Each GPU fits a logistic regression model. """
# These imports will not trigger any theano GPU binding
from multiprocessing import Process, Manager
import numpy as np
import os
def f(shared_args,private_args):
""" B... |
# pylint: disable=unused-variable,misplaced-comparison-constant,expression-not-assigned
from expecter import expect
from .utils import load
def describe_get():
def it_requires_a_name_to_return_aliases(client):
status, data = load(client.get("/api/aliases/"))
expect(status) == 200
expec... |
#
# 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
# ... |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
FixedTableDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... |
import numpy as np
import scipy as sp
from scipy.interpolate import UnivariateSpline
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 4, 9, 16, 26, 30, 51]
# Test Spline
trajectory = np.array([x, y], dtype=float)
print trajectory
plt.plot(trajectory[0], trajectory[1])
plt.show()
s = sp.interpolate.U... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def CustomizationIPSettings(vim, *args, **kwargs):
'''IP settings for a virtual network a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Código desarrollado por Daniel Mansilla
from django.shortcuts import render, render_to_response, redirect
from django.views.generic import ListView, CreateView, DetailView, DeleteView, UpdateView, TemplateView
from django.http import HttpResponse, HttpResponseRedirect, Ht... |
import os
from neovim.compat import IS_PYTHON3
def test_get_length(vim):
assert len(vim.current.buffer) == 1
vim.current.buffer.append('line')
assert len(vim.current.buffer) == 2
vim.current.buffer.append('line')
assert len(vim.current.buffer) == 3
vim.current.buffer[-1] = None
assert len... |
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.models import ColorBar, ColumnDataSource, LinearColorMapper, Patches, Plot
from bokeh.palettes import Viridis11
from bokeh.resources import INLINE
from bokeh.sampledata import unemployment, us_counties, us_states
from bokeh.transform impor... |
#!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import os
import subprocess
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import pynacl.p... |
# Copyright 2013 Hewlett-Packard, Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import requests
import logging
import sys
import scrapper_form
import csv
__author__ = "José Vicente"
__copyright__ = "Copyright (c) 2017 José Vicente"
__credits__ = ["José Vicente"]
__license__ = "MIT"
__version__ = "3.2.1"
'''
The purpose of this module is to generate an adjacency list from the metro system servin... |
from dispatch.theme.widgets import Zone, Widget
from dispatch.theme.fields import CharField, TextField, ArticleField, ImageField, WidgetField, Field
from dispatch.theme import register
from dispatch.tests.cases import DispatchAPITestCase, DispatchMediaTestMixin
from dispatch.theme.exceptions import InvalidWidget, Inval... |
import nengo_theano as nef
import random
import abs_val
def make(net, name, neurons, dimensions, dim_fb_err, radius=1.5,
tau_inhib=0.005, inhib_scale1=10, inhib_scale2=1):
"""A function that makes a subnetwork to calculate the weighted
value of a specified cortical action.
:param Networ... |
#!/usr/bin/python
# ===========================================================================
# config unittest
# Copyright 2004, University of Auckland
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software F... |
"""
Item Exporters are used to export/serialize items into sqlite3 database.
"""
from scrapy.exporters import BaseItemExporter
import sqlite3
class SqliteWebpageExporter(BaseItemExporter):
def __init__(self, file, **kwargs):
super().__init__()
self._configure(kwargs)
self.conn = sqlite3.c... |
from datetime import datetime
import glob
import io
from IPython import get_ipython
from IPython.core.magic import register_line_magic
from IPython.display import HTML, IFrame
from nbconvert import HTMLExporter, PDFExporter
import nbformat
import os
import requests
import shlex
import shutil
import subprocess
import te... |
'''
Zen Coding's settings parser
Created on Jun 14, 2009
@author: Sergey Chikuyonok (http://chikuyonok.ru)
'''
from copy import deepcopy
import re
import types
from .zen_settings import zen_settings
_original_settings = deepcopy(zen_settings)
TYPE_ABBREVIATION = 'zen-tag',
TYPE_EXPANDO = 'zen-expando',
TYPE_REFEREN... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... |
# TaskQ - Priority queue with task categorisation support
# Copyright (C) 2014 Steve Henderson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your o... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2015 Juniper Networks
# 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 ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2019 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This ... |
## Hook.io Nach tracker updater.
## This takes a query with parameters of ?val=<number>&tr=<Nach tracker ID>&sec=<secret word>
## and adds a data point to the Nach tracker with ID corresponding to the "tr" param.
## It is intended to be used with IFTTT's Maker channel action but could be triggered from anywhere.
## It ... |
import re
from django.template import loader, RequestContext
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render
from django import forms
from django.conf import settings
from django.contrib import messages
from django.core import urlresolvers
from... |
"""
pghoard - pg_receivexlog handler
Copyright (c) 2016 Ohmu Ltd
See LICENSE for details
"""
import datetime
import logging
import select
import subprocess
import time
from .common import set_subprocess_stdout_and_stderr_nonblocking, terminate_subprocess
from .pgutil import get_connection_info
from threading import ... |
# -*- coding: utf-8 -*-
#
# 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
#... |
import os
import unittest
from click.testing import CliRunner
from pymr import run
class TestRun(unittest.TestCase):
def test_run_command_finds_default(self):
runner = CliRunner()
with runner.isolated_filesystem():
with open('.pymr', 'w') as f:
f.write('[tags]\ntags ... |
# Copyright: 2011, Grigoriy Petukhov
# Author: Grigoriy Petukhov (http://lorien.name)
# License: BSD
import email
import logging
#import urllib
#try:
# from StringIO import StringIO
#except ImportError:
# from io import StringIO
import threading
import random
import requests
from grab.error import GrabError, Gr... |
# This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
#!/usr/bin/env python
# coding=utf-8
from datetime import *
from webcrawl.character import *
from webcrawl.task import *
from webcrawl.urlkit import URLParse
from newsspider import *
from webcrawl import request
#_print, logger = logprint(modulename(__file__), modulepath(__file__))
class SpiderToutiao(SpiderNewsOrig... |
import unittest
import numpy
import pytest
import cupy
from cupy import testing
@testing.gpu
class TestRounding(unittest.TestCase):
@testing.for_all_dtypes(no_complex=True)
@testing.numpy_cupy_allclose(atol=1e-5)
def check_unary(self, name, xp, dtype):
a = testing.shaped_arange((2, 3), xp, dtyp... |
# Copyright (c) 2015 Tobias Neumann, Philipp Rescheneder.
#
# This file is part of Slamdunk.
#
# Slamdunk 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 ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from subprocess import Popen
import pty
import os
import sys
import pynotify
def parse_ICY(line):
aline = line.split('\r\n')[-1]
junk, info = aline.split('=', 1)
try:
info, junk = info.split(';', 1)
except ValueError:
pass
artist, title = info.split('-')
return artist.strip("'"... |
from __future__ import unicode_literals
import sys
import os
import re
import mimetypes
from copy import copy
from importlib import import_module
from io import BytesIO
from django.apps import apps
from django.conf import settings
from django.core import urlresolvers
from django.core.handlers.base import BaseHandler
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# Logging: easier workflow with some utility methods to log and handle errors
from collections import defaultdict, namedtuple
from enum import Enum
import bpy
import os
import sys
import traceback
class LogLevel(Enum):
DEBUG = 'debug'
INFO = 'info'
WARNING = 'warning'
ERROR = 'error'
FATAL = 'fata... |
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d
from matplotlib import pyplot
from spm1d import rft1d
### EPS production preliminaries:
fig_width_mm = 100
fig_height_mm = 80
mm2in = 1/25.4
fig_width = fig_width_mm*mm2in # width in inches
fig_height = fig_height_mm*mm2in # height in inch... |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright (C) 2008-2015
# Christian Kohlöffel
# Vinzenz Schulz
# Jean-Paul Schouwstra
#
# This file is part of DXF2GCODE.
#
# DXF2GCODE is free software: you can redistribute it and/or mod... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
class Scrooge... |
# coding: utf-8
from flask import Flask,request,session,g,redirect,url_for,Blueprint
from flask import abort,render_template,flash
from helpers import getAvatar
import config
#from .base import BaseHandler
import base
config = config.rec()
user = Blueprint('user', __name__)
import pika
#class LoginHandler(BaseHandl... |
# Play a wave file with amplitude modulation.
# Assumes wave file is mono.
# This implementation reads and plays a one frame (sample) at a time (no blocking)
"""
Read a signal from a wave file, do amplitude modulation, play to output
Original: pyrecplay_modulation.py by Gerald Schuller, Octtober 2013
Modified to read ... |
#!/usr/bin/python
import math
import pygame
from lib.Globals import UnitType, Debug, Vars, LoadImage
import lib.Effects
class Projectile(pygame.sprite.Sprite):
""" All projectiles will inherit this class for a basic projectile. """
def __init__(self, d=None, l=-1, offset=0):
pygame.sprite.Sprite.__ini... |
# coding: utf-8
from .utils import XdrLengthError
from .stellarxdr import StellarXDR_pack as Xdr
# Compatibility for Python 3.x that don't have unicode type
try:
type(unicode)
except NameError:
unicode = str
class NoneMemo(object):
def __init__(self):
pass
def to_xdr_object(self):
ret... |
#!/usr/bin/python
'''
Git pre commit hook: write latest commit's datetime
This script writes the date and time of the pending commit into
the source file `doc/index.rst` for the documentation and
the file `__init__.py` of pytrajectory such that it is obvious
to which current code version they belong.
If changed, th... |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2013-2019 Luiko Czub, TestLink-API-Python-client developers
#
# 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... |
import threading
import time
import sublime
import sublime_plugin
import SublimeHaskell.autocomplete as Autocomplete
import SublimeHaskell.event_common as EventCommon
import SublimeHaskell.internals.backend_mgr as BackendManager
import SublimeHaskell.internals.settings as Settings
import SublimeHaskell.internals.util... |
import functools
class TestStatus: # FIXME should really be an Enum
pending = -1
failure = 0
success = 1
class Test:
def __init__(self, func, description):
self.func = func
self.description = description
self.status = TestStatus.pending
self._callback = None
sel... |
from jsonrpc import ServiceProxy
import sys
import string
import getpass
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9332")
e... |
# -*- coding: utf-8 -*-
import random
from datetime import datetime
from wechatpy.pay.base import BaseWeChatPayAPI
class WeChatCoupon(BaseWeChatPayAPI):
def send(self, user_id, stock_id, op_user_id=None, device_info=None,
out_trade_no=None):
"""
发放代金券
:param user_id: 用户在公众... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pyds documentation build configuration file, created by
# sphinx-quickstart on Thu May 29 20:47:19 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding M2M table for field categories on 'Article'
m2m_table_name = db.... |
# Copyright (c) 2013 dotCloud, Inc.
# Copyright (c) 2015 HyperHQ 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/license... |
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.utils.encoding import smart_text
from django.utils.translation import get_language, ugettext_lazy as _
from rest_framework import fields, serializers
from olympia.amo.utils import to_language
from olymp... |
import datetime
import json
from hashlib import sha1
import requests
import peewee
from rivr_peewee import Database
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import JsonLexer
from bluepaste.lexer import BlueprintLexer
from bluepaste.config import BLUEPRINT_PARSER... |
"""Tests for pytype.pytd.parse.builtins."""
from pytype.pytd import pytd
from pytype.pytd.parse import builtins
from pytype.pytd.parse import visitors
import unittest
class UtilsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.builtins = builtins.GetBuiltinsPyTD()
def testGetBuiltinsPyTD(se... |
__author__ = 'davide'
from random import randint
from quadtree import QuadTree, Rect
import pygame
from pygame.constants import *
from pygame.color import THECOLORS
from pygame.draw import rect, circle, line
W = 800
H = 600
R = 2
N = 100
def col(name):
"""
@type name: str
@return the color as a tuple
... |
# type_params {'generic_tolist': ['GTL'], 'flatten': ['FL'], 'flatten_dict': ['DK','DV']}
def generic_tolist(a):
return [a]
u = generic_tolist(1.2)
u[0] = 2.4
v = generic_tolist(True)
v2 = v[v[0]]
def flatten(lists):
"""
Flattens a list of lists into a flat list
"""
return [item for sublist in ... |
# -*- coding: utf-8 -*-
import pdb
import logging as mod_logging
import unittest as mod_unittest
import oneapi.object as mod_object
import oneapi.models as mod_models
class Tests(mod_unittest.TestCase):
def test_json_deserialization(self):
class Alias(mod_object.AbstractModel):
name = mod_... |
#!/usr/bin/env python
from ctypes import *
from ctypes.util import find_library
from os import path
import sys
try:
dirname = path.dirname(path.abspath(__file__))
print dirname
print sys.platform
if sys.platform == 'win32':
libsvm = CDLL(path.join(dirname, r'..\windows\libsvm.dll'))
else:
print path.joi... |
# -*- coding: ascii -*-
#
# Copyright 2006-2012 Andr\xe9 Malo or his licensors, as applicable
#
# 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.... |
import numpy as np
import logging
#from bfgs import lineSearch, BFGS
from pygmin.optimize import LBFGS
from mylbfgs_updatestep import mylbfgs_updatestep
__all__ = ["MYLBFGS"]
_logger = logging.getLogger("pygmin.optimize")
class MYLBFGS(LBFGS):
"""
minimize a function using the LBFGS routine
this cl... |
from functools import wraps
import inspect
import time
class Intraspector():
def __init__(self, debug=True):
self._trace = []
self._debug=debug
def record(self):
def record_decorator(func):
def wrapper(*args, **kwargs):
if self._debug:
tr... |
#!/usr/bin/env python
# Copyright (C) 2004-present Facebook. All Rights Reserved
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
"""Add, change, or delete a route on FBOSS controller
"""
import contextlib
import ipad... |
"""
@author: mweigert
A basic wrapper class around pyopencl.cl__array
"""
from __future__ import absolute_import, print_function
import numpy as np
import pyopencl.array as cl_array
import pyopencl as cl
from pyopencl.characterize import has_double_support
from gputools import get_device
from gputools.core.oclprogr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2017 Snowflake Computing Inc. All right reserved.
#
"""
Concurrent test module
"""
from logging import getLogger
from multiprocessing.pool import ThreadPool
import pytest
from parameters import (CONNECTION_PARAMETERS_ADMIN)
logger = getLogger(__name... |
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.sql import select
from sqlalchemy.sql import and_, or_, not_
from sqlalchemy.sql import text
from sqlalchemy import func, desc
print(sqlalchemy.__version__)
engine = create... |
# import tests
from config_tests import ConfigTests
from nodes_tests import NodesTests
from catalogs_tests import CatalogsTests
from pollers_tests import PollersTests
from obm_tests import OBMTests
from workflows_tests import WorkflowsTests
from workflowTasks_tests import WorkflowTasksTests
from tags_tests import TagsT... |
"""Async gunicorn worker for aiohttp.web"""
import asyncio
import os
import re
import signal
import sys
from types import FrameType
from typing import Any, Awaitable, Callable, Optional, Union # noqa
from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat
from gunicorn.workers import base
from aiohtt... |
from __future__ import print_function
import json
import logging
import os
from collections import OrderedDict
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
'''
Helper class for updating/retrieving Inventory data
Interesting info and formulas:
https:... |
# $language = "python"
# $interface = "1.0"
import os
import sys
import logging
# Add script directory to the PYTHONPATH so we can import our modules (only if run from SecureCRT)
if 'crt' in globals():
script_dir, script_name = os.path.split(crt.ScriptFullName)
if script_dir not in sys.path:
sys.path.... |
import numpy as np
import theano as theano
import theano.tensor as T
from utils import *
import operator
class TheanoRNN:
def __init__(self, word_dim, hidden_dim=100, bptt_truncate=4):
# Assign instance variables
self.word_dim = word_dim
self.hidden_dim = hidden_dim
self.bptt_trun... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.