id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11282051 | <filename>models/__init__.py
from models import proto
from models import my_proto
from models import proto_meta
| StarcoderdataPython |
4902064 | <gh_stars>10-100
import ConfigParser
import logging
import subprocess
import sys
from flask import Flask, render_template, request, redirect, url_for
from controller_config import Config
from switch_nexa import NexaSwitcher
app = Flask(__name__)
def read_logs(file_name='/run/nexa_controller.log'):
try:
... | StarcoderdataPython |
1966354 | from .categorical_policy import CategoricalPolicy
from .deterministic_policy import DeterministicPolicy
from .gaussian_policy import GaussianPolicy
from .squashed_gaussian_policy import SquashedGaussianPolicy
REGISTRY = {}
REGISTRY['categorical'] = CategoricalPolicy
REGISTRY['deterministic'] = DeterministicPolicy
REG... | StarcoderdataPython |
3345814 | DEFAULT_COMMAND_MAP = {
".c": "$CC -o $target $CFLAGS $CCFLAGS $sources",
".cpp": "$CXX -o $target $CXXFLAGS $CCFLAGS $sources",
}
| StarcoderdataPython |
9768509 | <reponame>BCV-Uniandes/Gabor_Layers_for_Robustness
import os
import torch
import argparse
import numpy as np
import pandas as pd
import os.path as osp
from models.vgg import VGG16
from models.resnet import ResNet18
# Taken _explicitly_ from
# The Singular Values of Convolutional Layers
# https://openreview.net/pdf?id... | StarcoderdataPython |
8174643 | <reponame>sbworth/getnoc
# ---------------------------------------------------------------------
# Forwarding Instance model
# ---------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# -----------------------------------------------------... | StarcoderdataPython |
8051181 | """Package setuptools config."""
import importlib
import setuptools
pkg_meta_spec = importlib.util.spec_from_file_location(
'pkg_meta',
'sttp/pkg_meta.py',
)
pkg_meta = importlib.util.module_from_spec(pkg_meta_spec)
pkg_meta_spec.loader.exec_module(pkg_meta)
with open('README.md', 'r', encoding='utf-8') as... | StarcoderdataPython |
50406 | import json
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from webapps.buildinginfos.models import BuildingInfo
from _utils.device_list_utils import get_device_list_and... | StarcoderdataPython |
276670 | import numpy as np
import pandas as pd
def evaluate_TPD(path):
xlsx = pd.read_excel(path, header=None)
score = 0.
frame_size = xlsx.shape[0]
print(frame_size)
for t in range(frame_size):
det_obj = xlsx.shape[1]
trac_obj = xlsx.shape[1]
for n in range(1, xlsx.shape[1]+1):
if n != int(xlsx... | StarcoderdataPython |
9631243 | <reponame>idekerlab/cdqforcelayout
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__version__ = '0.0.5'
| StarcoderdataPython |
3544194 | from pathlib import Path
import pandas as pd
RAW_DATA_DIR = Path('data/raw/')
BULLYING_LABELS = {'Yes'}
def load_original_dataset():
"""Returns a preprocessed DataFrame from the original dataset"""
# Preprocess Dataset
df = pd.read_csv(RAW_DATA_DIR / 'formspring_data.csv', sep='\t')
df['label'] = (
... | StarcoderdataPython |
9613389 | #encoding:utf-8
subreddit = 'izlam'
t_channel = '@r_izlam'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| StarcoderdataPython |
9686370 | <filename>modules/boost/simd/ieee/script/modf.py
[ ## this file was manually modified by jt
{
'functor' : {
'description' : ['Computes the integer part and the fractionnal part of the input',
'\par',
'As demonstrated in the synopsis this function can b... | StarcoderdataPython |
4856027 | #erros and exceptions
try:
a =10
f = open('file.txt')
except Exception as e:
print('in exception block, sorry this file does not exist', e)
else:
print(' in else block, no exception occured')
finally:
print('in finally block which would definietly run')
| StarcoderdataPython |
6403674 |
class InfusionsoftException(Exception):
"""Base exception for all library errors."""
pass
class AuthError(InfusionsoftException):
"""Something is wrong with authentication."""
pass
class TokenError(AuthError):
"""Something is wrong with the tokens."""
pass
class DataError(InfusionsoftExce... | StarcoderdataPython |
3304196 | <reponame>gnudeb/8051
class IntelHexParser:
def __init__(self, hex_bytes):
self.chars = map(chr, hex_bytes)
def next_record(self):
self.assume(self.next_char() is ':')
byte_count = self.next_byte()
address = self.next_byte(2)
record_type = self.next_byte()
data... | StarcoderdataPython |
6482488 | #!/usr/bin/python3
import RPi.GPIO as GPIO
import time
# careful lowering this, at some point you run into the mechanical limitation of how quick your motor can move
step_sleep = 0.002
class Stepmotor:
def __init__(self, out1, out2, out3, out4):
self.out1 = out1
self.out2 = out2
self.out3 ... | StarcoderdataPython |
1734524 | from werkzeug.exceptions import NotFound, InternalServerError
from shared.error.exceptions import ObjectNotFound
from flask import current_app
class ViewResultHandler:
def __init__(self):
self.result = None
def handle_success(self, result):
self.result = result
def handle_client_error(se... | StarcoderdataPython |
5445 | #!/usr/bin/python3
#------------------------------------------------------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root):
... | StarcoderdataPython |
8152359 | <filename>pb/ErrorHandling_pb2.py
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: ErrorHandling.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from goo... | StarcoderdataPython |
3414205 | from node_exec.base_nodes import defNode
from PySide2.QtWidgets import QInputDialog, QLineEdit
IDENTIFIER = 'Input Dialog'
@defNode("Choose Item", isExecutable=True, returnNames=["item", "accepted"], identifier=IDENTIFIER)
def getItem(parentWindow=None, title="Item Selection", label="Item:", items=["t0", "t1"], curre... | StarcoderdataPython |
11261908 | <reponame>Schmek704/DealershipProject
import requests
import json
from .models import CarDealer, DealerReview
from requests.auth import HTTPBasicAuth
# from ibm_watson import NaturalLanguageUnderstandingV1
# from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
# from ibm_watson.natural_language_understanding_... | StarcoderdataPython |
8092546 | <reponame>Kaushikpatnaik/Active-Learning-and-Best-Response-Dynamics
from numpy import *
from scipy.stats import norm as normal
from learners import *
class QuasiAdditive(LinearLearner, OnlineLearner):
def __init__(self, d, transform, z = None, rate = 1.0):
self.d = d
self.transform = transf... | StarcoderdataPython |
8111576 | <filename>home/urls.py
from django.conf.urls import url
from home.views import HomeView
from . import views
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$', views.change_friends, name='change_friends')
] | StarcoderdataPython |
5077546 | <reponame>DivyanshuBagga/LNMarketBot<filename>LNMarketBot/Examples/MultipleFeeds.py
import time
import talib
import datetime
from LNMarketBot import Strategy, BacktestBroker, CSVData, Bot
class MultipleFeedStrat(Strategy):
def init(self):
self.stopLoss = 0.0
self.highest = 0.0
self.drawdo... | StarcoderdataPython |
3369215 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | StarcoderdataPython |
1825622 | <filename>HACKERRANK_CHALLENGES/triplets.py
def partitionArray(A, k):
flag = 0
if not A and k == 1:
return "Yes"
if k > len(A) or len(A) % len(A):
return "No"
flag += 1
cnt = {i: A.count(i) for i in A}
if len(A)//k < max(cnt.values()):
return "No"
flag += 1
if(flag == 0):
return "Yes"
k = int(input("k= ")... | StarcoderdataPython |
11283320 | #!/usr/bin/env python
# this script:
# 1) outputs each TE insertion call into new files based on family
# 2) collapses TEs of same famly within 50 base pairs of one another
# 3) outputs all the unqiue TE positions to a new file
# 4) calculates the coverage for each sample at each insertion postion +/- 25 base pairs
# 5... | StarcoderdataPython |
1640582 | <reponame>alysivji/github-adapter
from datetime import date
import logging
from typing import NamedTuple
from dateutil.parser import parse as parse_dt
import requests
from .blueprint import cfps_bp
from .models import CallForProposalsConfiguration
from busy_beaver.common.wrappers import SlackClient
from busy_beaver.t... | StarcoderdataPython |
5002250 | <reponame>hz-b/bluesky-queueserver
import pandas as pd
import os
def spreadsheet_to_plan_list(*, spreadsheet_file, data_type, file_name, **kwargs):
"""
Process trivial spreadsheet with plan parameters (for use in unit tests).
The spreadsheet is expected to contain parameters of 'count' plan in the form:
... | StarcoderdataPython |
393083 | <filename>.virtualenvs/cbrl-PqEIqGlc/lib/python3.7/site-packages/machina/apps/forum_conversation/forum_polls/forms.py
"""
Forum polls forms
=================
This module defines forms provided by the ``forum_polls`` application.
"""
from django import forms
from django.core.exceptions import ValidationEr... | StarcoderdataPython |
5064230 | import sys
import unittest
import pycodestyle
from pyflakes.api import checkRecursive
from pyflakes.reporter import Reporter
CHECK_DIRECTORYS = ["src/", "tests/"]
class Pep8Test(unittest.TestCase):
def test_pep8(self):
style = pycodestyle.StyleGuide()
check = style.check_files(CHECK_DIRECTORYS)
... | StarcoderdataPython |
11221446 | """ Python Character Mapping Codec generated from 'PTCP154.txt' with gencodec.py.
Written by <NAME> (<EMAIL>).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 <NAME>.
""" # "
import codecs
# ## Codec APIs
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
re... | StarcoderdataPython |
1891048 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# 加载包
import os
import time
import xlsxwriter
from db import Database
db = Database()
ABS_PATH = os.path.split(os.path.realpath(__file__))[0]
REPORT_PATH = os.path.join(ABS_PATH, 'report-%s.xlsx' % time.strftime("%Y-%m-%d"))
def get_tasks():
sql = 'SELECT * FROM %s_task' ... | StarcoderdataPython |
1659074 | <reponame>jorgesaw/kmarket<filename>apps/locations/serializers/__init__.py
from .states import StateModelSerializer
from .cities import CityModelSerializer, CityWithStateModelSerializer, UpdateCityModelSerializer | StarcoderdataPython |
5109503 | from unittest import TestCase
import requests_mock
from parameterized import parameterized
from hvac.adapters import Request
from hvac.api.auth_methods import Mfa
from hvac.api.auth_methods.github import DEFAULT_MOUNT_POINT
class TestMfa(TestCase):
@parameterized.expand([
("default mount point", DEFAUL... | StarcoderdataPython |
1911317 | from pathlib import Path
import click
from databricks_cli.configure.config import debug_option
from databricks_sync import CONTEXT_SETTINGS
from databricks_sync.cmds import templates
@click.command(context_settings=CONTEXT_SETTINGS, help="Initialize export configuration.")
@click.argument("filename", nargs=1)
@debu... | StarcoderdataPython |
1978327 | from django.contrib import admin
from addresses.models import Address
admin.site.register(Address)
| StarcoderdataPython |
4957175 | <filename>DictionaryComprehensions/main.py
prizes = {"mleko": 2, "chleb": 4, "szynka": 30, "ser": 20, "woda": 2}
prizes_in_euro = {key: (value * 4.4) for (key, value) in prizes.items()}
print(prizes_in_euro)
selected_items = {key: value for (key, value) in prizes_in_euro.items() if value > 10}
print(selected_items)
... | StarcoderdataPython |
8065371 | <reponame>Tandaradei/devnia<gh_stars>0
import json
class CLI_UI:
def __init__(self, base):
self.base = json.loads(base)
def update_base(self, base):
self.base = json.loads(base)
def render_world(self):
tiles = self.base["world"]["tiles"].split(',')
for tile in tiles:
... | StarcoderdataPython |
3475914 | <filename>abjadext/nauert/MeasurewiseQSchema.py
import abjad
from .QSchema import QSchema
class MeasurewiseQSchema(QSchema):
r"""
Measurewise q-schema.
Treats measures as its timestep unit.
>>> q_schema = abjadext.nauert.MeasurewiseQSchema()
.. container:: example
Without arguments, ... | StarcoderdataPython |
3424107 | <filename>databay/__init__.py
import os
import sys
from databay import config
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
config.initialise()
from databay.record import Record
from databay.outlet import Outlet
from databay.inlet import Inlet
from databay.link import Link
from databay.link impor... | StarcoderdataPython |
11253405 | (VoidTypeKind,
HalfTypeKind,
FloatTypeKind,
DoubleTypeKind,
X86_FP80TypeKind,
FP128TypeKind,
PPC_FP128TypeKind,
LabelTypeKind,
IntegerTypeKind,
FunctionTypeKind,
StructTypeKind,
ArrayTypeKind,
PointerTypeKind,
VectorTypeKind,
MetadataTypeKind,
X86_MMXTypeKind
) = range(16)
(IntEQ,
IntNE,
IntUGT,
Int... | StarcoderdataPython |
6687538 | from sparkpost import SparkPost
sp = SparkPost()
result = sp.suppression_list.delete('<EMAIL>')
print(result)
| StarcoderdataPython |
8183082 | #!/usr/bin/env python
import sys, freesia
sys.exit(freesia.main())
| StarcoderdataPython |
1942497 | <filename>HTC_lib/VASP/Sub_Directory_Calculation_Scripts/ENCUT_convergence.py
#!/usr/bin/env python
# coding: utf-8
# In[4]:
import os, sys, re, math, shutil, json
##############################################################################################################
##DO NOT change this part.
##../setup.py ... | StarcoderdataPython |
11254929 | <reponame>Carlososuna11/codewars-handbook
import codewars_test as test
from solution import t_area
@test.describe('Basic tests.')
def triangle_tests():
@test.it('First triangle area')
def test_case1():
test.assert_equals(t_area('\n.\n. .\n'), .5)
@test.it('Second triangle area')
def t... | StarcoderdataPython |
4958095 | <filename>src/sentry/utils/services.py
from __future__ import absolute_import
import functools
import inspect
import itertools
import logging
import threading
import six
from django.utils.functional import empty, LazyObject
from sentry.utils import warnings
from sentry.utils.concurrent import FutureSet, ThreadedExec... | StarcoderdataPython |
11360779 | # system.py
# Contains helper functions related to the system
# Handles putting an actual name to the sys.platform value
def get_sys_name(val):
return {
'linux2':'Linux',
'win32':'Windows',
'cygwin':'Windows/Cygwin',
'darwin':'MacOSX',
'os2':'OS/2',
'os2emx':'OS/2 E... | StarcoderdataPython |
6600294 | <reponame>fzaidi2014/pytorch-image-classisifcation
import numpy as np
import pandas as pd
from PIL import Image
from torch.utils.data import *
class ImageDataset(Dataset):
def __init__(self, csv_path,
transforms=None,
labels=False):
self.labels = None
self.... | StarcoderdataPython |
1634220 | # !/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
import os
import uuid
from pybpodgui_api.models.session import Session
from pybpodgui_api.utils.generate_name import generate_name
logger = logging.getLogger(__name__)
class SubjectBase(object):
def __init__(self, project):
self._path = None
... | StarcoderdataPython |
72988 | """
Finds the minimum differrence of a pair of pentagonal numbers
Author: <NAME>
"""
import math
"""
Returns the minimum different of the pair of pentagonal numbers
"""
def minimum_difference(p):
d = float('inf')
for i in range(len(p)-1):
if p[i+1]-p[i]>d:
print('Found the limit, this is d... | StarcoderdataPython |
8032919 | <gh_stars>0
# (C) Crown Copyright, Met Office. All rights reserved.
#
# This file is part of ocean_error_covs and is released under the BSD 3-Clause license.
# See LICENSE in the root of the repository for full licensing details.
###################################################################################
# Runn... | StarcoderdataPython |
1761922 |
def readtxt(path,encoding):
with open(path, 'r', encoding = encoding) as f:
lines = f.readlines()
return lines
def email_parser(email_path):
punctuations = """,.<>()*&^%$#@!'";~`[]{}|、\\/~+_-=?"""
content_list = readtxt(email_path, 'iso-8859-1')
content = (' '.join(content_list)).... | StarcoderdataPython |
8549 | <reponame>ATRS7391/Discord_Nitro_Generator_And_Checker_Python_Version
import random
import sys
import subprocess
def pip_install(module: str):
subprocess.run([sys.executable, "-m", "pip", "-q", "--disable-pip-version-check", "install", module])
try:
import requests
except:
print("'requests' ... | StarcoderdataPython |
6487121 | # python3.7
"""Contains the visualizer to visualize images as a GIF."""
from PIL import Image
from ..image_utils import parse_image_size
from ..image_utils import load_image
from ..image_utils import resize_image
from ..image_utils import list_images_from_dir
__all__ = ['GifVisualizer']
class GifVisualizer(object)... | StarcoderdataPython |
1966836 | import gdb
from tailq import TailQueue
from ptable import ptable, as_hex
class KernelSegments():
def invoke(self):
self.dump_segments()
def get_all_segments(self):
return TailQueue(gdb.parse_and_eval('seglist'), 'segq')
def dump_segments(self):
segments = self.get_all_segments()... | StarcoderdataPython |
9627438 | <filename>bokeh/exceptions.py
class DataIntegrityException(Exception):
pass
class AuthenticationException(Exception):
pass
class UnauthorizedException(Exception):
pass
| StarcoderdataPython |
1927291 | import hashlib
message = "Hello".encode('utf-8')
h = hashlib.md5()
h.update(message)
print(h.hexdigest())
h = hashlib.sha256()
h.update(message)
print(h.hexdigest())
# check - file checksum
salt = "<PASSWORD>".encode('utf-8')
h = hashlib.sha256()
h.update(message + salt)
print(h.hexdigest())
password = "<PASSWORD... | StarcoderdataPython |
11202037 | import random
from torch.utils.data import IterDataPipe, Sampler, SequentialSampler, functional_datapipe
from typing import Dict, Iterator, List, Optional, Sized, Tuple, Type, TypeVar
T_co = TypeVar('T_co', covariant=True)
class SamplerIterDataPipe(IterDataPipe[T_co]):
r""" :class:`SamplerIterDataPipe`.
It... | StarcoderdataPython |
11234483 | <reponame>sarahlc888/safe-gif-scanner
# code for LO2: Compare
# showing that "I can compare distinct versions of the same repository
# to discern a clear, organized vision of their differences."
| StarcoderdataPython |
9708676 | # -*-coding: utf-8-*-
import string
from src.justauth.config.AuthSourceConfig import AuthSourceConfig
from src.justauth.request.AuthRequest import AuthRequest
from selenium import webdriver
class AuthGithubRequest(AuthRequest):
def __init__(self, driver, config_path) -> object:
self.driver = driver
... | StarcoderdataPython |
1673967 | <filename>src/getoffmylawn/migrations/versions/6781acfc7c14_urls.py
"""url.
Revision ID: 6781acfc7c14
Revises: <PASSWORD>
Create Date: 2019-04-29 21:16:48.157964
"""
from alembic import op
from sqlalchemy.dialects import postgresql
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "<KEY>"
... | StarcoderdataPython |
3434130 | import os
from os import path
import csv
def write_artifact(filename, *raw_data):
"""Writes an artifact file,
which is a temporary fakefile used to gauge game data
"""
basepath = path.join(path.dirname(__file__), '../../../artifacts/')
os.makedirs(basepath, exist_ok=True)
with open(path.join... | StarcoderdataPython |
11248696 | <reponame>foxpass/divvy-client-python<gh_stars>1-10
from __future__ import absolute_import
from collections import namedtuple
import re
import socket
from divvy.connection import Connection
from divvy.exceptions import InputError
from divvy.protocol import Translator
class DivvyClient(object):
def __init__(self... | StarcoderdataPython |
12833039 | <reponame>istellartech/OpenVerne
# -*- coding: utf-8 -*-
""" Google Earth file output example
required simplekml module.
if you didn't install simplekml, execute the following command.
> pip install simplekml
"""
from OpenVerne import IIP
import numpy as np
import pandas as pd
import simplekml
import warnings
warning... | StarcoderdataPython |
12827118 | <gh_stars>1-10
"""
Interfaz para un juego de \"Piedras, Papel o Tijeras\".
"""
from discord import Interaction
from discord import PartialEmoji as Emoji
from discord.enums import ButtonStyle
from discord.ui import Button, button
from ..archivos import DiccionarioStats
from ..ppt import jugar_partida_ppt
from .ui_gene... | StarcoderdataPython |
6444147 | <filename>migrations/postgres_versions/2020-04-23_5154f7db278d_base.py
"""base
Revision ID: 5154f7db278d
Revises:
Create Date: 2020-04-23 12:23:01.219218
"""
import geoalchemy2
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision ... | StarcoderdataPython |
1766408 | <gh_stars>1-10
class Node:
'''
Node class to use in directed graph.
'''
def __init__(self, x, y, heading):
self.x = x
self.y = y
self.heading = heading
self.total = 1
def get_point(self):
return [self.x, self.y, self.heading]
def update(self, node):
self.x = ((self.x * self.total) + node.x) / (sel... | StarcoderdataPython |
11315545 | from keras.models import load_model
import numpy as np
from scipy.stats import norm
import random
default = '0.0.1'
models = {
'0.0.1': {
'bottleneck': 300,
'size': 64,
'decoder':{
'f': 'decoder-f64.h5',
'm': 'decoder-m64.h5'
}
}
}
for version, model in models.items():
dir_ = 'autoencoders/' + versio... | StarcoderdataPython |
3547604 | <gh_stars>0
import logging
import secrets
import string
import traceback
from ceph.ceph import CommandFailed
from tests.cephfs.cephfs_utilsV1 import FsUtils
log = logging.getLogger(__name__)
def run(ceph_cluster, **kw):
"""
Pre-requisites:
1. Create 2 cephfs volume
creats fs volume create <vol_na... | StarcoderdataPython |
9634019 | <filename>camera/src/capture.py
import gphoto2 as gp
import io
from PIL import Image
class Capture :
def __init__(self):
self.camera = gp.Camera()
self.camera.init()
def _do_capture(self):
# capture actual image
OK, camera_file_path = gp.gp_camera_capture(
self.... | StarcoderdataPython |
9690371 | # coding: utf-8
from StringIO import StringIO
from maxipago.utils import etree
from maxipago.resources.base import Resource
from maxipago.exceptions import CustomerAlreadyExists, CustomerException
class CustomerAddResource(Resource):
def process(self):
tree = etree.parse(StringIO(self.data))
err... | StarcoderdataPython |
385538 | <reponame>pvital/4lg0rithm5
#!/bin/python3
from myitertools import dropwhile, takewhile
def testFunction(x):
return x < 40
if __name__ == '__main__':
vals = [10, 20, 30, 40, 50, 40, 30]
print(list(dropwhile(testFunction, vals)))
print(list(takewhile(testFunction, vals)))
| StarcoderdataPython |
8080125 | from logik import parser
from logik import lexer
from logik.parser import parse
from logik.parser import Lexbuf
from logik.lexer import lex
def test_parse():
outputA = parse(Lexbuf(list(lex("a et b"))))
expectedA = ('et', ('symb', 'a'), ('symb', 'b'))
outputB = parse(Lexbuf(list(lex("a ou b")... | StarcoderdataPython |
1871225 | # Copyright 2020 Google LLC
#
# 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 |
6549211 | <filename>source/test_hash.py
HASH_MAX = ((2 ** 32) - 1)
# Dummy hash function based on mersenne primes
# to be replaced with actual hash function
def minerHash(addr, pair, buyInd, sellInd, nonce):
comp1 = addr * ((2 ** 31) - 1)
comp2 = pair * ((2 ** 37) - 1)
comp3 = buyInd * ((2 ** 41) - 1)
comp4 = ... | StarcoderdataPython |
229841 | import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr % 2 == 1)
print(x)
| StarcoderdataPython |
11200515 | '''
File: roles.py
Description: The file contains the definition for the user roles model
which will be used to assign roles to the user.
'''
from bugzot.application import db
class Role(db.Model):
"""User roles model.
The model is responsible for storing the information about the user roles
... | StarcoderdataPython |
28286 | <reponame>zstackio/zstack-utility
import json
import os
import shutil
from jinja2 import Template
from zstacklib.utils import http
from zstacklib.utils import jsonobject
from zstacklib.utils import linux
from zstacklib.utils import linux_v2
from zstacklib.utils import iptables
from zstacklib.utils import lock
from zst... | StarcoderdataPython |
206446 | <gh_stars>0
# Version: 2020.02.21
#
# MIT License
#
# Copyright (c) 2018 <NAME> and <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limit... | StarcoderdataPython |
1721633 | import pytest
from oem import tools
def test_parse_integer():
tools.parse_integer(1, None)
tools.parse_integer(1.0, None)
with pytest.raises(ValueError):
tools.parse_integer(1.1, None)
| StarcoderdataPython |
9682839 | #
# Copyright 2016 Cluster Labs, Inc.
#
# 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 |
32044 | <filename>addons/stock_landed_costs/models/account_move.py
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class AccountMove(models.Model):
_inherit = 'account.move'
landed_costs_ids = fields.One2many('stock.landed.cost'... | StarcoderdataPython |
366811 | <reponame>spetrovic450/ksvotes.org
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import Optional, Regexp
from flask_babel import lazy_gettext
from app.main.helpers import KS_DL_PATTERN
class KSIDField(StringField):
def process_formdata(self, valuelist):
dl = valuel... | StarcoderdataPython |
5102432 | <gh_stars>1-10
"""Code generation and assertion tests."""
import itertools
import textwrap
from pytest_bdd.scenario import get_python_name_generator
from tests.utils import assert_outcomes
def test_python_name_generator():
"""Test python name generator function."""
assert list(itertools.islice(get_python_nam... | StarcoderdataPython |
3405741 | import logging
from cloud_functions_dispatch import dispatch
log = logging.getLogger(__name__)
@dispatch
def echo(*args, **kwargs):
log.info('echo called with args=%s, kwargs=%s', args, kwargs)
@dispatch
def my_func(a, b, cheer='hooray!'):
if a > b:
log.warning('a is too large!')
else:
... | StarcoderdataPython |
3255643 | <reponame>JiveHelix/pex<filename>python/pex/wx/window.py
from typing import List
import abc
import wx
from .. import pex
class Window:
""" A mixin that disconnects pex when the window is destroyed. """
tubes_: List[pex.HasDisconnectAll]
wxId_: int
def __init__(self: wx.Window, tubes: List[pex.HasDisc... | StarcoderdataPython |
3534217 | <gh_stars>0
from django.apps import AppConfig
# Create your apps here.
class UsersConfig(AppConfig):
name = 'users'
| StarcoderdataPython |
12806816 | <gh_stars>1-10
import pdb
import logging
logger = logging.getLogger("milvus_benchmark.parser")
def operations_parser(operations):
if not operations:
raise Exception("No operations in suite defined")
for run_type, run_params in operations.items():
logger.debug(run_type)
return (run_typ... | StarcoderdataPython |
9764975 | <filename>budgetportal/migrations/0023_infrastructureprojectpart.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-08-15 09:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("budgetportal", "0022_event_prese... | StarcoderdataPython |
9649932 | <gh_stars>1-10
import numpy as np
import pyqtgraph as pg
import time
import csv
from PyQt5.Qsci import QsciScintilla, QsciLexerPython
from spyre import Spyrelet, Task, Element
from spyre.widgets.task import TaskWidget
from spyre.plotting import LinePlotWidget
from spyre.widgets.rangespace import Rangespace
from spyre... | StarcoderdataPython |
6671379 | class Solution:
def compressString(self, S: str) -> str:
n = len(S)
res = ''
i = 0
while i < n:
j = i
while j < n and S[j] == S[i]:
j += 1
res += S[i] + str(j - i)
i = j
if len(res) < n:
retu... | StarcoderdataPython |
4893811 | <filename>graphgallery/gallery/linkpred/pyg/gae.py<gh_stars>0
import numpy as np
from graphgallery.sequence import FullBatchSequence
from graphgallery import functional as gf
from graphgallery.gallery.linkpred import PyG
from graphgallery.gallery import Trainer
from graphgallery.nn.models import get_model
@PyG.regist... | StarcoderdataPython |
11248399 | # -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.osv import osv
class ir_configparameter(osv.Model):
_inherit = 'ir.config_parameter'
def init(self, cr, force=False):
super(ir_configparameter, self).init(cr, force=force)
if force:
IMD = self.pool['ir.model.data... | StarcoderdataPython |
8086056 | <gh_stars>0
n = int(input('Um número: '))
d = (n * 2)
t = (n * 3)
r = (n ** (1/2))
print('O dobro do número {} é {}. \nO triplo do número {} é {}. \nA raiz quadrada do número {} é {:.2f}.'.format(n, d, n, t, n, r))
| StarcoderdataPython |
8110029 | <reponame>mic2100/casper-script
#!/usr/bin/env python
import scrollphathd
try:
while True:
for x in range(18):
scrollphathd.fill(0.1,0,0,x,7)
scrollphathd.show()
for x in range(18):
scrollphathd.fill(0,0,0,x,7)
scrollphathd.show()
except KeyboardInte... | StarcoderdataPython |
1674726 | <gh_stars>0
#!/usr/bin/env python3
import sys
import json
from github import Github, GithubObject
def make_issue():
kwargs = {
"body": json.load(sys.stdin)['message'],
"labels": sys.argv[2].split(',')
}
if "," in sys.argv[3]:
kwargs["assignees"] = sys.argv[3].split(',')
else:
... | StarcoderdataPython |
6453090 | import logging
import os
import posixpath
import sys
from contextlib import contextmanager
from typing import TYPE_CHECKING, Callable, Iterable, Optional
from funcy import first
from dvc.fs.ssh import SSHFileSystem
from dvc.repo.experiments.base import (
EXEC_BRANCH,
EXEC_CHECKPOINT,
EXEC_HEAD,
EXEC_M... | StarcoderdataPython |
9610287 | import os
import platform
import shutil
import subprocess
import time
import uuid
def get_lines(std_pipe):
"""Generator that yields lines from a standard pipe as they are printed."""
for line in iter(std_pipe.readline, ""):
yield line
class Shell:
def __init__(self, shell_type):
self.pro... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.