id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3347941 | import cv2
import numpy as np
path = "./underexposed.jpg"
def _mask(img):
img = cv2.bitwise_not(img)
mask = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blured_img = cv2.GaussianBlur(mask, (15, 15), cv2.BORDER_DEFAULT)
return blured_img
def _local_contrast_correction(img, mask):
exponent = np.repeat((... | StarcoderdataPython |
3256315 | import itertools
from functools import partial
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
# --- Preliminaries ---
# - Partitioning techniques -
class BestSolutionHolder:
"""
Keeps in memory the best solution of a partitioning technique,
is used in the function below.
... | StarcoderdataPython |
33445 | <reponame>dargueta/binobj<gh_stars>1-10
"""Tests for the variable-length integers."""
import io
import pytest
from binobj import varints
@pytest.mark.parametrize(
"value,expected",
((0, b"\0"), (127, b"\x7f"), (128, b"\x81\x00"), (65535, b"\x83\xff\x7f")),
)
def test_encode_vlq_basic(value, expected):
... | StarcoderdataPython |
44473 | <reponame>d3F0g/ESD-G7T1
import os
from twilio.rest import Client
account_sid = 'AC<KEY>'
auth_token = '<PASSWORD>'
client = Client(account_sid, auth_token)
message = client.messages \
.create(
body='This is the ship that made the Kessel Run in fourteen parsecs?',
from_='+15017122661',
... | StarcoderdataPython |
6175 | <reponame>rmhsawyer/EC601-Final-Project-Mapping_User_Face_To_Emoji
#draw the predictions from real-time.py
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data ... | StarcoderdataPython |
1664569 | import numpy as np
from numpy import ndarray
from notebooks.thresholders import BaseThresholder
class SimpleThresholder(BaseThresholder):
"""
Tests each observation for the best cutoff point and then picks the median of that
observation and the one before it.
"""
def __init__(self, score_func):
... | StarcoderdataPython |
3208281 | from dotmailer import Base
class SurveyField(Base):
pass
| StarcoderdataPython |
1743453 | <reponame>zhsj/teuthology<gh_stars>1-10
import contextlib
import sys
import logging
import time
import itertools
from .config import config
from .exceptions import MaxWhileTries
log = logging.getLogger(__name__)
@contextlib.contextmanager
def nested(*managers):
"""
Like contextlib.nested but takes callables ... | StarcoderdataPython |
1636819 | <filename>casinotools/fileformat/casino2/File.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: casinotools.fileformat.casino2.File
.. moduleauthor:: <NAME> <<EMAIL>>
CASINO file structure: either sim or .cas.
"""
###############################################################... | StarcoderdataPython |
1742896 | #!/usr/bin/env python
# Copyright 2017 Calico LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | StarcoderdataPython |
70385 | # coding=utf-8
import numpy as np
import torch
from torch.utils.data import Dataset
from allennlp.data import Vocabulary
from updown.config import Config
from updown.data.readers import CocoCaptionsReader
from updown.utils.constraints import ConstraintFilter, FiniteStateMachineBuilder
from collections import Counte... | StarcoderdataPython |
3240569 | <reponame>AkiaCode/discodo
import asyncio
import logging
import re
import socket
import struct
import threading
import uuid
from websockets.exceptions import ConnectionClosed
from .config import Config
from .gateway import VoiceSocket
from .natives import Encrypter, opus
log = logging.getLogger("discodo.VoiceConnect... | StarcoderdataPython |
1616967 | <gh_stars>10-100
from __future__ import print_function, absolute_import, division
import yamlreader
import boto3
import logging
import yaml
from monocyte import Monocyte
def read_config(path):
return {} if path is None else yamlreader.yaml_load(path)
def get_config_path_from_args(args):
return args["--confi... | StarcoderdataPython |
4823960 | <filename>tensorflow_gan/examples/cyclegan/generator_test.py
# coding=utf-8
# Copyright 2020 The TensorFlow GAN Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... | StarcoderdataPython |
24683 | import pyHook
from threading import Timer
import win32gui
import logging
class blockInput():
def OnKeyboardEvent(self,event):
return False
def OnMouseEvent(self,event):
return False
def unblock(self):
logging.info(" -- Unblock!")
if self.t.is_alive():
... | StarcoderdataPython |
116449 | <reponame>DavoGrant/ExoTiC-MIRI
import unittest
import numpy as np
from jwst import datamodels
from exotic_miri import DropIntegrationsStep
class TestDropIntegrations(unittest.TestCase):
""" Test drop integrations step. """
def __init__(self, *args, **kwargs):
super(TestDropIntegrations, self).__ini... | StarcoderdataPython |
3299719 | from .asserts import BY_O, BY_C, BY_T
import re
from qtpp.libs.framework import libs
class OutPutParam:
'''
输出参数
'''
def get_output_variable_value(param_type, var_name, response, exp, match=0):
'''
获取出参变量,并返回list
Args:
param_type 出参类型
BODY_TEXT = 0
... | StarcoderdataPython |
37749 | <reponame>jacopotagliabue/paas-data-ingestion
import pulumi
import pulumi_aws as aws
import pulumi_snowflake as snowflake
from my_snowflake_roles import MySnowflakeRoles
from my_snowflake_snowpipe import MySnowpipe
from my_lambda import MyLambda
PROJECT_NAME = pulumi.get_project()
STACK_NAME = pulumi.get_stack()
PRE... | StarcoderdataPython |
1750982 | from twilio.twiml.voice_response import Dial, VoiceResponse, Sip
response = VoiceResponse()
dial = Dial(
record='record-from-answer',
timeout=10,
hangup_on_star=True,
caller_id='bob',
method='POST',
action='/handle_post_dial'
)
dial.sip(
'sip:<EMAIL>?customheader=foo',
method='POST',
... | StarcoderdataPython |
1680802 | <gh_stars>1-10
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import time
import argparse
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dst
from lambda_mobilenetv1 import g... | StarcoderdataPython |
6634 | from requests import get
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import datetime as dt
from bme280 import BME280
try:
from smbus2 import SMBus
except ImportError:
from smbus import SMBus
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys =[]
bus = SMBus(1)
bme280 = ... | StarcoderdataPython |
1727668 | from typing import Any, Dict, List
import torch.nn as nn
from ._utils import INTERNAL_ERROR_MESSAGE
from .nn import CatEmbeddings, CLSEmbedding, LinearEmbeddings
def default_no_weight_decay_condition(
module_name: str,
module: nn.Module,
parameter_name: str,
parameter: nn.Parameter,
) -> bool:
d... | StarcoderdataPython |
1736911 | # Units based LAMMPS unit styles (http://lammps.sandia.gov/doc/units.html)
units_style = {
"lj": {},
"real": {
"[mass]": "(gram mol ** -1)",
"[length]": "angstrom",
"[time]": "femtosecond",
"[energy]": "(kcal mol ** -1)",
"[velocity]": "(angstrom femtosecond ** -1)",
... | StarcoderdataPython |
3282766 | <filename>2015/day_06/solution_p1.py
#!/usr/bin/env python
"""
This code holds the solution for part 1 of day 6 of the Advent of Code for 2015.
"""
import hashlib
import sys
def create_light_grid(default_value):
grid = [[default_value] * 1000 for i in range(1000)]
return grid
def count_lights(grid):
re... | StarcoderdataPython |
35912 | <filename>odin/utils/iterator.py
import os
import glob
import random
from PIL import Image
from matplotlib import pyplot as plt
from ipywidgets import Button, Output, HBox, VBox, Label, BoundedIntText
from IPython.display import Javascript, display
class ImagesLoader:
def __init__(self, images_path, images_extens... | StarcoderdataPython |
159656 | import yaml
import sys
import os
import pathlib
import zipfile
import shutil
import tarfile
import errno
# Read YAML file
def main(argv):
command_name = 'mkisofs'
target_directory = 'target'
if sys.version_info[0] != 3 or sys.version_info[1] < 6:
print("This script requires Python version 3.6+")
... | StarcoderdataPython |
93248 | <filename>gamestonk_terminal/portfolio/brokers/ally/ally_model.py<gh_stars>1000+
"""Ally Model"""
__docformat__ = "numpy"
import ally
import pandas as pd
def get_holdings() -> pd.DataFrame:
"""Get holdings from Ally account in pandas df
Returns
-------
pd.DataFrame
Dataframe of positions
... | StarcoderdataPython |
11263 | <reponame>Arpan-206/Youtube-Downloader-Flask
from flask import Flask, request, send_file, render_template, url_for
import pytube
import logging
import sys
import os
from hello import timed_delete
from threading import Timer
timed_delete()
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app = Flask(__name__)... | StarcoderdataPython |
3315407 | from copy import deepcopy
from logging import getLogger
import joblib
import numpy as np
import sklearn
import xarray as xr
from replay_trajectory_classification.bins import (atleast_2d, get_centers,
get_grid, get_track_grid,
... | StarcoderdataPython |
3241351 | <gh_stars>1-10
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.analyses.derating.models.inductor_unit_test.py is part of The
# RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for the inductor ... | StarcoderdataPython |
172646 | <gh_stars>0
from __future__ import unicode_literals, print_function
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment
env = Environment()
env.loader = FileSystemLoader('.')
my_val = {
"vrf_name": 'blue',
"rd_number": '100:1',
"ipv4_enabled": 1,
"ipv6_enabled... | StarcoderdataPython |
16908 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Fable Input Output
# https://github.com/silx-kit/fabio
#
# Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: <NAME> (<EMAIL>)
#
# This program is free software: you can redistribute it an... | StarcoderdataPython |
1627384 | #!/usr/bin/python3
import argparse
import os
import serial
import sys
import time
def wait_for_prompt(port, timeout, prompt_string):
prompt_expected = b'\r\n' + prompt_string
prompt_buffer = b''
response_buffer = b''
time_timeout = timeout
time_elapsed = 0.0
time_start = time.time()
port.t... | StarcoderdataPython |
1609045 | <gh_stars>10-100
# This script makes a directory for each resolution of each simulation
# in the SXS-collaboration catalog
import json
import argparse
import os
import requests
parser = argparse.ArgumentParser(description="Makes a directory hierarchy for each resolution of each simulation in the SXS collaboration ca... | StarcoderdataPython |
3318181 | from collections import OrderedDict
import torch
import logging
import numpy as np
from mmskeleton.utils import call_obj, import_obj, load_checkpoint
from mmcv.runner import Runner
from mmcv import Config, ProgressBar
from mmcv.parallel import MMDataParallel
import os, re, copy
from sklearn.model_selection import KFold... | StarcoderdataPython |
4272 | import numpy as np
from something import Top
i = 0
while i < 10:
a = np.ndarray((10,4))
b = np.ones((10, Top))
i += 1
del Top
# show_store()
| StarcoderdataPython |
4804908 | from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
class Users(models.Model):
name = models.CharField(max_length=60)
mobile_no = models.IntegerField(max_length=10, unique=True)
type_user = models.CharField(max_length=20)
email_id = models.EmailField(... | StarcoderdataPython |
119009 | """
WSGI config for painindex project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
from dj_static import Cling # heroku staticfiles collection
os.environ["DJANGO_SETTI... | StarcoderdataPython |
3303857 | <gh_stars>0
"""myhomework URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='... | StarcoderdataPython |
159399 | #!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to ... | StarcoderdataPython |
4811771 | import ast
import json
from dbconnection import db_connect
db_object = db_connect()
global db
db = db_object.apiscan
def check_scan_status(data):
# Return the Scan status
total_scan = data['total_scan']
count = 0
for key,value in data.items():
if value == 'Y' or value == 'y':
coun... | StarcoderdataPython |
42942 | <filename>app/main.py
# import streamlit.cli
from app.src.launch import app
if __name__ == "__main__":
# streamlit.cli._main_run_clExplicit("./src/launch.py", "streamlit run")
app.run()
| StarcoderdataPython |
1689375 | <gh_stars>10-100
#!/usr/bin/env python3
from telnetlib import Telnet
import argparse
import ssl
parser = argparse.ArgumentParser(description="Connect to services behind an SNI proxy.")
parser.add_argument("hostname", type=str, help="hostname to connect to")
parser.add_argument(
"port", type=int, default=443, narg... | StarcoderdataPython |
1614936 | <gh_stars>1-10
from base import Person
class Warrior(Person):
hp = 100
strength = 2
accuracy = 5
defense = 4
attacks_by = "swings sword"
class Marksman(Person):
hp = 100
strength = 1
accuracy = 8
defense = 3
attacks_by = "shoots an arrow"
class Madman(Person):
hp = 100
... | StarcoderdataPython |
3252915 | <filename>worms/tests/test_vertex.py
from worms.vertex import *
import numba as nb
import numba.types as nt
import numpy as np
import pytest
from worms import vis
def test_Vertex_NC(bbdb):
bbs = bbdb.query("all")
v = Vertex(bbs, "NC")
assert v.len == 55
assert v.x2exit.shape == (55, 4, 4)
assert v.x2ori... | StarcoderdataPython |
1745536 | <filename>club_crm/api/app/pg.py
import frappe
import re
import uuid
from frappe.utils import now
import hashlib
import hmac
import hashlib
import base64
from datetime import datetime
import random
import string
@frappe.whitelist(allow_guest = True)
def create_log(**kwargs):
kwargs=frappe._dict(kwargs)
doc =... | StarcoderdataPython |
1750590 | <reponame>wengzilla/staketaxcsv
from common.ErrorCounter import ErrorCounter
from common.ExporterTypes import TX_TYPE_NFT_WHITELIST, TX_TYPE_NFT_CANCEL_ORDER
from terra import util_terra
from terra.api_lcd import LcdAPI
from terra.col4.handle_simple import handle_simple, handle_unknown
from terra.make_tx import (
m... | StarcoderdataPython |
3266873 | # --------------------------------------------------------
# Dragon
# Copyright(c) 2017 SeetaTech
# Written by <NAME>
# --------------------------------------------------------
import time
import pprint
from multiprocessing import Queue
from six.moves import range as xrange
import dragon.core.mpi as mpi
from .data_r... | StarcoderdataPython |
1667888 | from behave import given, when, then, step
from hamcrest import assert_that, equal_to
from src.classes.compte.Courant import Courant
class StepUS001CrediterUnCompte:
@given('un compte {numCompte} avec un solde {solde}')
def __init__(self, numCompte, solde):
self.compte = Courant(numCompte=eval(numCom... | StarcoderdataPython |
1672625 | from unittest import TestCase
from app import create_app
class TestWelcome(TestCase):
def setUp(self):
self.app = create_app().test_client()
def test_welcome(self):
"""
Tests the route screen message
"""
rv = self.app.get('/api/')
# If we recalculate the hash ... | StarcoderdataPython |
188035 | <reponame>marble/Toolchain_RenderDocumentation
#!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
from __future__ import absolute_import
import os
import sys
import tct
from os.path import exists as ospe
params = tct.readjson(sys.argv[1])
binabspath = sys.argv[2]
facts = tct.readjson(params... | StarcoderdataPython |
1730109 | <reponame>fromm-m/ecir2021-am-search
"""Implementation os baseline ranking methods."""
import logging
import pathlib
from abc import ABC
from collections import defaultdict
from logging import Logger
from operator import itemgetter
from typing import Collection, Mapping, Optional, Sequence, Tuple, TypeVar, Union
impor... | StarcoderdataPython |
32479 | <gh_stars>0
import numpy as np
import cv2
import sys
import json
import os
if (len(sys.argv) != 5):
print('2 arguments required')
exit()
img1 = cv2.imread(sys.argv[1])
img2 = cv2.imread(sys.argv[2])
file = open(sys.argv[4], "r")
points = json.loads(file.read())
dst_pts = np.float32(points['old']).reshape(-... | StarcoderdataPython |
3323026 | """
The base Spikey Module definition. Provides structure
and functionality that every class in Spikey should
abide by.
"""
from copy import deepcopy
import pickle
import numpy as np
class Key:
"""
A parameter for some module part.
Parameters
----------
name: str
Name / key of the paramet... | StarcoderdataPython |
159256 | <reponame>emillion/zimsoap<gh_stars>10-100
import zimsoap.client
import zimsoap.utils
from zimsoap.zobjects import DistributionList
zc = zimsoap.client.ZimbraAdminClient("xxxxxxx", "7071")
zc.login("zimbra", "xxxxxxxxxx")
a = zc.get_distribution_list(
DistributionList(name="<EMAIL>"))
try:
liste = zc.delete_d... | StarcoderdataPython |
199282 | <filename>src/orders/tests/pay_signals/conftest.py
import pytest
pytestmark = [pytest.mark.django_db]
@pytest.fixture
def order(factory):
return factory.order()
| StarcoderdataPython |
3364275 | <gh_stars>1-10
# Exercise 5
weather_c = {
"Monday":12,
"Tuesday":14,
'Wednesday':15,
'Thursday':14,
'Friday':21,
'Saturday':22,
'Sunday':24
}
weather_f = {key:round((9/5*temp_c)+32,2) for (key,temp_c) in weather_c.items()}
print(weather_f) | StarcoderdataPython |
1699476 | import logging
from commands import issue as issue_cmd
from signals import echo
from config import pass_config
import click
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# create a file handler
handler = logging.FileHandler('jira.log')
handler.setLevel(logging.INFO)
# create a logging format
... | StarcoderdataPython |
172872 | <filename>request_routing_in_a_web_server_with_a_trie.py
"""Create a router that can store handlers for paths within a trie.
Usage: request_routing_in_a_web_server_with_a_trie.py
Classes:
Router()
RouteTrie()
RouteTrieNode()
"""
import collections
class Router:
"""Creates a Router class that stores... | StarcoderdataPython |
3359158 | <gh_stars>0
from distutils.core import setup
import subprocess
desc = subprocess.check_output(['git','describe','--tags'])
tag = desc.split('-')[0]
setup(
name="panda-yoda",
version=tag,
description=' PanDA Yoda Package',
long_description="This package contains PanDA Yoda Components",
license='GPL',
... | StarcoderdataPython |
3228596 | <gh_stars>0
def titulo(txt):
print(30*'-')
print(txt)
print(30*'-')
# Programa Pricipal
titulo(' CURSO EM VÍDEO ')
titulo(' APRENDA PYTHON ')
titulo(' <NAME> ')
| StarcoderdataPython |
43104 | <gh_stars>0
"""
This module provides a Python interface for operations on Storages.
It is part of the Knowledge Graph API of Blue Brain Nexus v1.
https://bluebrainnexus.io/docs/api/1.1/kg/kg-storages-api.html
"""
from typing import Dict, Optional
from urllib.parse import quote_plus as url_encode
from nexussdk.utils.h... | StarcoderdataPython |
9188 | # Generated by Django 3.1 on 2020-08-22 17:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BoardGame',
fields=[
('id', models.AutoField(... | StarcoderdataPython |
64604 | <filename>Condicionais/If.py
i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2 | StarcoderdataPython |
31788 | import numpy as np
from random import sample, seed
#import matplotlib.pyplot as plt
from sys import argv, stdout
#from scipy.stats import gumbel_r
from score_matrix import readScoreMatrix, getMatrix
from seqali import smithWaterman, smithFast, plotMat, plotTraceMat
from multiprocessing import Process, Manager
def scra... | StarcoderdataPython |
1769270 | <reponame>Czembri/contentAgregator<filename>contentagregator/modules/bbc/models.py
from contentagregator import db
from datetime import datetime
class Bbc(db.Model):
__tablename__ = "bbc_news"
id = db.Column(db.Integer, primary_key=True)
source = db.Column(db.String(255), nullable=False)
description =... | StarcoderdataPython |
34597 | <reponame>sedlar/work-tracking<filename>api/src/wt/provider/db/models/statistics.py
from collections import namedtuple
from typing import List
from decimal import Decimal
from sqlalchemy import select, func
from wt.common import Money, Currency
from wt.costs.expenditures import ExpenditureStatus
from wt.ids import En... | StarcoderdataPython |
1647764 | <reponame>bchess/mrjob
"""Module for loading all tests, so we can run them from setup.py"""
import os
try:
import unittest2 as unittest
except ImportError:
import unittest
def load_tests():
return unittest.defaultTestLoader.discover(os.path.dirname(__file__))
| StarcoderdataPython |
104748 | from contextlib import contextmanager
import socket
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database
from settings import settings
class DbSession():
__engine = None
__session = Non... | StarcoderdataPython |
3233597 | # Copyright 2016 Intel 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 applicable law or agreed to in wri... | StarcoderdataPython |
4834720 | import gng2
from pygraph.classes.graph import graph
from pygraph.algorithms.minmax import cut_tree
from pygraph.algorithms.accessibility import connected_components
from utils import __dict_reverse as dict_reverse
import itertools
import time
from numpy import array,sum,sqrt
class data_block:
"""This is ... | StarcoderdataPython |
192896 | <filename>tests/unit/test_decorators.py
import json
import pytest
from justobjects import schemas, validation
from tests.models import Actor, Manager, Movie, Role, RoleManager, Unknown
def test_show_isolated_model() -> None:
js = schemas.show_schema(Actor)
assert js["type"] == "object"
assert js["requi... | StarcoderdataPython |
3346527 | <reponame>DonalChilde/Pfm-Util
import logging
import pytest
from pfmsoft.util.collection.sort import (
SortInstruction,
index_objects,
sort_in_place,
sort_to_new_list,
)
from .misc_test import SomeData
#### setting up logger ####
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHan... | StarcoderdataPython |
1696267 | #!/usr/bin/python
###########################################################################
# ConvertData.py :
#
# Shrink input images into slabs. For each input, the associated
# expert segmentation is first converted into an image and then shrunk into
# slabs the same way.
#
#######################################... | StarcoderdataPython |
3207842 | #!/usr/bin/env python3
"""
Holds all formatting utilities
"""
def std_float(number, num_decimals=2):
"""
Print a number to string with n digits after the decimal point
(default = 2)
"""
return "{0:.{1:}f}".format(float(number), num_decimals)
def timestamp_to_seconds(timestamp):
"""
Conve... | StarcoderdataPython |
45543 | from linked_list import LinkedList
from node import Node
from mergeList import ll_merge
# import pytest
def test_linked_list_creation():
"""Validating if Linked List was Created."""
ll = LinkedList([2, 3, 4, 5])
assert Node(2).val is ll.head.val
assert isinstance(ll.head.val, int)
def test_insert_i... | StarcoderdataPython |
3367979 | <reponame>zevgenia/Python_shultais
string = 'Питон'
data = string.encode()
print(type(data))
print(data)
print(list(data)) | StarcoderdataPython |
86879 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-13 21:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('draftin', '0004_draft_date_published'),
]
operations = [
migrations.AlterField... | StarcoderdataPython |
1674522 | import copy
import os
import zipfile
from ipaddress import ip_network
import dateutil.parser
from django.http import FileResponse
from django.db import transaction
from account.decorators import check_contest_permission, ensure_created_by
from account.models import User
from submission.models import Submission, Judge... | StarcoderdataPython |
106916 | <reponame>ataffe/smartGarden
import board
import busio
import adafruit_tsl2561
import time
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_tsl2561.TSL2561(i2c)
sensor.gain = 0
while True:
print('Lux: {}'.format(sensor.lux))
print('Broadband: {}'.format(sensor.broadband))
print('Infrare... | StarcoderdataPython |
1641615 | <reponame>suresh-guttikonda/sim-environment<filename>src/tensorflow/igibson/test_gym_env.py
#!/usr/bin/env python3
import os
import numpy as np
import pybullet as p
from utils.iGibson_env import iGibsonEnv
np.set_printoptions(precision=5, suppress=True)
if __name__ == '__main__':
config_filename = os.path.join('... | StarcoderdataPython |
121289 | <filename>tests/test_get_unique_craters.py
from __future__ import absolute_import, division, print_function
import numpy as np
import h5py
import pandas as pd
import sys
sys.path.append('../')
import deepmars.utils.transform as guc
class TestLongLatEstimation(object):
def setup(self):
ctrs = pd.HDFStore(... | StarcoderdataPython |
4808437 | from keras.layers import Conv2D, MaxPooling2D, Concatenate, Add
from keras import layers
from keras import backend as K
K.set_image_data_format('channels_last')
import sys
import os
sys.path.append(os.path.abspath('../'))
from models import caps_layers
from models.caps_layers import BilinearUpsampling
from experiment... | StarcoderdataPython |
39099 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | StarcoderdataPython |
55963 |
""" ATL - A Tensor Library """
from .quote_api import (
Function,
Var,
IVar,
Relation,
Size,
Type,
Sum,
Gen,
Let,
Tuple,
Expr,
IExpr,
Pred,
Fun,
ATLmath,
)
num = Type(float)
from .atl_types import is_type, Num, Tuple, Tensor
from .parse_pyast import func, macro
from .halide_ir import... | StarcoderdataPython |
1686933 | <gh_stars>1-10
'''
Write a Python program to create a set.
'''
num = [1, 2, 3, 4, 8]
set1 = set(num)
print(set1) | StarcoderdataPython |
4816378 | <reponame>rawkode/pulumi-equinix-metal
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, S... | StarcoderdataPython |
1673110 | # -*- coding: utf-8 -*-
#
# Copyright (c), 2016-2019, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author ... | StarcoderdataPython |
1631982 | from tkinter import *
root=Tk()
root.title("@happy_coding01")
root.geometry("300x300")
frame1=Frame(root,bg="blue")
frame1.pack(fill=BOTH,expand=True)
button=Button(frame1,text="Button",font=("Ariel",15,"bold"),
fg="red",height=5,width=15,bd=4,bg="black")
button.pack(anchor="nw",padx=80,pady=100... | StarcoderdataPython |
3304307 | <reponame>rskumarmb/dockerfiles
import sqlalchemy
import pymysql
import pyodbc
import psycopg2
assert 'FreeTDS' in pyodbc.drivers()
print("All is good. All imported successfully")
| StarcoderdataPython |
3314170 | #
# @section License
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2017, <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the ... | StarcoderdataPython |
1775717 | user = 'www-data'
group = 'www-data'
bind = '0.0.0.0:5000'
#workers = ${HDX_CKAN_WORKERS}
access_log_format = '"%({x-real-ip}i)s" %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
accesslog = '/var/log/ckan/ckan.access.log'
errorlog = '/var/log/ckan/ckan.error.log'
loglevel = 'warning'
timeout = 120
graceful_timeo... | StarcoderdataPython |
180617 | """lake_utils.py"""
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_style("darkgrid")
def merge_data():
"""
I need to be able to export this table so I can share the .csv
with my advisor.
"""
flux = pd.read_csv('~/Dropbox/CSE599/Kuhn/HW5/data/flux.csv')
che... | StarcoderdataPython |
3388937 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# mt: multithreading
# mp: multiprocessing
import os
import time
import threading as t
import multiprocessing as mp
import sqlite3
import funcy as fy
import pymysql
import sqlalchemy.pool
import mosql.db as modb
def run_in_thread(f, *args, **kwargs)... | StarcoderdataPython |
173059 | from __future__ import unicode_literals
import mock
try:
import unittest2 as unittest # Python2.6
except ImportError:
import unittest
import trovebox
class TestAlbums(unittest.TestCase):
test_host = "test.example.com"
test_photos_dict = [{"id": "1a", "tags": ["tag1", "tag2"]},
... | StarcoderdataPython |
1633580 | <gh_stars>1000+
"""
Add named or unnamed vispy colormaps to existing layers.
"""
import numpy as np
from skimage import data
import napari
histo = data.astronaut() / 255
rch, gch, bch = np.transpose(histo, (2, 0, 1))
v = napari.Viewer()
rlayer = v.add_image(
rch, name='red channel', colormap='red', blending='a... | StarcoderdataPython |
1760899 | import logging
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
def create_programs():
user = toolkit.get_action('get_site_user')({'ignore_auth': True}, {})
context = {'user': user['name']}
try:
data = {'id': 'programs'}
toolkit.get_action('vocabulary_show')(context, da... | StarcoderdataPython |
1681769 | from pydantic import BaseModel
from app.db.serializer import generate_user_key, generate_institution_key
import bcrypt
from datetime import datetime
class SignInForm(BaseModel):
'''
JSON representation of the sign in form
'''
email: str
password: str
@property
def password_hash(self):
... | StarcoderdataPython |
3259142 | # -*- coding:utf-8 -*-
#
# Copyright (C) 2012, <NAME> <<EMAIL>>
#
# 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 3 of the License, or
# (at your option) any later version.
#
# Th... | StarcoderdataPython |
4833466 | r"""
Library of commonly used, famous, or interesting polytopes
This module gathers several constructors of polytopes that can be reached
through ``polytopes.<tab>``. For example, here is the hypercube in dimension 5::
sage: polytopes.hypercube(5)
A 5-dimensional polyhedron in ZZ^5 defined as the convex hull ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.