code
stringlengths
1
199k
from __future__ import (unicode_literals, division, absolute_import, print_function) from inspect import ArgSpec, getargspec from powerline.segments import Segment def getconfigargspec(obj): if hasattr(obj, 'powerline_origin'): obj = obj.powerline_origin else: obj = obj args = [] defaults = [] if isinstance(ob...
import unittest from types import GeneratorType from pynes.compiler import (lexical, syntax, t_zeropage, t_address, t_separator, get_labels) class CompilerTest(unittest.TestCase): def setUp(self): self.zeropage = dict( type='T_ADDRESS', value='$00' ...
import sys from psycopg2 import errorcodes from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.utils import strip_quotes class DatabaseCreation(BaseDatabaseCreation): def _quote_name(self, name): return self.connection.ops.quote_name(name) def _get_database_create_s...
map(lambda x, y: <caret>x * y, [])
"""Perform massive transformations on a document tree created from the LaTeX of the Python documentation, and dump the ESIS data for the transformed tree. """ import errno import esistools import re import string import sys import xml.dom import xml.dom.minidom ELEMENT = xml.dom.Node.ELEMENT_NODE ENTITY_REFERENCE = xml...
from __future__ import print_function import json import mmap import os import re import sys import argparse parser = argparse.ArgumentParser() parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*') parser.add_argument("-e", "--skip-exceptions", help="ignore hack/verify-fla...
""" CCX API URLs. """ from django.conf.urls import patterns, url, include urlpatterns = patterns( '', url(r'^v0/', include('lms.djangoapps.ccx.api.v0.urls', namespace='v0')), )
try: range(0).start except AttributeError: print("SKIP") raise SystemExit print(range(1, 2, 3).start) print(range(1, 2, 3).stop) print(range(1, 2, 3).step) try: range(4).start = 0 except AttributeError: print('AttributeError')
import smtplib from email.message import EmailMessage from email.headerregistry import Address from email.utils import make_msgid msg = EmailMessage() msg['Subject'] = "Ayons asperges pour le déjeuner" msg['From'] = Address("Pepé Le Pew", "pepe@example.com") msg['To'] = (Address("Penelope Pussycat", "penelope@example.c...
from os.path import abspath as _abspath from gppylib.commands.base import WorkerPool from gppylib import gplog __path__[0] = _abspath(__path__[0]) logger = gplog.get_default_logger() class Operation(object): """ An Operation (abstract class) is one atomic unit of work. An implementation of Operation is full...
""" Tools for creating discussion content fixture data. """ from datetime import datetime import json import factory import requests from . import COMMENTS_STUB_URL class ContentFactory(factory.Factory): class Meta(object): model = dict id = None user_id = "1234" username = "dummy-username" ...
p = patch(0.05) p.seed = 54321 p.dim = 2 p.lattice = [10,10,1] p.build(50,"linebox",0.5,2,0.5,2,1) p.build(50,"linetri",0.5,1.5,0.5,1.5,1) p.write("data.line") print "all done ... type CTRL-D to exit Pizza.py"
""" Preprocessing script for SICK data. """ import os import glob def make_dirs(dirs): for d in dirs: if not os.path.exists(d): os.makedirs(d) def dependency_parse(filepath, cp='', tokenize=True): print('\nDependency parsing ' + filepath) dirpath = os.path.dirname(filepath) filepre =...
from test import support from test import multibytecodec_support import unittest class TestCP932Map(multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'cp932' mapfileurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/' \ 'WINDOWS/CP932.TXT' ...
from testtools import content from pbr.tests import base class TestCommands(base.BaseTestCase): def test_custom_build_py_command(self): """Test custom build_py command. Test that a custom subclass of the build_py command runs when listed in the commands [global] option, rather than the norma...
"""Fixer for exec. This converts usages of the exec statement into calls to a built-in exec() function. exec code in ns1, ns2 -> exec(code, ns1, ns2) """ from .. import pytree from .. import fixer_base from ..fixer_util import Comma, Name, Call class FixExec(fixer_base.BaseFix): BM_compatible = True PATTERN = "...
""" This module implements the Sequential Least SQuares Programming optimization algorithm (SLSQP), originally developed by Dieter Kraft. See http://www.netlib.org/toms/733 Functions --------- .. autosummary:: :toctree: generated/ approx_jacobian fmin_slsqp """ from __future__ import division, print_function...
import p1.m1
from __future__ import absolute_import from django.test import TestCase from ..model_inheritance.models import Title class InheritanceSameModelNameTests(TestCase): def setUp(self): # The Title model has distinct accessors for both # model_inheritance.Copy and model_inheritance_same_model_name.Copy ...
"""Convert pickle to JSON for coverage.py.""" from coverage.backward import pickle from coverage.data import CoverageData def pickle_read_raw_data(cls_unused, file_obj): """Replacement for CoverageData._read_raw_data.""" return pickle.load(file_obj) def pickle2json(infile, outfile): """Convert a coverage.py...
import unittest from string import Template class Bag: pass class Mapping: def __getitem__(self, name): obj = self for part in name.split('.'): try: obj = getattr(obj, part) except AttributeError: raise KeyError(name) return obj cla...
""" The GeometryColumns and SpatialRefSys models for the PostGIS backend. """ from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class PostGISGeometryColumns(models.Model): ...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, qualities, ) class WrzutaIE(InfoExtractor): IE_NAME = 'wrzuta.pl' _VALID_URL = r'https?://(?P<uploader>[0-9a-zA-Z]+)\.wrzuta\.pl/(?P<typ>film|audio)/(?P<id>[0-9a-zA-Z]+)' _TESTS = [...
""" generic mechanism for marking and selecting python functions. """ import inspect class MarkerError(Exception): """Error in use of a pytest marker/attribute.""" def pytest_namespace(): return {'mark': MarkGenerator()} def pytest_addoption(parser): group = parser.getgroup("general") group._addoption( ...
from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('lib', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.c...
import argparse import sys from sridentify import Sridentify parser = argparse.ArgumentParser( description="Identify an EPSG code from a .prj file", ) parser.add_argument( 'prj', help="The .prj file" ) parser.add_argument( '-n', '--no-remote-api', action='store_false', dest='call_remote_api'...
__author__ = 'leferrad' import matplotlib matplotlib.use('agg') from learninspy.core.model import NetworkParameters from learninspy.core.neurons import LocalNeurons from learninspy.core.autoencoder import AutoEncoder, StackedAutoencoder from learninspy.core.optimization import OptimizerParameters from learninspy.core.s...
''' Created on 2016-12-07 @author: hustcc ''' from __future__ import absolute_import from app import SQLAlchemyDB as db class BaseMethod(object): __table_args__ = {'mysql_engine': 'MyISAM', 'mysql_charset': 'utf8'} # insert and update def save(self): db.session.add(self) db.session.commit() ...
import logging from decimal import Decimal from datetime import datetime from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType import ep import requests import simplejson as json from django.conf import settings from django.db import models from djan...
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'test_db', # Or p...
from hmacauth.server.hmac_authorizer import hmac_authorized
from . import _assign from . import assign, bins from .assign import (NopMapper, FuncBinMapper, PiecewiseBinMapper, RectilinearBinMapper, RecursiveBinMapper, VectorizingFuncBinMapper, VoronoiBinMapper) from ._assign import accumulate_labeled_populations, assign_and_label, accumulate_state_population...
import os.path as op import logging from flask import Flask from flask_sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry db = SQLAlchemy(session_options={'autocommit': True, 'autoflush': True}) def create_app(config,config_override=None): """ Application factory Args: config: ...
import os import sys import argparse import exceptions import re from collections import defaultdict from urllib.parse import urlparse from errno import ENOENT try: import requests except ImportError: print("The Python Requests library for Python 3 is not installed.") print("Please install Requests and try ...
''' @param throws dict<idenifier, string> The string is a move in the game @return dict<identifier, int> The int is that player's pair from the game, or None on error ''' def game(throws): #hope there are only 2 players # Unpack the throws (moves) throw = [] for key in throws: throw.append((key, throws[key])) # I...
from congo.conf import settings from congo.maintenance.filters import LogLevelFilter, AuditLevelFilter, SiteLanguage from congo.templatetags.common import or_blank from congo.utils.classes import get_class from django.contrib import messages from django.db import models from django.utils.translation import ugettext_laz...
""" Django settings for squalo project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '...
""" Deals with models for deepseg module. Available models are listed under MODELS. """ import os import json import logging import colored import spinalcordtoolbox as sct import spinalcordtoolbox.download logger = logging.getLogger(__name__) MODELS = { "t2star_sc": { "url": [ "https://github.co...
from .. import Config from ..Client import Client from ..BankAccount import BankAccount from ..WebServices.PaymentMethod import PaymentMethod import unittest import datetime class PaymentMethodTest(unittest.TestCase): def setUp(self): Config.config(merchant_id = 160361, transaction_key = '1NSa45VrQJk2j5', api_...
import numpy as np from keras.models import load_model from keras import backend as K import tensorflow as tf from matplotlib import pyplot as plt from argparse import ArgumentParser from bhtsne import tsne from data import * from siam import contrastive_loss from net import create_base_network from keras import losses...
from django.conf.urls import url from notification.views import notices, mark_all_seen, single, notice_settings urlpatterns = [ url(r"^$", notices, name="notification_notices"), url(r"^settings/$", notice_settings, name="notification_notice_settings"), url(r"^(\d+)/$", single, name="notification_notice"), ...
from __future__ import unicode_literals import sass from ecqopcd import tpl from flask import Flask, render_template, g from flask.ext.assets import Environment, Bundle from flask.ext.cache import Cache APP_NAME = 'ecqopcd' def scss(_in, out, **kw): """sass compilation""" out.write(sass.compile(string=_in.read(...
import os import signal import sys import unittest import time import multiprocessing from satella.os import hang_until_sig class TestHangUntilSig(unittest.TestCase): @unittest.skipIf('win' in sys.platform, 'Needs a POSIX to run') def test_hang_until_sig(self): def child_process(): time.slee...
from ply.lex import TOKEN, lex t_OR = r"\|\|" t_AND = r"&&" t_GEQ = r">=" t_LEQ = r"<=" t_NEQ = r"!=" t_EQ = r"==" # line 331 t_LSH = r"<<" t_RSH = r">>" literals = ["+", "-", "*", "/", ":", "[", "]", "<", ">", "(", ")", "&", "|", "="] B_regex = r"([0-9A-Fa-f][0-9A-Fa-f]?)" @TOKEN("$" + B_regex) def t_AID(...
import ctypes import io from ctypes import c_uint32 as uint from time import sleep from uio.utils import cached_getter UART_CLK = 192000000 RX_IRQ = 1 << 0 TX_IRQ = 1 << 1 ERR_IRQ = 1 << 2 MSR_IRQ = 1 << 3 RXT_IRQ = 1 << 8 # controlled by enable-bit for RX_IRQ _IIR_MAP = { 0b0110: ERR_IRQ, 0b0100: RX_I...
from .adaboost import Adaboost from .bayesian_regression import BayesianRegression from .decision_tree import RegressionTree, ClassificationTree, XGBoostRegressionTree from .gradient_boosting import GradientBoostingClassifier, GradientBoostingRegressor from .k_nearest_neighbors import KNN from .linear_discriminant_anal...
from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division import matplotlib.pyplot as plt import numpy as np from random import seed from concept_formation.examples.examples_utils import avg_lines from concept_formation.evaluatio...
''' flask_login.login_manager ------------------------- The LoginManager class. ''' import warnings from datetime import datetime, timedelta from flask import (_request_ctx_stack, abort, current_app, flash, redirect, has_app_context, request, session) from .config import (COOKIE_NAME, COO...
from itty import * from tropo import Tropo, Session, Result, Choices @post('/index.json') def index(request): t = Tropo() choices = Choices("[4-5 DIGITS]", mode="dtmf", terminator = "#") t.ask(choices, timeout=15, name="digit", say = "What's your four or five digit pin? Press pound when finished.", asrLogSecu...
import logging import flask from flask.signals import got_request_exception from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, flaskApp, apiKey): self.flaskApp = flaskApp self.apiKey = apiKey self.sender = None got_reques...
from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from minigrade import minigrade, PORT_NUMBER import logging logging.basicConfig(filename='grader.log',level=logging.DEBUG) logging.debug('Started logging on port: ' + str(PORT_NUMBER)) http_server = HTTPSe...
import time import datetime import pickle import uuid import binascii import zlib import hashlib import json import random import string import __init__ as nomagic from setting import conn def create_order(order): order["type"] = "order" order["owner"] = order.get("owner", "") order["datetime"] = datetime.d...
from suspect import MRSData, transformation_matrix import numpy import struct import re rda_types = { "floats": ["PatientWeight", "TR", "TE", "TM", "TI", "DwellTime", "NumberOfAverages", "MRFrequency", "MagneticFieldStrength", "FlipAngle", "SliceThickness", "FoVHeight", "FoVWidth", "Pe...
print "Hello World"
import urllib2 from testserver import Server from sure import that, that_with_context from httpretty import HTTPretty, httprettified def start_server(context): context.server = Server(9999) context.server.start() HTTPretty.enable() def stop_server(context): context.server.stop() HTTPretty.enable() @...
import Map tile_information = { 'Farm': { 'image': 'assets/tile_farm.png', 'build': { 'materials': 1, 'food': 1, }, 'consume': { 'water': 1, 'energy': 1, }, 'produce': { 'food': 1, 'oxygen': 1, ...
""" Returns the likelihood resulting from a model in which motif probabilities are assumed to be equal to the observed motif frequencies, as described by Goldman (1993). This model is not informative for inferring the evolutionary process, but its likelihood indicates the maximum possible likelihood value for a site-i...
import github accounts = { "social" : TOKEN, } token = accounts["social"] client = github.Github(token, per_page=100)
import sublime, sublime_plugin import os from ...libs import util from ...libs import FlowCLI class JavascriptEnhancementsRefactorExtractParameterCommand(sublime_plugin.TextCommand): def run(self, edit, **args): view = self.view selection = view.sel()[0] contents = view.substr(selection).strip() conte...
from django.shortcuts import get_object_or_404,render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.utils import timezone from django.db.models import F from django.views import generic from .models import Question, Answer def create_route(route): return 'survey...
''' Created on Mar 3, 2014 @author: yoel ''' from parasite.applications import init init.run()
import rhinoscriptsyntax as rs import time import Rhino import datetime for i in range(1, 2): print i rs.RestoreNamedView (str(i), view=None, restore_bitmap=False) outpath = "F:\\_GSAPP\\05 Fall 2013\\01 Studio\\01 Rhino\\02 Renderings\\131115\\Batch\\img"+str(i)+".png" Rhino.RhinoApp.RunScript("Render"...
import json import random import asyncio import commands client = None with open("plugins/dunnos.json","r") as dunnofile: config = json.load(dunnofile) @commands.registerEventHandler(triggerType="\\commandNotFound", name="dunno") async def dunno(triggerMessage): if triggerMessage.channel.id in config["channels"...
import sys, imp from . import model, ffiplatform class VCPythonEngine(object): _class_key = 'x' _gen_python_module = True def __init__(self, verifier): self.verifier = verifier self.ffi = verifier.ffi self._struct_pending_verification = {} self._types_of_builtin_functions = {...
import os.path from django.conf import settings from django.contrib.sites.models import Site from django.core.cache import caches CURRENT_SITE_INSTANCE_CACHE_KEY = 'current-site-object' def get_current_site_from_cache(): cache = caches['inmemory'] return cache.get(CURRENT_SITE_INSTANCE_CACHE_KEY) def update_cur...
import pytest from .lcd import lcd @pytest.mark.parametrize('a,b,answer', ((1, 1, 1), (2, 3, 6), (20, 10, 20), (10, 15, 30))) def test_lcd(a: int, b: int, answer: int) -> None: assert lcd(a, b) == answer
''' @author: oShine <oyjqdlp@126.com> @link: https://github.com/ouyangjunqiu/ou.py 数据库配置文件 ''' DBHOST = "192.168.13.27" DBPORT = 33060 DBUSER = "cps.da-mai.com" DBPWD = "cps@da-mai.com" DBNAME = "dmcark_cps" DBCHAR = "utf8"
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from datetime import datetime lon_0, lat_0 = -105, 40 plt.figure() m = Basemap(projection='ortho',lon_0=lon_0,lat_0=lat_0,resolution='l') m.drawcoastlines() m.fillcontinents(color='coral',lake_color='aqua') m.drawparallels(np.ar...
from colander import MappingSchema, SchemaNode, Boolean, Float, Integer, \ String, Range, Invalid class TimeObject(object): """ Time format: float `1.2` or `HH:MM` """ def deserialize(self, node, cstruct): if not isinstance(cstruct, float) and not isinstance(cstruct, basestring): ...
from .keeper import Keeper from .storage.writecachestorage import WriteCacheStorage from .storage.filestorage import FileStorage from .version import __version__, __version_info__ __all__ = [ "Keeper", "FileStorage", "WriteCacheStorage", ]
import json fields = [ "coverage_start_date", "coverage_end_date", ] domains = [ "Domain 1 - Preventing people from dying prematurely", "Domain 2 - Enhancing quality of life for people with long-term conditions", "Domain 3 - Helping people to recover from ill-health or following injury", "Domain...
""" DGL-based AttentiveFP for graph property prediction. """ import torch.nn as nn import torch.nn.functional as F from deepchem.models.losses import Loss, L2Loss, SparseSoftmaxCrossEntropy from deepchem.models.torch_models.torch_model import TorchModel class AttentiveFP(nn.Module): """Model for Graph Property Predic...
''' @description: 核心购票新接口——万达订单查询接口测试用例。 @note: 这个接口查的是order表。 自动查询订单号的功能还没有写好,目前仅支持手动输入订单号的方式 @author: miliang<miliang@baidu.com> ''' import sys from base import Ticket_Base class Ticket_Order_Query(Ticket_Base): def __init__(self,third_order_id=None,order_index=1,log_id=123456): super(Ticket_Order_...
''' moduls::APIClient ~~~~~~~~~~~~~~~~~ request handler ''' import requests import json from ..calls.g_login import login as login_call class APIClient(object): def __init__(self): self.session = requests.Session() self.token = None self.uid = None self.expire_at = None self....
""" Build the network architecture. >>> arch = Architecture( ... rgb_shape=(3, 64, 64), ... lidar_shape=(6, 64, 64), ... fusion='early', ... obb_parametrization='vector_and_width', ... synthetic='no_pretrain', ... channel_dropout='cdrop', ......
import datetime import json import unittest import docker from cargo.image import Image with open('example_image_payload.json', 'r') as file_obj: EXAMPLE_PAYLOAD = json.loads(file_obj.read())[0] class TestImage(unittest.TestCase): def __init__(self, *args, **kw): super(TestImage, self).__init__(*args, **kw) ...
import zmq class Messenger(object): def __init__(self, port, url='tcp://127.0.0.1', context=zmq.Context(), single=False, worker_id='Messenger', json=True, *args, **kwargs): self.port = port self.url = url self.single = singl...
import os from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtWidgets from gui.resources import * from gui.mainwindow.guiconfig import views class SettingsMenu(QtWidgets.QMenu): """docstring for SettingsMenu""" def __init__(self, parent=None): super(SettingsMenu, self).__init__(parent) ...
""" file.py by David Weinman 5/1/13, 11:25p --- Contains the functions needed for reading / writing the data in the neural nets and the parameters for training to files. """ """ This file is licensed under the MIT License, see LICENSE for details. """ import os from neuralNet import * from ast import literal_eval...
from django.db import models class Taxon(models.Model): scientific_name=models.CharField(max_length=100) common_name=models.CharField(max_length=100) cites=models.BooleanField() regulated_native=models.BooleanField() part1_live=models.BooleanField() part2_live=models.BooleanField() def __uni...
from flask import request, jsonify from app import multiauth, models, mysqlhandler from . import tcm_point from .. import mysql tcmPointHandler = mysqlhandler.TCMPointHandler(mysql) runMySQL = mysqlhandler.MySQLHandler(mysql) @tcm_point.route('/api/_get_mission_ecgtime', methods=['POST']) @multiauth.login_required def ...
from pyinfra import host, local if 'misc_servers' in host.groups: local.include('apt.py') local.include('npm.py') local.include('files.py') local.include('server.py') local.include('virtualbox/virtualbox.py') if 'docker_servers' in host.groups: local.include('docker_ce.py')
__author__ = 'Andrew' import time import urllib.request from functions import stdout import workerpool class DownloadJob(workerpool.Job): "Job for downloading a given URL." def __init__(self, url, poster_id): self.url = url # The url we'll need to download when the job runs self.poster_id = pos...
from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from django.contrib import messages from datetime import date, timedelta f...
import pymel.core as pymel from maya import OpenMaya from omtk.libs import libPymel import logging log = logging.getLogger('omtk') def get_skin_cluster(obj): if isinstance(obj, pymel.nodetypes.SkinCluster): return obj for hist in pymel.listHistory(obj): if isinstance(hist, pymel.nodetypes.SkinCl...
import logging import discord import discord.ext.commands as commands import peony import config log = logging.getLogger(__name__) logging.getLogger('peony').setLevel(logging.WARNING) def setup(bot): """Extension's entry point.""" bot.add_cog(Twitter(bot)) class TwitterError(commands.UserInputError): """Bas...
from typing import Any, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpRes...
import optparse import ConfigParser def readConfig(file="hello_config.ini"): Config = ConfigParser.ConfigParser() Config.read(file) sections = Config.sections() for section in sections: #uncomment line below to see how this config file is parsed #print Config.items(section) phras...
import xlrd import xlwt import random shename = 'hello world' thename = 'what number?' savename = 'exfceldoc' fullsave = savename + '.xls' whx = random.randint(5,10) wb = xlwt.Workbook(encoding = 'ascii') ws = wb.add_sheet(shename) ws.write(whx, whx, label = thename) for n in range(whx): ws.write(n, n, label=n) wb....
import os import tamil.utf8 as utf8 from ngram.Corpus import Corpus from ngram.LetterModels import * from ngram.WordModels import * from opentamiltests import * class WordsNGram(unittest.TestCase): def test_basic(self): # WordModels word = u"அருஞ்சொற்பொருள்" self.assertEqual(get_ngram_groups...
import os,sys import django sys.path.append(".") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TestApp.settings") django.setup() from TestApp.models import * e=employee.objects.get(id=5) e.name="Hany" e.save("Majed")
def some_c_func(): pass
import logging import urllib import mimetools import itertools from tornado import escape from tornado.httputil import url_concat from tornado.auth import httpclient, OAuth2Mixin class WeiboMixin(OAuth2Mixin): """Weibo authentication using OAuth2.""" _OAUTH_ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/acces...
import matplotlib as mpl mpl.use('Agg') import utils import os import time import argparse import torch import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import matplotlib.pyplot as plt from tqdm import tqdm from options import TestOptions from loader import PepeLoa...
import time import tempfile import datetime import os import socket """ Time object. """ class Timer: def __enter__(self): self.start = time.clock() return self def __exit__(self, *args): self.end = time.clock() self.interval = self.end - self.start """ Select a host and port to ...
from gurobipy import * __author__ = "Sailik Sengupta" __version__ = "1.0" __email__ = "link2sailik [at] gmail [dot] com" try: # Create a new model m = Model("MIQP") m_ur = Model("MIQP_UR") f = open(sys.argv[1], "r") """ ------ Input file ------ No. of defender strategies (X) No. of attac...
import binascii from array import array txt = (0xe5534ada,0xc53023aa,0xad55518a,0xc42671f8,0xa1471d94,0xd8676ce1,0xb11309c1, 0xc27a64b1,0xae1f4a91,0xc73f2bfc,0xe74c5e8e,0x826c27e1,0xf74c4f80,0x81296ff3, 0xee451996,0x8a6570e2,0xaa0709c2,0xc4687eec,0xe44a1589,0x903e79ec,0xe75117ce, ...
""" config.py: Program configuration. """ HEIGHT = 100 WIDTH = 100 MAX_INTENSITY = 5 NOZZLES = 12 NOZZLE_SPREAD = 3.175 FEEDRATE = 1000 X_STEP = 0.300 Y_STEP = 3.175 SERIAL_BAUD = 19200 SERIAL_PORT = '/dev/ttyUSB0' SERIAL_TIMEOUT = 0.01 HEATMAP_OUTPUT = True CSV_OUTPUT = True
""" Django settings for p0sx project. Generated by 'django-admin startproject' using Django 1.8.4. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os import re...
import datetime import json import logging import time import traceback import webapp2 from functools import wraps from google.appengine.api import mail from google.appengine.api import memcache from google.appengine.ext import ndb ERRORS_KEY = 'errors' def rate_limit(seconds_per_request=1): def rate_limiter(functi...