code stringlengths 1 199k |
|---|
class LinkedList(object):
def __init__(self):
self.head = None
self.second = None
class Node(object):
def __init__(self,data):
self.data = data
self.next = None
def removeDup(self):
if self.head==None:
return
temp = self.head
next_next = None
while temp.next!=None:
if temp.data == temp.next... |
from django import forms
from . import validators
class UrlField(forms.CharField):
default_validators = [validators.UrlValidator()] |
from deluge._libtorrent import lt
import os
import glob
import base64
import logging
import threading
import tempfile
from urlparse import urljoin
import twisted.web.client
import twisted.web.error
from deluge.httpdownloader import download_file
import deluge.configmanager
import deluge.common
import deluge.component a... |
"""Manage user information and state.
Request handlers for /login, /logout and /signup."""
from flask import request, session, render_template, abort, redirect, flash, url_for
from flask_login import LoginManager, login_user, logout_user, login_required
from urlparse import urlparse, urljoin
from . import app
from .dat... |
from util import *
import time, os
import traceback
import sys
class Agent:
"""
An agent must define a getAction method, but may also define the
following methods which will be called if they exist:
def registerInitialState(self, state): # inspects the starting state
"""
def __init__(self, index... |
"""
buildintask.py Generated on 2017-09-22 14:15
Copyright (C) 2017-2031 YuHuan Chow <chowyuhuan@gmail.com>
"""
import sys
sys.path.append("../..")
from middleware.log import LogManager
import dbbase
class BuildinTask(DbBase):
"""Docstring for BuildinTask. """
def __init__(self, buildin_task):
super... |
import Snappy
class BrickLayer(Snappy.Sprite):
offset = 0
def When_r_Pressed(self):
self.drawrow()
def When_w_Pressed(self):
for i in range(5):
self.drawrow()
def When_space_Pressed(self):
self.Clear()
self.GoTo((-240,-160))
self.Hide()
def When_s_... |
from __future__ import print_function
import os
import pexpect
from pymavlink import mavutil
from common import AutoTest
from pysim import util
from pysim import vehicleinfo
import operator
testdir = os.path.dirname(os.path.realpath(__file__))
SITL_START_LOCATION = mavutil.location(-27.274439, 151.290064, 343, 8.7)
MIS... |
"""
WSGI config for hadronweb project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... |
import sys
import re
import io
definitionToSourceLocationMap = dict() # dict of tuple(parentClass, fieldName) to sourceLocation
fieldAssignDict = dict() # dict of tuple(parentClass, fieldName) to (set of values)
normalizeTypeParamsRegex = re.compile(r"type-parameter-\d+-\d+")
def normalizeTypeParams( line ):
return... |
from flask_admin.contrib.mongoengine import ModelView
__author__ = 'SALAR'
class BaseView(ModelView):
can_edit = True
can_delete = True
can_create = True
can_export = True
can_set_page_size = True
can_view_details = True |
import sys
sys.path.append('/home/pi/Desktop/ADL/YeastRobot/PythonLibrary')
from RobotControl import *
deck="""\
DW24P DW96W DW96W DW96W BLANK
DW24P BLANK BLANK BLANK BLANK
DW24P BLANK BLANK BLANK BLANK
DW24P BLANK BLANK BLANK BLANK
"""
OffsetDict={0: 'UL', 1: 'UR', 2: 'LL', 3: 'LR'}
DefineDeck(deck)
pr... |
from ctypes import *
import math
import time
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Print beamstrahlung spectrum generated by circe2")
parser.add_argument("-L",help="Directory of libpyISRBS.so. default=../lib/",dest="libdir", default="../lib/")
par... |
import logging
import re
import uuid
from flask import abort, g, make_response, render_template, request
from nwrsc.controllers.admin import Admin
from nwrsc.lib.encoding import json_encode
from nwrsc.lib.forms import *
from nwrsc.model import *
from nwrsc.model.superauth import SuperAuth
log = logging.getLogger(__name... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("ABM")
Dialog.resize(906, 584)
self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QL... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
# Flask settings
DEBUG = False
TESTING = False
DEVELOPMENT = False
CSRF_ENABLED = True
LOG_LEVEL = os.environ.get("LOG_LEVEL", "DEBUG")
# Heatflask settings
OFFLINE = False
APP_VERSION = ""
APP_N... |
import os, sys
from skrapa.core.database import Database
from skrapa.core.logger import logger
import skrapa.daemon as d
daemon = d.MyDaemon('/tmp/skrapa.pid')
db = Database()
def startSkrapa(path):
# If database exists, open it instead of creating new
if os.path.exists(path + '/database.json'):
db.open('database')... |
Workflow_2 = Workflow()
Function_3 = FunctionAction(
Inputs=[
Workflow_2.input()
],
Params=[
'x1',
'x2'
],
Expressions=[
'y1 = 2 * x1 + 2',
'y2 = 2 * x2 + 3'
]
)
Workflow_2.set_config(
OutputAction=Function_3,
InputAction=Function_3
)
Calibration_4... |
import requests
url = 'https://query.wikidata.org/sparql'
query = """
SELECT ?human ?humanLabel
WHERE
{
?human wdt:P21 ?gender
FILTER isBLANK(?gender) .
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en" }
}
limit 20
"""
r = requests.get(url, params = {'format': 'json', 'query': query})
... |
"""This module defines the class SdssForest to represent SDSS forests"""
from picca.delta_extraction.astronomical_objects.forest import Forest
from picca.delta_extraction.errors import AstronomicalObjectError
class SdssForest(Forest):
"""Forest Object
Methods
-------
__gt__ (from AstronomicalObject)
... |
from p2pool.bitcoin import networks
from p2pool.util import math
nets = dict(
bitcoin=math.Object(
PARENT=networks.nets['bitcoin'],
SHARE_PERIOD=10, # seconds
CHAIN_LENGTH=24*60*60//10, # shares
REAL_CHAIN_LENGTH=24*60*60//10, # shares
TARGET_LOOKBEHIND=200, # shares
... |
def ensure_fromlist(self, fromlist):
for sub in fromlist:
if sub:
if not recursive:
try:
all = 5
except AttributeError:
pass
else:
all = 6
continue |
from allauth.account.models import EmailAddress
from django.contrib.auth.models import User
from django.urls import reverse
from mock import patch
from postorius.tests.utils import ViewTestCase
class TestSubscription(ViewTestCase):
"""Tests subscription to lists"""
def setUp(self):
super(TestSubscriptio... |
import hashlib
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
print md5("t1.jpg") |
import math
import os
import json
from functools import lru_cache
from Rignak_Games.Entities import Entity
from Rignak_Games.Asteroid.Bullets import Bullet
from Rignak_Misc.path import get_local_file
SHIP_FILENAME = get_local_file(__file__, os.path.join('res', 'json', 'ships.json'))
class Ship(Entity):
def __init__... |
import geopy
from flask_babel import gettext
from plotting.plotter import Plotter
class LinePlotter(Plotter):
def parse_query(self, query):
super(LinePlotter, self).parse_query(query)
points = query.get("path")
if points is None or len(points) == 0:
points = ["47 N 52.8317 W", "4... |
"""
alfred
~~~~~~~~~~~~~~~~
This module provides a Alfred classes to manage requests.
"""
__author__ = "Laury Lafage"
__copyright__ = "Copyright 2016 alfred"
__contributors__ = []
__license__ = "GNU GENERAL PUBLIC LICENSE"
__version__ = "0.0.1"
__all__ = [] |
"""
Spyder Editor
Author Kushal
This is a temporary script file.
"""
import pandas as pd
import math
def data1_extract1(path,filename,ext,encoding="iso-8859-1"):
data_1 = pd.read_csv(path+filename+ext,encoding=encoding,header=0)
return data_1
def data2_extract2(path,filename,ext,encoding="iso-8859-1"):
data... |
from boxes import *
class Edges(Boxes):
"""Print all registerd Edge types"""
webinterface = False
def __init__(self):
Boxes.__init__(self)
def render(self):
self.ctx = None
self._buildObjects()
chars = self.edges.keys()
for c in sorted(chars, key=lambda x:(x.lower... |
""" Class to connect with the VMRC server """
from suds.client import Client
from radl.radl import Feature, system, FeaturesApp, SoftFeatures
class VMRC:
""" Class to connect with the VMRC server """
# define the namespace
namespace = 'http://ws.vmrc.grycap.org/'
server = None
def __init__(self, url... |
import os
import json
import requests
import sqlite3
from pprint import pprint
from datetime import datetime
from collections import OrderedDict
from waze_setup import DB_FILENAME, setup
if not os.path.exists(DB_FILENAME):
setup(DB_FILENAME)
con = sqlite3.connect(DB_FILENAME)
cur = con.cursor()
NOW = datetime.now()... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wins', '0020_auto_20160815_1357b'),
]
operations = [
migrations.AlterModelOptions(
name='breakdown',
options={'ordering': ['year']},
... |
from django.db import models
from django.contrib.auth.models import User
class Medico(models.Model):
OPCIONES = [
('hombre','Hombre'),
('mujer','Mujer'),
]
nombre = models.CharField(max_length = 50, null=True, blank=True)
apellido_materno = models.CharField(max_length = 50, null=True, blank=True)
ap... |
import zipfile
from bouncer.constants import READ, EDIT, CREATE, DELETE, MANAGE
from flask import Blueprint
from flask_login import login_required
from flask_restful import Resource
from sqlalchemy import and_, or_
from sqlalchemy.orm import contains_eager
from compair.authorization import require
from compair.models i... |
"""**Tests for safe common utilities**
"""
from safe.common.utilities import temp_dir, unique_filename
__author__ = 'Tim Sutton <tim@linfiniti.com>'
__version__ = '0.5.0'
__revision__ = '$Format:%H$'
__date__ = '21/08/2012'
__license__ = "GPL"
__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
__copyri... |
from varmed.settings.base import *
import os, sys, logging
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format='%(message)s')
logging.info("\n----------- << RESTART >> -----------\n")
logging.info("Settings file: " + os.path.basename(__file__))
DEBUG = True # If True, will return ... |
def milia(arabnum):
global mil
mil = (arabnum // 1000)
return(mil)
def centum(arabnum):
global mil
global cent
if (mil == 0):
cent = (arabnum // 100)
elif (mil == 1):
cent = ((arabnum - 1000) // 100)
elif (mil == 2):
cent = ((arabnum - 2000) // 100)
elif (mil ... |
from module.plugins.internal.SimpleCrypter import SimpleCrypter
class CrockoComFolder(SimpleCrypter):
__name__ = "CrockoComFolder"
__version__ = "0.01"
__type__ = "crypter"
__pattern__ = r'http://(?:www\.)?crocko.com/f/.*'
__description__ = """Crocko.com folder decrypter plugin"""
__author_name_... |
from yowsup.layers.protocol_iq.protocolentities.test_iq_result import ResultIqProtocolEntityTest
from yowsup.layers.protocol_media.protocolentities import ResultRequestUploadIqProtocolEntity
from yowsup.structs import ProtocolTreeNode
class ResultRequestUploadIqProtocolEntityTest(ResultIqProtocolEntityTest):
def se... |
import numpy as np
class Track(object):
def __init__(self,url,genre,length,fileType,title,band,bpm=None):
self.url = url
self.genre = genre
self.length = length
self.fileType = fileType
self.title = title
self.band = band
self.bpm = bpm
if not self.title:
self.title = ""
if not self.band:
self.... |
import unittest
from unittest.mock import patch
from collections import defaultdict
import numpy as np
from tmc import points
from tmc.utils import load, get_out
module_name="src.most_frequent_first"
most_frequent_first = load(module_name, "most_frequent_first")
def sort_rows(a):
"""Sort rows in lexicographical ord... |
import json
from pkg_resources import resource_filename
import datetime
import os
import plotly.offline as py
import jinja2
from pycoQC.common import *
from pycoQC.pycoQC_parse import pycoQC_parse
from pycoQC.pycoQC_plot import pycoQC_plot
from pycoQC import __version__ as package_version
from pycoQC import __name__ as... |
"""
Test suite for the window managing classes.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2014
:license:
GNU Lesser General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
from obspy import UTCDateTime
import os
import pytest
from lasif.window_manager import Window... |
from __future__ import absolute_import, print_function, unicode_literals
from . import util, exceptions
from distlib.database import DistributionPath
import os
class Database(object):
@classmethod
def check_installed(cls, requirement):
path = DistributionPath(include_egg=True)
package_name = uti... |
from hcsvlab_robochef.braided.ingest import *
from hcsvlab_robochef.braided import ingest
import unittest
import rdflib
SPKR = rdflib.term.URIRef(u'http://ns.ausnc.org.au/schemas/annotation/ice/speaker')
def unittests():
#res = doctest.DocTestSuite(ingest)
#res.addTest(unittest.makeSuite(UnitTest))
res = unittest... |
"""
pycman configuration handling
This module handles pacman.conf files as well as pycman options that
are common to all action modes.
"""
import io
import os
import glob
import sys
import argparse
import collections
import warnings
import pyalpm
class InvalidSyntax(Warning):
def __init__(self, filename, problem, arg)... |
class X: #(A)
m = 10 #(B)
n = 20 #(C)
def __init__( self, mm ): #(D)
self.m = mm ... |
__all__ = ['MainFrame']
from PyQt5 import QtWidgets
from utils.customs import Dimension
class Frame(QtWidgets.QMainWindow):
DIM = Dimension(0, 0)
def __init__(self):
super(Frame, self).__init__()
def setup(self):
raise NotImplementedError
def open(self):
raise NotImplementedError... |
from numpy import concatenate
import numpy
from resource_manager_base import resource_manager_base,start_resource_manager
class resource_manager (resource_manager_base):
def __init__(self,orb):
resource_manager_base.__init__(self,orb)
# set initial parameters
self.required_ber = 1e-4
self.constraint =... |
import songwrite2.model as model
import songwrite2.plugins as plugins
class ExportPlugin(plugins.ExportPlugin):
def __init__(self):
plugins.ExportPlugin.__init__(self, "TextTab", ["txt"], 1, 1)
def export_to(self, song, filename):
import texttab
if isinstance(song, model.Songbook):
data = u"\n\n... |
import pygtk
pygtk.require('2.0')
import gtk
from tumblpy import Tumblpy
import os
import platform
import json
from HTMLParser import HTMLParser
import catImageBox
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
ret... |
"""
Distance Metrics.
Compute the distance between two items (usually strings).
As metrics, they must satisfy the following three requirements:
1. d(a, a) = 0
2. d(a, b) >= 0
3. d(a, c) <= d(a, b) + d(b, c)
"""
from nltk.internals import deprecated
def _edit_dist_init(len1, len2):
lev = []
for i in range(len1):... |
from os import path
import json
from typing import List
import jinja2
from virgene.common_defs import FEATURES_DIR
from virgene.common_defs import TEMPLATES_DIR
class FeatureBase:
def __init__(self, name, identifier, feature_type, description,
enabled, category, installed, template: str, options: L... |
import errno
import os
import requests
from django.conf import settings
from lxml import etree
from requests import RequestException
from tenacity import (
retry,
retry_if_exception_type,
stop_after_attempt,
wait_fixed,
)
from ESSArch_Core.essxml.Generator.xmlGenerator import (
XMLGenerator,
par... |
import os
import time
import unittest
from xml.dom import minidom
from npoapi import MediaBackend
from npoapi.xml import mediaupdate
from npoapi.xml import poms
ENV = "acc"
MID = "WO_VPRO_783763"
CONFIG_DIR=os.path.dirname(os.path.dirname(__file__))
DEBUG=False
class MediaBackendTest(unittest.TestCase):
def __init_... |
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('CreateYourLaws', '0010_auto_20171222_1505'),
]
operations = [
migrations.RemoveField(
model_name='lawprop',
name='lawarticle_ptr',
),
... |
from __future__ import annotations
import threading
import typing
from nion.swift import DisplayCanvasItem
from nion.swift.model import UISettings
from nion.swift.model import Utility
from nion.ui import CanvasItem
from nion.ui import DrawingContext
from nion.utils import Geometry
if typing.TYPE_CHECKING:
from nion... |
import functools
import math
p_no = 150
emoa_points = [i/(p_no-1) for i in range(p_no)]
p_no2 = 300
emoa_points2 = [i/(p_no2-1) for i in range(p_no2)]
def emoa_fitness_2(f1, g, h, x):
y = g(x[1:])
return y * h(f1(x[0]), y)
def subfit1(x, f1):
return f1(x[0])
def subfit2(x, f1, g, h):
return emoa_fitness... |
import os
import glob
import sys
tests = glob.glob('test*.py')
for test in tests:
os.system('python %s' % test) |
import sys
import salome
salome.salome_init()
theStudy = salome.myStudy
import salome_notebook
notebook = salome_notebook.NoteBook(theStudy)
import os
sys.path.insert( 0, r'{}'.format(os.getcwd()))
sys.path.append('/usr/local/lib/python2.7/dist-packages')
if Z_2nd == Zt:
Z_2nd_artif = Zt+1.0 # just to ensure the ro... |
"""
This module defines a custom GUI text entry for file extensions, displaying a
popup with a list of supported file formats.
One can still enter a file extension not in the list in case an unrecognized
file format plug-in is used.
"""
from __future__ import absolute_import
from __future__ import print_function
from _... |
import operator
import bpy
from bpy_extras.view3d_utils import location_3d_to_region_2d, region_2d_to_origin_3d
import blf
import gpu
from gpu_extras.batch import batch_for_shader
from mathutils import Matrix, Vector
from ..lib import unit
class _LocAdapt:
__slots__ = "region", "region_3d", "scale", "offset"
de... |
from google.appengine.ext import ndb
from rest_framework.authentication import TokenAuthentication as BaseTokenAuth
from rest_framework.authentication import (
BaseAuthentication, CSRFCheck
)
from rest_framework import exceptions
from .models import Token
class TokenAuthentication(BaseTokenAuth):
model = Token
... |
from flask import Blueprint
main = Blueprint('main', __name__)
from . import views, errors, api |
import datetime
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext_lazy as _
from ..utils import time_horizon
from ..models import Deployment, ScheduleDelay
@login_required
def timeline(request):
deploy = get... |
from __future__ import print_function, division
import sys, os, subprocess, glob
import re
PFX_SFX_SEP = "-"
PERIOD_RE = "[0-9]{3,}([.][0-9]+)?"
PFX_RE = "[A-Za-z0-9_]+"
DAR_GLOB_SFX = ".[0-9]*.dar"
DEFAULT_SUFFIX = "%Y%m%d_%H%M%S_%f"
def suffix_now ():
import datetime
return datetime.datetime.now().strftime (DEFAU... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Feed.flow'
db.alter_column('rainman_feed', 'flow', self.gf('django.db.models.fields.FloatField')(null=True))
def ... |
import os
from __future__ import division
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
a = 0.5
b = 0.5
x = arange(0.01, 1, 0.01)
y = stats.beta.pdf(x, a, b)
plt.plot(x, y, '-')
plt.title('Beta: a=%.1f, b=%.1f' % (a, b), fontsize=15)
plt.xlabel('x', fontsize=15)
plt.ylabel('Probability ... |
from urllib.parse import urljoin
from pyquery import PyQuery
from novel import serial, utils, config
BASE_URL = 'http://www.11bz.org/{}_{}/'
class Bz11(serial.SerialNovel):
def __init__(self, tid):
super().__init__(utils.base_to_url(BASE_URL, tid), '#content:eq(1)',
intro_sel='#intr... |
from __future__ import print_function
import requests
TOKEN = "oxULdqRTAKNgPDbasjhL"
URL1 = "http://usmar-gitlab01.us.oracle.com:81/api/v3/groups?all_available=true"
URL2 = "http://usmar-gitlab01.us.oracle.com:81/api/v3/groups/%s/projects"
def main():
headers = {"PRIVATE-TOKEN":TOKEN}
for group in requests.get(... |
from org.eclipse.draw2d import MouseMotionListener
from org.eclipse.draw2d import FigureCanvas
from org.eclipse.draw2d import Panel
from org.eclipse.draw2d import Figure
from org.eclipse.draw2d import XYLayout
from org.eclipse.swt.widgets import Display;
from org.eclipse.swt.widgets import Shell;
from org.eclipse.draw2... |
import sys
from gurobipy import tuplelist
import random
from collections import OrderedDict
import networkx as nx
import copy
import data as d
from time import time
class Preprocess:
def __init__(self):
return
# done
def preprocess_with_weights(self, data, k):
data_components = list()
... |
import datetime
def daterange(start, stop):
"""Generator for date ranges
This is a generator for date ranges. Based on a start and stop value,
it generates one day intervals.
:param start: a date instance, end of range
:param stop: a date instance, end of range
:yield date: dates with one day in... |
from xml.parsers.expat import ParserCreate
class DefaultSaxHandler(object):
def start_element(self, name, attrs):
print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))
def end_element(self, name):
print('sax:end_element: %s' % name)
def char_data(self, text):
print('sax:char... |
from __future__ import division, print_function, absolute_import
__author__ = "Marek Rudnicki"
import numpy as np
from . import spikes
from . import stats
def plot_neurogram(spike_trains, fs, ax=None, **kwargs):
"""Visualize `spike_trains` by converting them to bit map and plot
using `plt.imshow()`. Set `fs` r... |
name = 'Rust'
file_patterns = ['*.rust', '*.rs']
built_in = """
Copy Send Sized Sync Drop Fn FnMut FnOnce drop Box ToOwned Clone
PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator
Extend IntoIterator DoubleEndedIterator ExactSizeIterator Option
Some None Result Ok Err SliceConcatExt Stri... |
from __future__ import unicode_literals
import itertools
import json
import erpnext
import frappe
import copy
from erpnext.controllers.item_variant import (ItemVariantExistsError,
copy_attributes_to_variant, get_variant, make_variant_item_code, validate_item_variant_attributes)
from erpnext.setup.doctype.item_g... |
"""
Functions to optimize shifts and microlensing between curves, minimizing a dispersion function of your choice.
Sometimes interactive plots are optional, the main goal is to return values or better change the lightcurves you pass
"""
import numpy as np
import scipy.optimize as spopt
import matplotlib.pyplot as plt
i... |
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 field 'PiezaConjunto.numero_inventario'
db.add_column(u'cachi_piezaconjunto', 'numero_inven... |
from gi.repository import Gtk, Gdk, GObject
from opendrop.mvp import ComponentSymbol, View, Presenter
from opendrop.utility.bindable.gextension import GObjectPropertyBindable
from opendrop.widgets.float_entry import FloatEntry
from opendrop.widgets.integer_entry import IntegerEntry
from .model import FigureOptions
figu... |
"""Unit tests for //deeplearning/clgen/cli.py."""
import os
import pathlib
import tempfile
from deeplearning.clgen import clgen
from deeplearning.clgen import errors
from deeplearning.clgen.proto import clgen_pb2
from labm8.py import app
from labm8.py import pbutil
from labm8.py import test
FLAGS = test.FLAGS
pytest_pl... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('overseas', '0026_niinfo_volume'),
]
operations = [
migrations.AlterField(
model_name='niinfo',
name='time',
field=mod... |
import os
import sys
import json
import csv
import codecs
wordints = {}
nextword = 1
"""
Iterate through the tokenized corpus, printing out integer tokens in-time
for each line.
"""
for line in sys.stdin:
words = line.strip().split(' ')
ints = []
for word in words:
if word not in wordints:
... |
import sys
import types
import os
import os.path
import unittest
from modules.Cheetah.NameMapper import NotFound, valueForKey, \
valueForName, valueFromSearchList, valueFromFrame, valueFromFrameOrSearchList
class DummyClass(object):
classVar1 = 123
def __init__(self):
self.instanceVar1 = 123
de... |
import fresh_tomatoes
import media
the_matrix = media.Movie("The Matrix",
"A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",
"https://images-na.ssl-images-amazon.com/images/M/MV5BMDMyM... |
import matplotlib.pyplot as plt
import numpy
import bsam_io
import bsam_plot
fig = plt.figure()
ax = fig.add_subplot(211)
data = bsam_io.parse_adaptive_data_file("out/m00000.dat")
root_patch = data['levels'][0][0]
bsam_plot.plot_grid(ax, data, 5)
bsam_plot.plot_interface(ax, root_patch)
bsam_plot.plot_contourf(ax, roo... |
import sys
import os
import pytest
from . import common
def test_valid():
from adjsim import core, analysis, utility
class ValidTracker(analysis.Tracker):
def __call__(self, value):
pass
test_sim = core.Simulation()
test_sim.trackers["count"] = ValidTracker()
common.step_simulate... |
import psycopg2 as dbapi2
from classes.court import Court
from classes.model_config import dsn, connection
class court_operations:
def __init__(self):
self.last_key=None
def get_courts(self):
global connection
courts=[]
try:
connection = dbapi2.connect(dsn)
... |
import gtk
import gobject
import threading
from chirp import errors, chirp_common
class ShiftDialog(gtk.Dialog):
def __init__(self, rthread, parent=None):
gtk.Dialog.__init__(self,
title=_("Shift"),
buttons=(gtk.STOCK_CLOSE, gtk.RESPONSE_OK))
s... |
# This file is part of HamsiManager.
import os, sys, platform
from Core.MyObjects import *
from Core import Universals as uni
from Core import Dialogs
from Core import Execute
from Core import ReportBug
import FileUtils as fu
pluginName = str(translate("MyPlugins/Explorer_CM", "Windows Explorer`s Context Menus"))
plug... |
from .base import ConfigBase
from flask_vises.deploy import DeployLevel
class Config(ConfigBase):
# Deploy
DEBUG = False
TEMPLATES_AUTO_RELOAD = False
DEPLOY_LEVEL = DeployLevel.release
# Session/Cookie/Flask-Login
SECRET_KEY = "THIS IS SECRET KEY, PLEASE CHANGE FOR PRODUCT ENVIRONMENT"
# Se... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import lines
import sys
import seaborn as sns
kms2kpcGyr = 1000./977.775
def method_comparison(results_file,name,dontplot=[],rangess=None,Jranges=None,MNL=[5,5]):
results = np.genfromtxt(results_file)
labels = [... |
execfile("../config.py")
from kirbybase import KirbyBase, KBError
from variousfct import *
from datetime import datetime, timedelta
import shutil
import os
import numpy as np
db = KirbyBase()
if thisisatest:
print "This is a test run."
images = db.select(imgdb, ['gogogo','treatme','testlist'], [True, True, True], ret... |
import serpent
from ethereum.tools import tester
from ethereum import utils
serpent_code = '''
data player[2](address, choice)
data num_players
data reward
data check_winner[3][3] # captures the rules of rock-paper-scissors game
def init():
#If 2, tie
#If 0, player 0 wins
#If 1, player 1 wins
#0 = rock
#1 = pap... |
from deepin_utils.config import Config as DConfig
class Config(DConfig):
'''
Config module to read *.ini file.
'''
def __init__(self,
config_file,
default_config=None):
'''
Init config module.
@param config_file: Config filepath.
@param d... |
import decimal
import math
def float2dec(f, digits=10):
parts = str(f).split(".")
if len(parts) > 1:
if parts[1][:digits] == "9" * digits:
f = math.ceil(f)
elif parts[1][:digits] == "0" * digits:
f = math.floor(f)
return decimal.Decimal(str(f))
def stripzeros(n):
"""
Strip zeros and convert to decimal.
... |
"""
Description: Simple multi-objective test function for design optimization with use of weighting factors resulting in a Pareto front
"""
from DesOptPy import OptimizationProblem
import numpy as np
class Multobj:
x = 2
def SysEq(self):
self.f1 = self.x
self.f2 = 100.0 - self.x ** 2
sel... |
import numpy as np
from matplotlib import pyplot
import rft1d
np.random.seed(0)
nResponses = 12
nTestStatFields = 2
nNodes = 101
nIterations = 2000
FWHM = 10.0
df = nResponses-1
sqrtN = np.sqrt(nResponses)
rftcalc = rft1d.prob.RFTCalculator(STAT='T', df=(1,df)... |
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Impact function Test Cases.**
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of t... |
import psutil
import sys
import os
pid = sys.argv[1]
leafPids = []
branchPids = []
def getallkids(mpid,leafPids,branchPids):
mmpid = psutil.Process(int(mpid))
mylasts = mmpid.children()
if(not mylasts):
leafPids.append(mpid)
return()
else:
branchPids.append(mpid)
for x in mylasts:
getallki... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.