id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
69378 | import torch
import torch.nn as nn
def L1_Loss_calc(model, factor=0.0005):
l1_crit = nn.L1Loss(size_average=False)
reg_loss = 0
for param in model.parameters():
# zero_vector = torch.rand_like(param)*0
zero_vector = torch.zeros_like(param)
reg_loss += l1_crit(param, zero_vector)
... | StarcoderdataPython |
1708803 | from define import HOGE
def get_hoge():
return HOGE
| StarcoderdataPython |
1767678 | from support import log
class LexicalStream:
def __init__(self, controlling_parsing_process):
self.controlling_parser_process = controlling_parsing_process
self.id = 0
def stream_into_syntax(self, terminal_lexical_item, lst_branched, inflection, ps, index):
terminal_lexical_item = sel... | StarcoderdataPython |
1712383 | <reponame>VIAME/kwiver<filename>python/kwiver/vital/util/entrypoint.py<gh_stars>1-10
import pkg_resources
from pkg_resources import iter_entry_points
from kwiver.vital import vital_logging
from kwiver import PYTHON_PLUGIN_ENTRYPOINT, CPP_SEARCH_PATHS_ENTRYPOINT
import kwiver
import os
logger = vital_logging.getLogge... | StarcoderdataPython |
3203416 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers, status, authentication, permissions
from storage.api.serializers import DriveFolderSerializer
from storage.models import DriveFolder
from django.shortcuts import get_object_or_404
class DriveFo... | StarcoderdataPython |
144239 | def f(arr, t):
# print(t)
N = len(arr)
x0,v0 = arr[0]
l,r = x0 - t*v0, x0 + t*v0
for i in range(1, N):
xi,vi = arr[i]
l1, r1 = xi - t*vi, xi + t*vi
if l1 < l:
(l,r), (l1,r1) = (l1,r1), (l,r)
if l1 > r:
return False
l,r = max(... | StarcoderdataPython |
4835786 | <filename>TempAnalysis.py
import sys
import csv
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def read_csv_file():
with open('temp.csv') as csv_file:
global data_array
data_array = []
csv_reader = csv.reader(csv_file, delimiter = ',')
line_count = 0
current_col = 0
... | StarcoderdataPython |
1665417 | <filename>src/graphing.py
import matplotlib.pyplot as plt
def plot_grid(draw, initialize=lambda f,a,p: None, dims=(1,1), include=[]):
f, axes = plt.subplots(dims[0], dims[1],figsize=(20,20))
initialize(f, axes, plt)
for i in xrange(dims[0]):
for j in xrange(dims[1]):
if not (i,j) i... | StarcoderdataPython |
7667 | <reponame>elcolie/battleship<filename>config/api_urls.py
from rest_framework import routers
from boards.api.viewsets import BoardViewSet
from fleets.api.viewsets import FleetViewSet
from missiles.api.viewsets import MissileViewSet
app_name = 'api'
router = routers.DefaultRouter()
router.register(r'boards', BoardView... | StarcoderdataPython |
1613962 | """Top-level package for Gdoc2Mdown."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| StarcoderdataPython |
4827169 | <reponame>tefra/xsdata-w3c-tests<filename>output/models/ms_data/datatypes/facets/g_day/g_day_min_inclusive003_xsd/__init__.py
from output.models.ms_data.datatypes.facets.g_day.g_day_min_inclusive003_xsd.g_day_min_inclusive003 import (
FooType,
Test,
)
__all__ = [
"FooType",
"Test",
]
| StarcoderdataPython |
4815816 | <reponame>Charlie818/video
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: qiujiarong
# Date: 08/03/2018
import cv2
import numpy as np
import os
def dense_optical_flow_test(frames,folder):
os.system("rm -rf %s" % folder)
os.system("mkdir %s" % folder)
# print(frames,folder)
assert len(frames)... | StarcoderdataPython |
170974 | <reponame>rf-peixoto/Studies<filename>Code/Python/timekey.py
# ======================================================== #
# TimeKey
# ======================================================== #
from secrets import token_urlsafe
from datetime import datetime
from hashlib import md5
# ====================================... | StarcoderdataPython |
1667920 | from PIL import Image
import numpy as np
import torch
import os
import argparse
from torch import nn
from skimage import exposure
from skimage import img_as_float, transform
def save_image(im, path):
"""
Saves a numpy matrix or PIL image as an image
Args:
im_as_arr (Numpy array): Matrix of sha... | StarcoderdataPython |
1719631 |
from django.db import models
from datetime import datetime
# Create your models here.
class BaseModel(models.Model):
created_at = models.DateTimeField(default=datetime.now())
updated_at = models.DateTimeField(null=True, blank=True)
created_by = models.CharField(blank=True, max_length=250)
deleted_at =... | StarcoderdataPython |
1774246 | <gh_stars>0
x = int(input("Enter an integer value:"))
if x < 0:
print("x is less then zero")
elif x > 0:
print("x is greater then zero")
else:
print("x is equal to zero")
| StarcoderdataPython |
1751740 | <reponame>sumnerevans/advent-of-code
#! /usr/bin/env python3
import sys
import time
from typing import List
test = False
debug = False
stdin = False
INFILENAME = "inputs/01.txt"
for arg in sys.argv:
if arg == "--test":
test = True
INFILENAME = "inputs/01.test.txt"
if arg == "--debug":
... | StarcoderdataPython |
1662017 | <gh_stars>0
import pytest
from boxtribute_server.enums import ShipmentState
from boxtribute_server.models.definitions.shipment import Shipment
from boxtribute_server.models.utils import utcnow
from .base import data as base_data
from .transfer_agreement import data as transfer_agreement_data
from .user import default_... | StarcoderdataPython |
3202377 | <gh_stars>1-10
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | StarcoderdataPython |
3210515 | # IMAGE_MAGIC_DIR = r'C:\Program Files\ImageMagick-7.0.8-Q16'
# TMP_DIR = '.'
IMAGE_MAGIC_DIR = r'/usr/bin'
TMP_DIR = r'/tmp/webexe' | StarcoderdataPython |
3333994 | <filename>metrics.py
import utils
import pandas as pd
import torch
import transformers
def calculate_jaccard_score(original_context, target_string, question_val, idx_start, idx_end):
if idx_end < idx_start:
idx_end = idx_start
filtered_output = original_context[idx_start:idx_end+1]
jac ... | StarcoderdataPython |
1739779 | import responses
from matrix_client import client
class TestTagsApi:
cli = client.MatrixClient("http://example.com")
user_id = "@user:matrix.org"
room_id = "#foo:matrix.org"
@responses.activate
def test_get_user_tags(self):
tags_url = "http://example.com" \
"/_matrix/client/r0/... | StarcoderdataPython |
4826944 | from random import randint
class Snake:
def __init__(self, *, rows=10, cols=10, mode="diffs"):
# mode determines return type
# either the whole game grid or just the changes
self.mode = mode
# game grid size, denoted by number of rows and columns (cols)
self.rows = rows
self.cols = cols
# builds up a... | StarcoderdataPython |
3381409 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# __BEGIN_LICENSE__
# Copyright (c) 2009-2013, United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The NGT platform is licensed under the Apache License, Version 2.0 (the
# "Lic... | StarcoderdataPython |
196749 | import numpy as np
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from scipy.stats import beta as Beta
i=9
n=10
alpha=5
beta=5
samples=np.random.choice(2, n, replace=True, p=[0.3,0.7])
k=len([y for y in samples if y==1])
#x-axis values
x=np.linspace(0,1, 100)
#r'$\alpha=1, \beta$=1'
plt.... | StarcoderdataPython |
1702759 | from .attack import AttackConnectivityTest, AttackTest
from .simple import SimpleConnectivityTest
| StarcoderdataPython |
174858 | <reponame>ivan-c/truenth-portal
from alembic import op
import sqlalchemy as sa
"""empty message
Revision ID: <KEY>
Revises: ('<KEY>', '<PASSWORD>')
Create Date: 2017-12-19 16:31:24.963128
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = ('<KEY>', '<PASSWORD>')
def upgrade():
pas... | StarcoderdataPython |
135345 | __all__ = ["PriceProvider"]
import abc
from .subject import Subject
class PriceProvider(abc.ABC):
"""
A PriceProvider is an interface that encapsulates the operations of an underlying price provider implementation.
"""
@abc.abstractmethod
def start(self):
"""
Starts the pricing ... | StarcoderdataPython |
3261290 | #!/usr/bin/env python
import sys
import os
name = ""
base_name = ""
if len(sys.argv) < 4:
print("create_exhirom.py <super metroid rom> <alttp rom> <output filename> <filler byte>")
sys.exit()
else:
sm_name = sys.argv[1]
alttp_name = sys.argv[2]
output_name = sys.argv[3]
filler = int(sys.argv[4] or "0x00", base=1... | StarcoderdataPython |
4803270 | <reponame>gloriousDan/recipe-scrapers
from recipe_scrapers.meljoulwan import Meljoulwan
from tests import ScraperTest
class TestMeljoulwanScraper(ScraperTest):
scraper_class = Meljoulwan
def test_host(self):
self.assertEqual("meljoulwan.com", self.harvester_class.host())
def test_author(self):
... | StarcoderdataPython |
1671178 | #!/usr/bin/env python3
import re
import urllib
from pathlib import Path
from pprint import PrettyPrinter
from typing import AnyStr, Match
import click
pprint = PrettyPrinter().pprint
# TODO: handle case when inline equation spans multiple lines.
# TODO: improve regular expression so that inline equation pattern doe... | StarcoderdataPython |
3284445 | from __future__ import print_function, division, absolute_import
import unittest
import pytest
import numpy as np
from openmdao.api import Problem, Group, IndepVarComp
#from openmdao.components.multiply_divide_comp import ElementMultiplyDivideComp
from openconcept.utilities.math.multiply_divide_comp import ElementMul... | StarcoderdataPython |
1693103 | <filename>aa.py
print("wwwww")
print("qqqqq") | StarcoderdataPython |
1640250 | # -*- coding: utf-8 -*-
"""Top-level package for pyn5."""
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
__version__ = "1.0.1"
from h5py_like import Mode
from .python_wrappers import open, read, write
from .pyn5 import (
DatasetUINT8,
DatasetUINT16,
DatasetUINT32,
DatasetUINT64,
DatasetINT8,
... | StarcoderdataPython |
19528 | <reponame>amalshehu/exercism-python<gh_stars>1-10
# File: etl.py
# Purpose: To do the `Transform` step of an Extract-Transform-Load.
# Programmer: <NAME>
# Course: Exercism
# Date: Thursday 22 September 2016, 03:40 PM
def transform(words):
new_words = dict()
for point, letters in words... | StarcoderdataPython |
1633735 | <reponame>eladmw/autokeras
import kerastuner
import tensorflow as tf
from tensorflow.python.util import nest
from autokeras import blocks
from tests import utils
def test_augment_build_return_tensor():
block = blocks.ImageAugmentation()
outputs = block.build(
kerastuner.HyperParameters(),
tf... | StarcoderdataPython |
7855 | """
功能:模拟掷骰子
版本:1.0
"""
import random
def roll_dice():
roll = random.randint(1, 6)
return roll
def main():
total_times = 100000
result_list = [0] * 6
for i in range(total_times):
roll = roll_dice()
result_list[roll-1] += 1
for i, x in enumerate(result_list):
... | StarcoderdataPython |
3396112 | <filename>commercia/products/management/commands/create_categories.py<gh_stars>1-10
from random import randint
from django.core.management.base import BaseCommand
from ...factories import CategoryFactory
class Command(BaseCommand):
help = 'Create Categories and add products'
def handle(self, *args, **optio... | StarcoderdataPython |
3317057 | <reponame>lioshi/vscode-lioshi-theme
import asyncio
def showcase():
"""Some code to showcase the syntax.
HACK doctests are highlighted too.
>>> print('''hello
... world''')
"""
activities = {8: 'Sleeping',
20: 'Eating',
22: 'Resting' }
raw_input("Enter an int... | StarcoderdataPython |
43285 | import time
import TSL2561
chip = TSL2561.TSL2561()
while True:
chip.power_on()
print("Raw Channel 0 = " + str(chip.read_channel0()))
print("Raw Channel 1 = " + str(chip.read_channel1()))
print("Lux Channel 0 = " + str(chip.calculate_lux(chip.read_channel0())))
print("Lux Channel 1 = " + str(chip.calculate_lux(ch... | StarcoderdataPython |
4829925 | #Here goes the code that was written for n-dimensional minimum volume ellipsoid.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import numpy as np
import sys
from sklearn.cluster import KMeans
import os
# Get Current working Directory
currentDirectory = os.getcwd()
current... | StarcoderdataPython |
1640105 | from exception import *
class Cache(object):
'''Class for caching
'''
def __init__(self, content = {}):
self._content = content
def add(self, key, item, overwrite = False):
'''Adds the dict {key: item} to self._content
If overwrite is True, then if that key already exists... | StarcoderdataPython |
4804409 | <filename>Logistic_Regression/Scripts/logistic_regression_with_regularization.py
"""
Example 3 - Logistic Regression without regularization
NOTE: The example and sample data is being taken from the "Machine Learning course by <NAME>" in Coursera.
Problem:
Suppose that you are the administrator of a university depar... | StarcoderdataPython |
1658296 | import os
from typing import Optional
import tweepy
from django.conf import settings
from news.models import Fact
def post_fact_to_twitter(fact_obj: Fact) -> Optional[str]:
if (
not settings.TWITTER_API_KEY
or not settings.TWITTER_API_KEY_SECRET
or not settings.TWITTER_ACCESS_TOKEN
... | StarcoderdataPython |
1747875 | <reponame>aobo-y/cornac
# Copyright 2018 The Cornac 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.0
#
# Unless... | StarcoderdataPython |
194775 | from datetime import datetime
from dcop_engine.room.dpop_room import DpopRoom
from dcop_engine.zone.dpop_zone import DpopZone
from logs import log
from logs.message_types import MessageTypes
from mqtt.custom_mqtt_class import CustomMQTTClass
from dcop_engine.zone_multi.dpop_zone_multi import DpopZoneMulti
from model.mo... | StarcoderdataPython |
3321874 | <filename>player.py<gh_stars>1-10
import pygame
from constants import *
# This sprite class represents the player platform
class Player(pygame.sprite.Sprite):
def __init__(self, pos):
super(Player, self).__init__()
self.image = pygame.image.load(IMAGE_PLAYER).convert_alpha()
self.rect = s... | StarcoderdataPython |
1733446 | """
account module
"""
from ker.utils import request
from .list import API_LIST
class Account:
"""
all account apis
"""
def __init__(self, email, token):
self.email = email
self.token = token
def get_quota(self):
"""
get quota infomation for user
"""
... | StarcoderdataPython |
3248678 | #!/usr/bin/python3
from pathlib import Path
Import("env")
SOURCE_START_LOCATION = 0x10000
def create_full_bin(source, target, env):
firmware_file = target[0].get_abspath()
full_image_filename = env.subst("$BUILD_DIR/${PROGNAME}-full.bin")
parts = []
# Will contain 3 parts outside of the main firmw... | StarcoderdataPython |
4841211 | import setuptools
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext
from distutils.dist import Distribution
import os
import subprocess
import platform
import sys
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=""):
Extension.__init__(self, ... | StarcoderdataPython |
150963 | <filename>main.py
import wifimgr as wm
wlan = wm.get_connection()
if wlan is None:
print("Could not initialize the network connection.")
while True:
pass # you shall not pass :D
# Main Code goes here, wlan is a working network.WLAN(STA_IF) instance.
print("ESP OK")
from machine import Pin... | StarcoderdataPython |
1760873 | #
# @cond ___LICENSE___
#
# Copyright (c) 2017 <NAME> and individual contributors.
#
# 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 rig... | StarcoderdataPython |
1639803 | import sys
import click
from .. import shared
@shared.cli.command()
@click.argument("name", required=False)
@click.option("--list_docs", "-l", is_flag=True, required=False)
@click.pass_context
def show(ctx, name, list_docs):
"""Send contents of document to stdout."""
# yew = ctx.obj["YEW"]
docs = share... | StarcoderdataPython |
3393685 | import os
from setuptools import setup, find_packages
# Get current location
here = os.path.abspath(os.path.dirname(__file__))
# Get the long description from the README file
with open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
readme = f.read()
# Setup
setup(
name='rabectl',
version='0.1.0... | StarcoderdataPython |
16621 | import json
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import dash_table
def get_comps_data(bd, projverurl):
print('Getting components ...')
# path = projverurl + "/components?limit=5000"
#
# custom_headers = {'Acc... | StarcoderdataPython |
3384427 | import os
# For reading, visualizing, and preprocessing data
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F
from pytorch_toolbelt.utils import fs
from sklearn.decomposition import PCA
from sklearn.model_selection import GroupKFold
from sklearn.preprocessing import StandardScaler
fr... | StarcoderdataPython |
3392641 | from core.functions import truncate_text
from core.exceptions import NotFoundError
from core.markdown import MarkdownParser
from core.article_helpers import get_article, get_all_articles
def get_page_data(path, get, post, variables):
article = get_article(get.get('name', ''))
if not article:
raise NotFoundErr... | StarcoderdataPython |
3235343 | # generating a quantity of dictionaries from 2 to 10 as well as number of elements (keys and values)
# in future generated dictionaries
import random
from random import randint
dicts_number = randint(2,10)
elements_number = randint(1,10)
# print('dicts number =', dicts_number, 'elements number =', elements_number)
# ... | StarcoderdataPython |
133855 | <gh_stars>1-10
import PySimpleGUI as sg
from display4D.image_resizer_fields import *
from equations.FieldsEP.vectorfieldEP import *
from sympy import preview, sympify
def vectorfield_gui4d(event, metric_tensor, coord_sys):
"""
The main process of the GUI that produces the image of a vector field
for a giv... | StarcoderdataPython |
4804738 | from app.models import db
from app.models.base import SoftDeletionModel
class Microlocation(SoftDeletionModel):
"""Microlocation model class"""
__tablename__ = 'microlocations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
latitude = db.Column(db.Float)
... | StarcoderdataPython |
4842625 | <reponame>ryan-shaw/app-bitcoin-new
from .device_exception import DeviceException
from .errors import (UnknownDeviceError,
DenyError,
IncorrectDataError,
NotSupportedError,
WrongP1P2Error,
WrongDataLengthError,
... | StarcoderdataPython |
1660628 | # -*- coding: utf-8 -*-
# DO NOT EDIT THIS FILE!
# This file has been autogenerated by dephell <3
# https://github.com/dephell/dephell
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os.path
readme = ''
here = os.path.abspath(os.path.dirname(__file__))
readme_pa... | StarcoderdataPython |
1742841 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/28 16:09
# @Author : ywb
# @Site :
# @File : test_interface.py
# @Software: PyCharm
import pytest
import requests
from common.request_util import RequestUtil
from common.yaml_util import read_yaml
def test_func_04():
print('这是... | StarcoderdataPython |
18881 | <reponame>atamurad/coinflip
from Crypto.Util.number import getRandomRange
from sympy.ntheory.residue_ntheory import jacobi_symbol
N = int(input("N ? "))
x = getRandomRange(2, N)
x2 = (x*x) % N
J = jacobi_symbol(x, N)
print(f"x2 = {x2}")
guess = int(input("j_guess ? "))
print(f"x = {x}")
print("Outcome = Heads" if ... | StarcoderdataPython |
4805728 | <reponame>tferreira/slackron<gh_stars>1-10
from pathlib import Path
from yaml import load
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
class Config:
def __init__(self):
self._config = load(
open('{}/.slackron.yml'.format(str(Path.home())), 'r'),
... | StarcoderdataPython |
58796 | <reponame>daedaluschan/GeneosReportTools
from os import listdir
from os.path import isfile, join
from shutil import move
from pandas import DataFrame as df
import pandas as pd
import csv
import requests
import string
from datetime import datetime
from lxml import etree
from lxml import html
incomingFolder = '.\\in'... | StarcoderdataPython |
8357 | # Copyright 2020 Curtin University
#
# 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 writi... | StarcoderdataPython |
3391 | <gh_stars>1-10
#!/usr/bin/env python
"""Builds the documentaion. First it runs gendoc to create rst files for the source code. Then it runs sphinx make.
.. Warning:: This will delete the content of the output directory first! So you might loose data.
You can use updatedoc.py -nod.
Usage, just call::
upd... | StarcoderdataPython |
4822390 | <filename>graph_utils/vdes_graph.py
from .graph import Graph, nx, plt
class VDESGraph(Graph):
def __init__(self, boat_count=10, satellite_count=2, radio_tower_count=2, **attr):
super().__init__(**attr)
self.graph_params = "YWRkIG1lZyBww6Ugc25hcCBmb3IgTEY6IHNqdXJiZQ=="
self.boat_count = boa... | StarcoderdataPython |
3337701 | import unittest
from strings.find_pattern_in_text_bruteforce import find_pattern_v1, find_pattern_v2
class FindPatternBruteForce(unittest.TestCase):
def test_return_the_position_of_first_occurrence_v1(self):
test_cases = [
("abracadabra", "bra"),
("aaaaaaab", "ab"),
("c... | StarcoderdataPython |
3399922 | <filename>aerosandbox/numpy/test_numpy/test_rotations.py
import pytest
import aerosandbox.numpy as np
def test_euler_angles_equivalence_to_general_3D():
phi = 1
theta = 2
psi = 3
rot_euler = np.rotation_matrix_from_euler_angles(phi, theta, psi)
rot_manual = (
np.rotation_matrix_3D(psi... | StarcoderdataPython |
3361868 | <gh_stars>10-100
"""This module contains methods!
If we write our docstrings as ReST, we get nice documentation
"""
def add(x, y):
"""Add two objects and return the result
>>> from methods import add
>>> add(2, 4)
6
>>> add('Cheese', 'burger')
'Cheeseburger'
"""
return x + y
def subt... | StarcoderdataPython |
3325121 | <filename>authentication/backend.py
import jwt
from django.conf import settings
from rest_framework import authentication, exceptions
from .models import User
class JWTAuthentication(authentication.BaseAuthentication):
keyword = "Bearer"
def authenticate(self, request):
"""
This checks that t... | StarcoderdataPython |
4805452 | <gh_stars>1000+
def configuration(parent_package='io',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('matlab', parent_package, top_path)
config.add_extension('_streams', sources=['_streams.c'])
config.add_extension('_mio_utils', sources=['_mio_utils.c'])
... | StarcoderdataPython |
3212380 | import os
from os.path import join as pjoin, abspath
import grp
import pwd
import sys
from distutils.util import spawn
from distutils.version import StrictVersion, LooseVersion
from distutils.dir_util import mkpath
from distutils.file_util import copy_file
import distutils.core
from tempfile import mkdtemp
from .tmpdi... | StarcoderdataPython |
1664910 | <filename>utils/config.py<gh_stars>1-10
# -*- coding: utf-8 -*-
prefixes = [
u"Sir ",
u"Mr ",
u"Ms ",
u"The Rt Hon "
]
sufixes = [
u" MP",
u"Mr ",
u"Ms ",
u"The Rt Hon "
]
lords_titles = [
u"Lady",
u"Lord",
u"Earl",
u"Baroness",
u"Viscount",
u"Bishop",
u"Co... | StarcoderdataPython |
1648521 | import util
class Puck:
# The constructor
def __init__(self, ):
# Data members
self.X = util.WIDTH / 2
self.Y = util.HEIGHT / 2
self.dX = util.random.uniform(0.2, 0.4)
self.dY = util.random.uniform(0.1, 0.3)
self.Raidus = 10
if util.random.randint(0, 5) ... | StarcoderdataPython |
3263047 | <reponame>DHI/MIKECore-Examples<gh_stars>1-10
# Writes information on static items to console
import sys
import clr
from math import *
import array
# The SetupLatest method will make your script find the MIKE assemblies at runtime.
# This is required for MIKE Version 2019 (17.0) and onwards. For previous vers... | StarcoderdataPython |
1605023 | #!/usr/bin/env python3
n = int(input().strip())
temp = list(map(int, input().split()))
p = [0]
p.extend(temp)
for i in range(1, n + 1):
for j in range(1, n + 1):
if p[p[j]] == i:
print(j)
break
| StarcoderdataPython |
1688877 | from django.apps import AppConfig
class DictConfig(AppConfig):
name = 'dict'
| StarcoderdataPython |
3214784 | """ This will reab cis-camera and render to rtsp
the meta dat will bge extracting with.
------------ To make change ---------
- to change the model: change config .txt file
- and the parse function 'pgie_src_pad_buffer_probe' with the corresponded parser for th new model
"""
import sys
import io
imp... | StarcoderdataPython |
3380590 | <gh_stars>0
import html # To format or unescape the fetched data
class QuizBrain:
""" Receive question list and hold this list properties like:
No. of questions,
Show next question,
Checks the answer
"""
def __init__(self, q_list):
self.question_number = 0
... | StarcoderdataPython |
3243157 | from pymongo import MongoClient
import requests
def get_database():
CONNECTION_STRING = "mongodb://localhost:27017/"
client = MongoClient(CONNECTION_STRING)
return client['test']
db = get_database()
data = db['images'].find({})
length = len(list(data.clone()))
for doc in data:
print(f"PROCESSING IMAG... | StarcoderdataPython |
3256622 | from collections import defaultdict
from itertools import count
from operator import itemgetter
from pathlib import Path
from typing import Dict, Optional
from typing import List, Tuple, Union
import htbuilder
import streamlit as st
from htbuilder import span, div, script, style, link, styles, HtmlElement, br
from htb... | StarcoderdataPython |
47082 | """
fakedata.py
====================================
Generate artificial pupil-data.
"""
import numpy as np
import scipy.stats as stats
from .baseline import *
from .pupil import *
def generate_pupil_data(event_onsets, fs=1000, pad=5000, baseline_lowpass=0.2,
evoked_response_perc=0.02, respon... | StarcoderdataPython |
104280 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 14:39:35 2015
@author: smichel
# NOTE: notes refer to an older data set. Specific examples may not relate to the latest datafiles (which were released in March 2016, at time this note was written.)
Check this: Add capability for multiple chapters/sections etc. For ex... | StarcoderdataPython |
95580 | <reponame>Leonardo-Maciel/PSO_Maciel<gh_stars>1000+
import textwrap
def DALS(s):
"dedent and left-strip"
return textwrap.dedent(s).lstrip()
| StarcoderdataPython |
34774 | from argparse import ArgumentParser
from sys import stdin, stdout
from tempfile import NamedTemporaryFile
from time import sleep
from webbrowser import open as open_web
from naughtty import NaughTTY
from thtml import get_version
from thtml.cli import write_html
from thtml.options import Scope
def cli_entry() -> Non... | StarcoderdataPython |
3236809 | #!/usr/bin/env python3
import os
import sys
import tempfile
import subprocess
BINS_DIR = 'binaries'
ghidra_dir = sys.argv[1]
headless_path = os.path.join(ghidra_dir, 'support', 'analyzeHeadless')
if os.name == 'nt':
headless_path += '.bat'
with tempfile.TemporaryDirectory(prefix='temp_ghidra2dwarf_') as temp_dir:
... | StarcoderdataPython |
3274658 | """ID admin."""
# Django
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
# Project
from id.models import (
User,
EmailActivationToken,
PasswordResetToken,
TermAndCondition,
UserTermAndCondition,
Country,
Province,
District,
Locality
)
@adm... | StarcoderdataPython |
4804062 | <filename>stu_grade_prediction.py
# -*- coding: utf-8 -*-
"""
@author: Emmanuel
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import warnings
import time
from sklearn.linear_model import ElasticNet, Lasso, Linear... | StarcoderdataPython |
3222968 | <reponame>Arfey/aiohttp_admin2<filename>tests/test_connection_injectors.py<gh_stars>10-100
from aiohttp_admin2.connection_injectors import ConnectionInjector
from aiohttp import web
async def test_connection_injector(aiohttp_client):
"""
In this test we check corrected work of ConnectionInjector:
1. ... | StarcoderdataPython |
1723424 | """Wrappers for Navisworks API classes."""
from npw.db import element
def wrap(nvswrks_mi):
return element.Element(nvswrks_mi)
| StarcoderdataPython |
68788 | # coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.3725
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
from inspect import getargspec as getfullargspec
... | StarcoderdataPython |
1738849 | from qt_core import *
class ClickableQLineEdit(QLineEdit):
#clicked= Signal()
doubleClicked = Signal()
def __init__(self,widget):
super().__init__(widget)
#def mousePressEvent(self,QMouseEvent):
# self.doubleClicked.emit()
def event(self, event):
if event.type() ==... | StarcoderdataPython |
1632866 | <reponame>rubengarciallorens/X-Serv-15.5-Django-CMS<gh_stars>0
from django.contrib import admin
# Register your models here.
from models import Pages
admin.site.register(Pages)
| StarcoderdataPython |
3223489 | """
Context Manager used with the statement 'with' to time some execution.
Example:
with TimingManager() as t:
# code to time
process(its_complicated)
# print measured time, e.g.:
logger.info('Elapsed time {}'.format(time.end_log()))
TODO:
- improve docstring
Based on: http://stackove... | StarcoderdataPython |
17000 | <filename>tests/python/text_utility.py
#~ Copyright 2014 <NAME>.
#~ Distributed under the Boost Software License, Version 1.0.
#~ (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
def read_text(filename):
with open(filename, 'r') as f:
return f.read()
def write_text(filename,... | StarcoderdataPython |
134537 | from PyQt5 import QtWidgets, QtGui
from .resultviewwindow import ResultViewWindow
from ..utils.anisotropy import AnisotropyEvaluator
class ShowAnisotropyWindow(ResultViewWindow):
anisotropyWidget: AnisotropyEvaluator = None
def setupUi(self, Form: QtWidgets.QWidget):
self.anisotropyWidget = Anisotro... | StarcoderdataPython |
165141 | <filename>primeirocodigo.py
# -*- coding: utf-8 -*-
def codigobasico():
valor1 = 800
valor2 = 100
soma = valor1+valor2
print("O valor 1 é: " + str(valor1) + ", O valor 2 é: " + str(valor2) + ", Aqui está o retorno da soma: " + str(soma))
codigobasico()
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.