id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
192075 | <reponame>dmitrykoro/NetworksLab2020<filename>Lab04_git/action_operator.py<gh_stars>0
import json
import sys
from math import ceil
from server import BLOCK_SIZE
from encrypt import encrypt_password
from database_handler import add_to_database, get_from_database, delete_from_database, get_total_amount
from datet... | StarcoderdataPython |
3373588 | import ctypes
class CEnumMeta(type(ctypes.c_int)):
def __new__(cls, name, bases, namespace):
cls2 = type(ctypes.c_int).__new__(cls, name, bases, namespace)
if namespace.get("__module__") != __name__:
namespace["_values_"].clear()
for name in namespace["_names_"].keys():
... | StarcoderdataPython |
152230 | from django.contrib import admin
from django.contrib.auth.models import Permission
from simple_history.admin import SimpleHistoryAdmin
from django.db.models import F
from .models import School, Profile, CotisationHistory, WhiteListHistory
class CotisationHistoryAdmin(SimpleHistoryAdmin):
"""
The admin class f... | StarcoderdataPython |
3326644 | """Chat history plugin"""
import os
from typing import Optional, List, Any
from dataclasses import dataclass, field
from wechaty_puppet import MessageType, FileBox
from wechaty import Wechaty, Message, get_logger
from wechaty.plugin import WechatyPlugin, WechatyPluginOptions
from sqlalchemy.ext.asyncio import AsyncSess... | StarcoderdataPython |
3361458 | <gh_stars>1-10
from netapp.netapp_object import NetAppObject
class VolumeFlexcacheAttributes(NetAppObject):
"""
Information about FlexCache volumes.
"""
_origin = None
@property
def origin(self):
"""
The name of the origin volume that contains the
authoritative data... | StarcoderdataPython |
67212 | <reponame>run-ai/runai
import os
import unittest
import keras
from keras.utils.np_utils import to_categorical
from keras.layers import Dense
from keras.models import Sequential
import keras.optimizers
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
import runai.utils
import r... | StarcoderdataPython |
3290961 | <gh_stars>1-10
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647... | StarcoderdataPython |
37762 | # Export the contents of AviSys files SIGHTING.DAT and FNotes.DAT to CSV format
# Author: <NAME> <<EMAIL>>
# Version: 1.2 3 April 2021
import sys
import csv
import ctypes
# Input files
DATA_FILE = 'SIGHTING.DAT'
MASTER_FILE = 'MASTER.AVI'
PLACES_FILE = 'PLACES.AVI'
NOTE_INDEX = 'FNotes.IX'
NOTE_FILE = 'FNotes.DAT'
AS... | StarcoderdataPython |
3294410 | <filename>extract_haplotype_read_counts.py<gh_stars>0
#!/bin/env python
#
# Copyright 2013 <NAME> and <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... | StarcoderdataPython |
3292827 | # -*- coding: utf-8 -*-
"""
* TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available.
* Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in complianc... | StarcoderdataPython |
4837464 | import argparse
import sys
import time
import numpy as np
import pyqtgraph as pg
from sensapex import UMP
from sensapex.sensapex import LIBUM_DEF_BCAST_ADDRESS
from sensapex.utils import bytes_str
parser = argparse.ArgumentParser(
description="Test for sensapex devices; perform a series of random moves while rap... | StarcoderdataPython |
3223832 | <filename>python_code/vnev/Lib/site-packages/jdcloud_sdk/services/cdn/apis/SetReferRequest.py
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | StarcoderdataPython |
4809266 | <reponame>dmontoya1/cajas
from django.db import models
from enumfields import EnumField
from enumfields import Enum
class ConceptType(Enum):
SIMPLE = 'SM'
DOUBLE = 'DB'
SIMPLEDOUBLE = 'SD'
class Labels:
SIMPLE = 'Simple'
DOUBLE = 'Doble'
SIMPLEDOUBLE = 'Simple y doble'
cla... | StarcoderdataPython |
3345045 | <gh_stars>1-10
import os
import math
import json
import logging
import torch
import torch.optim as optim
from tensorboardX import SummaryWriter
from ..utils.util import ensure_dir
class BaseTrainer:
"""
Base class for all trainers
"""
def __init__(self, model, loss, metrics, resume, config, train_logg... | StarcoderdataPython |
1716660 | <gh_stars>1-10
class Solution:
def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
return sorted(points, key = lambda x: x[0] ** 2 + x[1] ** 2)[:K]
| StarcoderdataPython |
114935 | <filename>src/pass.py
import os
import threading
import hashlib
import ast
import keypirinha as kp
import keypirinha_util as kpu
class Pass(kp.Plugin):
"""
Provides an interface to a [password store](https://www.passwordstore.org/).
"""
CAT_FILE = kp.ItemCategory.USER_BASE + 1
CAT_FILE_LINE = kp.I... | StarcoderdataPython |
76692 | <filename>aiotdlib/api/functions/delete_revoked_chat_invite_link.py
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
... | StarcoderdataPython |
76331 | <reponame>fuckseer/Refactoring
from PIL import Image
import numpy as np
import doctest
def convert_image_to_mosaic(image,size,gradation_step):
"""
Convert image to mosaic
param image: needed image
param size: block size mosaic
param gradation_step: gradation of gray
return... | StarcoderdataPython |
99861 | <filename>2020/days/friday/bfs.py
from collections import deque
def neighbors(v):
pass # Tůdů
def bfs(start, end):
queue = deque([start])
beenTo = set()
direction = dict()
while len(queue) > 0:
v = queue.popleft()
if v == end:
cesta = [v]
while v != start:... | StarcoderdataPython |
4823161 | <reponame>Taymindis/kubernetes-ingress<filename>tests/suite/test_app_protect_watch_namespace.py<gh_stars>1000+
import requests
import pytest
import time
from settings import TEST_DATA, DEPLOYMENTS
from suite.ap_resources_utils import (
create_ap_logconf_from_yaml,
create_ap_policy_from_yaml,
delete_ap_poli... | StarcoderdataPython |
194647 | <reponame>Mariatta/batavia
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class PrintTests(TranspileTestCase):
def test_buffering(self):
self.assertCodeExecution("""
print('1: hello', ' world')
print('2: hello\\n', 'world')
print('3: hello', ' world\\n'... | StarcoderdataPython |
1605200 | import random
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
from groovebot.core.models import Album, Music, Abbreviation, Strike
from groovebot.core.utils import (
read_file,
failure_message,
success_message,
config,
text_to_neuropol,
)
class Mu... | StarcoderdataPython |
3371757 | <gh_stars>1-10
try:
import rest_framework
except ImportError:
import unittest
raise unittest.SkipTest("djangorestframework is not installed")
from decimal import Decimal
from typing import Optional
from typing import Set
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models... | StarcoderdataPython |
1692423 | <reponame>oxigenocc/oxigeno.cc<filename>mysite/equipos/management/commands/equipos_db_migration.py
from django.core.management.base import BaseCommand
from oxigeno.models import Tanque, Concentrador
from equipos.models import Tanque as Tan
from equipos.models import Concentrador as Conc
def migration():
tanques =... | StarcoderdataPython |
139528 | from spacy.tokens import Doc
def convert(cols, matched_token_idx):
#temp_path = os.path.join(this_dir,'temp.conllu')
matched_i = [list(map(lambda x: str(x+1), matched)) for matched in matched_token_idx]
for matched in matched_i:
cols = change_head(matched, cols)
return cols
def ch... | StarcoderdataPython |
1633549 | # views.py
from datetime import datetime
from flask import Flask
from flask import render_template
from flask import flash
from flask import redirect
from flask import request
from flask_sqlalchemy import SQLAlchemy
from flask_login import login_user
from flask_login import logout_user
from flask_login import current_u... | StarcoderdataPython |
3294600 | # -*- coding: utf-8 -*-
from spiders.BeiJing import BeijingSpider
from model.config import DBSession
from model.rule import Rule
from scrapy.crawler import CrawlerProcess
from scrapy.settings import Settings
from scrapy.crawler import Crawler
from twisted.internet import reactor
from scrapy import signals
RUNNING_CRA... | StarcoderdataPython |
178244 | <gh_stars>1-10
#!/usr/bin/env python
import matplotlib
import matplotlib.gridspec as gridspec
from pylab import *
import matplotlib.pyplot as plt
import numpy as np
from math import pow, exp
from scipy.stats import norm
# 133 0.5
#Create test data with zero valued diagonal:
data = np.genfromtxt("seq.txt", delimiter='... | StarcoderdataPython |
3320798 | import os
import random
import numpy as np
from itertools import chain, combinations
import torch
from torchvision import transforms
import torch.optim as optim
import PIL.Image as Image
from sklearn.metrics import accuracy_score
#from utils.BaseExperiment import BaseExperiment
from PIL import ImageFont
from modal... | StarcoderdataPython |
4826832 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
import torch.nn.init as init
from sklearn.preprocessing import MinMaxScaler
import sys
from tqdm import tqdm
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') !... | StarcoderdataPython |
107338 | <filename>shared.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# =============================================================================
#
# This file cont... | StarcoderdataPython |
3270570 | import sys
import time
import subprocess
import os
import signal
wait = False
timeout = 0
srvfil = open("./antifreeze/time_" + sys.argv[1] +".txt", "r")
while (True):
srvtime = 0
time.sleep(1)
srvfil.seek(0)
try:
srvtime=int(srvfil.readlines()[0])
except IndexError as e:
print(e)
continue
systime=round(ti... | StarcoderdataPython |
1764020 | <gh_stars>0
import sys
import argparse
import torch
from genre.util.util_print import str_warning
from genre.datasets import get_dataset
from genre.models import get_model
def add_general_arguments(parser):
# Parameters that will NOT be overwritten when resuming
unique_params = {'gpu', 'resume', 'epoch', 'wor... | StarcoderdataPython |
1718855 |
import itertools
import time
from testbase import cur
for num in itertools.count():
cur.execute("select * from foo")
foovals = cur.fetchall()
print num, 'I fetched', len(foovals), 'values.', time.ctime()
| StarcoderdataPython |
3338347 | from contextlib import contextmanager
import json
from pprint import PrettyPrinter
from toolspy import merge
def run_interactive_shell(app, db):
app.config['WTF_CSRF_ENABLED'] = False
# Needed for making the console work in app request context
ctx = app.test_request_context()
ctx.push()
# app.p... | StarcoderdataPython |
3383884 | <filename>vidbench/visualize.py
# ###########################################################################
#
# CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP)
# (C) Cloudera, Inc. 2021
# All rights reserved.
#
# Applicable Open Source License: Apache 2.0
#
# NOTE: Cloudera open source products are modular sof... | StarcoderdataPython |
3271665 | <reponame>Illumina/SMNCopyNumberCaller
from charts.colors import color_arr
from charts.scale import scale, y_scale
class SvgElement:
def __init__(self, name, attrs, value=None):
self.name = name
self.value = value
self.attrs = attrs
def to_string(self):
result = "<%s" % self.n... | StarcoderdataPython |
3377991 | # Relational
# Copyright (C) 2008 Salvo "LtWorf" Tomaselli
#
# Relational 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 later version.
#
# This pro... | StarcoderdataPython |
1607328 | import os
import sys
import gensim
import logging.config
from gensim.models import KeyedVectors
from typing import List, Any, Tuple
from tqdm import tqdm
from kbc_rdf2vec.dataset import DataSet
from kbc_rdf2vec.prediction import PredictionFunctionEnum
logconf_file = os.path.join(os.path.dirname(__file__), "log.conf"... | StarcoderdataPython |
3262097 | # 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
# distributed under the Li... | StarcoderdataPython |
71706 | import os
import yaml
def _replace_desdata(pth, desdata):
"""Replace the NERSC DESDATA path if needed.
Parameters
----------
pth : str
The path string on which to do replacement.
desdata : str
The desired DESDATA. If None, then the path is simply returned as is.
Returns
-... | StarcoderdataPython |
3371212 | <filename>tests/test_package.py
from importlib import util
def test_package():
fastapi_profile_spec = util.find_spec("fastapi_profile")
assert fastapi_profile_spec is not None
| StarcoderdataPython |
1780470 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_options_tab.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_options(object):
def setupUi(self, options):
optio... | StarcoderdataPython |
3325805 | <filename>pyinsteon/handlers/from_device/broadcast_command.py
"""Base class to handle Broadcast messages from devices."""
from datetime import datetime
from ...constants import MessageFlagType
from ..inbound_base import InboundHandlerBase
class BroadcastCommandHandlerBase(InboundHandlerBase):
"""Base class to ha... | StarcoderdataPython |
1789071 | import os
import struct
import binascii
import socket
import threading
import datetime
from time import time, sleep
from json import load, loads, dumps
from src.utils import *
from src.db_worker import *
from src.logs.log_config import logger
from src.protocols.Teltonika.crc import crc16
class Teltonika:
BASE_PAT... | StarcoderdataPython |
55707 | # FinSim
# Copyright 2018 <NAME>. All Rights Reserved.
# NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, ... | StarcoderdataPython |
1649339 | #----------------------------------------------------------------------
# Copyright (c) 2012-2015 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including without limitation ... | StarcoderdataPython |
3377238 | from __future__ import print_function
import unittest
import nifty
import nifty.graph
nlmc = nifty.graph.lifted_multicut
import numpy
import random
class TestLiftedGraphFeatures(unittest.TestCase):
def generateGrid(self, gridSize):
def nid(x, y):
return x*gridSize[1] + y
G = nifty.g... | StarcoderdataPython |
3220996 | """Repository rule for def file filter autoconfiguration.
This repository reuses Bazel's VC detect mechanism to find undname.exe,
which is a tool used in def_file_filter.py.
def_file_filter.py is for filtering the DEF file for TensorFlow on Windows.
On Windows, we use a DEF file generated by Bazel to export symbols f... | StarcoderdataPython |
116213 | <reponame>Jumpscale/jumpscale_core8
"""
Test JSCuisine (core)
"""
import unittest
from unittest import mock
from JumpScale import j
from JumpScale.tools.cuisine.JSCuisine import JSCuisine
import JumpScale
from JumpScale.tools.cuisine.ProcessManagerFactory import ProcessManagerFactory
class TestJSCuisine(unittest.Te... | StarcoderdataPython |
57231 | <filename>test/test_exec.py<gh_stars>0
from unittest import TestCase
from easy_exec import exec
class TestExec(TestCase):
def test_stdout(self):
stdout, stderr, has_error = exec('echo "hello world"')
self.assertEqual('hello world\n', stdout)
self.assertEqual('', stderr)
self.as... | StarcoderdataPython |
3300335 | from django.apps import AppConfig
class GoodscfConfig(AppConfig):
name = 'goodscf'
| StarcoderdataPython |
4828527 | <reponame>Snehakri022/HackerrankPractice
# Problem: https://www.hackerrank.com/challenges/new-year-chaos/problem
# Score: 40
t = int(input())
for test in range(t):
n = int(input())
arr = list(map(int, input().split()))
count = 0
for i in range(2):
for j in range(len(arr) - 1, 0, -1):
... | StarcoderdataPython |
3236501 | <filename>embiggen/node_label_prediction/node_label_prediction_model.py<gh_stars>1-10
"""Module providing abstract node label prediction model."""
from typing import Optional, Union, List, Dict, Any, Tuple
import pandas as pd
import numpy as np
import warnings
from ensmallen import Graph
from embiggen.utils.abstract_mo... | StarcoderdataPython |
60404 | <filename>test/sysl/test_sysldata.py<gh_stars>1-10
from sysl.core import syslloader, sysldata
import unittest
import re
import os
import sys
from os import path
import traceback
import tempfile
import argparse as ap
class TestSetOf(unittest.TestCase):
def setUp(self):
self.outpath = tempfile.gettempdir()
... | StarcoderdataPython |
4826105 | <gh_stars>0
from django import template
from django.db.models import Count, F
from shop.models import Category
register = template.Library()
@register.simple_tag()
def get_categories():
return Category.objects.annotate(
cnt=Count('product', filter=F('product__is_published'))).filter(cnt__gt=0).order_by('... | StarcoderdataPython |
3355222 | from clinicadl.utils.network.autoencoder.cnn_transformer import CNN_Transformer
from clinicadl.utils.network.cnn.models import Conv4_FC3, Conv5_FC3, resnet18
from clinicadl.utils.network.sub_network import AutoEncoder
class AE_Conv5_FC3(AutoEncoder):
"""
Autoencoder derived from the convolutional part of CNN ... | StarcoderdataPython |
3370962 | """Plotting methods."""
from collections import Counter
from itertools import cycle
from itertools import islice
import os
import pickle
import sys
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FormatStrFormatter
f... | StarcoderdataPython |
1674144 | # Copyright 2013 Google Inc. 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 ag... | StarcoderdataPython |
1685837 | from datetime import datetime, timedelta
from calelib import Constants
def get_deadline(deadline_string):
"""
Parse string like to datetime object
:param deadline_string: string in format "DAY MONTH"
:return: string in datetime format
"""
if len(deadline_string.split(',')) > 1:
date,... | StarcoderdataPython |
4838795 | <gh_stars>1-10
# Exercise 1
# Напишете програма, която дава възможност на потребителя да въвежда неограничен брой цели числа.
# Да се изведе какъв е процента на числата, които са кратни на 7, резултата да се закръгли до втория
# знак след десетичната запетая. Да се изведе каква е сумата на числата, които не са кратн... | StarcoderdataPython |
3398879 | """Tests for ``from_datatimes`` generator class method."""
import math
import random
import numpy as np
from waves import Sound
def test_from_datatimes_mono(mono_ttf_gen):
fps, frequency, volume = (44100, 110, 0.5)
time_to_frame = mono_ttf_gen(fps=fps, frequency=frequency, volume=volume)
sound = Sound... | StarcoderdataPython |
63904 | import sys
import numpy as np
import pandas as pd
#py 101903371.py 101903371-data.csv 1,1,1,2,2 +,-,+,-,+ 101903371-result.csv
def topsis(filename,weights,impacts,output_filename):
#Check if input file is csv
if filename.split(".")[-1]!="csv":
sys.exit("Error: Please enter a valid input csv f... | StarcoderdataPython |
3385723 | <reponame>jimnarey/alu_auto_builder
from shared import configs, help_messages
import runners
input_path_opt = {
'name': 'input_path',
'cli_short': 'i',
'gui_required': True,
'type': 'file_open',
'help': help_messages.INPUT_PATH
}
input_dir_opt = {
'name': 'input_dir',
'cli_short': 'i',... | StarcoderdataPython |
1607367 | <reponame>kissingurami/python_twisted<filename>multi_thread/RLock_example.py
# -*- coding: utf-8 -*-
'''
Lock与RLock的区别
从原理上来说:在同一线程内,对RLock进行多次acquire()操作,程序不会阻塞。
每个thread都运行f(),f()获取锁后,运行g(),但g()中也需要获取同一个锁。如果用Lock,这里多次获取锁,就发生了死锁。
但我们代码中使用了RLock。在同一线程内,对RLock进行多次acquire()操作,程序不会堵塞,
'''
import threading
rlock = threadin... | StarcoderdataPython |
11865 | """Use pika with the Tornado IOLoop
"""
import logging
from tornado import ioloop
from pika.adapters.utils import nbio_interface, selector_ioloop_adapter
from pika.adapters import base_connection
LOGGER = logging.getLogger(__name__)
class TornadoConnection(base_connection.BaseConnection):
"""The TornadoConne... | StarcoderdataPython |
72625 | <filename>fairseq/models/hubert/hubert.py
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
impo... | StarcoderdataPython |
3262708 | <filename>lazysort.py
import typing
from random import randint
from heapq import merge
from itertools import chain, tee
def lazysort(l: list) -> typing.Iterator:
# Stage 1
stack = []
current_list = iter(l)
sentinel = object()
first = next(current_list, sentinel)
while first is not sentinel:
... | StarcoderdataPython |
3333017 | from lib.base_controller import CommandController
class CollectinfoCommandController(CommandController):
log_handler = None
def __init__(self, log_handler):
CollectinfoCommandController.log_handler = log_handler
| StarcoderdataPython |
3382304 | # -*- coding: utf-8 -*-
from django.urls import re_path
from layouter.views import ToggleGridView
app_name = 'layouter'
urlpatterns = [
re_path(r'^toggle-grid/', ToggleGridView.as_view(), name='toggle-grid')
]
| StarcoderdataPython |
3247218 | from __future__ import absolute_import, division, print_function
__all__ = ["chachifuncs","descriptors","chachies", "version"]
from chachies import chachifuncs
from chachies import descriptors
from chachies.version import __version__
| StarcoderdataPython |
125206 | <filename>python-flask/tests/test_api.py<gh_stars>0
# Copyright (c) 2016 <NAME>
# All rights reserved.
import unittest
from app import app
class APITestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_index(self):
with app.test_client() as client:
... | StarcoderdataPython |
1732750 | <reponame>tokenchain/tronpytool
#!/usr/bin/env python
# coding: utf-8
from tronpytool import Tron
tron = Tron().setNetwork('nile')
st1 = tron.address.to_hex('TT67rPNwgmpeimvHUMVzFfKsjL9GZ1wGw8')
st2 = tron.address.to_hex_0x('TT67rPNwgmpeimvHUMVzFfKsjL9GZ1wGw8')
st22 = tron.address.to_hex_0x_41('TT67rPNwgmpeimvHUMVzFf... | StarcoderdataPython |
3367294 | # general imports
import shutil
import pytest
from pathlib import Path
# AHA imports
import fault
import magma as m
# DragonPHY-specific imports
from dragonphy import get_deps_cpu_sim
THIS_DIR = Path(__file__).parent.resolve()
BUILD_DIR = THIS_DIR / 'build'
def list_head(lis, n=25):
trimmed = lis[:n]
if len... | StarcoderdataPython |
1643419 | from unittest import TestCase
from salesdataanalyzer.analyzer import analyze_data
from salesdataanalyzer.helpers import Salesman, Customer, Sale, SaleItem, \
DataSummary
class AnalyzerTest(TestCase):
def test_analyze_data(self):
salesmen = [
Salesman('12312312312', '<NAME>', 192000.00),
... | StarcoderdataPython |
1759228 | <gh_stars>1-10
import fulfillment
fulfillment.core.api_key = 'YOUR_API_KEY_GOES_HERE'
# set debug to true to get print json
fulfillment.core.Debug = True
fulfillment.Product.create(
title='example product',
barcode='123456789',
type='merchandise',
origin_country='US',
hs_code='1234.56.78',
req... | StarcoderdataPython |
3367658 | <reponame>awsa2ron/aws-doc-sdk-examples
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Unit tests for find_running_models.py.
"""
import pytest
from botocore.exceptions import ClientError
import datetime
import boto3
import models
from boto3.session imp... | StarcoderdataPython |
93114 | import pprint
import re
from typing import Any, Dict
import numpy as np
import pytest
from qcelemental.molutil import compute_scramble
from qcengine.programs.tests.standard_suite_contracts import (
contractual_accsd_prt_pr,
contractual_ccd,
contractual_ccsd,
contractual_ccsd_prt_pr,
contractual_ccs... | StarcoderdataPython |
1764088 | <reponame>sonecabr/konker-platform
import xml.etree.ElementTree as ET
from .gateway import *
CARTS_RESOURCE = "http://ec2-52-4-244-64.compute-1.amazonaws.com/konkershop/api/carts/"
FIND_LAST_CART_TEMPLATE = CARTS_RESOURCE + "?filter[id_customer]=%s&sort=[id_DESC]&limit=1"
GET_LAST_CART_TEMPLATE = CARTS_RESOURCE + "%s"... | StarcoderdataPython |
1794341 | {
"targets": [
{
"target_name": "addon",
"sources": [
"src/addon.cc",
"src/blake2.cc",
"lib/BLAKE2/sse/blake2b.c",
"lib/BLAKE2/sse/blake2bp.c",
"lib/BLAKE2/sse/blake2s.c",
"lib/BLAKE2/sse/blake2sp.c"
],
"include_dirs" : [
"lib/BLAKE2/sse"
],
"cflags_c": [ "-std=c99" ]
... | StarcoderdataPython |
1671700 | """
Contains classes and functions pertaining to database serialization.
"""
import os
from breakdb.io.export.voc import VOCDatabaseEntryExporter
from breakdb.io.export.yolo import YOLODatabaseEntryExporter
from breakdb.io.reading import CsvDatabaseReader, ExcelDatabaseReader, \
JsonDatabaseReader
from breakdb.io.... | StarcoderdataPython |
1668384 | <filename>workbench/invoices/test_projected_invoices.py<gh_stars>10-100
from decimal import Decimal
from django.core import mail
from django.test import TestCase
from django.utils.translation import deactivate_all
from time_machine import travel
from workbench import factories
from workbench.invoices.tasks import se... | StarcoderdataPython |
125527 | import json
import pickle
import ast
import math
import operator
def get_lang_prior(pomdp_to_map_fp, lang_dict_fp):
"""
Convert the lang prior dictionary to a format usable by pomdp
"""
pomdp_to_map = {}
with open(pomdp_to_map_fp, 'r') as fin:
pomdp_to_map = json.load(fin)
lang_dict =... | StarcoderdataPython |
3358772 | """
##################################################################################################
# Copyright Info : Copyright (c) <NAME> @ Hikvision Research Institute. All rights reserved.
# Filename : builder.py
# Abstract :
# Current Version: 1.0.0
# Date : 2020-05-31
#######... | StarcoderdataPython |
3256032 | from .webgme import WebGME
from .pluginbase import PluginBase
from .exceptions import CoreIllegalArgumentError, CoreIllegalOperationError, CoreInternalError, JSError
name = "webgme_bindings"
| StarcoderdataPython |
1667169 | <filename>gammapy/spectrum/sherpa_models.py<gh_stars>1-10
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Sherpa spectral models
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from sherpa.models import ArithmeticModel, Parameter, modelCacher1d
__all__ = [
... | StarcoderdataPython |
112013 | CONTAINER = "container"
BLUE = "#33aeff"
GREEN = "#a4c639"
| StarcoderdataPython |
3299188 | '''
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.)
Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".)
Example 1:
Input: "banana"
Output: "an... | StarcoderdataPython |
79755 | """
The Yahoo finance component.
https://github.com/iprak/yahoofinance
"""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Final, Union
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers impor... | StarcoderdataPython |
2562 | <gh_stars>0
import logging
import pathlib
logging.basicConfig(level=logging.INFO)
# Dirs
ROOT_DIR = pathlib.Path(__file__).parent.absolute()
DUMP_DIR = ROOT_DIR / 'dumps'
| StarcoderdataPython |
3234211 | <reponame>JalajaTR/cQube
import csv
import os
import re
import time
from selenium.webdriver.support.select import Select
from Data.parameters import Data
from filenames import file_extention
from get_dir import pwd
from reuse_func import GetData
class test_course_based_on_timeperiods():
def __init__(self,driver... | StarcoderdataPython |
1608082 | __all__ = ['retry', 'retry_call']
import logging
from .api import retry, retry_call
from .compat import NullHandler
log = logging.getLogger(__name__)
log.addHandler(NullHandler())
| StarcoderdataPython |
1614365 | <reponame>Time0o/advent-of-code
#!/usr/bin/env python3
import json
def add_numbers(data, ignore_red: bool = False) -> int:
if isinstance(data, dict):
if ignore_red and ('red' in data.keys() or 'red' in data.values()):
return 0
return sum([add_numbers(k, ignore_red) + add_numbers(v, i... | StarcoderdataPython |
3282822 | from .block_body import BlockBodyFactory # noqa: F401
from .block_hash import BlockHashFactory, Hash32Factory # noqa: F401
from .chain_context import ChainContextFactory # noqa: F401
from .db import ( # noqa: F401
MemoryDBFactory,
AtomicDBFactory,
HeaderDBFactory,
AsyncHeaderDBFactory,
)
from .les.p... | StarcoderdataPython |
138541 | <filename>supbot/statemanager/state.py
from enum import Enum
from typing import Tuple, cast
from abc import ABC
from supbot import g
from supbot.results import GotoStateResult
class State(Enum):
"""
Represents different states of the gui in whatsapp app
"""
MAIN = 0,
CHAT = 1,
SEARCH = 2
... | StarcoderdataPython |
3332701 | <gh_stars>0
# class for generating command line, and configuration files:
# a replacement for arparser, it performas all the same functions with several key differences
# 1: can use an editable configuration file to set all or some arguments, allowing cmdline entries to take precedence if present
# 2: it can generate N... | StarcoderdataPython |
89461 | <reponame>Allain18/pimontecarlo
"""Calcule pi grace à la méthode de monte Carlo"""
import random
import argparse
import matplotlib.pyplot as plt
def compute_pi(iteration, show_plot=False):
"""Compute pi"""
inside = 0
x_inside = []
y_inside = []
x_outside = []
y_outside = []
for _ in ra... | StarcoderdataPython |
1623048 | #Programa creado por <NAME>
def foreign_exchange_calculator(ammount):
mex_to_col_rate = 145.97
return mex_to_col_rate * ammount
def run():
print('CALCULADORA DE DIVISAS')
print('Convierte pesos mexicanos a persos colombianos.')
print('')
ammount = float(input('ingresa la cantidad de pesos me... | StarcoderdataPython |
1682369 | <reponame>lrei/text-classification
import math
import torch
from tqdm import tqdm
def train_eval(model, criterion, eval_iter, rnn_out=False):
model.eval()
acc = 0.0
n_total = 0
n_correct = 0
test_loss = 0.0
for x, y in eval_iter:
with torch.no_grad():
if torch.cuda.is_avai... | StarcoderdataPython |
1621805 | <reponame>ArenaNetworks/dto-digitalmarketplace-supplier-frontend
# coding: utf-8
from __future__ import unicode_literals
import urllib2
from app.main.helpers.users import generate_supplier_invitation_token
from dmapiclient import HTTPError
from dmapiclient.audit import AuditTypes
from dmutils.email import generate_t... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.