id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1765450 | #!/usr/bin/python3.5
# -*- coding: utf-8 -*-
import cgitb
import sys
cgitb.enable()
from nlp_form import make_nlp_form
PY3 = sys.version_info[0] > 2
if PY3:
sys.stdout.buffer.write("Content-Type: text/html\n\n\n".encode("utf8"))
content = make_nlp_form("public", "interactive")
sys.stdout.buffer.write(content.enc... | StarcoderdataPython |
41941 | """
Metrics extensions for routes.
"""
try:
from microcosm_metrics.classifier import Classifier
except ImportError:
raise Exception("Route metrics require 'microcosm-metrics'")
from microcosm_flask.audit import parse_response
from microcosm_flask.errors import extract_status_code
class StatusCodeClassifier... | StarcoderdataPython |
197366 | <gh_stars>0
# !usr/bin/python
# usage: results announcement
print "Enter user name r qualified or not:::"
name=raw_input()
list1=['kalyan','supraja','mahindra','anil','siva','ajay','haritha','keerthi','suhashini','subhashini','nariyan','manoj','santhosh','kumar','niveda','thomos','rasii']
if name in list1 :
print ... | StarcoderdataPython |
157843 | <reponame>chldkato/Fre-GAN-pytorch<filename>preprocess.py
import pandas as pd
import numpy as np
import os, librosa, glob, shutil, torch
from tqdm import tqdm
from hparams import *
text_dir = './archive/transcript.v.1.4.txt'
metadata = pd.read_csv(text_dir, dtype='object', sep='|', header=None)
wav_dir = metadata[0]... | StarcoderdataPython |
3273887 | import pandas as pd
from cowidev.vax.utils.incremental import enrich_data, increment
from cowidev.utils.clean.dates import localdate
from cowidev.utils import paths
def read(source: str) -> pd.Series:
data = pd.read_csv(source, sep=";")
return parse_data(data).pipe(enrich_data, "date", get_date())
def pars... | StarcoderdataPython |
1680446 | <filename>scripts/utils_mpc.py<gh_stars>0
import math
import numpy as np
from example_robot_data.robots_loader import Solo12Loader
import Joystick
import Logger
import Estimator
import pinocchio as pin
######################################
# RPY / Quaternion / Rotation matrix #
####################################... | StarcoderdataPython |
4817612 | from inspect import getmembers
from inspect import isfunction
import hug
from hug_middleware_cors import CORSMiddleware
from constants import MASK_COLOR
from constants import OUTPUT_IMAGE_FORMAT
from image_io import load_image
from image_io import serialize_image
from image_processing import apply_morphology
import i... | StarcoderdataPython |
1743717 | <gh_stars>1-10
from obywatele import views as v
from django.urls import path
app_name = 'obywatele'
urlpatterns = (
path('', v.obywatele, name='obywatele'),
path('poczekalnia/', v.poczekalnia, name='poczekalnia'),
path('poczekalnia/<int:pk>/', v.obywatele_szczegoly, name='poczekalnia_szczegoly'),
path... | StarcoderdataPython |
1745008 | # Copyright 2016 Mirantis Inc.
#
# 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, so... | StarcoderdataPython |
4807746 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
***************************************************************************
test_qgssymbollayer.py
---------------------
Date : October 2012
Copyright : (C) 2012 by <NAME>
Email : massimo dot endrighi at geopartner do... | StarcoderdataPython |
4807962 | # -*- coding: utf-8 -*-
"""
(c) 2018 - Copyright Red Hat Inc
Authors:
<NAME> <<EMAIL>>
"""
from __future__ import unicode_literals, absolute_import
import unittest
import sys
import os
import time
import mock
import pygit2
sys.path.insert(
0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."... | StarcoderdataPython |
5588 | <reponame>cpelley/improver
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are p... | StarcoderdataPython |
1733454 | <reponame>HouTiger/InfoMarket
from flask import Flask, session, request, render_template, redirect
import time
import order_def
import holding_def
import init
import math
import func_def
myWeb = Flask(__name__)
trade_board_length = 60 # 交易面板容纳的最大订单数量
price_queue_length = 4 # 价格队列的长度
order_limit = 6 # 单个用户订单上限
# 运行中
ad... | StarcoderdataPython |
1603352 | <reponame>DotzInc/debussy_concert
from debussy_concert.core.movement.movement_base import MovementBase
from debussy_concert.core.movement.protocols import (
PStartPhrase,
PIngestionSourceToRawVaultStoragePhrase,
PRawVaultStorageToDataWarehouseRawPhrase,
PEndPhrase
)
from debussy_concert.data_ingestion.c... | StarcoderdataPython |
3287332 | """ Wordlist Mixer by jaa2
https://github.com/jaa2/wordlist-mixer """
import argparse
import itertools
import sys
def read_all_lines(fname):
with open(fname, "r") as f:
content = f.read().splitlines()
return content
def main(args):
# Read word lists
wlists = []
for wordlist in args.wo... | StarcoderdataPython |
3359508 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
import webapp2
import webtest
from google.appengine.api import users
from dashboard import edit_config_handler
from dashboard import edit_... | StarcoderdataPython |
4830762 | from rest_framework import serializers
from forums.models import Thread, Forum, Post
from .profiles import SimpleUserSerializer
from .competitions import CompetitionSerializerSimple
import logging
logger = logging.getLogger(__name__)
class ThreadCreateSerializer(serializers.Serializer):
title = serializers.CharF... | StarcoderdataPython |
1757142 | <filename>hadar/optimizer/lp/domain.py
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com)
# See AUTHORS.txt
# This Source Code Form is subject to the terms of the Apache License, version 2.0.
# If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www... | StarcoderdataPython |
3221456 | <gh_stars>1-10
import json
import shutil
from argparse import ArgumentParser, Namespace
from pathlib import Path
from random import random
from typing import Dict, Tuple, List
from bidict import bidict
from tqdm import tqdm
TColor = Tuple[float, ...]
def rand_color() -> TColor:
return tuple([int(255 * random())... | StarcoderdataPython |
3312512 | from django.urls.base import reverse, reverse_lazy
from rest_framework import status
from user.urls import app_name
from core.tests.utils import BaseCaller, create_image
from ..creators import create_user
# USER_LIST_URL = reverse_lazy(f"{app_name}:user-list")
USER_ME_DETAIL_URL = reverse_lazy(
f"{app_name}:user-... | StarcoderdataPython |
1764271 | from iohandler.datareader import find_files
import re
import pdb
# pdb.set_trace()
fs = find_files('sprite_imgs', '.*\.jpg')
fs = sorted(fs)
# for iWord in range(iFirst, iLast+1):
with open('char10000.tsv', 'w', encoding='utf-8') as f:
for filename in fs:
# print 'Word %d: %s' % (iWord, unichr(iWord))
... | StarcoderdataPython |
3383781 | """A set of functions to standardize some options for python scripts"""
import logging
import argparse
from os import getcwd, path
logger = logging.getLogger(__name__)
def setup_parser_help(parser, additional_docs=None):
"""
Set formatting for parser to raw and add docstring to help output
Parameters
... | StarcoderdataPython |
3231496 | <reponame>KelvinAraujo/Python<filename>desafio 051.py
primeiro = int(input('Primeiro termo: '))
raz = int(input('Razão: '))
for c in range(primeiro, primeiro + 10 * raz, raz):
print(c, end=' => ')
| StarcoderdataPython |
3371653 | <gh_stars>0
from wordcloud import WordCloud, STOPWORDS
from collections import Counter
from stopwords import get_stopwords
import numpy as np
from PIL import Image
def gen_wordcloud(wc, path, source):
counts_all = Counter()
with open(f'./{path}/{source}', 'r') as f:
for line in f:
counts_li... | StarcoderdataPython |
196472 | <filename>anuvaad-etl/anuvaad-nmt-models-fetch/src/utilities/app_context.py
MODULE_CONTEXT = {'metadata':{'module':'ANUVAAD-NMT-MODELS'}}
def init():
global app_context
app_context = {
'application_context' : None
} | StarcoderdataPython |
42374 | from numbers import Number
from typing import *
import nuke
from . import *
class PyCustom_Knob(Script_Knob):
"""
PyCustom_Knob
"""
def __hash__(self, ):
"""
Return hash(self).
"""
return None
def __init__(self, *args, **kwargs):
"""
Initialize sel... | StarcoderdataPython |
186497 | <reponame>tisnik/victimsdb-lib<filename>victimsdb_lib/model.py<gh_stars>1-10
"""VictimsDB model."""
import re
import yaml
from f8a_version_comparator.comparable_version import ComparableVersion
from victimsdb_lib.errors import ParseError
class Record(object):
"""CVE Record in a database."""
def __init__(se... | StarcoderdataPython |
1685691 | ## Num_Integ.py
# ------------------------- #
# Description:
# A collection of Numerical Methods functions for solving/simulating deterministic and stochastic differential equations.
# ------------------------- #
# Created by: <NAME>, RRSG, UCT.
# Date created: 20 June 2016
# Edits: 16 July 2016: added fnRK4_mom... | StarcoderdataPython |
3387205 | #!/usr/bin/env python
""" Demonstrate microsecond pulsing on three lasers (active trigger).
A camera trigger signal must be used as input to the FPGA. The
FPGA generates three laser trigger signals (laser0, laser1 and
laser2). Those laser signals are short pulses of 1, 2 and 3 us,
respectively, on each rising edge of ... | StarcoderdataPython |
3292265 | from django.shortcuts import render
from rest_framework import request
# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework.views import APIView
from rest_framework import status
from ... | StarcoderdataPython |
1686360 | <gh_stars>1-10
"""
1351. Count Negative Numbers in a Sorted Matrix
Given a m * n matrix grid which is sorted in non-increasing order both row-wise and column-wise.
Return the number of negative numbers in grid.
Example 1:
Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]
Output: 8
Explanation: Ther... | StarcoderdataPython |
1793143 | <gh_stars>10-100
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "CHR"
addresses_name = (
"2021-04-16T12:59:18.049121/Re-submission - Democracy_Club__06May2021.tsv"
)
stations_name = (
"20... | StarcoderdataPython |
1728088 | <reponame>kagemeka/atcoder-submissions
import sys
import numpy as np
MOD = 10**4 + 7
def matrix_power_mod(x, n, modulus):
x = np.asanyarray(x)
if len(x.shape) != 2:
raise ValueError("input must be a matrix")
if x.shape[0] != x.shape[1]:
raise ValueError("input must be a squar... | StarcoderdataPython |
1696286 | <reponame>troup-system/troup<filename>troup/infrastructure.py
# Copyright 2016 <NAME>
#
# 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
#
# Un... | StarcoderdataPython |
1771595 | <filename>app/api/v2/managers/fact_api_manager.py
from app.api.v2.managers.base_api_manager import BaseApiManager
from app.objects.c_operation import InvalidOperationStateError
from json import JSONDecodeError
from app.api.v2.responses import JsonHttpBadRequest
from aiohttp import web
import copy
import json
class F... | StarcoderdataPython |
3349930 | <filename>schevo/counter.py
"""Schema counter singleton."""
# Copyright (c) 2001-2009 ElevenCraft Inc.
# See LICENSE for details.
import sys
from schevo.lib import optimize
class schema_counter(object):
"""Schema counter singleton.
This is a class instead of a global, because globals won't work
because... | StarcoderdataPython |
96311 | <reponame>latonaio/titaniadb-sentinel
import etcd3
import os
import datetime
import time
import json
pr1 = {
'projectSymbol': '<KEY>',
'projectName': 'exampleProject',
'projectID': 'exampleProjectID',
'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
d1 = {
'device... | StarcoderdataPython |
4837355 | <reponame>mojo0243/OsoConMigoV2<gh_stars>1-10
import argparse
from index import app
# Define variables arguments for the program
web_parser = argparse.ArgumentParser()
# Define variable arguments for Web Server
web_parser.add_argument('-p', '--port', dest='port', action='store', help='This flag will start the web s... | StarcoderdataPython |
1636977 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsCoordinateFormatter.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version... | StarcoderdataPython |
4821515 | <reponame>ukwahlula/django-server-boilerplate<filename>{{cookiecutter.project_slug}}/apps/storage/tests/fixtures.py<gh_stars>1-10
import pytest
from apps.storage.tests import factories
@pytest.fixture
def image():
return factories.ImageFactory()
@pytest.fixture
def file_data():
return factories.FileFactory... | StarcoderdataPython |
104970 | from __future__ import absolute_import
# import apis into api package
from .console_api import ConsoleApi
from .cq_api import CqApi
from .crx_api import CrxApi
from .custom_api import CustomApi
from .sling_api import SlingApi
| StarcoderdataPython |
1768287 | import datetime
import gym
import gym_mouse_lib
import gym_mouse_lib.gym_mouse
import numpy as np
from deep_deterministic_policy_gradient import Agent
#from utils import plot_learning_curve
import numpy as np
import matplotlib.pyplot as plt
def plot_learning_curve(x, scores, figure_file):
running_avg = np.zeros(l... | StarcoderdataPython |
1615134 | <reponame>davidsmandrade/movies_backend
import datetime
import os
import random
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prs_project.settings')
import django
django.setup()
from collector.models import Log
SEED = 42
films = {'comedy':
[
'0475290'
,'128940... | StarcoderdataPython |
1675891 | <reponame>yuzhiguo07/openfold<filename>openfold/np/relax/amber_minimize.py
# Copyright 2021 AlQuraishi Laboratory
# Copyright 2021 DeepMind Technologies Limited
#
# 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 ... | StarcoderdataPython |
4828090 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import os
import os.path
import tempfile
# Import Salt Testing libs
from salttesting import TestCase
from salttesting.mock import patch, MagicMock
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('..... | StarcoderdataPython |
18101 | <gh_stars>0
# -*- coding: utf-8 -*-
import time
import xlrd
import Register_aidaiwangApp
import LogOut_aidiawangApp
def start_to_login(filename):
print(u'login')
driver = Register_aidaiwangApp.driver
driver.launch_app()
time.sleep(3)
try:
driver.find_element_by_id('cn.phaidai.loan:id/rb_m... | StarcoderdataPython |
18931 | <reponame>qq1010903229/OIer
f = open("OI_school.csv")
op = open("mdt.txt","w")
for i in f.readlines():
c = i.split('","')
op.write(c[-3]+','+c[-2]+','+"".join([i+',' for i in eval(c[1])])[:-1]+'\n')
| StarcoderdataPython |
3278515 | <filename>graviteeio_cli/commands/apim/auth/load.py
import click
from graviteeio_cli.modules.gio_module import GioModule
@click.command()
@click.argument('user', required=True)
@click.pass_obj
def load(obj, user):
"""
Load current profile
"""
config = obj['config'].getGraviteeioConfig(GioModule.APIM)... | StarcoderdataPython |
95705 | <reponame>DropBear586/ursina<filename>ursina/scripts/chunk_mesh.py<gh_stars>1000+
from ursina import *
from math import floor
app = Ursina()
t = time.time()
application.asset_folder = application.asset_folder.parent.parent
terrain = Entity(model=Terrain('grass_fields_heightmap', skip=8), texture='grass', texture_scal... | StarcoderdataPython |
11935 | import random
from Virus import Virus
class Person:
''' The simulation will contain people who will make up a population.'''
def __init__(self, is_vaccinated, infection=None):
''' We start out with is_alive = True
All other values will be set by the simulation through the parameters when
... | StarcoderdataPython |
1604642 | <filename>tests/util/test_types.py
import ctypes
import unittest
import racetools.util.types as types
def c_string(content, length=16):
array_type = ctypes.c_char * length
result = array_type()
result[:len(content)] = content
return result
class TestCStringToStr(unittest.TestCase):
def test_val... | StarcoderdataPython |
1657478 | <reponame>sisl/VerifyGAN
from xpc3 import *
from xpc3_helper import *
from xpc3_helper_SK import *
from nnet import *
from PIL import Image
import numpy as np
import h5py
import time
import mss
import cv2
import os
filename = "../../models/KJ_TaxiNet.nnet"
network = NNet(filename)
### IMPORTANT PARAMETERS FOR IMAGE ... | StarcoderdataPython |
14588 | <gh_stars>1-10
import ipfinder
con = ipfinder.config('f67f788f8a02a188ec84502e0dff066ed4413a85') # YOUR_TOKEN_GOES_HERE
# domain name
by = 'DZ';
dby = con.getDomainBy(by)
print(dby.all)
| StarcoderdataPython |
1766043 | <filename>echolect/tools/iteration.py<gh_stars>1-10
#-----------------------------------------------------------------------------
# Copyright (c) 2014, <NAME>
# All rights reserved.
#
# Distributed under the terms of the BSD 3-Clause ("BSD New") license.
#
# The full license is in the LICENSE file, distributed with th... | StarcoderdataPython |
1687546 | <filename>website/lab/apps.py
from __future__ import unicode_literals
from django.apps import AppConfig
class LabConfig(AppConfig):
name = 'lab'
| StarcoderdataPython |
3295726 | def test_empty_object(worksheet):
ws = worksheet
sheet_items = ws.sheet_items
assert sheet_items == []
def test_parse_csv_header(worksheet):
ws = worksheet
path = "tests/inventory.csv"
csv_file = open(path, "r", encoding="utf-8-sig")
ws.csv_to_dict(csv_file=csv_file, delimiter=";")
ws_... | StarcoderdataPython |
3212387 | from calendar import EPOCH
from tensorflow import keras
from tensorflow.keras.applications import DenseNet121
import environmentsettings
from tensorflow.keras.callbacks import LearningRateScheduler
import math
def step_decay(epoch):
initial_lrate = 0.1
drop = 0.5
epochs_drop = 10.0
lrate = initial_lrate * math.pow... | StarcoderdataPython |
1644590 | <reponame>Elyk8/dotrice
#!/usr/bin/python
import inkscapeMadeEasy.inkscapeMadeEasy_Base as inkBase
import inkscapeMadeEasy.inkscapeMadeEasy_Draw as inkDraw
class switch(inkBase.inkscapeMadeEasy):
def add(self, vector, delta):
# nector does not need to be numpy array. delta will be converted to numpy arra... | StarcoderdataPython |
3384261 | <reponame>rajahaidar/lmctl<gh_stars>0
import datetime
import requests
import logging
import time
from .base import LmDriver
logger = logging.getLogger(__name__)
class LmSecurityDriver(LmDriver):
"""
Client for LM Security APIs
"""
def __init__(self, lm_base):
super().__init__(lm_base)
d... | StarcoderdataPython |
33365 | <reponame>keceli/mechdriver<filename>mechroutines/es/runner/scan.py
""" Library to perform sequences of electronic structure calculations
along a molecular coordinate and save the resulting information to
SCAN or CSAN layers of the save filesystem.
"""
import numpy
import automol
import autofile
import elstru... | StarcoderdataPython |
195913 | <reponame>xianlinfeng/project_euler_python3
import itertools
class Number:
"""
class to store a middle-stage data
"""
def __init__(self, start, belong, end, value):
"""
docstring
"""
self.start = start # the previous list which share the first two digits with sel... | StarcoderdataPython |
86018 | from urllib.request import urlopen
from urllib.request import FancyURLopener
from bs4 import BeautifulSoup
import pandas as pd
import os
import _proj_functions as proj
import _lookups as lookups
import re
outdir = '../output'
##### duke ###########################
school = 'duke'
sports_dict = lookups.get_sports_dic... | StarcoderdataPython |
3398495 | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from path import Path
from slugify import slug... | StarcoderdataPython |
3212648 | import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime
plt.style.use(['science', 'no-latex'])
df = pd.read_excel('data/pf_result_new_with_benchmark.xlsx')
df.columns = ['timestamp', 'Portfolio Monthly Return', 'Benchmark Monthly Return', 'Portfolio Total Return (0 -> t)',
... | StarcoderdataPython |
1657538 | import numpy as np
import pandas as pd
import math
import os
root_path = os.path.dirname(os.path.abspath('__file__'))
def mean_absolute_percentage_error(y_true,y_pred):
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
def PPTS(y_true,y_pred,gamma):
"""
Compute peak percentage threshold statistic... | StarcoderdataPython |
198310 | #!/usr/bin/python
# Copyright (c) 2020, Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""Provide Module Description
"""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
__author__ = ["<NA... | StarcoderdataPython |
1771338 | hyper_params = {
'lr': 1e-4,
'betas': (0.9, 0.999),
'batch': 4,
'num_workers': 0,
'epochs': 1,
'seed': 1234,
'model_save_path': '/home/pattersonwu/apps/NeuroImaging/'
}
| StarcoderdataPython |
3251279 | #!/usr/bin/env python
import sys
import argparse
import numpy as np
def compare(hex_file, int_file):
# Parse the hex file
data_list = []
fp = open(hex_file, 'r')
line_list = []
for line in fp:
line_list.append(line.strip())
for s in line_list:
data_line = []
fo... | StarcoderdataPython |
3237225 | <reponame>yangdemin/dingpan
from huobi.model.constant import *
class CompleteSubAccountInfo:
"""
Sub-account completed info
:member
id: The sub-id.
account_type: The sub account type.
balances: The balance list, the content is Balance class.
"""
def __init__(self):
... | StarcoderdataPython |
1613811 | <reponame>NikolaSiplakova/Baobab<gh_stars>10-100
"""empty message
Revision ID: 85d13062a5e7
Revises: <PASSWORD>
Create Date: 2020-02-25 18:22:20.037572
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
# #... | StarcoderdataPython |
93586 | <gh_stars>0
"""Test entity_registry API."""
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.helpers.entity_registry import RegistryEntry
from homeassistant.components.config import entity_registry
from tests.common import mock_registry, MockEntity, MockEntityPlatform
@pytest.fi... | StarcoderdataPython |
120477 | from flask import current_app as app
class Purchase:
def __init__(self, id, uid, ticker,num_shares, cost, time_purchased):
self.id = id
self.uid = uid
self.ticker = ticker
self.num_shares=num_shares
self.cost=cost
self.time_purchased = time_purchased
@staticmet... | StarcoderdataPython |
12591 | #!/usr/bin/env python
from .error import FLVError
from .compat import is_py2
from .tag import Header, Tag
class FLV(object):
def __init__(self, fd=None, strict=False):
self.fd = fd
self.header = Header.deserialize(self.fd)
self.strict = strict
def __iter__(self):
return self
... | StarcoderdataPython |
1799515 | <reponame>YorkSu/hat<gh_stars>1-10
# pylint: disable=attribute-defined-outside-init
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.layers import Layer
from tensorflow.python.keras.utils import conv_utils
class ExtendRGB(Layer):
"""
Extend the RGB channels
Input:
(batch... | StarcoderdataPython |
1686388 | import tkinter as Tk
class View:
result = ''
def __init__(self, controller, model):
self.controller = controller
self.model = model
self.model.register(self)
def update(self, result):
self.result = result
self.display()
def display(self):
print(self.... | StarcoderdataPython |
3352405 | <filename>artview/scripts/_common.py<gh_stars>0
"""
_common.py
auxiliary functions for scripts
"""
import pyart
from ..components import (Menu, RadarDisplay, GridDisplay, LinkPlugins,
SelectRegion, PointsDisplay)
from ..core import QtGui, QtCore
def _add_all_advanced_tools(menu):
# add... | StarcoderdataPython |
129061 | import random
import torch
import torch.optim as optim
from parlai.agents.dialog_evaluator.auto_evaluator import (
TorchGeneratorWithDialogEvalAgent,
CorpusSavedDictionaryAgent
)
from parlai.core.metrics import AverageMetric
from parlai.core.torch_agent import History
from parlai.core.torch_generator_agent im... | StarcoderdataPython |
1765224 | import flask
import pytest
# Rewrites the path so the app can be imported like it normally is
import os
import sys
topdir = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(topdir)
from app import app
INVALID_USER = dict(
username="invalid",
password="<PASSWORD>"
)
TEST_ENDPOINTS = [
'/',
... | StarcoderdataPython |
132533 | from model.group import Group
from model.contact import Contact
import mysql.connector
class DbFixture:
def __init__(self, host, name, user, password):
self.host=host
self.name=name
self.user=user
self.password=password
self.connection=mysql.connector.connect(host=host, data... | StarcoderdataPython |
188105 | #!/usr/bin/env python
"""
Copyright (C) 2019 <NAME> Ltd
Copyright (C) 2019 <NAME>, ETH Zurich
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
th... | StarcoderdataPython |
3206963 | <filename>app/lib/graph.py
import networkx as nx
import matplotlib.pyplot as plt
def grapher(combos):
if not combos:
print("NO NODES")
return
graph = nx.Graph()
for c in combos:
graph.add_edge(c[0], c[1], weight=1)
# print("Number of Nodes: " + str(G.number_of_nodes()))
# p... | StarcoderdataPython |
3286761 | <reponame>zhaofeng-shu33/django-todo
import bleach
import json
import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.urls import reverse
from todo.models import Task, TaskList
"""
First the "smoketests" - do they respond at all for a logged in admin use... | StarcoderdataPython |
4803515 | <reponame>DadeCoderh/starlingx-stagingm
# Copyright 2015 Huawei Technologies Co., Ltd.
# Copyright 2015 Ericsson AB.
# 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 Licen... | StarcoderdataPython |
1721718 | <filename>messages.py
#!/usr/bin/python
class Upload:
def __init__(self, from_id, to_id, up_bw):
self.from_id = from_id
self.to_id = to_id
self.bw = up_bw
def __repr__(self):
return "Upload(from_id = %s, to_id=%s, bw=%d)" % (
self.from_id, self.to_id, self.bw)
clas... | StarcoderdataPython |
107781 | <gh_stars>10-100
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from fa2l import force_atlas2_layout
from adjustText import adjust_text
import networkx as nx
from .utils import set_node_size, set_node_color, set_node_label
from .utils import edgecolor_by_source, filter_graph, get_subgraph_pos
... | StarcoderdataPython |
3304177 | <filename>Python/strings.py
# strings can be enclosed in single, double, or triple quotes
a = "Hello world"
b = 'CECS 424 is awesome'
c = """Triple-quoted strings
can go more than one line"""
# can index strings with []
d = a[0] # d = 'H'
# the slicing operator [i:j] can extract substrings from index
# i <= k < j
e =... | StarcoderdataPython |
1775342 | <reponame>mikegrudic/Firefly
import pandas as pd
import os
def write_to_json(dictionary,path=None):
"""Simple utility function to write a dictionary to a path as :code:`.json` file.
If path is None then instead a string is returned (thanks pandas!)
:param dictionary: arbitrary data dictionary that we ... | StarcoderdataPython |
133708 | from setuptools import setup, find_packages
import sys
setup(
name='doaj',
version='5.0.3',
packages=find_packages(),
install_requires=[
"Werkzeug==0.16.0",
"Flask==1.1.1",
"Flask-Login==0.4.1",
"WTForms==2.2.1",
"Flask-WTF==0.14.2",
"Flask-Mail==0.9.1",
... | StarcoderdataPython |
3330002 | import numpy as np
import matplotlib.pyplot as plt
arr = np.random.random(size=1000)
print("Uniform distribution")
print("Mean: ", np.mean(arr), "Std. dev.: ", np.std(arr))
plt.hist(arr, 50)
plt.title('Uniform distribution')
arr = np.random.normal(size=1000)
print("Normal distribution")
print("Mean: ", np.mean(arr), ... | StarcoderdataPython |
4817061 | <reponame>Haoyu-R/CarND-Behavioral-Cloning-P3
import csv
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda,... | StarcoderdataPython |
1655672 | <filename>sgains/pipelines/extract_10x_pipeline.py
'''
Created on Jul 13, 2017
@author: lubo
'''
import os
import gzip
import glob
import subprocess
from collections import defaultdict
import pysam
import pandas as pd
from dask import distributed
from termcolor import colored
from sgains.pipelines.mapping_pipeline ... | StarcoderdataPython |
1613612 | from . import BasicDataIgnition
import transaction
from mock import MagicMock, Mock
from mock_alchemy.mocking import AlchemyMagicMock
from pyramid import testing
from unittest.mock import patch
from sqlalchemy.exc import IntegrityError, OperationalError
class TestMacro(BasicDataIgnition):
def setUp(self):
... | StarcoderdataPython |
4804526 | #
#
# #############################################################################
# Copyright (c) 2018 Universidad Nacional de Colombia All Rights Reserved.
#
# This work was made as a development to improve data collection
# for self-assessment and accreditation processes in the Vicedeanship
... | StarcoderdataPython |
1780904 | <filename>tahoe_sites/migrations/0001_initial.py
# Generated by Django 2.2.26 on 2022-01-14 08:28
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
from tahoe_sites import zd_helpers
class Migration(migrations.Migration):
initial = True
... | StarcoderdataPython |
122874 | <gh_stars>1-10
# Utility functions.
#
# This file is part of a modified version of thomasa88lib, a library of useful
# Fusion 360 add-in/script functions.
#
# Copyright (c) 2021 ZXYNINE
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fil... | StarcoderdataPython |
3316547 | from enum import Enum, IntEnum
from subprocess import CalledProcessError
from colored import fg, stylize
from .environment import EnvironmentVariable
class Color(Enum):
ERROR = fg("red")
NOTICE = fg("yellow")
class MessageLevel(IntEnum):
LOUD = 2
NORMAL = 1
QUIET = 0
def _level() -> MessageL... | StarcoderdataPython |
1707108 | # -*- coding: utf-8 -*-
import pytest
from pytest import raises
import pip
import pip._internal.commands
import pip._internal.commands.install
import six
import picage
from picage.model import Package, Module
from pathlib_mate import PathCls as Path
def assert_is_strictly_ascending(l):
for i, j in zip(l[:-1], ... | StarcoderdataPython |
1696787 | import streamlit as st
import pandas as pd
import numpy as np
import pickle
import base64
@st.cache(suppress_st_warning=True)
def get_fvalue(val):
feature_dict = {"No":1,"Yes":2}
for key,value in feature_dict.items():
if val == key:
return value
def get_value(val,my_dict):
for key,va... | StarcoderdataPython |
24102 | #!/usr/bin/env python
import drmaa
import shlex
from optparse import OptionParser
from sys import stderr, stdin, exit
from datetime import datetime
import traceback
def Stop(pool, jt, info):
'''Job failure function that stops synchronization.'''
pool.shall_stop = True
pool.all_done = False
pool.failed... | StarcoderdataPython |
10436 | from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
wine = load_wine()
columns_names = wine.feature_names
y = wine.target
X = wine.data
print('Pre scaling X')
print(X)
scaler = StandardScaler()
scaler.fit(X)
scaled_features = sc... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.