src stringlengths 721 1.04M |
|---|
import os
import sys
import pinproc
import Queue
import yaml
import time
import copy
import logging
from procgame import config
from gameitems import *
from procgame import util
from mode import *
from pdb import PDBConfig, LED
from procgame import LEDs
def config_named(name):
if not os.path.isfile(name): # If we ... |
# in-progress; implementing SOCKS5 client-side stuff as extended by
# tor because txsocksx will not be getting Python3 support any time
# soon, and its underlying dependency (Parsely) also doesn't support
# Python3. Also, Tor's SOCKS5 implementation is especially simple,
# since it doesn't do BIND or UDP ASSOCIATE.
fr... |
'''
Created on Oct 4, 2013
@author: geraldine
'''
from ch.fluxkompensator.nelliepi.ui.screen.ScreenWithFooter import ScreenWithFooter
from ch.fluxkompensator.nelliepi.ui.widgets.TextButton import TextButton
from ch.fluxkompensator.nelliepi.Constants import RED
from ch.fluxkompensator.nelliepi.Constants import BLUE
fro... |
#! /usr/bin/env python
import sys
OFFSET = 6
train_line = None
test_line = None
for i, line in enumerate(sys.stdin):
if "Evaluation on training data" in line:
train_line = i + OFFSET
elif "Evaluation on test data" in line:
test_line = i + OFFSET
if i==train_line:
train_line = line
... |
__author__ = 'Jason'
import os, re, csv, ast, csv
import math
import jinja2
jinja_environment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
import flask
from utils import encode
def _show_frequent_features(mysql,g_sty):
topk... |
import sys
import os
import codecs
class Runner(object):
runnerName = None
def __init__(self):
'''
read input files and process
run directly on input files
run directly on input dir
process output
'''
pass
def run(self, args):
'''
i... |
#!/usr/bin/env python
from lxml import etree
import sqlite3
import os
import datetime
from shows_hosts_with_open_port_and_service_desc import parse_opts
__program__ = 'python_convert_nmap_xml_to_sqlite_db'
___author__ = 'dave b. <db@d1b.org>'
__license__ = 'GPL v2'
class nmap_xml_to_sqlite:
def __init__(self, filen... |
"""Databaes URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-b... |
import eventlet
import mock
import st2actions.resultstracker.resultstracker as results_tracker
from st2common.constants import action as action_constants
from st2common.exceptions.db import StackStormDBObjectNotFoundError
from st2common.persistence.action import Action
from st2common.persistence.executionstate import ... |
from django import forms
from django.utils.decorators import classproperty
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.utils.html import mark_safe
class BaseModelActionForm(forms.Form):
@classproperty
def MODEL_CHOICES(cls):
choices = sorted(C... |
"""
This is a script to build the NetPyNE html documentation
All steps should be executed from netpyne/doc
The following are required:
1) Sphinx documentation generator: https://www.sphinx-doc.org/en/master/
2) Sphinx RTD Theme
3) Autodoc summary table: https://autodocsumm.readthedocs.io/en/latest/index.html
4) Wheel... |
"""
CrossingCounter.py
By Denis Dube, 2005
"""
def countAllCrossings(levelDictionary):
"""
Returns all the edge crossings in the graph
Input: levelDictionary where each level is a list of NodeWrapper objects
Output: # of crossings between all the layers
"""
edgeCrossings = 0
for i in rang... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# 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
# Unles... |
# This plugin is adapted from the Python Console plugin and the IPython
# cookbook at:
# http://ipython.scipy.org/moin/Cookbook/EmbeddingInGTK
# Copyright (C) 2009-2010 Brian Parma
# Updated 2012 Brian Parma
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU... |
#!/usr/bin/env python
import os,sys
import pickle
import threading
from Queue import Queue
from pixiv_api import Pixiv
import pixivdl
import Tkinter
import ttk
import tkFileDialog
import tkMessageBox
class Application(Tkinter.Frame):
def __init__(self,master=None):
Tkinter.Frame.__init__(self,master)
... |
# Copyright 2001-2014 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this perm... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
from builtins import range
import numpy
import logging
import warnings
import collections
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def gridSearch(examples,
labels,
learner,
... |
# -*- coding: utf-8 -*-
#= DESCRIZIONE =================================================================
"""
Inietta una bimba in locanda.
"""
#= IMPORT ======================================================================
import random
from src.database import database
from src.defer import defer_random_time... |
'''
Created on Jul 28, 2015
.. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl>
'''
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import unittest
import unittest.mock as mock
from ema_workbench.em_framework.outcomes import ScalarOutcome,\
T... |
#!/usr/bin/python
# calculate the number of pixels for a stimulus
# fixed: viewer distance, vertical resolution, visual angle
# argv[1] = vertical screen height (cm)
from math import atan2, degrees
import sys
if sys.argv[1]:
h = float(sys.argv[1])
else:
h = 21.5 # Dell laptop
h = 20.6 # M... |
# SPDX-License-Identifier: LGPL-3.0-or-later
# dlb - a Pythonic build tool
# Copyright (C) 2020 Daniel Lutz <dlu-ch@users.noreply.github.com>
import testenv # also sets up module search paths
import dlb.di
import dlb.fs
import dlb.ex
import dlb_contrib.generic
import dlb_contrib.git
import dlb_contrib.sh
import os.pa... |
import re,sys,os,itertools
import ujson as json
## Umm, try to replicate config in 50_quadify ...
OPTS = {}
OPTS['min_date'] = '2009-08-03'
OPTS['max_date'] = '2012-09-30'
OPTS['msa_county_file'] = os.path.join(os.path.dirname(__file__), '../../../geo_metro/msa_counties.tsv')
OPTS['num_msas'] = 200
countyfips2regioni... |
# ETConf -- web-based user-friendly computer hardware configurator
# Copyright (C) 2010-2011 ETegro Technologies, PLC <http://etegro.com/>
# Sergey Matveev <sergey.matveev@etegro.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2014, Paweł Wodnicki
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, t... |
import os
import pyopencl as cl
def cls():
os.system('cls' if os.name=='nt' else 'clear')
def print_info(data):
for row in data:
if type(row[2]) == list:
print("{0:<2} {1:<40}: {2: >40}".format(row[0], row[1], row[2][0]))
for i in range(1, len(row[2])):
print("{... |
#!/usr/bin/env python
import base64
import hashlib
from datetime import datetime
import hmac
import binascii
import sys
import json
import requests
import pytz
def hextobyte(hex_str):
bytes = []
hex_str = ''.join( hex_str.split(' ') )
for i in range(0, len(hex_str), 2):
bytes.append( chr( int (hex... |
#!/usr/bin/python
class PartyAnimal:
#x = 0
#name = ""
def __init__(self,nam):
self.x = 0
self.name = nam
print self.name, "I am constructed"
def party(self):
self.x += 1
print self.name,"So far", self.x
def __del__(self):
print self.name, "I am destructed", self.x
an = PartyAnimal("Hitesh")
an.... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import unittest
import time
from robot.output.filelogger import FileLogger
from robot.utils import StringIO, robottime
from robot.utils.asserts import *
from robot.utils.robottime import TimestampCache
class _FakeTimeCache(TimestampCache):
def __init__(self):
self.fake = time.mktime((2006, 6, 13, 8, 37,... |
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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
# autogenerated file.
#
# ... |
# Copyright (c) 2019 PaddlePaddle 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 app... |
import zope.interface
class ICache(zope.interface.Interface):
"""
interface of cache center
wrapper of sth. like memcache and redis
"""
def set_value(key, value, expire):
"""
set key value pair to cache
"""
def get_value(key):
"""
get v... |
"""SAML2.0 IdP implementation
It contains endpoints to receive:
- authentication requests,
- logout request,
- logout response,
- name id management requests,
- name id management responses,
- attribut requests.
- logout
- logoutResponse
TODO:
- manageNameId
- manageNa... |
# coding=utf-8
import os
import threading
from os.path import expanduser, join, exists
import numpy as np
import pandas as pd
class BasketsHandler(threading.Thread):
def __init__(self, threadID, name, interactions):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name... |
#!/usr/bin/python2
# -*- coding: utf8 -*-
# Tiny_telecom is a tiny library of comunitions via Telegram Bot's API.
#Copyright (C) 2015 Juan Pablo Navarro
#This program 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 Softwar... |
"""Production settings and globals."""
from analytics_dashboard.settings.base import *
from analytics_dashboard.settings.yaml_config import *
from analytics_dashboard.settings.logger import get_logger_config
LOGGING = get_logger_config()
# ######### HOST CONFIGURATION
# See: https://docs.djangoproject.com/en/1.5/re... |
from functools import lru_cache
from types import MappingProxyType
from typing import Dict, Tuple
from deck_chores.config import cfg, CONTAINER_CACHE_SIZE
from deck_chores.utils import log
####
@lru_cache(maxsize=CONTAINER_CACHE_SIZE)
def container_name(container_id: str) -> str:
return cfg.client.containers.g... |
##############################################################################
#
# Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <info@alistek.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take th... |
# libjingle
# Copyright 2013 Google Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following dis... |
from django.db.models import F
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from pylinks.links.models import Category, Link
class LinkListView(ListView):
model = Link
context_object_name = 'links'
paginate_b... |
import discord
from discord.ext import commands
from bs4 import BeautifulSoup
from urllib.parse import quote_plus
class Converter:
def __init__(self, bot):
self.bot = bot
self.aiohttp_session = bot.aiohttp_session
self.url = 'https://google.com/search'
self.headers = {
... |
'''++
Copyright (C) 2019 3MF Consortium (Original Author)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditi... |
#!/usr/bin/env python3
"""
A curses-based version of Conway's Game of Life.
An empty board will be displayed, and the following commands are available:
E : Erase the board
R : Fill the board randomly
S : Step for a single generation
C : Update continuously until a key is struck
Q : Quit
Cursor keys :... |
import os
import shutil
from unicurses import *
from appdirs import *
SEPARATOR = (os.name in ['ce', 'nt', 'dos']) and '\\' or '/';
def add_vector(a, b):
return (a[0] + b[0], a[1] + b[1]);
def w_log( path, attr = "a+", string = '' ):
dir_path = user_log_dir("cnake");
path = "{}{}{}".format(dir_path, SEPARATOR... |
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.translation import ugettext as _
from django.conf import settings
from django.contrib.auth.models import User
from apps.thirdparty.userpro... |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear 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,... |
#!/usr/bin/env python
#
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Renders a single template file using the Jinga templating engine.'''
import argparse
import sys
import os
import itertools
sys.p... |
"""
Test watchpoint list, enable, disable, and delete commands.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class WatchpointCommandsTestCase(TestBase):
mydir = TestBase.compute_mydir(__f... |
""" Command line utilities for managing Galaxy servers
"""
from __future__ import print_function
import os
import sys
import json
import logging
import subprocess
from argparse import ArgumentParser
from .config_manager import ConfigManager
from .process_manager.supervisor_manager import SupervisorProcessManager
lo... |
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import unittest2 as unittest
import re
from bkr.client import BeakerWo... |
'''
XBMC LCDproc addon
Copyright (C) 2012-2018 Team Kodi
Copyright (C) 2012-2018 Daniel 'herrnst' Scheller
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 ... |
class PorterStemmer:
def __init__(self):
"""The main part of the stemming algorithm starts here.
b is a buffer holding a word to be stemmed. The letters are in b[k0],
b[k0+1] ... ending at b[k]. In fact k0 = 0 in this demo program. k is
readjusted downwards as the stemming progresses... |
#!/usr/bin/env python
"""Read the contents of a directory containing DFT output and create a csv style file of information"""
from __future__ import print_function
import sys
import dill as pickle
import PDielec.__init__
version = PDielec.__init__.__version__
def print_help():
print('pickled_reader filenames', fil... |
#!/bin/env python
import sys
import os
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import SGDRegressor
from boomlet.storage import joblib_load
from boomlet.transform.preprocessing import PercentileScaler
from autocause.challenge import target_score
CONFIGS_FOLDER = 'configs'
RES... |
from datetime import datetime as dt
import pandas as pd
import pkg_resources as pr
from astropy import units as u
from numpy import poly1d
from . import io
from .ringcube import RingCube
def get_year_since_resonance(ringcube):
"Calculate the fraction of the year since moon swap."
t0 = dt(2006, 1, 21)
td... |
'''
mcgui UI.
'''
import sys
import os
import re
from widgets import *
from PyQt5 import Qsci, QtWidgets
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from mccodelib import mccode_config
from mccodelib.utils import ComponentParser, ComponentParInfo
'''
View class containing windows and dialogs as del... |
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from django.template import RequestContext, Template, Context
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.http import Http404
from django.contrib.auth.decorators import login_required, permission_require... |
"""
minimize-content-pack
Remove assessment items, subtitles and po files from a content pack.
Usage:
minimize-content-pack.py <old-content-pack-path> <out-path>
"""
import zipfile
from pathlib import Path
from docopt import docopt
ITEMS_TO_TRANSFER = [
"metadata.json",
"content.db",
"backend.mo",
... |
__author__ = 'linlin'
import os
import logging
import pdb
logger = logging.getLogger('main_module')
def GetWordsDic(file_path):
file = open(file_path, 'r')
for line in file:
if ";;;;" in line:
break
dict = {}
for line in file:
if len(line) != 0:
dict[line.stri... |
# -*- coding: utf-8 -*-
# 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... |
from south.db import db
from django.db import models
from channelguide.channels.models import *
class Migration:
no_dry_run = True
def forwards(self, orm):
"Write your forwards migration here"
for channel in orm.Channel.objects.all():
for field in ('owner', 'featured_by', 'moderat... |
import sys
import argparse
from itertools import izip
import pybedtools as bt
import os
def parseArgument():
# Parse the input
parser = argparse.ArgumentParser(description="Select the FIMO cutoff by maximizing F1 for a list of FIMO files")
parser.add_argument("--FIMOFileListFileName", required=True, \
help="List ... |
#! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# Instanciate one distribution object
distribution = Gumbel(2.0, -0.5)
print("Distribution ", repr(distribution))
print("Distribution ", distribution)
# Is this dis... |
# -*- coding: utf-8 -*-
"""Kontalk XMPP s2s component."""
"""
Kontalk XMPP server
Copyright (C) 2014 Kontalk Devteam <devteam@kontalk.org>
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, eithe... |
import xml.etree.ElementTree as ET
import math
from util import *
''' Reference for next 2 functions: http://wiki.openstreetmap.org/wiki/Mercator'''
def merc_x(lon):
r_major=6378137.000
return r_major*math.radians(lon)
def merc_y(lat):
if lat>89.5:lat=89.5
if lat<-89.5:lat=-89.5
r_major=6378137.000
r_minor=63... |
import normalize as n
import cluster as c
import jsonpickle as j
import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument('matrix')
parser.add_argument('options')
args = parser.parse_args()
matrix = ast.literal_eval(args.matrix)
options = ast.literal_eval(args.options)
# steps:
# 1. norma... |
import random
from unittest import TestCase
from hamcrest import *
from chapter17.textbook17_4 import table_insert, table_delete
from datastructures.dynamic_table import DynamicTable
class TestTextbook17_4(TestCase):
def test_table_insert(self):
nelements = 20
elements = [random.randint(0, 999)... |
import time
from pykka.actor import ThreadingActor
from pykka.registry import ActorRegistry
def time_it(func):
start = time.time()
func()
print('%s took %.3fs' % (func.func_name, time.time() - start))
class SomeObject(object):
baz = 'bar.baz'
def func(self):
pass
class AnActor(Thread... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'SessionBlockTweet.next'
db.delete_column(u'twit_sessionblocktweet', 'next_id')
# ... |
# This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will b... |
"""
Custom storage system for Mosso Cloud Files within Django.
"""
import re
from django.conf import settings
from django.core.files import File
from django.core.files.storage import Storage
from django.core.exceptions import ImproperlyConfigured
try:
import cloudfiles
from cloudfiles.errors import NoSuchObje... |
from mail.mail_message import truncate_text
from openerp.osv import orm, fields
from tools.translate import _
class bom_add_note(orm.TransientModel):
"""Adds a new note to the case."""
_name = 'bom.add.note'
_description = "Add Internal Note"
_columns = {
'body': fields.text('Note Body', requ... |
#
# Copyright 2018 Analytics Zoo 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 applicable law or agreed to... |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import hashlib
import json
import collections
import pprint
class Dependency(object):
def __init__(self,**kwargs):
assert"sha1"not in kwargs
if'recurse'not in kwargs:
kwargs['recurse']=True
... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VmfsDatastoreInfo(vim, *args, **kwargs):
'''Information details about a VMFS datastor... |
# -*- coding:Latin-1 -*-
#####################################
# Bombardement d'une cible mobile #
# (C) G. Swinnen - Avril 2004 - GPL #
#####################################
from Tkinter import *
from math import sin, cos, pi
from random import randrange
from threading import Thread
class Canon:
"""Petit cano... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-04-07 19:07
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('venta', '0025_auto_20160216_1... |
# -*- coding: utf-8 -*-
#
# Author: Alejandro J. Cura <alecu@canonical.com>
#
# Copyright 2010 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 dis... |
import os
import json
from dateutil.parser import parse
import plotly
from plotly.graph_objs import Histogram, Scatter, Scatter3d, Data, Layout, XAxis, YAxis, ZAxis, Figure
__version__ = '0.0.1'
def is_numeric(x):
try:
float(x)
return True
except ValueError:
return False
def... |
import unittest
import transaction
from pyramid import testing
def dummy_request(dbsession):
return testing.DummyRequest(dbsession=dbsession)
class BaseTest(unittest.TestCase):
def setUp(self):
self.config = testing.setUp(settings={
'sqlalchemy.url': 'sqlite:///:memory:'
})
... |
from opencog_b.python.blending.connector.connect_conflict_random import \
ConnectConflictRandom
from opencog_b.python.blending.connector.connect_conflict_viable import \
ConnectConflictAllViable
from opencog_b.python.blending.connector.connect_simple import ConnectSimple
from opencog_b.python.blending.util.blen... |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is distributed... |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
#Copyright (c) 1986 Nick Wong.
#Copyright (c) 2016-2026 TP-NEW Corp.
# License: TP-NEW (www.tp-new.com)
__author__ = "Nick Wong"
'''
virtualenv 为应用创建“隔离”环境
virtualenv为应用提供了隔离的Python运行环境,解决了不同应用间多版本的冲突问题。
python3.3以后自带venv模块支持轻量级虚拟环境,virtualenv模块仍然支持,可安装。
1.创建虚拟环境
vir... |
import itertools
import random
import pytest
from pyope.hgd import HGD
from pyope.ope import ValueRange
from pyope.stat import sample_uniform
def test_uniform():
# Short ranges
value = 10
unit_range = ValueRange(value, value)
assert sample_uniform(unit_range, []) == value
short_range = ValueRange... |
#!/usr/bin/env python
#new unionfind code, still using dictionaries but not as weird as other version
#also rewritten from scratch using orig paper + clrs as a guide
class unionFind(object):
'''allows union, find, tolists, uses path compression and join by rank,
from CLRS algorithms textbook and previous c imple... |
#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
# Copyright 2013-2014 Sebastian Werner
#
import re
import os
import hashlib
import tempfile
import subprocess
import sys
import shlex
import jasy.core.Console as Console
import jasy.core.Base62 as Base62
def executeCommand(args, failMessage=None, pat... |
# encoding: utf-8
from collections import Counter
import re
import os.path
#from https://mathiasbynens.be/demo/url-regex diego's one
VALID_URL= re.compile(r"^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9... |
import random
import pygame
import pygame.mixer
from pygame.locals import *
from constants import *
import global_vars as g
class SoundEngine():
def __init__(self):
if not pygame.mixer: print "Warning, sounds are disabled!"
pygame.mixer.init()
# states
self.playingSound = False
... |
from django.forms import ModelForm
from django.template.loader import render_to_string
from models import Recipe
import django.forms as forms
from django.forms.models import BaseInlineFormSet
from django.conf import settings
from django.contrib.sites.models import Site
from django.template import loader, RequestContext... |
from argparse import Namespace
import unittest
from migrator import main
class TestMain(unittest.TestCase):
def test_noop(self):
"""Test that noop function can take variable amount of parameters."""
test = []
for i in range(5):
main.noop(*test)
test.append(i)
... |
#!/usr/bin/env python
# This file is part of nexdatas - Tango Server for NeXus data writer
#
# Copyright (C) 2012-2017 DESY, Jan Kotanski <jkotan@mail.desy.de>
#
# nexdatas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak 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 So... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import etl_plugin_core
#
# get taxonomy for aggregated facets / filters
#
# example: '§ 153 Abs. 1 Satz 2' -> ['§ 153', '§ 153 Absatz 1', '§ 153 Absatz 1 Satz 2']
# todo:
def get_taxonomy(law_clause, law_code = None):
law_clauses = [law_clause]
ret... |
import datetime
import re
import StringIO
import stem
import stem.control
import stem.descriptor.router_status_entry
import stem.response
import stem.version
from stem.util import connection, log, str_tools, tor_tools
# Matches keyword=value arguments. This can't be a simple "(.*)=(.*)" pattern
# because some positi... |
"""
List with unique entries. UniqueList does not allow null nor duplicates.
"""
__version__= '$Revision: 11 $'[11:-2]
__author__ = "Duan Guoqiang (mattgduan@gmail.com)"
class UniqueList(list):
def __init__(self, initlist=[]):
# call super class
list.__init__(self)
# add initlist
... |
import re
def fileToDic(configFile):
def isAlphaNumUnder(s):
return s.isalpha() or s == '_' or s.isdigit()
keyValueDict = {}
for line in configFile:
if(line[0] == '#'):
pass
else:
foundKey = False
foundSeparator = False
foundValue = False
lineKey = ""
lineValue = ""
for currentChar i... |
"""
FEniCS tutorial demo program: Poisson equation with Dirichlet conditions.
As d1_p2D.py, but chosing linear solver and preconditioner is demonstrated.
-Laplace(u) = f on the unit square.
u = u0 on the boundary.
u0 = u = 1 + x^2 + 2y^2, f = -6.
"""
from dolfin import *
# Create mesh and define function space
mesh ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
"""To build simple dialogues etc. (requires wxPython)
"""
from __future__ import absolute... |
"""Babbage - Framework for decoding data.
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless req... |
import random
import pickle
import numpy as np
import networkx as nx
from app.optim import slow_compute_loss, step
def main(input_file, num_police, num_steps, prob_step):
"""
Parameters
----------
num_police : the number of police to use
num_steps : the number of steps to take
prob_step : th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.