id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
109883 | <gh_stars>0
world_cities = ['Dubai', 'New Orleans', 'Santorini', 'Gaza', 'Seoul']
print('***********')
print(world_cities)
print('***********')
print(sorted(world_cities))
print('***********')
print(world_cities)
print('***********')
print(sorted(world_cities, reverse=True))
print('***********')
print(world_cities)
pri... | StarcoderdataPython |
11832 | <filename>main.py
import pandas as pd
import numpy as np
import io
import time
import uuid
from flask import Flask, render_template, request, redirect, url_for, Response, session, send_file, make_response, send_from_directory
from os.path import join, dirname, realpath
from werkzeug.wsgi import FileWrapper
app = Flas... | StarcoderdataPython |
4824277 | import random
from operator import add
class SlipperyGrid:
"""
Slippery grid-world modelled as an MDP
...
Attributes
----------
shape: list
1d list with two elements: 1st element is the num of row cells and the 2nd is the num of column cells (default [40, 40])
initial_state : lis... | StarcoderdataPython |
60797 | from readthedocs.api.v2.views.footer_views import BaseFooterHTML
from readthedocs.core.utils.extend import SettingsOverrideObject
from readthedocs.embed.views import EmbedAPIBase
class BaseProxiedFooterHTML(BaseFooterHTML):
# DRF has BasicAuthentication and SessionAuthentication as default classes.
# We don'... | StarcoderdataPython |
3393939 | <reponame>TylerYep/wolfbot<filename>tests/solvers/state_test.py<gh_stars>1-10
from tests.conftest import set_roles
from wolfbot import const
from wolfbot.enums import Role, SwitchPriority
from wolfbot.solvers import SolverState
from wolfbot.statements import Statement
class TestSolverState:
"""Tests for the Solve... | StarcoderdataPython |
3391774 | import random, time, sys, subprocess, threading, pycurl, os, requests
from colorama import Fore
class Proxy_Checker():
def __init__(self):
subprocess.call('clear', shell=True)
sys.setrecursionlimit(10**6)
print(f"""{Fore.BLUE}
โโโโโโ โโโโโโ โโโโโโ โโโ โโโโโ โโโ โโโโโโโโโโโโโโโ โ... | StarcoderdataPython |
3340585 | from math import cos, sin, pi
card_w, card_h = map(int, input().split())
env_w, env_h = map(int, input().split())
eps = 1e-10
if card_w == env_h and card_h == env_w:
print('Possible')
exit()
def check_insert(w, h):
if w <= env_w + eps and h <= env_h + eps:
return True
else:
ret... | StarcoderdataPython |
1749863 | # -*- coding: utf-8 -*-
import scrapy
class VisirSlurperItem(scrapy.Item):
url = scrapy.Field()
article_text = scrapy.Field()
author = scrapy.Field()
possible_authors = scrapy.Field()
date_published = scrapy.Field()
headline = scrapy.Field()
description = scrapy.Field()
body = scrapy.... | StarcoderdataPython |
3281340 | ##
## controlpanels.py - part of wxfalsecolor
##
## $Id$
## $URL$
import os
import wx
import wx.lib.foldpanelbar as fpb
# work around for bug in some new wxPython versions
if not 'FPB_DEFAULT_STYLE' in dir(fpb):
fpb.FPB_DEFAULT_STYLE = fpb.FPB_VERTICAL
import wx.lib.buttons as buttons
class BaseControlPanel(wx.... | StarcoderdataPython |
36991 | <filename>ETLPipeline (1).py
import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
input:
messages_filepath: The path of messages dataset.
categories_filepath: The path of categories dataset.
output:
df: The me... | StarcoderdataPython |
137984 | #!/usr/bin/python
"""Example of a guild - Qt hybrid system.
This example shows three ways to connect guild pipelines to Qt
objects. Version 1 (preferred) uses a normal guild pipeline with a
hybrid (guild/Qt) display object. Version 2 uses a hybrid source and a
standard Qt display, which is what you'd do if you don't ... | StarcoderdataPython |
3331105 | <reponame>McStasMcXtrace/ufit
# -*- coding: utf-8 -*-
# *****************************************************************************
# ufit, a universal scattering fitting suite
#
# Copyright (c) 2013-2019, <NAME> and contributors. All rights reserved.
# Licensed under a 2-clause BSD license, see LICENSE.
# ********... | StarcoderdataPython |
97329 | from datetime import timedelta, datetime
from celery.schedules import crontab
from celery.task.base import periodic_task
from couchlog.models import ExceptionRecord
from django.conf import settings
@periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr(settings, 'CELERY_PERIODIC_QUEUE', 'celery'))
def purge... | StarcoderdataPython |
110063 | <filename>tests/test_action_lib_remove_old_snapshots.py
from manage_iq_base_action_test_case import ManageIQBaseActionTestCase
from lib.remove_old_snapshots import RemoveOldSnapshots
from st2common.runners.base_action import Action
import mock
import datetime
import requests
class TestRemoveOldSnapshots(ManageIQBas... | StarcoderdataPython |
3282725 | # Finds the root of an equation in the range [a, b] by using the Secant Method.
import math
def equation(x):
return math.cos(x) - x #Original equation.
def iterate(p1, p0, i):
p = p1 - ((equation(p1) * (p1 - p0)) / (equation(p1) - equation(p0)))
print("\n(p" + str(i) + ", f(p" + str(i) + ")) = " + str((p, equatio... | StarcoderdataPython |
1795246 | """
K-Means
"""
import logging as log
import numpy as np
import random
log.basicConfig(format="%(message)s", level=log.INFO)
def load_data(file_path):
"""ๅ ่ฝฝๆฐๆฎ
ๆบๆฐๆฎๆ ผๅผไธบๅค่ก๏ผๆฏ่กไธบไธคไธชๆตฎ็นๆฐ๏ผๅๅซ่กจ็คบ (x,y)
"""
data = []
with open(file_path, 'r', encoding='utf-8') as fr:
for line in fr.read().splitlines... | StarcoderdataPython |
1771281 | from setuptools import setup
setup(
name='PyMoe',
version='1.0.7',
packages=['Pymoe', 'Pymoe.Anilist', 'Pymoe.Kitsu', 'Pymoe.VNDB', 'Pymoe.Bakatsuki'],
url='https://github.com/ccubed/PyMoe',
license='MIT',
author='<NAME>',
author_email='<EMAIL>',
description="PyMoe is the only lib you'l... | StarcoderdataPython |
3229431 | <gh_stars>0
from django.test import TestCase, Client
from chat.views import *
from socket import socket
import os
import json
class UserTest(TestCase):
def setUp(self) -> None:
self.client = Client()
self.email = '<EMAIL>'
self.user_id = ''
self.login_data = ''
self.socket... | StarcoderdataPython |
190987 | import bpy
import sys
import addon_utils
from pathlib import Path
def get_python_path():
if bpy.app.version < (2,9,0):
python_path = bpy.app.binary_path_python
else:
python_path = sys.executable
return Path(python_path)
python_path = get_python_path()
blender_path = Path(bpy.app.binary_pat... | StarcoderdataPython |
87639 | <reponame>mcvine/mcvine
#!/usr/bin/env python
#
#
import unittest
import journal
svq_f = lambda qx,qy,qz: qx*qx
def createSvq():
import histogram as H
qxaxis = H.axis( 'Qx', boundaries = H.arange(-5, 5.0, 0.1) )
qyaxis = H.axis( 'Qy', boundaries = H.arange(-5, 6.0, 0.1) )
qzaxis = H.axis( 'Qz', boun... | StarcoderdataPython |
1727292 | <reponame>JiriVales/orienteering-tools<filename>python-scripts/vegetation/Create-cultivated-land-(height&RUIAN).py
##Create cultivated land (height&RUIAN)=name
##ruianparcelswithattributes=vector
##expressionforextractcorrespondingpolygonsfromruianbyattribute=string"druhpozemk" IN ('2')
##vegetationheightopenland=vecto... | StarcoderdataPython |
4825753 | import pyexcel as pe
import xlrd
import logging
def process_excel(filename):
if filename.endswith(".csv"):
# add merged cells here please
sheet = pe.get_sheet(file_name=filename)
yield sheet, "name", ()
else:
book = pe.get_book(file_name=filename)
sheets = b... | StarcoderdataPython |
1683898 | import os
import sys
import tempfile
import contextlib
import shutil
import distutils
import setuptools
import setuptools.command.build_ext
import cppimport.config
from cppimport.filepaths import make_absolute
if sys.version_info[0] == 2:
import StringIO as io
else:
import io
@contextlib.contextmanager
def ... | StarcoderdataPython |
199918 | <filename>tests/generator/test_legacy_array.py
from responses import RequestsMock
from tests import loader
def test_formula_prefix(responses: RequestsMock, tmpdir):
responses.add(
responses.GET,
url="http://test/",
json={
"swagger": "2.0",
"paths": {
... | StarcoderdataPython |
3367127 | # Copyright (c) 2020. Author: <NAME>, <EMAIL>
# Ref: https://github.com/yanx27/Pointnet_Pointnet2_pytorch/blob/master/data_utils/ShapeNetDataLoader.py
import os, json, torch, warnings, numpy as np
from PC_Augmentation import pc_normalize
from torch.utils.data import Dataset
warnings.filterwarnings('ignore')
class P... | StarcoderdataPython |
4802690 | import setuptools
import pkg
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name=pkg.name,
version=pkg.version,
author=pkg.author,
author_email=pkg.author_email,
description=pkg.description,
long_description=long_description,
long_description_content_... | StarcoderdataPython |
3374839 | <reponame>MarcSkovMadsen/panel-presentation<gh_stars>10-100
import panel as pn
import param
from .base import ComponentBase
import numpy as np
class Trend(ComponentBase):
component = param.Parameter(pn.indicators.Trend)
reference = param.String("https://panel.holoviz.org/reference/indicators/Trend.html#indicat... | StarcoderdataPython |
1763624 | import re
from pydantic import BaseModel, validator
def validate_image(image: str) -> str:
if re.fullmatch(r"https?://[\w!?/+\-_~;.,*&@#$%()'[\]]+", image) is None:
raise ValueError('malformed image url: %s' % image)
return image
def validate_name(name: str) -> str:
if len(name) == 0:
r... | StarcoderdataPython |
106523 | <filename>rtamt/exception/stl/exception.py
class STLException(Exception):
pass
class STLParseException(Exception):
pass
class STLOfflineException(Exception):
pass | StarcoderdataPython |
3373807 | <filename>ilrdc/util/__init__.py
from .url_downloader import download_url
from .sound_url_modifier import modify_sound_url
| StarcoderdataPython |
104029 | """Preprocessing of raw LAU2 data to bring it into normalised form."""
import geopandas as gpd
import pandas as pd
from renewablepotentialslib.shape_utils import to_multi_polygon
OUTPUT_DRIVER = "GeoJSON"
KOSOVO_MUNICIPALITIES = [f"RS{x:02d}" for x in range(1, 38)]
def merge_lau(path_to_shapes, path_to_attributes, ... | StarcoderdataPython |
1717619 | """
Tests for functions in ensemble_tools.py.
Authors: <NAME> & <NAME>
Note that functions that start with an underscore (_) are designed for local
use only by the primary functions within ensemble_tools.py. Therefore, testing
of those local scripts does not include checking for irrational inputs that
would cause me... | StarcoderdataPython |
3337077 | """Implementation of quicksort in Python."""
def quick_sort(iter):
"""Sort the iterable using the merge sort method."""
if not isinstance(iter, (list, tuple)):
raise TypeError("Input only a list/tuple of integers")
if len(iter) < 2:
return iter
if not all(isinstance(x, (int, float)) fo... | StarcoderdataPython |
43966 | # For SSH
import Exscript
# For Color Font
from colorama import init as colorama_init
from colorama import Fore
colorama_init(autoreset=True)
username = "user1"
password = "<PASSWORD>"
ip4 = "192.168.33.3"
# SSHใปใใทใงใณใฎ็ขบ็ซ
session = Exscript.protocols.SSH2()
session.connect(ip4)
# ใซใผใฟใซใญใฐใคใณ
account = Exscript.Account(n... | StarcoderdataPython |
1660834 | from oem_format_minimize.main import MinimalFormat
from oem_format_msgpack.main import MessagePackFormat
class MessagePackMinimalFormat(MessagePackFormat, MinimalFormat):
__key__ = 'minimize+msgpack'
__extension__ = 'min.mpack'
| StarcoderdataPython |
3252016 | '''Faรงa um programa que leia 6 numeros inteiros
e mostre a soma apenas dos que forem pares
se o valor for impar desconsidere-o'''
valor = 0
contador = 0
for x in range(1, 6):
x = int(input('Digite um numero inteiro: '))
if x % 2 == 0:
valor += x
contador += 1
print('Total de numeros pares dig... | StarcoderdataPython |
45375 | from yuuhpizzakebab import app, admin_required, login_required
from .models import Pizza, Topping
from flask import render_template, session, redirect, url_for, request, flash
@app.route('/pizzas')
def list_pizzas():
"""Shows a list of pizzas."""
return render_template('pizza/pizzas.html',
... | StarcoderdataPython |
3226985 | <filename>wmdadict/migrations/0030_auto_20170917_2104.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-17 11:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wm... | StarcoderdataPython |
3204805 | <reponame>thunder-/paprika<gh_stars>0
from paprika.repositories.ChunkRepository import ChunkRepository
from paprika.repositories.ProcessActionPropertyRepository import ProcessActionPropertyRepository
from paprika.repositories.ProcessPropertyRepository import ProcessPropertyRepository
from paprika.repositories.ProcessRe... | StarcoderdataPython |
3389174 | <reponame>tylerclair/py3canvas
"""ErrorReports API Tests for Version 1.0.
This is a testing template for the generated ErrorReportsAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.error_reports import ErrorReportsAPI
from py3canvas.apis.error_reports import Errorreport
class TestErro... | StarcoderdataPython |
58518 | import numpy as np
import matplotlib.pyplot as plt
import random
s0=4.96*10**8
mtop=5.04*10**8
oneday=24*60*60
oneyear=365
t=[i for i in range(1,oneyear*30)]
bprice0=6.4669
bprice=bprice0
bnum0=1000000
b0=1.0*bnum0
cw0=0.065
cw1=0.075
cw2=0.08
cw3=0.1
realmine=0
p0list=[]
b0list=[]
s0list=[]
p1list=[]
b1list=[]
s1lis... | StarcoderdataPython |
152085 | <reponame>City-of-Helsinki/atv<filename>services/tests/test_admin.py<gh_stars>0
from django.urls import reverse
def test_admin_service_list_view_query_count_not_too_big(
admin_client, django_assert_max_num_queries, service_api_key_factory
):
admin_view_url = reverse("admin:services_service_changelist")
w... | StarcoderdataPython |
115750 | <reponame>PrabhuJoseph/cloudbreak
import json
import logging
from logging.handlers import RotatingFileHandler
class MetricsLogger:
def __init__(self, name, path, max_bytes, backup_count, debug=False):
fmt = '%(message)s'
logging.basicConfig(
level=logging.INFO,
for... | StarcoderdataPython |
4819402 | <filename>codes/main.py<gh_stars>1-10
import cv2
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
import LeNet_modified as lenet
from sklearn.utils import shuffle
# import disparity image
disp_gt=cv2.imread('scene1.truedisp.pgm'... | StarcoderdataPython |
1751576 | #!/usr/bin/env python
#
# filter-noisy-assembler-warnings.py
# Author: <NAME>
# <https://stackoverflow.com/a/41515691>
import sys
for line in sys.stdin:
# If line is a 'noisy' warning, don't print it or the following two lines.
if ('warning: section' in line and 'is deprecated' in line
or 'note: change s... | StarcoderdataPython |
3235784 | # Generated by Django 3.1.3 on 2020-11-26 13:55
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0012_auto_20201126_1918'),
]
operations = [
migrations.AddField(
model_name='reservation',
n... | StarcoderdataPython |
72225 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: create_template_with_yaml.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from g... | StarcoderdataPython |
1646355 | ## ALL RIGHTS RESERVED.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writin... | StarcoderdataPython |
3238200 | <reponame>fpischedda/yaff
"""
Yaff game runner
It runs a Yaff based appliction specifiyng its package name, example:
$ yaff run example
this script will look up the module example.main and will try to execute
the run function
"""
import importlib.util
import sys
import click
@click.group()
def cli():
pass
@c... | StarcoderdataPython |
3254138 | <reponame>hcallen/python-xmatters<gh_stars>0
import requests
from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
from xmatters import errors as err
from xmatters.connection import Connection
class OAuth2Auth(Connection):
_endpoints = {'token': '/oauth2/token'}
def... | StarcoderdataPython |
189450 | from __future__ import annotations
import asyncio
import functools
import inspect
import logging
import uuid
from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any, Awaitable, Callable, Optional
from ocpp.charge_point import camel_to_snake_case, remove_nones, snake_to_camel_case
from o... | StarcoderdataPython |
1740750 | <reponame>ThundeRatz/vss_simulation
#!/usr/bin/env python3
# coding=utf-8
"""
File:
keyboard_node.py
Description:
Simple python routine to watch the keyboard or a joystick
to send velocity commands to a Gazebo simulation.
"""
import pygame
import sys
import rospy
from geometry_msgs.ms... | StarcoderdataPython |
1660418 | <filename>Django/middlewareimplement/my_middleware.py
# -*- coding: utf-8 -*-
# @Author: Clarence
# @Date: 2020-06-10 18:39:52
# @Last Modified by: Clarence
# @Last Modified time: 2020-06-10 18:46:26
# ไธญ้ดไปถ็็ฎๅๅฎ็ฐ
class Router(obejct):
def __init__(self):
self.path_info = {}
def route(self, environ, start_respons... | StarcoderdataPython |
86127 | <filename>icrawler/utils/session.py
import requests
from six.moves.urllib.parse import urlsplit
class Session(requests.Session):
def __init__(self, proxy_pool):
super(Session, self).__init__()
self.proxy_pool = proxy_pool
def _url_scheme(self, url):
return urlsplit(url).scheme
d... | StarcoderdataPython |
3322496 | """
!!! Use this for ad-hoc updating of results for a known list of supplier IDs.
Takes a CSV file with rows in the format: Supplier ID, Supplier Name, Result
e.g:
123456, Supplier name 1, pass
123212, Supplier name 2, fail
234567, Supplier name 3, pass
The supplier name is cross-referenced against the supplier name ... | StarcoderdataPython |
46313 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='darch',
# Versions ... | StarcoderdataPython |
163736 | <reponame>CubexX/tram-bot<filename>utils.py
import re
import requests
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup,
ReplyKeyboardMarkup)
from stations import invert_stations, stations
from storer import Storer
storer = Storer('bot.db')
def get_inline_keyboard(station_id):
... | StarcoderdataPython |
1626373 | <reponame>marnunez/ezc3d
"""
Test for file IO
"""
from pathlib import Path
import numpy as np
import pytest
import ezc3d
def test_create_c3d():
c3d = ezc3d.c3d()
# Test the header
assert c3d['header']['points']['size'] == 0
assert c3d['header']['points']['frame_rate'] == 0.0
assert c3d['he... | StarcoderdataPython |
15033 | <filename>tests/validation/test_is_subnational1.py
import unittest
from ebird.api.validation import is_subnational1
class IsSubnational1Tests(unittest.TestCase):
"""Tests for the is_subnational1 validation function."""
def test_is_subnational1(self):
self.assertTrue(is_subnational1("US-NV"))
de... | StarcoderdataPython |
3282518 | <filename>autoprompt/pre_defined_prompt.py
import time
import argparse
import json
import logging
from pathlib import Path
import random
import os
import pickle
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
import transformers
from transformers import AutoConfi... | StarcoderdataPython |
66412 | # -*- coding: utf-8 -*
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import requests
import os
from astropy.coordinates import SkyCoord
import astropy.units as u
from astropy.table import Table, Column
from astropy.io.votable import parse
from astroquery import log
from astroquery.c... | StarcoderdataPython |
1663482 | <gh_stars>0
"""
this is a program intend to let usr to sort list
@author: <NAME>
"""
def insertion_sort(l):
""" scan each item in a list and findout if the current position number is less than target """
sorted_list = []
for item_compare in l:
for offset, sorted_number in enumerate(sorted_list.cop... | StarcoderdataPython |
1718375 | <reponame>Pcosmin/Optimus
from pyspark.sql import DataFrame as SparkDataFrame
from dask.dataframe.core import DataFrame as DaskDataFrame
from optimus.helpers.columns import check_column_numbers
from optimus.helpers.columns import parse_columns
from optimus.plots.functions import plot_scatterplot, plot_boxplot, plot_fr... | StarcoderdataPython |
122453 | <filename>min_heap.py<gh_stars>1-10
#!/usr/bin/env python
# encoding: utf-8
'''
@author: <NAME>
@license: (C) Copyright @ <NAME>
@contact: <EMAIL>
@file: min_heap.py
@time: 2019/4/29 20:23
@desc:
'''
# please see the comments in max_heap.py
def min_heap(array):
if not array:
return None
leng... | StarcoderdataPython |
3244994 | """
Picklify is a function that works similar to memoization; it is meant for
functions that return a dictionary. Often, such functions will parse a file to
generate a dictionary that maps certain keys to values. To save on such
overhead costs, we "picklify" them the first time they are called (save the
dictionary in a... | StarcoderdataPython |
3333379 | #!/usr/bin/env python3
# Copyright (C) 2021, RTE (http://www.rte-france.com)
# SPDX-License-Identifier: CC-BY-4.0
"""
Script to test Pacemaker module: stop VM
"""
from vm_manager.helpers.pacemaker import Pacemaker
VM_NAME = "vm1"
SLEEP = 1
if __name__ == "__main__":
with Pacemaker(VM_NAME) as p:
state... | StarcoderdataPython |
1779302 | # Based on the 'util/collect_env.py' script from PyTorch.
# <https://github.com/pytorch/pytorch>
#
# From PyTorch:
#
# Copyright (c) 2016- Facebook, Inc (<NAME>)
# Copyright (c) 2014- Facebook, Inc (<NAME>)
# Copyright (c) 2011-2014 Idiap Research Institute (<NAME>)
# Copyright (c) 2012-20... | StarcoderdataPython |
1685521 | from setuptools import setup, find_packages
VERSION = "1.0"
DESCRIPTION = "DeepTile"
LONG_DESCRIPTION = "Large image tiling and stitching algorithm for deep learning libraries."
setup(
name="deeptile",
version=VERSION,
author="<NAME>",
author_email="<<EMAIL>>",
description=DESCRIPTION,
long_de... | StarcoderdataPython |
1771365 | <filename>{{cookiecutter.project_slug}}/app/users/managers.py<gh_stars>0
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def __create_user(self,
email,
name,
password=<PASSWORD>,
is_s... | StarcoderdataPython |
3235248 | '''
่ถ
ๅ่พจ็ๆฐๆฎๅบ
'''
import os
import glob
import imageio
import cv2
import numpy as np
from torch.utils.data import Dataset, DataLoader
# ๆฅ่ช sr_utils
def im_to_batch(im, sub_im_hw=(640, 640)):
'''
่พๅ
ฅไธๅผ ๅพๅ๏ผ่พๅบๅๅๅพๅๅบๅ
:param im: np.array [h, w, c]
:param sub_im_hw: ๅๅๅคงๅฐ
:return:
'''
ori_hw = im.sh... | StarcoderdataPython |
15214 | from os import path
import autolens as al
import autolens.plot as aplt
from test_autogalaxy.simulators.imaging import instrument_util
test_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "..", "..")
def pixel_scale_from_instrument(instrument):
"""
Returns the pixel scale from... | StarcoderdataPython |
4800618 | import keras.backend as K
import numpy as np
import matplotlib.pylab as plt
import cPickle as pickle
import sys
import os
def find_top9_mean_act(data, Dec, target_layer, feat_map, batch_size=32):
"""
Find images with highest mean activation
args: data (numpy array) the image data
shape : (n_s... | StarcoderdataPython |
4806321 | import cv2
import scipy
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from datetime import datetime
from pprint import pprint
from skimage import transform
from utils import detect_faces, detect_landmarks, generate_embedding, recognize
output_path = 'outputs'
test_file = 'videos/ongiocaud... | StarcoderdataPython |
62881 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from perlin import generate_perlin
def gaussian_2d_fast(size, amp, mu_x, mu_y, sigma):
x = np.arange(0, 1, 1/size[0])
y = np.arange(0, 1, 1/size[1])
xs, ys = np.meshgrid(x,y)
dxs = np.minimum(np.abs(xs-mu_x), 1-np.abs(xs-mu_x)... | StarcoderdataPython |
1783457 | <gh_stars>1-10
# Copyright 2019 <NAME> (<EMAIL>)
# ---------------------------
# Distributed under the MIT License:
# ==================================
# 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... | StarcoderdataPython |
4815730 | import torch
import numpy as np
import torch.nn as nn
from torch.nn import functional as F
__all__ = ['BCELoss', 'BalancedBCELoss',
'DiceLoss', 'BCEDiceLoss', 'GeneralizedDiceLoss',
'BinaryFocalLoss',
'TverskyLoss']
# todo: ๅญฆไน ไธไธ https://github.com/LIVIAETS/surface-loss/blob/maste... | StarcoderdataPython |
1602146 | start, end = map(int, input().split())
if start == end:
print('O JOGO DUROU 24 HORA(S)')
elif start > end:
time = (24 - start) + end
if time >= 24:
day = time // 24
hours = time % 24
print(day, 'JOGO DUROU', hours, 'HORA(S)')
else:
print('O JOGO DUROU', time, 'H... | StarcoderdataPython |
1781783 | <gh_stars>0
# Generated by Django 3.1.4 on 2021-03-21 19:09
from django.db import migrations, models
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('flex', '0007_auto_20210321_1830'),
]
operations = [
migrations.AddField(
model_name='form... | StarcoderdataPython |
1609257 | # Copyright 2021 The Cirq Developers
#
# 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 agreed to in ... | StarcoderdataPython |
1767929 | <filename>02-Libraries-Implementation/csv/MergeCSV.py<gh_stars>1-10
import csv
def merge_csv(csv_list, output_path):
fieldnamese = list()
for file in csv_list:
with open(file, 'r') as input_csv:
fn = csv.DictReader(input_csv).fieldnames
fieldnamese.extend(x for x in fn if x not... | StarcoderdataPython |
440 | #!/usr/bin/env python
# -*- coding: utf-8 -*
import os
from setuptools import find_packages, setup
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
with open('requirements.txt') as f:
install_requires = f.read().splitlines()
setup(
name... | StarcoderdataPython |
87469 | <filename>plasma/child_chain/child_chain.py
import rlp
from ethereum import utils
from web3 import Web3
import json
from plasma.utils.utils import unpack_utxo_pos, get_sender, recoverPersonalSignature
from .block import Block
from .exceptions import (InvalidBlockMerkleException,
InvalidBlockSi... | StarcoderdataPython |
1624940 | <reponame>eldorbekpulatov/textractor<filename>app.py
# importing required modules
import os
import random
import textract
from flask import Flask, request, render_template, redirect, url_for
app = Flask(__name__)
UPLOAD_FOLDER = 'tmp/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# allow files of a s... | StarcoderdataPython |
31497 | <reponame>storagebot/readthedocs.org
import os
import shutil
import codecs
import logging
import zipfile
from django.template import Template, Context
from django.contrib.auth.models import SiteProfileNotAvailable
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from builds impor... | StarcoderdataPython |
3333066 | <reponame>Nv7-GitHub/mold
def read(file):
with open(file) as f:
return f.read() | StarcoderdataPython |
67249 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2014 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | StarcoderdataPython |
3270475 | <reponame>dadito6/juego_memoria<gh_stars>0
import PySimpleGUI as sg
from src.GUI import board
from src.Controllers import config_theme as theme, Usuario , matriz
""" Aqui se trabajara la logica del tablero"""
def start(username):
window = loop(username)
window.close()
def loop(username):
datos=Usuario.ge... | StarcoderdataPython |
3254378 | <filename>src/background.py
# Copyright (C) 2022 viraelin
# License: MIT
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
class Background(QGraphicsRectItem):
def __init__(self) -> None:
super().__init__()
self.setZValue(-1000)
size = 800000
siz... | StarcoderdataPython |
39363 | <reponame>csb6/libtcod-ada<filename>third_party/libtcod/.ci/conan_build.py<gh_stars>100-1000
#!/usr/bin/env python3
"""Build script for conan-package-tools:
https://github.com/conan-io/conan-package-tools
"""
import os
import subprocess
from cpt.packager import ConanMultiPackager
try:
version = subprocess.check_... | StarcoderdataPython |
152534 | import frappe
from erpnext.compliance.utils import get_default_license
from frappe.modules.utils import sync_customizations
def execute():
sync_customizations("bloomstack_core")
compliance_info = frappe.get_all('Compliance Info', fields=['name'])
if not compliance_info:
return
sales_orders = frappe.get_all("S... | StarcoderdataPython |
50658 | <reponame>rwst/wikidata-molbio
import pronto, six, csv, os, json, argparse, sys, datetime
"""
Uses eyeballed A004.txt. Cleans and moves all items chunkwise (CHUNKSIZE).
"""
CHUNKSIZE = 10
# Initiate the parser
parser = argparse.ArgumentParser()
# Read arguments from the command line
args = parser.parse_args()
# Che... | StarcoderdataPython |
11734 | import re
import time
from lemoncheesecake.events import TestSessionSetupEndEvent, TestSessionTeardownEndEvent, \
TestEndEvent, SuiteSetupEndEvent, SuiteTeardownEndEvent, SuiteEndEvent, SteppedEvent
from lemoncheesecake.reporting.report import ReportLocation
DEFAULT_REPORT_SAVING_STRATEGY = "at_each_failed_test"
... | StarcoderdataPython |
3288871 | import csv
with open('data/lean1.csv', 'rb') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
genre_count[row[0]][row[1]] += 1 | StarcoderdataPython |
1604677 | from __future__ import annotations
from typing import Any
import enum
class EnumMeta(enum.EnumMeta):
def __repr__(cls) -> str:
return f"{cls.__name__}[{', '.join([f'{member.name}={repr(member.value)}' for member in cls])}]"
def __str__(cls) -> str:
return cls.__name__
def __call__(cls, ... | StarcoderdataPython |
115166 | """PreProcess Data
Process data for training.
.. helpdoc::
This widget pre-processes data so that it can be more efficiently used in prediction. This involves removing predictors with near zero variance (using nearZeroVar()), predictors with high correlation (using findCorrelation()), and reducing predictors ... | StarcoderdataPython |
1764795 | from pyexpat import features
from darts.models.forecasting.gradient_boosted_model import LightGBMModel
import wandb
from darts.models import TCNModel
import pandas as pd
from darts.metrics import mape, mae
from darts import TimeSeries
from darts.dataprocessing.transformers import Scaler
from copy import deepcopy
import... | StarcoderdataPython |
3218328 | # Source Server Stats
# File: sourcestats/util/__init__.py
# Desc: general utilities
from hashlib import sha1
import requests
from flask import jsonify, abort
SOURCE_APPS = None
def get_source_apps():
global SOURCE_APPS
if SOURCE_APPS is None:
response = requests.get('http://api.steampowered.com/I... | StarcoderdataPython |
1635722 | # python3 compatibity while retaining checking
# for both str and unicode in python2
try:
string_types = (str, unicode)
except NameError:
string_types = (str,)
def is_string_type(val):
return isinstance(val, string_types)
try:
# python3
from functools import reduce
except NameError:
pass
reduc... | StarcoderdataPython |
1761244 | <gh_stars>0
from setuptools import setup
setup(
name='ppmp',
version='1.0.1',
description='Prediction of Perturbations of Modular Protein structures by triplet analysis',
author='<NAME>',
author_email='<EMAIL>',
packages=['ppmp'],
install_requires=['matplotlib', 'numpy', 'pandas', 'seaborn', 'scip... | StarcoderdataPython |
4834571 | <filename>tests/test_fms_api_match_details_parser.py
import json
from datetime import datetime
import unittest2
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from datafeeds.parsers.fms_api.fms_api_match_parser import FMSAPIMatchDetailsParser
class TestFMSAPIEventListParser(unittest2... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.