code
stringlengths
1
199k
""" MIT License Copyright (c) 2016 Arnaud Aliès Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di...
__title__ = "gapy" __version__ = "1.3.6" __author__ = "Government Digital Service"
""" @author: Dr Ekaterina Abramova, 2017 INTENDED USE: Tutorial on different ways of calculating a Fibonacci sequence and returning n-th element of this sequence. Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21 etc n-th element index: 1, 2, 3, 4 ,5, 6, 7, 8, 9 etc PARAMETERS: n - the position of an element in a seque...
from pyqtgraph.Qt import QtGui, QtCore import collections, os, weakref, re from ParameterItem import ParameterItem PARAM_TYPES = {} def registerParameterType(name, cls, override=False): global PARAM_TYPES if name in PARAM_TYPES and not override: raise Exception("Parameter type '%s' already exists (use o...
""" @api {post} /send/sms 01_Send_SMS @apiGroup "SMS" @apiName 01_Send_SMS @apiVersion 0.1.0 @apiDescription Send SMS to specified number. @apiParam {string} mobileno Phone number. @apiParam {string} message SMS message. @apiParam {string} message_type Message type (Zenziva). @apiParam {boolean} [qu...
import tensorflow as tf from data import inputs from .inference import inference from .model import train_step, cal_loss, cal_accuracy from .hooks import hooks BATCH_SIZE = 128 LAST_STEP = 20000 LEARNING_RATE = 0.1 EPSILON = 1.0 BETA_1 = 0.9 BETA_2 = 0.999 DROPOUT = 0.5 SCALE_INPUTS = 1 DISTORT_INPUTS = True ZERO_MEAN_...
""" Locale-aware builtin functions """ from rpython.rlib.rlocale import (setlocale as rsetlocale, LocaleError, localeconv as rlocaleconv, nl_langinfo as rnl_langinfo) from rpython.rlib import rlocale from rpython.rtyper.lltypesystem.rffi import charp2str from rpython.rtyper.lltypesystem import rffi from rpython...
import pygame import random import math class Rabbit(object): def __init__(self, x, y, upper, lower, screen_width, screen_height): width = math.floor(screen_width/6) height = math.floor(screen_height/6) self.img = pygame.image.load("rabbit1.png") self.img = pygame.transform.scale(sel...
__author__ = 'tilmannbruckhaus' import unittest import string_distance class TestStringDistance(unittest.TestCase): def test_string_distance(self): fixtures = [["baba", "ba", 4], ["ab", "ab", 2], ["x", "x", 1], ["", "", 0], ["ab...
from blog import db from blog.tags import Tag def test_show_tag(tagsetup): r = tagsetup.app.get('/tags/1') assert r.status_code == 200 assert 'Tag test' in r.data tagsetup.done() def test_cannot_show_nonexisting_tag(tagsetup): r = tagsetup.app.get('/tags/2') assert r.status_code == 404 asser...
import numpy as np from matplotlib.colors import colorConverter as cc from matplotlib.patches import Polygon as MplPol from numpy import sqrt, arctan2, pi, sin, cos class Point(object): def __init__(self, ax, x, y, **kwargs): self._update_func = kwargs.get('update', lambda p,t,dt: None) dot, = ax.pl...
"""Config Port Stats message tests.""" from pyof.v0x04.controller2switch.multipart_reply import PortStats from tests.test_struct import TestStruct class TestPortStats(TestStruct): """Config Port Stats message tests.""" @classmethod def setUpClass(cls): """Configure raw file and its object in parent ...
import matplotlib.pyplot as plt import numpy as np from hexgrid.plotting import plot_hexagons from hexgrid import HexPoints col, row = np.array([ [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], ], dtype=int).T hexpoints_even_row = HexPoints.from_even_row_offse...
from django.shortcuts import render, redirect from django.views.generic import View from sentiment.models import Tweet, Word from sentiment.bayes import * from django.db.models import Avg from django.http import JsonResponse class IndexView(View): template = 'sentiment/index.html' def get(self, request): ...
from .sub_resource import SubResource class ApplicationGatewayBackendAddressPool(SubResource): """Backend Address Pool of an application gateway. :param id: Resource ID. :type id: str :param backend_ip_configurations: Collection of references to IPs defined in network interfaces. :type backend_...
""" The Plaid API The Plaid REST API. Please see https://plaid.com/docs/api for more details. # noqa: E501 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from plaid.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ...
import logging class Post(object): def __init__(self, slug, title, reference, time, author, author_email, content): self.slug = slug self.title = title self.reference = reference self.author = author self.author_email = author_email self.time = time self.conte...
from setuptools import setup version = '0.1' setup(version=version, name='nexus-root', description="Root your Nexus.", packages=[ ], scripts=[ ], long_description="""Root your Nexus.""", classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers includ...
import csv import statistics from urllib.request import urlopen base = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/" feed_url = base + "4.5_week.csv" source = urlopen(feed_url) text = source.read().decode() reader = csv.DictReader(text.splitlines()) depths = [ float(record["depth"]) for record in reader ]...
""" parse_address """ import os from csv import reader dirs = { 'N': ['N', 'NORTH', 'NO'], 'S': ['S', 'SOUTH', 'SO'], 'E': ['E', 'EAST', 'EA'], 'W': ['W', 'WEST', 'WE'] } houseNumSufList = ['1/4', '1/3', '1/2', '2/3', '3/4'] searchStates = { 'houseNumber': 1, 'houseNumberSuffixOrPrefixDirection'...
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_databas...
import _plotly_utils.basevalidators class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="showexponent", parent_name="layout.ternary.caxis", **kwargs ): super(ShowexponentValidator, self).__init__( plotly_name=plotly_name, ...
from setuptools import setup with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.md') as history_file: history = history_file.read() requirements = [ "logging", "argparse", "numpy", "matplotlib", "pandas", "more_itertools", "seaborn" ] test_requireme...
from CIM14.IEC61970.Dynamics.TurbineGovernors.TurbineGovernor import TurbineGovernor class GovSteamFV3(TurbineGovernor): def __init__(self, *args, **kw_args): """Initialises a new 'GovSteamFV3' instance. """ super(GovSteamFV3, self).__init__(*args, **kw_args) _attrs = [] _attr_types ...
import _plotly_utils.basevalidators class Tick0Validator(_plotly_utils.basevalidators.AnyValidator): def __init__(self, plotly_name="tick0", parent_name="layout.xaxis", **kwargs): super(Tick0Validator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit...
import logging import os class GenericObject(object): def getLogger(): console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter( logging.Formatter( '[%(levelname)s][%(module)s:%(funcName)s]: %(message)s', ) ) ...
from django.shortcuts import render, render_to_response from core.models import * from core.forms import * from django.core import serializers from django.core.context_processors import csrf from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.exceptions import ObjectDoesNotExist fr...
import re import traceback import urllib2 import pandas as pd import json,random,time,datetime from bs4 import BeautifulSoup from pandas.tseries.offsets import YearEnd from sqlalchemy import text from webapp import db, app from webapp.models import FinanceBasic headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows ...
import py, pytest from rpython.conftest import option from rpython.annotator.model import UnionError from rpython.rlib.jit import (hint, we_are_jitted, JitDriver, elidable_promote, JitHintError, oopspec, isconstant, conditional_call, elidable, unroll_safe, dont_look_inside, conditional_call_elidable, enter_...
import unittest from mgz.fast.header import parse from mgz.util import Version class TestFastUserPatch15(unittest.TestCase): @classmethod def setUpClass(cls): with open('tests/recs/small.mgz', 'rb') as handle: cls.data = parse(handle) def test_version(self): self.assertEqual(self...
import deepchem as dc import numpy as np def test_reshard_with_X(): """Test resharding on a simple example""" X = np.random.rand(100, 10) dataset = dc.data.DiskDataset.from_numpy(X) assert dataset.get_number_shards() == 1 dataset.reshard(shard_size=10) assert (dataset.X == X).all() assert dataset.get_numb...
def v11_larger_h(x, y, z, h, H, imax=4.0): r = np.sqrt(x**2 + y**2) return np.array(integrate.quad(j0sh, 0, imax,args=(r, z, h, H))) + \ x**2 / r * h0 * np.array(integrate.quad(j1xsh, 0, imax,args=(r, z, h, H))) def v11_smaller_h(x, y, z, h, H, imax=4.0): r = np.sqrt(x**2 + y**2) return n...
__author__ = 'rcj1492' __created__ = '2015.07' __license__ = 'MIT' ''' PLEASE NOTE: ec2 package requires the boto3 module. (all platforms) pip3 install boto3 ''' try: import boto3 except: import sys print('ec2 package requires the boto3 module. try: pip3 install boto3') sys.exit(1) from labpack.authe...
import _plotly_utils.basevalidators class ValueValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="value", parent_name="sunburst.marker.colorbar.tickformatstop", **kwargs ): super(ValueValidator, self).__init__( plotly_nam...
""" rotations.py """ import numpy as np def rotz(angle): return np.array( [ [np.cos(angle), -np.sin(angle), 0], [np.sin(angle), np.cos(angle), 0], [0, 0, 1], ] ) def roty(angle): return np.array( [ [np.cos(angle), 0, np.sin(angle)], ...
import unittest import ast import pandas as pd from blotter import blotter from pandas.util.testing import assert_dict_equal class TestBlotter(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def assertEventEqual(self, ev1, ev2): self.assertEqual(ev1.type, ev2.type)...
__author__ = 'Moch'
import unittest from monthly_budget.models.income import Income class TestIncome(unittest.TestCase): def test_converts_hourly_to_salary(self): rate = 35.00 # dollars an hour income = Income(rate=rate) self.assertEqual(72800.00, income.get_salary()) def test_initalizes_with_salary(self):...
class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ reach = 1 for i in nums: if reach <= 0: return False else: reach = max(reach - 1, i) return True
import base64 from Crypto.Cipher import AES from Crypto import Random import json import sys fp = open(sys.argv[1]) read_file = json.load(fp) for key in read_file: if 'Key' in key: decoded_key = base64.b64decode(read_file[key]) if 'Pdf' in key: decoded_pdf = base64.b64decode(read_file[key]) iv = R...
from django.urls import path from InternetSemLimites.markdown.views import fame, shame app_name = 'markdown' urlpatterns = [ path('README.md', fame, name='fame'), path('HALL_OF_SHAME.md', shame, name='shame'), ]
from bot.TwitchBot import TwitchBot class YusticeBot(TwitchBot): pass class YusticeObserverBot(TwitchBot): def chat_message(self, user, message): pass
import datetime import itertools import sqlalchemy as sa from sqlalchemy import Boolean from sqlalchemy import cast from sqlalchemy import DateTime from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy import Integer from sqlalchemy import literal from sqlalchemy impor...
"""Find good/bad examples of cross-identification. Input files: - ??? Output files: - images/cdfs_ba_grid.pdf - images/cdfs_ba_grid.png Matthew Alger <matthew.alger@anu.edu.au> Research School of Astronomy and Astrophysics The Australian National University 2017 """ import matplotlib.pyplot as plt import configure_plot...
r""" Pore seed models are use to calculate random numbers for each pore, which can subsequently be used in statistical distributions to calculate actual pore sizes. .. autofunction:: openpnm.models.geometry.pore_seed.random .. autofunction:: openpnm.models.geometry.pore_seed.spatially_correlated """ import numpy as _np...
from __future__ import unicode_literals from django.db import migrations, models FLOWCELL_STATUS_INITIAL = 'initial' FLOWCELL_STATUS_SEQ_RUNNING = 'seq_running' FLOWCELL_STATUS_SEQ_COMPLETE = 'seq_complete' FLOWCELL_STATUS_SEQ_RELEASED = 'seq_released' FLOWCELL_STATUS_SEQ_FAILED = 'seq_failed' FLOWCELL_STATUS_DEMUX_STA...
from flask.ext.login import LoginManager from .models import User login_manager = LoginManager() @login_manager.user_loader def load_user(user_id): return User.query.get(user_id)
import numpy as np import WrightTools as wt from WrightTools import datasets def test_perovskite(): p = datasets.wt5.v1p0p0_perovskite_TA # axes w1=wm, w2, d2 # A race condition exists where multiple tests access the same file in short order # this loop will open the file when it becomes available. whi...
from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "Hexagon-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ", ""...
from setuptools import setup, find_packages setup( name='PicRandomFromImgur', version='1.0', author='Philip merk0ff', packages=find_packages(), install_requires = [ 'beautifulsoup4' ] )
from .models import Item, Category from vendor.models import Store from django.shortcuts import get_object_or_404, render def index(request): item_list = Item.objects.all() context = {'item_list': item_list} return render(request, 'vip/index.html', context) def block(request): category_list = Category.o...
""" For Class #3 of an informal mini-course at NYU Stern, Fall 2014. Topics: pandas data management Repository of materials (including this file): * https://github.com/DaveBackus/Data_Bootcamp Prepared by Dave Backus, Sarah Beckett-Hile, and Glenn Okun Created with Python 3.4 """ import pandas as pd """ Examples of Da...
SQLALCHEMY_DATABASE_URI = 'mysql://admin:admin@mysql/framgiatw'
from __future__ import print_function import os from os.path import join as pjoin import sys import textwrap import re import types import shutil import subprocess import platform import SCons.Node.FS def quoted(s): """ Returns the given string wrapped in double quotes.""" return '"%s"' % s def mglob(env, subdi...
import os.path from parser.leftLexer import * from parser.leftVisitor import * from parser.leftParser import * from CodeGen.variables import * from CodeGen.functions import * from CodeGen.visitor import * from CodeGen.irgenerator import IRGenerator from CodeGen.compiler import IRCompiler from llvmlite import ir varnam...
from django.apps import AppConfig class FirstConfig(AppConfig): name = 'first'
from database import db class GuessUser(db.Model): __tablename__ = "guess_users" id = db.Column(db.Integer(), primary_key=True) guess_id = db.Column(db.Integer(), db.ForeignKey('guess.id')) tuser_id = db.Column(db.Integer())
import collections import datetime import logging import re from typing import Dict, List, Mapping, MutableSequence, Sequence, Tuple import pytz from google.appengine.ext import ndb from pyre_extensions import none_throws from backend.common.consts.alliance_color import AllianceColor from backend.common.consts.comp_lev...
import os template_sh = '''\ export WEST_ROOT={WESTROOT} export WEST_BIN={WESTBIN} export WEST_PYTHON={WESTPYTHON} export PATH=$WEST_BIN:$PATH \n''' template_csh = '''\ setenv WEST_ROOT "{WESTROOT}" setenv WEST_BIN "{WESTBIN}" setenv WEST_PYTHON "{WESTPYTHON}" \n''' with open('westpa.sh', 'w') as f: f.write(templat...
from __future__ import print_function import numpy as np from genomic_neuralnet.config import PARALLEL_BACKEND from genomic_neuralnet.methods import get_lasso_prediction from genomic_neuralnet.analyses import run_optimization def main(): alphas = list(np.arange(0.01, 1.01,0.01)) params = {'alpha': alphas} r...
from importlib import import_module from moneybot import config from moneybot.exc import InvalidCommand from moneybot.ledger import get_user_balance from os import listdir COMMANDS = {} class Moneybot: async def get_balance(self): return await get_user_balance(self.server_id, self.author_id) async def i...
from json import loads, dumps, JSONEncoder class _JsonEncoder(JSONEncoder): def default(self, o): if isinstance(o, set): return list(o) return JSONEncoder.default(self, o) class JsonSerializer(object): @staticmethod def dumps(o): return dumps(o, cls=_JsonEncoder) @sta...
import re, os, sys, shutil from math import * from string import * from optparse import OptionParser """ In this version of this program the coords for each match type are stored in arrays - if there are duplicates, they are inlcluded, but they are not noted as duplicates in any way -- this was taking too long Eventual...
r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base....
import os import sys import tempfile import yaml import zlib import sha import numpy as np import pandas as pa import simplejson as js import subprocess as sb from time import time,sleep from os import path from scipy.stats.mstats import mquantiles from sklearn.feature_selection import SelectKBest, f_classif from sklea...
from django.http import HttpResponseRedirect from django.http import HttpResponse from django.contrib.auth import authenticate, login, logout from django.template import RequestContext from django.shortcuts import render_to_response from social_network.forms import UserForm, UserProfileForm from social_network.models i...
from question_processor_core import QuestionProcessorCore from gensim.models import Word2Vec from model_wrapper import VectorModelWrap from models_params import model_params from multiprocessing import Pool, Lock from functools import partial import os import pickle import traceback import gc def l(s): s = s.lower(...
import requests from copy import deepcopy class Resource: _uri = None def __init__(self, uri): self._uri = uri def __repr__(self): return "<Resource %s>" % self._uri def __str__(self): return self._uri __unicode__ = __str__ def __getitem__(self, name): return Reso...
'''auto filtering call chain test mixins''' from inspect import ismodule from twoq.support import port class ASliceQMixin(object): def test_first(self): self.assertEqual(self.qclass(5, 4, 3, 2, 1).first().end(), 5) def test_nth(self): self.assertEqual(self.qclass(5, 4, 3, 2, 1).nth(2).end(), 3) ...
from os.path import join, dirname from django.conf.urls.defaults import * urlpatterns = patterns('giraffe.publisher.views', url(r'^$', 'index', name='publisher-index'), url(r'^page/(?P<page>\d+)', 'index', name='publisher-index-page'), url(r'^feed$', 'index', {'template': 'publisher/feed.xml', 'content_type...
import math import requests import requests_cache import ephem import datetime from math import degrees from calendar import timegm requests_cache.install_cache('satellite', backend='memory', expire_after=300) def chunks(l, n): """ Yield successive n-sized chunks from l""" for i in range(0, len(l), n): ...
import os import os.path from skidl import * def convert_libs(from_dir, to_dir): lib_files = [l for l in os.listdir(from_dir) if l.endswith(lib_suffixes[KICAD])] for lib_file in lib_files: print(lib_file) basename = os.path.splitext(lib_file)[0] lib = SchLib(os.path.join(from_dir, lib_fi...
from tvd.dvd.tvseries import TVSeriesDVD import numpy as np import pandas from pkg_resources import resource_filename class test_TVSeriesDVD(object): def setup(self): # load DVD groundtruth self.dvds = pandas.read_csv( resource_filename(__package__, 'data/test.csv'), converte...
""" TODO: turn this into the API Gateway? TODO: authentication and authorization should go here? The ScoreKeeper application lets users define, create and keep track of any type of game or competition. Behind the scenes, we're aiming at a microservices architecture, keeping all services neatly separated...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('inventory', '0003_auto_20160610_1223'), ] operations = [ migrations.AlterField( model_name='item', name='name', field...
import numpy import chainer from chainer import backend from chainer.backends import cuda from chainer.backends import intel64 from chainer import configuration from chainer import function_node import chainer.functions from chainer.utils import argument from chainer.utils import conv from chainer.utils import type_che...
import unittest import numpy import chainer from chainer import cuda from chainer import testing from chainer.testing import attr import chainer.training.updaters.multiprocess_parallel_updater as mpu import copy class SimpleNet(chainer.Chain): insize = 5 def __init__(self): super(SimpleNet, self).__init...
import disamby.preprocessors as prep from disamby import Disamby import pytest pipeline = [prep.normalize_whitespace, prep.remove_punctuation, prep.compact_abbreviations, lambda x: prep.ngram(x, 4)] @pytest.mark.parametrize('size', [20, 1000, 2000]) def test_fitting(size, company_df,...
import click import json import os @click.group() def cli(): pass @cli.command("compactdb") @click.option('-d', '--dir', required=True, help="Directory containing target.json and images", type=click.Path(exists=True, resolve_path=True, file_okay=False, readable=True)) def compact_db(dir): """ Comp...
""" Transformations that primarily involve manipulating/munging variables into other formats or shapes. """ import numpy as np import pandas as pd from collections import OrderedDict as odict from bids.utils import listify from .base import Transformation from patsy import dmatrix import re from bids.variables import D...
import sys import urlparse class BaseNode(object): out = sys.stdout class NodeSet(object): def __init__(self, nodes=None): self._node_dict = {} if nodes is not None: self.__initNodes(nodes) def __initNodes(self, nodes): for node in nodes: node_str = str(node) ...
from .config import _cfg from mandrill import Mandrill email = Mandrill(_cfg("mandrill_api")) def _email_admins(subject, content): admin_email = _cfg("admin_email") if "," in admin_email: to = [] for i in admin_email.split(","): to.append({"email": i}) else: to = [{"email...
import pymongo import csv import random import re from nltk import sent_tokenize, Tree client = pymongo.MongoClient() db = client.confessions parses = list(db.parses.find()) random.shuffle(parses) texts = [] for confession in parses[:1000]: texts.append((confession["_id"], confession["message"])) num_texts = 10 wit...
def cycle(seq): """Return a generator producing items from seq. When seq is exhausted, the generator will cycle over from item 0 again. Beware that a break statement is necessary in a for loop. Also, seq is a sequence supporting the len function and enumerated 0-based. Examples: >>> seq = ['one'...
"""Map layers""" from __future__ import division import array from tmxlib import helpers, tileset, tile, mapobject, image, fileio class LayerList(helpers.NamedElementList): """A list of layers. Allows indexing by name, and can only contain layers of a single map. """ def __init__(self, map, lst=None): ...
from typing import List, Union from sympy import MatAdd, MatMul, Determinant, Rational, \ Identity, ln, pi, Add, ZeroMatrix, srepr, MatrixExpr from sympy.core.decorators import call_highest_priority from symgp.superexpressions import Variable, CompositeVariable, Mean, Covariance from symgp.utils import utils from s...
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ Renderer and value mapper for text values selected from a list of options. In some cases, the ren dered edit control also inclused a button for creating a new value. """ __author__ = "Graham Klyne (GK@ACM.O...
t = int(raw_input().strip()) for i in xrange(t): data = [int(j) for j in raw_input().strip().split()] n = data[0] m = data[1] minSalary = [int(j) for j in raw_input().strip().split()] company = [] for j in xrange(m): data = [int(k) for k in raw_input().strip().split()] company.ap...
import sys, os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..')) from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np app = QtGui.QApplication([]) mw = QtGui.QMainWindow() mw.resize(800,800) view = pg.GraphicsLayoutWidget() ## GraphicsView with GraphicsLayout inserted ...
import sys import os sys.path.append(os.path.abspath(os.path.dirname('./utils/python'))) from python.utils import timeit @timeit def solution_1(): f1, f2, s, = 0, 1, 0, while f2 < 4000000: f2, f1 = f1, f1 + f2 if f2 % 2 == 0: s += f2 return s @timeit def solution_2(): s, a, b...
import tensorflow as tf from tensorflow.contrib import rnn import os os.environ["TF_CPP_MIN_LOG_LEVEL"]="2" class LogitsLayer(): def __init__(self, args, inputs, scope): print("building logits layer", scope) batch_size = args.batch_size vocab_size = args.vocab_size keep_prob = args.k...
{ '# of International Staff': 'کارمندان بین المللی #', '# of National Staff': 'کارمندان ملی #', '# selected': 'انتخاب شده #', '%(app)s not installed. Ask the Server Administrator to install on Server.': '.نصب نشدند. از مدیر سرور تقاضا نمایید تا در سرور نصب کند %(app)s', '%(count)s Roles of the user removed': 'نقش استعم...
import os, types, uuid import json, bson, hjson from fcntl import flock, LOCK_EX, LOCK_NB, LOCK_UN class FakeDB: datadir = "" readflag = "r" writeflag = "w" fileformat = ".json" test = 0 codec = None def __init__(self, directory="./data", jsonformat="json"): self.test = 0 self.datadir = os.path.abspath(direc...
""" BlenderBot2 Agent Code. BlenderBot 2 combines a long-term memory module with a retriever module. The Search Query Generator generates a query that tells BB2 to either access its memory or access the internet. The Memory Decoder examines the context and generates memories to write to the long-term memory module. """...
import threading import time import logging def daemon(): logging.debug('Starting') time.sleep(1) logging.debug('Exiting') def non_daemon(): logging.debug('Starting') time.sleep(1) logging.debug('Exiting') logging.basicConfig( level=logging.DEBUG, format='(%(threadName)-10s) %(message)s'...
from utils import cached @cached def s(n): if n == 1: return 8 if n == 2: return 9 else: return s(n - 1) * 3 + s(n - 2) * 2 print s(25)
import 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 'Tweet.timestamp' db.add_column('carson_tweet', 'timestamp', self.gf('django.db.models.fields.DateTimeField')(default=da...
from argparse import ArgumentParser import sys import yggdrasil.config for path_elt in yggdrasil.config.PYTHONPATH.split(':'): sys.path.insert(0, path_elt) from sleipnir import dbi def prompt_corpora(): # Main loop main_loop = True while main_loop: corpora = dbi.list_corpora() print("Cur...
__author__ = 'bps'
from direct.gui.DirectGui import * from panda3d.core import * class EnergyBar(DirectFrame): def __init__(self, parent): _pos = (.5, 0, .075) DirectFrame.__init__(self, pos=_pos, frameColor=(0, 0, 0, 1), frameSize=(-.3, .125, 0, .075), parent=parent) self.initiali...