id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1770687 | <reponame>remram44/d3m-primitives
import numpy as np
from rpi_d3m_primitives.featSelect.helperFunctions import normalize_array, joint
from rpi_d3m_primitives.featSelect.mutualInformation import mi, joint_probability
"""---------------------------- CONDITIONAL MUTUAL INFORMATION ----------------------------"""
def m... | StarcoderdataPython |
4811282 | import json
import discord
import logging
from random_message import *
from util.decorator import only_owner
logger = logging.getLogger("Link")
def load_link_file():
try:
with open("private/link.data", 'r') as fd:
return json.loads(fd.read())
except:
logger.error("IMPOSSBILE DE LOA... | StarcoderdataPython |
177951 | <gh_stars>0
"""
Complete the function that accepts a string parameter,
and reverses each word in the string. All spaces in
the string should be retained.
Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
"""
def reverse_words(text):
str_list = []
for word in text.... | StarcoderdataPython |
3381051 | import pandas as pd
import numpy as np
df = pd.read_csv('csv/rest.csv')
df = df[['names', 'category', 'rating', 'reviews', 'cost', 'cuisine', 'featured', 'location','urls']]
# print(type(df['featured'][1])) # its a string, not a list. convert to list by split.
df['names'] = df['names'].apply(lambda x : x.strip())
... | StarcoderdataPython |
3346653 | <filename>scraper/storage_spiders/chihienvn.py
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='box-content']/div[@class='box-header']/h1",
'price' : "//div[@class='prod... | StarcoderdataPython |
1795274 | <gh_stars>10-100
from lookup import files as lookup_files
from ui.read import x as ui_read
from core.read import read as core_read
from ui.read import plasma_selection
from api.plasma import open as opener
def goto_selection(view):
read_view = ui_read.all(view)
plasmas = core_read.plasmas(read_view.ptext)
... | StarcoderdataPython |
178588 | import numpy as np
from scipy import ndimage
'''
See paper: Sensors 2018, 18(4), 1055; https://doi.org/10.3390/s18041055
"Divide and Conquer-Based 1D CNN Human Activity Recognition Using Test Data Sharpening"
by <NAME> & <NAME>
This code loads and sharpens UCI HAR Dataset data.
UCI HAR Dataset data can be download... | StarcoderdataPython |
3352768 | <gh_stars>0
# Copyright (c) 2006-2010 <NAME> http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
# All rights reserved.
#
# 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 withou... | StarcoderdataPython |
78130 | import os
import argparse
import matplotlib.pyplot as plt
from datetime import datetime, timedelta, date
import nottingham_covid_modelling.lib.priors as priors
import numpy as np
import pints
from nottingham_covid_modelling import MODULE_DIR
# Load project modules
from nottingham_covid_modelling.lib._command_line_args... | StarcoderdataPython |
3396472 | import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
background = pygame.Surface(screen.get_size())
background.fill((255, 255, 255))
sprite = pygame.image.load("mario.png")
x=150
y=150
clock = pygame.time.Clock()
while 1:
clock.tick(40)
pygame.event.pump()
keyinput = pygame.key.get... | StarcoderdataPython |
192253 | <filename>caffe-dslt/examples/test.py
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 1 22:05:35 2016
@author: luxiankai
"""
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
# Make sure that caffe is on the python path:
caffe_root = '../' # this file is expected to be in {caffe_root}/examples
i... | StarcoderdataPython |
17167 | <filename>wxtbx/wx4_compatibility.py
from __future__ import absolute_import, division, print_function
'''
Author : Lyubimov, A.Y.
Created : 04/14/2014
Last Changed: 11/05/2018
Description : wxPython 3-4 compatibility tools
The context managers, classes, and other tools below can be used to make the
GUI code ... | StarcoderdataPython |
1680123 | from octopus.engine.explorer import Explorer
from requests.exceptions import ConnectionError as RequestsConnectionError
import json
EOS_DEFAULT_RPC_PORT = 8888
EOS_WALLET_RPC_PORT = 8889
class EosExplorer(Explorer):
"""
EOS REST RPC client class
doc: https://eosio.github.io/eos/group__eosiorpc.html
... | StarcoderdataPython |
1674552 | #
# The Python Imaging Library.
# $Id$
#
# package placeholder
#
# Copyright (c) 1999 by Secret Labs AB.
#
# See the README file for information on usage and redistribution.
#
# ;-)
| StarcoderdataPython |
4826917 | # EMACS settings: -*- tab-width: 2; indent-tabs-mode: t; python-indent-offset: 2 -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
# ==============================================================================
# Authors: <NAME>
#
# Python functions: ... | StarcoderdataPython |
4820377 | <reponame>webdev188/tytus<gh_stars>10-100
usuarios = [
{"name":"Admin", "password":"<PASSWORD>"}
] | StarcoderdataPython |
3216836 | <reponame>Erick0212/thedefender
import random
import json
from pygame.locals import *
import os
import pygame
import pygameMenu
from pygameMenu.locals import *
WIDTH = 900
HEIGHT = 700
FPS = 60
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.mixer.init()
screen = pygame.display.set_mode((... | StarcoderdataPython |
82206 | #!/usr/bin/python3 -S
# -*- coding: utf-8 -*-
import unittest
import pickle
import copy
from cargo import aliased, Model
from cargo.fields import Field
from unit_tests import configure
class Tc(object):
def __init__(self, field):
self.field = field
class FieldModel(Model):
field = Field()
class... | StarcoderdataPython |
1611507 | <reponame>vumichien/hummingbird
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------... | StarcoderdataPython |
70373 | from django.views.decorators.http import require_http_methods
from graphene_django.views import GraphQLView
@require_http_methods(['POST'])
def graphql_view(request):
from graph_wrap.tastypie import schema
schema = schema()
view = GraphQLView.as_view(schema=schema)
return view(request)
| StarcoderdataPython |
93529 | <filename>pipeline2/modules/preprocess.py
import json
import os
from typing import List, Any, Union, Iterator, Tuple
from natsort import natsorted
# noinspection PyTypeChecker
from pandas import DataFrame, Index, Series
from pandas.core.arrays import ExtensionArray
from pandas.core.generic import NDFrame
from pandas.i... | StarcoderdataPython |
41508 | <filename>test_bot/cogs/misc.py
import io
from base64 import b64decode
import disnake
from disnake.ext import commands
class Misc(commands.Cog):
def __init__(self, bot):
self.bot: commands.Bot = bot
def _get_file(self, description: str) -> disnake.File:
# just a white 100x100 png
dat... | StarcoderdataPython |
1716455 | import unittest2 as unittest
import os
import datetime
class HouseKeeping(unittest.TestCase):
def test_license_year(self):
self.assertTrue(os.path.exists('LICENSE.txt'))
now = datetime.datetime.now()
current_year = datetime.datetime.strftime(now, '%Y')
license_text = open('LICENSE... | StarcoderdataPython |
148267 | <reponame>chandojo/climbbeta<filename>video/management/commands/loadvideos.py
from django.core import management
from django.core.management.base import BaseCommand, CommandError
from django.core.management.commands import loaddata
from datetime import date
class Command(BaseCommand):
help = "Uploads video fixture... | StarcoderdataPython |
3228580 | RALI_LIB_NAME = 'librali.so'
from enum import Enum
from enum import IntEnum
class ColorFormat(Enum):
IMAGE_RGB24 = 0
IMAGE_BGR24 = 1
IMAGE_U8 = 2
class Affinity(Enum):
PROCESS_GPU = 0
PROCESS_CPU = 1
class TensorLayout(Enum):
NHWC = 0
NCHW = 1
class TensorDataType(IntEnum):
FLOAT32 = 0
F... | StarcoderdataPython |
96043 | from collections import Counter, namedtuple
from itertools import product
from operator import attrgetter
from random import randint
init_possible_codes = set(product([1, 2, 3, 4, 5, 6], repeat=4))
Feedback = namedtuple('Feedback', ['blacks', 'whites'])
ScoreData = namedtuple('ScoreData', ['guess', 'score', 'is_poss... | StarcoderdataPython |
98022 | <gh_stars>1-10
from .AggregateMatrix import AggregateMatrix as aggregate_matrix
| StarcoderdataPython |
4801935 |
from model.contact import Contact
from random import randrange
import random
def test_edit_contact(app,db, check_ui):
if app.contact.count_contact() == 0: # falls keine Gruppe gibt´s
app.contact.create_contact(Contact(firstname_of_contact="test_firstna... | StarcoderdataPython |
197908 | <filename>onlinejudge/implementation/command/test.py
# Python Version: 3.x
import onlinejudge
import onlinejudge.implementation.utils as utils
import onlinejudge.implementation.logging as log
import onlinejudge.implementation.command.utils as cutils
import sys
import os
import os.path
import re
import glob
import color... | StarcoderdataPython |
3367396 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
3207642 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'kute'
# __mtime__ = '2016/12/24 20:45'
"""
多线程,协称 执行器
"""
import os
import attr
import gevent
from gevent import monkey
from gevent.pool import Pool
monkey.patch_all()
def valide_func(instance, attribute, value):
if not callable(value):
... | StarcoderdataPython |
1776048 | #
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. T... | StarcoderdataPython |
1730333 | import json
import pytest
from rest_framework import status
QUERY_URL = "/api/v3/genotype_browser/query"
pytestmark = pytest.mark.usefixtures(
"wdae_gpf_instance", "dae_calc_gene_sets")
def test_simple_query_variants_preview(db, admin_client, remote_settings):
data = {
"datasetId": "TEST_REMOTE_io... | StarcoderdataPython |
12393 | <reponame>Ublimjo/nwt
def task_clean_junk():
"""Remove junk file"""
return {
'actions': ['rm -rdf $(find . | grep pycache)'],
'clean': True,
}
| StarcoderdataPython |
1731865 | import os
import sipconfig
from PyQt4 import pyqtconfig
from distutils import sysconfig
vcs_so = '%s/vcs/_vcs.so' % sysconfig.get_python_lib()
vcs_inc = '%s/vcs/Include' % sysconfig.get_python_lib()
## vcs_so = '/Users/hvo/src/uvcdat/cdatBuild/lib/python2.7/site-packages/vcs/_vcs.so'
## vcs_inc = '/Users/hvo/src/uv... | StarcoderdataPython |
4829623 | <filename>examples/launch_moasha_instance_tuning.py
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.ap... | StarcoderdataPython |
36238 | <gh_stars>0
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if len(nums) < 3:
return []
ans = []
nums.sort()
for i in range(0, len(nums)-2):
if nums[i] > 0:
break
if i > 0 and nums[i-1] == nums[i]:
... | StarcoderdataPython |
1779114 | # -*- coding: utf-8 -*-
from openprocurement.api.utils import (
json_view,
opresource,
APIResource,
ROUTE_PREFIX,
context_unpack
)
from openprocurement.tender.core.utils import save_tender, optendersresource
from openprocurement.relocation.core.utils import change_ownership
from openprocurement.relo... | StarcoderdataPython |
4838788 | try:
from workers_defaults import sink_instance, sender_instance
except:
sink_instance = {
'ami': 'ami-915394eb',
'first_ip': '10.0.17.0',
'security': ['sg-21d88f5c'], # nosec
'net_subnet': 'subnet-3557de19',
'instance_type': 't2.micro',
'key_name': 'gate',
... | StarcoderdataPython |
64475 | from abc import ABC, abstractmethod
import asyncio
from typing import (
AsyncIterator,
Tuple,
)
from cancel_token import (
CancelToken,
OperationCancelled,
)
from eth.constants import GENESIS_BLOCK_NUMBER
from eth.exceptions import (
HeaderNotFound,
)
from eth_typing import (
BlockNumber,
... | StarcoderdataPython |
1754132 | import math
import sys
def main():
a, b, k = map(int, sys.stdin.readline().split())
query_range = range(a, b + 1)
query_range = list(query_range)
print("なんだこのバグ")
exit()
if a == b:
res = query_range
elif k >= math.ceil((b - a + 1) / 2):
res = query_range
... | StarcoderdataPython |
1666791 | <gh_stars>0
import pprint
import scipy
import scipy.linalg # SciPy Linear Algebra Library
import numpy as np
a = np.matrix([ [1, 2, 3], [2, 3, 4], [1, 2, 5] ])
k = scipy.array([ [8, 2, 9], [4, 9, 4], [6, 7, 9] ])
#print("Secret key is ")
#print(k)
P, L, U = scipy.linalg.lu(k)
#print ("A:")
#pprint.pprint(... | StarcoderdataPython |
1711273 | <reponame>Catalyst9k-SLA/Cat9k
# Importing the variable file in the dir Variable
import sys
import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
dirParent = os.path.dirname(currentdir)
dirVariable = dirParent + "/Variables"
sys.path.insert(0, dirVariable)
from... | StarcoderdataPython |
195611 | <gh_stars>10-100
# encoding: utf-8
import xadmin
from xadmin.views import BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView
from DjangoUeditor.models import UEditorField
from DjangoUeditor.widgets import UEditorWidget
from django.conf import settings
class XadminUEditorWidget(UEditorWidget):
... | StarcoderdataPython |
3353409 | <reponame>velovix/debutizer<gh_stars>1-10
import re
from pathlib import Path
from typing import List
def find_binary_packages(path: Path, recursive: bool = False) -> List[Path]:
return _glob_search(path, BINARY_PACKAGE_GLOB, recursive)
def find_debian_source_files(path: Path, recursive: bool = False) -> List[Pa... | StarcoderdataPython |
3284153 | def solvepart1():
freq = 0
with open('inputs/day1.txt') as f:
for i in f:
freq += int(i)
return freq
def solvepart2():
freq = 0
seen_freqs = set([freq])
while True:
with open('inputs/day1.txt') as f:
for i in f:
freq += int(i)
if freq in seen_freqs:
return freq
seen_freqs.add(freq)
r... | StarcoderdataPython |
3228228 | from tensorflow.keras.layers import Conv2D
def RPN(inputs, k):
x = Conv2D(256, kernel_size=(3, 3), activation='relu')(inputs)
cls = Conv2D(2 * k, kernel_size=(1, 1))(x)
reg = Conv2D(4 * k, kernel_size=(1, 1))(x)
return [cls, reg]
| StarcoderdataPython |
149907 | <filename>practice/src/decorator/class/cached_property.py
# -*- coding: utf-8 -*-
#
# © 2011 <NAME>, MIT License
#
#引数ありクラスデコレータ
import time
import random
class cached_property(object):
"""Decorator for read-only properties evaluated only once within TTL period.
It can be used to created a cached property l... | StarcoderdataPython |
6903 | <reponame>RomanMahar/personalsite
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-02-06 16:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0028_merge... | StarcoderdataPython |
1779410 | <gh_stars>0
"""Bazel rule for loading external repository deps for J2CL."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
_IO_BAZEL_RULES_CLOSURE_VERSION = "master"
def load_j2cl_repo_deps():
http_archive(
name = "io_bazel_rules_closure",
strip_prefix = "rules_closure-%s" % _IO_BAZEL... | StarcoderdataPython |
3277285 | <filename>bugtests/test373.py
"""
Test for bug [608628] long(java.math.BigInteger) does not work.
"""
import support
# local name bugtests/test381.py
ns = '10000000000'
import java
ns2 = str(long(java.math.BigInteger(ns)))
assert ns == ns2, ns2
| StarcoderdataPython |
1673712 | <reponame>kundajelab/chip-nexus-pipeline
#!/usr/bin/env python
# ENCODE DCC filter wrapper
# Author: <NAME> (<EMAIL>)
import sys
import os
import argparse
import multiprocessing
from encode_common_genomic import *
def parse_arguments():
parser = argparse.ArgumentParser(prog='ENCODE DCC filter.',
... | StarcoderdataPython |
3352855 | <reponame>uktrade/enav-alpha<gh_stars>0
from django.contrib import admin
from .models import Market, Article
admin.site.register(Market)
admin.site.register(Article)
| StarcoderdataPython |
3349828 | <filename>checkov/kubernetes/parser/parser.py<gh_stars>0
import logging
from yaml import YAMLError
from checkov.kubernetes.parser import k8_yaml, k8_json
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
logger = logging.getLogger(__name__)
def parse(filename):
... | StarcoderdataPython |
20359 | <gh_stars>0
import os
import warnings
from dotenv import find_dotenv, load_dotenv
from yacs.config import CfgNode as ConfigurationNode
from pathlib import Path
# Please configure your own settings here #
# YACS overwrite these settings using YAML
__C = ConfigurationNode()
### EXAMPLE ###
"""
# data augmentation par... | StarcoderdataPython |
1742873 | <filename>pydm/widgets/baseplot.py
import functools
from qtpy.QtGui import QColor, QBrush
from qtpy.QtCore import Signal, Slot, Property, QTimer, Qt
from .. import utilities
from pyqtgraph import PlotWidget, PlotDataItem, mkPen, ViewBox, InfiniteLine, SignalProxy, CurvePoint, TextItem
from collections import OrderedDic... | StarcoderdataPython |
3303865 | # Generated by Django 3.1.5 on 2021-03-07 16:32
from django.db import migrations, models
import django_gotolong.uploaddoc.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UploadDocModel',
fi... | StarcoderdataPython |
3348453 | <reponame>smnarayanan/slimbootloader
## @file
# Create makefile for MS nmake and GNU make
#
# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
## Import Modules
#
from __future__ import print_function
from __future__ import absolute_import
impo... | StarcoderdataPython |
45764 | #!/usr/bin/python
import simple_test
simple_test.test("test29", ["-h", ])
| StarcoderdataPython |
3315538 | # !/usr/bin/env python
from playhouse.migrate import migrate
from fsb import logger
from fsb.db import base_migrator
from fsb.db.models import Chat
from fsb.db.models import Member
from fsb.db.models import MemberRole
from fsb.db.models import QueryEvent
from fsb.db.models import Rating
from fsb.db.models import Rati... | StarcoderdataPython |
1764026 | <gh_stars>0
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from tracker import views
urlpatterns = patterns('tracker.views',
url(regex=r'^new_char/$',
view=views.CharacterCreateView.as_view(),
name='new_char'),
url(regex=r'^chars/$',
view=views.CharacterLis... | StarcoderdataPython |
1721792 | <reponame>Sithlord-dev/Dog_vision<gh_stars>0
from __future__ import division, print_function
# coding=utf-8
import os
# Keras
from keras.models import model_from_json
# Flask utils
from flask import Flask, request, render_template
from werkzeug.utils import secure_filename
from model_files.ml_model import make_predic... | StarcoderdataPython |
3267063 | <gh_stars>0
import torch.utils.data as data
#import h5py
import numpy as np
import os
from glob import glob
from pyntcloud import PyntCloud
import numpy as np
from sklearn.neighbors import KDTree
from utils import hand
from utils.config import config
from utils.database import *
import torch
class ModelNetDataset(dat... | StarcoderdataPython |
3224987 | # Test data is contained in goldens.json. This is an array of objects, with
# keys:
#
# - original_code
# - new_code
# - original_tests
# - new_tests
#
# The tests load this file, and then verify that calling fixup_* functions
# on the original_* data returns the same values as in the new_* data.
#
# To generate go... | StarcoderdataPython |
1747295 | #!/usr/bin/env python
#
# Copyright 2015 Airbus
# Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
#
# 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 |
1714828 | s1 = "<KEY>"
s2 = "<KEY>"
# take 2 strings s1 and s2 including only letters from ato z.
# Return a new sorted string, the longest possible, containing distinct letters
# This version is using bitwise
def longest(s1, s2):
visited = 0
s = s1 + s2
result = ""
for i in range(len(s)):
shift = ord(s[... | StarcoderdataPython |
3394923 | import os
import sys
import subprocess
import pickle
import time
import pandas as pd
import numpy as np
from datetime import datetime
from scipy.sparse import csr_matrix
from implicit.als import AlternatingLeastSquares
class Recommender:
def __init__(self, **args):
self.TRAINING_THREADS = int(args.get("training_... | StarcoderdataPython |
73264 | import asyncio
import random
import pytest
import uuid
from collections import defaultdict
import aiotask_context as context
@asyncio.coroutine
def dummy3():
yield from asyncio.sleep(random.uniform(0, 2))
return context.get("key")
@asyncio.coroutine
def dummy2(a, b):
yield from asyncio.sleep(random.un... | StarcoderdataPython |
1786476 | <filename>src_2/server/batch_server.py<gh_stars>0
# Copyright 2015 gRPC 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 ... | StarcoderdataPython |
3265738 | <reponame>osmante/freeCodeCamp_Courses
import tensorflow as tf
import numpy as np
def predict_with_model(model, imgpath):
"""
Predict an image to which class it belongs
Parameters:
model: tensorflow model
imgpath: to be predicted image path (str)
Returns:
prediction: predicted... | StarcoderdataPython |
1638858 | <gh_stars>1-10
class RoutingRulesAdditionalFields:
USERS = "users"
CASE_TYPES = "case_types"
FLAGS = "flags"
COUNTRY = "country"
choices = [
(USERS, "Users"),
(CASE_TYPES, "Case Types"),
(FLAGS, "flags"),
(COUNTRY, "Country"),
]
class StatusAction:
DEACTIVA... | StarcoderdataPython |
3218586 | <filename>demos/kitchen_sink/main.py
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.path.abspath(__file__).split('demos')[0])
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.pro... | StarcoderdataPython |
3370382 | import json
from pathlib import Path
import re
import questionary
from questionary import Choice
from rich.console import Console
from dbt_coves.tasks.base import BaseConfiguredTask
from dbt_coves.utils.jinja import render_template, render_template_file
console = Console()
NESTED_FIELD_TYPES = {
"SnowflakeAdap... | StarcoderdataPython |
3292574 | <filename>language/bert/sequene_parallel/loss_func/cross_entropy.py
from colossalai.context.parallel_mode import ParallelMode
import torch
from torch.cuda.amp import custom_bwd, custom_fwd
class _VocabCrossEntropy(torch.autograd.Function):
@staticmethod
@custom_fwd
def forward(ctx, vocab_parallel_logits,... | StarcoderdataPython |
1771653 | <reponame>sdpython/code_beatrix<gh_stars>1-10
"""
@brief test log(time=1s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from code_beatrix.ipythonhelper.magic_scratch import MagicScratch
from code_beatrix.jsscripts.nbsnap import RenderSnap
class TestMagicSnap(unittest.TestCase):
def... | StarcoderdataPython |
4835043 | <reponame>CopenhagenCityArchives/CorrectOCR<filename>CorrectOCR/setup.py
from setuptools import setup
setup(
name='CorrectOCR',
version='',
packages=['', 'tokens', ''],
package_dir={'': 'CorrectOCR'},
url='https://github.com/CopenhagenCityArchives/CorrectOCR',
license='CC-BY-4.0',
author='<NAME>',
author_email... | StarcoderdataPython |
1737398 | # Generated by Django 3.1.5 on 2021-02-14 11:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20210214_0842'),
]
operations = [
migrations.CreateModel(
name='BankInfo',
... | StarcoderdataPython |
194409 | from __future__ import absolute_import
__all__ = ('Device', )
from sentry.interfaces.base import Interface, InterfaceValidationError
from sentry.utils.safe import trim, trim_dict
class Device(Interface):
"""
An interface which describes the device.
>>> {
>>> "name": "Windows",
>>> "vers... | StarcoderdataPython |
1756926 | import discord
from discord.ext import commands
from utils.configManager import BotConfig
class HelpCommand(commands.HelpCommand):
def __init__(self):
super().__init__()
self.botConfig = BotConfig()
async def send_bot_help(self, mapping):
helpMessage = discord.Embed(
title... | StarcoderdataPython |
4814731 | from os import name, system
from variables import *
# define global variables
inventory = {
"health": 10,
"money": 10,
"social": 10,
"fame": 10,
}
scenarios = [
scenario01,
scenario02,
scenario03,
scenario04,
scenario05,
scenario06,
scenario07,
scenario08,
]
def clear... | StarcoderdataPython |
3340579 | import wikipedia
import cPickle as pickle
import string
from csv import DictReader, DictWriter
import re
import nltk
"""
This class is used to fetch articles from wiki and dump it locally so that the runtime for the program is reduced.
"""
class ArticleDump:
def web_lookup(self):
"""
... | StarcoderdataPython |
3265371 | from meltano.core.plugin import PluginInstall, PluginType
class ModelPlugin(PluginInstall):
__plugin_type__ = PluginType.MODELS
def __init__(self, *args, **kwargs):
super().__init__(self.__class__.__plugin_type__, *args, **kwargs)
| StarcoderdataPython |
188570 | import pytest
from werkzeug.exceptions import BadRequest, InternalServerError
# Link Controller
from abitly.services.link.controller import (validate_request_body,
get_generated_url,
get_original_url)
def test_validate_request_... | StarcoderdataPython |
1680326 | <filename>nmtg/modules/loss.py
import torch
from torch import nn, Tensor
class NMTLoss(nn.Module):
def __init__(self, output_size, padding_idx, label_smoothing=0.0):
super().__init__()
self.output_size = output_size
self.padding_idx = padding_idx
self.label_smoothing = label_smooth... | StarcoderdataPython |
1660002 | """Credit to <NAME>:
https://github.com/MilesCranmer/easy_normalizing_flow/blob/master/flow.py
"""
import torch
from torch import nn, optim
from torch.functional import F
import numpy as np
####
# From Karpathy's MADE implementation
####
DEBUG = False
class MaskedLinear(nn.Linear):
""" same as Linear except has... | StarcoderdataPython |
152549 | # Time: O(n^2 * 2^n)
# Space: O(1)
# brute force, bitmask
class Solution(object):
def maximumGood(self, statements):
"""
:type statements: List[List[int]]
:rtype: int
"""
def check(mask):
return all(((mask>>j)&1) == statements[i][j]
for i ... | StarcoderdataPython |
182076 | <gh_stars>0
n = int(input('Informe um número entre 0 e 9999: ').strip())
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print(f'Analisando o número {n}...')
print('Unidade: {}'.format(u))
print('Dezena: {}'.format(d))
print('Centena: {}'.format(c))
print('Milhar: {}'.format(m))
| StarcoderdataPython |
1700882 | class UserProfile:
pass
# trailing comment
#leading comment
#noinspection PyUnusedLocal
def foo(sender):
pass
| StarcoderdataPython |
4809727 | import argparse
from picamera import PiCamera
from aiy.vision.inference import CameraInference
from aiy.vision.models import face_detection
from aiy.vision.annotator import Annotator
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from environs import Env
import urllib.request,... | StarcoderdataPython |
19544 | #!/usr/bin/python
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for ... | StarcoderdataPython |
192892 | <gh_stars>10-100
#!/usr/bin/python3
from botbase import *
_traunstein_cc = re.compile(r"([0-9.]+) Neuinfektionen")
_traunstein_c = re.compile(r"insgesamt ([0-9.]+) bestätigte Fälle")
_traunstein_g = re.compile(r"genesen gelten mindestens ([0-9.]+) Personen \(([0-9.]+) Personen mehr")
_traunstein_d = re.compile(r"insge... | StarcoderdataPython |
3299959 | <gh_stars>1-10
"""Abstract base classes and default types"""
import copy
from abc import ABC, abstractmethod
from enum import Enum
from threading import Event
from typing import List, Dict
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QWidget
from solarviewer.config import content_ctrl_name
f... | StarcoderdataPython |
1662647 | <gh_stars>1-10
import os
import uuid
from typing import Dict
import pandas as pd
import matplotlib.pyplot as plt
COLUMN_OF_INTEREST = 'g:send' # to be changed to 'roundtrip' once issue is fixed
def clean_dataframe(file_path: str = 'routes.parquet') -> pd.DataFrame:
routes_df = pd.read_parquet(file_path)
# D... | StarcoderdataPython |
4833254 | import pandas as pd
from random import randint
import os
import time
transactions = pd.read_csv('stream.csv', header='infer', sep=',')
output_directory = 'output'
i = 0
while True:
# number of simultaneous transactions
simultaneous = randint(1, 150)
subset = transactions.iloc[i:i+simultaneous]
f... | StarcoderdataPython |
3209983 | t = int(input());
while t > 0:
companies = input().split(' ');
x , y = input().split(' ');
selx = 0;
sely = 0;
for i in range(3):
if( x == companies[i]):
selx = i;
if( y == companies[i]):
sely = i;
if(selx < sely):
print( companies[sel... | StarcoderdataPython |
3296836 | <filename>language/threading/13_lazy_connection.py<gh_stars>1-10
import threading
from socket import socket, AF_INET, SOCK_STREAM
from functools import partial
class LazyConnection:
def __init__(self, address, family=AF_INET, type_=SOCK_STREAM):
self.address = address
self.family = family
... | StarcoderdataPython |
3383969 | from posixpath import basename, join
from copy import copy, deepcopy
from io import BytesIO
import sys
import numpy as np
from dataflow.lib.uncertainty import Uncertainty
# Action names
__all__ = [] # type: List[str]
# Action methods
ALL_ACTIONS = [] # type: List[Callable[Any, Any]]
IS_PY3 = sys.version_info[0] >= ... | StarcoderdataPython |
1778894 | #!/usr/bin/env python
from gimpfu import *
from math import pow, sqrt
from gimpcolor import RGB
def euclidean_distance(point_one, point_two):
""" Calculate the euclidean distance.
Args:
point_one (tuple)
point_two (tuple)
Returns:
float: the distance between t... | StarcoderdataPython |
119956 | <filename>api/artifacts.py<gh_stars>0
from flask import request
from hurry.filesize import size
from ...shared.utils.restApi import RestResource
from ...shared.connectors.minio import MinioClient
from ...shared.utils.api_utils import build_req_parser, upload_file
class Artifacts(RestResource):
delete_rules = (
... | StarcoderdataPython |
106052 | import requests
from urllib.parse import urljoin, urlencode
from .utils import flatten
class APIKeyMissingError(Exception):
pass
class CFLApi(object):
def __init__(self, apiKey, baseUri='http://api.cfl.ca'):
if apiKey == None:
raise APIKeyMissingError(
"An API Key is requir... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.