code
stringlengths
1
199k
VERSION = (0, 0, 1, 'alpha', 0)
from cmath import phase; c = complex(input()) print(abs(c)) print(phase(c))
__author__ = 'mwagner' from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMessageLog from PyQt4.Qt import QThread, pyqtSignal, QMutex, QMutexLocker, QDir, QFile class RestoreGeometry(QThread): run_finished = pyqtSignal(str, bool) run_progressed = pyqtSignal(str, int, int) report_message = pyqtSig...
import contextlib from collections import namedtuple, Mapping import numpy as np from graphviz import Digraph from scipy import signal from scipy.interpolate import InterpolatedUnivariateSpline from torch.autograd import Variable import torch import time def namedtuple_with_defaults(typename, field_names, default_value...
"""Mock Connection for the PLM.""" import asyncio import binascii import logging import async_timeout _LOGGER = logging.getLogger(__name__) async def wait_for_plm_command(plm, cmd, loop): """Wait for a command to hit the PLM.""" try: with async_timeout.timeout(10, loop=loop): while not plm.t...
from torext.handlers import oauth from torext.app import TorextApp from torext.handlers import BaseHandler from tornado.web import asynchronous import settings app = TorextApp(settings) _url_prefix = 'http://127.0.0.1:8000' class MyBaseHandler(BaseHandler): def _on_auth(self, user): print 'user', user ...
''' ====== exercicio s 05/04/2017 1) Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido. x = 0 while x == 0: nota1 = int(input("Digite o numero: ")) if nota1 > 10: print('Digite um valor válido...
import os import time import logging import unicodedata import string, pickle from random import choice from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import RequestContext from django.utils.translation import ugettext_lazy as _ from django.http import ...
from flask import render_template, redirect, url_for, abort, flash, request,\ current_app, make_response from flask_login import login_required, current_user from flask_sqlalchemy import get_debug_queries from . import main from .forms import EditProfileForm, EditProfileAdminForm, PostForm,\ CommentForm from .....
from __future__ import annotations from typing import TYPE_CHECKING, Any from schema.config import Guild, Table from utils.asyncqlio import to_dict if TYPE_CHECKING: from bot import BeattieBot class Config: def __init__(self, bot: BeattieBot): self.db = bot.db self.bot = bot self.db.bind...
from livefyre.src.utils import is_valid_full_url from .type import CollectionType from livefyre.src.utils.validator import Validator class CollectionValidator(Validator): def validate(self, data): reason = '' reason += self.verify_attr(data, 'article_id') if not hasattr(data, 'type') or not ...
""" csv parser lib wrapper. """ __author__ = 'pewho' __version__ = '0.2-alpha' from ulv.parser import Importer, Exporter
from django.conf.urls import patterns, include, url from paysto.views import * urlpatterns = patterns('', url(r'^check$', PaymentCheckView.as_view(), name='paysto_check'), url(r'^result$', PaymentResultView.as_view(), name='paysto_result'), url(r'^...
""" Created on Wed Apr 06 20:05:22 2016 @author: vhd """ from Tkinter import * from ttk import * from random import * word = 0 word_length = 0 clue = 0 def gui(): global word, word_length, clue dictionary = ["unstoppable","interstellar","divergent","insurgent","fargo","aliens","species"] word = choice(dicti...
from __future__ import unicode_literals from django.db import migrations, models import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('djconnectwise', '0050_servicenote'), ] operations = [ migrations.CreateModel( name='OpportunityNote', ...
import re import os from math import * print os.uname() print while True : code = raw_input('>>> ') if re.match(r'.+:\s*$', code) : while True : tmp = raw_input('... ') code = code + '\n' + tmp if tmp == '' : break try : ans = eval(code) ...
from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, listenWS import json, cgi from twisted.internet import reactor class BroadcastServerProtocol(WebSocketServerProtocol): """ Протокол сервера """ def onConnect(self, request): print("Client connecting: {...
import argparse from server import Server class Main: def __init__(self): self.parse_arguments() def parse_arguments(self): parser = argparse.ArgumentParser(prog='EchoServer', description='testing robot soccer', add_help=True) parser.add_argument('-p', '--port', type=int, action='store',...
import unittest class TestOcr(unittest.TestCase): pass if __name__ == '__main__': unittest.main()
"""Automatically strip all trailing whitespace before saving.""" import gedit import os import gconf from smart_indent import get_crop_spaces_eol, get_insert_newline_eof, get_remove_blanklines_eof class SaveWithoutTrailingSpacePlugin(gedit.Plugin): """Automatically strip all trailing whitespace before saving.""" ...
instructions = [ 'LUI', 'AUIPC', 'JAL', 'JALR', 'BEQ', 'BNE', 'BLT', 'BGE', 'BLTU', 'BGEU', 'LB', 'LH', 'LW', 'LBU', 'LHU', 'SB', 'SH', 'SW', 'ADDI', 'SLTI', 'SLTIU', 'XORI', 'ORI', 'ANDI', 'SLLI', 'SRLI', 'SRAI'...
import tensorflow as tf import sys import argparse def export_input_graph(model_folder): sys.path.append(model_folder) from model import get_model with tf.Session() as sess: model = get_model('policy') saver = tf.train.Saver() tf.train.write_graph(sess.graph_def, model_folder, 'input...
""" ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from orcid_api_v3.models...
alphabet_size = 256 modulus = 1000003 def rabin_karp(pattern: str, text: str) -> bool: """ The Rabin-Karp Algorithm for finding a pattern within a piece of text with complexity O(nm), most efficient when it is used with multiple patterns as it is able to check if any of a set of patterns match a section...
import fractions class MatrixError(Exception): pass class Matrix(object): def __init__(self, mat=None): if mat is None: mat = get_input() length = len(mat[0]) for row in mat: for element in row: if not isinstance(element, (int, long, float, complex...
import ez_setup ez_setup.use_setuptools() from setuptools import setup, find_packages version = '0.1.2' LONG_DESCRIPTION = """ simplexmlapi provides an easy way to access XML data. It is pure Python code with no dependencies. simplexmlapi uses the xml.dom.minidom module to parse XML data, then allows the resulting docu...
import logbook from redis import StrictRedis redis = StrictRedis(db=15) def main(): while 1: image_name = redis.lpop("media_name") if not image_name: logbook.info("change is over") break try: redis.zadd("image_name", int(image_name), int(image_name)) ...
import shopify import code import sys import os import os.path import glob import subprocess import functools import yaml import six from six.moves import input, map def start_interpreter(**variables): # add the current working directory to the sys paths sys.path.append(os.getcwd()) console = type("shopify ...
from decimal import Decimal from typing import List, Set import jsonschema from django.contrib.auth import get_user_model from django.db import transaction from django.db.models import Case, When from django.db.models.deletion import ProtectedError from django.db.utils import IntegrityError from django.http.request imp...
import time import numpy as np import theano import theano.tensor as T from theano import pp, config from plotly.tools import FigureFactory as FF import plotly.graph_objs as go from ..io.read_vtk import ReadVTK from ..data_attachment.measures import Measures from ..data_attachment.varifolds import Varifolds from ..m...
import copy import csv import logging import logging.config import pkg_resources import unicodecsv LOG_NAMESPACE = "multiverse" LOG_CONFIG = { "version": 1, "disable_existing_loggers": False, "formatters": { "debug": { "format": "[%(levelname)s] %(name)30s:%(lineno)d :: %(message)s" ...
"""This is the docstring for the LCLfind.py module.""" import numpy as np from constants import constants from esat import esat def LCLfind(Td, T, p): """ LCLfind(Td, T, p) Finds the temperature and pressure at the lifting condensation level (LCL) of an air parcel. Parameters - - - - - - Td ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zwiki.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from tkinter import * from tkinter import ttk from collections import defaultdict from tkinter import messagebox import json """ pass the dict of geojson objects to this gui in order to do some preprocessing of the gj_stack. specifically, we want the user to define the parameter that stores the name for each feature, t...
import unittest from kyu7.get_sum import get_sum class TestGetSum(unittest.TestCase): def test_one_zero_equals_one(self): self.assertEqual(1, get_sum(1, 0)) def test_one_two_equals_three(self): self.assertEqual(3, get_sum(1, 2)) def test_zero_one_equals_one(self): self.assertEqual(1,...
__author__ = 'zklinger' import maya.cmds as cmds class XPassShader(object): def __init__(self, imageName, dirName): self._imageName = imageName self._dirName = dirName self._layerNum = imageName[11:14] self._shader = cmds.shadingNode('mia_material_x_passes', ...
import asyncio from sqlblock import AsyncPostgresSQL, SQL db = AsyncPostgresSQL(dsn="postgresql://postgres@localhost/test") @db.transaction async def hello_world(): await create_table() await init_data(start_sn=100) SQL("SELECT * FROM tmp_tbl") >> db assert [r.sn async for r in db] == [100, 101, 102, 10...
""" Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explana...
class Solution(object): def groupStrings(self, strings): """ :type strings: List[str] :rtype: List[List[str]] """ hash_dict={} if not strings: return [] for sub in strings: key=self.hash_key(sub) hash_dict[key]=hash_dict.get...
import re from IPython import embed particle_rotationless_diffusion_vars = [u'df', u'vt', u'vc'] particle_rotation_diffusion_vars = [u'vr'] particle_diffusion_vars = particle_rotationless_diffusion_vars + particle_rotation_diffusion_vars particle_flux = [u'pf'] particle_vars = particle_flux + particle_diffusion_vars he...
""" Copyright (c) 2016, Jose Dolz .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 conditions and the foll...
"""Tests the main function in base""" from series import base from tests.data import mock_get_data class TestFullData: """ Simulates a scenario were all data is retrived. TODO: implement it """ def test_with_data(self, monkeypatch, capsys): def mockreturn(name): return mock_get_d...
from scrapy.spider import BaseSpider class CnnHomepageSpider(BaseSpider): name = 'cnn_homepage' allowed_domains = ['www.cnn.com'] start_urls = ['http://www.cnn.com/',] def parse(self, response): open('homepage.html', 'wb').write(response.body)
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("events", "0020_auto_20190204_1725")] operations = [ migrations.AlterField( model_name="participant", name="billed", field=models.IntegerField(default=0), ) ]
from lexer import lang from ..tree import Node class Parameter(Node): """docstring for Parameter.""" def __init__(self, datatype, identifier, token): super().__init__(None, token) self.datatype = datatype self.identifier = identifier def process_semantic(self, **cond): dataty...
from lists.client import Client from datetime import datetime from time import sleep c = Client("liststest") a_list = c.list("foo@bar.com", name="Foo") a_thread = c.thread(a_list, 'test', title="testing") print a_list print a_thread print c.lists.save(a_list) c.threads.save(a_thread) a_msg = c.msg(a_thread, title="some...
import pathlib import numpy as np import xarray as xr def to_netcdf( grid, path, include="*", exclude=None, time=None, format="NETCDF4", mode="w" ): """Write landlab a grid to a netcdf file. Write the data and grid information for *grid* to *path* as NetCDF. If the *append* keyword argument in True, app...
''' test_cis_splice_effects_identify.py -- Integration test for `regtools cis-splice-effects identify` Copyright (c) 2015, The Griffith Lab Author: Avinash Ramu <aramu@genome.wustl.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation fil...
from collections import OrderedDict from sqlalchemy import func from api.models import get_model_from_fields from api.utils import get_session from .utils import (calculate_median, get_summary_geo_info, merge_dicts, get_stat_data, get_objects_by_geo, group_remainder) PROFILE_SECTIONS = ( 'demographics', 'ed...
from . import app, mongo from alexandria.decorators import * from flask import request, jsonify, url_for, session from flask.ext.classy import FlaskView, route import json from bson import json_util from bson.objectid import ObjectId import bcrypt class SettingsView(FlaskView): route_prefix = '/api/' @authentic...
from unittest import TestCase import numpy as np from sklearn.svm.classes import SVC from tests.estimator.classifier.Classifier import Classifier from tests.language.Ruby import Ruby class SVCRubyTest(Ruby, Classifier, TestCase): def setUp(self): super(SVCRubyTest, self).setUp() self.estimator = SVC...
"""FRACTALS: ITERATED FUNCTION SYSTEM""" import numpy as np import matplotlib.pyplot as plt from numba import jit PRECISION = np.float32 def plotf(x, y, win_title='ITERATED FUNCTION SYSTEM FRACTAL', color='#0080FF'): """ Inputs: x, y -- tuple, list, or numpy array of numbers -- must have the same le...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
TapAPIQuoteLoginAuth = { "UserNo": "string", "ISModifyPassword": "char", "Password": "string", "NewPassword": "string", "QuoteTempPassword": "string", "ISDDA": "char", "DDASerialNo": "string", } TapAPIQuotLoginRspInfo = { "UserNo": "string", "UserType": "int", "UserName": "string...
""" Utility module """ import os from collections import Mapping, MutableMapping from .structures import IgnoreCaseDict def get_file_ext(filename): """ Get the extension from the given filename. :param str filename: The filename. :return str: The extension. """ return os.path.splitext(filename)[...
import requests import html2text from pattern.fr import parsetree sources = [ "http://www.jeuxdemots.org/HACK/hack_texts/Au%20bonheur%20des%20dames_1%20-%20Wikisource.htm", "http://www.jeuxdemots.org/HACK/hack_texts/Au%20bonheur%20des%20dames_10%20-%20Wikisource.htm", "http://www.jeuxdemots.org/HACK/hack_texts/Au%20bon...
from processpathway.process import LiveProcess, FPS __all__ = ['process']
import numpy as np from qtpy.QtCore import Qt, Slot, QPointF, QRectF from qtpy.QtGui import QFontMetrics, QFont from qtpy.QtWidgets import QGraphicsObject from .mapitems import MapItem from .functions import makePen, makeBrush, clip from .qtsupport import getQVariantValue class MapScaleItem(QGraphicsObject, MapItem): ...
import os import sys import argparse import datetime import subprocess as subp import logging from subprocess import check_output as qx def getArrayname(aname): '''Return a valid SciDB array name from the input''' res = aname res = res.replace(".","_") res = res.replace("-","_") return res def getArrayDescription(...
from django.core.management.base import BaseCommand, CommandError from datetime import datetime import re, sys from django.db import connection, transaction import logging logger = logging.getLogger(__name__) from django.contrib.auth.models import User from team.models import Player class Command(BaseCommand): """ ...
from datetime import datetime from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User class SignupCode(models.Model): """ """ code = models.CharField(max_length=40) max_uses = models.PositiveIntegerField(default=0) expiry = models.DateT...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('images', '0007_auto_20170214_1731'), ] operations = [ migrations.AlterField( model_name='image', name='total_likes', ...
from __future__ import unicode_literals from django.db import migrations import taggit.managers class Migration(migrations.Migration): dependencies = [ ('taggit', '0002_auto_20150616_2121'), ('blog', '0003_auto_20170320_1247'), ] operations = [ migrations.AddField( model_...
try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') else: print('You entered {0}'.format(text))
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('iiits', '0008_admissionsfinancialassistance_admissionspolicy'), ] operations = [ migrations.AddField( model_name='admissionsfeestructure', ...
from flask import Flask,render_template,request,url_for,redirect,jsonify,flash,abort, send_from_directory,send_file,Response from werkzeug import secure_filename import os from os import path,makedirs,rename from uuid import uuid4 from bson import Binary, Code from bson.json_util import dumps from media_server import a...
__author__ = 'Сергей' from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' def ready(self): from products.models import PricedProduct, ProductVariationValue import autocomplete_light autocomplete_light.register(PricedProduct, ...
from .resource import Resource class VirtualMachineExtension(Resource): """Describes a Virtual Machine Extension. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :i...
from process_base import * from targets import * import subprocess import os class ProcessDeviceIo(ProcessBase): def __init__(self, Controller, crashdump_folder, breakpoint_handler, pid, ph, unique_identifier, verbose, logger): # Specific options self.path_to_exe = b"C:\\Windows\\System32\\notepad.exe" self.comm...
import time from itertools import chain, count import sys import os import fractions import decimal if sys.hexversion > 0x03000000: xrange = range from operator import mul from functools import reduce import math prod = lambda L: reduce(mul, L, 1) def timed(f): def inner(*args, **kwargs): c1 = time.cloc...
import versioneer versioneer.versionfile_source = "pyannote/metrics/_version.py" versioneer.versionfile_build = versioneer.versionfile_source versioneer.tag_prefix = "" versioneer.parentdir_prefix = "pyannote-metrics-" from setuptools import setup, find_packages setup( # package namespace_packages=["pyannote"],...
from sklearn.ensemble import VotingClassifier, AdaBoostClassifier, BaggingClassifier, RandomForestClassifier, GradientBoostingClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from...
import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class TransparentDataEncryptionActivitiesOperations(object): """TransparentDataEncryptionActivitiesOperations operations. :param client: Client for service requests. :param con...
import importlib import json import numpy as np import os import sys import time import uuid import copy from hypergan.discriminators import * from hypergan.distributions import * from hypergan.generators import * from hypergan.inputs import * from hypergan.samplers import * from hypergan.trainers import * import hyper...
from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRe...
import sys from VectorAlgebra import * atom_type = {'1' : 'C', '2' : 'N', '3' : 'O', '4' : 'C', '5' : 'H', '6' : 'C'} atom_desc = {'1' : 'C-Alpha', '2' : 'N', '3' : 'O', '4' : 'C-Beta', '5' : 'H-Beta', '6' : 'C-Prime'} PDB_type = {'1' : 'CA', '2' : 'N', '3' : 'O', '4' : 'CB', '5' : 'HB', '6' : 'C' } class PDB_Atom: no...
from setuptools import find_packages, setup name = "django-authlink" description = "Provides magic-link authentication for Django web apps" author = "Luke Burden" author_email = "lukeburden@gmail.com" url = "https://github.com/lukeburden/django-authlink" with open("README.md", "r") as fh: long_description = fh.read...
""" The test suite for the math module of my utils package. """ from utils import math import pytest import random def test_average_valid_input_random(): random.seed(5) numbers = [random.random()*10 for i in range(10)] should_be = sum(numbers)/len(numbers) assert should_be == math.average(numbers) def t...
import ephem MIN_ALT = 5.0 * ephem.degree class AstroObject(): INTERESTING_OBJECTS = [ ephem.Sun, ephem.Moon, ephem.Mercury, ephem.Venus, ephem.Mars, ephem.Jupiter, ephem.Saturn, ephem.Uranus, ephem.Neptune, ] SPOKEN_NAMES = { '...
from multiprocessing import Process, Queue, Pool from time import sleep workq = Queue() doneq = Queue() errq = Queue() def f(): retries=0 q = workq done = doneq err = errq while True: ### get an item from the queue try: i = q.get_nowait() except Queue.Empty: ...
class Fraction(): def __init__(self, frac_str='0/1'): self.frac = tuple([int(i) for i in frac_str.split('/')]) def __str__(self): return str(self.numerator()) + '/' + str(self.denominator()) def numerator(self): return self.frac[0] def denominator(self): return self.frac[...
""" WSGI config for superleetctf project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import Djan...
try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('CHANGELOG.rst') as changelog_file: changelog = changelog_file.read().replace('.. :changelog:', '') requirements = [ "requests>=0.11.1,...
"""This module reads files from disk""" import os def crawl_files(): file_dic = [] dir = os.path.dirname(__file__) for root, dirs, files in os.walk(dir + '/../articles'): for file in files: file_path = os.path.join(root, file) file_dic.append({'name': file_path}) return f...
import os import tempfile import shutil import unittest import pytest from qtpy import QtCore, QtWidgets from qtpy.QtTest import QTest from qtconsole.console_widget import ConsoleWidget from qtconsole.completion_widget import CompletionWidget from . import no_display class TemporaryDirectory(object): """ Contex...
""" Ingest data provided by the rucsoundings.noaa.gov website RAOB sounding valid at: RAOB 12 17 JUL 2013 1 94980 72558 41.32N 96.37W 350 1117 2 100 100 1400 129 72558 3 3 OAX 99999 kt HHMM bearing range 9 9830 350 ...
from nodeset.core import dispatcher from nodeset.core import node, config, message, utils from twisted.trial import unittest from twisted.internet import defer, reactor class NodeTestCase(unittest.TestCase): def setUp(self): c = config.Configurator() c._config = {'dispatcher-url': 'pbu://localhost:5...
from __future__ import absolute_import, print_function import pickle import pymongo import six import bson import unittest import warnings from distutils.version import StrictVersion from datetime import datetime from .fixtures import Base, PickleEmbedded, PickleTest from mongoengine import ( connect, Q, CASCADE, N...
from org.xdi.service.cdi.util import CdiUtil from org.xdi.oxauth.security import Identity from org.xdi.model.custom.script.type.auth import PersonAuthenticationType from org.xdi.oxauth.service import UserService, AuthenticationService, AppInitializer from org.xdi.oxauth.service import MetricService from org.xdi.model.m...
import base64 import pytest try: import ecdsa from ecdsa.util import sigdecode_der except ImportError: ecdsa = None from irctest import authentication, cases, scram from irctest.irc_utils.message_parser import Message ECDSA_KEY = """ -----BEGIN EC PARAMETERS----- BggqhkjOPQMBBw== -----END EC PARAMETERS-----...
"""example URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/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-bas...
import tweepy import os from ConfigParser import ConfigParser parser = ConfigParser() ini_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \ 'twitter.ini') parser.read(ini_path) def post_on_twitter(img_path, content): CONSUMER_KEY = parser.get('twitter', 'consumer_key') CONSUMER_SECRET = parser.get('tw...
""" environment management ~~~~~~~~~~~~~~~~~~~~~~ :Created: 2016-8-5 :Copyright: (c) 2016<smileboywtu@gmail.com> """ from rest_framework import permissions from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from models import Environments, ...
import sys import numpy from numpy import array import dadi def usage(): print "dadi_boostrapExpansion.py <input file> <output file>" def likelihood_grid(function, data, ns, pts_l): outfile = open("likelihood_grid.txt", "w") outfile.write("nu\tT\tLL\n") for T in numpy.arange(0.001, 10, .1): for ...
""" ====================================== Generalized hyperfine component fitter ====================================== .. moduleauthor:: Adam Ginsburg <adam.g.ginsburg@gmail.com> """ import numpy as np import model import fitter ckms = 2.99792458e5 class hyperfinemodel(object): """ Wrapper for the hyperfine m...
""" Copyright (c) 2014 Eric Vallee <eric_vallee2003@yahoo.ca> 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, merg...
import os, subprocess, sys if sys.platform == 'win32': bin = 'Scripts' else: bin = 'bin' try: subprocess.call(['pip', 'install', 'mysql-python']) subprocess.call(['pip', 'install', 'flask']) subprocess.call(['pip', 'install', 'flask-login']) subprocess.call(['pip', 'install',...
import os import zipfile from typing import Dict, Any, Callable from unittest.mock import patch from uuid import uuid4, UUID from django.core.handlers.wsgi import WSGIRequest from django.urls import reverse from rest_framework.status import HTTP_200_OK, HTTP_404_NOT_FOUND, HTTP_204_NO_CONTENT, \ HTTP_400_BAD_REQUES...
from django.contrib import admin from books_recsys_app.models import MovieData,UserProfile class MoviesAdmin(admin.ModelAdmin): list_display = ['title', 'description'] admin.site.register(UserProfile) admin.site.register(MovieData,MoviesAdmin)
from pyres import ResQ from pyres.worker import Worker from remotecv.utils import logger class UniqueQueue(ResQ): def _escape_for_key(self, value): return value.replace(" ", "").replace("\n", "") def _create_unique_key(self, queue, key): return "resque:unique:queue:%s:%s" % (queue, self._escape_...