id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
105407 | <reponame>daraymonsta/daily-do
'''
WRITTEN BY <NAME>
PURPOSE
Two strings are anagrams if you can make one from the other
by rearranging the letters. The function named is_anagram takes
two strings as its parameters, returning True if the strings are
anagrams and False otherwise.
EXAMPLE
The call i... | StarcoderdataPython |
242803 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 15:48:50 2020
@author: <NAME>
Purpose Reads weight values from the weights file
"""
import struct
import numpy as np
byte_order = 'little'
size_float = 8
file = open("weights.bin","rb")
#Read in metadata
pixals_in_image = int.from_bytes(file.read(4),byte_order)... | StarcoderdataPython |
6686454 | """CNNs for testing/experiments."""
import torch
import torch.nn as nn
from backpack.core.layers import Flatten
from deepobs.pytorch.testproblems import testproblems_modules
def cifar10_c4d3(conv_activation=nn.ReLU, dense_activation=nn.ReLU):
"""CNN for CIFAR-10 dataset with 4 convolutional and 3 fc layers.
... | StarcoderdataPython |
1664540 | # Generated by Django 3.0.9 on 2020-08-18 10:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shopping', '0019_auto_20200817_2046'),
]
operations = [
migrations.RemoveField(
model_name='cartproduct',
name='store',
... | StarcoderdataPython |
230706 | <filename>7kyu/greatest_common_divisor.py
# http://www.codewars.com/kata/5500d54c2ebe0a8e8a0003fd/
def mygcd(x, y):
remainder = max(x, y) % min(x, y)
if remainder == 0:
return min(x, y)
else:
return mygcd(min(x, y), remainder)
| StarcoderdataPython |
3423831 | # Copyright 2015 Red Hat 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... | StarcoderdataPython |
6590743 | <gh_stars>0
# Project Quex (http://quex.sourceforge.net); License: MIT;
# (C) 2005-2020 <NAME>;
#_______________________________________________________________________________
from quex.input.code.base import CodeFragment, CodeFragment_NULL
from quex.engine.analyzer.door_id_address_label imp... | StarcoderdataPython |
1792745 | class Sensor(object):
"""
Dummy sensor object
"""
def __init__(self):
pass
def read_data(self):
pass
def adjust_polling_rate(self):
pass | StarcoderdataPython |
3225906 | """Black format your Jupyter Notebook and JupyterLab.
Usage:
------
Format one Jupyter file:
$ jblack notebook.ipynb
Format multiple Jupyter files:
$ jblack notebook_1.ipynb notebook_2.ipynb [...]
Format a directory:
$ jblack python/
Format one Jupyter file with a line length of 70:
$ jblack -l... | StarcoderdataPython |
8059576 | <reponame>ConsultingMD/covid-data-public
import enum
import pathlib
import pandas as pd
import datetime
import dateutil.parser
import pydantic
import structlog
from covidactnow.datapublic import common_fields
from covidactnow.datapublic.common_fields import CommonFields
from covidactnow.datapublic import common_init
D... | StarcoderdataPython |
83853 | <filename>pyexfil/Comm/DNSoTLS/constants.py
import os
DNS_OVER_TLS_PORT = 853
CHUNK_SIZE = 128
CHECK_CERT = True # We recommend using valid certificates. An invalid certificate (self-signed) might trigger alerts on some systems.
LOCAL_HOST = 'localhost'
MAX_BUFFER = 4096
MAX_CLIEN... | StarcoderdataPython |
3354678 | <reponame>vestial/vision-video-analyzer
from main.utils.feedback.shot.shot_recommendation import get_shot_recommendation
from main.utils.histogram_analyzer import get_exposure_histogram
from main.utils.shots_analyzer import get_background, get_contrast, get_shot_screenshot, get_shots, get_shots_length
from celery impor... | StarcoderdataPython |
3237723 | #!/usr/bin/python
"""
Retrieves and collects data from the the NetApp E-series web server
and sends the data to an influxdb server
"""
import struct
import time
import logging
import socket
import argparse
import concurrent.futures
import requests
import json
import hashlib
from datetime import datetime
from datetime ... | StarcoderdataPython |
3575460 | velocidade = float(input("Qual é a velocidade atual do carro? "))
limite_permitido = 80
if velocidade > limite_permitido:
multa = (velocidade - 80) * 7
print(f"MULTADO! Você excedeu o limite permitido que é de 80Km/h\nVocê deve pagar uma multa de R${multa:.2f}!")
print("Tenha um bom dia! Dirija com seguran... | StarcoderdataPython |
4916350 | from typing import Any
from fugue.dataframe import DataFrame, DataFrames, LocalDataFrame, ArrayDataFrame
from fugue.extensions.context import ExtensionContext
from fugue.extensions.transformer.constants import OUTPUT_TRANSFORMER_DUMMY_SCHEMA
class Transformer(ExtensionContext):
"""The interface to process logica... | StarcoderdataPython |
5007576 | <filename>laymon/observers.py
from .interfaces import Observer, ObserverFactory
from .displays import FeatureMapDisplay
class FeatureMapObserver(Observer):
"""
An class used to create observers that are used to monitor the feature maps of the given layer.
"""
def __init__(self, layer, layer_name, upd... | StarcoderdataPython |
1951743 | import yfinance as yf
import util
# @param ticker_symbol - str
# @param time_period - Valid Periods: 1d, 5d, 1mo,3mo,6mo,1y,2y,5y,10y,ytd,maxi
# @param time_interval - Valid Periods:`1m , 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo
def get_historical_data(ticker_symbol: str, time_period: str, time_interval... | StarcoderdataPython |
5000861 | from app.config import gunicorn_settings
from app.logging import log_config
# Gunicorn config variables
accesslog = gunicorn_settings.ACCESS_LOG
bind = f"{gunicorn_settings.HOST}:{gunicorn_settings.PORT}"
errorlog = gunicorn_settings.ERROR_LOG
keepalive = gunicorn_settings.KEEPALIVE
logconfig_dict = log_config.dict(ex... | StarcoderdataPython |
1617400 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Sample script to print a simple list of all the nodes registered with the controller.
Output format: ``app_name,tier_name,node_name,host_name``
"""
from __future__ import print_function
from appd.cmdline import parse_argv
from appd.request import AppDynamicsClient
... | StarcoderdataPython |
3328291 | <reponame>duarteocarmo/CervicalCancer<gh_stars>1-10
from Project_Clean_data import raw
from Project_Clean_data import header
from matplotlib.pyplot import boxplot, xticks, ylabel, title, show
import numpy as np
from textwrap import wrap
# find integer columns
integer = []
for column in range(raw.shape[1]):
if np.... | StarcoderdataPython |
145272 | <gh_stars>0
from typing import Iterator, List, Optional
from django.db import models
from ufdl.annotation_utils.image_segmentation import annotations_iterator
from ufdl.core_app.exceptions import BadArgumentValue
from ufdl.core_app.models import Dataset, DatasetQuerySet
from ufdl.core_app.models.files import File
f... | StarcoderdataPython |
3593839 | <reponame>CatTiger/vnpy<filename>venv/lib/python3.7/site-packages/tigeropen/quote/response/quote_brief_response.py
# -*- coding: utf-8 -*-
"""
Created on 2018/10/31
@author: gaoan
"""
import json
import six
from tigeropen.common.consts import TradingSession
from tigeropen.common.util.string_utils import get_string
fr... | StarcoderdataPython |
1787472 | ind0 = '' #master string
lis0 = [''] #paritioning substrings
lis00 = [] #master matrix of indices of lis0 alongside length of partitioned strings
counter = 0
for i in range(len(s)-1):
ind1 = ' ' #inner string
if (ord(s[i]) <= ord(s[i+1])):
ind1 = s[i]
lis0[counter] += s[i]
else:
lis0... | StarcoderdataPython |
9760579 | <reponame>somnus0208/tinyftp
import socket
import os
import argparse
import struct
import tls
import sys
class ArgumentParserError(Exception): pass
class ThrowingArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ArgumentParserError(message)
def exit(self, status=0, message=None... | StarcoderdataPython |
1667587 | import pytest
from lunavl.sdk.errors.errors import LunaVLError
from lunavl.sdk.errors.exceptions import LunaSDKException
from lunavl.sdk.faceengine.setting_provider import DetectorType
from lunavl.sdk.image_utils.image import VLImage
from tests.base import BaseTestClass
from tests.resources import ONE_FACE
class Tes... | StarcoderdataPython |
4894470 | #!/usr/bin/python
import time
def fib(n):
return 1 if n <= 2 else fib(n-1) + fib(n-2)
cnt = 0
print 'Calculating Fib(40)...'
while 1:
t = time.time()
fib(40)
cnt += 1
print 'Iteration', cnt, ':', time.time()-t, 'Seconds'
| StarcoderdataPython |
1813417 | <filename>ocr_joplin_notes/cli.py
# -*- coding: utf-8 -*-
"""Console script for ocr_joplin_notes."""
import sys
import click
from .ocr_joplin_notes import (
set_language,
set_autorotation,
set_mode,
run_mode, set_add_previews,
)
from . import __version__
def parse_argument(arg):
"""Helper functio... | StarcoderdataPython |
5173086 | <filename>experiments/testing_env/models/ppo_entropy/model/src/model_ppo.py<gh_stars>0
import torch
import torch.nn as nn
class Model(torch.nn.Module):
def __init__(self, input_shape, outputs_count):
super(Model, self).__init__()
self.device = "cpu"
hidden_size = 64
self.... | StarcoderdataPython |
3341258 | <reponame>kupc25648/RL-Structure
'''
==================================================================
Frame structure environemnt file
This file contains environment for train agent using reinforcement learning
ENV : contains Game class
Game1 : REDUCE TOTAL SURFACE for Q-Learning , Double Q-Learning and Ac... | StarcoderdataPython |
8016299 | <filename>config.py
# Device id can be obtained by calling MCP_GetDeviceId on the Wii U
# Serial number can be found on the back of the Wii U
DEVICE_ID = 1234567890
SERIAL_NUMBER = "..."
SYSTEM_VERSION = 0x220
REGION = 4 #EUR
COUNTRY = "NL"
USERNAME = "..." #Nintendo network id
PASSWORD = "..." #Nintendo network passw... | StarcoderdataPython |
6558300 | """
@author: <NAME>, and Conte
"""
import numpy as np
import scipy.stats as stats
class Uniform:
# Method with in this uniform class
def __init__(self, lower, upper): # method recieves instance as first argument automatically
# the below are the instance variables
self.lower = lower
... | StarcoderdataPython |
3300006 | from state import State
from info import Info
from math import pi
import numpy as np
class Choose(State):
def __init__(self, name):
super().__init__(name)
self.itemsPos = [
(26, 16),
(26, 28),
(26, 41),
(26, 53)
]
se... | StarcoderdataPython |
3371420 | import argparse
import bioc
import json
import itertools
from collections import defaultdict,Counter
def getID_FromLongestTerm(text, lookupDict):
"""
Given a span of text, this method will tokenize and then identify the set of entities that exist in the text. It will prioritise long terms first in order to reduce am... | StarcoderdataPython |
6647184 | <filename>scripts/get_vocab.py<gh_stars>10-100
import argparse
import functools
import itertools
import sys
from collections import Counter
from multiprocessing import Pool
def count(lines):
voc = Counter()
for l in lines:
voc.update(l.split())
return voc
def group(lines, group):
groups = []... | StarcoderdataPython |
1957539 | from gensim.models import word2vec
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from sklearn.metrics import accuracy_score, f1_score
from sklearn.metrics import classification_report
from sklearn.externals import joblib
import numpy as np
import pandas as pd
np.s... | StarcoderdataPython |
6531836 | from __future__ import absolute_import
from setuptools import setup
setup(
name='BoardServer',
version='0.1dev',
author='<NAME>',
author_email='<EMAIL>',
packages=['boardserver'],
scripts=['bin/board-serve.py'],
entry_points={'jrb_board.games': []},
install_requires=['gevent', 'six'],
... | StarcoderdataPython |
3254156 | <filename>episodes/v1.1/src/rounding_property_test.py
from rounding import percentages
from hypothesis import given, settings, note
from rounding.test_helpers import portfolios
def noround(portfolio):
return {
k: round(v / sum(portfolio.values()) * 100, 4) for k, v in portfolio.items()
}
examples =... | StarcoderdataPython |
5072915 | <reponame>videoflow/videoflow-contrib
import os
from collections import defaultdict
from os import path as osp
import numpy as np
import torch
from scipy.interpolate import interp1d
def bbox_overlaps(boxes, query_boxes):
"""
Parameters
----------
- boxes: (N, 4) ndarray or tensor or variable
- qu... | StarcoderdataPython |
4889643 | <reponame>kmshin1397/ETSimulations
class ParticleSet:
"""Represents a set of particles of the same kind within a TEM-Simulator run.
This class directly corresponds to the particleset segments defined within a configuration file
for the TEM-Simulator software.
Attributes:
name: The name of the ... | StarcoderdataPython |
3243289 | import unittest
#from extracttext import ExtractText
class Test_getTextFromUrl(unittest.TestCase):
""" extractText = ExtractText()
def test_ret_type(self):
textFromUrl = self.extractText.getTextFromUrl(
'https://sara-sabr.github.io/ITStrategy/home.html')
assert isi... | StarcoderdataPython |
177063 | <reponame>musyoku/chainer-gqn-playground<filename>gqn/mathematics.py
import math
def yaw(eye, center):
eye_x, eye_z = eye[0], eye[2]
center_x, center_z = center[0], center[2]
eye_direction = (center_x - eye_x, center_z - eye_z)
frontward_direction = (0, 1)
norm_eye = math.sqrt(eye_direction[0] * e... | StarcoderdataPython |
1728801 | from typing import List
class ShellSort:
def sort(self, items: List) -> None:
size = len(items)
h = 1
while h < size / 3:
h = 3 * h + 1
while h >= 1:
for i in range(h, size):
j = i
while j >= h and items[j] < items[j-h]:
... | StarcoderdataPython |
8063589 | <filename>mycfo/discussion_forum/page/discussion_forum/discussion_forum.py
from __future__ import unicode_literals
import frappe
from frappe.utils import cint
from frappe.website.render import resolve_path
from frappe import _
from frappe.website.render import clear_cache
from frappe.utils import today, cint, global_d... | StarcoderdataPython |
5106953 | """
Test cases for the Comparisons class over the Chart elements
"""
import numpy as np
from holoviews import Dimension, Curve, Bars, Histogram, Scatter, Points, VectorField
from holoviews.element.comparison import ComparisonTestCase
class CurveComparisonTest(ComparisonTestCase):
def setUp(self):
"Varia... | StarcoderdataPython |
9610651 | '''
This file is part of Semantic SLAM
License: MIT
Author: <NAME>
Email: <EMAIL>
Web: https://1989Ryan.github.io/
'''
from pspnet import *
from std_msgs.msg import String
from sensor_msgs.msg import Image
from map_generator.msg import frame
from cv_bridge import CvBridge
import numpy as np
import tensorflow as tf
imp... | StarcoderdataPython |
11388837 | <filename>skforecast/ForecasterAutoregCustom/tests/test_predict_interval.py
import numpy as np
import pandas as pd
from skforecast.ForecasterAutoregCustom import ForecasterAutoregCustom
from sklearn.linear_model import LinearRegression
def create_predictors(y):
'''
Create first 5 lags of a time series.
'... | StarcoderdataPython |
5193536 | from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/echo', methods=['POST'])
def echo():
body = request.get_json()
return jsonify(body), 200
@app.route('/', methods=['GET'])
def get():
return 'Hellow get method', 200
| StarcoderdataPython |
6552326 | import random as r
from random import randint
import numpy as np
class Structures: # This class generates stochatic initial, transition, and observation matrices used in model.py
# columnxrows
N = 2
M = 3
A = [[0] * N] * N
B = [[0] * M] * N
pi = [[0] * N]
# Scales for randomizing sto... | StarcoderdataPython |
98243 | import minstrel.db
import minstrel.tracks
class TrackStorage():
def __init__(self, name, track_locations, uuid, created=None, deleted=None, updated=None):
self.created = created
self.name = name
self.track_locations = track_locations
self.updated = updated... | StarcoderdataPython |
8123211 | <reponame>ParikhKadam/pyrwr<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from utils import iterator
from .pyrwr import PyRWR
class PageRank(PyRWR):
def __init__(self):
pass
def compute(self, c=0.15, epsilon=1e-6, max_iters=100,
handles_deadend=True... | StarcoderdataPython |
9628190 | <reponame>shouxian92/sqlite-diff-tool
#! Python 3.7
import sqlite3
import os
from datetime import datetime
from sqlite3 import Error
DEBUG = False
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return:... | StarcoderdataPython |
1726947 | <filename>mtdynamics/simulation_parameters.py
## Dictionary to store all parameters
simParameters = {}
## Simulation type choices
simParameters['record_data'] = True
simParameters['record_data_full'] = False
simParameters['plot_figures'] = True
simParameters['compare_results'] = False
simParameters['end_hydrolysis'] =... | StarcoderdataPython |
9618757 | from create_permutation_gif import animate_permutations
if __name__=='__main__':
permutations = [
[2, 3, 4, 1, 0],
]
imgs = animate_permutations(permutations, ["red", "blue", "yellow", "green", "purple"], ["1", "2", "3", "4", "5"], (500, 250), 30, 50, 20)
imgs[0].save('examples/example_1.gif', save_all=Tru... | StarcoderdataPython |
9777696 | <filename>WEKO3AutoTest/03/Autotest03_091.py
__file__
import pytest
import configparser
from playwright.sync_api import sync_playwright
from os import path
config_ini = configparser.ConfigParser()
config_ini.read( "conf.ini", encoding = "utf-8" )
print("SET_TIMEOUT = " + config_ini['DEFAULT']['SETTIMEOUT'])
print("SET... | StarcoderdataPython |
3318012 | <reponame>aliyun/dingtalk-sdk
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.core import TeaCore
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util.client import Client as ... | StarcoderdataPython |
11254579 | import pytest
from genalog.text import preprocess
from genalog.text.alignment import GAP_CHAR
@pytest.mark.parametrize(
"token, replacement, desired_output",
[
("", "_", ""), # Do nothing to empty string
(" ", "_", " "), # Do nothing to whitespaces
(" \n\t", "_", " \n\t"),
(... | StarcoderdataPython |
3475126 | <gh_stars>1-10
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def focal_loss(input_values, gamma):
"""Computes the focal loss"""
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return loss.mean()
class FocalLoss(nn.Module):
def... | StarcoderdataPython |
3318733 | <gh_stars>0
# Generated by Django 3.1.2 on 2020-10-22 12:14
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('board', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='commen... | StarcoderdataPython |
1971800 | import sys
import warnings
import importlib
import pythoncom
from importlib.abc import MetaPathFinder, Loader
from importlib.machinery import ModuleSpec
class PyWinAutoFinder(MetaPathFinder):
def find_spec(self, fullname, path, target=None): # pylint: disable=unused-argument
if fullname == 'pywinauto':
... | StarcoderdataPython |
93831 | import random
import numpy as np
def read_data(pairs_file):
with open(pairs_file, 'r') as file:
tcrs = set()
peps = set()
all_pairs = []
for line in file:
tcr, pep, cd = line.strip().split('\t')
# print(tcr, pep)
# Proper tcr and peptides
... | StarcoderdataPython |
336769 | """
Test only that the wrapper behaves nicely in all cases.
Injection itself is tested through inject.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import pytest
from antidote import world
from antidote._internal.utils import Default
from antidote._internal.w... | StarcoderdataPython |
6684376 | from keras.utils import to_categorical
from keras.preprocessing import sequence
from mxnet import gluon
from sklearn.model_selection import train_test_split
from keras.models import Model, load_model
from keras.layers import Conv1D, GlobalMaxPooling1D, Dropout, Dense, Input, Embedding, MaxPooling1D, Flatten
from keras.... | StarcoderdataPython |
3376036 | '''
Created on May 22, 2015
@author: hsorby
'''
ELEMENT_OUTLINE_GRAPHIC_NAME = 'element_outline'
IMAGE_PLANE_GRAPHIC_NAME = 'image_plane'
| StarcoderdataPython |
1698290 | # -*- coding: utf-8 -*-
import hubblestack.modules.reg as reg
import hubblestack.utils.win_reg
from hubblestack.exceptions import CommandExecutionError
from tests.support.helpers import random_string
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.suppo... | StarcoderdataPython |
3566512 | <reponame>elyase/polyaxon
from sanic import Sanic
from streams.resources.builds import build_logs
from streams.resources.experiment_jobs import experiment_job_logs, experiment_job_resources
from streams.resources.experiments import experiment_logs, experiment_resources
from streams.resources.health import health
from ... | StarcoderdataPython |
242842 | from django.shortcuts import render, get_object_or_404, redirect
from .models import Products
from .forms import ProductForm
# Create your views here.
def dynamic_lookup_view(request, product_id):
try:
obj = get_object_or_404(Products, id = product_id)
except Products.DoesNotExist:
raise Http4... | StarcoderdataPython |
11339396 | from django.apps import AppConfig
class StarterkitConfig(AppConfig):
name = 'starterkit'
| StarcoderdataPython |
3237329 | # uncompyle6 version 3.3.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\pushbase\track_frozen_mode.py
# Compiled at: 2018-11-30 15:48:12
from... | StarcoderdataPython |
1927170 | def fun_callback(input, extend_input):
print('fun_callback sum :',input)
print('fun_callback extend_input :', extend_input)
return
def fun_call(one, two, f_callback,three):
result = one + two
f_callback(result, three)
return
first = 10
second = 20
third = 30
fun_call(first, second, fun_callbac... | StarcoderdataPython |
213019 | <gh_stars>0
"""Useful functions for the Singularity containers
TODO:
- [x] figure out how to mount in other file-systems
-B dir1,dir2
Put to release notes:
`conda install -c bioconda singularity`
OR
`conda install -c conda-forge singularity`
"""
from __future__ import absolute_import
from __future__ import print... | StarcoderdataPython |
1779957 | <filename>notebooks/icos_jupyter_notebooks/station_characterization/gui.py
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 08:38:51 2020
@author: <NAME>
"""
from ipywidgets import Dropdown, SelectMultiple, FileUpload, HBox, Text, VBox, Button, Output, IntText, RadioButtons,IntProgress, GridspecLayout
from IPython.c... | StarcoderdataPython |
9708467 | import os
from flask import Flask, current_app, send_file, redirect, url_for, json
from flask_dance.contrib.twitter import make_twitter_blueprint
from flask_cors import CORS
from werkzeug.contrib.fixers import ProxyFix
from flask_restful import Api as API
from flask_cors import CORS
from routes import route_dict
from r... | StarcoderdataPython |
99226 | import os, subprocess
from itertools import chain
from os.path import join
import pandas as pd
from Modules.Utils import run, make_dir
class FileManager:
"""Project non-specific class for handling local and cloud storage."""
def __init__(self, training=False):
"""create an empty local_paths variable ... | StarcoderdataPython |
1608323 | <reponame>Tshimanga/pytorch-lightning<filename>pl_examples/domain_templates/computer_vision_fine_tuning.py
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License... | StarcoderdataPython |
5013316 | from argparse import ArgumentParser
import numpy as np
import torch
import imageio
from PIL import Image
import torchvision.transforms as transforms
from tqdm.auto import trange
from utils import to_image, image_to_tensor
from model import NeuralStyle
from utils import Params
CONTENT_LAYERS = ["conv_4"]
STYLE_LAYERS ... | StarcoderdataPython |
1778040 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 20:49:22 2019
MIT License
Copyright (c) 2019 <NAME> <EMAIL>
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 witho... | StarcoderdataPython |
4948817 | <gh_stars>0
from .app import Webserver
if __name__ == '__main__':
Webserver.run()
| StarcoderdataPython |
6593824 | <reponame>DeanBiton/Beyond-07-team-4
def test_check_pytest():
assert True
| StarcoderdataPython |
8190764 | import requests
# traer la funcion html para convertir html a un archivo para aplicar xpath
import lxml.html as html
# Crear carpeta con fecha de hoy
import os
# Traer la fecha actual
import datetime
HOME_URL = 'https://www.larepublica.co/'
XPATH_LINK_TO_ARTICLE = '//div[@class="V_Trends"]/h2/a/@href'
XPATH_TITLE = '... | StarcoderdataPython |
1784005 | <reponame>profjsb/PyAdder
import unittest
import doctest
import sys
def additional_tests():
import bson
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(bson))
return suite
def all_tests_suite():
def get_suite():
return additional_tests(
unittest.TestLoader().lo... | StarcoderdataPython |
4939421 | # -*- coding: utf-8 -*-
import unittest
import parser
import time, datetime
import pdb
class ParserTest(unittest.TestCase):
def setUp(self):
self.t = time.time()
self.date = datetime.datetime.fromtimestamp(self.t)
self.parser = parser.Parser(self.t)
pass
def tearDown(self):
... | StarcoderdataPython |
4800670 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Rules for validating whether a conversational Finnish word
# can be a reduced form of a standard Finnish word.
def is_uoa(ch):
return ch in ("u", "o", "a")
def is_ie(ch):
return ch in ("i", "e")
def is_yoa(ch):
return ch in ("y", "ö", "ä")
def is_vowel(ch):
ret... | StarcoderdataPython |
11301984 | import math
import functorch._src.decompositions
import torch
from torch._decomp import get_decompositions
from torchinductor import config
aten = torch.ops.aten
decompositions = get_decompositions(
[
aten.clamp_max,
aten.clamp_min,
aten.cudnn_batch_norm,
aten.hardsigmoid,
... | StarcoderdataPython |
3583633 | <filename>anpylar/app_module.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright 2018 The AnPyLar Team. All Rights Reserved.
# Use of this source code is governed by an MIT-style license that
# can... | StarcoderdataPython |
100431 | import copy
import echidna
import echidna.output.plot as plot
import echidna.core.spectra as spectra
from echidna.output import store
import matplotlib.pyplot as plt
import argparse
import glob
import numpy as np
import os
def convertor(path):
flist=np.array(glob.glob(path))
for ntuple in flist:
os.sy... | StarcoderdataPython |
1874214 | import collections
import dataclasses as dc
import operator
from datetime import date, datetime
from functools import reduce, partial
from typing import Type as PyType, Dict, Any, Union, Callable, Sequence, Optional
import statey as st
from statey.syms import types, utils, impl
# Default Plugin definitions
@dc.datac... | StarcoderdataPython |
369185 | import tensorflow as tf
class TacotronPostnet(tf.keras.layers.Layer):
"""Tacotron-2 postnet."""
def __init__(self, config, **kwargs):
"""Init variables."""
super().__init__(**kwargs)
self.conv_batch_norm = []
for i in range(config.n_conv_postnet):
conv = tf.keras.lay... | StarcoderdataPython |
37324 | <reponame>oclyke-dev/blue-heron
import blue_heron
import pytest
from pathlib import Path
from lxml import etree as ET
from blue_heron import Root, Drawing
@pytest.fixture(scope='module')
def test_board():
with open(Path(__file__).parent/'data/ArtemisDevKit.brd', 'r') as f:
root = ET.parse(f).getroot()
yield ... | StarcoderdataPython |
3356748 | from functools import partial
import numpy as np
import nifty
import nifty.graph.opt.multicut as nmc
from .blockwise_mc_impl import blockwise_mc_impl
#
# cost functionality
#
def _weight_edges(costs, edge_sizes, weighting_exponent):
w = edge_sizes / float(edge_sizes.max())
if weighting_exponent != 1.:
... | StarcoderdataPython |
9750604 | import unittest
import pipgh
class TestInstall(unittest.TestCase):
def test_cli_fail(self):
# install ( (<full_name> [ref]) | (-r <requirements.txt>) )'
argvs = [
['instal'],
['install'],
['instal', 'docopt/docopt'],
['install', '-r'],
... | StarcoderdataPython |
3426991 | #SCS_class_creator_for_initialization_configuration_sate_validation_and_data_adquisition
from SocketExecutor import SocketExecutor
class K4200:
print "U R in class K4200" #flag 4 debug
#Relate a IP address to the SCS
def __init__(self, ip, port=2099):
print "U R in K4200 - __init__" #flag ... | StarcoderdataPython |
3324887 | <reponame>jnthn/intellij-community
import nspackage.a<caret> | StarcoderdataPython |
1755430 | # get string input
Total_bill =int(raw_input("Enter the total amont: "))
# get integer input: int() convert string to integer
# float() convert string to floating number
tip_rate = float(raw_input("Enter tip rate (such as .15): "))
tip=(Total_bill*tip_rate)
total=int(Total_bill+tip)
# use string formatting to outpu... | StarcoderdataPython |
333258 | from __future__ import annotations
from datetime import datetime
from typing import Any, Mapping, Optional, Sequence, Union
from dataclasses import dataclass
from snuba.datasets.cdc.cdcprocessors import (
CdcProcessor,
CdcMessageRow,
postgres_date_to_clickhouse,
parse_postgres_datetime,
)
from snuba.w... | StarcoderdataPython |
3261436 | from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth import login, logout, authenticate
from .forms import NewPostForm
from django.contrib.auth.decorators import login_required
f... | StarcoderdataPython |
3247652 | <filename>tests/test_help.py
import subprocess
import sys
import pytest
from openpifpaf import __version__
PYTHON = 'python3' if sys.platform != 'win32' else 'python'
MODULE_NAMES = [
'predict',
'train',
'logs',
'eval',
'export_onnx',
'migrate',
'count_ops',
'benchmark',
]
if sys... | StarcoderdataPython |
11336650 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from sqlalchemy import Integer, DateTime, String
from sqlalchemy import Column, MetaData, Table, ForeignKey
ENGINE = 'InnoDB'
CHARSET = 'utf8'
def upgrade(migrate_engine):
"""
... | StarcoderdataPython |
3537790 | <reponame>gtfarng/Odoo_migrade
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import dateutil
import logging
import time
from collections import defaultdict
from odoo import api, fields, models, SUPERUSER_ID, tools, _
from odoo.exceptions import Acce... | StarcoderdataPython |
4891199 | import os
import sys
from alize.exception import *
from blue.utility import *
from blue.utility import LOG as L
from blue.script import testcase_base
class TestCase_Slack(testcase_base.TestCase_Unit):
def slack_message(self, message, channel=None):
if channel == None: channel = self.get("slack.channel"... | StarcoderdataPython |
4819382 | print(21 + 43)
print(142 - 52)
print(10 * 342)
print (5 ** 2) | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.