id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
83249
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets 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 app...
StarcoderdataPython
1608755
<gh_stars>0 # Copyright (c) 2021 PaddlePaddle 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 requi...
StarcoderdataPython
94833
import os, sys, json from collections import Counter def load_data(path): data = {} for line in open(path, 'r'): jobj = json.loads(line.strip()) sentid = jobj['sentid'] assert sentid not in data data[sentid] = [] conversation = jobj['sent'].replace('<SEP>', '', 100).spl...
StarcoderdataPython
3393110
<filename>utils/neuron/models/losses/losses.py<gh_stars>10-100 import torch import torch.nn as nn import neuron.ops as ops from neuron.config import registry __all__ = ['BalancedBCELoss', 'FocalLoss', 'GHMC_Loss', 'OHEM_BCELoss', 'LabelSmoothLoss', 'SmoothL1Loss', 'IoULoss', 'GHMR_Loss', 'Tripl...
StarcoderdataPython
1688194
<gh_stars>0 from django.apps import AppConfig class JoladnijoConfig(AppConfig): name = 'joladnijo' verbose_name = '<NAME>' def ready(self): import joladnijo.signals # noqa: F401
StarcoderdataPython
141365
<gh_stars>1-10 #!/usr/bin/env python3 import netifaces as nf import psutil as ps import socket import time # https://github.com/sindresorhus/cli-spinners/blob/HEAD/spinners.json # spin = ['|','/','-','\\','+'] # spin = ["◴","◷","◶","◵"] # spin = ["◐","◓","◑","◒"] spin = ["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"] wrap ...
StarcoderdataPython
3297967
# The MIT License # Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS) # Copyright (c) 2017-2020 Estonian Information System Authority (RIA) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"...
StarcoderdataPython
1667108
from .oauth2 import load
StarcoderdataPython
1643731
<filename>project_files/spiders/test/ThreadPoolTest.py import threading import time from concurrent.futures import ThreadPoolExecutor exitFlag = 0 class ThreadDemo(threading.Thread): def __init__(self, thread_id, name, counter): threading.Thread.__init__(self) self.thread_id = thread_id s...
StarcoderdataPython
4810470
# # K2HDKC DBaaS based on Trove # # Copyright 2020 Yahoo Japan Corporation # # K2HDKC DBaaS is a Database as a Service compatible with Trove which # is DBaaS for OpenStack. # Using K2HR3 as backend and incorporating it into Trove to provide # DBaaS functionality. K2HDKC, K2HR3, CHMPX and K2HASH are components # provide...
StarcoderdataPython
1679707
import unittest from unittest.mock import Mock from PySide.QtGui import QApplication from libtuto.size import Size from libtuto.tutorial import Tutorial from plustutocenter.definitions.mvp import Controller from plustutocenter.qt.view_qt import ViewQt from plustutocenter.qt.widgets.main_window import MainWindow cl...
StarcoderdataPython
63696
<filename>pyowapi/tests/test_api.py<gh_stars>1-10 from unittest import TestCase import pyowapi class TestAPI(TestCase): def test_single_player(self): player = pyowapi.get_player("Jayne#1447") self.assertTrue(player.success) def test_single_player_playstation(self): player = pyowapi.ge...
StarcoderdataPython
160380
import torch from torch import nn from torch.nn import functional as F from torch import optim from torch.autograd import Variable import numpy as np class ConcreteDropout(nn.Module): def __init__(self, weight_regularizer=1e-7, dropout_regularizer=1e-6, init_min=0.1, init_max=0.1): super(C...
StarcoderdataPython
3222652
<filename>code/sheet_cleaner/sheet_processor.py import logging import os from datetime import datetime from typing import List import configparser import pandas as pd from geocoding import csv_geocoder from spreadsheet import GoogleSheet from functions import (duplicate_rows_per_column, fix_na, fix_sex, ...
StarcoderdataPython
1685358
from django.db import models, migrations import core.models class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20150126_1611'), ] operations = [ migrations.AlterField( model_name='person', name='birth_date', field=models.DateFi...
StarcoderdataPython
39848
{ "targets": [ { "target_name": "gpio", "sources": ["gpio.cc", "tizen-gpio.cc"] } ] }
StarcoderdataPython
3269806
import pytest from django.urls import reverse @pytest.mark.django_db def test_plan_unit_detail( django_db_setup, admin_client, plan_unit_factory, lease_test_data ): # Add plan unit for lease area plan_unit_factory( identifier="PU1", area=1000, lease_area=lease_test_data["lease_area...
StarcoderdataPython
3397921
<reponame>yushroom/FishEngine_-Experiment<filename>GenProperty.py<gh_stars>1-10 def GenCPPProperty(type, name): assert(name.startswith('m_')) # if name.startswith('m_'): # name = name[2:] pretty_name = name[2:] # print '+++++++++++++' # print('') if type in ('int', 'float', 'bool', 'uin...
StarcoderdataPython
4821735
<gh_stars>1-10 from __future__ import absolute_import, print_function, division import numpy as np from xmeos.models import core import pytest import matplotlib.pyplot as plt import matplotlib as mpl from abc import ABCMeta, abstractmethod import copy #==================================================================...
StarcoderdataPython
3295643
degree = int(input()) time_of_the_day = input() outfit = "" shoes = "" if time_of_the_day == "Morning": if 10 <= degree <= 18: outfit = "Sweatshirt" shoes = "Sneakers" elif 18 < degree <= 24: outfit = "Shirt" shoes = "Moccasins" else: outfit = "T-Shirt" shoes...
StarcoderdataPython
3245724
# -*- coding: utf-8 -*- """ Created on Mon Mar 30 23:26:47 2020 @author: Js0805 """ import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import autocorrelation_plot from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_squared_error dataset_1= pd.read_excel(...
StarcoderdataPython
4835675
""" from dataclasses import dataclass @dataclass class HsmScript: name: str default_params: dict use_large_stack: bool = True """ class HsmScript(object): def __init__(self, name: str, default_params: dict, use_large_stack: bool = True): self.name = name self.default_params = default_...
StarcoderdataPython
1724622
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: <NAME> 9/24/14 This script reads in an per base bedtools gff, the source gff file, and then calculates the length and average coverage depth of each feature. It also concats start stop positions for ...
StarcoderdataPython
159027
<reponame>likein12/comprog-cffi-pypy-set<gh_stars>0 coset_init = lib.coset_init_ll insert = lib.cs_insert_ll remove = lib.cs_remove_ll get_s = lib.cs_get_size_ll clear = lib.cs_clear_ll get_min = lib.cs_min_ll get_max = lib.cs_min_ll upper_bound = lib.cs_upper_bound_ll rupper_bound = lib.cs_rupper_bound_ll get_k = l...
StarcoderdataPython
1695172
<gh_stars>0 import setuptools import pubsub_zmq def get_long_desc(): with open("README.rst", "r") as fh: return fh.read() setuptools.setup( name="pubsub-zmq", version=pubsub_zmq.__version__, author="<NAME>", author_email="<EMAIL>", description="A tiny library that implements the Asyn...
StarcoderdataPython
3368965
# Generated by Django 2.1.7 on 2019-05-21 13:27 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Company', fields=[ ('id', models.AutoField(...
StarcoderdataPython
97644
<gh_stars>0 label_name = [] with open("label_name.txt",encoding='utf-8') as file: for line in file.readlines(): line = line.strip() name = (line.split('-')[-1]) if name.count('|') > 0: name = name.split('|')[-1] print(name) label_name.append((name)) for item in...
StarcoderdataPython
194036
#!/usr/bin/python import glob import logging import os.path import sys import configure from cs.CsHelper import mkdir from cs.CsPasswordService import CsPasswordServiceVMConfig from databag.merge import QueueFile OCCURRENCES = 1 LOG_DIR="/var/log/cosmic/router" if not os.path.isdir(LOG_DIR): mkdir(LOG_DIR, 0o7...
StarcoderdataPython
3213010
<reponame>saewashi/R1-peer-review-blcmill<filename>funone.py #!/usr/bin/env python ''' For this exercise, draw a circle wherever the user clicks the mouse ''' import sys, pygame import random from datetime import datetime# #Was assert sys.version_info >= (3,4), 'This script requires at least Python 3.4' screen_size ...
StarcoderdataPython
3318422
<reponame>pcen/pulumi # coding=utf-8 # *** WARNING: this file was generated by test. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities imp...
StarcoderdataPython
3307300
<gh_stars>1000+ """Exception classes used by Pexpect""" import traceback import sys class ExceptionPexpect(Exception): '''Base class for all exceptions raised by this module. ''' def __init__(self, value): super(ExceptionPexpect, self).__init__(value) self.value = value def __str__(s...
StarcoderdataPython
32679
# encoding: utf-8 # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: <NAME> (<EMAIL>) # from __future__ import absolute_import, division, unicode_literals fr...
StarcoderdataPython
78892
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
StarcoderdataPython
1719571
''' Created on 21 déc. 2020 @author: robert ''' import math from trajectory.Environment.Constants import Feet2Meter from trajectory.Environment.Earth import EarthRadiusMeters from trajectory.Guidance.GeographicalPointFile import GeographicalPoint class RunWay(GeographicalPoint): ''' The Charles De Gaul...
StarcoderdataPython
1793351
<gh_stars>0 # Typed namedtuple from typing import NamedTuple class Employee(NamedTuple): """Represents an employee.""" name: str id: int = 3 employee = Employee('Patrick', 2) print(employee) print(employee.__annotations__) print(employee.__doc__) # Another way to represent typed named tuples Police = Nam...
StarcoderdataPython
48490
<reponame>JTechnologies/daze-tool #!/usr/bin/env python import sys import os def split(delimiters, string, maxsplit=0): import re regexPattern = '|'.join(map(re.escape, delimiters)) return re.split(regexPattern, string, maxsplit) def toHtml(input, outputPart="full"): head=input.split("$content")[0] bod...
StarcoderdataPython
107022
<reponame>wy1157497582/arcpy # -*- coding:utf-8-*- import arcpy import time # import datetime try: cursor = arcpy.da.InsertCursor(r'E:\苍穹软件\20171030_房屋\xy.shp', "SHAPE@") for x in range(0, 25): cursor.insertRow([x]) del cursor except arcpy.ExecuteError: print arcpy.GetMessages()
StarcoderdataPython
4823977
<reponame>ssbgp/data-tools from processing.data_loader import DataLoader from processing.data_processor import DataProcessor from processing.errors import ProcessingError from processing.file_container import FileContainer from processing.file_selector import FileSelector from tools.utils import print_error class App...
StarcoderdataPython
4807075
#!/usr/bin/env python import json import os import re import subprocess devnull = open(os.devnull) extensions_path = '/home/matejc/.config/chromium/Default/Extensions' def list_apps(path): result = [] for root, dirs, files in os.walk(path, followlinks=True): if files: for file in files: ...
StarcoderdataPython
1702792
from keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition np.random.seed(5) # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.resh...
StarcoderdataPython
3376795
<gh_stars>0 import numpy as np def n_kron(*inputs): """Return Kronecker product of a variable number of inputs. Args: Variable number of input matrices and vectors Returns: Kronecker product """ kp = np.array([[1.0]]) for op in inputs: kp = np.kron(kp, o...
StarcoderdataPython
3249630
import pathlib import responses from krypto.cli import IssueRunner from krypto.github import prepare_body from tests.conftest import ( sample_config, username, repository, url, todo_from_json, raw_todo, ) def test_runner(): runner = IssueRunner( "./tests", pathlib.Path.cw...
StarcoderdataPython
3386191
"""Global variables for Skyrim Unlocked build system""" import os DIR_REPO = "C:\\Users\\user\\Documents\\GitHub\\skyrim-unlocked" """Directory where the git repository for Skyrim Unlocked is stored.""" DIR_REPO_LE = DIR_REPO """Directory where all mod files for Legendary Edition are stored.""" DIR_REPO_SE = os.path...
StarcoderdataPython
1680061
<filename>resupply_runner.sikuli/resupply_runner.py from common import Common, logged from fleet import Fleet from sikuli import * from config import Config from status import Status class ResupplyRunner(Common): def __init__(self, fleets, from_small_resuppy=False, enable_expedition_check=False, message=None): ...
StarcoderdataPython
3253924
" URL definitions " from django.conf.urls.defaults import url, patterns username = '(?P<username>[-\w]+)' urlpatterns = patterns('jetpack.views', # browsing packages url(r'^addons/$', 'browser', {'type_id': 'a'}, name='jp_browser_addons'), url(r'^libraries/$', 'browser', {'type_id': 'l'}, ...
StarcoderdataPython
72652
<filename>app/app/calc.py def add(x, y): """Adds two numbers""" return x+y def subtract(x, y): """Subtracts two numbers""" return x-y
StarcoderdataPython
3223949
# Generated by Django 3.2.10 on 2021-12-29 04:17 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('eye', '0002...
StarcoderdataPython
4830185
<filename>drwr/scripts/tf_records_generator.py import startup import sys import os import glob import re import random import math import numpy as np from scipy.io import loadmat from imageio import imread from skimage.transform import resize as im_resize from util.fs import mkdir_if_missing from util.data import t...
StarcoderdataPython
59044
<filename>courier/elements/statistics.py from dataclasses import dataclass, field from typing import Any, Dict, List, Tuple from courier.config import get_config from courier.utils import flatten from .elements import CourierIssue CONFIG = get_config() @dataclass class IssueStatistics: issue: CourierIssue ...
StarcoderdataPython
146344
from setuptools import setup, find_packages from visual_perception import __version__ with open("README.md", "r") as fh: long_description = fh.read() setup( name='visual_perception', version = __version__, description='A High Level Python Library for Visual Recognition ', url="https://github.com/S...
StarcoderdataPython
1799163
<reponame>mattjm/iam-messaging<filename>tools/aws_manage.py # # IAM AWS messaging mgement # # json classes import json import base64 import string import time import re import os.path from sys import exit import signal from optparse import OptionParser import threading import logging from messagetools.iam_message i...
StarcoderdataPython
3203559
class Player(): """docstring for Player""" def __init__(self): super(Player, self).__init__() self.inventory = [] class Scene(): """docstring for Scene""" def __init__(self, intro, keywords, player=None, condition=None, success=None, fail=None): super(Scene, self).__init__() ...
StarcoderdataPython
1781455
import datetime from datetime import datetime # imports for discord api import discord from discord.ext import commands from discord.ext.commands import has_permissions from discord.ext.commands import CommandNotFound from discord.ext import tasks # extras import asyncio import requests import json import pytz from p...
StarcoderdataPython
1739208
# Copyright 2018-20 <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) # This script parses the IDNA table from # https://unicode.org/Public/idna/11.0.0/IdnaMappingTable.txt, # and converts it to a C++ table. ...
StarcoderdataPython
3208829
import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path...
StarcoderdataPython
3304075
<reponame>Kevincrh/multi-model_fusion import os import bisect import config import numpy as np import os.path as osp import matplotlib.pyplot as plt from tqdm import tqdm from glob import glob from math import isnan from random import shuffle from mpl_toolkits.mplot3d import Axes3D def des(a, b): return np.linalg...
StarcoderdataPython
1718579
import scrapy class StackOverSpider(scrapy.Spider): """Scraper for google serach.""" name = "stack_spider" def __init__(self): """Initialize the spider.""" super(StackOverSpider, self).__init__() self.start_urls = ['StackOverflow.com/jobs'] def parse(self, response): ...
StarcoderdataPython
1632617
import discord from discord.ext import commands import serial arduino = serial.Serial('/dev/ttyACM0', 9600) bot = commands.Bot(command_prefix=".") @bot.event async def on_ready(): print("bot is ready") @bot.command() async def temp(ctx): arduino.write(b't') t = arduino.readline() print(t.d...
StarcoderdataPython
3320636
""" Library Features: Name: lib_jupyter_plot_ts Author(s): <NAME> (<EMAIL>) Date: '20210113' Version: '1.0.0' """ ####################################################################################### # Libraries import os import pandas as pd from library.jupyter_generic.lib_jupyter_utils...
StarcoderdataPython
3368282
import re def find_longest_path_length(path): r'''Finds the longest path to a file in a representation of a filesystem. >>> find_longest_path_length("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext") # noqa 32 >>> find_longest_path_length("dir\n\tsubdir1\n\tsu...
StarcoderdataPython
146863
<reponame>datavaluepeople/tentaclio<gh_stars>10-100 import pytest from tentaclio.clients import base_client, decorators class TestCheckConn: def test_missing_connection_attribute(self): class TestClient: @decorators.check_conn def func(self): return True ...
StarcoderdataPython
3392345
<gh_stars>1-10 import os from dotenv import load_dotenv load_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv('DEBUG', default=False) def comma_separated_list(va...
StarcoderdataPython
1667198
import logging import time from dataclasses import dataclass from dataclasses import field from enum import Enum from os import system from typing import Callable import irsdk from racelogger.model.recorderstate import RecorderState from racelogger.processing.carproc import CarProcessor from racelogger.processing.dri...
StarcoderdataPython
3399903
<reponame>HogniJacobsen/Kattis-solutions. hand = input().split() dominant = hand[1] values = {'A':[11,11],'K':[4,4],'Q':[3,3],'J':[20,2],'T':[10,10],'9':[14,0],'8':[0,0],'7':[0,0],} sum = 0 for i in range(int(hand[0]) * 4): number = input() if number[1] == dominant: sum += values[number[0...
StarcoderdataPython
3235305
<reponame>cdoebler1/AIML2<filename>test/programytest/utils/files/test_config.py import unittest from programy.utils.files.filewriter import FileWriterConfiguration class FileWriterConfigurationTests(unittest.TestCase): def test_init_defaults(self): config = FileWriterConfiguration("filename.txt") ...
StarcoderdataPython
167730
<reponame>wowvwow/Phala-Network #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import requests import json def dingtalk(txt): print(txt) headers = {"Content-Type": "application/json"} data = {"msgtype": "text", "text": {"content": txt}} json_data = json.dumps(data) access_token = '111...
StarcoderdataPython
3295570
<reponame>timo95/knausj_talon from talon import Module, Context # --- App definitions --- mod = Module() mod.apps.fanfictionnet = """ tag: browser browser.host: www.fanfiction.net browser.host: m.fanfiction.net """ mod.apps.fictionpress = """ tag: browser browser.host: www.fictionpress.com browser.host: m.fictionpress...
StarcoderdataPython
3312471
from .svd import SVD from .eigh import EigenSolver from .qr import QR
StarcoderdataPython
183860
from django.apps import AppConfig class KdlWagtailPeopleConfig(AppConfig): name = 'kdl_wagtail.people' label = 'kdl_wagtail_people'
StarcoderdataPython
4824130
<reponame>vegetablejuiceftw/vacuum<filename>players/prefer_last_lazy.py<gh_stars>0 from agent import Point from players.prefer_last import RandomPreferLastMoveAgent class LazyRandomPreferLastMoveAgent(RandomPreferLastMoveAgent): NAME = "Lazy" AUTHOR = "<EMAIL>" def __init__(self) -> None: super()...
StarcoderdataPython
1728539
<filename>Python3/461.hamming-distance.py<gh_stars>0 # # @lc app=leetcode id=461 lang=python3 # # [461] Hamming Distance # # @lc code=start class Solution: def hammingDistance(self, x: int, y: int): if x == y: return 0 cnt = 0 while x > 0 or y > 0: if x & 1 != y & ...
StarcoderdataPython
3268623
import cv2 import numpy as np img = cv2.imread(r'C:\Users\Lenovo\OneDrive\Desktop\n1',cv2.IMREAD_COLOR) img1=img grayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) th = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 115, 1) #cv2.imshow('original',img) #cv2.imshow('Adaptiv...
StarcoderdataPython
1744011
from django.contrib import admin from models_completed import CompletedTask from models import Task class TaskAdmin(admin.ModelAdmin): display_filter = ['task_name'] list_display = ['task_name', 'task_params', 'run_at', 'priority', 'attempts'] admin.site.register(Task, TaskAdmin) admin.site.register(Comple...
StarcoderdataPython
3340502
''' This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de). PM4Py 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, either version 3 of the License, or (at your option) any late...
StarcoderdataPython
68037
from setuptools import setup, find_packages """ Instructions for creating a release of the scispacy library. 1. Make sure your working directory is clean. 2. Make sure that you have changed the versions in "scispacy/version.py". 3. Create the distribution by running "python setup.py sdist" in the root of the reposit...
StarcoderdataPython
1709372
<filename>evennia/contrib/base_systems/email_login/tests.py """ Test email login. """ from evennia.commands.default.tests import BaseEvenniaCommandTest from . import email_login class TestEmailLogin(BaseEvenniaCommandTest): def test_connect(self): self.call( email_login.CmdUnconnectedConnect...
StarcoderdataPython
1733193
<filename>CS2/9200_data_structures/linked_lists/linked_list_student_day5.py ''' Fill in the code to make the removeValue function work in the linked list class below. You can use any previous linked list code. An addToHead function has been provided. ''' # Linked list example in Python # Link class class Link: # ...
StarcoderdataPython
3256519
import tvm.relay as relay import tvm def create_target(device): if device == "x86": print("from x86") target = tvm.target.create("llvm -mcpu=core-avx2") elif device == "x86-avx2": print("from x86-avx2") target = tvm.target.create("llvm -mcpu=core-avx2") elif device == "x86-a...
StarcoderdataPython
198784
<gh_stars>0 # coding: utf-8 pyslim_version = '0.700' slim_file_version = '0.7' # other file versions that require no modification compatible_slim_file_versions = ['0.7']
StarcoderdataPython
1705615
#Return the element with maximum frequency in a list def maxfreq(x): y=max(set(x),key=x.count) return y #Return the element with minimum frequency in a list def minfreq(x): y=min(set(x),key=x.count) return y #Return a List of all "keys" in a dictionary def dkey(x): y=list(x.keys()) ...
StarcoderdataPython
3369917
""" To solve this puzzle, you must press and hold keys 3, 7 and 11. """ import mpr121 from machine import Pin i2c = machine.I2C(3) mpr = mpr121.MPR121(i2c) # the winning combination is 3, 7 and 11 combination = (1<<3) | (1<<7) | (1<<11) # check all keys def check(pin): t = mpr.touched() print(t) if t & ...
StarcoderdataPython
1649500
#!/usr/bin/env python import os import socket from twisted.internet import defer from twisted.internet import reactor from twisted.internet import error from twisted.names import error from twisted.names.common import extractRecord # from twisted.names.client import getResolver from common import getResolver # XXX: See...
StarcoderdataPython
1634540
from gii.core import app from PyQt4 import QtGui, QtCore from PyQt4.QtCore import Qt class ListStackModel(QtCore.QAbstractListModel): def __init__(self, stacks): super(ListStackModel,self).__init__() self.stacks=stacks def rowCount(self, parent): return len(self.stacks) def data(self, idx, role=Qt.DisplayR...
StarcoderdataPython
3273402
<gh_stars>0 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(0) if l1.val < l2.val: result = l1 l1 = ...
StarcoderdataPython
3284538
<gh_stars>0 # -*- coding: utf-8 -*- # # Copyright (c) 2007 <NAME> <<EMAIL>> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED ...
StarcoderdataPython
127522
<gh_stars>10-100 # stdlib imports import os import sys import unittest # src imports import_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../schematool') sys.path.append(import_path) from command import CommandContext, DownCommand from db import MemoryDb from errors import MissingRefError # tes...
StarcoderdataPython
3212230
from collections import Counter, defaultdict import csv import requests CSV_URL = 'https://raw.githubusercontent.com/pybites/SouthParkData/master/by-season/Season-{}.csv' # noqa E501 def get_season_csv_file(season): """Receives a season int, and downloads loads in its corresponding CSV_URL""" with re...
StarcoderdataPython
4808552
<filename>lib/bes/git/git_changelog_options.py # -*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- from bes.common.check import check class git_changelog_options(object): def __init__(self, **kargs): self._check_options(kargs) self.max_chars = kargs.get('max_chars...
StarcoderdataPython
120695
<filename>tests/user/test_model.py<gh_stars>0 # -*- coding: utf-8 # Core import pytest from mixer.backend.django import mixer # Models from custom_auth_user.models import User @pytest.mark.django_db class TestUserModel(): def test_user_model(self): user = mixer.blend(User, first_name='first', last_name=...
StarcoderdataPython
62194
from mcc_libusb import * import datetime import time import numpy as np mcc = USB1208FS() mcc.usbOpen() #mcc.usbDConfigPort(DIO_PORTA, DIO_DIR_OUT) #mcc.usbDConfigPort(DIO_PORTB, DIO_DIR_IN) #mcc.usbDOut(DIO_PORTA, 0) #num = mcc.usbAIn(1, BP_1_00V) #print(str(mcc.volts_FS(BP_1_00V, num))) #channel = np.array([1, 2, 3...
StarcoderdataPython
4808748
<filename>blog/migrations/0003_post_picture.py # Generated by Django 3.2.11 on 2022-01-31 10:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_counted_views'), ] operations = [ migrations.AddField( model_n...
StarcoderdataPython
4823826
""" ============================================================= ~/fn_portal/tests/api/crud_api/test_fn121.py Created: 08 Sep 2020 10:40:55 DESCRIPTION: This file contains a number of unit tests that verify that the api endpoint for FN121 objects works as expected: + sample-list should be available to both lo...
StarcoderdataPython
34840
<filename>testTF.py # Importing required libraries import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing.text import Tokenizer # List of sample sentences that we want to tokenize sentences = ['I love my dog', 'I love my cat', 'you love my dog!', ...
StarcoderdataPython
131970
<reponame>arvy-p/sagemaker-run-notebook<gh_stars>10-100 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.ama...
StarcoderdataPython
149786
<gh_stars>1-10 import selenium from functions.Functions import Functions as Selenium import unittest from classes.FormLogin import EventLogin from classes.FormTerminosCondiciones import EventTerminosCondiciones as EventTC class TratamientoDatos(Selenium,unittest.TestCase): def setUp(self): Selenium.abrir_...
StarcoderdataPython
1661808
"""Robotx is a set of automation toolset. ...""" __version__ = '0.2.2'
StarcoderdataPython
3220530
ROOT_SCOPE = "root" ENDPOINT_SCOPE = "endpoint" REQUEST_SCOPE = "request" class MalformedSpecError(Exception): pass class HTTPMethodNotAllowedError(MalformedSpecError): """Raised when the HTTP method in the API spec is invalid""" def __init__(self, method, allowed_methos, *args): message = ( ...
StarcoderdataPython
3232513
<filename>codes/dataops/batchaug.py import random import numpy as np import torch from torch.nn import functional as F class BatchAugment: def __init__(self, train_opt): self.mixopts = train_opt.get( "mixopts", ["blend", "rgb", "mixup", "cutmix", "cutmixup", "cutout"]) # , "cu...
StarcoderdataPython
1728791
from flask import abort, jsonify, session from app.util import request_helper from app.services import reddit_service from app.db.models.raffle import Raffle from app.db.models.user import User @request_helper.require_login def get_user_submissions(): """ Return the user's Reddit submissions that are not already...
StarcoderdataPython
3387057
from torch import nn from fairscale.utils.meta import init_meta_context, materialize_module def test_meta(): with init_meta_context(): m = nn.Linear(in_features=1, out_features=1) assert m.weight.device.type == "meta" print(m) materialize_module(m) assert m.weight.device.type == "c...
StarcoderdataPython