id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
136873 | import typing
import dataclasses as dc
from .raw_client import RawClient
T = typing.TypeVar('T')
@dc.dataclass
class ApiStorage:
_client: RawClient
_apis: typing.Dict[typing.Type[typing.Any], typing.Any] = dc.field(default_factory=dict)
def get_api(self, api_type: typing.Type[T]) -> T:
if not i... | StarcoderdataPython |
1791470 | from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'user'
urlpatterns = [
path('signup', views.signup, name='signup'),
path('sent', views.activation_sent, name='activation_sent'),
path('activate/<slug:uidb64>/<slug:token>/', views.activate, nam... | StarcoderdataPython |
1612225 | <reponame>ChaseKnowlden/airflow
# 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 ... | StarcoderdataPython |
3351299 | """ Implementation of the 'original' volume/area scaling glacier model from
Marzeion et. al. 2012, see http://www.the-cryosphere.net/6/1295/2012/.
While the mass balance model is comparable to OGGMs past mass balance model,
the 'dynamic' part does not include any ice physics but works with ares/volume
and length/volume... | StarcoderdataPython |
3366996 | <filename>src/softmax_mnist.py
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
DATA_DIR = "/tmp/data"
NUM_STEPS = 1000
MINIBATCH_SIZE = 100
data = input_data.read_data_sets(DATA_DIR, one_hot=True)
# define inputs
x = tf.placeholder(tf.float32, [None, 784])
# define weights
W = tf.... | StarcoderdataPython |
16392 | <filename>ui/main_window.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.12.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self,... | StarcoderdataPython |
3340906 | from picamera import PiCamera
from time import sleep
camera = PiCamera()
# We can adjust the Brightness and contrast of the image
camera.start_preview()
for i in range(100):
camera.annotate_text = "Brightness: %s" % i
camera.brightness = i
sleep(0.1)
camera.stop_preview()
camera.brightness = 50
camera.s... | StarcoderdataPython |
69740 | import h5py as h5
import feather
import pandas as pd
import numpy as np
import os
correlation_files = os.listdir("correlation_folder")
for i in range(0, len(correlation_files)):
print(i)
correlation = pd.read_feather("correlation_folder/"+correlation_files[i])
f = h5.File("h5/"+correlation_files[i].replac... | StarcoderdataPython |
4817502 | <reponame>bdowning/aiotools
from pprint import pprint
import asyncio
import aiotools
@aiotools.actxmgr
async def mygen(id):
yield f'mygen id is {id}'
async def run():
ctxgrp = aiotools.actxgroup(mygen(i) for i in range(10))
async with ctxgrp as values:
pprint(values)
if __name__ == '__main__':... | StarcoderdataPython |
124111 | import sys
from cx_Freeze import setup, Executable
build_exe_options = {
'includes': [
'ninfs',
'ninfs.gui',
'ninfs.mount.cci',
'ninfs.mount.cdn',
'ninfs.mount.cia',
'ninfs.mount.exefs',
'ninfs.mount.nandctr',
'ninfs.mount.nandhac',
'ninfs.mou... | StarcoderdataPython |
3276104 | # -*- coding: utf-8 -
"""Event driven concurrent framework for Python"""
from .utils.version import get_version
VERSION = (2, 0, 2, 'final', 0)
__version__ = version = get_version(VERSION)
__author__ = "<NAME>"
DEFAULT_PORT = 8060
ASYNC_TIMEOUT = None
SERVER_NAME = 'pulsar'
JAPANESE = b'\xe3\x83\x91\xe3\x83\xab\x... | StarcoderdataPython |
3266984 | import random
NUMBER_OF_TRIALS = 100000 # Constant
numberOfHits = 0
for i in range(NUMBER_OF_TRIALS):
x = random.random() * 2 - 1
y = random.random() * 2 - 1
if x * x + y * y <= 1:
numberOfHits += 1
pi = 4 * numberOfHits / NUMBER_OF_TRIALS
print("PI is", pi)
| StarcoderdataPython |
1692578 | import struct
import socket
def scannerIp(stringIp):
sock = socket.socket(socket.AF_INET)
sock.settimeout(3)
sock.connect((stringIp, 445))
packet = b'\x00\x00\x00\xc0\xfeSMB@\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00... | StarcoderdataPython |
1720742 | #! /usr/bin/env python3
import sys
import ftplib
import os
import re
import datetime
def getDirDate(inDir=''):
"""Strip the date from the cdas2 directory name.
The directory name that contains the cdas2 files has the pattern
cdas2.YYYYmmdd. This function will verify the directory contains
the correc... | StarcoderdataPython |
1752192 | <gh_stars>0
class Something :
def __init__ ( self ):
pass
def do_something(self):
print("class asdf")
def do_something_else(self):
self.do_something()
if __name__ == '__main... | StarcoderdataPython |
3389436 | <gh_stars>1-10
# -*- coding: UTF-8 -*-
#Exercício Python 28: Escreva um programa que faça o computador “pensar” em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.
from random import randi... | StarcoderdataPython |
1697424 | #!.venv/bin/python -W ignore
from libs.bunq_lib import BunqLib
from libs.share_lib import ShareLib
def main():
all_option = ShareLib.parse_all_option()
environment_type = ShareLib.determine_environment_type_from_all_option(all_option)
ShareLib.print_header()
bunq = BunqLib(environment_type)
acc... | StarcoderdataPython |
67923 | <reponame>geostk/deepSVDD<gh_stars>1-10
from datasets.base import DataLoader
from datasets.preprocessing import center_data, normalize_data, \
rescale_to_unit_interval, global_contrast_normalization, zca_whitening, \
make_unit_norm, extract_norm_and_out, learn_dictionary, pca
from utils.visualization.mosaic_plo... | StarcoderdataPython |
1633396 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class FAQConfig(AppConfig):
name = 'faq'
verbose_name = _("FAQ")
default_app_config = 'faq.FAQConfig'
| StarcoderdataPython |
1611715 | import os
import sys
import mock
import pytest
import torch
import random
# mock detection module
sys.modules['torchvision._C'] = mock.Mock()
import segmentation_models_pytorch as smp
def get_encoder():
is_travis = os.environ.get('TRAVIS', False)
exclude = ['senet154']
encoders = smp.encoders.get_enco... | StarcoderdataPython |
4841828 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as tk
import threading
#import modułów konektora msg_stream_connector
from ComssServiceDevelopment.connectors.tcp.msg_stream_connector import InputMessageConnector
#import modułu klasy testowego kontrolera usługi
from ComssServiceDevelopment.development impo... | StarcoderdataPython |
3250194 | <gh_stars>0
"""Handle cross-origin resource sharing (CORS) preflight requests. See:
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
"""
_max_age_header = str(86400 * 365)
def tween_factory(handler, registry):
def cors_tween(request):
if request.method == 'OPTIONS':
# Tell ... | StarcoderdataPython |
100100 | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import luigi
from servicecatalog_factory import aws
from servicecatalog_factory.workflow.portfolios.create_portfolio_task import (
CreatePortfolioTask,
)
from servicecatalog_factory.workfl... | StarcoderdataPython |
61508 | <filename>examples/gridworld/GridWorldUnitTests/GridFactory.py<gh_stars>1-10
import numpy as np
from examples.gridworld.Grid import Grid
from examples.gridworld.SimpleGridOne import SimpleGridOne
class GridFactory:
step = SimpleGridOne.STEP
fire = SimpleGridOne.FIRE
blck = SimpleGridOne.BLCK
goal = S... | StarcoderdataPython |
343 | #!/usr/bin/python2.7
"""
Extract unique set of station locations (and names) along with number of obs
RJHD - Exeter - October 2017
"""
# ECMWF import defaults
import traceback
import sys
from eccodes import *
# RJHD imports
import cartopy
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotli... | StarcoderdataPython |
3337760 | <filename>search_blog/urls.py
from django.conf.urls import url
from .views import do_search_blog
urlpatterns = [
url(r'^$', do_search_blog, name='search_blog')
] | StarcoderdataPython |
3289128 | #!/usr/bin/env python3
# encoding: utf-8
from easy_rmg_model.template_writer.submit.gaussian_submit import GaussianSubmit
from easy_rmg_model.template_writer.submit.slurm import SLURMSubmitScript
| StarcoderdataPython |
1692634 | from sklearn.datasets import load_boston
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#from icecream import ic
import random
from functools import reduce
from collections import defaultdict
from nn import Placeholder#导入
# sns.heatmap(dataframe.corr())
# x, y ; x with 13 dimensi... | StarcoderdataPython |
3342956 | <reponame>kaiker19/incubator-doris<filename>samples/insert/python/insert_utils.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
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 copy... | StarcoderdataPython |
1726881 | from datetime import date, datetime
from typing import Optional
import pytest
import statey as st
from statey.syms import encoders
@pytest.mark.parametrize(
"type, check",
[
pytest.param(int, lambda x: isinstance(x, encoders.IntegerEncoder), id="int"),
pytest.param(str, lambda x: isinstance(x... | StarcoderdataPython |
3398967 | # Copyright (C) <NAME>. All Rights Reserved.
# email: <EMAIL>
from engine.data.transforms import GaussianBlur, TwoCropsTransfrom
from engine.data.build import build_dataset, DatasetCatalog
from engine.utils.metric_logger import MetricLogger
from engine.utils.logger import GroupedLogger
from engine.solver import WarmupM... | StarcoderdataPython |
4817415 | <gh_stars>1-10
"""
tests.__init__.py
~~~~~~~~~~~~~~~~~
"""
| StarcoderdataPython |
110838 | # Copyright 2020 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 ... | StarcoderdataPython |
1619580 | <gh_stars>1-10
#
# Copyright (c) 2019, Neptune Labs Sp. z o.o.
#
# 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 |
1671022 | <reponame>CZ-NIC/deckard
"""Simple answer generator using local forwarder"""
# pylint: disable=C0301,C0111,C0103
# flake8: noqa
import ipaddress
import answer_checker
d = {"SIMPLE_ANSWER" : answer_checker.make_random_case_query("good-a.test.knot-resolver.cz", "A"),
"EDNS_ANSWER" : answer_checker.make_random_case... | StarcoderdataPython |
16998 | #import
import os
#import torch
#import torch.nn as nn
import torch.utils.data as Data
#import torchvision
import matplotlib.pyplot as plt
import h5py
#from torch.autograd import Variable
import numpy as np
import torch
class rawdataDataset(Data.Dataset):
def __init__(self):
super(rawdataDataset, self)... | StarcoderdataPython |
1694193 | <gh_stars>0
import os
import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
def epub2thtml(epub_path):
book = epub.read_epub(epub_path)
chapters = []
for item in book.get_items():
if item.get_type() == ebooklib.ITEM_DOCUMENT:
chapters.append(item.get_content())
ret... | StarcoderdataPython |
1630418 | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.modules as nnmodules
from torch.nn.modules.module import _addindent
import torchvision.transforms as transforms
import datasets.vegas_visual as vegas_visual
import numpy as np
import utils as ut # @UnresolvedImport
import values a... | StarcoderdataPython |
166379 | from datetime import timedelta
from .interchange import WaypointType
class ActivityStatisticCalculator:
ImplicitPauseTime = timedelta(minutes=1, seconds=5)
def CalculateDistance(act, startWpt=None, endWpt=None):
import math
dist = 0
altHold = None # seperate from the lastLoc variable,... | StarcoderdataPython |
1624198 | <reponame>nusherjk/DRF-system-for-ecommerce
from django.contrib import admin
from .models import *
from django.contrib.auth.admin import UserAdmin
# Register your models here.
admin.site.register(User, UserAdmin)
admin.site.register(Product)
admin.site.register(ProductReview)
admin.site.register(Order)
admin.site.regi... | StarcoderdataPython |
23919 | # Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
from ._types import IntegerType, VectorType, ToucaType
from datetime import datetime, timedelta
from enum import Enum
from typing import Dict, Tuple
class ResultCategory(Enum):
""" """
Check = 1
Assert = 2
class ResultEntry:
"""
Wrapp... | StarcoderdataPython |
48056 | #Función que calcula la matriz resultante "C" después de aplicar la operación convolución de A*B=
# EJERCICIO 28 DE OCTUBRE
# <NAME> A01377098
import numpy as np
def convolucion (A, B):
contaFil = 0
contaCol = 0
limiteFil = len(A)
limiteCol = len(A)
longitudB = len(B)
for x in range (len(C))... | StarcoderdataPython |
1692996 | from relogic.logickit.scorer.scorer import Scorer
from relogic.logickit.utils.utils import softmax, sigmoid
import torch.nn.functional as F
import torch
from tqdm import tqdm
import os
import subprocess
import json
class RecallScorer(Scorer):
def __init__(self, label_mapping, topk, correct_label='1', dump_to_file=No... | StarcoderdataPython |
4816908 | # 组合模式
class Store(object):
'''店面基类'''
# 添加店面
def add(self, store):
pass
# 删除店面
def remove(self, store):
pass
def pay_by_card(self):
pass
class BranchStore(Store):
def __init__(self, name):
self.name = name
self.my_store_list = []
def pay_b... | StarcoderdataPython |
3392152 | # Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
4801735 | <reponame>morganwillisaws/codeguru
from threading import Thread
class Counter(object):
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
c = Counter()
def go():
for i in range(1000000):
c.increment()
# Run two threads that increment the counter:
t1 = Thread(... | StarcoderdataPython |
168199 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Pocket PiAP
# ......................................................................
# Copyright (c) 2017-2020, <NAME>
# ......................................................................
# Licensed under MIT (the "License");
# you may not use this file except in co... | StarcoderdataPython |
1781623 | from .models import Project, Site
from onadata.apps.fsforms.models import FieldSightXF
def get_form_answer(site_id, meta):
fxf = FieldSightXF.objects.filter(pk=int(meta.get('form_id', "0")))
if fxf:
sub = fxf[0].project_form_instances.filter(site_id=site_id).order_by('-instance_id')[:1]
if sub:... | StarcoderdataPython |
1616149 | import os
import sys
import json
import torch
import logging
from tqdm import tqdm
from . import loader_utils
from ..constant import BOS_WORD, EOS_WORD, Tag2Idx
logger = logging.getLogger()
# -------------------------------------------------------------------------------------------
# preprocess label
# ------------... | StarcoderdataPython |
3278348 | #isLower is built into python😦
import Terry
def reverse(input):
output=""
for i in range(len(input)-1,-1,-1):
output+=input[i]
return output
#print(reverse("test"))
def leetspeak(input):
translationDict = {
"A":"4",
"E":"3",
"G":"6",
"I":"1",
"O":"0",
... | StarcoderdataPython |
179728 | <filename>multiway.py
"""
Program: multiway.py
Author: <NAME>
Date: October 9, 2017
"""
number = int(input("Enter the numeric grade:"))
if number >= 0 and number <= 100:
if number > 89:
letter = 'A'
print("The letter grade is", letter)
else:
print("Error: grade must be between 100 an... | StarcoderdataPython |
1778185 | <gh_stars>0
import gym
import numpy as np
import math
import time
import glfw
"""Data generation for the case of a single block pick and place in Fetch Env"""
actions = []
observations = []
infos = []
from pynput import mouse
class Actor(object):
def __init__(self, env):
self.x = 0.0
self.y = 0... | StarcoderdataPython |
3398738 | import numpy as np
import torch
import torch.nn as nn
from copy import deepcopy
from pybnn.bohamiann import Bohamiann
def vapor_pressure(t, a, b, c):
a_ = a
b_ = b / 10.
c_ = c / 10.
return torch.exp(-a_ - b_ / t - c_ * torch.log(t)) - torch.exp(-a_ - b_)
def pow_func(t, a, b):
return a * (t ... | StarcoderdataPython |
1666496 | <reponame>kemingy/daily-coding-problem<filename>src/LCA.py
# Given a binary tree, find the lowest common ancestor (LCA) of two given nodes
# in the tree. Assume that each node in the tree also has a pointer to its parent.
# According to the definition of LCA on Wikipedia: “The lowest common ancestor
# is defined... | StarcoderdataPython |
1770314 | <filename>src/zope/app/authentication/browser/rolepermissionview.py
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.... | StarcoderdataPython |
3367123 | import functools
import types
from typing import Any, Callable, Dict, List, Optional, Tuple, cast # noqa
FUNCTION_ATTRIBUTE = "_tomodachi_function_is_invoker_function"
START_ATTRIBUTE = "_tomodachi_deprecated_invoker_function_start_marker"
INVOKER_TASK_START_KEYWORD = "_tomodachi_invoker_task_start_keyword"
class I... | StarcoderdataPython |
196286 | <filename>park/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home' ),
path('add_park/', views.addPark, name='add_park'),
path('get_parks/', views.getParks, name='get_parks'),
]
| StarcoderdataPython |
1733319 | import tensorflow as tf
import numpy as np
from transformers import *
import re, string
import pandas as pd
import sys
from keras.preprocessing.sequence import pad_sequences
def map_sent(sent):
if sent == 'positive' or sent == 'neutral':
return 1
if sent == 'negative':
return 0
def deEmoji... | StarcoderdataPython |
183902 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import pdb, os, argparse
from tqdm import tqdm
from datetime import datetime
from model.CPD_ResNet_models import CPD_ResNet
from model.Sal_CNN import Sal_CNN
from data import get_loader
from utils import clip_gradient, a... | StarcoderdataPython |
3353750 | from unicorn.arm_const import *
from .. import native
def parse_fuzzed_irqs(entries):
allowed_irqs = set()
print("Parsing fuzzable irq configuration")
for name, int_or_range_string in entries.items():
# print("[PARSE FUZZED IRQs] Looking at entry: {} -> {}".format(name, int_or_range_string))
... | StarcoderdataPython |
118266 | <reponame>rzuckerm/pylama
""" Support libs. """
| StarcoderdataPython |
1635566 | # Generated by Django 2.2.19 on 2021-05-11 13:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("wagtailcore", "0060_fix_workflow_unique_constraint"),
("feedback", "0001_initial"),
]
operations = [
... | StarcoderdataPython |
1601840 | <filename>taxa_de_servico.py
nome=input("Informe seu nome: ")
diaria=int(input("Quantos dias você ficou? "))
conta = diaria * 60
if diaria > 15:
taxa = diaria * 5.5
elif diaria == 15:
taxa = diaria * 6
else:
taxa = diaria * 8
conta = (diaria * 60) + taxa
print(nome, "Total da conta", con... | StarcoderdataPython |
191948 | <filename>HTML-Swapper/GUI/RuleWidgetTwoValues.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\Programming\HTML-Swapper\RuleWidgetTwoValues.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, Q... | StarcoderdataPython |
129894 | <filename>svhn 64x64/unpacker.py
import h5py
class GetBoundingBoxes:
def __init__(self, inf):
self.inf = h5py.File(inf, 'r')
self.digitStructName = self.inf['digitStruct']['name']
self.digitStructBbox = self.inf['digitStruct']['bbox']
def get_name(self, n):
return ''.join([chr... | StarcoderdataPython |
43681 | <reponame>hth945/pytest<filename>paddle/za/test/test2.py
# 导入图像读取第三方库
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import cv2
import numpy as np
from PIL import Image
import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Linear
# 读取图像
img1 = cv2.imread('./work/example_0.png... | StarcoderdataPython |
194719 | """Support alarm_control_panel entity for Xiaomi Miot."""
import logging
from homeassistant.const import * # noqa: F401
from homeassistant.components.alarm_control_panel import (
DOMAIN as ENTITY_DOMAIN,
AlarmControlPanelEntity,
)
from homeassistant.components.alarm_control_panel.const import *
from . import... | StarcoderdataPython |
3389913 | <reponame>cypherdotXd/o3de
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
# Tests the Python API from DisplaySettingsPythonFuncs.cpp while the Editor is runni... | StarcoderdataPython |
3206581 | <gh_stars>0
from coopihc.observation.BaseObservationEngine import BaseObservationEngine
import copy
class CascadedObservationEngine(BaseObservationEngine):
"""CascadedObservationEngine
Cascades (serially) several observation engines.
Gamestate --> Engine1 --> Engine2 --> ... --> EngineN --> Observation
... | StarcoderdataPython |
4839286 | from bai_kafka_utils.events import (
BenchmarkDoc,
VisitedService,
FetcherBenchmarkEvent,
DownloadableContent,
FetcherPayload,
FileSystemObject,
)
BIG_FETCHER_JSON = """{
"date": "Thu May 02 16:15:42 UTC 2019",
"authenticated": false,
"payload": {
... | StarcoderdataPython |
54019 | <filename>cannula/helpers.py
import os
import pkgutil
import sys
def get_root_path(import_name):
"""Returns the path to a package or cwd if that cannot be found.
Inspired by [flask](https://github.com/pallets/flask/blob/master/flask/helpers.py)
"""
# Module already imported and has a file attribute. ... | StarcoderdataPython |
1676914 | <filename>ucsmsdk/mometa/extmgmt/ExtmgmtGatewayPing.py
"""This module contains the general information for ExtmgmtGatewayPing ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class ExtmgmtGatewayPingConsts:
pass
class Extm... | StarcoderdataPython |
100336 | #!/usr/bin/env python
from scapy.all import *
import sys
import argparse
import math
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("remoteIP", help="Remote IP")
parser.add_argument("localIP", help="Local IP")
parser.add_argument("-p", "--protocol", type=str, default='udp',
... | StarcoderdataPython |
1681437 | <gh_stars>1-10
from PIL import Image
import matplotlib.pyplot as plt
import nibabel as nib
import numpy as np
from skimage.exposure import equalize_hist
from skimage.transform import resize
import torch
from torchvision import transforms
def plot(image, f=None):
plt.axis("off")
plt.imshow(image, cmap="gray", ... | StarcoderdataPython |
1766504 | <filename>pycon_project/migrations/008_create_sessions_slots.py
def migrate():
from datetime import datetime
from django.db import connections
from review.models import ProposalResult, promote_proposal
from schedule.models import Slot, Session
accepted_proposals = ProposalResult.objec... | StarcoderdataPython |
48607 | <reponame>Fragoso09/orstool-qgis
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ORStools
A QGIS plugin
QGIS client to query openrouteservice
-------------------
begin : 2017-... | StarcoderdataPython |
1659122 | from rest_framework import serializers
from stump.models import AppearanceType
class AppearanceTypeSerializer(serializers.ModelSerializer):
class Meta:
model = AppearanceType
fields = '__all__'
| StarcoderdataPython |
98787 | <reponame>denisrmp/hacker-rank<filename>hacker-rank/implementation/new_year_chaos.py
# https://www.hackerrank.com/challenges/new-year-chaos
from collections import deque
def new_year_chaos(n, q):
acc = 0
expect = list(range(1, n + 1))
while len(q):
iof = expect.index(q[0])
if iof > 2:
... | StarcoderdataPython |
1649660 | import logging
import os
import re
import jinja2
from functools import total_ordering
import sqlalchemy as sa
from datadock.helpers import extract_type_annotations, extract_flag_comment, check_flag
logger = logging.getLogger(__name__)
@total_ordering
class Statement:
def __init__(self, path: str, default_sourc... | StarcoderdataPython |
3267562 | <filename>unitorch/cli/models/swin/__init__.py
# Copyright (c) FULIUCANSHENG.
# Licensed under the MIT License.
# pretrained infos
pretrained_swin_infos = {
"default-swin": {
"config": "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json",
"vision_config": "https:... | StarcoderdataPython |
3200445 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Software Foundation. This proje... | StarcoderdataPython |
4837155 | <filename>Week 8/try_week8.py
fin = open('words.txt')
for line in fin:
word = line.strip()
print(word) | StarcoderdataPython |
1761149 | """ Household microsynthesis """
import numpy as np
import pandas as pd
import ukcensusapi.Nomisweb as Api_ew
import ukcensusapi.NRScotland as Api_sc
import humanleague
import household_microsynth.utils as utils
import household_microsynth.seed as seed
class Household:
""" Household microsynthesis """
# Placehol... | StarcoderdataPython |
43064 | <reponame>joshuahlang/template-specialize
# Licensed under the MIT License
# https://github.com/craigahobbs/template-specialize/blob/master/LICENSE
from .main import main
if __name__ == '__main__':
main() # pragma: no cover
| StarcoderdataPython |
3278068 | <gh_stars>0
import os
import sys
import inspect
import unittest
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.append(os.path.dirname(currentdir))
import image
class ImageContainerTest(unittest.TestCase):
def setUp(self):
... | StarcoderdataPython |
3368431 | <filename>peripteras/users/api/views.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from collections import Counter
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.db.models i... | StarcoderdataPython |
3393450 | <reponame>DaoDaoer/PaddleSeg
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | StarcoderdataPython |
4810460 | import watertank
import burner
import shac
ha = shac.comp([watertank.watertank, burner.burner])
shac.compile(ha, COMPOSED=True, ABOF=True)
| StarcoderdataPython |
1739910 | <reponame>cenkalti/hcloud-python
# -*- coding: utf-8 -*-
from hcloud.actions.client import BoundAction
from hcloud.core.client import BoundModelBase, ClientEntityBase, GetEntityByNameMixin
from hcloud.core.domain import add_meta_to_result
from hcloud.images.domain import Image
class BoundImage(BoundModelBase):
m... | StarcoderdataPython |
101515 | <filename>sug-blog/unit4/account.py
import handler.handler as handler
import util.security as security
import util.validator as validator
from google.appengine.ext import db
class AccountHandler(handler.TemplateHandler):
"""
AccountHandler inherits from the hander.TemplateHandler class.
It gives users the... | StarcoderdataPython |
3350455 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# PythonTidyWrapper.py
# 2007 Mar 06 . ccr
# 2010 Sep 08 . ccr . Add JAVA_STYLE_LIST_DEDENT.
# 2010 Mar 16 . ccr . Add KEEP_UNASSIGNED_CONSTANTS and PARENTHESIZE_TUPLE_DISPLAY.
# 2007 May 25 . ccr . Changed MAX_SEPS. Add WRAP_DOC_STRINGS and DOC_TAB_REPLACEMENT.
# 2007 May 0... | StarcoderdataPython |
107447 | import http.server
import socketserver
# Inicializando o servidor web
# ============================================================================
PORT = 8000
HANDLER = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), HANDLER) as httpd:
print("Servindo na porta:", PORT)
httpd.se... | StarcoderdataPython |
152036 | <reponame>DanNixon/PlayMusicCL<gh_stars>100-1000
from setuptools import setup
setup(
name='playmusiccl',
version='0.6.2',
entry_points = {
'console_scripts': ['playmusiccl=playmusiccl:run'],
},
description='Text based command line client for Google Play Music',
classifiers=[
'Li... | StarcoderdataPython |
3216363 | <gh_stars>10-100
from evaluation.fix_spans import _contiguous_ranges
import pandas as pd
import numpy as np
from ast import literal_eval
import os
import sys
from evaluation.metrics import f1
def get_spans_from_offsets(text, offsets):
text_spans = []
ranges = _contiguous_ranges(offsets)
for _range in rang... | StarcoderdataPython |
163170 | #!/usr/bin/env python3
import argparse
import pytest
import datetime
import dateutil
from dateutil.parser import parse
import os
legal_days_of_week="MTWRF"
def mkdir_p(newdir):
"""works the way a good mkdir should :)
- already exists, silently complete
- regular file in the way, raise an exceptio... | StarcoderdataPython |
1733700 | <reponame>RodrigoMSCruz/CursoEmVideo.com-Python<gh_stars>0
# Lê 6 números e mostra o somatório deles. Se for digitado um valor
# ímpar, é desconsiderado.
print('Digite 6 números para serem somados. Números ímpares serão desconsiderados.')
s = 0
c = 0
for i in range (1, 7, 1):
n = int(input('Digite um número: '))
... | StarcoderdataPython |
3257533 | <filename>samurai/settings.py
#!/usr/bin/env python3
from os import getenv
def get_env_debug_secret_hosts():
debug = bool(getenv("DEBUG"))
if not getenv("SECRET_KEY") and not debug:
raise Exception("Won't allow you to use default secret key out of DEBUG.")
secret_key = getenv("SECRET_KEY", "<KEY>... | StarcoderdataPython |
153978 | <reponame>58563528/nonebot-hk-reporter
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
nonebot.init(command_start=[""])
app = nonebot.get_asgi()
driver = nonebot.get_driver()
driver.register_adapter('cqhttp', CQHTTPBot)
nonebot.load_builtin_plugins()
nonebot.load_plugin('nonebot_plugin_help')
non... | StarcoderdataPython |
1628242 | <reponame>nguyentientungduong/python_client<filename>sample/RemoveRowByRowkey.py
#!/usr/bin/python
import griddb_python as griddb
import sys
factory = griddb.StoreFactory.get_instance()
argv = sys.argv
containerName = "SamplePython_RemoveRowByRowKey"
rowCount = 5
nameList = ["notebook PC", "desktop PC", "keyboard",... | StarcoderdataPython |
3268888 | <reponame>curtjen/clither
#!/bin/env python
# ===== Usage =====
# --- Import ---
# import helpers
#
# --- create_directory("DIRECTORY_NAME") ---
#
# --- backup_file("FILE_PATH") ---
#
# --- create_symlink("FILE_PATH") ---
# This will create a symlink inside the $HOME directory for a given file path.
import calendar
i... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.