text string | size int64 | token_count int64 |
|---|---|---|
# stdlib
import json
import subprocess
# third party
from PyInquirer import prompt
import click
# grid relative
from ...utils import Config
from ...utils import styles
class AZ:
def locations_list(self):
proc = subprocess.Popen(
"az account list-locations",
shell=True,
... | 3,376 | 1,018 |
"""Sparv preloader."""
import logging
import multiprocessing
import pickle
import socket
import struct
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Dict, Iterator
from rich.logging import RichHandler
from sparv.core import config, log_handler
from sparv.core.console im... | 8,930 | 2,635 |
"""
Flask-ac
--------
Flask-ac provide role based access control(rbac) for Flask.
This plugin implement tree-like permission structure for access control.
Flask-ac is not implement persistent storage of user, roles and permissions,
instead using self-defined loaders to load data from anywhere you want.
"""
from se... | 1,273 | 382 |
class TransportContext(object):
""" The System.Net.TransportContext class provides additional context about the underlying transport layer. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return TransportContext()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def GetChann... | 887 | 237 |
print('=== Desafio 15 ===')
print('Aluguel de carro')
d = int(input('Por quantos dias o carro foi alugado? '))
k = float(input('Qual a quantidade de quilometros percorridos?'))
rd = float(d*60)
rk = float(k*0,15)
r = float(rd + rk)
print(f'Você tem a pagar R${r}')
| 269 | 122 |
# -*- coding: utf-8 -*-
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext as _
from django_tables2.views import SingleTableMixin as BaseSingleTableMixin
from .list import ListView
from .utils import TableActions
from ..html.icons.base import Icon
from ..tables.util... | 3,387 | 970 |
import os
import sys
def usage():
print "%s script.b" % sys.argv[0]
sys.exit(127)
class Machine:
def __init__(self, filename):
self.filename = filename
self.code = []
self.codePos = 0
self.tape = []
self.tapePos = 0
try:
with open(filename, ... | 1,825 | 604 |
# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc")
y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2 = [1,0,3,1,2,2,3,3,2,1 ,2,1,1,1,1,1,1,1,1,1]
x = range(11,31)
#设置图形大小
plt.figure(figsize=(20,8... | 668 | 382 |
"""
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import azlmbr.bus as bus
impo... | 3,830 | 1,130 |
# -*- coding:utf-8 -*-
from hashlib import sha1
import hmac
import base64
import datetime
import time
import os
def getToken():
AK = os.environ.get('AK') or ''#七牛Access Key,推荐写入环境变量
SK = os.environ.get('SK') or '' #七牛Secret Key,推荐写入环境变量
dl=int(time.mktime(datetime.datetime.now().timetuple()))+21600
s=... | 554 | 272 |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 2,600 | 884 |
from django.conf.urls import patterns, url
from . import forms
from . import views
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/$', 'login',
{'template_name': 'userprofiles/login.html',
'authentication_form': forms.AuthenticationForm},
name='auth_login'),
url(r'^p... | 1,992 | 644 |
from django.apps import AppConfig
from django.db.models.signals import post_save, post_delete
from django.conf import settings
class SyncConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'sync'
def ready(self):
try:
from .signals import init_signals
... | 456 | 126 |
# ===================================
# = https://github.com/EduFreit4s =
# ===================================
# TRADUZ CÓDIGO DE CORES DE RESISTORES DE QUATRO BANDAS
# OBS : SAÍDA STRING
def resistorCor(cor1, cor2, cor3, cor4):
def corToNumber(cor): # CONVERTE COR DO PARAMETRO PARA ... | 1,816 | 730 |
# # def _run_admin_command(self, command, params):
# # available_commands = ["cancel_job", "view_job_logs"]
# # if command not in available_commands:
# # raise ValueError(f"{command} not an admin command. See {available_commands} ")
# # commands = {"cancel_job": self.cancel_job, "view_job_logs": sel... | 7,018 | 2,143 |
import json
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from channels.generic.websocket import WebsocketConsumer
from notifications.models import Notification
class NotificationConsumer(WebsocketConsumer):
def connect(self):
"""Authenticate the user and accept ... | 1,705 | 456 |
'''
This code is part of QuTIpy.
(c) Copyright Sumeet Khatri, 2021
This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative wor... | 1,737 | 645 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Jari Torniainen <jari.torniainen@ttl.fi>
# Finnish Institute of Occupational Health
# Copyright 2015
#
# This code is released under the MIT license
# http://opensource.org/licenses/mit-license.php
#
# Please see the file LICENSE for details
import pygame
import reque... | 3,061 | 1,100 |
# Copyright (c) OpenMMLab. All rights reserved.
from math import sqrt
import pytest
import torch
from mmflow.models.utils import CorrBlock
@pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA not available')
@pytest.mark.parametrize('scaled', [True, False])
def test_corr_block(scaled):
feat1 = torch.... | 1,339 | 493 |
'''
File: defaultMetafileParser.py
Copy this file as a starting point for a custom metadata file parser
and replace with customer version of parsebody (maintain signature).
Author: Ken Robbins, March 2016
Copyright 2016 Novartis Institutes for BioMedical Research
Licensed under the Apache License, Version 2.0... | 2,154 | 600 |
location = {loc : [ -97.732517999999999, 30.259606000000002 ], 'mental_health': 'N', 'med_service': 'Y', 'food': 'Y', 'private': 'N', 'shelter': 'N', 'subst_abuse_service': 'N', 'med_facility': 'Y', 'title': 'Manos De Cristo: Dental Clinic', 'address': '1201 E Cesar Chavez St, Austin, TX 78702, USA'}
db.austindb.inser... | 30,952 | 14,407 |
# 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 in writing, software
# distributed unde... | 22,080 | 6,527 |
from .. import BaseApi, NamedEndpoint
from .urls import ContentApiUrls
class ContentApi(NamedEndpoint):
"""
This class wraps the Val-Content-v1 Api calls provided by the Riot API.
See https://developer.riotgames.com/apis#val-content-v1 for more detailed
information
"""
def __init__(self, bas... | 870 | 239 |
from setuptools import find_packages, setup
from sonify import __version__
setup(
name='sonify',
version=__version__,
packages=find_packages(),
entry_points=dict(console_scripts='sonify = sonify.sonify:main'),
)
| 230 | 73 |
# 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"); you may not u... | 2,811 | 920 |
import json
import logging
from flask_babel import lazy_gettext as _
from markupsafe import Markup
#from wtforms import widgets
from wtforms.widgets import html_params, HTMLString
from wtforms import SelectField
from wtforms.compat import izip, text_type
log = logging.getLogger(__name__)
DEFAULT_JSEDITOR_CONFIG = {
... | 5,284 | 1,645 |
from abc import ABCMeta, abstractmethod
import inspect
import itertools
import linecache
from os import path
from typing import Any, cast, Dict, Sequence
import colorama
from wsgi_lineprof.stats import LineProfilerStat, LineProfilerStats
from wsgi_lineprof.types import Stream
class BaseFormatter(metaclass=ABCMeta):... | 3,780 | 1,130 |
import requests
import zipfile
import tempfile
import sys
import argparse
import time
CLIENT_ID = 'JlZIsxg2hY5WnBgtn3jfS0UYCl0K8DOg'
INFO_BASE_URL = 'https://api.soundcloud.com/resolve.json'
TRACKS_BASE_URL = 'https://api.soundcloud.com/users/{:d}/tracks'
LIMIT = 50 # the max track data SoundCloud will return
ARCHIV... | 4,611 | 1,464 |
# (C) 2020, Schlumberger. Refer to LICENSE
import numpy
import datetime
import scipy.signal
import os
import distpy.io_help.io_helpers as io_helpers
import distpy.io_help.directory_services as directory_services
import distpy.calc.pub_command_set as pub_command_set
import distpy.calc.extra_numpy as extra_numpy
import... | 5,564 | 1,710 |
from flask import Flask, render_template, request, jsonify
from main import Validate
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/validate')
def validate_cep():
cep = str(request.args.get('cep'))
try:
res = Validate(cep)
error = None... | 542 | 182 |
# -*- coding: utf-8 -*-
import re
import urllib.parse
from ..base.simple_downloader import SimpleDownloader
class ShareplaceCom(SimpleDownloader):
__name__ = "ShareplaceCom"
__type__ = "downloader"
__version__ = "0.19"
__status__ = "testing"
__pyload_version__ = "0.5"
__pattern__ = r"http:... | 1,537 | 591 |
from h2pubsub import Client
client = Client(address='localhost', port=443)
client.subscribe('/test')
while True:
print(client.receive())
| 145 | 48 |
name = input('What is your name? ')
print('Hello, {}, nice to meet you!'.format(name))
| 87 | 28 |
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras import backend as K
import numpy as np
import time
from numpy import linalg ... | 3,152 | 1,450 |
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
def Smiles_Tokeniser(smiles):
toke_smiles = list(smiles)
return toke_smiles
def max_length_list(input_list):
... | 3,144 | 1,112 |
from django.http import JsonResponse
from django.views import View
import logging
logger = logging.getLogger('sample_log')
class SampleLogEndPoint(View):
def get(self, request):
logger.info('access to SampleLogEndPoint')
return JsonResponse({'status': 201, 'msg': 'success'})
| 300 | 87 |
#!/usr/bin/env python
'''
Merge together a pdf document containing only front pages with a separate
document containing only back pages and save the result into a new document.
@author: Matt Garriott
'''
import argparse
import os
from pyPdf import PdfFileReader, PdfFileWriter
def merge(fppath, bppath, outputpath, no... | 2,196 | 649 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-04-26 10:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('MainAPP', '0004_auto_20180418_1544'),
]
... | 935 | 329 |
import os.path
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, Client
from neurovault.apps.statmaps.forms import NIDMResultsForm
from neurovault.apps.statmaps.models import Collection, StatisticMap, Comparison
from neurovault.... | 3,722 | 1,091 |
# Copyright (C) 2019-2021 HERE Europe B.V.
# SPDX-License-Identifier: Apache-2.0
import json
from datetime import datetime, timedelta
import pandas as pd
import pytest
import pytz
from geojson import FeatureCollection, Point
from geojson.geometry import LineString
from here_location_services import LS
from here_loca... | 32,045 | 12,634 |
lista = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o último número: ')))
print(f'Você digitou os valores {lista}')
print(f'O número 9 apareceu {lista.count(9)} vez(es)')
if 3 in lista:
print(f'O número 3... | 521 | 188 |
from __future__ import unicode_literals
from cms.models import CMSPlugin
from cmsplugin_filer_video import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from filer.fields.image import FilerImageField
from os.path import basena... | 2,890 | 952 |
from django.urls import path
from django.conf.urls import url
from django.urls import include
from api.seq import views
urlpatterns = [
path('chipseq/', include('api.seq.chipseq.urls')),
path('counts', views.counts, name='counts'),
path('mapped', views.mapped, name='mapped'),
path('type', views.data_t... | 341 | 113 |
"""Tests for tags of the ``multilingual_news``` application."""
from django.test import TestCase
from django.test.client import RequestFactory
from django.utils.translation import activate
from cms.api import add_plugin
from mixer.backend.django import mixer
from ..templatetags.multilingual_news_tags import (
get... | 6,159 | 1,796 |
from __future__ import division
import unittest
import networkx as nx
import dwave_networkx as dnx
try:
import matplotlib.pyplot as plt
_plt = True
except ImportError:
_plt = False
try:
import numpy as np
_numpy = True
except ImportError:
_numpy = False
class TestDrawing(unittest.TestCase)... | 3,590 | 1,499 |
'''
accuracy_utils
Module for checking accuracy of retrieval
'''
from scipy.optimize import fsolve
from scipy.spatial import distance
import numpy as np
from ._scaler import Scaler
class RetrievalMetricCalculator:
def __init__(self, parameter_limits):
'''
The RetrievalMetricCalculator generate... | 6,634 | 1,688 |
import sys
try:
import pefile
except ImportError:
print 'You have to install pefile (pip install pefile)'
sys.exit()
def main():
if len(sys.argv) < 2:
print 'usage: dumpsec.py program.exe'
return
pe = pefile.PE(sys.argv[1], fast_load=True)
data = pe.get_memory_mapped_image()
i = 0
for secti... | 715 | 288 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from .models import ImagePlugin
from .conf import settings
class GlossaryFormBase(forms.ModelForm):
glossary_fields = tuple()
def __init__(self, data=None, files=None, **kwargs):
# set values for glossary form ... | 1,708 | 512 |
# -*- coding: utf-8 -*-
from sqlalchemy import MetaData, Table
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# DB Model Auto Generate
engine = create_engine('mysql://{USER_NAME}:{PASSWORD}@{DB_END_POINT}:{DB_PORT}/{DB_NAME}?charset=utf8', echo=F... | 1,898 | 637 |
def solution(A): # O(N)
"""
Given an array find the first non-repeating integers in the array
>>> solution([3, 2, 3, 2, 5, 4, 3, 4])
5
>>> solution([3, 2, 3, 2, '%', 5, 4, 'd', 3, 4])
5
>>> solution([3, 2, 3, 2, 5, 4, 3, 4, 8])
5
>>... | 1,898 | 519 |
from sqlalchemy import Column, Integer, String, Boolean, create_engine
from sqlalchemy.engine.base import Engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session
from config import config
Base = declarative_base()
engine = creat... | 2,741 | 802 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import defaultdict
from github_poster.loader.base_loader import BaseLoader
class MutipleLoader(BaseLoader):
def __init__(self, from_year, to_year, _type, **kwargs):
super().__init__(from_year, to_year, _type)
self.types = kwargs.get(... | 5,760 | 1,639 |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
... | 2,284 | 708 |
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
import numpy as np
from matplotlib import pyplot as plt
from sklearn import linear_model
housing = np.load('housingprices.npy')
challenger = np.load('challenger.npy')
def raw():
plt.plot(housing[:,1], housing[:,0], 'o'... | 3,070 | 1,487 |
from machine.scripture import VerseRef
from tests.corpora.dbl_bundle_test_environment import DblBundleTestEnvironment
def test_get_segments_nonempty_text() -> None:
with DblBundleTestEnvironment() as env:
text = env.corpus.get_text("MAT")
segments = list(text.get_segments())
assert len(se... | 2,983 | 975 |
import zipfile
import os
import shutil
import plistlib
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
RootDir1 = ROOT_DIR + '/Extract'
# RootIcon = ROOT_DIR + '/Data/PNGs/AppIcon60x60@3x.png'
appName = ""
bundleID = ""
version = ""
buildNumber = ""
# ROOT_DIR = ""
# RootDir1 = ROOT_DIR + '/Extract'
# def ... | 3,210 | 1,061 |
import urllib.request
import re
import numpy as np
import os, sys, time
import datetime
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from time import sleep
import random
from urllib.request import HTTPError
from urllib.request import URLError
def mailfunc(year,semester... | 2,565 | 982 |
import unittest
from datetime import datetime, timedelta
import time
import dateutil
import mock
import transaction
import flask_testing
from models import Base, Edge, Node, Player, Goal, Policy, Funding, Budget
from network import Network
from game import Game, get_game
from utils import random
from wallet import Wa... | 94,637 | 35,285 |
import logging
import os
from typing import Tuple, Iterable, Optional, List
import gin
import pandas as pd
import numpy as np
from ariadne.point_net.point.points import Points, save_points_new
from ariadne.preprocessing import (
BaseTransformer,
DataProcessor,
DataChunk,
ProcessedDataChunk,
Proces... | 10,954 | 3,555 |
from os.path import abspath, dirname, join
from setuptools import find_packages, setup
# Fetches the content from README.md
# This will be used for the "long_description" field.
with open(join(dirname(abspath(__file__)), "README.md"), encoding='utf-8') as f:
README_MD = f.read()
setup(
# The name of your proje... | 2,972 | 911 |
# coding: utf-8
"""
TGS API
A production scale tool for BYOND server management # noqa: E501
OpenAPI spec version: 9.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class TestMerge(object):
"""NOTE: This class is a... | 10,595 | 3,443 |
import os
import sys
import shutil
import pytest
import subprocess
import xarray as xr
import numpy as np
# Current, parent and file paths
CWD = os.getcwd()
CF = os.path.realpath(__file__)
CFD = os.path.dirname(CF)
# Import library specific modules
sys.path.append(os.path.join(CFD, "../"))
sys.path.append(os.path.j... | 2,987 | 1,693 |
#!/usr/bin/env python
# coding: utf-8
# <a href="https://colab.research.google.com/github/nagi1995/sarcastic-comment-detection/blob/main/Sarcastic_Comments.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# In[1]:
from google.colab import drive
dr... | 26,957 | 10,881 |
"""
motifscan.motif
---------------
Module for motif related classes and functions.
"""
import logging
import os
import re
from motifscan.config import Config
from motifscan.exceptions import PfmsFileNotFoundError, \
PwmsFileNotFoundError, PfmsJasparFormatError, PwmsMotifScanFormatError
from motifscan.genome imp... | 14,098 | 4,500 |
x="There are %d types of people." % 10
binary="binary"
do_not="don't "
y="Those who know %s and those who %s." % (binary, do_not)
print (x)
print (y)
print ("I said: %r." %x)
print ("I also said: '%s'." %y)
hilarious =False
joke_evaluation="Isn't that joke so funny?! %r"
print (joke_evaluation % hilarious)
w="This is t... | 387 | 162 |
import os
import sys
import unittest
import Test8Case
import ODBCHelper
def setHe(he):
Test8Case.helper = he
def injectParam(param,tepar) :
Test8Case.param = param
Test8Case.teparam = tepar
class TestSuite(unittest.TestCase):
def setUp(self):
self.param = Test8Case.param
s... | 821 | 283 |
import collections
import functools
import random
from typing import Dict, List
from river import base, utils
def iter_counts(X: List[List[str]]):
"""
Given lists of words, return vocabularies with counts. This is useful
for the VariableVocabKMeans model that expects this input.
Parameters
-----... | 6,742 | 2,106 |
"""
.. _multi-taper-psd:
===============================
Multi-taper spectral estimation
===============================
The distribution of power in a signal, as a function of frequency, known as the
power spectrum (or PSD, for power spectral density) can be estimated using
variants of the discrete Fourier transfor... | 12,956 | 4,278 |
""" Test the creation of the index
"""
import sys
import logging
import os
import json
import copy
import subprocess
import tempfile
import shutil
from flask import Flask, Response
from multiprocessing import Process
from cStringIO import StringIO
try:
import unittest2 as unittest
except ImportError:
import... | 16,253 | 5,036 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017, Data61
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# ABN 41 687 119 230.
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE... | 4,074 | 1,238 |
import sys
from buttercup import logger
from buttercup.bot import ButtercupBot
EXTENSIONS = [
# The config cog has to be first!
"config",
"admin",
"handlers",
"welcome",
"name_validator",
"find",
"search",
"stats",
"heatmap",
"history",
"ping",
"rules",
"leaderb... | 551 | 203 |
# MIT License
#
# Copyright (c) 2021 islam kamel
#
# 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, m... | 6,245 | 1,990 |
import sys
import math
import random
# Function: main()
# --- Arguments: none; takes slice.csv as command line argument
# --- Return: none
# --- Purpose: takes slice.csv discard slice as argument, prints out SAT firewall policy (default-deny format)
#
def main():
# ensure proper arguments
if len(sys.argv) != 2:
p... | 1,750 | 720 |
from django.db import models
# Create your models here.
class image(models.Model):
image = models.BinaryField(blank = True)
target = models.IntegerField('target')
class meta:
ordering = ['target']
def __str__(self,):
return 'an image'
class Author(models.Model):
"""Model represen... | 765 | 239 |
#!/usr/bin/env python
# inst.eecs.berkeley.edu/~cs61a/sp12/hw/hw1.html
# Q4. Douglas Hofstadter’s Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.
#
# Pick a positive number n
# If n is even, divide it by 2.
# If n is odd, multipy it by 3 and add 1.
# Continue this process unt... | 1,079 | 379 |
from core.outfits import listing
from core.outfits.base import Outfit
| 70 | 22 |
from sanic import Sanic
Sanic.test_mode = True
| 48 | 18 |
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Helper module for simplified QISKit usage."""
import logging
from qiskit import transpiler
from qiskit.transpiler._passm... | 5,818 | 1,743 |
import argparse
import time
import csv
from collections import OrderedDict
import os
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import custom_transforms
import models
from utils import tensor2array, save_checkpoint, save_path_formatter, log_output_ten... | 43,323 | 13,881 |
import logging
import itertools
import numpy as np
from scipy.optimize import OptimizeResult, minimize_scalar
import scipy.constants
from .util import find_vertex_x_of_positive_parabola
def scalar_discrete_gap_filling_minimizer(
fun, bracket, args=(), tol=1.0, maxfev=None, maxiter=100, callback=None, verbos... | 13,038 | 4,059 |
#!/usr/bin/env python3
import os,json
print("Content-Type: text/html\r\n\r\n")
print
print("<title>Test CGI</title>")
print("<p>Hello World cmput404 class!</p>")
#Q1
print(os.environ)
json_object = json.dumps(dict(os.environ), indent = 4)
#print(json_object)
#Q2
for param in os.environ.keys():
if (param=="QUERY_... | 600 | 248 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
from glob import glob
tests=glob(os.path.join(os.path.dirname(__file__),"*.py"))
#__all__ = [os.path.basename(file)[:-3] for file in files
# if file!='__init__.py']
for test in tests:
__import__(os.path.basename(test)[:-3], global... | 344 | 140 |
from django import forms
from .models import Firm, Worksite, Subcontractor, Contract, Specification, Project
class DateInput(forms.DateInput):
input_type = 'date'
# FİRMA FORM
class FirmForm(forms.ModelForm):
class Meta:
model = Firm
fields = ['tax','name','full_name','phone','fax','web',... | 5,240 | 1,522 |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class PolyData(Component):
"""A PolyData component.
PolyData is exposing a vtkPolyData to a downstream filter
It takes the following set of properties:
- points: [x, y, z, x, y, z, ...],
- verts: [cel... | 2,566 | 806 |
'''
Description:
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
E... | 2,976 | 959 |
'''
Problem Description
Given an array of integers A, sort the array into a wave like array and return it, In other words, arrange the elements into a sequence such that
a1 >= a2 <= a3 >= a4 <= a5.....
NOTE : If there are multiple answers possible, return the one that's lexicographically smallest.
Input Format
Fir... | 974 | 365 |
from flybywire.ui import Application, Component
from flybywire.dom import h
from flybywire.misc import set_interval, clear_interval
@Application
class TimerApp(Component):
def __init__(self):
"""Initialize the application."""
super().__init__()
self.set_initial_state({'secondsElapsed': 0})... | 1,004 | 290 |
""" Basically the whole terminal screen itself. """
import sys
import os
import colorama
import cursor
foreground_colours = {
"BLACK": "\x1b[30m",
"RED": "\x1b[31m",
"GREEN": "\x1b[32m",
"YELLOW": "\x1b[33m",
"BLUE": "\x1b[34m",
"MAGENTA": "\x1b[35m",
"CYAN": "\x1b[36m",
"WHITE": "\x... | 3,491 | 1,107 |
import os
import sys
from typing import Dict, Optional
import torch
from loguru import logger
from torch.types import Number
from df.utils import get_branch_name, get_commit_hash, get_device, get_host
_logger_initialized = False
def init_logger(file: Optional[str] = None, level: str = "INFO"):
global _logger_i... | 2,763 | 996 |
import re
from .database import emote_database
from .node_types import EmoteNode,TextNode,CheermoteNode
from .providers.badges import Badges
from .providers.cheermotes import Cheermotes
class CheermoteCache:
"""Cheermote cache"""
matcher = re.compile("^$")
cheermotes = {}
databasePath = ''
def getCheermote(prefix... | 3,205 | 1,285 |
#!/usr/bin/env python
from scipy import stats
import numpy as np
import os
import os.path
from sklearn import mixture
def Deltest(F,M,E,length,crit=0.01,thres1=0.0005): # calculate the Del statistic given a FME combo in het files
# if True:
thres1=min(50/length,thres1)
if F/length<thres1 and M/length<thres... | 8,232 | 2,816 |
from django.contrib import admin # NOQA
| 41 | 13 |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... | 2,955 | 970 |
import scripts.other_module as om
om.get_me() | 46 | 17 |
# External module imports
import RPi.GPIO as GPIO
# Sensor that checks whether water levels have gone too low
class WaterLevelSensor:
# Store which pin receives info from the water level sensor
def __init__(self, pin):
self.pin = pin
self.is_too_low = False
# Check to see if the water le... | 602 | 198 |
"""Application and database initialization."""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
from swap.routes import swap
def configure_database(app):
"""Handle database initialization and shutdown."""
@app.before_first_request
def initialize_database():
db.c... | 782 | 250 |
import numpy as np
from matplotlib import pyplot as plt
import statsmodels.tsa.vector_ar.vecm as vecm
import pandas as pd
from . engine_output_creation import engine_output_creation
def anomaly_vecm(list_var,num_fut=5,desv_mse=2,train=True,name='model-name'):
df_var = pd.DataFrame()
for i in range(len(list_var)):... | 1,917 | 774 |
import pytest
import qobuz
import responses
from tests.resources.responses import playlist_create_json
from tests.resources.fixtures import playlist
@pytest.fixture
def app():
qobuz.api.register_app(app_id="request_from_api@qobuz.com")
def get_url(playlist_id):
return (
qobuz.api.API_URL
+ ... | 1,104 | 377 |
from django.contrib.auth import get_user_model
from questions.models import UserAnswer
User = get_user_model()
users = User.objects.all()
all_user_answers = UserAnswer.objects.all()
yemalin =users[0]
caden =users[1]
def get_points(user_a, user_b):
a_answers = UserAnswer.objects.filter(user = user_a)
b_answers =... | 1,684 | 728 |
from meinheld.server import *
from meinheld import mlogging
__version__ = '1.0.1'
| 82 | 32 |