id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
5156797 | """
j2lsnek, a python-based list server for Jazz Jackrabbit 2
By Stijn (https://stijn.chat)
Thanks to DJazz for a reference implementation and zepect for some misc tips.
"""
import urllib.request
import urllib.error
import subprocess
import importlib
import logging
import sqlite3
import socket
import json
import time... | StarcoderdataPython |
101011 | <filename>lab_exercise_05/lab_exercise_05_solution.py
# LAB EXERCISE 05
print('Lab Exercise 05 \n')
# SETUP
pop_tv_shows = [
{"Title": "WandaVision", "Creator": ["<NAME>"], "Rating": 8.2, "Genre": "Action"},
{"Title": "Attack on Titan", "Creator": ["<NAME>"], "Rating": 8.9, "Genre": "Animation"},
{"Title":... | StarcoderdataPython |
6649485 | from numpy import arange, setdiff1d
from numpy.random import choice
class batchSampler:
def __init__(self, indices, train_keys, bsize, shuffle = False):
self.indices = indices
self.train_keys = train_keys
self.bsize = bsize
self.shuffle = shuffle
def __iter__(self):
... | StarcoderdataPython |
6457364 | from sys import executable
from subprocess import check_output, CalledProcessError
from os import listdir
def run_script(script_path, input_str):
file_ext = script_path.suffix
script_runner = script_types.get(file_ext, None)
if script_runner is None:
raise ValueError('Not a valid filetype: ' + '"'... | StarcoderdataPython |
4820427 | # -*- coding: utf-8 -*-
# @Time : 2019/3/30 9:57 PM
# @Author : 章光辉
# @FileName: amap.py
# @Software: PyCharm
from multiprocessing import Manager
from multiprocessing.pool import ThreadPool
from time import sleep
import logging
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry impo... | StarcoderdataPython |
11227797 | # RUN: %PYTHON %s | npcomp-opt -split-input-file -npcomp-cpa-type-inference -canonicalize | FileCheck %s --dump-input=fail
import numpy as np
from npcomp.compiler import test_config
from npcomp.compiler.frontend import EmittedError
import_global = test_config.create_import_dump_decorator()
global_data = (np.zeros((2... | StarcoderdataPython |
9702711 |
import os
import imageList
from PythonCard import util
# this is just a copy and paste of the list in samples.rsrc.py
# and should be updated as new samples are added
SAMPLES = ['addresses', 'chat', 'companies', 'conversions', 'custdb', 'dbBrowser', \
'dialogs', 'doodle', 'flatfileDatabase', 'gadflyData... | StarcoderdataPython |
117183 | """
This code is taken from PyPi stream_service package
https://github.com/BR1py/stream_service
We publish here all the relevant classes for Users
"""
from __future__ import absolute_import
from .server import StreamChannelServer_Process
from .client import StreamChannelClient_Thread
from .lib import *
from .lib.frame... | StarcoderdataPython |
6496745 | <filename>Validation/HGCalValidation/scripts/makeHGCalValidationPlots.py<gh_stars>1-10
#!/usr/bin/env python
from __future__ import print_function
import os
import argparse
from Validation.RecoTrack.plotting.validation import SimpleValidation, SimpleSample
import Validation.HGCalValidation.hgcalPlots as hgcalPlots
im... | StarcoderdataPython |
8150508 | <gh_stars>0
from wasol import logger
from wasol import core
from wasol import daemon | StarcoderdataPython |
3342250 | try:
from zcrmsdk.src.com.zoho.crm.api.exception import SDKException
from zcrmsdk.src.com.zoho.crm.api.util import Constants
except Exception:
from ..exception import SDKException
from ..util import Constants
class Options(object):
def __init__(self):
"""Creates an instance of Options"""
pass
| StarcoderdataPython |
3264832 | <filename>py/storage.py
class A(object):
def __init__(self, name):
self.name = name
print '%s is inited' % self.name
def __del__(self):
print '%s is killed' % self.name
a = A('A')
b = A('B')
c = A('C')
b.x = c
c.x = b
| StarcoderdataPython |
3589577 | <reponame>yuyasugano/jpyc-rinkeby<filename>tests/test_approve.py
#!/usr/bin/python3
import pytest
@pytest.mark.parametrize("idx", range(5))
def test_initial_approval_is_zero(token, accounts, idx):
assert token.allowance(accounts[0], accounts[idx]) == 0
def test_approve(token, accounts):
amount = 1000 * 1e18
... | StarcoderdataPython |
8060007 | # https://codeforces.com/problemset/problem/977/B
n = int(input())
s = input()
d = {}
for i in range(n-1):
two_gram = f"{s[i]}{s[i+1]}"
if two_gram in d:
d[two_gram] += 1
else:
d[two_gram] = 1
print(max(d, key=d.get)) | StarcoderdataPython |
337777 | <gh_stars>0
'''
Created on Oct 28, 2021
@author: mballance
'''
import os
import jinja2
class TemplateLoader(jinja2.BaseLoader):
def get_source(self, environment, template):
path = template
if not os.path.exists(path):
raise jinja2.TemplateNotFound(template)
mtime = os.pat... | StarcoderdataPython |
262839 | # Copyright 2017 Suomi Corporation
#
# 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 wri... | StarcoderdataPython |
5073537 | # Add a floor below a sphere and plot it.
#
import pyvista
pl = pyvista.Plotter()
actor = pl.add_mesh(pyvista.Sphere())
actor = pl.add_floor()
pl.show()
| StarcoderdataPython |
6594346 | <filename>code/BOBO_hypterparameter_search.py<gh_stars>0
from argparse import Namespace
from psycopg2.extensions import connection
import torch
from torch import nn
import numpy as np
import ax
from ax.plot.contour import plot_contour
from ax.plot.trace import optimization_trace_single_method
from ax.service.managed_... | StarcoderdataPython |
6521577 | <reponame>Siddhant021295/Gesture-Recognation-IPN-Hands<filename>Googleopts.py
import argparse
def parse_opts():
# Offline means not real time
parser = argparse.ArgumentParser()
parser.add_argument('--root_path',default='',type=str,help='Root directory path of data')
parser.add_argument('--video_path'... | StarcoderdataPython |
1862916 | <filename>PyPoll/main.py
import os
import csv
csvpath = os.path.join("PyPoll.csv")
# Create lists and variables
candidates = []
total_votes = 0
candidate_votes = []
election_data = ['1', '2']
# Open CSV
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
... | StarcoderdataPython |
396610 | <reponame>heijp06/AoC-2021
def part1(rows):
return go(rows, 1)
def part2(rows):
return go(rows, 2)
def go(rows, part):
position = 0
depth = 0
aim = 0
for row in rows:
command, arg = row.split()
match command, int(arg):
case "forward", value:
positi... | StarcoderdataPython |
6422071 | import matplotlib.pyplot as plt
import numpy as np
class Visualizer:
def __init__(self):
print("Opening visualizer")
def plotPlane(self, X, Y, plane):
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, plane,
cmap=plt.cm.coolwarm,
... | StarcoderdataPython |
11289624 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2017-05-02 18:41
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hives', '0028_inspectionbox_inspection'),
]
operations = [
migrations.RemoveField(
... | StarcoderdataPython |
6439671 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-0015-3Sum.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-01-16
==============================================... | StarcoderdataPython |
9682911 | <reponame>SankarST/RepoOpenAcadTraining<gh_stars>0
# -*- coding: utf-8 -*-
from datetime import timedelta
from odoo import fields, models ,api ,exceptions
class Course(models.Model):
_name = 'oa.course'
_description = 'Course OA'
name = fields.Char(string='Title', required=True)
description = fields.... | StarcoderdataPython |
3203714 | <reponame>dgerod/ariac-2018_gear
#!/usr/bin/env python
from __future__ import print_function
import sys
import time
from test_example_node import ExampleNodeTester
from ariac_example import ariac_example
import rospy
import rostest
class GripperTester(ExampleNodeTester):
def test(self):
self.comp_clas... | StarcoderdataPython |
6500769 | <reponame>mightymercado/PythonPosit
from numpy import exp, array, random, dot
class NeuralNetwork():
def __init__(self):
# Seed the random number generator, so it generates the same numbers
# every time the program runs.
random.seed(1)
# We model a single neuron, with 3 input conn... | StarcoderdataPython |
4977546 | <reponame>beaupreda/cnn-rgbir<filename>stereo/testing.py<gh_stars>1-10
'''
script used to execute multiple runs of testing
simply calls corresponding lua script with chosen arguments
David-<NAME>
'''
import os
import subprocess
from utils import InputParser, YamlReader
def prepare_test(gpu_id=None,
... | StarcoderdataPython |
67721 | <reponame>itzmeanjan/tgnize<gh_stars>1-10
#!/usr/bin/python3
from __future__ import annotations
from typing import List, Tuple
from functools import reduce
from subprocess import run
from sys import argv
from os import mkdir
from os.path import abspath, exists, join
from datetime import timedelta
from .util import par... | StarcoderdataPython |
8121095 | <reponame>stefantaubert/tts-preparation
import shutil
from logging import getLogger
from pathlib import Path
from typing import List, Set, Tuple
from speech_dataset_preprocessing import load_final_ds
from speech_dataset_preprocessing import FinalDsEntryList
from text_utils import SpeakersDict
from text_utils.types imp... | StarcoderdataPython |
6464990 | # BUG: RangeIndex.where throws AssertionError #43240
import numpy as np
import pandas as pd
print(pd.__version__)
idx = pd.RangeIndex(0, 5)
v = np.array([False, False, True, True, True])
result = idx.where(v, 10)
print(result)
expected = pd.Index([10, 10, 2, 3, 4], dtype="int64")
pd.testing.assert_index_equal(re... | StarcoderdataPython |
12813597 | # Copyright 2022 <NAME>
# See LICENSE file for licensing details.
#
# Learn more about testing at: https://juju.is/docs/sdk/testing
import unittest
from ops.model import ActiveStatus, MaintenanceStatus
from ops.testing import Harness
from charm import DeferWithDispatchCharm
class TestCharm(unittest.TestCase):
... | StarcoderdataPython |
9676722 | import requests
import time
from dotenv import load_dotenv
import os
load_dotenv() # loads .env
PASTERY_API_KEY = os.getenv("PASTERY_API_KEY")
# POST https://www.pastery.net/api/paste/
# ?api_key=<api_key>
# &duration=<duration>
# &title=<title>
# &language=<language>
# &max_views=<max_views>
#... | StarcoderdataPython |
3261830 | """Verify that instantiation and operation of the CNN/CLDNN do not crash.
.. note::
This doesn't actually check if the attack "works" because "works" is pretty
subjective (what "adversarial success" is "good"?). Therefore, whether it "works"
is better left to human analysis of experiment outputs but this... | StarcoderdataPython |
8030016 | import matplotlib.pyplot as plt
#from kneed import KneeLocator
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
import numpy as np
import pandas as pd
enc_df = pd.read_csv("enc_tok.csv", header=0,name... | StarcoderdataPython |
12819154 | <reponame>project-origin/example-backend<gh_stars>0
"""
Asynchronous tasks for refreshing access tokens which
are close to expiring.
"""
from datetime import datetime, timezone
from celery import group
from originexample import logger
from originexample.db import inject_session, atomic
from originexample.auth import U... | StarcoderdataPython |
8077325 | # Problem: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem
# Score: 10
| StarcoderdataPython |
4841041 | <filename>tests/entities/test_arxiv_document.py<gh_stars>10-100
"""Tests the arxiv model
"""
import uuid
from webminer.entities import arxiv_document as ad
test_url = "https://arxiv.org/abs/1801.06605"
test_title = "A Collaborative Filtering Recommender System"
test_abstract = "The use of relevant metrics of software... | StarcoderdataPython |
1676459 | import sys
from django.shortcuts import render
from PIL import Image, ImageFilter
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def handle_image(request):
try:
im = Image.open(request)
im = i... | StarcoderdataPython |
5184820 | from django.contrib import admin
from boating.models import HirePoint, OpeningTimes, Boat, Booking
class OpeningTimesInline(admin.TabularInline):
model = OpeningTimes
extra = 0
class HirePointBoatInline(admin.TabularInline):
model = Boat
extra = 0
class HirePointAdmin(admin.ModelAdmin):
model... | StarcoderdataPython |
4968013 | import discord
import io
import textwrap
import traceback
from contextlib import redirect_stdout
from discord.ext import commands
import datetime
class Owner(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self._last_result = None
self.owner = bot.get_us... | StarcoderdataPython |
1993458 | <reponame>igapon50/training
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# @file const.py
# @version 1.0.0
# @author <NAME>(HN:igapon)
# @date 2021/04/26
# @brief 共通な定数を定義する
# @details 共通な定数を定義する
# @warning
# @note
__author__ = "<NAME>(HN:igapon)"
__copyright__ = "Copyright (c) 2021 igapon"
__credits__ = ["<NAME... | StarcoderdataPython |
3555641 | <reponame>2z1c/Community-document
'''
File: Photoresistor.py
Project: adc
File Created: Thursday, 24th December 2020 5:44:08 pm
Author: chengzhu.zhou
-----
Last Modified: Wednesday, 30th December 2020 10:10:33 am
Modified By: chengzhu.zhou
-----
Copyright 2020 - 2020 quectel
'''
from misc import ADC
imp... | StarcoderdataPython |
32486 | <filename>cheatsheets/py/pyython.6a.keras.py
from keras.datasets import imdb
top_words = 10000
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=top_words)
#imdb.get_word_index()
word_dict = imdb.get_word_index()
word_dict = { key:(value + 3) for key, value in word_dict.items() }
word_dict[''] = 0 # Pad... | StarcoderdataPython |
3578230 | from typing import Dict, Union
from news_scraper import config, ProjectVariables
from functools import wraps
from news_scraper.enums.site import Site
logging = ProjectVariables.root_logger
def accepts_dict(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if isinstance(args[1], dict):
retur... | StarcoderdataPython |
1899993 | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Unit-e developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the RPC call related to the runstringcommand command.
Test corresponds to code in rpc/misc.cpp.
"""
fr... | StarcoderdataPython |
1755042 | <reponame>cdeck3r/3DScanner<filename>src/homie-nodes/homie-apparatus/node_recentimages.py<gh_stars>1-10
import base64
import datetime
import hashlib
import json
import logging
import os
import pathlib
import re
import shutil
import subprocess
import tempfile
import time
from homie.node.node_base import Node_Base
from ... | StarcoderdataPython |
6505745 | <reponame>Savasw/ansible-provider
#!/usr/bin/python
# Copyright (c) 2017 Alibaba Group Holding Limited. <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it ... | StarcoderdataPython |
8025203 | <reponame>Ricardo191998/sistop-2020-1<filename>tareas/2/RomeroCristian_LopezUlysses/main.py
#!/usr/bin/python3
# -*-coding: utf-8 -*-x
from procesos.Proceso import Proceso
from procesos.Spn import Spn
from procesos.RRobin import RRobin
from procesos.Fcfs import Fcfs
def main():
procesos = list()
for _ in ran... | StarcoderdataPython |
8149428 | from Format import NewFormat
from AbsentError import AbsentError
import psycopg2
class database:
def __init__(self):
self.conn = psycopg2.connect(
host="localhost",
database="postgres",
user="root",
password="<PASSWORD>"
)
self.conn.autocommi... | StarcoderdataPython |
110849 |
class LCRecommendation:
TURN_LEFT = -1
TURN_RIGHT = 1
STRAIGHT_AHEAD = 0
CHANGE_TO_EITHER_WAY = 2
change_lane = True
change_to_either_way = False
recommendation = 0
def __init__(self, lane, recommendation):
self.lane = lane
self.recommendation = recommendation
... | StarcoderdataPython |
3293025 | import xadmin
from enterprise_manage.apps.user_center.models import *
class UserProfileAdmin(object):
list_display = ['id', 'name', 'to_user', 'mobile_phone', 'email', 'wechat', 'qq']
list_editable = ['id', 'name', 'to_user', 'mobile_phone', 'email', 'wechat', 'qq', 'leader']
xadmin.site.register(UserProfil... | StarcoderdataPython |
5092689 | import json
import boto3
from botocore.exceptions import ClientError
import urllib3
region = 'us-east-1'
def lambda_handler(event, context):
try:
dictionary={}
service=0
ec2 = boto3.client('ec2', region_name=region)
ec2_response = ec2.describe_instances()
instances_full_deta... | StarcoderdataPython |
6486108 | <filename>src/hub/management/commands/categorize-hubs.py
from django.core.management.base import BaseCommand
from hub.models import Hub, HubCategory
class Command(BaseCommand):
def update_hub_category(self, hub_name, category_name):
"""
Updates the category of a hub.
Parameters:
... | StarcoderdataPython |
1937254 | #!/usr/bin/env python
"""End to end tests that run ArtifactCollectorFlow."""
from grr.endtoend_tests import base
from grr.lib import aff4
from grr.lib import rdfvalue
class TestDarwinPersistenceMechanisms(base.AutomatedTest):
"""Test DarwinPersistenceMechanisms."""
platforms = ["Darwin"]
flow = "ArtifactColl... | StarcoderdataPython |
178142 | <reponame>Linekio/bin<gh_stars>0
import pygments
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
class TableHtmlFormatter(HtmlFormatter):
def __init__(self, **options):
super().__init__(**options)
if options.get('linenos', False) == 'bin-table':
... | StarcoderdataPython |
3555236 | <reponame>guilhermeleobas/rbc
"""https://en.cppreference.com/w/c/numeric/math
"""
from collections import namedtuple
from . import make_intrinsic
arg = namedtuple("arg", ("name", "ty"))
cmath = {
# Trigonometric
"cos": ("double", [arg(name="x", ty="double")]),
"cosf": ("float", [arg(name="x", ty="float"... | StarcoderdataPython |
1857500 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-11 15:58
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
mi... | StarcoderdataPython |
12846275 | import datetime
from mangrove.datastore.database import get_db_manager,\
_delete_db_and_remove_db_manager
from mangrove.bootstrap.initializer import _find_views
from pytz import UTC
import random
from mangrove.datastore.entity import Entity
from collections import defaultdict
class ViewGenerationTimer(object):
... | StarcoderdataPython |
3368645 | from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as plticker
def plot_image(value_fn):
# Values over all initial dealer scores and player scores
# Given the policy, the value should be near zero everywhere except when the player has a score of... | StarcoderdataPython |
6662628 | import numpy as np
import random
from openrec.tf1.utils.samplers import Sampler
def YouTubeSampler(dataset, batch_size, max_seq_len, user_feature, num_process=5, seed=100, sort=True):
random.seed(seed)
def batch(dataset, user_feature=user_feature, max_seq_len=max_seq_len, batch_size=batch_size):
... | StarcoderdataPython |
3253655 | <gh_stars>0
# Copyright 2015 <NAME>.
# 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... | StarcoderdataPython |
3347595 | n, y = map(int, input().split())
l = set([int(input()) for i in range(y)])
for i in range(n):
if i not in l:
print(i)
print(f"Mario got {len(l)} of the dangerous obstacles.")
| StarcoderdataPython |
5148936 | <gh_stars>1-10
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License")... | StarcoderdataPython |
1930905 | <gh_stars>1-10
from . import core # noqa
from . import sql_lab # noqa
from . import user_attributes # noqa
| StarcoderdataPython |
86913 | """Algo class definition."""
import os
import sys
import logging
import argparse
import pandas as pd
from datetime import datetime
from aqtlib import utils, Broker, Porter
from aqtlib.objects import DataStore
from abc import abstractmethod
from .instrument import Instrument
__all__ = ['Algo']
class Algo(Broker):
... | StarcoderdataPython |
306768 | #!/usr/bin/env python3
#
# Copyright 2021 Graviti. Licensed under MIT License.
#
import pytest
from tensorbay import GAS
from tensorbay.dataset import Data, Dataset, Frame, FusionDataset, FusionSegment, Segment
from tensorbay.exception import ResourceNotExistError
from tensorbay.label import Catalog, Classification, ... | StarcoderdataPython |
12803222 | import json
from project.models.models import Question, Answer
from project.users.views import auth_decode
from . import BaseTest
class TestQuestions(BaseTest):
def test_get_questions(self):
res = self.client().get('/api/v1/questions', content_type='application/json', headers=dict(token=self.login()))
... | StarcoderdataPython |
8121452 | """
helper module for finding installed device types
Author: <NAME>
Date: March 2018
Contact: <EMAIL>
"""
import os
import re
import json
from tiflash.utils import xmlhelper
from tiflash.utils.connections import get_connections_directory
from tiflash.utils.cpus import get_cpus_directory
DEVICES_DIR = "/ccs_base/... | StarcoderdataPython |
8127753 | import re
from pathlib import Path
from typing import List
from setuptools import find_namespace_packages, setup
def get_version(package: str) -> str:
"""
Extract package version, located in the `src/package/__version__.py`.
"""
version = Path("src", package, "__version__.py").read_text()
pattern... | StarcoderdataPython |
3299662 | from unittest import TestCase
from regene.expression.string import String, EmptyExpression
class StringTest(TestCase):
def test_string_multiplication(self):
assert String("F") * 4 == "FFFF"
class EmptyTest(TestCase):
def test_empty_multiplication(self):
assert EmptyExpression() == ""
| StarcoderdataPython |
6664995 | <gh_stars>1-10
"""A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] ... | StarcoderdataPython |
1850545 | import urllib.request
import re
import os.path
import http
import time
import logging
import timeit
import configparser
from datetime import datetime
# Установка папки со скриптом
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Путь к файлу настроек settings.ini
SETTINGS = os.path.join(BASE_DIR, "settings.ini... | StarcoderdataPython |
357898 | import warnings
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from ALDmodel import ALDGrowth
from core import plot_2d, plot_uq
from functools import partial
from scipy.stats import halfcauchy, triang
from scipy.interpolate import interp1d
from sopt import sbost... | StarcoderdataPython |
6631988 | # from . import readfile # 先在init里导入一下模块,先初始化一下,然后,包之外的另外一个文件就可以使用from 包 imoprt *来调用了
# from . import writefile
# __init__
# 1、声明文件夹是个包
# 2、可以做初始化操作
# 3、可以声明__all__影响 from 包 import *导入,在__all__里写的才会导入
# 当然这个init文件也可以想其他普通模块文件内一样,可以使用__all__ = ['readfile']这样的方式来确认模块里的哪些方法可以使用
# 这种是为了解决其他模块文件里用from changefile import ... | StarcoderdataPython |
8187222 | from . import member_bp
from app.models import *
from .models_members import *
from flask import jsonify, request
from sqlalchemy import and_
from sqlalchemy import or_
import json
from datetime import datetime
from lib.decorators import json
from lib.email1 import send_email2
@member_bp.route('/add_update_member_inf... | StarcoderdataPython |
373633 | from django.core.management.base import BaseCommand
from oxlos.newsletter.mail import send_newsletters
class Command(BaseCommand):
help = "Send newsletters."
def add_arguments(self, parser):
parser.add_argument(
"--dry-run",
action="store_true",
dest="dry_run",
... | StarcoderdataPython |
3305355 | <reponame>vyahello/quotes
"""ASGI config for manager project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from django.c... | StarcoderdataPython |
3337365 | import os
import sys
import argparse
import importlib
import numpy as np
import tensorflow as tf
import pdb
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '..'))
sys.path.append(os.path.join(BASE_DIR, '../utils'))
import provider
import provider_ri... | StarcoderdataPython |
3431074 | <reponame>wanchaosoft/commontools
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
__project__ = 'commontools'
__author__ = 'wanchao'
__create_time__ = '2017/12/11 16:42'
"""
from datetime import datetime
import os
import sys
NOW = None
def print_time(msg=None):
"""打印时间"""
global NOW
if not NOW:
... | StarcoderdataPython |
9781835 | import pickle
import queue
import time
from pathlib import Path
import numpy as np
from analysis_util import get_numpy_array, BaseFeatureHelper, \
get_sample_feature_value
from util.constants import NEWS_ROOT_NODE, RETWEET_EDGE, REPLY_EDGE, RETWEET_NODE, REPLY_NODE
from util.util import tweet_node
def get_post_... | StarcoderdataPython |
327951 | <filename>src/collective/solr/tests/test_contentlisting.py
from unittest import TestCase
from plone.app.contentlisting.interfaces import IContentListingObject
from plone.uuid.interfaces import IUUID
from zope.interface.verify import verifyClass
from collective.solr.contentlisting import FlareContentListingObject
from... | StarcoderdataPython |
3496046 | from flask import Blueprint
bp = Blueprint('git_class', __name__)
from app.giturl_class import routes
| StarcoderdataPython |
8075238 | import random
'''
Random file mixer
This small piece of code mixes lines randomly from a given file.
It's important to have random dataset to train your machine learning algorithm.
But mostly the data comes from structured sources so that it is may not be random.
It reads data from a file named dataset.csv and print... | StarcoderdataPython |
3537155 | from typing import List, Optional
from typing import OrderedDict as OrderedDictType
from typing import Set, TypeVar
from text_selection.metrics_applied import get_rarity
from text_selection.utils import get_filtered_ngrams
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
def get_rarity_ngrams(data: OrderedDictType[int, Li... | StarcoderdataPython |
3430987 | from django.shortcuts import redirect, render
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
#my scripts
from .forms import CreateUserForm
import os
# Create your views here.
def registerPage(request):
if re... | StarcoderdataPython |
3276448 | #!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1237/A
def f(l):
dl = [-1,1]
ii = 0
for i in range(len(l)):
if l[i]%2>0:
l[i] += dl[ii]
ii = (ii+1)%2
l[i] = l[i]//2
return l
n = int(input())
l = [int(input()) for _ in range(n)]
[print(r) ... | StarcoderdataPython |
8077037 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Kilt Troll """
import time
class KilnTrol(object):
""" KilnTrol Kiln Controller """
def __init__(self, temperature, heater, clock, target_profile, logger, tick_interval=5):
self.temperature = temperature
self.heater = heater
... | StarcoderdataPython |
2173 | <gh_stars>1000+
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import fnmatch
from io import StringIO
import json
import os
import shutil
import zipfile
import re
from datetime import datetime, timedelta, tzinfo
from distutils.util import strtobool
import boto3
import placebo
from botoc... | StarcoderdataPython |
3558012 | """Module wrapping the Client of Jina."""
import argparse
from typing import overload, Optional, Union
__all__ = ['Client']
if False:
from .base import BaseClient
from .asyncio import AsyncClient, AsyncWebSocketClient
from .grpc import GRPCClient
from .websocket import WebSocketClient
# overload_inj... | StarcoderdataPython |
1896759 | from nose.tools import istest, assert_equal
from mammoth import documents
from mammoth.docx.xmlparser import element as xml_element
from mammoth.docx.comments_xml import read_comments_xml_element
from mammoth.docx import body_xml
@istest
def id_and_body_of_comment_is_read():
body = [xml_element("w:p")]
comme... | StarcoderdataPython |
4939600 | from __future__ import annotations
import logging
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
log = logging.getLogger(__name__)
engine = create_engine(
"sqlite:///dev.db", connect_args={"check_same_thread": False}, future=T... | StarcoderdataPython |
1681943 | import unittest
from aviation_weather import Wind
from aviation_weather.exceptions import WindDecodeError
class TestWind(unittest.TestCase):
"""Unit tests for aviation_weather.components.wind.Wind"""
def _test_valid(self, raw, direction, speed, gusts, variable):
w = Wind(raw)
self.assertEqual... | StarcoderdataPython |
9791245 | # Standardize a crashes CSV into compatible JSON document.
# Author terryf82 https://github.com/terryf82
import argparse
import os
import pandas as pd
from pandas.io.json import json_normalize
import yaml
from collections import OrderedDict
import csv
import calendar
import random
import pytz
import dateutil.parser as... | StarcoderdataPython |
8067735 | <filename>reader/src/clients/python/tomerge.py<gh_stars>0
#!/usr/bin/env python
import sys
import ctypes
import time
import threading
import Queue
lib = ""
callbackList = ""
def callbackHandlerFunction(char_ptr):
callbackString = ""
try:
for i in char_ptr:
if i == "\0":
break
else:
callbackStrin... | StarcoderdataPython |
4857202 | from sales import models as m_sales
def delete_sale_docs(task, status):
from .models import STATUS_APPROVED
sale_id = int(task.reference)
sale = m_sales.Sale.objects.get(pk=sale_id)
if status == STATUS_APPROVED:
m_sales.Document.objects.filter(sale_id=sale_id).delete()
m_sales.Sale.obj... | StarcoderdataPython |
6507091 | <reponame>jyxzhang/hknweb<filename>hknweb/academics/models/logistics/__init__.py
from hknweb.academics.models.logistics.course import Course
from hknweb.academics.models.logistics.department import Department
from hknweb.academics.models.logistics.instructor import Instructor
from hknweb.academics.models.logistics.seme... | StarcoderdataPython |
11392571 | import pytest
from Registry.Registry import RegSZ
from regrippy.plugins.typedurls import Plugin as plugin
from .reg_mock import (LoggerMock, RegistryKeyMock, RegistryMock,
RegistryValueMock)
@pytest.fixture
def mock_reg():
key = RegistryKeyMock.build("Software\\Microsoft\\Internet Explore... | StarcoderdataPython |
9794417 | <gh_stars>0
class Handler(object):
context = None
resources = None
action = None
params = None
name = None
def __init__(self, context, resources, action, name, params):
self.context = context
self.resources = resources
self.action = action
self.name = name
... | StarcoderdataPython |
304070 | # SPDX-License-Identifier: MIT
# Copyright (C) 2020-2021 Mobica Limited
"""Provide error handling helpers"""
NO_ERROR = 0
CONFIGURATION_ERROR = 1
REQUEST_ERROR = 2
FILESYSTEM_ERROR = 3
INTEGRATION_ERROR = 4 # Indicates that some assumption about how the Jira works seems to be false
INVALID_ARGUMENT_ERROR = 5
INPUT_DA... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.