id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6532151 | #This code is to reach out into a url and read and parse an xml document to deliver a sum of the occurence of a piece of string data in int form.
import urllib
import xml.etree.ElementTree as ET
def main():
url = get_user_input()
xml = read_xml(url)
count_str_list = count_str_collector(xml) #collect list ... | StarcoderdataPython |
2663 | MEDIA_SEARCH = """
query ($search: String, $type: MediaType, $exclude: MediaFormat, $isAdult: Boolean) {
Media(search: $search, type: $type, format_not: $exclude, isAdult: $isAdult) {
id
type
format
title {
english
romaji
native
}
synonyms
status
description
start... | StarcoderdataPython |
5186754 | <reponame>BGTCapital/hummingbot<gh_stars>1000+
import base64
import hashlib
import hmac
import time
from typing import Dict
from hummingbot.connector.exchange.coinbase_pro import coinbase_pro_constants as CONSTANTS
from hummingbot.connector.exchange.coinbase_pro.coinbase_pro_utils import CoinbaseProRESTRequest
from hu... | StarcoderdataPython |
1711885 | <gh_stars>0
# Generated by Django 3.1.7 on 2021-04-28 14:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_shopvideo_templates_video_link'),
]
operations = [
migrations.RenameField(
model_name='shopvideo',
... | StarcoderdataPython |
4813921 | <gh_stars>0
from unicodedata import normalize
from uuid import uuid4
def __generate_id__():
codigo = uuid4()
return str(codigo)
def __equals(obj, other):
hobj = hash(frozenset(vars(obj).items()))
hother = hash(frozenset(vars(other).items()))
print(obj, hobj)
print(other, hother)
return h... | StarcoderdataPython |
5056933 | <reponame>grvkmrpandit/competitiveprogramming
arr=list(map(int,input().split()))
n=arr[0]
graph=[[]for i in range(n+1)]
cost=[]
for i in range(1,n+1):
cost.append(arr[i])
cost=[0]+cost
manager=[]
for i in range(n+1,2*n+1):
manager.append(arr[i])
manager=[0]+manager
for i in range(1,n+1):
k=manager[i]
if manager[i]!... | StarcoderdataPython |
6620902 | import os
import glob
import sys
sys.path.append("..")
import cfg
import random
if __name__ == '__main__':
traindata_path = cfg.BASE + r'\train'
labels = os.listdir(traindata_path)
valdata_path = cfg.BASE + r'\test'
##写train.txt文件
txtpath = cfg.BASE+r'/'
print(labels)
if os.path.exi... | StarcoderdataPython |
11342442 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Callable, Dict, Iterable, Optional
import onnx
from onnx.helper import get_attribute_value
from mmdeploy.utils import get_root_logger
def attribute_to_dict(attr: onnx.AttributeProto) -> Dict:
"""Convert onnx op attribute to dict.
Args:
... | StarcoderdataPython |
8052152 | <filename>apps/blog/views.py<gh_stars>0
# -*- coding: utf-8 -*-
import random
from django.conf import settings
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.contrib.syndication.views import Feed
from .models import Blog, Tag
from django.core.exceptions imp... | StarcoderdataPython |
6563047 | <filename>semantic_similarity/kypher.py<gh_stars>1-10
"""
Kypher query backend support for KGTK similarity computations.
"""
import os.path
import json
import numpy as np
import pandas as pd
import kgtk.kypher.api as kapi
from kgtk.exceptions import KGTKException
config = json.load(open('semantic_similarity/conf... | StarcoderdataPython |
6571452 | <gh_stars>100-1000
import sys
import os
license=[
"/* LICENSE>>\n",
"Copyright 2020 <NAME> (CaptainYS, http://www.ysflight.com)\n",
"\n",
"Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n",
"\n",
"1. Redistributions of s... | StarcoderdataPython |
3368436 | <reponame>dingguanglei/jdit
from unittest import TestCase
class TestFeatureVisualization(TestCase):
def test__hook(self):
pass
def test__register_forward_hook(self):
pass
def test_trace_activation(self):
pass
| StarcoderdataPython |
5068695 | from tools import log, DDingWarn, ip_update, music_play, reformat_music_type, ServerChanWarn, send_email, Text2Speech
from config import *
from Spiders.SoulBread import jdjzww_daily
from events import Bibles
import time
logger = log.logger_generator(logger_name='Assistant')
mk_dirs([excluded_file, tts_location, time_r... | StarcoderdataPython |
5197049 | from geoscript.style import util
from geoscript.style.expression import Expression
from geoscript.style.symbolizer import Symbolizer
from org.geotools.styling import RasterSymbolizer
class Opacity(Symbolizer):
def __init__(self, value=1.0):
Symbolizer.__init__(self)
self.value = Expression(value)
def _pr... | StarcoderdataPython |
144527 | <reponame>EkremBayar/bayar<gh_stars>100-1000
from typing import Any
import numpy as np
from numpy.typing import _SupportsArray
class Index:
def __index__(self) -> int:
...
a: "np.flatiter[np.ndarray]"
supports_array: _SupportsArray
a.base = Any # E: Property "base" defined in "flatiter" is read-only
... | StarcoderdataPython |
1794436 | BOOKMARK_MSGS = {
'BOOKMARK_SUCCESSFUL': 'Article has been added to your bookmarks.',
'BOOKMARKS_FOUND': 'Here are your bookmarks.',
'NO_BOOKMARKS': 'You have no bookmarked articles.',
'ARTICLE_NOT_FOUND': ('We couldn\'t add the bookmark because '
'the article could not be foun... | StarcoderdataPython |
3441478 | <filename>yeelight/tests.py
import json
import os
import sys
import threading
import time
import unittest
if sys.version_info >= (3, 3):
import unittest.mock as mock
else:
import mock
from yeelight import Bulb, BulbType
from yeelight import enums
from yeelight import Flow
from yeelight import flows
from yeeli... | StarcoderdataPython |
8066337 | <reponame>S10MC2015/cms-django<gh_stars>0
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.utils.translation import ugettext as _
from django.shortcuts import redirect
from ...decorators import region_permission_required
from ...models impor... | StarcoderdataPython |
4886824 | import smtplib
user = 'username'
pwd = 'password'
msg =MIMEText(text)
msg['From'] = user
msg['To'] = to
msg['subject'] = subject
def banner():
print "[***] Anon-mail p238 [***]"
def sendMail(user, pwd, to, subject, text):
try:
smtpServer = smtplib.SMTP('smtp.gmail.com', 587)
print "[+] Connecting to Mail Serv... | StarcoderdataPython |
5175256 | <reponame>CloudCIX/metrics_cloudcix
#!/usr/bin/env python
from setuptools import setup
with open('README.md', 'r') as f:
readme = f.read()
with open('requirements.txt', 'r') as f:
requires = f.read().split('\n')
setup(
name='cloudcix_metrics',
version='1.0.0',
description='Metrics library for Cl... | StarcoderdataPython |
4945478 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 8 14:10:02 2021
@author: philippbst
"""
from matplotlib import cm
import matplotlib.pyplot as plt
import visualization.visualization_general as visgen
import numpy as np
COLORMAP_1 = cm.turbo
FONT_STYLE = 'Arial'
def plotMultiLearningCurves(Loss... | StarcoderdataPython |
8105912 | #!/usr/bin/env python
# coding: utf-8
from IPython.display import clear_output
import numpy as np
import pandas as pd
import os
import glob
import logging
import sys
from pathlib import Path
sys.path.append(str(Path('.').absolute().parent))
from importlib import reload
from tqdm import tqdm
import pickle
from pygmo.c... | StarcoderdataPython |
4862517 | <gh_stars>0
from LakeShore350 import LakeShore350
import time
from uncertainties import ufloat
from threading import Thread, Event
import zmq
import logging
# from threading import Thread
logger = logging.getLogger('CryostatGUI.zmqComm')
class genericAnswer(Exception):
pass
class customEx(Exception):
pass... | StarcoderdataPython |
6674185 | from Voltron.Algorithms.DynamicProgramming.memoization import (
# In order of appearance or usage.
fibonacci,
grid_traveler
)
import pytest
def test_fibonacci():
assert fibonacci(6) == 8
assert fibonacci(7) == 13
assert fibonacci(8) == 21
assert fibonacci(50) == 12586269025
def test_g... | StarcoderdataPython |
9657998 | <reponame>PLANET-Q/StatwindTool<gh_stars>0
import numpy as np
import numpy.linalg as LA
import sympy
import json
def getConditionalBivariateNorm(mu_X, mu_Y, sigma_XX, sigma_XY, sigma_YY, X):
# Y|X が多変量正規分布N(mu, Sigma)に従う場合のmu, Sigmaを求める
sigma_XX_i = LA.inv(sigma_XX)
mu = mu_Y + np.dot(np.dot(sigm... | StarcoderdataPython |
316638 | <gh_stars>1-10
import logging; logger = logging.getLogger("morse." + __name__)
import morse.core.actuator
from math import sqrt
from morse.core.mathutils import Vector, Matrix
from morse.core.services import service, async_service, interruptible
from morse.helpers.components import add_data, add_property
class Dyncall... | StarcoderdataPython |
1639473 | from matplotlib.ticker import PercentFormatter
from scipy.stats import skew, kurtosis
from typing import Tuple
import matplotlib.pyplot as plt
import pandas as pd
__all__ = [
'univariate_plot',
'univariate_plot_v2',
'boxplot_summary',
'pareto_plot',
]
def univariate_plot_v2(independent_variable: pd.... | StarcoderdataPython |
5042867 | import collections
class Solution(object):
def numJewelsInStones(self, J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
sCounter = Counter(S)
j = set(J)
jwels = 0
for stone in sCounter:
if stone in j:
jwels += sC... | StarcoderdataPython |
9707499 | # import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from game_stats import GameStats
from ship import Ship
from alien import Alien
import game_functions as gf
def run_game():
# Initialize game and create a screen object.
pygame.init()
ai_settings = Setting... | StarcoderdataPython |
3203143 | # Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
# Example 1:
# Input: strs = ["flower","flow","flight",'araba']
# Output: "fl"
class Solution(object):
def longestCommonPrefix(self, strs):
key = strs[0]
... | StarcoderdataPython |
1994473 | """ Module for Airtunnel's ingestion sensors. """
import os
from airflow.models import TaskInstance
from airflow.operators.sensors import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
import airtunnel.data_store
import airtunnel.operators
from airtunnel.data_asset import BaseDataAsset
K_DISC... | StarcoderdataPython |
1864406 | <gh_stars>100-1000
#!/usr/bin/env python
import os
import joblib
import argparse
from PIL import Image
from .util import draw_bb_on_img
from .constants import MODEL_PATH
from face_recognition import preprocessing
def parse_args():
parser = argparse.ArgumentParser(
'Script for detecting and classifying fa... | StarcoderdataPython |
6438306 | from asyncio import get_running_loop, sleep
from typing import TYPE_CHECKING
import warnings
import logging
import traceback
from vkwave.bots.core.dispatching.dp.processing_options import ProcessEventOptions
from vkwave.bots.core.dispatching.events.raw import ExtensionEvent
from vkwave.bots.core.types.bot_type import ... | StarcoderdataPython |
317683 | from .OutputBase import OutputBase
from .OutputOpenSdg import OutputOpenSdg
from .OutputGeoJson import OutputGeoJson
from .OutputDataPackage import OutputDataPackage
from .OutputCsvw import OutputCsvw
from .OutputSdmxMl import OutputSdmxMl
| StarcoderdataPython |
1951598 | <gh_stars>10-100
# -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class PostController(Controller):
def get(self):
payload = self.helper.web.aws.s3.generate_presigned_post(
key='foo/bar/baz.tmp',
success_action_redirect='http://127.0.0.1/uploaded',
... | StarcoderdataPython |
4859697 | <gh_stars>1-10
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ringapp', '0011_comminvariance'),
]
operations = [
migrations.CreateModel(
name='FAQ',
... | StarcoderdataPython |
1612744 | # Copyright 2019 Alibaba Cloud 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 la... | StarcoderdataPython |
6673763 | # pylint: disable=missing-docstring
class Auth:
def __init__(self, email, password):
self.email = email
self.password = password
def get_email(self):
return self.email
def get_password(self):
return self.password
def get_verification_code(self):
# pylint: dis... | StarcoderdataPython |
115845 | <filename>diagonal_diff.py<gh_stars>0
#!/bin/python
import sys
n = int(raw_input().strip())
a = []
for a_i in xrange(n):
a_temp = map(int,raw_input().strip().split(' '))
a.append(a_temp)
diag = [ a[i][i] for i in range(len(a)) ]
counter_diag = [ row[-i-1] for i,row in enumerate(a) ]
sum = 0
for i in diag:
... | StarcoderdataPython |
4862436 | <filename>Final/Test/server.py<gh_stars>0
import socket
import threading
import argparse
import sys
def broadcast(clients, msg, data=""):
for client in clients:
message = data.encode('utf-8') + msg
client.send(message)
def chat_room(c, clients):
try:
data = c.recv(4096).decode('utf-8')... | StarcoderdataPython |
6487260 | # Copyright 2021 The Layout Parser team. 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 applica... | StarcoderdataPython |
3385482 | import csv
import gpxpy
import gpxpy.gpx
import pandas as pd
from pyproj import CRS, Transformer
import random
import string
transformer = Transformer.from_crs("EPSG:4326", "EPSG:27700")
# Get all of Lottie's 5K runs in 2019
df = pd.read_csv("export_37643766/activities.csv") # Lottie
df['Date'] = pd.to_datetime(df['A... | StarcoderdataPython |
1679216 | from auxiliar import receberInt, receberFixo
pessoaIndividual = dict()
pessoas = list()
mediaIdade = 0
while True:
pessoaIndividual['nome'] = input('\n\tDigite o nome: ').strip().capitalize()
pessoaIndividual['sexo'] = receberFixo('\tDigite o sexo (m / f): ', 'mf')
pessoaIndividual['idade'] = receberInt('\... | StarcoderdataPython |
1919622 | <reponame>AlexWayfer/sentry<gh_stars>1-10
from __future__ import absolute_import
from django.utils.functional import empty
def extract_lazy_object(lo):
"""
Unwrap a LazyObject and return the inner object. Whatever that may be.
ProTip: This is relying on `django.utils.functional.empty`, which may
or ... | StarcoderdataPython |
8114541 | <reponame>jviloria96744/acg-covid-challenge-frontend
#!/usr/bin/env python3
import os
from aws_cdk import core
from static_site_stack.static_site_stack import StaticSiteStack
from certificate_stack.certificate_stack import CertificateStack
app = core.App()
sub_domain = "acg-covid-challenge"
domain = app.node.try_get_... | StarcoderdataPython |
279572 | <filename>pastebin/core/app_messages.py
from django.contrib import messages
class Messenger:
"""
Simpole wrapper for the django messages
"""
def __init__(self, domain):
super().__init__()
self.domain = domain
import logging
self.logger = logging.getLogger(__name__)
... | StarcoderdataPython |
1838967 | import uuid
import random
import datetime
from typing import Tuple
from faker import Faker
from apps.climsoft.schemas import physicalfeatureclass_schema
fake = Faker()
def get_valid_physical_feature_class_input(station_id: str):
return physicalfeatureclass_schema.PhysicalFeatureClass(
featureClass=stati... | StarcoderdataPython |
6531665 | import types
from plenum.test.helper import sdk_send_random_and_check
from plenum.test.test_node import TestNode
def test_restart_clientstack_before_reply_on_4_of_4_nodes(looper,
txnPoolNodeSet,
sdk_po... | StarcoderdataPython |
12837875 | <reponame>kenseitrg/room-monitor<filename>scheduler.py
import threading
import time
from typing import Callable, List, Dict
class Scheduler():
def __init__(self, interval:int, function:Callable, *args, **kwargs) -> None:
self._timer = None
self.interval = interval
self.function = function
... | StarcoderdataPython |
6624344 | import argparse
from collections import OrderedDict
import torch
def get_parser():
parser = argparse.ArgumentParser(description='FCOS Detectron2 Converter')
parser.add_argument(
'--model',
default='weights/fcos_R_50_1x_official.pth',
metavar='FILE',
help='path to model weights... | StarcoderdataPython |
9787278 | <reponame>davidhannan/dphgx8
import json
import Staff
class Professor(Staff.Staff):
def __init__(self, name,users,courses):
self.users = users
self.all_courses = courses
self.name = name
self.courses = self.users[name]['courses']
self.password = self.users[name]['password']... | StarcoderdataPython |
5138735 | #!/usr/bin/env python
import sys
import os
import subprocess
first = sys.argv[1]
second = sys.argv[2]
path = os.path.abspath(os.path.dirname(__file__))
ws = os.path.join(path, "websockify.py")
print str(ws)
os.system(ws + " " + first + " " + second + " &")
| StarcoderdataPython |
3215044 | <filename>month02/multiprocessing/process01.py
"""
进程模块使用,基础示例
"""
# 不能选带横线的
import multiprocessing
from time import sleep
a = 1
# 进程执行函数
def fun():
print("开始运行第一个进程")
sleep(2)
global a
print(a)
a = 100 # 打印子进程a
print("第一个进程结束")
# 实例化进程对象
p = multiprocessing.Process(target=fun)
# 启动进程 此刻才... | StarcoderdataPython |
9632217 | <reponame>frederica07/Dragon_Programming_Process<gh_stars>0
'''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p, constants as _cs, arrays
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_IBM_multimode_draw_arrays'
def _f( function ):
return _p.createFunction... | StarcoderdataPython |
3311875 | <reponame>ZestIoT-Technologies-Pvt-Ltd/BPCL_TB_Sultanpur
import cv2
import numpy as np
x_prev, y_prev = 0, 0
def helmet(img) :
global x_prev, y_prev
number_motion = 0
mask = np.zeros(img.shape[:2], np.uint8)
#pts = np.array([[566,504],[590,264], [870,305],[870,504]])
pts = np.array([[588,284], [985,305],[985,504... | StarcoderdataPython |
282810 | from django.urls import path
from . import views
app_name = "courses"
urlpatterns = [
path("", views.CourseListView.as_view(), name="course-list"),
# lesson
path(
"<slug:slug>/lesson/<int:pk>",
views.LessonScriptDetailView.as_view(),
name="lesson-script-detail",
),
path(
... | StarcoderdataPython |
8184647 | #encoding=utf-8
import argparse
import time
from others.logging import init_logger
from prepro import data_builder
def do_format_to_lines(args):
print(time.clock())
data_builder.format_to_lines(args)
print(time.clock())
def do_format_to_bert(args):
print(time.clock())
data_builder.format_to_be... | StarcoderdataPython |
3312354 | import math
import numpy
import ujson as json
from bisect import bisect_left, bisect_right
from operator import add
from collections import Counter
from sift.models.links import EntityVocab
from sift.dataset import ModelBuilder, Documents, Model, Mentions, IndexedMentions, Vocab
from sift.util import ngrams, iter_sent... | StarcoderdataPython |
11314518 | <gh_stars>0
#!/usr/bin/python
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICEN... | StarcoderdataPython |
9710887 | import os
import importlib.util
from framework import Task
import sys, random, string, csv, copy
from framework import Stack
from multiprocessing import Pool
from graphviz import Digraph
from .Task import Task
from .Stack import Stack
class Handler(object):
def run_algorithm(file_name, data_set, passed_tasks):
... | StarcoderdataPython |
3280631 |
def import_by_string(name: str):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
| StarcoderdataPython |
9612250 | <gh_stars>0
import pandas as pd
movies_df = pd.read_csv(r"..\data\movie.csv")
print(movies_df.head())
print(movies_df.director_name)
print(type(movies_df.director_name))
director_name = movies_df.director_name
len(director_name)
director_name.index
for i in director_name.index:
print(i)
director_name[director_na... | StarcoderdataPython |
4992182 | <filename>galaa/views.py
from django.shortcuts import render
from django.http import HttpResponse,Http404
from .models import photos,Category,Location
from django.core.exceptions import ObjectDoesNotExist
# Create your views here.
def welcome(request):
return render(request, 'welcome.html')
def index(request):... | StarcoderdataPython |
399022 | <gh_stars>0
# from django.contrib.postgres.fields.jsonb import JSONField
import pghistory
import django.utils.timezone
import model_utils.fields
from django.contrib.postgres.indexes import GinIndex
from django.db import models
from model_utils.models import SoftDeletableModel, TimeStampedModel
class Category(TimeStam... | StarcoderdataPython |
8108697 | <reponame>forca-inf/forca
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
filename = sys.argv[1]
datafile = open(filename, 'r')
try:
data = datafile.read()
finally:
datafile.close()
data = re.compile('\s*{\s*').sub(' { ', data)
data = re.compile('\s*;\s*').sub('; ', data)
data = re.compile... | StarcoderdataPython |
11341101 | """ Python 'utf-7' Codec
Written by <NAME> (<EMAIL>).
"""
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = staticmethod(codecs.utf_7_encode)
decode = staticmethod(codecs.... | StarcoderdataPython |
3378148 | # from bigannotator import threshold, image_arithmetic
# add your tests here...
import numpy as np
from bigannotator import napari_experimental_provide_function
import napari
from enum import Enum
# tmp_path is a pytest fixture
class Operation(Enum):
add = np.add
subtract = np.subtract
mul... | StarcoderdataPython |
288699 | <filename>tests/conftest.py
import enum
import math
from collections import OrderedDict, UserString
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Type, Union
from ruamel import yaml
import pytest # type: ignore
import yatiml
from yatiml.recognizer import Recognizer
@pytest.fixt... | StarcoderdataPython |
322541 | """
Nozomi
Decodable Module
author: <EMAIL>
"""
from json import loads
from typing import Any, Optional, TypeVar, Type, List, Dict
T = TypeVar('T', bound='Decodable')
class Decodable:
"""Abstract protocol defining an interface for decodable classes"""
@classmethod
def decode(self, data: Any) -> T:
... | StarcoderdataPython |
1610396 | import numpy as np
from logbook import Logger
from catalyst.constants import LOG_LEVEL
from catalyst.protocol import Portfolio, Positions, Position
log = Logger('ExchangePortfolio', level=LOG_LEVEL)
class ExchangePortfolio(Portfolio):
"""
Since the goal is to support multiple exchanges, it makes sense to
... | StarcoderdataPython |
4965480 | <filename>Lib/site-packages/win32comext/shell/test/testSHFileOperation.py
from win32com.shell import shell, shellcon
import win32api
import os
def testSHFileOperation(file_cnt):
temp_dir=os.environ['temp']
orig_fnames=[win32api.GetTempFileName(temp_dir,'sfo')[0] for x in range(file_cnt)]
new_fnames=... | StarcoderdataPython |
3524274 | <reponame>widdiot/EEND<gh_stars>1-10
# Copyright 2019 Hitachi, Ltd. (author: <NAME>)
# Licensed under the MIT license.
import numpy as np
import chainer
import chainer.functions as F
import chainer.links as L
from itertools import permutations
from chainer import cuda
from chainer import reporter
from eend.chainer_bac... | StarcoderdataPython |
11270046 | from output.models.ms_data.group.group_b006_xsd.group_b006 import (
ComplexType,
Doc,
Elem,
)
__all__ = [
"ComplexType",
"Doc",
"Elem",
]
| StarcoderdataPython |
4976165 | # ====================================================================
# 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 re... | StarcoderdataPython |
3322743 | <gh_stars>0
# Generated by Django 3.1.5 on 2021-03-02 11:52
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='tutorial',
n... | StarcoderdataPython |
11351455 | import codecs
import re
import encodings
from typing import Tuple
utf8 = encodings.search_function("utf8")
repl_table = {
"if!": "for _BYFON_DUMMY in",
"while! (.*?):": r"with byfon.while_(\1):",
"whilex! (.*?):": r"with byfon.while_expr(\1):",
"or!": "|",
"and!": "&",
"<-": "|=",
r"\.not... | StarcoderdataPython |
5118179 | import csv
from collections import defaultdict, namedtuple
import os
from urllib.request import urlretrieve
from pathlib import Path
"""
From PyBites Bite 30: https://codechalleng.es/bites/30/
"""
BASE_URL = 'https://bites-data.s3.us-east-2.amazonaws.com/'
TMP = '/tmp'
base_dir = Path(__file__).resolve().parent
fnam... | StarcoderdataPython |
6567644 | # Generated by Django 3.0.8 on 2020-08-17 22:17
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import jutil.modelfields
import jutil.validators
class Migration(migrations.Migration):
replaces = [
("jbank", "0001_initial"),
("jbank", "0002_a... | StarcoderdataPython |
3305751 | import argparse
import os
from src.utils import utils_files, utils_visualization
from src.constants.constants import NumericalMetrics
from src.evaluators.habitat_sim_evaluator import HabitatSimEvaluator
def main():
# parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument("--log-dir-d... | StarcoderdataPython |
1825128 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : pymdb.py
# Author : <NAME>
# Date : 07.11.2015
# Last Modified Date: 07.11.2017
# Last Modified By : <NAME>
from __future__ import print_function
import json
import string
try:
from urllib.request import urlopen
from u... | StarcoderdataPython |
3246750 | # 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
#
# Unless required by ap... | StarcoderdataPython |
12826189 | <gh_stars>1-10
"""
To use, make sure that pyJsonAttrPatternFactory.py is in your MAYA_PLUG_IN_PATH
then do the following:
import maya
maya.cmds.loadPlugin("pyJsonAttrPatternFactory.py")
maya.cmds.listAttrPatterns(patternType=True)
// Return: ["json"]
"""
import os
import sys
import json
import traceback
i... | StarcoderdataPython |
5092537 | #!/usr/bin/python3
import random
from random import randint
import string
import sys
class bcolors:
red = '\033[91m'
yellow = '\033[93m'
green = '\033[92m'
cyan = '\033[96m'
reset = '\033[0m'
def main():
length = 8
try:
if len(sys.argv[1:]) > 1:
return print(f"The accepted arguments are:\n{printInColor(b... | StarcoderdataPython |
244504 | ##
# Copyright (c) 2012-2017 Apple 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 l... | StarcoderdataPython |
5082675 | <gh_stars>0
class Event:
"""A representation of an event in bangarang."""
def __init__(self, metric=0.0, host="", service="", sub_service="", occurences=0, tags={}, status=0):
self.host = host
self.metric = metric
self.service = service
self.sub_service = sub_service
self.occurences = occurences
self.ta... | StarcoderdataPython |
6678099 |
import unittest
from osbot_jira.api.jira_server.API_Jira import API_Jira
from osbot_utils.utils.Dev import Dev
class Test_API_Jira(unittest.TestCase):
def setUp(self):
self.api = API_Jira()
# check connection
def test_jira_server_info(self):
jira = self.api.jira()
assert jira... | StarcoderdataPython |
8169804 | # -*- coding: utf-8 -*-
# Copyright (c) 2020 DDN. All rights reserved.
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
from collections import namedtuple
import re
from django.db import models
from django.db.models import CASCADE
class Nid(models.Model):
""... | StarcoderdataPython |
3516062 | <reponame>AlexanderJenke/nsst
import pickle
import numpy as np
import europarl_dataloader as e_dl
DATASET_PATH = "output/europarl-v7.de-en.de.clean"
TRAIN_STEP_SIZE = 20
THRESHOLD = 4
# MODEL_PATH = "output/tss20_th4_nSt200_nIt101.pkl"
def main(MODEL_PATH):
print(MODEL_PATH)
lines = e_dl.load_clean_datase... | StarcoderdataPython |
6417340 | from django.db import models
from django.contrib.auth import get_user_model
import os
def upload_image_to(instance, filename):
user_id = str(instance.user.id)
return os.path.join('image', user_id, filename)
class Profile(models.Model):
user = models.OneToOneField(
get_user_model(), unique=True, ... | StarcoderdataPython |
1639943 | '''
Utilities for logging things that happen during the skeleton/rig creation so
the users can be warned appropriately.
'''
from pymel.core import cmds, dt, listRelatives
import pdil
from . import node
def findRotatedBones(joints=None):
'''
Checks joints (defaulting to the )
'''
if not joints:
... | StarcoderdataPython |
374350 | <filename>stream/ciphers.py<gh_stars>0
# Shift cipher
def shift(plain, key):
if plain.isalnum() == False:
raise ValueError("Plaintext should be alphanumeric")
ctext = ""
for c in plain:
if c.islower():
ctext += chr((ord(c) - ord('a') + key) % 26 + ord('a'))
elif... | StarcoderdataPython |
5105684 | <gh_stars>10-100
from subprocess import PIPE, Popen
from sys import argv
from operator import itemgetter
import math, itertools, time
from random import expovariate
from numpy import array,save,vstack,random,arange
from collections import namedtuple
import click
mili_p_s = 1000
s_p_m = 60
m_p_h = 60
h_p_d = 24
d_p_y... | StarcoderdataPython |
163520 | # Generated by Django 3.1.1 on 2020-09-27 13:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app_users', '0001_initial'),
('curriculum', '0005_auto_20200927_1914'),
]
operations = [
migrations.RenameModel(
old_name='Comme... | StarcoderdataPython |
9773394 | """Accounts forms module."""
from math import floor
from django import forms
from django.db.models import Q
from django.contrib.auth import forms as auth_forms
from django.contrib.auth import password_validation
from django.contrib.sites.shortcuts import get_current_site
from django.conf import settings
from django.cor... | StarcoderdataPython |
1709684 | from rest_framework.serializers import ModelSerializer
from core.models import Todo
class TodoSerializer(ModelSerializer):
class Meta:
model = Todo
fields = ('__all__')
| StarcoderdataPython |
11274287 | <gh_stars>1-10
import requests
def ask_qaqash(text="hi cutie pie"):
url = "http://qaqash.com/api/ask"
data = {"language_id": "1", "question": text}
r = requests.post(url, data).json()
return r["content"]
if __name__ == "__main__":
print(ask_qaqash("are you alive?"))
| StarcoderdataPython |
1739421 |
SvelteFiles = provider("transitive_sources")
def get_transitive_srcs(srcs, deps):
return depset(
srcs,
transitive = [dep[SvelteFiles].transitive_sources for dep in deps],
)
SVELTE_ATTRS = {
"entry_point": attr.label(allow_files = True, single_file = True),
"deps": attr.label_list(),
"srcs"... | StarcoderdataPython |
12836881 | <reponame>ultimatezen/felix
"""
Tests for MemoryEngine::RemoteMemory
"""
import unittest
import cPickle
from cStringIO import StringIO
import mock
from FelixMemoryServes import MemoryEngine
class WebMocker(unittest.TestCase):
def set_request_val(self, val):
self.req_val = cPickle.dumps(v... | StarcoderdataPython |
12855919 | <reponame>bpneumann/django-raster<filename>raster/migrations/0006_auto_20141016_0522.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('raster', '0005_auto_20141014_0955'),
]
opera... | StarcoderdataPython |
325284 | import unittest
from tap_s3_csv import merge_dicts
class TestDictionaryMerge(unittest.TestCase):
def test_merge_dicts(self):
self.assertEqual(
merge_dicts({'a': 1}, {'a': 2}),
{'a': 2})
self.assertEqual(
merge_dicts({'a': 1}, {'b': 2}),
{'a': 1, '... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.