id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1732920 | # encoding: utf-8
# pylint: disable=too-many-arguments
"""
运行程序相关的Invoke模块
"""
from invoke import task
import logging
log = logging.getLogger(__name__) # pylint: disable=invalid-name
@task(
default=True,
help={
"host": "主机IP",
"port": "接口",
"pty": "pty支持",
"use-reloader": "是... | StarcoderdataPython |
3242927 | <filename>lib/innvestigate/src/innvestigate/tests/tools/test_pattern.py
# Get Python six functionality:
from __future__ import\
absolute_import, print_function, division, unicode_literals
###############################################################################
##############################################... | StarcoderdataPython |
4829672 | <reponame>proactivity-lab/moteping
"""packets.py: MotePing util."""
import sys
__author__ = "<NAME>"
__license__ = "MIT"
print_colors = False
def has_colors():
if sys.platform == 'win32':
return False
return True
def print_std(s):
print(s)
sys.stdout.flush()
def print_red(s):
if pri... | StarcoderdataPython |
130763 | def arithmeticExpression(a, b, c):
"""
Consider an arithmetic expression of the form a#b=c.
Check whether it is possible to replace # with one of
the four signs: +, -, * or / to obtain a correct
"""
return (
True if (a + b == c) or (a - b == c) or (a * b == c) or (a / b == c) else Fals... | StarcoderdataPython |
3224226 | <filename>exec04/exec04.py
year = int(input('Entre com um ano: '))
if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0):
print(f'{year} é um ano bissexto')
else:
print(f'{year} não é um ano bissexto')
| StarcoderdataPython |
37028 | <reponame>kuna/twfavcrawler
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from models import *
import twitter
# -------------------------------
def main(request):
return render(request, "main.htm")
# if not logined, then go to auth page fir... | StarcoderdataPython |
3312791 | <reponame>TermService/OnyxForum
import datetime
import logging
from typing import Tuple
from sqlalchemy import func
from flask_login import current_user
from flaskbb.user.models import User
from flaskbb.forum.models import Post
from flaskbb.utils.helpers import render_template
from flaskbb.extensions import db
from ... | StarcoderdataPython |
3265411 | <filename>glearn/crf/ixx_glodon/template/logger.py
# coding=utf-8
u"""
Description: Generate basic template from xls.
Used SQLalchemy tool .
User: Jerry.Fang
Date: 13-12-13
"""
from lib.log_util import create_log
logger = create_log('glodon')
| StarcoderdataPython |
1794041 | """
A collection of functions for processing parent-child lists into hierarchical dictionaries.
The goal, which buildConceptDict accomplishes, is to go from a list like this:
inp = [['San Francisco','California'], ['California','United States'], ['North America',None], ['Africa',None],\
['New York','Unite... | StarcoderdataPython |
71259 | import pygame
import json
class SpriteSheet:
"""
Class for managing sprite sheets and loading them in and getting the next frame
"""
def __init__(self, root_location: str, sprite_id: int):
self.next_frame = 1
with open(f"{root_location}\\data.json", "r") as file:
data = jso... | StarcoderdataPython |
3216170 | <filename>payments/client/exceptions.py
class MangopayError(Exception):
pass
class MangopayTransferError(MangopayError):
pass
| StarcoderdataPython |
3302168 | print('******************')
print('* EMPRÉSTIMO *')
print('******************')
nome = input('Bom dia, senhor... Qual é o seu nome?\n')
sal = float(input('Bom dia, senhor {}, posso ver que o senhor precisa de um empréstimo para comprar uma casa, '
'qual é o seu '
'salário mensal?\n'.forma... | StarcoderdataPython |
1661664 | from typing import List, Union
from random import randint
b = ":black_large_square:"
r = ":red_square:"
o = ":orange_square:"
p = ":purple_square:"
g = ":green_square:"
def t(char):
return ":regional_indicator_"+char+":"
def text1(char):
return b+b+t(char)+b+b
def text2(char):
return b+t(char)+b+t(ch... | StarcoderdataPython |
3319743 | <gh_stars>0
#<NAME>
#jan 24 17
#Milage Prgm
#Calculates the milage you can get out of a single tank of gas
#variables
# tank, gas tank size
# car, the name of the car
# mpg, miles per gallon the car gets
# price, cost of gas
# cost, cost to fill the whole tank
# distance, total distance the car ca... | StarcoderdataPython |
4800243 | import numpy as np
from backend.GA.genetic_algorithm import GeneticAlgorithm
from backend.GA.genomes import Genome1D
from backend.helpers import translate_bits_to_float
def fitness_function(genome):
interval = [0, 512]
x = translate_bits_to_float(bit_string=genome.genes[::-1], interval=interval)
... | StarcoderdataPython |
91042 | import subprocess
def main():
parser = argparse.ArgumentParser(description='Builds a Latex file.')
parser.add_argument('filename',
type=str,
default='',
help='File to be built')
args = parser.parse_args()
subprocess.check_call(['xelatex', args.filename])
if __name__ == '__main__':
main()
| StarcoderdataPython |
1788429 | <filename>my_util/sloth/sloth/plugins/plugin.py
# -*- encoding: utf-8 -*-
'''
@Time : 2021-08-14
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc : 基础类
'''
# here put the import lib
from selenium.webdriver.chrome.webdriver import WebDriver
import abc
class Plugin(metaclass=abc.ABCMe... | StarcoderdataPython |
114917 | <gh_stars>0
from django import forms
from localflavor.us.forms import USStateSelect
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column
class StateForm(forms.Form):
state = forms.CharField(widget=USStateSelect)
enable_filter = forms.BooleanField(re... | StarcoderdataPython |
3321825 | <filename>tests/things/test_holiday.py<gh_stars>1-10
from django.utils import timezone
from core.response import Response
from things.tests import TestCase
class HolidayTest(TestCase):
def setUp(self):
self.create_user(is_staff=True)
def nottest_data_go_kr_get_holidays(self): # name prefix to test ... | StarcoderdataPython |
1717351 | <gh_stars>1-10
from django.contrib import admin
from django.urls import include, path
from home import accounts, views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("home.urls")),
# Accounts
path('accounts/login/', accounts.Login.as_view(), name='login'),
path('accounts/logout/... | StarcoderdataPython |
1641492 | <filename>src/ext/executor/wf_executor.py
import concurrent.futures
from service import train_image_service as ti_service
running_id = {}
pool = concurrent.futures.ThreadPoolExecutor(5)
def submit_train_task(root_path, label):
print('Call submit_train_task')
if (not label in running_id or running_id... | StarcoderdataPython |
165123 | from datetime import datetime, date
from django.urls import reverse
from django.contrib.gis.geos import Point
from rest_framework.test import APITestCase
from rest_framework import status
from robber import expect
import pytz
from data.factories import PoliceUnitFactory, OfficerFactory, OfficerHistoryFactory, Office... | StarcoderdataPython |
3275000 | # -*- coding: utf-8 -*-
# Copyright 2015 <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/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
167518 | #!/usr/bin/python
# Copyright 2012 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 applic... | StarcoderdataPython |
192296 | <reponame>assuzzanne/my-sqreen
# -*- coding: utf-8 -*-
# Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved.
# Please refer to our terms for more information:
#
# https://www.sqreen.io/terms.html
#
""" Blank request for callbacks needing a request when no one is present
"""
from .base import BaseRequ... | StarcoderdataPython |
3292239 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP
class res_partner(models.Model):
_name = 'res.partner'
_inherit = 'res.partner'
def _compu... | StarcoderdataPython |
1736110 | <reponame>Ahmad-Fahad/Python
class Queue:
def __init__(self):
self.lst = list()
def enQueue(self, item):
self.lst.append(item)
def deQueue(self):
return self.lst.pop(0)
def is_empty(self):
if self.lst == []:
return True
return False
st = Queue()
st.enQueue(1)
st.enQueue(2)
st.enQueue(3)
st.enQueue(4... | StarcoderdataPython |
3357130 | <reponame>bitsofinfo/swarm-traefik-state-analyzer
#!/usr/bin/env python
__author__ = "bitsofinfo"
import random
import json
import pprint
import re
import argparse
import getopt, sys
import ssl
import datetime
import logging
import swarmstatedb
import servicechecksdb
import servicechecker
import servicecheckerreport
... | StarcoderdataPython |
10565 | class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class Binary_Tree:
def __init__(self):
self.root = None
def pre_order(self):
""" root-left-right """
try:
self.values=[]
if self.ro... | StarcoderdataPython |
1770453 | <gh_stars>0
# Downloads everything from a YouTube Playlist before a certain date
# Use -d option to set the date
from ydl import ydl
from optparse import OptionParser
import sys
parser = OptionParser()
parser.add_option("-d", "--date",
action="store", dest="datebefore",
help="Down... | StarcoderdataPython |
149501 | import torch
import torch.nn as nn
_input_size = 4
_seq_len = 2
_batch = 3
_hidden_size = 3
# model
class net_RNN(nn.Module):
def __init__(self):
super().__init__()
self.op = nn.RNN(_input_size, _hidden_size, 1)
def forward(self, input):
return self.op(input)
_model_ = net_RNN()
#... | StarcoderdataPython |
4831819 | <reponame>pgDora56/Mocho
# coding=utf-8
class Board:
channel = None
random_ch = None
owner = None
locked = False
joiner = []
answers_judge = []
prev = []
def __init__(self, main_channel, random_channel):
self.channel = main_channel
self.random_ch = random_cha... | StarcoderdataPython |
116905 | from stv.generators.ispl.ispl_generator import IsplGenerator
import itertools
import random
class BridgeModelIsplGenerator(IsplGenerator):
@property
def card_names(self) -> [str]:
return ["Ace", "King", "Queen", "Jack", "ten", "nine", "eight", "seven", "six", "five", "four", "three", "two"]
@pro... | StarcoderdataPython |
1616213 | def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
comps = path.split('/')
new_comps = []
for comp in comps:
if comp == '':
continue
if comp in ('.', '..'):
raise ValueError('relative paths not allowed')
new_comps.append(comp)
s... | StarcoderdataPython |
1686967 | <gh_stars>0
#!/usr/bin/env python
# coding: utf-8
# In[31]:
pip install sounddevice
# In[32]:
import sounddevice
# In[33]:
pip install scipy
# In[34]:
from scipy.io.wavfile import write
# In[35]:
fps= 44100
# In[36]:
duration= 10
# In[37]:
print("recording...")
# In[38]:
recording = sound... | StarcoderdataPython |
187575 | <gh_stars>1-10
import os
ISO8601_DATETIME = "%Y-%m-%dT%H:%M:%S.%s%z"
CONFIGURATION = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(name)s\t%(user)s\t%(levelname)s\t[%(asctime)s]\t%(message)s',
'datefmt': ISO8601_DATETIME,
... | StarcoderdataPython |
3225713 | import discord, sqlite3, asyncio
from discord.ext import commands
from discord_slash import cog_ext, ButtonStyle
from discord_slash.utils.manage_commands import create_option
from discord_slash.utils.manage_components import *
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext... | StarcoderdataPython |
1692141 | <gh_stars>0
import json
import flask
from flask_cors import CORS
from load import load
N_TOP_USERS = 50 * 1
def load_data():
load.data()
load.fixtures()
load.top_squads(top_k=N_TOP_USERS)
load_data()
app = flask.Flask(__name__)
app.config["DEBUG"] = True
CORS(app) # This will enable CORS for all routes
... | StarcoderdataPython |
109147 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import (
CONF_COLOR_TEMPERATURE,
CONF_GAIN,
CONF_ID,
CONF_ILLUMINANCE,
CONF_GLASS_ATTENUATION_FACTOR,
CONF_INTEGRATION_TIME,
DEVICE_CLASS_ILLUMINANCE,
ICON_LI... | StarcoderdataPython |
1693678 | <filename>extract_replicons_random_gemma_runs.py
#!/usr/bin/env python3
"""
extract_replicons_random_gemma_runs.py --output <output file>
[-n (50)]
<annotated file> <combined random file>
"""
import argparse
import collections
import csv
import gzip
import itertools
parser = argparse.ArgumentParse... | StarcoderdataPython |
98496 | """
Enum with keyword-specified variants
"""
from . import NameSpace, Meta
class EnumDict(NameSpace):
"""
MetaEnum namespace with mapping for member names
A member is any non-descriptor attribute not present in object.
Skipping descriptors allows methods to be defined in Enum subclasses.
"""
d... | StarcoderdataPython |
3212356 | <gh_stars>1-10
import sys
import argparse
from tigerlib import extractor as ext
def main(samples):
for sample in samples:
print(f'[+] Extracting config for {sample}')
extractor = ext.ExtractorFactory().get_extractor(sample)
config = extractor.extract()
for ip in config.get('ip... | StarcoderdataPython |
1616812 | # -*- coding: utf-8 -*-
"""Analysis plugin to look up files in VirusTotal and tag events."""
import logging
from plaso.analysis import interface
from plaso.analysis import manager
from plaso.lib import errors
class VirusTotalAnalyzer(interface.HTTPHashAnalyzer):
"""Class that analyzes file hashes by consulting Vi... | StarcoderdataPython |
1612860 | <reponame>palbo/ccx2
# Copyright (c) 2008-2009 <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met: Redistributions of
# source code must retain the above copyright notice, this list o... | StarcoderdataPython |
1641229 |
from .base import ApiCaller, BaseApi
from .audiostation import AudioStation
class Info(ApiCaller):
def __init__(self, parent):
super(Info, self).__init__()
self.parent = parent
self.host = self.parent.host
self.verify_ssl = self.parent.verify_ssl
self.apiname = 'SYNO.API.I... | StarcoderdataPython |
101551 | <filename>Recursion/Palindrome.py
def isPalindrome(string):
if len(string) <= 1:
return True
else:
return string[0] == string[-1] and isPalindrome(string[1:-1])
userInput = input("Please enter a sequence to check if it is an palindrome: ")
answer = isPalindrome(userInput)
print("Is '" + userI... | StarcoderdataPython |
1780755 | # -*- coding: utf-8 -*-
"""
Defining a pipeline task that merges relation extracted from different tasks, e.g. participation extraction or naive
open relation extraction.
"""
# EXT
import luigi
# PROJECT
from bwg.decorators import time_function
from bwg.mixins import ArticleProcessingMixin
from bwg.serializing import... | StarcoderdataPython |
3265805 | from .unet import UNet, ModernUNet
from .utils import UpBlock, ModernUpBlock | StarcoderdataPython |
1613071 | #!/usr/bin/python
import unittest
from graphtheory.structures.edges import Edge
from graphtheory.structures.graphs import Graph
from graphtheory.chordality.peotools import find_peo_mcs
from graphtheory.chordality.tdtools import find_td_chordal
from graphtheory.chordality.tdtools import find_td_order
from graphtheory.c... | StarcoderdataPython |
1674332 | <filename>webapp/apps/account/middleware.py
import re
from django.conf import settings
from django.http import HttpResponseRedirect
from django.utils import translation
from django.utils.cache import patch_vary_headers
from django.utils.http import urlquote
from django.contrib.auth import REDIRECT_FIELD_NAME
from mo... | StarcoderdataPython |
3338132 | """一组表示燃油汽车和电动汽车的类"""
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
... | StarcoderdataPython |
1798446 | from __future__ import division, print_function, absolute_import
import unittest
from tempfile import NamedTemporaryFile
import os
import numpy as np
import deepdish as dd
from contextlib import contextmanager
class TestCore(unittest.TestCase):
def test_multi_range(self):
x0 = [(0, 0), (0, 1), (0, 2), (1,... | StarcoderdataPython |
104124 | import time
import requests
from pysmashgg.exceptions import *
# Runs queries
def run_query(query, variables, header, auto_retry):
# This helper function is necessary for TooManyRequestsErrors
def _run_query(query, variables, header, auto_retry, seconds):
json_request = {'query': query, 'variables': v... | StarcoderdataPython |
181035 | packages=[
]
| StarcoderdataPython |
3391908 | from setuptools import setup, find_packages
from pathlib import Path
version = 0.1
with Path("README.txt").open() as readme:
readme = readme.read()
setup(
name="delegato",
version=version if isinstance(version, str) else str(version),
keywords="executable",
description="delegate and then manage ... | StarcoderdataPython |
1613222 | def add(n1, n2):
"""
Add two numbers
:param n1: operand 1
:param n2: operand 2
:return: the result of adding operand 1 and operand 2
"""
print(n1 + n2)
# Try-Except-Else block
try:
number1 = 10
number2 = input("Please enter a number: ")
add(number1, number2)
except:
print(... | StarcoderdataPython |
145158 | <reponame>kamoljan/amazon-personalize-samples<filename>next_steps/operations/ml_ops/personalize-step-functions/lambdas/list-solutions/list-solutions.py
from os import environ
from loader import Loader
import actions
import json
LOADER = Loader()
def lambda_handler(event, context):
try:
response = LOADER.... | StarcoderdataPython |
34157 | from __future__ import annotations
import logging
import pathlib
from logging.handlers import TimedRotatingFileHandler
from os import getenv
from typing import Union, List, Mapping
from bundle.utils.recorder import Recorder
from bundle.utils.cache_file_helpers import CacheFolder, USER_DOCS_PATH
from bundle.seeker imp... | StarcoderdataPython |
88041 | # Exercise 13
# https://learnpythonthehardway.org/book/ex13.html
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
opinion = raw_input("What do you thin... | StarcoderdataPython |
1703943 | import inspect
from .. import interface
from . import (
bbox,
seq
)
FORMATS = {}
for module in (bbox, seq):
for attr_name in dir(module):
attr = getattr(module, attr_name)
if inspect.isclass(attr):
if issubclass(attr, interface.seq.SeqLike) or issubclass(attr, interface.bbox.B... | StarcoderdataPython |
1752736 | <reponame>unendin/allennlp
# pylint: disable=no-self-use,invalid-name,protected-access
import torch
import pytest
import numpy
from allennlp.common.testing import AllenNlpTestCase
from allennlp.common.checks import ConfigurationError
from allennlp.training.metrics import F1Measure
class F1MeasureTest(AllenNlpTestCas... | StarcoderdataPython |
4836561 | from solutions.a0131palindromepartitioning import Solution
solution = Solution()
def test_partition1():
s = "aab"
expect = [
["aa", "b"],
["a", "a", "b"]
]
actual = solution.partition(s)
assert sorted(actual) == sorted(expect)
def test_partition2():
s = ""
expect = [
]
actual = solution.p... | StarcoderdataPython |
198936 | <gh_stars>0
from django.contrib import admin
from .models import Projects
admin.site.site_header = "Portfolio Admin"
@admin.register(Projects)
class AuthorAdmin(admin.ModelAdmin):
list_display = ['title', 'description']
list_filter = ['title']
| StarcoderdataPython |
3346452 | <filename>brokenChains/models.py<gh_stars>1-10
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from rest_framework.authtoken.models import Token... | StarcoderdataPython |
1643375 | <reponame>Hansybx/guohe3
"""
-*- coding: utf-8 -*-
Time : 2019/7/19 9:55
Author : Hansybx
"""
from flask import request, jsonify
from app.api.v1.stu import stu
from app.models.error import AuthFailed, PasswordFailed
from app.models.res import Res
from app.utils.score.score_utils import get_score, grade_point_av... | StarcoderdataPython |
3223406 | <gh_stars>0
from datetime import datetime
import json
import logging
import uuid
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseServerError
from django.shortcuts import render
from django.templat... | StarcoderdataPython |
85706 | <reponame>yakutovicha/aiida-core
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | StarcoderdataPython |
3390290 | # Copyright 2015, Ericsson AB
#
# 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 |
3282265 | <filename>cv_read_video.py<gh_stars>0
# -*- coding:utf-8 -*-
__author__ = 'shichao'
import cv2
def display_from_file(path):
cap = cv2.VideoCapture(path)
while(1):
# get a frame
ret, frame = cap.read()
# show a frame
if ret:
cv2.imshow("capture", frame)
... | StarcoderdataPython |
1666972 | <gh_stars>1-10
a=int(input("Enter the first angle in degree "))
b=int(input("Enter the second angle in degree "))
c=180-(a+b)
print("The third angle is ",c)
| StarcoderdataPython |
64417 | import wandb
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from collections import OrderedDict
from transformers import BertModel
from torchmeta.modules import MetaModule, MetaSequential, MetaLinear
from torchmeta.utils.gradient_based import gradient_update_parameters
from .... | StarcoderdataPython |
1683917 | import argparse
import os
import torch
from compressai.models import MeanScaleHyperprior
from compressai.zoo.pretrained import load_pretrained
from torchdistill.common import yaml_util
from torchdistill.common.main_util import load_ckpt
from torchdistill.common.module_util import count_params
from torchdistill.models.... | StarcoderdataPython |
3200227 | <filename>tests/test_main.py<gh_stars>1-10
import flask
import main
def test_json_data_iris():
main.app.config['TESTING'] = True
client = main.app.test_client()
with main.app.app_context():
response = client.get('/data/iris.data')
result = flask.json.loads(response.data)
assert le... | StarcoderdataPython |
1737021 | import pyvista as pv
import pickle
# THIS SCRIPT IS USED TO CREATE ANIMATIONS
path = '/Users/brandelt/Dropbox/EDUCATION/Imperial College/MScAI/010 Software Project/main_repository/deepl_brain_surfaces/experiment_data/aligned_inflated_50_-2'
with open(path + f'/data_validation1.pkl', 'rb') as file:
data, label... | StarcoderdataPython |
3239617 | <filename>setup.py
# MIT License
#
# Copyright (c) 2018 Republic Wireless
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to u... | StarcoderdataPython |
3384304 | from typing import Optional
from copy import deepcopy
from .backend import keras
from .backend import backend as K
from .custom_grads import CustomReLU
__all__ = ['replace_layers', 'replace_relu']
def replace_layers(model: keras.models.Model,
layer_mapping: Optional[dict] = None,
... | StarcoderdataPython |
145986 | from HartreeParticleDSL.HartreeParticleDSLExceptions import RepeatedNameError, \
InvalidNameError
import HartreeParticleDSL.HartreeParticleDSL as HartreeParticleDSL
class variable_access():
'''
A class to handle variable accesses. Used whenever variab... | StarcoderdataPython |
87348 | import torch
import pytest
import kornia.augmentation as K
class TestVideoSequential:
@pytest.mark.parametrize('shape', [(3, 4), (2, 3, 4), (2, 3, 5, 6), (2, 3, 4, 5, 6, 7)])
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_exception(self, shape, data_format, device, dtype):
... | StarcoderdataPython |
1767677 | <gh_stars>0
#-- monitor.py
""" test monitor script
"""
### logging / color
from powertools import AutoLogger
log = AutoLogger()
log.remove_all()
log.add_stdout()
from powertools import term
term.init_color()
log.print(' ', term.pink('----'), ' ', term.yellow('ripsaw monitor'), ' ', term.pink('----'))
### imports... | StarcoderdataPython |
121876 | <filename>skiing-huabei/page_get/basic.py<gh_stars>0
import os
import time
import signal
import requests
from config import headers
from utils import (send_email, getip)
from decorators import (timeout_decorator, timeout)
from config import (get_timeout, get_crawl_interval, get_excp_interval, get_max_retries)
from logg... | StarcoderdataPython |
57343 | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def log_loss(x, y, eps=1e-6):
x = np.clip(x, eps, 1-eps)
return -(y*np.log(x) + (1-y)*np.log(1-x)) | StarcoderdataPython |
4840823 | <filename>CeV - Gustavo Guanabara/exerc063.py
# sequencia de fibonacci
print("seuqencia de fibonacci")
'''
a b a+b
1 1 1 2
2 1 2 3
3 2 3 5
4 3 5 8
5 5 8 13
'''
'''n = int(input("N:"))
fb1, fb2 = 1, 1
cont = 1
while cont <= n - 2:
fb1, fb2 = fb2, fb1 + fb2
... | StarcoderdataPython |
3338876 | # Wireless network
WIFI_SSID = "<YOUR_WIFI_SSID>"
WIFI_PASS = "<<PASSWORD>_WIFI_PASSWORD>"
# MQTT serer's configuration
MQTT_SERVER = "<YOUR_MQTT_SERVER_IP"
MQTT_PORT = 0
MQTT_USER = "<MQTT_USER_NAME"
MQTT_KEY = "<MQTT_PASSWORD>"
MQTT_CLIENT_ID = "id-1223" # Can be anything start with id-
MQTT_TEMPERATURE_FEED = "de... | StarcoderdataPython |
1723103 | from PySide2.Qt3DExtras import (Qt3DExtras)
from PySide2.QtGui import QColor
from component.Component import Component
from component.ComponentProperty import ComponentProperty
from component.ComponentType import ComponentType
class PhongMaterial(Component):
def __init__(self):
super(PhongMat... | StarcoderdataPython |
3273550 | <reponame>perezja/routines
import logging
from WDL import values_to_json
from WDL.runtime.task import run_local_task, _eval_task_inputs, InputStdLib
from WDL.runtime import task_container
from utils import unmarshall_task, unmarshall_input, load_config
from cluster import app
def _eval_command(logger, cfg, task,... | StarcoderdataPython |
192762 | """
jupylet/lru.py
Copyright (c) 2020, <NAME> - <EMAIL>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of ... | StarcoderdataPython |
1787159 | from _utility import *
def meta_insertconquerablestation(station_data):
insertcount = 0
for key,value in station_data.iteritems():
try:
solarSystemID = value['system_id']
stationID = value['id']
x = value['x']
y = value['y']
z = value['z']
... | StarcoderdataPython |
105590 | <reponame>prosper-20/Restaurant<gh_stars>0
from django.urls import path
from .views import (
Index,
About,
Order,
Test_Order,
OrderConfirmation,
OrderPayConfirmation,
home_page)
from . import views
urlpatterns = [
path('', views.home_page, name='index'),
path('about/', About.as_vie... | StarcoderdataPython |
3232888 | <filename>cli/cli/handlers/root.py<gh_stars>10-100
import sys
from winnow.pipeline.pipeline_context import PipelineContext
from winnow.pipeline.progress_monitor import ProgressBar
from winnow.utils.config import resolve_config
from .database import DatabaseCli
from .db_getter import DBGetterCli
from .errors import han... | StarcoderdataPython |
46182 | <filename>losses/msloss.py<gh_stars>1-10
# Copyright (c) Malong Technologies Co., Ltd.
# All rights reserved.
#
# Contact: <EMAIL>
#
# This source code is licensed under the LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
class LossFunction(n... | StarcoderdataPython |
169130 | <reponame>guillefix/mt-lightning<gh_stars>10-100
# encoding: utf-8
"""
This module contains an implementation of Conditional Random Fields (CRFs)
"""
# pylint: disable=no-member
# pylint: disable=invalid-name
import numpy as np
from ..processors import Processor
class ConditionalRandomField(Processor):
"""
I... | StarcoderdataPython |
1706244 | from unittest import TestCase
from prometheus_client.registry import CollectorRegistry
from app.prom.metrics.general.redo import Redo, COUNT
from tests.helpers import setUpApp, with_context
class TestRedo(TestCase):
def setUp(self):
setUpApp(self)
@with_context
def test_should_collect(self):
... | StarcoderdataPython |
3266921 | <gh_stars>1-10
import logging
import os
from .db import Database, News # isort:skip
from .rss_source import RSSSource # isort:skip
from .url_shortener import BitlyShortifier, GooglShortifier, URLShortifier # isort:skip
from .bot import RSSBot # isort:skip
if os.environ.get('APP_ENV') in ('staging', 'develop'):
... | StarcoderdataPython |
3211996 | <filename>hours.py<gh_stars>0
#Program to find days
years=eval(input("Enter number of years "))
days=years*365
hours=days*24
minutes=hours*60
sec=minutes*60
print("In",years,"years there are ",days,"days ",hours,"hours ",minutes,"minutes and ",sec,"seconds")
| StarcoderdataPython |
108764 | from pyradioconfig.parts.bobcat.calculators.calc_aox import Calc_AoX_Bobcat
class calc_aox_viper(Calc_AoX_Bobcat):
pass
| StarcoderdataPython |
173 | primeiro = int(input('Digite o priemiro termo da PA: '))
razão = int(input('Digite a razão da PA: '))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total += mais
while cont <= total:
print(f'{termo} ', end='')
termo += razão
cont += 1
print('Pausa')
mais = int(in... | StarcoderdataPython |
28769 | <gh_stars>0
import logging
from typing import Dict, Union, Optional, Any
from ..models.presets import get_preset_models
from .abstract_trainer import AbstractForecastingTrainer, TimeSeriesDataFrame
logger = logging.getLogger(__name__)
class AutoForecastingTrainer(AbstractForecastingTrainer):
def construct_model... | StarcoderdataPython |
3290279 | import json
import discord
import requests
import datetime
from colorama import Fore, init
from discord.ext import tasks
token = 'TOKEN'
init(autoreset=True)
client = discord.Client()
@tasks.loop(hours=5)
async def updateList():
contents = requests.get(
"https://raw.githubusercontent.com/nikolaischunk/d... | StarcoderdataPython |
3356780 | #! /usr/bin/env python
# coding=utf-8
"""Accelerator API setup script
run "./setup.py --help-commands" for help.
"""
from datetime import datetime
from os import chdir, environ
from os.path import dirname, abspath, join
from sys import argv
from setuptools import setup, find_packages
# Sets Package information
PACK... | StarcoderdataPython |
3272218 | <filename>createSchema.py
import json
import csvsearch
def createschema():
# get json from googleDoc
project = json.load(open("results.json"))
# load the blank schema
skeleton = json.load(open("claimSchema.json"))
# define what a requirement looks like
requirement = {
"$id": "/proper... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.