text string | size int64 | token_count int64 |
|---|---|---|
# Generated by Django 3.1.2 on 2020-12-27 10:36
from django.db import migrations, models
import django.db.models.deletion
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
('crm', '0001_initial'),
]
operations = [
migrations... | 4,608 | 1,329 |
import os
import datetime
from collections import defaultdict
import numpy as np
from scipy import sparse
from episim.ontology import Ontology
from episim.plot.modeling import System, Accumulator
from .data import State
class EulerSimulator(object):
"""
Explicit Euler method
"""
def __init__(self, ... | 10,289 | 3,400 |
import numpy as np
from sensor_msgs.msg import CameraInfo, RegionOfInterest
from std_msgs.msg import Header
class CameraIntrinsics(object):
"""A set of intrinsic parameters for a camera. This class is used to project
and deproject points.
"""
def __init__(self, frame, fx, fy=None, cx=0.0, cy=0.0, ske... | 4,620 | 1,508 |
import logging
from logging.handlers import SysLogHandler
# Logging environment that can be used by the application to output syslog
logging_object = logging.getLogger(__name__)
logging_object.setLevel(logging.INFO)
syslog_handler = logging.handlers.SysLogHandler(address='/dev/log')
logging_object.addHandler(syslog_ha... | 327 | 93 |
import logging
from datetime import datetime
import sqlalchemy as sa
import sqlalchemy.orm as so
from .base import Base, Session
__all__ = ["User", "Message"]
logger = logging.getLogger(__name__)
class User(Base):
__tablename__ = "users"
id = sa.Column(sa.Integer, primary_key=True)
nickname = sa.Colu... | 2,446 | 806 |
import six
from unittest import TestCase
from uberlogs.private import UberStringFormatter
class UberStringFormatterTests(TestCase):
def setUp(self):
self.formatter = UberStringFormatter()
self.invalid_format = "{[blabla]"
def test_raise_on_invalid_format_when_not_silent(self):
with ... | 553 | 172 |
from django.conf import settings
from django.db import models
from redis_pubsub.models import PublishableModel
class Message(PublishableModel):
"""
"""
PUBLISH_ON_CREATE = True
PUBLISH_ON_UPDATE = True
from_user = models.ForeignKey(settings.AUTH_USER_MODEL)
to_user = models.ForeignKey(settin... | 371 | 123 |
from functools import wraps
from typing import Iterable
import numpy as np
import scipy.stats as scist
import matplotlib.pyplot as plt
from rpy2.robjects.packages import importr
from rpy2.robjects.vectors import FloatVector
from phat.utils import argsetter
base = importr('base')
utils = importr('utils')
utils.choos... | 10,602 | 4,096 |
from flask_wtf import FlaskForm
from wtforms import HiddenField, IntegerField, SelectField, StringField, SubmitField, ValidationError
from wtforms.validators import Length, Required
from .. models import EventFrameTemplate
class CopyEventFrameTemplateForm(FlaskForm):
name = StringField("Name", validators = [Required(... | 3,075 | 926 |
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
from stegano import lsb
from flask import Flask, render_te... | 3,751 | 1,324 |
jogador = dict()
lista_de_jogadores = []
lista = []
print("_"*38)
contador = 0
while True:
jogador["nome"] = str(input("Informe o nome do jogador: ")).strip()
jogador["partidas"] = int(input("Informe quantas partidas foram jogadas: "))
jogador["gols marcados"] = []
for c in range(0, jogador["partidas"])... | 1,585 | 598 |
from django.apps import AppConfig
import logging
logger = logging.getLogger(__name__)
class StockConfig(AppConfig):
name = 'stock'
def ready(self):
from background_task.models import Task
task_update_daily_stock_price = Task.objects.filter(
task_name='stock.tasks.cron_update_dail... | 954 | 285 |
import threading
from io import BytesIO
from django.db import models
import fast
import time
import numpy as np
from PIL import Image
from django.conf import settings
from slide.timing import Timer
from tag.models import Tag
class Slide(models.Model):
"""
Model for whole slide image
"""
name = models.... | 8,568 | 2,635 |
from __future__ import annotations
import typing
from di.api.providers import CallableProvider, CoroutineProvider
from di.dependant import Dependant
from xpresso.dependencies._dependencies import Depends, DependsMarker
Endpoint = typing.Union[CallableProvider[typing.Any], CoroutineProvider[typing.Any]]
class Endp... | 742 | 212 |
#!/usr/bin/python
class Sensor:
Name = ""
ID = 0
UUID = 0
Type = 0
Value = 0
def __init__(self, id, type, local_id):
self.ID = local_id
self.UUID = id[:-1] + str(local_id)
self.Type = type
def SetInterval(self, interval):
self.UpdateInterval = interval
def SetUUID(self, dev... | 554 | 257 |
mytuple = ("Max", 28, "Boston")
print(mytuple)
print(type(mytuple))
mytuple2 = ("Max") ## , is needed before the closing paranthese if only one string
print(mytuple2)
print(type(mytuple2))
mt3 = tuple(["Max", 28, "Boston"]) ## mt indicates mytuple + number
print(mt3)
print(type(m... | 1,010 | 430 |
# coding=utf-8
# Copyright 2018 The Google AI Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 13,330 | 4,349 |
import enoki as ek
import pytest
import mitsuba
def r_inv(divisor, index):
factor = 1
value = 0
recip = 1.0 / divisor
while index != 0:
next_val = index // divisor
factor *= recip
value = value * divisor + index - next_val * divisor
index = next_val
return value *... | 3,260 | 1,381 |
import warnings
import torch
from torch.utils.data.dataloader import DataLoader
from torch.optim import lr_scheduler
import numpy as np
from models import *
from dataloader import Aff2CompDataset, SubsetSequentialSampler, SubsetRandomSampler, Prefetcher
from tqdm import tqdm
import os
import time
from sklearn.metrics i... | 14,656 | 5,038 |
def show_help():
print("Carbon Intensity API Help")
def show_bad_argument_help():
print("app -e generation")
| 123 | 44 |
import os
def dir_setup(path):
if not os.path.exists(path):
os.makedirs(path)
"""def dir_setup(path):
if not os.path.isdir(path):
dir_setup(os.path.split(path)[0])
else:
return
os.mkdir(path)"""
| 251 | 105 |
# -*- coding: utf-8 -*-
'''Autor: Alessandra Souza
Data: 05/05/2017
Objetivo: Calcular o volume de uma esfera.
ID Urionlinejudge: 1011'''
R=float(input())
vol=((4.0/3)*3.14159)*R**3
print("VOLUME = %.3f" %vol)
| 212 | 110 |
import numpy as np
import tensorflow as tf
import tensorlayer as tl
import datetime
from log import LOG_PATH
import os
import src.visualization as vis
from src.config import Config as con
import tensorflow.contrib as tfcontrib
server_count = con.server_count
server_state_dim = con.server_state_dim
total_server_state_d... | 18,002 | 5,426 |
# 2 * n 타일링
def solution(n):
dp = [0] * 60001
dp[0], dp[1] = 1, 1
for i in range(2, n + 1):
dp[i] = (dp[i - 1] + dp[i - 2]) % 1000000007
return dp[n]
print(solution(4)) | 194 | 120 |
api_key = None
def configure(key=None):
global api_key
api_key = key
| 79 | 30 |
from setuptools import setup, find_packages
setup(
name="Recourse",
version="0.1.1",
packages=find_packages(),
install_requires=open('requirements.txt').read().split('\n')
) | 190 | 63 |
import pandas as pd
#####################
# Load Dataset
# https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data
df = pd.read_csv('../data/wdbc.data', header=None)
from sklearn.preprocessing import LabelEncoder
X = df.loc[:, 2:].values
y = df.loc[:,1].values
le = LabelEncoder()
... | 536 | 204 |
import argparse
import os
from PIL import Image
def get_args():
parser = argparse.ArgumentParser(description='Transform tga files to jpg')
parser.add_argument('input_dir', type=str, help='Path of input directory containing tga files')
parser.add_argument('output_dir', type=str, help='Path of output direct... | 733 | 238 |
# Copyright 2016-2020 Blue Marble Analytics LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 3,057 | 805 |
import logging
import random
from typing import Dict, List, Tuple, Union
from construction_finder import codelets, frame
logger = logging.getLogger(f"{__name__}")
class SpinResult:
def __init__(
self,
temp_modifier: float,
workspace_modifiers: Union[List[codelets.WorkSpaceModifier], None... | 3,052 | 954 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Default configurations of model configuration, training.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path as osp
from typing import Dict
CONFIG = {
'is_train': True,
... | 1,713 | 673 |
#!/usr/bin/env python3
#############################################################################
##
## Copyright (C) 2018 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the plugins of the Qt Toolkit.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial License Usage
## Licensee... | 54,959 | 17,316 |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
# open and read web page, decode it if it contains Chinese
html = urlopen('https://mofanpy.com/static/scraping/table.html').read().decode('utf-8')
print(html)
# 'lxml' is parser name
soup = BeautifulSoup(html, features='lxml')
# search by tag... | 819 | 272 |
import os
import matplotlib
# get_ipython().run_line_magic("matplotlib", "widget") # i.e. %matplotlib widget
import matplotlib.pyplot as plt
from ophyd import Device, Component, EpicsSignal
from ophyd.signal import EpicsSignalBase
from ophyd.areadetector.filestore_mixins import resource_factory
import uuid
import os... | 1,826 | 594 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: snakeskin/protos/peer/peer.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... | 5,021 | 2,056 |
#!/usr/bin/python3
'''
test for the place model here.
'''
import unittest
from models.base_model import BaseModel
from models.place import Place
class TestUser(unittest.TestCase):
'''
Testing Place class
'''
def setUp(self):
'''
Create instance for place.
'''
... | 3,236 | 973 |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from flask_login import LoginManager
from flask_msearch import Search
from config import config
from jieba.analyse import Chin... | 1,714 | 605 |
import asyncio
import json
from ..utils import DEFAULT_SETTINGS
from ..utils.DEFAULT_ENCRYPTION import SERVER_encryption, CLIENT_encryption
def json_dumper(data):
return bytes(json.dumps(data), encoding=DEFAULT_SETTINGS.ENCODING)
def json_loader(data):
return json.loads(str(data, encoding=DEFAULT_S... | 1,893 | 635 |
#! /usr/bin/env python3
#-- harvest scheduler that runs on the compute pool nodes
import argparse
import time
import sys
import logging
import os
import psutil
from applicationinsights import TelemetryClient
from applicationinsights.logging import LoggingHandler
from getargs import getargs
import azlog
azlog.color=... | 6,413 | 2,169 |
#!/usr/bin/env python3
#loading tf is slow, so don't do it unless we're using it
USE_TENSORFLOW = False
import collections
import numpy as np
import os
import pickle
if USE_TENSORFLOW:
import tensorflow as tf
from tensorflow import keras
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import modelInput
#use... | 7,758 | 2,343 |
import logging
import subprocess
import time
def wait_until(cmd):
logging.debug('waiting for %s\n' % cmd)
while subprocess.call(cmd, shell=True) != 0:
time.sleep(1)
| 183 | 64 |
# -*- coding: utf-8 -*-
ZESTY_TRACKING_CLASSES = [
'zesty_metrics.tracking.UserAccounts',
]
ZESTY_TIMING_SAMPLE_RATE = 1
ZESTY_TIME_RESPONSES = True
ZESTY_TRACK_USER_ACTIVITY = True
| 189 | 97 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_channels, out_channels):
super(Bottleneck, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_channels, in_channels, 1, padding=0, bias=False),
... | 3,368 | 1,377 |
import math
from datetime import datetime
AVAILABLE_ACTIONS = [{'action': 'add', 'admin_required': False,
'operator': '+'},
{'action': 'subtract', 'admin_required': False,
'operator': '-'},
{'action': 'multiply', 'admin_required': Fa... | 1,716 | 508 |
""" API v1 models. """
import logging
from itertools import groupby
from django.db import transaction
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from common.djangoapps.course_modes.models import CourseMode
from lms.djangoapps.verify_student.models import VerificationDeadline
... | 6,009 | 1,771 |
import sys
import pandas as pd
import numpy as np
import itertools
from sklearn.preprocessing import RobustScaler
from sklearn.tree import DecisionTreeClassifier
from evaluate_model import evaluate_model
dataset = sys.argv[1]
pipeline_components = [RobustScaler, DecisionTreeClassifier]
pipeline_parameters = {}
min_i... | 984 | 342 |
'''
Wrapper function to run PPO algorithm for training
'''
import numpy as np
import matplotlib.pyplot as plt
import time
import math
import logging
from scipy.optimize import minimize, LinearConstraint
# custom libraries
from training.PPO.run_helper import buyerPenaltiesCalculator, buyerUtilitiesCalculator, evaluati... | 3,428 | 1,056 |
import pytest
from scripts.custom import clean_dateTime
@pytest.mark.parametrize(
"test_input,expected",
[
("2015", "2015"),
("2015-02", "2015-02"),
("201502", "2015-02"),
("2015-02-07", "2015-02-07"),
("20150207", "2015-02-07"),
("2015-02-07T13:28:17", "2015-0... | 850 | 525 |
import os
import traceback
from dataclasses import dataclass
from typing import Any, Callable, List, Optional, Union
import pytorch_pfn_extras as ppe
import torch
from pytorch_pfn_extras.training import extension, extensions
from torch import nn
from torch.utils.data import DataLoader
from mlprogram import distribute... | 14,927 | 4,109 |
import matplotlib.pyplot as plt
import math
import numpy as np
class Visualization:
"""
This class contains methods for reducing the dimensions of the points to 2-D and
visualization of the reduced points.
Attributes
----------
OUTLIERS : list
List of points marked as outlier... | 3,381 | 1,031 |
from operator import add, itruediv, mul, sub
ops = [add, sub, mul, itruediv]
a = float(input("Inserisci un numero: "))
b = float(input("Inserisci un altro numero: "))
op = int(
input("Inserisci un operatore (0 per addizione, 1 per sottrazione, 2 per moltiplicazione oppure 3 per divisione: ")
)
print(ops[op](a, b)... | 322 | 123 |
from robot.api.parsing import ModelTransformer, get_model, ModelVisitor, Token
import os, sys
keywordlist = []
other_keywords = []
used_keywords = []
class ext_ExtraIndentForKeywordArguments(ModelTransformer):
def __init__(self):
self.cont = 0
def visit_File(self, node):
# Get keywords in py... | 3,639 | 1,090 |
from typing import Tuple
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from Common.Strategies.TechIndicators.AbstractTechStrategy import AbstractTechStrategy
from Common.TechIndicators.MacdIndicator import MacdIndicator
class MacdStrategy(AbstractTechStrategy):
_macd_indicator: MacdIndica... | 6,581 | 2,253 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2018.5
# Email : muyanru345@163.com
###################################################################
from collections import defaultdict
import utils
from qt import *
from s... | 7,572 | 2,347 |
from __future__ import division, print_function, generators
import numpy as np
pi = np.pi
def techChange_rhs(uB_pB, t, rvar, pBmin, pE, delta, smax, sBmax):
uB, pB = uB_pB
if sBmax == 0.:
p = pE
else:
if smax < sBmax * uB:
p = pE + smax / uB
else:
p = s... | 897 | 435 |
# -*- coding: utf-8 -*-
"""
:Authors: cykooz
:Date: 23.06.2019
"""
from pathlib import Path
import piexif
import pytest
from PIL import Image
from cykooz.heif.errors import HeifError
from cykooz.heif.image import RawHeifImage
from cykooz.heif.pil import register_heif_opener
@pytest.fixture(scope='session', autouse=... | 2,502 | 1,036 |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | 3,960 | 1,065 |
import bpy
from bpy.props import *
from bpy.types import Operator, AddonPreferences
class MFT_PT_PanelPose(bpy.types.Panel):
bl_label = "Bones"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_context = "posemode"
bl_category = 'Mifth'
# bl_options = {'DEFAULT_CLOSED'}
def draw(self, co... | 5,630 | 1,935 |
"""
Fabfile for deploying and setting up code that looks like the production
environment. it also makes it easy to start up the servers
If you want to run on the localhost you may need to first do::
rm -rf ~/.ssh/known_hosts
"""
from __future__ import with_statement
import os
import re
from fabric.api import ... | 11,830 | 3,748 |
from channels.routing import ProtocolTypeRouter
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'/websocket', consumers.VNCConsumer)
]
| 183 | 60 |
# Copyright (C) 2016 Intel Corporation
# Released under the MIT license (see COPYING.MIT)
from oeqa.core.case import OETestCase
from oeqa.utils.package_manager import install_package, uninstall_package
class OERuntimeTestCase(OETestCase):
# target instance set by OERuntimeTestLoader.
target = None
def se... | 515 | 165 |
"""
scaffoldgraph tests.analysis.test_general
"""
from scaffoldgraph.analysis import get_singleton_scaffolds, get_virtual_scaffolds
from ..test_network import long_test_network
def test_get_virtual_scaffolds(network):
v = get_virtual_scaffolds(network)
assert len(v) == 19
def test_get_singleton_scaffolds(n... | 393 | 146 |
import math
import time
t1 = time.time()
N = 1000000
n = (N+1)//2
p = [True]*(n)
i = 1
prime = [2]
while i < n:
if p[i]:
t = 2*i+1
prime.append(t)
j = i
while j < n:
p[j] = False
j += t
i += 1
def isPrime(item):
root = math.floor(math.sqrt... | 1,750 | 598 |
from django.apps import AppConfig
class SecretConfig(AppConfig):
name = 'secret'
| 87 | 26 |
import torch
import torch.nn as nn
from collections import OrderedDict
class AdapterLayer(nn.Module):
def __init__(self, input_size, reduction_factor):
super(AdapterLayer, self).__init__()
self.skip_adapter = False
self.adapter = nn.Sequential(nn.Linear(input_size, input_size//reduc... | 2,190 | 731 |
import unittest
import os
import re
import subprocess
class TestPrependError(unittest.TestCase):
def test_symmain_directory(self):
self.assertIn("LLVMBIN", os.environ, "Path to llvm-bin not set")
self.assertIn("KLEEBIN", os.environ, "Path to klee-bin not set")
bitcodefile = "bin/klee_sym... | 3,934 | 1,352 |
import os
import subprocess
from typing import Optional
from hydrus import hydrus_log_analyzer
from hydrus.hydrus_deployer_interface import IHydrusDeployer
from simulation.simulation_error import SimulationError
from utils import path_formatter
class _HydrusDesktopDeployer(IHydrusDeployer):
LOG_FILE = "simulatio... | 1,851 | 569 |
from openprocurement.api.utils import APIResource, json_view, context_unpack, get_now, generate_id
from openprocurement.framework.core.utils import (
submissionsresource,
apply_patch,
save_qualification,
)
from openprocurement.framework.core.validation import (
validate_patch_submission_data,
valida... | 3,600 | 955 |
from __future__ import division
from torch.autograd import Variable
import cv2
import numpy as np
import torch
def bbox_iou(box1, box2):
# returns IoU of two bounding boxes
b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]
b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2... | 7,090 | 2,781 |
class Solution:
def sortArrayByParityII(self, A: List[int]) -> List[int]:
A.sort(key=lambda x: (x % 2 != 0))
b = []
for i in range(int(len(A) / 2)):
b.append(A[i])
b.append(A[-(1+i)])
return b
# ---------- 320ms, 15.9MB ---------- #
class Solution:
def so... | 743 | 272 |
from rabbitConsumer import *
from socketConsumer import SocketConsumer
from dlx import *
import threading
import sys
if __name__ == '__main__':
work_with = sys.argv[1]
r_k = ['*.jpg', '*.jpeg', '#']
threads = []
dlx = ReconnectingDlx()
threads.append(threading.Thread(target=dlx.run))
for j... | 1,190 | 376 |
"""Mapeamento das tabelas para persistir os processos datajud
Revision ID: 6fdbb9233bd6
Revises: 8d2eb6149b1d
Create Date: 2020-10-18 09:22:06.650559
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '6fdbb9233bd6'
down_revision = '8d2eb6149b1d'
branch_labels = N... | 1,797 | 682 |
"""
A set of CC412022, CC416168 were run back to back without blanks on 2019-11-12.
Rough quantification is done by the below.
"""
__package__ = 'Z'
from datetime import datetime
from settings import CORE_DIR, DB_NAME
from IO.db import connect_to_db, GcRun, Integration, Standard, SampleQuant
from processing import b... | 1,991 | 709 |
import logging
import sys
from datacatalog_fileset_enricher import datacatalog_fileset_enricher_cli
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
argv = sys.argv
datacatalog_fileset_enricher_cli.\
DatacatalogFilesetEnricherCLI.run(argv[1:] if len(argv) > 0 else argv)
| 310 | 106 |
# Copyright (C) 2013 Peter Rowlands
"""csgo events module
Contains event classes for CS:S and CS:GO events
"""
from __future__ import absolute_import, unicode_literals
from future.utils import python_2_unicode_compatible
from .generic import (BaseEvent, PlayerEvent, PlayerTargetEvent, KillEvent,
... | 10,473 | 3,125 |
import re
class Telefone:
padrao = "([0-9]{2,3})?([0-9]{2})([0-9]{4,5})([0-9]{4})"
def __init__(self, telefone):
if self.valida_telefone(telefone):
self._numero = telefone
else:
raise ValueError("Número Incorreto!")
def __str__(self):
return self.format_n... | 695 | 258 |
# Listing_19-1.py
# Copyright Warren & Carter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Trying out sounds in Pygame
import pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode([640,480])
pygame.... | 670 | 218 |
import six
import docker_emperor.logger as logger
from docker_emperor.nodes.context import Context
def run(root, *args, **kwargs):
name = args[0].strip() if args else None
if name:
if name in root.project['contexts']:
root.project.config['context'] = name
logger.success(u'Cont... | 1,532 | 451 |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import time
from instance_lock import InstanceLock
################################################################################
def main():
print(sys.argv[0])
... | 759 | 220 |
import modelexp
from modelexp.experiments.sas import Sans
from modelexp.models.sas import Sphere
from modelexp.data import XyeData
from modelexp.fit import LevenbergMarquardt
from modelexp.models.sas import InstrumentalResolution
app = modelexp.App()
app.setExperiment(Sans)
dataRef = app.setData(XyeData)
dataRef.lo... | 1,194 | 554 |
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2019/1/9 上午12:35
"""
使用ProxyHandler在程序中动态设置代理
"""
import urllib2
proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8087'})
opener = urllib2.build_opener([proxy])
urllib2.install_opener(opener)
response = urllib2.urlopen('http://www.zhichu.com... | 345 | 168 |
#!/usr/bin/env python
import argparse
import logging
from metasv.generate_final_vcf import convert_metasv_bed_to_vcf
if __name__ == "__main__":
FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)
logger = logging.getLogger(__name__)
p... | 1,254 | 379 |
from __future__ import annotations
from abc import ABC, abstractmethod, abstractproperty
from typing import Any, Optional, Set
from .page_path import PagePath, PagePathLike
class AbstractPage(ABC):
"""The base abstract page interface."""
def __init__(
self,
path: PagePathLike,
) -> None... | 2,273 | 627 |
from trame import state
from trame.html import vuetify, vtk
from trame.layouts import SinglePage
from vtkmodules.vtkImagingCore import vtkRTAnalyticSource
from vtkmodules.vtkFiltersGeometry import vtkGeometryFilter
from vtkmodules.vtkRenderingCore import (
vtkRenderer,
vtkRenderWindow,
vtkRenderWindowInter... | 3,022 | 876 |
# Generated by Django 3.2.9 on 2021-12-17 22:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('toolz_swap_app', '0020_auto_20211217_1402'),
]
operations = [
migrations.AddField(
model_name='listing',
name='item_... | 601 | 205 |
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.shortcuts import get_object_or_404, redirect
from django.template.response import TemplateResponse
from django.utils.translation import pgettext_lazy
from ....store.models import SpecialPage
from ...views imp... | 2,540 | 751 |
cidade = str(input('Qual cidade voce mora?'))
print(cidade.strip().lower().startswith('santo'))
| 96 | 31 |
from datetime import datetime, timedelta
from typing import BinaryIO, Generator, Optional, Tuple
import astropy.units as u
import pytz
from astropy.units import Quantity
from salt_finder_charts.image import Survey, SurveyImageService
from salt_finder_charts.mode import (
Mode,
ModeDetails,
ImagingModeDeta... | 8,417 | 2,378 |
import argparse
import logging
import sys
from datetime import datetime
import satstac
from satstac import Catalog
import satstac.landsat as landsat
from .version import __version__
# quiet loggers
logging.getLogger('urllib3').propagate = False
logging.getLogger('requests').propagate = False
logger = logging.getLog... | 2,449 | 774 |
import sqlite3
import random
import string
import re
import sys
# domain name
args = sys.argv
if len(args)==2:
if args[1] == 'localhost':
domain = "localhost:5000/"
else:
domain = "https://squez-url-shortener.herokuapp.com/"
else:
domain = "https://squez-url-shortener.herokuapp.com/"
# URL... | 3,005 | 1,014 |
from turtle import Turtle
from scoreboard import Scoreboard
WIDTH = 800
HEIGHT = 600
START_SPEED = 0.1
class Ball(Turtle):
"""Class for creating and moving the ball. Extends Turtle"""
def __init__(self) -> None:
super().__init__()
self.y_trajectory = 10
self.x_trajectory = 10
... | 1,954 | 673 |
from .validation import *
from .preparation import *
from .external import *
from .core import *
from .preprocessing import *
from .transforms import *
from .mixed_augmentation import * | 185 | 51 |
# Generated by Django 2.0 on 2018-04-08 15:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('push_notifications', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='device',
name='is_active',
... | 703 | 219 |
jira_user_url = ""
jira_email = ""
jira_token = "" | 50 | 23 |
import subprocess, re, os
from baseq.utils.runcommand import run_it, run_generator
import pandas as pd
import random
"""
baseq dev bed ./bed
"""
import click, os, sys
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
pass
class BEDFILE:
def ... | 1,216 | 406 |
from io import UnsupportedOperation
import pytest
from xz.io import IOStatic
def test_read() -> None:
static = IOStatic(b"abcdefghij")
# read all
static.seek(0)
assert static.read() == b"abcdefghij"
static.seek(4)
assert static.read() == b"efghij"
# read partial
static.seek(6)
... | 855 | 296 |
# -*- coding: utf-8 -*-
"""
__init__.py
"""
import os
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, request, jsonify, render_template, make_response
from classes.database import db
from config import DefaultConfig
from classes import views
#from classes import models
f... | 4,264 | 1,362 |
#!/usr/bin/env python3
import pytest
import fileinput
import sys
DAY=12
class Plants():
def __init__(self, in_lines):
self.generation = 0
lines = iter(in_lines)
initial_state = next(lines).replace('initial state: ', '')
self.pots = {i:s for i, s in enumerate(initial_state)
if s == '#'
}
... | 2,313 | 897 |
# Databricks notebook source
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, lit
from pyspark.sql.functions import sum,avg,max,min,mean,count
spark = SparkSession.builder.appName("Spark DataFrames").getOrCreate()
# COMMAND ----------
df = spark.read.options(header='True', inferSchema='True... | 826 | 297 |
#!/usr/bin/python3
"""
A queue is a first-in first-out type of data structure
For this to work, you must be able to enqueue (add) items to the queue, dequeue (remove) items from the queue
"""
class List_Queue:
"""
Creates a List Queue
"""
def __init__(self, size):
self.size = size
... | 897 | 273 |