id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3249445 | # -*- coding: utf-8 -*-
"""
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | StarcoderdataPython |
2180 | # Test definitions for Lit, the LLVM test runner.
#
# This is reusing the LLVM Lit test runner in the interim until the new build
# rules are upstreamed.
# TODO(b/136126535): remove this custom rule.
"""Lit runner globbing test
"""
load("//tensorflow:tensorflow.bzl", "filegroup")
load("@bazel_skylib//lib:paths.bzl", "... | StarcoderdataPython |
3237839 | import time
from load_tests.utils import client_request, stats
def test_peak(stats):
"""send 50 client requests at once with 0.3 delay between them"""
n = 50
delay = 0.3
r = []
for i in range(n):
r.append(client_request("{}:{}".format(n, i), stats))
time.sleep(delay)
for thre... | StarcoderdataPython |
1701891 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class SurveyComposeMessage(models.TransientModel):
_inherit = 'survey.mail.compose.message'
@api.model
def default_get(self, fields):
result = super(SurveyComposeMessa... | StarcoderdataPython |
3203557 | <filename>python/flask/pattern_replace.py<gh_stars>0
# goal: to replace a string in a pattern
# example: "hello" : 3312
# we want to replace 3312 which follows from "hello" :
import re
s1 = '"hello": 3312'
s2 = '"hello" : 3315'
# replace the number after "hello" : to another number
s_r = re.sub('(\s*)("\w+")\s*:\... | StarcoderdataPython |
1796293 | <filename>model/modify_model.py<gh_stars>0
# coding: utf-8
# 封装其他模块对模型的修改接口
# 外部模块只能通过本文件的函数对模型进行修改
from global_data import SUCCESS, Orders, Trucks, Bases
# truck接单,修改模型相关状态:truck/order/base
# 传入参数为object
# 返回是否修改成功
from model.base_model.base import Base
def model_truck_take_orders(truck_id, order_ids):
result ... | StarcoderdataPython |
143414 | import os
import logging
from argparse import ArgumentParser
from concurrent.futures import ThreadPoolExecutor, as_completed
from .lib.saj import StreamAnalyticsJobs
from .lib.utils import chkpath, mklog
def get_args():
parser = ArgumentParser(description="Start or stop Stream Analytics Jobs")
parser.add_arg... | StarcoderdataPython |
79216 | <filename>tystrings/tylogger.py
from .tyformatter import *
from colorama import Fore, Style
from tabulate import tabulate
# Emoji
BEER_EMOJI = u'\U0001F37A '
BEERS_EMOJI = u'\U0001F37B '
GHOST_EMOJI = u'\U0001F47B '
# Log Level
PROCESS = 11
DONE = 12
SUCCESS = 13
ADDITION = 14
class TyLogger(logging.Logger):
... | StarcoderdataPython |
90535 | <reponame>haimadrian/AlgorithmsInMultimediaUsingPython
__author__ = "<NAME>"
import numpy as np
import cv2
from matplotlib import pyplot as plt
# Assignment 1
def normalizeImage(img):
img = img - np.min(img)
img = np.round(img * 255 / np.max(img))
return np.uint8(img)
def myMasking(img, m... | StarcoderdataPython |
1678750 | from utils.utils import get_pair, store_json_dic
import random
from scipy.stats import pearsonr
import scipy
from utils.utils import load_json_dic
import json
import os
import numpy as np
import seaborn as sns
from models.mlm_wrapper import MLMWrapper
def compare_distribution(in_distribution, out_distribution, norm_i... | StarcoderdataPython |
3382368 | <reponame>mdmeadows/DSM-to-DTM
# Visualise: Performance of each modelling approach, with reference to test datasets & zones
# Import required packages
import sys
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors, gridspec
from mpl_toolkits.basemap import Basemap
imp... | StarcoderdataPython |
144460 | <reponame>Karl-Krauth/recommender-RCT<gh_stars>1-10
from __future__ import annotations
import secrets
import time
import typing
import jwt
import werkzeug.security
from . import base
SECRET_KEY = secrets.token_hex(128)
class User(base.db.Model):
__tablename__ = 'users'
id = base.db.Column(base.db.Integer,... | StarcoderdataPython |
1693709 | <reponame>bergran/pokemon_project_example<filename>core/signals/login_signal.py
# -*- coding: utf-8 -*-
from django.core.cache import cache
from django.conf import settings
def get_key_user(username):
return 'user_attempts:{}'.format(username)
def login_success(sender, user, request, **kwargs):
cache.set(ge... | StarcoderdataPython |
1733647 | <filename>gym-trivial/gym_trivial/envs/trivial_env.py
from gym import spaces
from gym.utils import seeding
import gym
import numpy as np
class Trivial (gym.Env):
metadata = {"render.modes": ["human"]}
reward_range = (-100.0, 100.0)
def __init__ (self):
self.reset()
self.action_space = sp... | StarcoderdataPython |
3265637 | <reponame>MarcinDadura/Shamboogeon<filename>classes/monster.py<gh_stars>1-10
from classes.player import Player
import pygame
from pygame.sprite import Sprite
from classes.game_object import GameObject
class Monster(GameObject):
"""Monster abstract obj"""
sprite = None
sound = None
horizontal_directi... | StarcoderdataPython |
3300835 | <gh_stars>0
#sort lists
# file name: romeo.txt
filename=input('Enter the file name:')
file=open(filename)
lista=list()
final=list()
for line in file:
lista=line.split()
for i in lista:
if i not in final:
final.append(i)
final.sort()
print(final)
| StarcoderdataPython |
3234439 | """
Django settings for ryu project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import... | StarcoderdataPython |
1650707 | <reponame>HuberTRoy/pyppeteer
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tracing module."""
import asyncio
from pathlib import Path
from typing import Any, Awaitable
from pyppeteer.connection import CDPSession
from pyppeteer.util import merge_dict
class Tracing(object):
"""Tracing class."""
def __i... | StarcoderdataPython |
168950 | """
mem_check.py
functions for getting memoroy use of the current python process
Downloaded from: http://pythonchb.github.io/PythonTopics/weak_references.html
Windows and *nix versions
USAGE:
amount = get_mem_use(units='MB') # options are KB, MB, GB
"""
import sys
div = {'GB': 1024*1024*1024,
... | StarcoderdataPython |
33831 | <gh_stars>0
def params_create_rels_unwind_from_objects(relationships, property_identifier=None):
"""
Format Relationship properties into a one level dictionary matching the query generated in
`query_create_rels_from_list`. This is necessary because you cannot access nested dictionairies
in the UNWIND qu... | StarcoderdataPython |
1696696 | from perfcomp import ansbile_playbook, pip_diff, rpm_diff
from perfcomp.graphs import graph_ansible_playbook
class JobDiff:
def __init__(self, good, bad, ansible_playbooks_diff, rpm_diff, pip_diff):
self.good, self.bad = good, bad
self.ansible_diff = ansible_playbooks_diff
self.rpm_diff =... | StarcoderdataPython |
4824809 | # Write a program to find the node at which the intersection of two singly linked lists begins.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 先把A用字典保存起来,然后用B中的数字一个个判断是否在字典中存在
class Solution:
def getIntersectionNode(self, headA: Lis... | StarcoderdataPython |
105298 |
from shuffle import SHUFFLE
import csv
shuffle=SHUFFLE()
documents=[]
labell=[]
negative=[]
positive=[]
file="dataset_twitter.csv"
dataset_names=['A','B','C','D','E','F']
Size=[500000,450000,350000,250000,150000,100000]
with open(file) as Data:
reader=csv.reader(Data)
records=list(reader)
... | StarcoderdataPython |
1667856 | player1 = int(input())
player2 = int(input())
winner = input()
out_of_eggs = False
while not winner == "End of battle":
if winner == "one":
player2 -= 1
else:
player1 -= 1
if 0 == player1:
print(f"Player one is out of eggs. Player two has {player2} eggs left.")
out_of_eggs =... | StarcoderdataPython |
4834272 |
from typing import List
from base import version
class Solution:
@version("40ms, 18.3mb")
def solve(self, board: List[List[str]]) -> None:
height, width = len(board), len(board[0])
proxy = [[item for item in row] for row in board]
for m in range(height):
for n in range(... | StarcoderdataPython |
3267190 | from .RandomPerturb import perturb_randCorr
from .RandomCorrNear import nearcorr
from .RandomCorr import randCorr
from .RandomCorrMatEigen import randCorrGivenEgienvalues
from .Diagnostics import CorrDiagnostics, isPD, isvalid_corr
from .ConstantCorr import constantCorrMat | StarcoderdataPython |
1600842 | <filename>events/api/serializers.py
from events.models import Event
from rest_framework import serializers
class EventSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Event
fields = ("id", "title", "start", "url")
| StarcoderdataPython |
49251 | import os
import sys
import cv2
import numpy as np
class Equirectangular:
def __init__(self, img):
self._img = img
#self._img = cv2.imread(img_name, cv2.IMREAD_COLOR)
[self._height, self._width, _] = self._img.shape
print(self._img.shape)
def GetPerspective(self, FOV, THET... | StarcoderdataPython |
135240 |
# Problem code
def countAndSay(n):
if n == 1:
return "1"
current = "1"
for i in range(2, n + 1):
current = helper(current)
return current
def helper(current):
group_count = 1
group_member = current[0]
result = ""
for i in range(1, len(current)):
if current[i] =... | StarcoderdataPython |
1659100 | import logging
from hikcamerabot.camera import HikvisionCam
from hikcamerabot.config import get_result_queue
from hikcamerabot.processes import CameraSupervisorProc
class CameraProcessManager:
"""Camera Process Manager Class."""
def __init__(self, cam_registry, event_q):
self._log = logging.getLogge... | StarcoderdataPython |
92424 | <reponame>maynard242/Machine-Learning-At-Scale
#!/usr/bin/env python
"""
This mapper reads from STDIN and waits 0.001 seconds per line.
Its only purpose is to demonstrate one of the scalability ideas.
"""
import sys
import time
for line in sys.stdin:
time.sleep(0.001) | StarcoderdataPython |
1746168 | from tesi_ao import main220316
import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
from tesi_ao.mems_command_to_position_linearization_measurer import CommandToPositionLinearizationMeasurer
from tesi_ao.mems_command_to_position_linearization_analyzer import CommandToPositionLinearization... | StarcoderdataPython |
1723933 | <reponame>XavierBecerra/block3_py_questionnaire
#Defining imports
import pandas as pd
# QUESTION 4
def compute_drivers_performance():
#pandas library will be used.
#First we import both tables needed for the exercise from the csv provided
orders_df = pd.read_csv("D:/paack/Data/orders_table.csv", sep=',')
... | StarcoderdataPython |
1791211 | # 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, software
# d... | StarcoderdataPython |
103058 | <filename>tests/test_parsing.py
from units_calculator.all import (
Kilograms,
Meters,
Milliseconds,
Seconds,
parse,
parse_pure_units,
)
def test_parse_pure_units() -> None:
test_str = "s^(-1)*kg*m/s"
x = parse_pure_units(test_str)
assert tuple(x) == ((Seconds, -2), (Kilograms, 1), ... | StarcoderdataPython |
6763 | # Author: <NAME> <<EMAIL>>
import numpy as np
from bolero.representation import BlackBoxBehavior
from bolero.representation import DMPBehavior as DMPBehaviorImpl
class DMPBehavior(BlackBoxBehavior):
"""Dynamical Movement Primitive.
Parameters
----------
execution_time : float, optional (default: 1)
... | StarcoderdataPython |
1727762 | from django.core.management.base import BaseCommand
from common.utils import progress_bar
from intrinsic.models import IntrinsicImagesDecomposition
from intrinsic.tasks import upload_intrinsic_file
class Command(BaseCommand):
args = ''
help = 'Upload images to EC2'
def handle(self, *args, **options):
... | StarcoderdataPython |
19804 | <reponame>viditvarshney/100DaysOfCode
from logo import logo
def add(n1, n2):
return n1 + n2
def multiply(n1, n2):
return n1 * n2
def subtract(n1, n2):
return n1 - n2
def divide(n1, n2):
return n1 / n2
symbols = ['+', '-', '/', '*']
operations = {'+': add, '-': subtract,
'*': mult... | StarcoderdataPython |
3240398 | <reponame>ATLJoeReed/branch_data_engineering<gh_stars>0
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
import io
import os
import sys
import pandas as pd
from utils import helpers
def extract_election_results(logger):
logger.info('Starting to extract election summary results')
try:
conn = helpers.get... | StarcoderdataPython |
1783346 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# FEDERAL UNIVERSITY OF UBERLANDIA
# Faculty of Electrical Engineering
# Biomedical Engineering Lab
# ------------------------------------------------------------------------------
# Author: <NAME>
# Contact: <EMAIL... | StarcoderdataPython |
3229794 | # -*- coding: utf-8 -*-
import errno
import re
from datetime import datetime
from itertools import tee
from shutil import rmtree, copytree
import networkx
import jinja2
from pathlib2 import Path
STATIC_DIR = Path(__file__).parent/'static'
class RouteSchedule(object):
_DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'... | StarcoderdataPython |
4807994 | import inspect
from collections import defaultdict
from typing import Any, Callable, Dict, List, Optional, Tuple
from openff.toolkit.typing.engines.smirnoff import (
ForceField,
ParameterAttribute,
ParameterHandler,
)
from openff.toolkit.utils import all_subclasses
from openff.units import unit
from openff... | StarcoderdataPython |
1799379 | from enum import Enum
import copy
from abc import ABC, abstractmethod
import numbers
from itertools import count
import numpy as np
import scipy
class Type(Enum):
Continuous = 'c'
Discrete = 'o'
class DuplicateHyperparameterError(Exception):
pass
class MissingHyperparameterError(Exception):
pass... | StarcoderdataPython |
3337108 | <filename>ex022/ex022.py
print('-=-=- Analisando de Textos -=-=-')
nome = str(input('Digite seu nome aqui: ')).strip()
print(f'Seu nome em letra maiúscula é {nome.upper()}')
print(f'Seu nome em letras minúsculas é {nome.lower()}')
print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' ')))
#print(f'Se... | StarcoderdataPython |
1615161 | import pytest
from django.urls import reverse
@pytest.mark.django_db(transaction=True, reset_sequences=True)
def test_healthcheck(app):
url = reverse("healthcheck")
response = app.get(url).json
assert response["detail"] == "Everything works"
@pytest.mark.django_db(transaction=True, reset_sequences=True)... | StarcoderdataPython |
127433 | """Example demonstrating a basic usage of choke package."""
from time import sleep
from redis import StrictRedis
from choke import RedisChokeManager, CallLimitExceededError
REDIS = StrictRedis() # Tweak this to reflect your setup
CHOKE_MANAGER = RedisChokeManager(redis=REDIS)
# Example configuration: enforce limit o... | StarcoderdataPython |
3272602 | import logging
import os
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, ctx):
logger.info("Handling as %s", ctx.function_name)
logger.info("env %s", os.environ)
return {
"statusCode": 200,
"body": "hello python"
} | StarcoderdataPython |
1773203 | <gh_stars>0
def superDigit(n, k):
if len(n) == 1:
return int(n)
cur_sum = 0
for d in n:
cur_sum += int(d)
cur_sum *= k
return superDigit(str(cur_sum), 1)
# Test cases:
print(superDigit('123', 3))
print(superDigit('148', 3))
print(superDigit('9875', 4))
| StarcoderdataPython |
3344449 | <reponame>jadarve/lluvia<filename>lluvia/bazel/node/macros.bzl
"""
"""
load("@rules_vulkan//glsl:defs.bzl", "glsl_shader")
load("@rules_pkg//:pkg.bzl", "pkg_zip")
load("@rules_pkg//experimental:pkg_filegroup.bzl", "pkg_filegroup")
def ll_node(
name,
shader,
builder,
deps = None,
... | StarcoderdataPython |
142731 | import os
from typing import List
from asm_utils import hex_to_bin
def read_obj(obj_file: str) -> List[str]:
"""Reads object file and returns list of instructions
Parameters
----------
obj_file : str
path to object file
Returns
-------
List[str]
list of instructions in th... | StarcoderdataPython |
61558 | <reponame>twerkmeister/table-segmenter
import argparse
from typing import Text
import os
import table_segmenter.model
import table_segmenter.io
import table_segmenter.preprocessing
import table_segmenter.metrics
import tensorflow
from tensorflow import keras
def load_data_for_training(data_path: Text):
"""Conven... | StarcoderdataPython |
7905 | from flask import Flask, render_template, request, redirect, url_for
from os.path import join
from stego import Steganography
app = Flask(__name__)
UPLOAD_FOLDER = 'static/files/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
@app.route("/")
def home():
return render_te... | StarcoderdataPython |
1797763 | # -*- coding: utf-8 -*-
import socket
import time
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ
def get(path):
s = socket.socket()
s.connect(('localhost', 5000))
request = 'GET {} HTTP1.0\r\n\r\n'.format(path)
s.send(request.encode())
chunks = []
while True:
chunk =... | StarcoderdataPython |
1723482 | import numpy
from matchms import Fragments, Spectrum
from matchms.filtering import normalize_intensities
def _create_test_spectrum():
intensities = numpy.array([1, 1, 5, 5, 5, 5, 7, 7, 7, 9, 9], dtype="float")
return _create_test_spectrum_with_intensities(intensities)
def _create_test_spectrum_wit... | StarcoderdataPython |
3281305 | <gh_stars>0
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Email
class LoginForm(FlaskForm):
email = StringField('Email', validators=[InputRequired(), Email()])
password = PasswordField('Password', validators=[Inpu... | StarcoderdataPython |
4820098 | from planner import *
from othertools import *
import matplotlib.pyplot as plt
def main():
score_2t = readfile('rq1_TimeLIME.csv')
score_2f = readfile('rq1_LIME.csv')
scores2_x = readfile('rq1_XTREE.csv')
scores2_alve = readfile('rq1_Alves.csv')
scores2_shat = readfile('rq1_Shat.csv')
scores2_... | StarcoderdataPython |
1637920 | """Support for Stateless Exterior Heating device."""
import logging
from pyoverkiz.enums import OverkizCommand
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import HVAC_MODE_HEAT, HVAC_MODE_OFF
from homeassistant.const import TEMP_CELSIUS
from ..entity import ... | StarcoderdataPython |
1637530 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, _
class StockPicking(models.Model):
_inherit = "stock.picking"
def _pre_action_done_hook(self):
res = super()._pre_action_done_hook()
# We use the 'skip_expired' contex... | StarcoderdataPython |
163222 | <filename>django-rgd-imagery/rgd_imagery/rest/download.py
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import api_view
from rgd.permissions import check_read_perm
from rgd_imagery import models
... | StarcoderdataPython |
3320575 | from .css_format import CSSFormatter
| StarcoderdataPython |
3308708 | <gh_stars>0
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from requests import get
import helper
import data
class Details(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Chrome()
self.browser.get(data.Register.registerURL)
def te... | StarcoderdataPython |
89572 | # Copyright 2004-2008 <NAME>.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""contains classes that allow to configure code generation for free\\member functions, operators and etc."""
import os
from . import u... | StarcoderdataPython |
3215223 | <reponame>borninfreedom/vismod<filename>vismod.py<gh_stars>1-10
import tkinter as tk
from tkinter import ttk
from view_model import ViewModel
from add_slidebar import AddSlideBar
from config import WINDOW_WIDTH, WINDOW_HEIGHT
WINDOW_SIZE = str(WINDOW_WIDTH) + 'x' + str(WINDOW_HEIGHT)
class Vismod(tk.Frame):
def... | StarcoderdataPython |
44247 | """Wikidump reader and processor module.
"""
import os
with open(os.path.join(
os.path.dirname(__file__),
'scripts',
'DUMP_VERSION')) as f:
DUMP_VERSION = f.readline().strip()
with open(os.path.join(
os.path.dirname(__file__),
'scripts',
'TORRENT_HASH')) as f:
... | StarcoderdataPython |
3381120 | #
# Class for particle-size distributions, one distribution at every
# x location of the electrode, with uniform concentration in each
# particle
#
import pybamm
from .base_distribution import BaseSizeDistribution
class UniformProfile(BaseSizeDistribution):
"""
Class for molar conservation in particle-size d... | StarcoderdataPython |
3363139 | class butter_filters:
def __init__(self, data=[0.0], cutoff=2.0, fs=30.0, order=2, type="enumerate(('low', 'high'))"):
from scipy.signal import butter,filtfilt
nyq = 0.5 * fs # Nyquist Frequency
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype=type, analog=Fal... | StarcoderdataPython |
159184 | <gh_stars>1-10
'''
Created by <NAME>
Feb 1, 2018
'''
from sys import stdout
import re, json, requests
from bs4 import BeautifulSoup
from pyvirtualdisplay import Display
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.com... | StarcoderdataPython |
3395608 | """Implements get process fot master playlist."""
from logging import getLogger
from typing import Mapping, Union
import m3u8 # type: ignore
from radikoplaylist.authorization import Authorization
from radikoplaylist.master_playlist import MasterPlaylist
from radikoplaylist.master_playlist_request import MasterPlayli... | StarcoderdataPython |
11318 | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | StarcoderdataPython |
1638728 | import maya.cmds as mc
import data
class SetData( data.Data ):
'''
SetData class object.
Contains functions to save, load and rebuild maya sets.
'''
def __init__(self,setNode=None):
'''
SetData class initializer.
'''
# Execute Super Class Initilizer
super(SetData, self).__init__()
# Initialize ... | StarcoderdataPython |
3391905 | from autovirt.structs import Message
def build_innovations_renewal_list(messages: list[Message]) -> list:
renewal = []
for message in messages:
for attach in message.attaches:
renewal.append(attach)
return renewal
| StarcoderdataPython |
27320 | from nndct_shared.utils import registry
| StarcoderdataPython |
3309382 | <reponame>imabackstabber/segment-with-nn<gh_stars>1-10
# coding=utf-8
import unittest
import logging
import tensorflow as tf
from segelectri.data_loader.utils.parse_img_op import parse_img_and_mask
class TestParseImgOp(unittest.TestCase):
def test_true(self):
self.assertTrue(True)
def parse_sample_f... | StarcoderdataPython |
1648589 | <filename>preprocessing.py
"""
Modulo
Neural Modular Networks in PyTorch
preprocessing.py
"""
import argparse
import os
import pickle
import numpy as np
from itertools import chain
from torch.autograd import Variable
import torch
from torch import LongTensor, FloatTensor
from torch.cuda import LongTensor as CudaLong... | StarcoderdataPython |
22940 | #%% [markdown]
#
# We will load EEG data from the lab and attemp to build a classifier that distinguishes between learners and non-learners
#%%
import mne
import numpy as np
import os.path
import glob
import re
import pandas as pd
# try to enable cuda support to speed up filtering, make sure the MNE_USE_C... | StarcoderdataPython |
3312501 | import numpy as np
import torch
from utils import *
class MuRP(torch.nn.Module):
def __init__(self, d, dim):
super(MuRP, self).__init__()
self.Eh = torch.nn.Embedding(len(d.entities), dim, padding_idx=0)
self.Eh.weight.data = (1e-3 * torch.randn((len(d.entities), dim), dtype=torch.double, ... | StarcoderdataPython |
3321325 | '''Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
O... | StarcoderdataPython |
3249353 | # -*- coding: utf-8 -*-
"""
Codes for GPU Caculation.
Created on Thu Apr 27 19:47:13 2017
@author: cheny
"""
import numpy as np
import math
def calc_density_gpu(xs,ys,weights,kernel_type,cutoffd=0,sigma=0):
from numba import cuda, float64,float32
@cuda.jit
def calc_density_gauss_cuda(xs,ys,weight... | StarcoderdataPython |
3267635 | # 이미지 주변에 padding을 넣고 300*300으로 변환, 저장하기.
import cv2
import numpy as np
from imutils import paths
filepath = "C:\\Users\\haram\\PycharmProjects\\OpenBankProject\\1024data\\1"
imagePaths = list(paths.list_images(filepath))
size = 500
for i, imagePath in enumerate(imagePaths):
save_dicname = imagePath.split('\\')
... | StarcoderdataPython |
1688748 | <reponame>EagleMIT/m-i-d
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
class FocalLoss(nn.Module) :
def __init__(self, gamma=0, alpha=None, size_average=True) :
super(FocalLoss, self).__init__()
self.gamma = gamma
self.alpha = alpha
... | StarcoderdataPython |
4840233 | from typing import List
from collections import defaultdict
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
edge_count, max_count = defaultdict(int), 0
for row in wall:
s = 0
for brick in row[0:-1]:
s += brick
edge_count[... | StarcoderdataPython |
41083 | """Checks if any of the latests tests has performed considerably different than
the previous ones. Takes the log directory as an argument."""
import os
import sys
from testsuite_common import Result, processLogLine, bcolors, getLastTwoLines
LOGDIR = sys.argv[1] #Get the log directory as an argument
PERCENTAGE = 5 #De... | StarcoderdataPython |
167036 | import unittest
import pytest
from tfsnippet.utils import BaseRegistry, ClassRegistry
class RegistryTestCase(unittest.TestCase):
def test_base_registry(self):
a = object()
b = object()
# test not ignore case
r = BaseRegistry(ignore_case=False)
self.assertFalse(r.ignore_... | StarcoderdataPython |
1734848 | <reponame>codelovin/kaggle-utils
class BlenderBase:
def __init__(self, name):
self.name = name
def blend(self, scores, *args):
raise NotImplementedError
class PowerBlend(BlenderBase):
def __init__(self):
super().__init__("")
def blend(self, scores, lin_coefs, exp_coef... | StarcoderdataPython |
144451 | """Test gates defined in `qibo/core/gates.py`."""
import pytest
import numpy as np
from qibo import gates, K
from qibo.config import raise_error
from qibo.tests.utils import random_state, random_density_matrix
def apply_gates(gatelist, nqubits=None, initial_state=None):
if initial_state is None:
state = K... | StarcoderdataPython |
4815379 | <reponame>MateusGundel/python-utils
from random import shuffle
continue = 'S'
while continue.upper()
words = input("insira a frase: ").split(" ")
for word in words: shuffle(words)
print(" ".join(words))
continue = input('Digite S para continuar') | StarcoderdataPython |
1723062 | <filename>nrpc/__init__.py<gh_stars>1-10
from .lib import (
parse_subject,
parse_subject_tail,
streamed_reply_request,
streamed_reply_handler,
)
from .exc import ClientError
__all__ = [
"ClientError",
"parse_subject",
"parse_subject_tail",
"streamed_reply_request",
"streamed_reply_h... | StarcoderdataPython |
89078 | <gh_stars>0
#/* n=int(input("Enter the number to print the tables for:"))
#for i in range(1,11):
# print(n,"x",i,"=",n*i)
n=int(input("Enter the number"))
for i in range(1,11):
print (n ,"x", i, "=", n * i)
| StarcoderdataPython |
1661080 | <gh_stars>0
"""
Display drag from the app into the graph widget and the event bridge.
This is similar to the hello world sample.
"""
import sys
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QDrag
from PyQt5.QtWidgets import (
QGridLayout,
QMainWindow,
QPushButton,
... | StarcoderdataPython |
4811470 | <filename>tests/musicxml/elements/note/test_rest.py
from unittest import TestCase
from musicscore.musicxml.elements.fullnote import DisplayStep, DisplayOctave, Rest
class TestRest(TestCase):
def setUp(self):
self.rest = Rest()
def test_rest(self):
result = '''<rest/>
'''
self.assertE... | StarcoderdataPython |
3314733 | import numpy as np
from kalah.agents.randomagent import RandomAgent
from kalah.agents.maxscoreagent import MaxScoreAgent
from kalah.agents.maxscorerepeatagent import MaxScoreRepeatAgent
from kalah.agents.minimaxagent import MinimaxAgent
from kalah.kalahagentfactory import KalahAgentFactory
import unittest
class Tes... | StarcoderdataPython |
4832336 | class Car(object):
condition = "new"
my_car = Car()
print(my_car.condition)
| StarcoderdataPython |
82554 | __all__ = ["euler_gamma_law", "sr_euler_gamma_law", "sr_mhd", "sr_rmhd", "sr_mf"]
| StarcoderdataPython |
1654489 | <reponame>puyomi/gostagram
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models, serializers
class NotifyToUser(APIView):
def get(self, request, format=None):
user = request.user
notification = models.Notifica... | StarcoderdataPython |
1632944 | <reponame>Princeton21/DSA
class newNode:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def verticalSumUtil(root, hd, Map):
if root == None:
return
verticalSumUtil(root.left, hd - 1, Map)
if hd in Map.keys():
Map[hd] = Map[hd] ... | StarcoderdataPython |
3246530 | #!/usr/bin/python3
import sklearn.datasets
# parameters are n, dimension, useful_dimension, noise level
n = 10**4
dim = 30
useful_dim = 25
sigma = 1.0
X, Y = sklearn.datasets.make_regression(n, dim, useful_dim, noise=sigma)
# maximum one-norm of any x or y
max_y_norm = max(Y)
max_x_norm = max([sum(list(map(abs,x)))... | StarcoderdataPython |
4815168 | #!/usr/bin/env python
'''
isobands_matplotlib.py is a script for creating isobands.
Works in a similar way as gdal_contour, but creating polygons
instead of polylines
This version requires matplotlib, but there is another one,
isobands_gdal.py that uses only GDAL python
Originally created by <NAME>, made available vi... | StarcoderdataPython |
1709215 | """
Aggregations.
| Copyright 2017-2021, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import numpy as np
import eta.core.utils as etau
from fiftyone.core.expressions import ViewField as F
import fiftyone.core.media as fom
import fiftyone.core.utils as fou
class Aggregation(object):
"""Abstract b... | StarcoderdataPython |
4812459 | #
# Copyright (c) 2013,2014, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the... | StarcoderdataPython |
65845 | import logging
import os
import numpy as np
import xml.etree.ElementTree as ET
from PIL import Image
from paths import DATASETS_ROOT
log = logging.getLogger()
VOC_CATS = ['__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle',
'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'hors... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.