id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1718594 | <reponame>alexey-anufriev/intellij-community<filename>python/testData/resolve/multiFile/tryExceptMultilineNamespace/root1/pkg/__init__.py<gh_stars>1-10
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__) | StarcoderdataPython |
134417 |
"""
class TestNewOffsets(unittest.TestCase):
def test_yearoffset(self):
off = lib.YearOffset(dayoffset=0, biz=0, anchor=datetime(2002,1,1))
for i in range(500):
t = lib.Timestamp(off.ts)
self.assert_(t.day == 1)
self.assert_(t.month == 1)
self.asse... | StarcoderdataPython |
2088 | #!/usr/bin/python3
import os
import sys
import socket
CURRENT_DIR = os.path.dirname(__file__)
NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../'])
sys.path.insert(0, NEWSBLUR_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'newsblur_web.settings'
import threading
class ProgressPercentage(object):
def __init__(self, fil... | StarcoderdataPython |
122231 | <reponame>raaahulss/project_viralnews
import tldextract
import validators
from src.collection.twitter_api import get_tweet
from src.collection.news_fetcher import get_news_from_url
from src.collection.news_fetcher import get_news_from_file
from src.error import ApplicationError, error_list
supported_sources = ('twitte... | StarcoderdataPython |
3339867 | import os
IN_PRODUCTION = os.getenv("ENV_NAME", False)
SECRET_KEY = os.getenv("SECRET_KEY", "shhhh! it's a secret")
# infrastructure
local_db = "sqlite:////home/densolovev/Projects/learn-io/learn-io.db"
DATABASE_URI = os.getenv("DATABASE_URI", local_db)
# internal configuration
LOGGING_CONFIG = {
"version": 1,
... | StarcoderdataPython |
3245152 | <filename>src/normalize.py
from src.parser import parse_line
def by_max_count(rdd_in):
"""
Assuming that rdd_in has is a triplet of (user_id, song_id, and
play_count (int))
:param rdd_in: RDD that represents a list of triplets.
:return: Returns an RDD with with play count normalized
"""
dat... | StarcoderdataPython |
3309407 | <filename>gcslab.py
import numpy as np
from numpy import pi
import matplotlib.pyplot as plt
from matplotlib import rcParams
__author__ = "<NAME>"
__license__ = "Apache License, Version 2.0"
class GCSlabModel(object):
def __init__(self):
self._h = []
self._n = []
self._a_src = []
... | StarcoderdataPython |
1721534 | <gh_stars>1-10
from sage.all import *
def hensel_lift(curve, p, point):
A, B = map(long, (E.a4(), E.a6()))
x, y = map(long, point.xy())
fr = y**2 - (x**3 + A*x + B)
t = (- fr / p) % p
t *= inverse_mod(2 * y, p) # (y**2)' = 2 * y
t %= p
new_y = y + p * t
return x, new_y
p = 1685745... | StarcoderdataPython |
1689797 | #!/usr/bin/env python3
# # -*- coding: utf-8 -*-
"""
Default package.
________________________________________________________________________________
Created by brightSPARK Labs
www.brightsparklabs.com
"""
# standard libraries
import os
import sys
from pathlib import Path
from typing import Dict, Iterable
# vendor... | StarcoderdataPython |
37451 | import unittest
import io
import sys
from main import Gedcom
class TestProject(unittest.TestCase):
def test_us22_unique_id(self):
# Redirect stdout for unit test
capturedOutput = io.StringIO()
sys.stdout = capturedOutput
FILENAME="My-Family-27-Jan-2019-275.ged"
... | StarcoderdataPython |
1654403 | <reponame>bigdatalab/movingdata
from testify import *
from deploy.dag.edge import *
from deploy.dag.vertex import *
class EdgeTestCase(TestCase):
@class_setup
def init_the_variable(self):
self.edge = Edge(Vertex("A"), Vertex("B"))
def test_str(self):
assert_equal(str(self.edge), "(A,B,0)... | StarcoderdataPython |
1704564 | import h5py
from htmlgen import (Document, Element, Division, UnorderedList, Checkbox,
Label, ListItem, html_attribute, Span, Link, Script,
)
from pathlib import Path
from .datatypes import fmt_dtype, dtype_description
from . import utils
_PKGDIR = Path(__file__).parent
clas... | StarcoderdataPython |
22387 | """
NCL_bar_2.py
===============
This script illustrates the following concepts:
- Drawing bars instead of curves in an XY plot
- Changing the aspect ratio of a bar plot
- Drawing filled bars up or down based on a Y reference value
- Setting the minimum/maximum value of the Y axis in a bar plot
- Using n... | StarcoderdataPython |
1711360 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 5 09:01:45 2018
@author: tarum
"""
# Ignore this block code.
# Define Function for printing result
def cetak(name, val, unit = "", pad=50):
print('| {:>15s} = {:>10.5f} {:<{n}s}|'.format(name, val, unit, n = pad-15-10-7))
def new_line(pad = 50):
print('='*p... | StarcoderdataPython |
115557 | import pgzrun
WIDTH = 800
HEIGHT = 600
TITLE = "Balloon Fight"
game_over = False
up = False
balloon = Actor("balloon")
balloon.pos = 400, 300
def on_key_up(key):
global up
if key == keys.SPACE:
up = True
balloon.y -= 50
up = False
def update():
if not game_over:
if not ... | StarcoderdataPython |
179484 | <gh_stars>1-10
import itertools
import string
import json
from datetime import datetime
from elasticsearch import Elasticsearch
import elasticsearch
import elasticsearch.helpers
from elasticsearch.client import IndicesClient, CatClient
import sys, os, getopt
from file_utils import readFileToJson
from config_properties ... | StarcoderdataPython |
1746548 | <filename>bot/src/item.py
'''
Created on Feb 15, 2022
@author: JP
'''
from datetime import datetime
from datetime import timezone
from datetime import timedelta
import re
import distutils.util
from src.database import AHDatabase
from src.utils import InvalidCommand
from src.utils import ParseArgs
cl... | StarcoderdataPython |
170352 | import numpy as np
import os
import csv
import argparse
import torchvision.transforms as transforms
from PIL import Image
def loading_ucf_lists():
dataset_root = "/home/ubuntu/data/ucf101"
split = 'split_1'
# data frame root
dataset_frame_root = os.path.join(dataset_root, 'rawframes')
# data lis... | StarcoderdataPython |
3281450 | # Copyright 2017 Hewlett Packard Enterprise Development LP
#
# 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... | StarcoderdataPython |
3344394 | import os
from resolwe.flow.models import Data
from resolwe.test import tag_process
from resolwe_bio.utils.test import BioProcessTestCase
class WgsWorkflowTestCase(BioProcessTestCase):
@tag_process("workflow-wgs-paired")
def test_wgs_workflow(self):
def filter_gatkcmd(line):
return line.... | StarcoderdataPython |
3208064 | <reponame>klittlepage/aoc2020
import aoc.d09
from tests.aoc.test_base import BaseTestCase
class TestAll(BaseTestCase):
def test_part_one(self):
self.run_aoc_part(9, 373803594, aoc.d09.p_1)
def test_part_two(self):
self.run_aoc_part(9, 51152360, aoc.d09.p_2)
| StarcoderdataPython |
4833082 | <filename>esatsang/esatsang.py<gh_stars>1-10
#!/usr/bin/python
# 388622626:wq
# Author: <NAME>, <NAME>
# The base class for Twitter and GPlus Objects
#
import logging
import sys
from bs4 import BeautifulSoup
import urllib2
import re
import pytz
from datetime import datetime, date, time
URL="http://www.dayalbagh.org.i... | StarcoderdataPython |
93124 | #
# SPDX-License-Identifier: MIT
#
# Copyright (C) 2019-2021, AllWorldIT.
#
# 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
# u... | StarcoderdataPython |
3330124 | <reponame>gustavofoa/pympm<filename>apps/mpm/views/view_datas.py
from django.shortcuts import get_object_or_404, render
from django.http import JsonResponse
from datetime import date, timedelta
from ..models import Data
from django.views.decorators.cache import cache_control, cache_page
@cache_control(max_age = 60 * ... | StarcoderdataPython |
3238902 | <filename>gestion/migrations/0010_auto_20181106_2159.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-11-07 01:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gestion', '0009_auto_20181106_0010'),
... | StarcoderdataPython |
3265361 | <reponame>ericmjl/hiv-resistance-prediction
import pandas as pd
import numbers
import numpy as np
import networkx as nx
from scipy.spatial.distance import pdist, squareform
# A list of backbone chain atoms
BACKBONE_ATOMS = ['N', 'CA', 'C', 'O']
class AtomicInteractionNetwork(object):
"""docstring for AtomicInteract... | StarcoderdataPython |
1748083 | <reponame>Khushboo85277/NeoAlgo
'''
Given five positive integers, the aim is to find the minimum and maximum values that can be calculated by summing exactly four of the five integers.
'''
def MMSum(a):
# sorting the array so that it becomes easier to find the min and max set of values
a.sort()
... | StarcoderdataPython |
190349 | import numpy as np
import pandas as pd
# Install packages and libraries
# This only needs to be done once per notebook.
# installing nltk and its packages
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('brown')
# Installing textract
!apt-get install python-dev libxml2-... | StarcoderdataPython |
3298776 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | StarcoderdataPython |
3243988 | <filename>big_data/python_tools/big_data_tools/bokeh_tools/find_dist.py
from scipy import stats
from scipy.stats import probplot
import math
import scipy
import numpy as np
import pprint
from bokeh.plotting import figure, show
from bokeh.layouts import gridplot
import pprint
# /home/henry/Envs/class/lib/python3.5/site-... | StarcoderdataPython |
1720237 | <reponame>eadwinCode/django-ninja<gh_stars>1000+
import os
import sys
ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__))))
sys.path.insert(0, ROOT)
sys.path.insert(0, os.path.join(ROOT, "tests/demo_project"))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")
# from django.co... | StarcoderdataPython |
3304225 | <reponame>ds-vologdin/market_from_django<filename>catalog/urls.py
from django.urls import path
from . import views
app_name = 'catalog'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path(
'category/<int:category_id>/',
views.IndexView.as_view(),
name='index_categor... | StarcoderdataPython |
89470 | name = "wrangalytics.config" | StarcoderdataPython |
107328 | <reponame>klmitch/stepmaker
import pytest
from stepmaker import addresses
from stepmaker import exceptions
from stepmaker import utils
class ExceptionForTest(Exception):
pass
class ValidationException(Exception):
def __init__(self, message, path):
super(ValidationException, self).__init__(message)
... | StarcoderdataPython |
4836763 | <gh_stars>0
from pathlib import Path
from t2wml.api import Sheet, SpreadsheetFile, Wikifier
from caching import CacheHolder
class CalcParams:
def __init__(self, project, data_path, sheet_name, yaml_path=None, annotation_path=None):
self.project = project
self.project_path = project.directory
... | StarcoderdataPython |
134739 | # Copyright (c) 2013 Qubell Inc., http://qubell.com
#
# 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 agr... | StarcoderdataPython |
4809245 | # -*- coding: utf-8 -*-
u"""ML execution template.
:copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcompat
from pykern import pkio
from pykern import pk... | StarcoderdataPython |
178383 | <reponame>pyaf/severstal-steel-defect-detection<filename>extras/20190901/code/dummy_08/kaggle.py
from common import *
# https://www.kaggle.com/iafoss/severstal-fast-ai-256x256-crops-sub
# https://www.kaggle.com/rishabhiitbhu/unet-starter-kernel-pytorch-lb-0-88
def run_length_decode(rle, height=256, width=1600, fil... | StarcoderdataPython |
4619 | # -*- coding: utf-8 -*-
# MIT License
#
# Copyright 2018-2020 New York University A<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 ... | StarcoderdataPython |
1689488 | import torch
import dqc.utils
from dqc.utils.config import config
from dqc.utils.misc import logger
from dqc.test.utils import assert_fail
def test_converter_length():
a = torch.tensor([1.0])
# convert to itself
assert torch.allclose(dqc.utils.convert_length(a), a)
# convert from atomic unit to angstr... | StarcoderdataPython |
1651380 | '''
https://www.youtube.com/watch?v=-3ODe9mqoDE
'''
import pygame, math
pygame.init()
width = 10
fps = 10
class Square:
def __init__(self, surface, x, y, color):
self.surface = surface
self.color = color
self.rect = pygame.Rect(x,y,width,width)
self.direction = ""
def draw(... | StarcoderdataPython |
3256395 | <gh_stars>0
from pymongo import MongoClient
from flask import session
client = MongoClient("mongodb://localhost:27017")
data = client['mile12']
users=data['users']
section_items=data['sections']
items=data['items']
reports=data['reports']
| StarcoderdataPython |
3243210 | import pytest
from dependency_injector import Scope
from . import ioc
pytestmark = pytest.mark.asyncio
async def test_scan_package(ioc):
from .services import scan_package as module
from .services.scan_package.service1 import Service1
from .services.scan_package.service2 import Service2
ioc.scan(m... | StarcoderdataPython |
1749169 | from rest_framework import serializers
from mpesa.models import LNMOnline, C2BPayments
class LNMOnlineSerializer(serializers.ModelSerializer):
class Meta:
model = LNMOnline
fields = (
'id',
'merchant_request_id',
'checkout_request_id',
'result_code'... | StarcoderdataPython |
73818 | <filename>volumeSlider/test_IMS_converter.py
# -*- coding: utf-8 -*-
import numpy as np
from matplotlib import pyplot as plt
import re
import h5py
#from .helperFunctions import perform_shear_transform
from numpy import moveaxis
from skimage.transform import rescale
import logging
logger = logging.getLogger(__name__)
... | StarcoderdataPython |
3305073 | <gh_stars>0
#
# SPDX-License-Identifier: Apache-2.0
#
# Copyright 2020 <NAME>
#
# 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 req... | StarcoderdataPython |
3348127 | <filename>Python/Mundo01/Exercicios/ex029.py
'''Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h,
mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite.'''
vel = float(input('Qual é a sua velocidade atual do carro? '))
if vel > 80:
pr... | StarcoderdataPython |
1636254 | #
# Copyright (c) 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 i... | StarcoderdataPython |
192267 | def equal_slices(total, num, per_person):
res = num * per_person
if res <= total:
return True
return False
foo = equal_slices(11, 11, 1)
print(str(foo))
| StarcoderdataPython |
63850 | <gh_stars>0
from __future__ import (absolute_import, division, print_function)
from array import array
import copy
import random
from mycode import mydeap
from mycode.rep.fitness import Fitness
from mycode.settings import config
# print("using REPR-C = reprb + fperm order")
from mycode.rep.individual_base import Ind... | StarcoderdataPython |
21511 | <reponame>futurice/PythonInBrowser
# Käydään läpi mitä opimme viime viikolla (ja myös jotakin uutta)
# Jos jokin asia mietityttää, kysy vain rohkeasti apua!
##### INFO #####
# Viime viikon tärkeimmät asiat olivat:
# 1. print-komento
# 2. muuttujan käyttö
# 3. kilpikonnan käyttäminen piirtämiseen
# Ohelmointi vaatii u... | StarcoderdataPython |
1774516 | from simplepg.simple_utils import register_test, nprs
import numpy as np
from chainer import Variable
register_test(
"a2c.compute_returns_advantages",
kwargs=lambda: dict(
rewards=nprs(0).uniform(size=(5, 2)),
dones=nprs(1).choice([True, False], size=(5, 2)),
values=nprs(2).uniform(size... | StarcoderdataPython |
13376 | # Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwa... | StarcoderdataPython |
1746405 | <reponame>wgwz/flask-error-alerts
import os
import traceback
from flask import Flask
from werkzeug.exceptions import InternalServerError
import sendgrid
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
sg = sendgrid.SendGridAPIClient()
def create_message(email_text):
return sendgrid.helpers.mail... | StarcoderdataPython |
1787185 | <filename>vs_listener/apps.py
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.apps import AppConfig
class VSListenerConfig(AppConfig):
name = 'vs_listener'
| StarcoderdataPython |
59606 | import torch
class EarlyStopping():
"""
Monitor the training process to stop training early if the model shows
evidence of beginning to overfit the validation dataset, and save the
best model.
Note that patience here is measured in steps, rather than in epochs,
because the size of an epoc... | StarcoderdataPython |
107219 | <filename>ch2_practice/12_excel/05_xlsx2txt/xlsx2txt.py
#! python
# xlsx2txt.py - вставка данных из excel в TXT.
import openpyxl, sys
if len(sys.argv) == 1 or len(sys.argv) > 2:
print('Usage: py.exe txt2xlsx.py <file>')
elif len(sys.argv) == 2:
# проверка вх данных
fileName = sys.argv[1]
if fileName.e... | StarcoderdataPython |
3368393 | <filename>data_tracker/tasks.py
from celery import task, current_task
from celery.result import AsyncResult
from time import sleep
from tracker import models
NUM_OBJ_TO_CREATE = 1000
# when this task is called, it will create 1000 objects in the database
@task()
def create_models():
for i in range(1, NUM_OBJ_TO_CRE... | StarcoderdataPython |
136201 | <gh_stars>10-100
"""Classes and routines for handling aquifers."""
from collections import OrderedDict
import numpy as np
import h5py
from .base_component import BaseComponent
class Aquifers(BaseComponent):
"""
Aquifers component class.
"""
def __init__(self, **kwargs):
super().__init__(**kwar... | StarcoderdataPython |
3296292 | <gh_stars>10-100
# -*- coding:utf8 -*-
# File : in.py
# Author : <NAME>
# Email : <EMAIL>
# Date : 3/2/17
#
# This file is part of TensorArtist.
from tartist.data.rflow import control, InputPipe
import time
q = InputPipe('tart.pipe.test')
with control(pipes=[q]):
for i in range(10):
print(q.get()['... | StarcoderdataPython |
3350277 | <gh_stars>0
import gc
import unittest
from hecuba import config, StorageNumpy
import uuid
import numpy as np
from storage.api import getByID
from time import time as timer
import random
class StorageNumpyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.old = config.execution_name
... | StarcoderdataPython |
4807786 | <gh_stars>1-10
"""
Reweighting-related functions
"""
import numpy as np
def reweight1d(a, reference=1, bins=10, get_w_ref=False):
"""Get weights for a 1d array to match the distribution of another array.
Args:
a (array_like): The array with the variable we want to reweight.
reference (scalar... | StarcoderdataPython |
1781051 | # -*- coding: utf-8 -*-
from abc import ABC
from pathlib import Path
import pandas as pd
import scrapy
from src.crawl.utils import cleanup
from settings import YEAR, CRAWLING_OUTPUT_FOLDER
BASE_URl = "https://directory.unamur.be/teaching/courses/{}/{}" # first format is code course, second is year
PROG_DATA_PATH = ... | StarcoderdataPython |
134266 | import sqlite3
from flask import g
from app import app
DATABASE = './database.db'
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect(DATABASE)
return db
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
... | StarcoderdataPython |
76833 | <reponame>JohnLauFoo/clc_packages_Yu<filename>matplotlib-3.4.3/matplotlib-3.4.3/examples/lines_bars_and_markers/filled_step.py
"""
=========================
Hatch-filled histograms
=========================
Hatching capabilities for plotting histograms.
"""
import itertools
from collections import OrderedDict
from fu... | StarcoderdataPython |
94511 | import pandas
u202 = pandas.read_csv("u202.csv", encoding="utf-8")
u203 = pandas.read_csv("u203.csv", encoding="utf-8")
u302 = pandas.read_csv("u302.csv", encoding="utf-8")
u202.dropna(inplace=True)
u203.dropna(inplace=True)
u302.dropna(inplace=True)
u202["místnost"] = "u202"
u203["místnost"] = "u203"
u302["místnost... | StarcoderdataPython |
3351245 | # Author: <EMAIL>
# Version: 1.0 - 2017/12/24
# About: perceptron algorithm applied on sentiment analysis
from utilities import *
from args import *
ITERATIONS = int(args.number_of_iterations)
LEARNING_RATE = float(args.learning_rate)
SHUFFLE_COEF = int(args.shuffle_factor)
DATA_SPLIT_COEF = 0.9
# Characters to be r... | StarcoderdataPython |
196040 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import logging
logger = logging.getLogger(__name__)
import six
import requests
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
class EmailVerif(object):
__metaclass__ = ABC... | StarcoderdataPython |
3279367 | # -*- coding: utf-8 -*-
""""""
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection
from coop_cms.models import Alias
from coop_cms.settings import is_localized
class Command(BaseCommand):
"""patch alias redirect"""
help = "patch alias redirec... | StarcoderdataPython |
3373049 | <filename>src/bt/extract/btdata.py
import os
def get_string_data(ba, ident, num):
strings = [u"", ] * num
start = ba.find(ident)
for i in xrange(num):
end = ba.find(b"\x00", start)
strings[i] = str(ba[start:end])
start = end + 1
return strings
| StarcoderdataPython |
3212062 | <filename>structures/qregistry.py
import cmath as cm
import numpy as np
import random as rnd
from structures.qgate import _getMatrix
class QRegistry:
def __init__(self, nqbits, **kwargs):
# nqbits -> number of QuBits in the registry.
# Seed for the Pseudo Random Number Generation can be specified with seed = <see... | StarcoderdataPython |
37378 | from project_utils import dict_to_file, get_word_count
if __name__ == "__main__":
inp_filename = 'sample.txt'
out_filename = 'count.csv'
print("Reading file ", inp_filename)
word_dict = get_word_count(inp_filename)
print("Output from get_word_count is")
print(word_dict)
print("W... | StarcoderdataPython |
3218890 | <gh_stars>1-10
# Copyright 2022 AI Singapore
#
# 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 agree... | StarcoderdataPython |
1653945 | from kivy.lang import Builder
from kivy.properties import BooleanProperty, NumericProperty, Clock
from kivy.uix.widget import Widget
from cobiv.modules.core.component import Component
Builder.load_string('''
<TouchButton>:
rad: self.rad_large if self.active else self.rad_small
canvas:
Color:
... | StarcoderdataPython |
143727 | <reponame>shogi880/lossyless<gh_stars>10-100
import logging
import math
from typing import Hashable
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torchvision
from matplotlib.lines import Line2D
import einops
from pytorch_lightning.ca... | StarcoderdataPython |
1727389 | <gh_stars>10-100
"""
Module to provide for the recognition of Markdown tables.
"""
from pymarkdown.extension_impl import ExtensionDetails
# pylint: disable=too-few-public-methods
class MarkdownTablesExtension:
"""
Extension to implement the tables extension.
"""
@classmethod
def get_details(cls)... | StarcoderdataPython |
1691105 | <gh_stars>0
#!/usr/bin/env python
#
# Copyright (c) 2015 <NAME>
# Copyright (c) 2015 <NAME>
# All rights reserved.
#
# This software was developed by SRI International and the University of
# Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
# ("CTSRD"), as part of the DARPA CRASH research progr... | StarcoderdataPython |
4824905 | from nose.plugins.attrib import attr
@attr('demo_smoke', 'smoke', 'known_good')
def test_dummy_known_good_with_assertion_pass():
assert True
def test_with_generator():
for i in range (0, 5):
yield do_something, i
def do_something(i):
assert True, "do something number: {}".format(i)
def test_wit... | StarcoderdataPython |
3329911 | <reponame>caiuamelo/pybaqus<gh_stars>0
"""
Utilities to read the ASCII *.fil files generates by abaqus.
"""
import re
from .fil_result import FilParser
def open_fil(file_name):
"""Read the *.fil file
Parameters
----------
file_name : str
Path to the *.fil file
Returns
-------
Re... | StarcoderdataPython |
1764504 | from time import time
import bintrees
import json
import getopt
import sys
tasks = []
time_slice = 45
num_timeslices = 8
tree = bintrees.RBTree()
exit = False
class ProcessTree:
def __init__(self, tasks=None):
self.tree = bintrees.RBTree()
self.stats = tasks.get('stats')
if tasks:
... | StarcoderdataPython |
3274549 | import random
import numpy
import boards
def print_sudoku_board(board: list):
for i in range(9):
if i % 3 == 0:
print("-------------------------")
for j in range(9):
if j % 3 == 0:
print("|", end=" "),
print(board[i][j], end=" ")
print(... | StarcoderdataPython |
3308924 | <gh_stars>0
from .unsigned_integer_array import UnsignedIntegerArray
class U8(UnsignedIntegerArray):
@property
def _type_code(self) -> str:
return 'B'
| StarcoderdataPython |
1025 | import gym
import gym.spaces as spaces
import sys
import socket
from _thread import *
import os
import numpy as np
import pandas as pd
import math as m
import time
import random
class NetEnv(gym.Env):
def __init__(self):
# Robot State values that will be bounced with client
self.robot_state = None
self.p... | StarcoderdataPython |
3262237 | <reponame>oleksiilytvyn/grailkit
# -*- coding: UTF-8 -*-
"""
Tests for db module
:copyright: (c) 2017-2020 by <NAME> (http://alexlitvin.name).
:license: MIT, see LICENSE for more details.
"""
import unittest
import os
import shutil
import tempfile
import sqlite3 as sqlite
import grailkit.db as db
... | StarcoderdataPython |
1648307 | <filename>hadoop_script_2.0/common/valid/validator.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import abc
__author__ = "jiandequn"
""""
抽象验证器实现
"""
class Validator(object):
_metaclass__ = abc.ABCMeta
@abc.abstractproperty
def vlidate(self, val):
"""
定义当前操作表
"""
r... | StarcoderdataPython |
142586 | # Copyright (c) 2013 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditi... | StarcoderdataPython |
85756 | <reponame>Sebastiaan-Alvarez-Rodriguez/Meizodon
#!/usr/bin/env python
import lib.independence.fs as fs
# The greater purpose of this file is
# to set some global variables that are used at many places
def init(_path):
global root
root = _path
global installersdir
installersdir=fs.join(_path,'installe... | StarcoderdataPython |
1720587 | <filename>ProgrammingProject1/TaskB/decrypt.py<gh_stars>0
import math
import BigNumber
# public key is {e, n}
# private key is {d, n}
def gcd(a,b):
return gcd(b,a%b)
def encrypt(me, e, n):
en = me**e
c = en % n
print("Encrypted Message is: ", c)
return c
def hexToDec(temp):
a = ""
for i ... | StarcoderdataPython |
4830269 | <gh_stars>0
from service.baseservice import BaseService
from server import Server
from util.util import print_trace_exception
import logging
class Application(object):
def __init__(self, service_list):
self.server = Server()
self.hub = {}
map(lambda service: self.register(service()), serv... | StarcoderdataPython |
3342059 | <reponame>KostasTok/keras_DCGAN_transfer_learning
import numpy as np
class Batcher():
'''
Creates two minibatches, one with real images,
and one with generated ones.
labels, and noise for the generator.
Inputs:
data -> array (n, height, width, dim), where n is the
number of... | StarcoderdataPython |
3235396 | import os
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle
from kivy.uix.image import Image
class MyBackground(Widget):
# this class is used as a parent class to all the GraphicalNodes
# this class also renders the background image
def __init__(... | StarcoderdataPython |
196440 | <filename>client/verta/tests/test_permissions/test_sharing_old.py
"""
Original collaboration/sharing tests, before the visibility overhaul.
"""
import pytest
from verta._internal_utils import _utils
pytestmark = pytest.mark.not_oss
class TestProject:
def test_share_project_personal_workspace(self, client, clie... | StarcoderdataPython |
1659997 | <filename>python/blackjack/hand.py
from cardvalues import card_values
class Hand:
def __init__(self, cards):
self.cards = cards
self.max_score = 21
self.subscribers = []
@property
def cards(self):
return self._cards
@cards.setter
def cards(self, cards: list):
... | StarcoderdataPython |
4837403 | #!/usr/bin/env python
import os
from django.core.management import call_command
def handler(event, context):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cmcs_regulations.settings")
import django
django.setup()
call_command('loaddata', 'supplemental_content.category.json')
call_command('loadd... | StarcoderdataPython |
3243549 | import numpy
import random
from multiprocessing.pool import ThreadPool as Pool
import copy
import time
from math import floor
def randomiseNumberOrder():
numberOrderGrid=numpy.zeros([9,9,9])
for i in range(0,9):
for j in range(0,9):
numbersToSort=[1,2,3,4,5,6,7,8,9]
for k in range(0,9):
index=random.rand... | StarcoderdataPython |
1690501 | <reponame>rcelebi/android-elfali
# Copyright 2015 The TensorFlow Authors. 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... | StarcoderdataPython |
1768539 | <reponame>asellis/Christmas_Tree_Lights<gh_stars>0
# A console text interface to execute commands for xmas LED controller
# NOTES: directory is hard coded to project directory
from LEDPlayer import LEDPlayer
from time import sleep
import _thread
import sys
import os
currentDir = os.getcwd()
demoDir = currentDir+'/Prem... | StarcoderdataPython |
1724901 | """
This file contains a Database class which dictates table creation, deletion, and access.
"""
from pathlib import Path
import os
from sqlalchemy import Column, Integer, Table
from sqlalchemy import create_engine, MetaData, event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import mapp... | StarcoderdataPython |
3225603 | #! /usr/bin/env python3.5
import logging
import os
import re
import pwd
import csv
import time
import shutil
import psutil
import pathlib
import datetime
import subprocess
from collections import OrderedDict, abc
import elo
import yaml
from bs4 import BeautifulSoup
DROPBOX_DEBUG = logging.DEBUG - 1
logger = logging... | StarcoderdataPython |
3323278 | <reponame>bbhunter/fuzz-lightyear<filename>testing/vulnerable_app/main.py
import os
from .app import get_current_application
from .core.database import Base
from .core.database import create_engine
from .core.database import get_database_file
from .core.routes import configure_routes
def main():
app = get_curren... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.