content stringlengths 5 1.05M |
|---|
# O mesmo professor quer sortear a ordem de apresentação dos seus alunos. Faça um programa para ajuda-lo.
from random import shuffle
aluno1 = input("Qual o primeiro aluno? ")
aluno2 = input("Qual o segundo aluno? ")
aluno3 = input("Qual o terceiro aluno? ")
aluno4 = input("Qual o quarto aluno? ")
lista = [aluno1, aluno... |
import numpy as np
from astropy.wcs import WCS
from astropy.io import fits
def read_spec(filename):
'''Read a UVES spectrum from the ESO pipeline
Parameters
----------
filename : string
name of the fits file with the data
Returns
-------
wavelength : np.ndarray
wavelength ... |
import token
import tokenize
PREVIOUS_TOKEN_MARKERS = (token.INDENT, token.ENDMARKER, token.NEWLINE)
def _is_docstring(
tokeninfo: tokenize.TokenInfo, previous_token: tokenize.TokenInfo
) -> bool:
"""Check if a token represents a docstring."""
if (
tokeninfo.type == token.STRING
and (
... |
import random
from starter_logic import generate_journal_starter
from eliza_logic import eliza_analyze
from continuation_logic import generate_generic_continuation, generate_specific_continuation
def generate_response(text_input):
# Trim and format input
char_limit = 1000
text = text_input[-char_limit:]
... |
income = float(input())
gross_pay = income
taxes_owed = income * .12
net_pay = gross_pay - taxes_owed
print(gross_pay)
print(taxes_owed)
print(net_pay) |
import logging
import psutil
from django.conf import settings
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from django.core.management.base import BaseCommand
from django_apscheduler.jobstores import DjangoJobStore
from django_apscheduler.models impor... |
"""Definition of component types"""
import numbers
from sympy import Symbol, sympify
from unyt import unyt_quantity, degC, delta_degC, V
from circuits.common import PortDirection, temperature_difference
class Port:
"""Base class for ports
Concept:
- signals flow through ports
- ports connect to other... |
ERROR = "ERROR"
WARNING = "WARNING"
INFO = "Info"
DEBUG = "Debug"
VERBOSE = " "
log_levels = [ERROR, WARNING]
def Log(level, msg):
global log_levels
if level in log_levels:
print(level + ": " + msg)
return 0
def SetLevels(levels):
global log_levels
log_levels = levels
return 0 |
import logging
import os
#pylint: disable=unused-import
import sure # flake8: noqa
import sys
paths = [
'..',
]
for path in paths:
sys.path.append(os.path.abspath(path))
import pyaci
logging.captureWarnings(True)
def testSubtreeClass():
opt = pyaci.options.subtreeClass('fvSubnet')
... |
import random
import numpy as np
import networkx as nx
import sys, os, json, argparse, itertools
import grinpy as gp
import time
from glob import glob
from multiprocessing import Pool
from ortools.sat.python import cp_model
"""
This code is based on https://github.com/machine-reasoning-ufrgs/GNN-GCP
"""
def solve_cs... |
import hashlib # used for password hashing
import requests # (NOT A PYTHON STANDARD LIBRARY, MUST DOWNLOAD)
# this is used to get content from pwnedpasswords api
# go to : http://docs.python-requests.org/en/latest/ ... to get Requests library
my_password = input('\n Enter a Password : '... |
from django.contrib.auth.views import LogoutView
from django.urls import path
from django_salesforce_oauth.views import oauth, oauth_callback
urlpatterns = [
path("", oauth, {"domain": "login"}, name="oauth"),
path("sandbox/", oauth, {"domain": "test"}, name="oauth-sandbox"),
path("callback/", oauth_callb... |
import functools
import queue
import threading
import traceback
class Worker(threading.Thread):
def __init__(self, tasks):
super().__init__(daemon=True)
self.tasks = tasks
self.start()
def run(self):
while True:
func, args, kwargs = self.tasks.get()
tr... |
# -------------------------------------------------------------------------
# Copyright (c) PTC Inc. and/or all its affiliates. All rights reserved.
# See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# Datalogger Test - Test to ... |
import logging
import random
from babel.numbers import format_currency
from django.conf import settings
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.signals import post_save, post_delete
fr... |
from django.db import models
from django.utils import timezone
class Course(models.Model):
name = models.CharField(max_length=250, unique=True)
description = models.TextField()
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(null=True)
def __str__(self):
... |
# By Mostapha Sadeghipour Roudsari
# [email protected]
# Honeybee started by Mostapha Sadeghipour Roudsari is licensed
# under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
"""
Remove Glazing
-
Provided by Honeybee 0.0.55
Args:
_HBZones: List of Honeybee Zones
srfIndex_: Ind... |
#!/usr/bin/env python3
"""
Author: Jakob Beckmann
Copyright 2018 ChainSecurity AG
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... |
from django.test import TestCase
from django.urls import reverse
from django_marina.test import ExtendedClient
class ExtendedClientTestCase(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.url_echo = reverse("echo")
def test_get(self):
client = Extended... |
# vim:ts=4 sw=4 sts=4:
import unittest
from igraph import *
from igraph.test.utils import skipIf
try:
import numpy as np
except ImportError:
np = None
class EdgeTests(unittest.TestCase):
def setUp(self):
self.g = Graph.Full(10)
def testHash(self):
data = {}
n = self.g.ecount(... |
import pytest
from euclidean.R3 import V3, P3
def test_v3_create():
vector = V3(1, 2, 3)
assert 1 == vector.x
assert 2 == vector.y
assert 3 == vector.z
assert V3(1, 2, 3) == vector
assert P3(1, 2, 3) != vector
for a, b in zip(vector, [1, 2, 3]):
assert a == b
def test_v3_mag... |
import numpy as np
if __name__ == "__main__":
optdata = np.zeros([900, 1800], dtype=np.float64)
for v in range(8):
isuffix = v // 4
jsuffix = v % 4
grid = np.loadtxt(
f"data\\gpw_v4_population_count_rev11_2020_30_sec_{v+1}.asc", skiprows=6
)
for i in range(45... |
'''
@author : jhhalls
'''
def plot_stratified_cross_validation():
fig, both_axes = plt.subplots(2, 1, figsize=(12, 5))
# plt.title("cross_validation_not_stratified")
axes = both_axes[0]
axes.set_title("Standard cross-validation with sorted class labels")
axes.set_frame_on(False)
n_folds = 3
... |
# UCI Electronics for Scientists
# https://github.com/dkirkby/E4S
#
# Control the AC relay using a single digital output.
# Pull out the green terminal block and use a small
# slotted screwdriver to fasten two long jumper wires.
# Connect the "-" jumper wire to the M4 GND.
# Connect the "+" jumper wire to the M4 D2.
im... |
"""Python configuration file parser."""
from __future__ import unicode_literals
import imp
import sys
_PY2 = sys.version_info < (3,)
if _PY2:
str = unicode
_BASIC_TYPES = (bool, int, float, bytes, str)
"""Python basic types."""
if _PY2:
_BASIC_TYPES += (long,)
_COMPLEX_TYPES = (tuple, list, set, dict)
""... |
import os
import time
if os.name == "posix":
var = "clear"
elif os.name == "ce" or os.name == "nt" or os.name == "dos":
var = "cls"
def login():
os.system(var)
time.sleep(.1)
print(f"\tIniciar sesión\n")
time.sleep(.1)
global usuario
usuario = input("Introduce tu nombre de u... |
import os
from datetime import date, datetime
from pathlib import Path
import pytest
import vcr as _vcr
from olog.httpx_client import Client
from olog.util import (UncaughtServerError, ensure_name, ensure_value, ensure_time,
simplify_attr)
# This stashes Olog server responses in JSON files (on... |
"""
Library for simulating scattering onto a detector according to Klein-Nishina equation
"""
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from scipy.constants import *
from scipy.interpolate import interp1d
from os.path import dirname,realpath
#I know global variables are evil,... |
# Öffentliche Klasse zur Repräsentation eines Bruchs
class Fraction:
# Konstruktor, der Zähler und Nenner eines Bruchs
# anfordert
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
# Öffentliche Methode zum Addieren eines Bruchs
# ... |
import collections
from ...keywords import Keyword, Keywords, parsers
def load_psi4_keywords(options: Keywords) -> None:
opts = _query_options_defaults_from_psi()
def p4_validator(val):
try:
nuval = val.upper()
except AttributeError:
nuval = val
return nuval
... |
import re
def handle_extends(content, seen_templates, template_processor):
matches = re.search(r'{%\s*extends\s*"([^"]+)"\s*%}', content)
if not matches:
return content
name = matches.group(1)
if name in seen_templates:
raise Exception("Recursive template in extends")
seen_templ... |
#!/usr/local/bin/python
import psycopg2
import sys
import time
import os
from db_config import config
from db_utils import cursor_pprint
def connect():
DEV = True
if 'ENVIRONMENT' in os.environ:
env = os.environ['ENVIRONMENT']
print('working on %s' % env)
DEV = 'DEV' in env
conn =... |
import argparse
from Tests.test_utils import str2bool, run_command
SERVER_GA = "Demisto-Circle-CI-Content-GA*"
SERVER_MASTER = "Demisto-Circle-CI-Content-Master*"
SERVER_ONE_BEFORE_GA = "Demisto-Circle-CI-Content-OneBefore-GA*"
SERVER_TWO_BEFORE_GA = "Demisto-Circle-CI-Content-TwoBefore-GA*"
AMI_LIST = [SERVER_GA, ... |
#
# Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
#
##############################################################################
# NOTE: the jvm should have been initialized, or this test will certainly fail
##############################################################################
import sys
i... |
from node import Node
from collections import deque
#Methods to implement:
#1 - isBalanced()
class BinaryTree:
def __init__(self, keyElement):
self.root = Node(int(keyElement))
self.size = 1
def getSize(self):
return int(self.size)
def preOrder(s... |
from common.test_base.mobile_test_case import MobileTestCase
from ..pages.main_page import MainPage
from ..pages.post_list_page import PostListPage
class BlogMobileTestCase(MobileTestCase):
"""Test case for testing by blog"""
@classmethod
def setup_class(cls):
super().setup_class()
... |
# 3rd-party modules
import requests
from bs4 import BeautifulSoup
URL: str = 'https://www.billboard.com/charts/hot-100/' # billboard web info
CLASS_FOR_SONG: str = 'u-line-height-125'
CLASS_FOR_ARTIST: str = 'a-truncate-ellipsis-2line'
class RequestBillboardInfo:
def __init__(self):
self.date_to_travel... |
# Generated by Django 3.2.13 on 2022-04-13 09:45
import django_extensions.db.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("challenges", "0015_auto_20220412_1038"),
("pages", "0003_historicalpage"),
]
operations = [
migr... |
print("Hello This is Mounika") |
# write a program to count characters in a string
st = "AmmarAdil"
count = {}
for a in st:
if a in count:
count[a]+=1
else:
count[a] = 1
print('Count', count)
# write a program to print count of vowels in a string
st = "ammaradil"
vowle = ['a', 'e', 'i', 'o', 'u']
count = 0
for s in st:
... |
import unittest
from merkle_tree import MerkleTree
from helpers import to_rpc_byte_order
class TestMerkleTree(unittest.TestCase):
class TransactionMock:
def __init__(self, hash_):
self.hash = hash_
def test_root_even_transactions(self):
# based on the block #125552 in the maincha... |
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from .base_urls import *
from django.urls import include, re_path
urlpatterns += [
re_path(r'^support', include('userservice.urls')),
re_path(r'^restclients/', include('rc_django.urls')),
re_path(r'^logging/', include(... |
import os
import shutil
import json
import openpyxl
import PyPDF2
import time
import zipfile
token_json = json.load(open("token/token.json", "r"))
def valid_token(token):
return token_json.get(token) is not None
def list_output(token):
os.makedirs(f"output/{token}", exist_ok=True)
return sorted(os.list... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
import copy
import math
import os
import re
colors_pastel = ["#e0f6e7", "#88aee1", "#eddaac", "#95bbef", "#daf4c5", "#cba9d3", "#b5d7a7", "#dec7f5", "#a1c293",
"#e8a7ba", "#72c8b8", "#e1a48e", "#7cd3eb", "#f1c1a6", "#99ceeb", "#c9aa8c", "#b8cff2", "#bbc49a",
"#b9b4dd", "#d7e0b5", "#9d... |
# @Author: Mikołaj Stępniewski <maikelSoFly>
# @Date: 2017-12-16T10:40:44+01:00
# @Email: [email protected]
# @Filename: progressBar.py
# @Last modified by: maikelSoFly
# @Last modified time: 2017-12-16T14:12:14+01:00
# @License: Apache License Version 2.0, January 2004
# @Copyright: Copyright © 2017... |
N, M = map(int, input().split())
if N - M > 0:
if N - M == 1:
print("Dr. Chaz needs 1 more piece of chicken!")
else:
print("Dr. Chaz needs", N-M, "more pieces of chicken!")
elif N - M < 0:
if abs(N - M) == 1:
print("Dr. Chaz will have 1 piece of chicken left over!")
else:
... |
import math
rat = 3/7
d_bound = 1000000
n_bound = math.floor(rat*d_bound)
fractions = {}
for i in range(-100,100):
for j in range(-100, 0):
distance = rat - (n_bound+i)/(d_bound+j)
fractions[distance] = str(n_bound+i)
min1 = 100
str1 = ''
for i in fractions:
if i>0 and i<min1:
min1 =... |
''' Utility Functions for Tests '''
from pgreaper import Table, read_pg
from pgreaper.postgres import get_table_schema
from pgreaper._globals import import_package, SQLIFY_PATH
from pgreaper.config import PG_DEFAULTS
from os import path
import copy
import unittest
import psycopg2
import os
TEST_DIR = os.path.join(os... |
import io
import pytest
from aws_lambda_builders.workflows.python_pip import utils
@pytest.fixture
def osutils():
return utils.OSUtils()
class TestOSUtils(object):
def test_can_read_unicode(self, tmpdir, osutils):
filename = str(tmpdir.join("file.txt"))
checkmark = u"\2713"
with io... |
from automancy import Radio
class TestRadio(object):
def test_radio_object_can_be_instantiated(self):
test_object = Radio('//div', 'Test Object', 'test_object')
assert test_object.locator == '//div'
assert test_object.name == 'Test Object'
assert test_object.system_name == 'test_ob... |
from __future__ import print_function
import flat
window = flat.Window(800, 600, "hi")
@window.event("on_draw")
def on_draw(window):
flat.gl.glClearColor(0.5, 0.5, 0.5, 1.0)
flat.gl.glClear(flat.gl.GL_COLOR_BUFFER_BIT)
flat.run() |
"""Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1 -> 2 -> 3 -> 4 -> 5, and n = 2.
After removing the second node from the end, the linked list becomes 1 -> 2 -> 3 ->5
Note:
Given n will always be valid.
Refer http... |
def cmdissue(toissue, activesession):
ssh_stdin, ssh_stdout, ssh_stderr = activesession.exec_command(toissue)
return ssh_stdout.read().decode('UTF-8')
|
from copy import deepcopy
from functools import partial
import random
import torch
from common.optim import ParamOptim
from dqn.algo import get_td_error
from dqn.sampler import Sampler
def tde_to_prior(x, eta=0.9):
return (eta * x.max(0).values + (1 - eta) * x.mean(0)).detach().cpu()
class Learner:
def __i... |
import datetime
from collections import defaultdict
from logs.constant import OrderLogType, MAP_NO_OPERATOR_ORDER_TYPE, OperateLogModule
from logs.models import OrderLog, OperateLogUnify, ConfigLog, PromotionLog, ProductLog, LogBaseModel, StaffLog
def get_all_module_dict():
module_dict = {}
for k, v in vars(... |
# -*- coding: utf-8 -*-
#
# This file is part of pywebmachine released under the MIT license.
# See the NOTICE for more information.
import datetime
import types
import webob
import webob.exc
def b03(res, req, rsp):
"Options?"
if req.method == 'OPTIONS':
for (header, value) in res.options(req, rsp):... |
from json import JSONDecodeError
import typing
from starlette.requests import Request as _Request, ClientDisconnect as _CD
ClientDisconnect = _CD
class Request(_Request):
"""The request object, passed to HTTP views and typically named `req`.
This is a subclass of [`Starlette.requests.Request`][starlette-r... |
from shared.args import arg_help, base_parser
def arguments(name):
parser = base_parser(name)
parser.add_argument(
'-u', '--unfollow', default=0, type=int, dest='num_unfollow',
help=arg_help('how many accounts to unfollow at once (0 = unlimited)')
)
parser.add_argument(
'-f', ... |
import mock
import pytest
from api.domain import user
from api.db import psql
from api.config import cfg
def test_where_sql():
sql = "SELECT id, username, email, contactid, date_joined FROM auth_user"
assert sql == user.where_sql()
sql = ("SELECT id, username, email, contactid, date_joined FROM auth_use... |
def add_facebook_link(strategy, details, user=None, backend=None, is_new=None, *args, **kwargs):
if is_new and backend.name == 'facebook':
user.facebook = 'http://www.facebook.com/{}'.format(kwargs['uid'])
user.save()
|
#Problem : 2016 Qualifiers - Uncle's Super Birthday Party
#Language : Python 3
#Compiled Using : py_compile
#Version : Python 3.4.3
#Input for your program will be provided from STDIN
#Print out all output from your program to STDOUT
import sys
data = sys.stdin.read().splitlines()
n = int(data[0]... |
import argparse
from hyperstyle.src.python.review.common.file_system import Extension
from analysis.src.python.evaluation.qodana.imitation_model.common.util import ModelCommonArgument
from evaluation.common.util import AnalysisExtension
def configure_arguments(parser: argparse.ArgumentParser) -> None:
parser.add... |
# Python modules
import time
import datetime
# 3rd party modules
# Our modules
# DateTime objects have a .strftime() method that accepts a format string.
# Below are some format strings for you to use. Please consider using one
# of these rather than creating a new format so that Vespa is at least
# somewhat cons... |
from datetime import datetime, timedelta
from typing import Optional, Union
from lineage.bigquery_query import BigQueryQuery
from exceptions.exceptions import SerializationError
from lineage.query import Query
from lineage.query_history_stats import QueryHistoryStats
from lineage.snowflake_query import SnowflakeQuery
f... |
import logging
import random
import traceback
import warnings
from typing import List
import func_utils
import Pages
from selenium.webdriver.remote.remote_connection import LOGGER
warnings.filterwarnings("ignore")
LOGGER.setLevel(logging.WARNING)
def main() -> None:
"""Start the script."""
profiles_visited ... |
print("How many time I have left If I live until 90 years old?")
age = input("What is your current age? ")
age = int(age)
years_until_90 = 90
months_until_90 = years_until_90 * 12
weeks_until_90 = years_until_90 * 52
days_until_90 = years_until_90 * 365
current_age = age
current_month = age * 12
current_weeks_lived... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import os, cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
_intensityBGR = 256
_projectDirectory = os.path.dirname(__file__)
_imagesDirectory = os.path.join(_projectDirectory, "images")
_images = []
for _root, _dirs, _files in os.walk(_imagesDirectory):
fo... |
import pytest
import qcdb
from qcdb.keywords import AliasKeyword, Keyword, Keywords, parsers, register_kwds
def validator(v):
if v > 5:
return v
else:
raise qcdb.KeywordValidationError
def test_1():
subject = Keyword(keyword="opt1", glossary="does stuff", validator=validator, default=6)... |
from data.data_set_home import DataSetHome, create_random_source
from train_ctc import build_model
from api import CompilationHome
from data.example_adapters import CTCAdapter
from data.generators import MiniBatchGenerator
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
pars... |
from pathlib import Path
from image import load
from feature_extraction import OrientationField
if __name__ == '__main__':
a = "database/UPEK/1_2.png"
b = "database/FVC2004/DB1_B/101_1.tif"
c = "database/AVA2017/AS.png"
d = "database/AVA2017/city_test2.jpg"
image_path = Path(__file__).parents[1] /... |
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from django.template.defaulttags import register
from pdfminer.converter import XMLConverter, HTMLConverter, T... |
import argparse
import json
import random
import requests
import time
from generate.idioms.score import Score
from generate.midi_export import MIDIFile
import generate.voices.chorale as chorale
from generate.voices.melody import Melody
from generate.voices.voice import Voice
def make_lily_file():
"""Generate Lilypon... |
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from models import Confirmation
class ConfirmationAdmin(admin.ModelAdmin):
list_display = ('shopper_id', 'ret_transdatetime', 'addr_name', 'trx_amount',
'trx_currency', 'ret_status')
fieldsets = (
... |
import logging
from django.utils.translation import gettext as _
from outpost.django.campusonline import models as co
from rest_framework import authentication, permissions, status
from rest_framework.exceptions import NotFound
from rest_framework.response import Response
from rest_framework.views import APIView
from... |
# https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/780/
# https://leetcode.com/problems/longest-palindromic-substring/description/
# Longest Palindromic Substring
#
# Given a string s, find the longest palindromic substring in s. You
# may assume that the maximum length ... |
"""Defines the ObservationModel for the 2D Multi-Object Search domain.
Origin: Multi-Object Search using Object-Oriented POMDPs (ICRA 2019)
(extensions: action space changes, different sensor model, gridworld instead of
topological graph)
Observation: {objid : pose(x,y) or NULL}. The sensor model could vary;
... |
from manimlib import *
class ImplictIntro(Scene):
def construct(self):
eq1 = Tex("x^2+y-1=0", color=YELLOW, isolate=list("x^2+y-1=0")).scale(1.2).to_edge(UP, buff=1)
xy1 = Tex("x=1", "\\quad\\Longrightarrow\\quad ", "y=0").next_to(eq1, DOWN, buff=.5)
implicit_label = VGroup(TexText("Implic... |
import numpy as np
from scipy.stats import multivariate_normal
class GaussianMixture:
def __init__(self, n_components, max_iter=100, n_restart=10, tol=1e-3):
self.n_components = n_components
self.max_iter = max_iter
self.n_restart = n_restart
self._loss = -np.inf
self._w =... |
# Copyright (c) 2018, Novartis Institutes for BioMedical Research Inc.
# 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
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
from __future__ import print_function, unicode_literals
import argcomplete
import argparse
import os
import sys
import logging
import hashlib
import glob
import tempfile
import zipfile
import shutil
import platform
import subprocess
import appdirs
i... |
"""
git style args
----------------
Using sub-commands (subparser)
https://docs.python.org/2.7/library/argparse.html#sub-commands
add_argument
name : name, -n, --name
type : type to which to convert this
int, file,
(most builtins) - add a path type
required
help :
metavar : na... |
import unittest
from parsers import ConsurfParser
from utils.exceptions import InvalidFormat
class ConsurfParserTestCase(unittest.TestCase):
def test_1(self):
dummy_prediction = """ Amino Acid Conservation Scores
===============================
- POS: The position of the AA in the SEQRES derived seque... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Rahul Handay <[email protected]>
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tes... |
#!/usr/bin/python3
import requests
import json
from bs4 import BeautifulSoup
token = 'Your token'
owner_id = 415577518
v = 5.63
def write_json(data, filename):
with open(filename, 'w') as file:
json.dump(data, file, indent=2, ensure_ascii=False)
def download_file(url):
r = requests.get(url, stream=True)
f... |
from dojson.contrib.marc21.utils import create_record, split_stream
from scoap3.hep.model import hep
from invenio_records import Record
from invenio_db import db
from invenio_indexer.api import RecordIndexer
from scoap3.modules.pidstore.minters import scoap3_recid_minter
recs = [hep.do(create_record(data)) for data in... |
# (request_status , db_acronym)
DEFAULT_STATUS_VALUES = {'waiting':'WAIT','accept':'ACCP','decline':'DECL'}
DEFAULT_CHANGE_APPOINTMENT_REQ_SIZE = 2
KEY_REQ_USERNAME = 'username'
KEY_REQ_PASSWORD = 'password'
KEY_REQ_FIRSTNAME = 'firstName'
KEY_REQ_LASTNAME = 'lastName'
KEY_REQ_PHONE = 'phone'
KEY_REQ_EMAIL = 'email'
KE... |
#!/usr/bin/env python2
__author__ = 'pgmillon'
import sys
import json
def main():
if len(sys.argv) == 2:
infile = sys.stdin
outfile = sys.stdout
path = sys.argv[1]
elif len(sys.argv) == 3:
infile = open(sys.argv[1], 'rb')
outfile = sys.stdout
path = sys.argv[2]... |
from logging import getLogger
import chainer
from chainer import functions as F
from chainer.initializers import LeCunNormal
from chainer import links as L
from chainerrl import distribution
from chainerrl.functions.bound_by_tanh import bound_by_tanh
from chainerrl.links.mlp import MLP
from chainerrl.links.mlp_bn imp... |
from django.contrib import admin
from web_app.models import Location, Posts
admin.site.register(Location)
admin.site.register(Posts)
|
'''
Workflow Serialization Unit Tests
To run unittests:
# Using standard library unittest
python -m unittest -v
python -m unittest tests/unit/test_indicator.py -v
or
python -m unittest discover <test_directory>
python -m unittest discover -s <directory> -p 'test_*.py'
# Using pytest
# "conda install pytest" or "p... |
import pygame
from pygame.locals import *
import sys
import random
screen = pygame.display.set_mode((400, 700))
bird = pygame.Rect(65, 50, 50, 50)
background = pygame.image.load("pics/background.png").convert()
pics = [pygame.image.load("pics/1.png").convert_alpha(), pygame.image.load("pics/2.png").convert_alpha(), ... |
# Generated from Documents\THESE\pycropml_pheno\src\pycropml\antlr_grammarV4\python\python3-py\Python3.g4 by ANTLR 4.8
from antlr4 import *
if __name__ is not None and "." in __name__:
from .Python3Parser import Python3Parser
else:
from Python3Parser import Python3Parser
# This class defines a complete generic... |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... |
"""
This module contains code for transition-based decoding. "Transition-based decoding" is where you
start in some state, iteratively transition between states, and have some kind of supervision
signal that tells you which end states, or which transition sequences, are "good".
If you want to do decoding for a vocabu... |
from __future__ import absolute_import
import sys
try:
import v8eval
except ImportError:
sys.tracebacklimit = 0
raise RuntimeError('Please install the python module v8eval either via pip or download it from https://github.com/sony/v8eval')
from . import JavaScriptInterpreter
from .encapsulated import tem... |
from __future__ import unicode_literals
from django.conf.urls import url
from extras.views import ObjectChangeLogView
from . import views
from .models import Tenant, TenantGroup, Package
app_name = 'tenancy'
urlpatterns = [
# Tenant groups
url(r'^service-providers/$', views.TenantGroupListView.as_view(), na... |
import meep as mp
from meep import mpb
import numpy as np
import matplotlib.pyplot as plt
# Compute modes of a rectangular Si strip waveguide on top of oxide.
# Note that you should only pay attention, here, to the guided modes,
# which are the modes whose frequency falls under the light line --
# that is, frequency ... |
# -*- coding: utf-8 -*-
import pickle
import os
import matplotlib.pyplot as plt
def get_ints(fid_list):
for fid in fid_list:
jar = pickle.load(open(dir+fid, 'r'))
obs = jar['observations'][0]
for o in obs.resolution_filter(d_max=1.81,d_min=1.78):
yield o[1]
dir = "/dls/x02-1/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.