id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3281071 | <filename>rest_api.py
"""This is the REST API module.
"""
import json
import logging
import requests
logger = logging.getLogger("REST_API")
logger.addHandler(logging.NullHandler())
headers = {"Content-Type": "application/json"}
class RestApi:
"""
This is a class for the REST API module.
:ivar int port_... | StarcoderdataPython |
1793856 | <filename>regions/management/commands/sync_regions.py<gh_stars>1-10
from django.core.management.base import BaseCommand, CommandError
from regions.models import Region
class Command(BaseCommand):
help = 'Sync regions data from amap api'
def handle(self, *args, **options):
try:
Region.objec... | StarcoderdataPython |
1788834 | import pandas as pd
import torch
import torch.nn as nn
import torch.utils.data
from torch_model_base import TorchModelBase
from utils import progress_bar
from torch_autoencoder import TorchAutoencoder
from torch.autograd import Variable
__author__ = "Simranjit"
__version__ = "CS224u, Stanford, Spring 2020"
class MMDV... | StarcoderdataPython |
3208035 | # Generated by Django 3.2 on 2021-04-23 10:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project_core', '0162_callpartfile_proposal_keywords_null'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
1747351 | <reponame>t-pool/rcoin
from test_framework.script import hash160
from test_framework.messages import sha256, hash256
from binascii import hexlify,unhexlify
if __name__ == '__main__':
# 生成script_test中的部分数据
print(hexlify(sha256(b"")))
print(hexlify(sha256(b"a")))
print(hexlify(sha256(b"abcdefghijklmnopqr... | StarcoderdataPython |
1790048 | from random import choice
import winsound
# VARIAVEIS
pd = str('Pedra')
pp = str('Papel')
ts = str('Tesoura')
lista = [pd, pp, ts]
escolha = choice(lista)
# INTERFACE
print ('''SUAS OPÇÕES
[ 1 ] Pedra
[ 2 ] Papel
[ 3 ] Tesoura''')
pergunta = int(input('Qual sua opção: '))
if pergunta == 1:
m = str('Pedra')
elif per... | StarcoderdataPython |
3214604 | <gh_stars>0
# -*- encoding: utf-8 -*-
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.core.validators import RegexValidator
from .models import *
from django.contrib.auth import get_user_model
User = get_user_model()
class RationCardInput(forms.Form):
rationcard_rx = ... | StarcoderdataPython |
1772520 | """
bgpls/tlvs/__init__.py
Created by <NAME> on 2016-11-26. <EMAIL>
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from exabgp.bgp.message.update.nlri.bgpls.tlvs.node import NodeDescriptor
from exabgp.bgp.message.update.nlri.bgpls.tlvs.neighaddr import N... | StarcoderdataPython |
68513 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 2 17:03:04 2017
@author: Villanueva
"""
import warnings
import pytest
from simetuc.util import IonType, Transition, DecayTransition, Excitation, EneryTransferProcess
from simetuc.util import log_exceptions_warnings
def test_transition():
'''Test generic transitio... | StarcoderdataPython |
3296647 | from sqlalchemy_utils import UUIDType
from sqlalchemy import UniqueConstraint
from sqlalchemy.types import JSON as JSONType
# Available for custom sqlalchemy_options
import datetime
from sqlalchemy import text, func
from bookshop.sqlalchemy import db
from bookshop.sqlalchemy.model.types import BigIntegerVariantType
... | StarcoderdataPython |
1783750 | <reponame>thinkmoore/das
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Some tools for manipulating PDF files
import py.test
import sys
import os
import re
from subprocess import call,Popen,PIPE,DEVNULL
import subprocess
import glob
import tempfile
__version__="0.1.0"
ERROR_LINES=30
DEBUG=False
if sys.platform==... | StarcoderdataPython |
1788431 | <reponame>fishjojo/pycosmosac
import os
import unittest
import json
from pycosmosac.param import parameters, data
here = os.path.abspath(os.path.dirname(__file__))
class KnownValues(unittest.TestCase):
def test_load(self):
myparam = parameters.Parameters() #default
self.assertEqual(myparam.paramet... | StarcoderdataPython |
190706 | <filename>src/genie/libs/parser/nxos/tests/ShowIpInterfaceBrief/cli/equal/golden_output_1_expected.py
expected_output = {'interface':
{'Eth5/48.106':
{'interface_status': 'protocol-down/link-down/admin-up',
'ip_address': '1... | StarcoderdataPython |
1621937 | from config.settings.base import HASHID_FIELD_SALT
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from hashid_field import HashidAutoField
class CustomUser(AbstractUser):
"""Custom user model.
This inherits from Django's... | StarcoderdataPython |
4813764 | """
Count Positives
Given several numbers, count how many different results bigger or equal than 0 can you produce by only
using addition (+) and substraction (-). All the numbers must be used.
Input: [2, 3, 1]
Output: 4
Output explanation:
2+3+1 = 6
2+3-1 = 4
2-3+1 = 0
2-3-1 = -2 (neg... | StarcoderdataPython |
1663651 | from QR_generate import generate_qr
import QR_scanner
import graph
generate_qr() | StarcoderdataPython |
58903 | from django.conf.urls import patterns, url
from qs import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^sendqs/$', views.sendqs, name='sendqs'),
url(r'^show/$', views.showall, name='showall'),
)
| StarcoderdataPython |
3358703 | <reponame>stac-utils/stac-api-benchmark
"""STAC API Benchmark."""
| StarcoderdataPython |
195968 | <gh_stars>0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import abc
from enum import Enum
from cryptography import utils
from cryptography.hazmat.backends import _get_backend
def l... | StarcoderdataPython |
3298811 | <gh_stars>0
"""
pyexcel_xlsx.xlsxw
~~~~~~~~~~~~~~~~~~~
Write xlsx file format using openpyxl
:copyright: (c) 2015-2019 by Onni Software Ltd & its contributors
:license: New BSD License
"""
import openpyxl
from pyexcel_io.book import BookWriter
from pyexcel_io.sheet import SheetWriter
class XLSX... | StarcoderdataPython |
90166 | <filename>oggm_vas/core.py
""" Implementation of the 'original' volume/area scaling glacier model from
Marzeion et. al. 2012, see http://www.the-cryosphere.net/6/1295/2012/.
While the mass balance model is comparable to OGGMs past mass balance model,
the 'dynamic' part does not include any ice physics but works with ar... | StarcoderdataPython |
3299942 | <reponame>ni-ning/django<filename>tests/forms_tests/widget_tests/test_textarea.py
from django.forms import Textarea
from django.utils.safestring import mark_safe
from .base import WidgetTest
class TextareaTest(WidgetTest):
widget = Textarea()
def test_render(self):
self.check_html(self.widget, 'msg'... | StarcoderdataPython |
1739788 | <gh_stars>0
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self, A, B):
if A == None and B == None: # if both trees are empty they are identical
return True
while A != None and B != None:
print("A.val = {} --- B.val = {}" .form... | StarcoderdataPython |
1753957 | import b
c = b.f(2, 3)
print(c) | StarcoderdataPython |
167693 | def test():
assert len(TRAINING_DATA) == 4, "Los datos de entrenamiento no concuerdan – esperaba 4 ejemplos."
assert all(
len(entry) == 2 and isinstance(entry[1], dict) for entry in TRAINING_DATA
), "Formato incorrecto de los datos de entrenamiento. Esperaba una lista de tuples dónde el segundo elem... | StarcoderdataPython |
8472 | #!/usr/bin/env python
import setuptools
from setuptools import setup
from os import path
# Read the package requirements
with open("requirements.txt", "r") as f:
requirements = [line.rstrip("\n") for line in f if line != "\n"]
# Read the contents of the README file
this_directory = path.abspath(path.dirname(__fi... | StarcoderdataPython |
3298027 | #!/usr/bin/env python3
# -*- coding: ascii -*-
"""
A script for locating Java source files in need of a recompile.
"""
import sys, os, re
import stat
COMMENT_RE = re.compile(r'^\s*(#.*)?$')
MAP_LINE_RE = re.compile(r'^([^\s:#]+):((?:\s*[^\s:#]+)*)\s*$')
class FSCache:
"A caching wrapper around select filesystem... | StarcoderdataPython |
1600078 | <reponame>qianjing2020/DS-Unit-3-Sprint-2-SQL-and-Databases
"""A pipeline to get data from sqlite db and insert to elephant sql db using OOP approach
"""
import os
import json
from dotenv import load_dotenv
import sqlite3
import psycopg2
from psycopg2.extras import execute_values
load_dotenv()
dbname = os.getenv("d... | StarcoderdataPython |
1727516 | <reponame>Leo-Ryu/gtfspy<filename>gtfspy/import_loaders/stop_times_loader.py
from gtfspy.import_loaders.table_loader import TableLoader, decode_six
class StopTimesLoader(TableLoader):
fname = 'stop_times.txt'
table = 'stop_times'
tabledef = ('(stop_I INT, trip_I INT, arr_time TEXT, dep_time TEXT, '
... | StarcoderdataPython |
101900 | import json
from mayan.apps.document_states.tests.mixins import WorkflowTestMixin
from mayan.apps.document_states.literals import WORKFLOW_ACTION_ON_ENTRY
from mayan.apps.documents.tests.base import GenericDocumentViewTestCase
from ..models import DocumentPageOCRContent
from ..workflow_actions import UpdateDocumentPa... | StarcoderdataPython |
3399968 | <filename>src/centrol_bots/centrol_discord.py
from configs.user_messages import (
CHART_NOT_AVAILABLE,
ALERT_KEY_NOT_KNOWN,
HOT_TIP_1,
HOT_TIP_2,
HOT_TIP_3,
HOT_TIP_4,
HOT_TIP_5,
HOT_TIP_6,
HOT_TIP_7,
)
from discord_slash.utils.manage_commands import create_option, create_... | StarcoderdataPython |
3370280 | <reponame>jarajanos/nanpy<filename>nanpy/examples/pressure.py
"""Pressure sensor demo.
Connect the BMP180 to the I2C bus.
"""
from __future__ import division
from nanpy.arduinotree import ArduinoTree
from nanpy.serialmanager import SerialManager
from nanpy.bmp180 import Bmp180
def main():
connection = SerialM... | StarcoderdataPython |
1616204 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ResBlock(nn.Module): # not paper original
def __init__(self):
super(ResBlock, self).__init__()
self.conv1 = nn.Conv2d(64, 64, kernel_size=5, stride=1, padding=2)
self.conv2 = nn.Conv2d(64, 64, kernel_size=5, stride=1... | StarcoderdataPython |
87634 | <filename>Convention/Script/AlignText/align_horizontally.py<gh_stars>1-10
import sys
from functools import reduce
import settings
def align_vertically():
lines_left, lines_right = read_input()
lines_left = rstrip_list(lines_left)
lines_right = rstrip_list(lines_right)
lines_left, lines_right = equa... | StarcoderdataPython |
3242020 | from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
from yolov3_tf2.models import YoloV3, YoloV3Tiny
from yolov3_tf2.utils import load_darknet_weights
import tensorflow as tf
flags.DEFINE_string('weights', './data/yolov3.weights', 'path to weights file')
flags.DEFINE_string('output', '... | StarcoderdataPython |
4233 | """
Author: <NAME>
"""
import numpy as np
import pandas as pd
from sklearn.neighbors import NearestNeighbors
def affinity_graph(X):
'''
This function returns a numpy array.
'''
ni, nd = X.shape
A = np.zeros((ni, ni))
for i in range(ni):
for j in range(i+1, ni):
dist = ((X[i] - X[j])**2).sum() # compute ... | StarcoderdataPython |
34256 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('extras', '0060_customlink_button_class'),
]
operations = [
migrations.AddField(
model_name='customfield',
name='created',
field=models.DateField(auto_now... | StarcoderdataPython |
3205536 | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
# Look pretty...
# matplotlib.style.use('ggplot')
plt.style.use('ggplot')
#
# TODO: Load up the Seeds Dataset into a Dataframe
# It's located at 'Datasets/wheat.data'
#
# .. your code here ..
df = pd.read_csv('Datasets/wheat.data')
#
# TODO: Cre... | StarcoderdataPython |
3364648 | <filename>clustering/gmm_lda/gmm/__init__.py
#! /usr/bin/env python
"""
Author: <NAME>
Program: __INIT__.PY
Date: Wednesday, May 23 2012
"""
from normal import Normal
from gmm_main import GMM, shownormal
| StarcoderdataPython |
124571 | import pandas as pd
import numpy as np
import py_entitymatching as em
from .magellan_modified_feature_generation import get_features
#Given a CANDIDATE SET and the list of ACTUAL duplicates (duplicates_df),
#this function adds the 1/0 labels (column name = GOLD) to the candset dataframe
def add_labels_to_candset(dupl... | StarcoderdataPython |
1640247 | from rmapy.api import Client
rmapy = Client()
def upload():
if rmapy.renew_token():
return True
else:
rmapy.log.error("Rmarkable token renew failed:")
| StarcoderdataPython |
3321753 | #Grade Point Average Calculator App
print("Welcome to the Grade Point Average Calculator App")
#Get user input
name = input("What is your name: ").title().strip()
grade_num = int(input("How many grades would you like to enter: "))
#Get the user's grades
grades = []
for i in range(grade_num):
grades.append(int(in... | StarcoderdataPython |
1691905 | #!/usr/bin/env python
##############################################################################
##
# This file is part of Sardana
##
# http://www.sardana-controls.org/
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Sardana is free software: you can redistribute it and/or modify
# it under th... | StarcoderdataPython |
59163 | #!/usr/bin/env python
# encoding: utf-8
####### todo:
# reverse compliment #
### input fasta file
### input gRNA.bed, design file
### output count number for next step.
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL)
from sys import stdin, stderr
import argparse
parser = argparse.ArgumentParser... | StarcoderdataPython |
3291464 | <filename>deeprl_cc/plot_utils.py
# -*- coding: utf-8 -*-
# Plotting utilities from OpenAI baselines package
# Source: https://github.com/openai/baselines/blob/master/baselines/common/plot_util.py
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
plt.style.use('ggplot')
class _... | StarcoderdataPython |
3301847 | <reponame>bmeyers/optimal-signal-demixing<filename>osd/components/markov.py
''' Markov Process Signal
This module contains the class for a signal defined as a Markov Process over
discrete values
Author: <NAME>
'''
from scipy import sparse
import numpy as np
from osd.components.component import Component
class Marko... | StarcoderdataPython |
81243 | from ..utils.constants import *
from ..utils.vector3 import vec3, rgb, extract
from functools import reduce as reduce
from ..ray import Ray, get_raycolor
from .. import lights
import numpy as np
from . import Material
from ..textures import *
class Emissive(Material):
def __init__(self, color, **kwargs)... | StarcoderdataPython |
3388333 | from pycocotools import mask as cocomask
from fastai2.vision.all import *
def get_segmentations(labeled):
nr_true = int(labeled.max())
segmentations = []
for i in range(1, nr_true + 1):
msk = labeled == i
segmentation = rle_from_binary(msk.astype('uint8'))
segmentation['counts'] = s... | StarcoderdataPython |
172608 | <gh_stars>0
#!/usr/bin/python
#Header Info
__author__ = 'Splix76'
__email__ = '<EMAIL>'
__license__ = 'GPLv3'
#import modules
import psutil
import sys
from optparse import OptionParser, OptionGroup
#parse argumements
def parse_args():
parser = OptionParser()
parser.description = "Check Linux Host Memory Us... | StarcoderdataPython |
3350742 | #!/usr/bin/python
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from math import pi
class imu_visualize():
def __init__(self):
#rotation
self.x_axis = 0.0
self.y_axis = 0.0
self.z_axis = 0.0
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
gl... | StarcoderdataPython |
3287821 | # Copyright (c) 2021 Graphcore Ltd. All rights reserved.
from pathlib import Path
import pytest
from examples_tests.test_util import SubProcessChecker
working_path = Path(__file__).parent.parent.joinpath("tut1_porting_a_model")
class TestComplete(SubProcessChecker):
@pytest.mark.category2
@pytest.mark.ipu... | StarcoderdataPython |
113393 | class Config(object):
env = 'default'
backbone = 'resnet18'
classify = 'softmax'
num_classes = 5000
metric = 'arc_margin'
easy_margin = False
use_se = False
loss = 'focal_loss'
display = False
finetune = False
meta_train = '/preprocessed/train_meta.csv'
train_root = '/p... | StarcoderdataPython |
1631788 | <filename>configs/lvis/exp_config.py
root= '/mnt/lustrenew/zhanggang/data_t1/mmdetection/'
cfg_root = root + 'configs/lvis/'
data_root = root + 'data/lvis'
_base_ = [cfg_root + 'mask_rcnn_r50_fpn_sample1e-3_mstrain_1x_lvis_v1.py']
data = dict(
samples_per_gpu=1,
workers_per_gpu=1,
train=dict(
data... | StarcoderdataPython |
3339549 | <reponame>seattleboy/DjangoLearn
from __future__ import unicode_literals
from django.db import models
# from django.utils.encoding import python_2_unicode_compatible
class Author(models.Model):
name=models.CharField(max_length=50)
qq=models.CharField(max_length=10)
addr=models.TextField()
email=models.... | StarcoderdataPython |
3360811 | <reponame>fakecoinbase/sweetpandslashAlgorithms<gh_stars>1-10
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import numpy as np
from torch.autograd import Variable
from torchvision import transforms
import pandas as pd
from sklearn.model_selection import train_tes... | StarcoderdataPython |
121751 | from __future__ import absoulte_import
from __future__ import division
from __future__ import print_function
import csv
import os
import tensorflow as tf
import advesarial_losses as adv_lib
flags = tf.app.flags
FLAGS = flags.FLAGS
| StarcoderdataPython |
103294 | import pickle
def audio_condition():
# natural versus narration
narration_users = ['user2', 'user4', 'user7', 'user8', 'user10','user14','user16','user18','user20']
natural_users = ['user3','user5','user6','user9','user11','user12','user15','user17','user19']
filename = '../data/narration_users.pkl'
... | StarcoderdataPython |
3383000 | <reponame>gmarciani/ipath<filename>control/shortestpath/common_sc.py
#Support Data-Structures Import
from sets import Set
#Math Imports
from random import sample
from itertools import combinations
#Map Import
from utils.map_utils import geo_distance
ISOLATED_NODE = 1
def get_random_nodes(graph, num_nodes):
nodes_... | StarcoderdataPython |
1739045 | <filename>app/migrations/versions/977bb6ada425_.py
"""empty message
Revision ID: 977bb6ada425
Revises: <KEY>
Create Date: 2016-11-28 11:38:08.169942
"""
# revision identifiers, used by Alembic.
revision = '977bb6ada425'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### ... | StarcoderdataPython |
3207610 | import http.client
import logging
from telegram import Update, ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, Chat
from telegram.ext import TypeHandler, CallbackContext, CommandHandler, MessageHandler, Filters
from bot import settings
from bot.const import TELEGRAM_BOT_TOKEN, DATABASE_FILE, DEBUG
from bot.git... | StarcoderdataPython |
1754475 | <reponame>smileboywtu/tornado-restful-cookiecutter
# -*- coding: utf-8 -*-
"""
配置日志信息,并添加 request_id
:create: 2018/9/23
:copyright: smileboywtu
"""
import datetime
import logging
import sys
import uuid
from logging.handlers import TimedRotatingFileHandler
from tornado import gen
from tornado.log import access_log
f... | StarcoderdataPython |
1712771 | <gh_stars>1-10
ab = "ssof"
cd = t(ab, vuln)
ef = s("hack")
gh = t(ef)
sink(gh,cd)
| StarcoderdataPython |
55782 | <reponame>Glenn-Po/LearningPython
import turtle
big_line = 100
little_line = 50
angle = 90
turtle.left(angle)
turtle.forward(big_line)
count = 0
while count < 4:
turtle.right(angle//2)
if count != 3:
turtle.forward(little_line)
else:
turtle.forward(big_line)
count = count + 1
turtle.righ... | StarcoderdataPython |
127652 | <reponame>artyl/playwright-python
# Copyright (c) Microsoft Corporation.
#
# 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 a... | StarcoderdataPython |
1776974 | <filename>src/ralph/backends/database/__init__.py
"""Database backends for Ralph"""
from .base import BaseDatabase # noqa: F401
from .es import ESDatabase # noqa: F401
| StarcoderdataPython |
1745230 | #!/home/jepoy/anaconda3/bin/python
x = 42
y = isinstance(x, int)
print(x)
print(y)
print()
x = 42
y = isinstance(x, float)
print(x)
print(y)
print()
x = 42
y = id(x)
print(x)
print(y)
print() | StarcoderdataPython |
39354 | <reponame>nhatnxn/ID_Passport-OCR
from .dectect import detect_card
__all__ = [detect_card] | StarcoderdataPython |
3304463 | <filename>Automation/autodelete.py
import os
##削除するファイルの拡張子を取得する
extension = (".xlsm") ##削除したい拡張子を入力
## ディレクトリのパスを取得
path_name = ("C:\\テスト") ##ディレクトリのパスを入力
##全てのディレクトリのファイル名を取得
for curDir, dirs, files in os.walk(path_name):
for filename in files:
if filename.endswith(extension): ##指定された拡張子を持つファイルが... | StarcoderdataPython |
87654 | # Generated by Django 3.2.9 on 2021-12-04 14:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0003_comment_image'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='profile_photo',
... | StarcoderdataPython |
3342206 | from cse.lang.PreprocessorStep import PreprocessorStep
class NltkStemmer(PreprocessorStep):
__stemmerType = None
def __init__(self, stemmerType):
self.__stemmerType = stemmerType
@staticmethod
def porter():
from nltk.stem.porter import PorterStemmer
return PorterStemmer()
... | StarcoderdataPython |
1631558 | #!/usr/bin/env python
"""
This module provides classes to create phase diagrams.
"""
from __future__ import division
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "2.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
__date__ = "Nov 25, 2012"
i... | StarcoderdataPython |
3300735 | import json
import os
mmdet_test_json = "/home/data1/yw/data/compt_data/qzb_data/HRSC_data/test.json"
mmdet_pre_json = '/home/data1/yw/data/iobjectspy_out/mmdetection/history_test_result/xf_result/qzb-hrsc.bbox.json'
out_json_path = "/home/data1/yw/data/compt_data/qzb_data/HRSC_data/merged_pre.json"
jf_add = json.loa... | StarcoderdataPython |
5243 | <filename>mypy/transformtype.py
"""Transform classes for runtime type checking."""
from typing import Undefined, List, Set, Any, cast, Tuple, Dict
from mypy.nodes import (
TypeDef, Node, FuncDef, VarDef, Block, Var, ExpressionStmt,
TypeInfo, SuperExpr, NameExpr, CallExpr, MDEF, MemberExpr, ReturnStmt,
Ass... | StarcoderdataPython |
185982 | from fastai import *
from fastai.vision import *
from fastai.torch_core import add_metrics
from fastai.callback import Callback
from batch_norm_vgg import VGG, make_layers, make_layers_BN
@dataclass
class ICS(LearnerCallback):
def __init__(self, learn: Learner, num_classes, bn):
super().__init__(learn)
... | StarcoderdataPython |
1770432 | <reponame>mottaquikarim/pydev-psets<filename>pset_challenging_ext/exercises/solutions/p20.py
"""
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
"""
"""Question 20
Level 3
Question:
Define a class with a generator which can iterate the numbers, wh... | StarcoderdataPython |
1685159 | <filename>poezio/tabs/xmltab.py
"""
The XMLTab is here for debugging purposes, it shows the incoming and
outgoing stanzas. It has a few useful functions that can filter stanzas
in order to only show the relevant ones, and it can also be frozen or
unfrozen on demand so that the relevant information is not drowned by
the... | StarcoderdataPython |
4813389 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Dataframe processing functions
"""
def determine_mode(row):
"""
Args:
row: a row in a pandas DataFrame
Returns:
Two new columns in the DataFrame, one that identifies when heat pump is heating
the other when heat pump is cooling
... | StarcoderdataPython |
4823346 | from __future__ import annotations
from dataclasses import dataclass
import hashlib
import hmac
"""Bare-bones implementation of SLIP-0021: https://github.com/satoshilabs/slips/blob/master/slip-0021.md."""
SLIP21_MASTER_NODE_KEY = b"Symmetric key seed"
@dataclass
class Slip21Node:
chain_code: bytes
key: byt... | StarcoderdataPython |
55010 | <filename>tests/node/test_node.py
from collections import namedtuple
from pytest import raises
from graphql.core import graphql
from graphql.core.type import (
GraphQLSchema,
GraphQLObjectType,
GraphQLField,
GraphQLArgument,
GraphQLList,
GraphQLNonNull,
GraphQLInt,
GraphQLString,
Gra... | StarcoderdataPython |
129480 | <filename>setup.py<gh_stars>1-10
import setuptools
# sets package info using setuptools module
setuptools.setup(
name='git-dragonfly',
version='0.1.12',
description='Bug analysis on Git repositories',
author='<NAME>, <NAME>, <NAME>',
url='https://mlaizure.github.io/dragonfly/',
packages=setupto... | StarcoderdataPython |
1602133 | <gh_stars>10-100
from .context import context
from .utils import merge_dict
class Config(dict):
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError("No such attribute: " + name)
def __setattr__(self, name, value):
self[nam... | StarcoderdataPython |
3217639 | #!/usr/bin/python3
"""podfox - podcatcher for the terminal
Usage:
podfox.py import <feed-url> [<shortname>] [-c=<path>]
podfox.py update [<shortname>] [-c=<path>]
podfox.py feeds [-c=<path>]
podfox.py episodes <shortname> [-c=<path>]
podfox.py download [<shortname> --how-many=<n>] [-c=<path>]
... | StarcoderdataPython |
1619317 | <filename>extras/gauss.py
# Naive Implementation of SUTD ISTD 2021 50.034 Introduction to Probability and Statistics Midterm Exam Final Question
# Created by <NAME> (2021)
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng()
LAMBDA = rng.uniform(0, 1)
N = 1_000_000
DATA_POINTS = 1_000_000... | StarcoderdataPython |
3394898 | <gh_stars>0
# telebot был выбран тк он более оптимален по безопасности, надежности и отзывам сообщества
import telebot
import config.config as cfg
from controller.main import main_controller
from commands.GetHelp import getHelp
print(f"token=[{cfg.TOKEN}] \nTeleBot starting\n")
bot = telebot.TeleBot(cfg.TOKEN, parse... | StarcoderdataPython |
19076 | <gh_stars>1-10
from bflib import units
from core import contexts
from core.components import Component, listing
from core.messaging import StringBuilder, Actor, Target, Verb
@listing.register
class Equipment(Component):
NAME = "equipment"
__slots__ = ["armor_restrictions", "weapon_restrictions", "weapon_size_... | StarcoderdataPython |
3353901 | <reponame>AmitMY/joeynmt
# coding: utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import argparse
import numpy as np
def read_vfiles(vfiles):
"""
Parse validation report files
:param vfiles: list of files
:return:
... | StarcoderdataPython |
4825656 | <gh_stars>1-10
from forex_python.converter import CurrencyCodes, CurrencyRates
from forex_python.bitcoin import BtcConverter
currency = CurrencyCodes()
cur_symbol = currency.get_symbol("EUR")
cur_name = currency.get_currency_name("EUR")
if __name__ == "__main__":
print(f"The currency name is: {cur_name}")
p... | StarcoderdataPython |
1766376 | from pyPdf import PdfFileWriter, PdfFileReader
import sys
import json
import os
class pdf_metadata():
page_height = 0
def load_pdf_metadata(filename):
metadata = filename + "_data/pdfbox_output/pdf_metadata.txt"
#print metadata
with open(metadata) as fn:
for line in fn:
tmp = line.split(",")
pdf_metadata... | StarcoderdataPython |
199065 | # Copyright (c) 2013 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.
# This file takes two arguments, the relative location of the shell script that
# does the checking, and the name of the sysroot.
# TODO(brettw) the bui... | StarcoderdataPython |
59230 | # 可以模拟魔方逆时针旋转的方法,一直做取出第一行的操作
# 输出并删除第一行后,再进行一次逆时针旋转
# 旋转思路
class Solution:
# matrix类型为二维列表,需要返回列表
def printMatrix(self, matrix):
result = []
while matrix:
result.extend(matrix.pop(0)) # result 是一个列表
if not matrix or not matrix[0]: # len([[]]) = 1
break
... | StarcoderdataPython |
4842726 | <reponame>hexatester/sdgs-dashboard<filename>sdgs/survey_individu/tambah/agama.py<gh_stars>0
from enum import Enum
class Agama(Enum):
ISLAM = "1"
KRISTEN = "2"
KATOLIK = "3"
HINDU = "4"
BUDHA = "5"
KHONGHUCU = "6"
LAINNYA = "other"
| StarcoderdataPython |
1628636 | <reponame>hanseungwook/tre_code<gh_stars>10-100
import json
import os
import subprocess
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from __init__ import project_root
from os.path import join as path_join
from time import sleep
from make_slurm_scripts import main as make_slurm_scripts_main
from m... | StarcoderdataPython |
186894 | <reponame>sacadena/mei<filename>featurevis/utils.py
import torch
def varargin(f):
""" Decorator to make a function able to ignore named parameters not declared in its
definition.
Arguments:
f (function): Original function.
Usage:
@varargin
def my_f(x):
... | StarcoderdataPython |
3388727 | #Could EASILY be joined with part 1, that is if i wasn't lazy
import copy
directions = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]
def checkNeighbors2(x, y):
neighbors = []
notFound = True
for d in directions:
notFound = True
i = x
j = y
while (i >= 0 and i < l... | StarcoderdataPython |
1692273 | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn import Parameter
# type: GN, BN, IN, LN
# Specifically, GN with GN GN_2 GN_4 ...
def getNormModuleND(dimension = 3, norm_type = 'GN'):
norm_ND = None
params = []
if '... | StarcoderdataPython |
4843140 | #coding=utf-8
#梦想的度假胜地P113 2017.4.17
theDreamedResort = {}
name = input("Thank you for join our survey,what's your name?\n")
theDreamedResort['name'] = name
place = input("What's your dream resort?\n")
theDreamedResort['place'] = place
reason = input("So,what's your reason?\n")
theDreamedResort['reason'] = reason
print... | StarcoderdataPython |
1694067 | <filename>examples/Q-size/main.py<gh_stars>0
'''
*
* Copyright (C) 2020 Universitat Politècnica de Catalunya.
*
* 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.apach... | StarcoderdataPython |
1770761 | <gh_stars>0
from nimblenet.activation_functions import sigmoid_function
from nimblenet.cost_functions import *
from nimblenet.learning_algorithms import *
from nimblenet.neuralnet import NeuralNet
from nimblenet.preprocessing import construct_preprocessor, standarize
from nimblenet.data_structures import Instance
from ... | StarcoderdataPython |
3215266 | <gh_stars>1-10
# coding: utf-8
"""
CardPay REST API
Welcome to the CardPay REST API. The CardPay API uses HTTP verbs and a [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) resources endpoint structure (see more info about REST). Request and response payloads are formatted as JSON. Merchan... | StarcoderdataPython |
1737244 | <filename>code/utils/data.py
"""
Created on Sun Mar 3 21:42:16 2019
@author: <NAME>
"""
import os
import sys
import gdal
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import matplotlib... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.