id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3324181 | <filename>sites_multidb/middleware.py
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import HttpResponseNotFound
from .utils import site_class
HOST_CACHE = {}
class DynamicSiteMiddleware:
def __init__(self, get_response):
self.get_response = get_response
... | StarcoderdataPython |
138290 | <reponame>macbre/Mike<filename>mycroft_holmes/sources/athena.py
"""
AWS Athena class
"""
from pyathena import connect
from .base import DatabaseSourceBase
class AthenaSource(DatabaseSourceBase):
"""
Returns a number result for a given SQL query run on AWS Athena.
https://aws.amazon.com/athena/
####... | StarcoderdataPython |
1652257 | <reponame>ereide/pyga-camcal
import numpy as np
from pygacal.common.cgatools import *
#TODO: from clifford_tools.common.g3c.core import *
from .costfunction import ( sumLineSquaredErrorCost, line2lineErrorCost,
sumPlaneSquaredErrorCost, plane2planeErrorCost,
... | StarcoderdataPython |
3314814 | # Bank
import time as t
import os
try :
with open("balance.txt") as f:
with open("balance.txt","r") as f:
read = f.read()
if read == "":
with open("balance.txt","w") as f:
write = f.write("0")
except FileNotFoundError:
with open("balance.txt","w") as f:
f.write("0")
info = print... | StarcoderdataPython |
3311144 | from mongoengine import (
BooleanField,
DateTimeField,
IntField,
StringField,
ObjectIdField,
ListField,
EmbeddedDocument,
EmbeddedDocumentField,
)
from maestro_api.db.mixins import CreatedUpdatedDocumentMixin
from maestro_api.libs.datetime import strftime
class RunConfigurationSchedule... | StarcoderdataPython |
100800 | from simplified_scrapy.core.spider import Spider# as SP
from simplified_scrapy.simplified_doc import SimplifiedDoc
# class Spider(SP):
# pass | StarcoderdataPython |
1640751 | #!/usr/bin/python
VERSION = 0.92
#---------------------------------
# BAGEL: Bayesian Analysis of Gene EssentaLity for python 3
# (c) <NAME>, 02/2015.
# modified 12/2019 for random seed option
# Free to modify and redistribute with attribtuion
#---------------------------------
from numpy import *
import scipy.st... | StarcoderdataPython |
4908 | <reponame>ProtKsen/pgame
"""Text parts."""
SEPARATOR = '----------------------------------'
CONT_GAME = 'enter для продолжения игры'
GREETING = 'Добро пожаловать в игру ''Сундук сокровищ''!\n' \
'Попробуй себя в роли капитана корабля, собери ' \
'команду и достань все сокровища!'
NAME_QUESTION ... | StarcoderdataPython |
1766702 | import pytest
from schemaperfect import SchemaBase, SchemaModuleGenerator
@pytest.fixture
def schema():
return {
'definitions': {
'Person': {
'properties': {
'name': {'type': 'string'},
'age': {'type': 'integer'},
}
... | StarcoderdataPython |
3220701 | point = []
intrin = {"model": 0}
def rs2_project_point_to_pixel(pixel[2], intrin, point[3]):
x = point[0] / point[2]
y = point[1] / point[2]
if intrin.model == 0:
r2 = x * x + y * y
| StarcoderdataPython |
1771797 | <reponame>PingHuskar/hackerrank
# Mathematics > Linear Algebra Foundations > Eigenvalue of a Matrix I
# Basic problems related to eigenvalues.
#
# https://www.hackerrank.com/challenges/eigenvalue-of-matrix-1/problem
#
import numpy as np
M = np.matrix([[1, -3, 3],
[3, -5, 3],
[6, -6, 4]])... | StarcoderdataPython |
3394092 | <gh_stars>1-10
# Copyright 2021 <NAME> (rafsaf). 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... | StarcoderdataPython |
1638889 | <filename>kubernetes/models/v1/ConfigMapVolumeSource.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
from kubernetes.utils import is_valid_string, filter_model
from kubernetes.models.v1.K... | StarcoderdataPython |
1635267 | <filename>hallo/test/modules/server_control/test_list_servers.py
from hallo.events import EventMessage
from hallo.server import Server
from hallo.test.server_mock import ServerMock
def test_no_servers(hallo_getter):
test_hallo = hallo_getter({"server_control"}, disconnect_servers=True)
# Send command
test... | StarcoderdataPython |
1736074 | #네이버 실시간 검색 순위
import requests
import time
from bs4 import BeautifulSoup
loopNum = 1
while True:
print("*"*30)
response = requests.get('https://www.naver.com/')
assert response.status_code is 200
dom = BeautifulSoup(response.content, "html.parser") # (print(dom))
ranking_elements = dom.select("li.ah... | StarcoderdataPython |
1701380 | <gh_stars>0
import time
import unittest
from algorithms.main.sets.permutations_without_reps import permute_without_reps as pnr, permute_without_reps_two as pnrtwo, permute_without_reps_three as pnrthree
class TestPermutationsWithoutReps(unittest.TestCase):
def setUp(self):
self._started_at = time.time()
... | StarcoderdataPython |
49124 | <filename>api/v1/utilities/su.py
import os
class Guard:
_preserved_uid: int
_preserved_gid: int
_uid: int
_gid: int
def __init__(self, uid: int, gid: int):
# safety measure
if uid == 0 or gid == 0:
print("Tried to su Guard to root :(")
os.exit(-1)
... | StarcoderdataPython |
85682 | <filename>phl_courts_scraper/court_summary/core.py
"""Module for parsing court summary reports."""
import collections
from operator import itemgetter
from pathlib import Path
from typing import Any
from ..base import DownloadedPDFScraper
from ..utils import get_pdf_words
from . import utils
from .schema import CourtS... | StarcoderdataPython |
3397209 | <filename>part_2_read_test_json.py
import test_data
import json
# Creates and returns a GameLibrary object(defined in test_data) from loaded json_data
def make_game_library_from_json(json_data):
# Initialize a new GameLibrary
game_library = test_data.GameLibrary()
# Loop through the json_data
for gam... | StarcoderdataPython |
1745329 | from google.appengine.ext import ndb
context = ndb.get_context()
context.set_cache_policy(lambda key: False)
context.set_memcache_policy(lambda key: False)
| StarcoderdataPython |
1723768 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
珂珂喜欢吃香蕉。这里有 N 堆香蕉,第 i 堆中有 piles[i] 根香蕉。警卫已经离开了,将在 H 小时后回来。
珂珂可以决定她吃香蕉的速度 K (单位:根/小时)。每个小时,她将会选择一堆香蕉,从中吃掉 K 根。如果这堆香蕉少于 K 根,她将吃掉这堆的所有香蕉,然后这一小时内不会再吃更多的香蕉。
珂珂喜欢慢慢吃,但仍然想在警卫回来前吃掉所有的香蕉。
返回她可以在 H 小时内吃掉所有香蕉的最小速度 K(K 为整数)。
示例 1:
输入: piles = [3,6,7,... | StarcoderdataPython |
114800 | <reponame>dd2t/desafio<filename>my-app/api/api.py
from flask import Flask, render_template, url_for, request, redirect
import pymongo
from pymongo import MongoClient
import os
from password import passwd
app = Flask(__name__, static_folder='./build', static_url_path='/')
# Database
cluster = pymongo.MongoClient(passw... | StarcoderdataPython |
1693822 | import importlib
import logging
import numpy as np
import os
import os.path as osp
import time
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import _LRScheduler
from torch.utils.data import ConcatDataset
from bisect import bisect_right
from functools import partial
from six.moves import map, ... | StarcoderdataPython |
4827504 | import re
from datetime import datetime
from unittest import TestCase
from difflib import SequenceMatcher
import logging
from kqml.kqml_performative import KQMLPerformative
logging.basicConfig(format='%(levelname)s: %(name)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger('integration... | StarcoderdataPython |
51999 | <reponame>GYosifov88/Python-Basics<gh_stars>0
days = int(input())
type_of_room = input()
feedback = input()
price = 0
nights = days - 1
if type_of_room == 'room for one person':
price = 18
cost = nights * price
elif type_of_room == 'apartment':
price = 25
cost = nights * price
if days < 10:
... | StarcoderdataPython |
187763 | <gh_stars>0
from cipher_xs2423 import cipher_xs2423
import pytest
def cipher(text, shift, encrypt=True):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
assert isinstance(shift, int), 'The shift parameter should be an integer'
for c in text:
index = alphabet.fin... | StarcoderdataPython |
150841 | class PageEffectiveImageMixin(object):
def get_effective_image(self):
if self.image:
return self.image
page = self.get_main_language_page()
if page.specific.image:
return page.specific.get_effective_image()
return ''
| StarcoderdataPython |
199175 | <filename>tests/async/test_listeners.py
# Copyright (c) Microsoft 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 requir... | StarcoderdataPython |
3350815 | from decimal import Decimal
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.views.generic.base import View
from django.conf import settings
from django.urls import reverse_lazy
from django.contrib import messages
from django.db import transaction... | StarcoderdataPython |
3383234 | <filename>server/models.py
import sqlalchemy as sa
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
Base: DeclarativeMeta = declarative_base()
class Logger(Base):
__tablename__ = "loggers"
id = sa.Column(sa.Integer, sa.Sequence("logger_id_seq"), primary_key=True)
name = sa.Column... | StarcoderdataPython |
165175 | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
from eight import *
from .lca import LCA
from numpy.linalg import solve
class DenseLCA(LCA):
def solve_linear_system(self):
"""
Master solution function for linear system :math:`Ax=B`.
To most numerical analyst... | StarcoderdataPython |
3331490 | import hashlib
import os
import shutil
import subprocess
from django.views import generic
from django.template.response import TemplateResponse
from src.apps.main.forms import BinaryViewForm
class HomepageView(generic.FormView):
template_name = 'main/homepage.html'
form_class = BinaryViewForm
def form_... | StarcoderdataPython |
16720 | """TrafficSignDataset dataset."""
from .TrafficSignsDataset import Trafficsignsdataset
| StarcoderdataPython |
81359 | <filename>cache_dependencies/mixins.py
try:
import _thread
except ImportError:
import thread as _thread # Python < 3.*
class ThreadSafeDecoratorMixIn(object):
def __init__(self, delegate):
self._delegate = delegate
self._thread_id = self._get_thread_id()
@staticmethod
def _get_t... | StarcoderdataPython |
3371173 | <filename>sqswatcher/plugins/torque.py
# Copyright 2013-2016 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apach... | StarcoderdataPython |
1645838 | <filename>src/learning/models/vae/unet_vae.py<gh_stars>10-100
""" Full assembly of the parts to form the complete network """
import numpy as np
from torch import nn
from typing import *
from .base_vae import BaseVAE
from ..unet.unet_parts import *
from src.dataloaders.dataloader_meta_info import DataloaderMetaInfo
f... | StarcoderdataPython |
3358877 | <reponame>tk1012/ion-kit
# https://github.com/fixstars/ion-csharp/blob/master/test/Test.cs
from ionpy import Node, Builder, Buffer, PortMap, Port, Param, Type, TypeCode
import numpy as np # TODO: rewrite with pure python
def test_all():
t = Type(code_=TypeCode.Int, bits_=32, lanes_=1)
input_port = Port(key='i... | StarcoderdataPython |
14782 | import zeep
import asyncio, sys
from onvif import ONVIFCamera
import cv2
import numpy as np
import urllib
from urllib.request import urlopen
IP="192.168.2.22" # Camera IP address
PORT=80 # Port
USER="admin" # Username
PASS="<PASSWORD>" # Password
XMAX = 1
XMIN = -1
YMAX = 1
YMIN = -1
movere... | StarcoderdataPython |
1792748 | <filename>frontend/sphinx/tests/test_button.py
import unittest
from widget.button import Button, button_dictionary
class TestButton(unittest.TestCase):
def test_constructor(self):
button = Button("run_button")
self.assertEqual(button.name, button_dictionary["run_button"]["name"], msg="button name... | StarcoderdataPython |
1608057 | <filename>aliyun-python-sdk-mts/aliyunsdkmts/__init__.py
__version__ = "2.6.1" | StarcoderdataPython |
25901 | import sys
import csv
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("lp_files", help="The label pair need to be converted")
parser.add_argument("dir2pubmed", help="The directory to the place for pubmed articles")
parser.add_argument('out_path', help="The path to store finaltraining ... | StarcoderdataPython |
4834263 | # Ejemplo de como manejar excepciones (Exception handling)
# Definimos una lista
a = [1,2]
try:
print(a[2]) #Tratamos de imprimir un indice que no existe!
except IndexError:
print("The requested index is not available. The highest available index is %s" % (len(a)-1))
except:
print("An unknown error occur... | StarcoderdataPython |
1638111 | # -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2013, 2015 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany th... | StarcoderdataPython |
3327007 | # Generated by Django 3.2.8 on 2021-11-04 16:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('vault', '0006_auto_20211103_1452'),
]
operations = [
migrations.RenameField(
model_name='keys',
old_name='pwd',
... | StarcoderdataPython |
1622561 | <reponame>Clinical-Genomics/scout<filename>scout/commands/load/exons.py
import logging
from datetime import datetime
from pprint import pprint as pp
import click
from flask.cli import with_appcontext
from scout.load import load_exons
from scout.server.extensions import store
from scout.utils.handle import get_file_ha... | StarcoderdataPython |
116956 | from discord.ext import commands
from backup_bot.logger import logger
from os.path import isdir
from os import mkdir
import shelve
from datetime import datetime
from discord import File, Embed
from collections import OrderedDict
extension_name = "backup"
logger = logger.getChild(extension_name)
@commands.command("ba... | StarcoderdataPython |
3241093 | <reponame>trisadmeslek/V-Sekai-Blender-tools
preview_verts = None
preview_uvs = None
preview_is_quads = False
def set_preview_data(verts, uvs, is_quads=True):
"""
Set the preview data for SprytileGUI to draw
:param verts:
:param uvs:
:param is_quads:
:return:
"""
global preview_verts, p... | StarcoderdataPython |
1768485 | # Generated by Django 2.1.1 on 2018-09-03 16:11
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrati... | StarcoderdataPython |
157700 | <gh_stars>10-100
"""
This code enables geolocation of the ISS LIS background datasets
http://dx.doi.org/10.5067/LIS/ISSLIS/DATA206
http://dx.doi.org/10.5067/LIS/ISSLIS/DATA207
Notable required packages: xarray, cython, cartopy
<NAME>
<EMAIL>
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
... | StarcoderdataPython |
1658421 | <reponame>databio/pararead<filename>pararead/exceptions.py
""" Specific exception types. """
__author__ = "<NAME>"
__email__ = "<EMAIL>"
class CommandOrderException(Exception):
""" The parallel reads processor needs certain method call sequence. """
def __init__(self, reason=""):
super(CommandOrderE... | StarcoderdataPython |
3232720 | #!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
__author__ = ["<NAME>"]
__all__ = ["BaseMetric"]
import inspect
from sklearn.base import BaseEstimator
class BaseMetric(BaseEstimator):
"""Base class for defining metrics in sktime.
Ext... | StarcoderdataPython |
168416 | <reponame>kkaris/indra_cogex
from inspect import Signature, signature
from typing import (
Any,
Callable,
Counter,
Dict,
Iterable,
List,
Mapping,
Tuple,
Type,
Optional,
Set,
)
from docstring_parser import parse
from indra.statements import Agent, Evidence, Statement
from in... | StarcoderdataPython |
1786539 | from otree.api import *
c = Currency
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'subject_email'
players_per_group = None
num_rounds = 1
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
pass
class Player(BasePlayer):
subject_email = mo... | StarcoderdataPython |
3257576 | import contextlib
import unittest
from parflow.subset.clipper import MaskClipper, BoxClipper
import parflow.subset.utils.io as file_io_tools
from parflow.subset.mask import SubsetMask
import numpy as np
import tests.test_files as test_files
import os
class RegressionClipTests(unittest.TestCase):
"""
Regressio... | StarcoderdataPython |
132417 | import hashlib
import logging
import urllib.parse
import uuid
from django.conf import settings
from django.contrib.auth import authenticate, login
from django.forms import ValidationError
from django.forms.utils import ErrorList
from django.http import (
HttpResponseForbidden,
HttpResponseRedirect,
)
from djan... | StarcoderdataPython |
44954 | <filename>TorPool/tor_method.py
# coding: utf-8
import subprocess
import shutil
import sys
import os
class TorMethod(object):
'''tor 代理伺服器製作
:::參數說明:::
torrc_dir: torrc要儲存的位置(必要)
tordata_dir: torrc內DataDirectory的資訊(必要)
__process: tor的process控制器, 可以使用TorMethod.get_process取得
__torname: torrc檔案和資料... | StarcoderdataPython |
5117 | <gh_stars>0
"""High-level search API.
This module implements application-specific search semantics on top of
App Engine's search API. There are two chief operations: querying for
entities, and managing entities in the search facility.
Add and remove Card entities in the search facility:
insert_cards([models.Card])... | StarcoderdataPython |
3319109 | <filename>obj_import_shape.py
#!python
# import a ESRI shape to vulcan objects
# input_shp: path to the shape file (the auxiliary files must also exist)
# object_layer: (optional) attribute that will be used as object layer
# object_name: (optional) attribute that will be used as object name
# object_group: (optio... | StarcoderdataPython |
1650603 | from pyteal import *
from algosdk.future import transaction
from algosdk.v2client import algod
import os
import pathlib
from util import deploy, get_private_key_from_mnemonic
#if Resource: application_args = (asset_total, asset_unit_name, asset_name, asset_url, asset_metadata_hash)
# Resource must include the address ... | StarcoderdataPython |
1721747 | <filename>tensorflow_transform/saved/saved_transform_io_v2.py
# 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/l... | StarcoderdataPython |
3250009 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# 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 applicab... | StarcoderdataPython |
3378484 | import zmq
import socket
data = []
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def tcp_stream():
global sock, data
dataTemp = ""
while '\n' not in dataTemp:
dataTemp += str(sock.recv(2048),"utf-8")
dataTemp = dataTemp.strip("\r\n").split(";")
#print(dataTemp)
data.append(... | StarcoderdataPython |
20162 | ##############################################################################
# Copyright 2009, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must r... | StarcoderdataPython |
3376443 | <reponame>progressivis/ipytablewidgets
# Initial software, <NAME>, <NAME>, Copyright (c) Inria, BSD 3-Clause License, 2021
import os
from os.path import join as pjoin
import json
from .._frontend import npm_module_name, npm_package_version
here = os.path.dirname(os.path.abspath(__file__))
def test_frontend():
p... | StarcoderdataPython |
155779 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import pytest
import gc
import copy
import numpy as np
import pandas as pd
try:
import geopandas as gpd
import shapely.geo... | StarcoderdataPython |
3237619 | <reponame>techthiyanes/malaya-speech
from malaya_speech.utils import (
check_file,
load_graph,
generate_session,
nodes_session,
)
from malaya_speech.model.synthesis import (
Tacotron,
Fastspeech,
Fastpitch,
GlowTTS,
GlowTTS_MultiSpeaker
)
from malaya_speech.path import STATS_VOCODER
... | StarcoderdataPython |
123872 | from biobb_common.tools import test_fixtures as fx
from biobb_analysis.ambertools.cpptraj_rgyr import cpptraj_rgyr
class TestCpptrajRgyrDocker():
def setUp(self):
fx.test_setup(self,'cpptraj_rgyr_docker')
def tearDown(self):
fx.test_teardown(self)
pass
def test_rgyr_docker(self):... | StarcoderdataPython |
3245555 | <filename>creations/protype/simpleLayer.py<gh_stars>0
from copy import copy, deepcopy
class simpleLayer():
background = [0,0,0,0]
content = 'blank'
def getContent(self):
return self.content
def getBackgroud(self):
return self.background
def paint(self,painting):
self.content=... | StarcoderdataPython |
95437 | <filename>Project 3/Q1-Q3.py
import numpy as np
### Q1
class convolution():
def __init__(self, n_filters, kernel_size, padding, stride, activation=None):
self.output_channel = n_filters
self.filter_size = kernel_size[0]
if padding == "VALID":
s... | StarcoderdataPython |
22209 | import random
TUPLE_SIZE = 4
DIGIT_BASE = 10
MAX_GUESS = DIGIT_BASE ** TUPLE_SIZE
def yield_all():
for i in xrange(DIGIT_BASE ** TUPLE_SIZE):
tup = tuple([int(x) for x in '%04d' % i])
assert len(tup) == TUPLE_SIZE
for l in tup:
if tup.count(l) != 1:
break
... | StarcoderdataPython |
1641830 | <gh_stars>1-10
"""Copyright 2018 <NAME> and The Netherlands Organisation for
Applied Scientific Research TNO.
Licensed under the MIT license.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software witho... | StarcoderdataPython |
3246392 |
from bcc import BPF
prog = """
int hello(void *ctx) {
bpf_trace_printk("hello, world!\\n");
return 0;
}
"""
# load BPF program
b = BPF(text=prog)
b.attach_kprobe(event="sys_clone", fn_name="hello")
print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "MESSAGE"))
while 1:
try:
(task, pid, cpu, flags... | StarcoderdataPython |
1797747 | from django import http
from django.core.paginator import Paginator, InvalidPage
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from satchmo.configuration import config_value
from satchmo.product.models import Product
from satchmo.productratings.queries imp... | StarcoderdataPython |
42423 | import numpy as np
import pandas as pd
from .scm import SCM
class DataGenerator:
def generate(self, scm: SCM, n_samples: int, seed: int):
pass
class SimpleDataGenerator(DataGenerator):
def generate(self, scm: SCM, n_samples: int, seed: int):
"""
Generates date according to the given... | StarcoderdataPython |
3310543 | from .x import *
print("init")
| StarcoderdataPython |
4835327 | import pytz
import uuid
from django.db import models
from django.urls import reverse
from django.utils import timezone
class Registrante(models.Model):
name = models.CharField(max_length=240)
legal_uid = models.CharField(max_length=90, db_index=True)
uid = models.UUIDField(default=uuid.uuid4, editabl... | StarcoderdataPython |
31220 | <reponame>tassotirap/data-science
#!/usr/bin/python
import sys
import csv
reader = csv.reader(sys.stdin, delimiter='\t')
writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)
userInfo = None
for line in reader:
thisType = line[1]
if thisType == 'A':
userInfo = line
... | StarcoderdataPython |
157356 | <filename>chatette_qiu/units/intent/example.py<gh_stars>0
from chatette_qiu.units import Example
class IntentExample(Example):
def __init__(self, name, text=None, entities=None):# -> None:
super(IntentExample, self).__init__(text, entities)
self.name = name
@classmethod
def from_example(c... | StarcoderdataPython |
13321 | import time
import pytest
from flask import g
from flask import session
import paho.mqtt.client as paho
from SmartSleep.db import get_db
from flask import json
import runpy
msg_nr = 0
messages = [""]
broker = 'broker.emqx.io'
port = 1883
def update_contor():
global msg_nr
msg_nr += 1
def on_message(client... | StarcoderdataPython |
1670316 | """Actions for linking object code produced by compilation"""
load(":private/pkg_id.bzl", "pkg_id")
load(":private/set.bzl", "set")
load(":private/path_utils.bzl", "get_lib_name")
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":private/packages.bzl", "expose_packages")
def _backup_path(target):
"""Return a p... | StarcoderdataPython |
1760814 | """
Copyright (c) 2017 Intel 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 |
180097 | <filename>m2py/thermo/script/test_gas.py
from m2py.thermo.marktable import read_data_tables
from m2py.thermo import gas as g
from pprint import pprint
from m2py.utils import resource_path
tables = read_data_tables(resource_path("../data/gas_test_data.txt"))
gases = list(tables.keys())
def test_fuction(function, gas... | StarcoderdataPython |
1708650 | <reponame>contek-io/contek-tusk
from __future__ import annotations
import atexit
from datetime import datetime
from threading import Timer, RLock
from typing import Optional, Union, Dict
import contek_tusk as tusk
from contek_tusk.batching_config import BatchingConfig
from contek_tusk.entry_input_normalizer import En... | StarcoderdataPython |
169649 | <gh_stars>0
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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... | StarcoderdataPython |
1667130 | # -*- coding: utf-8 -*-
"""
@author: TT
"""
import FileHelper as fh
import TypeHelper as th
import ziptozcta as zz
def LoadZipToZCTA():
fileName = r'Datafiles/zip_to_zcta10_nyc_with_NBH.csv'
return fh.readInCSVDicData(fileName, processZipToZCTA)
#process
def processZipToZCTA(fileList):
... | StarcoderdataPython |
1626922 | # imports
import stardust
import os
import inspect
from re import findall
class CustomStardustFilters:
rep = os.path.abspath(inspect.getfile(stardust.main.ctf)).strip('main.py') + 'filters/'
filters = rep + 'filters.txt'
info = rep + 'filters.info'
@classmethod
def get_number_of_filters(cls):
... | StarcoderdataPython |
1658739 | <gh_stars>1000+
#!/usr/bin/env python
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
def PathToNyc():
return os.path.join(
os.path.dirname(__file__), 'node_modules', 'nyc', 'bin', 'nyc... | StarcoderdataPython |
3277172 | # Generated by Django 3.2.12 on 2022-05-13 12:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('products', '0001_initial'),
migrations.swappable_dependency(se... | StarcoderdataPython |
3369880 | """
LeetCode Problem: 61. Rotate List
Link: hhttps://leetcode.com/problems/rotate-list/
Language: Python
Written by: <NAME>
Time Complexity: O(N)
Space Complexity: O(1)
"""
# Approach 1
class Solution:
def rotateRight(self, head: 'ListNode', k: 'int') -> 'ListNode':
# base cases
if not head:
... | StarcoderdataPython |
3349146 | # Copyright (c) 2018, 2020 ARM Limited
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
#... | StarcoderdataPython |
76807 | from __future__ import print_function,division
import os,sys,re
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import h5py
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage import median_filter
from scipy.optimize import leastsq, curve_fit
from scipy.signal import lombscargl... | StarcoderdataPython |
179732 | from setuptools import setup, find_packages
import datetime
import os
YEAR = datetime.date.today().year
__author__ = "<NAME>"
__version__ = "0.3.16"
__license__ = "MIT"
__copyright__ = u'%s, <NAME>' % YEAR
# Add Travis build id if not deploying a release (tag)
if os.environ.get("TRAVIS", "") == "true":
build_id... | StarcoderdataPython |
8227 | import os
import sys
import random
def get_next_wallpaper(curr_path):
lst_dir = os.listdir()
rand_index = random.randint(0, len(lst_dir) - 1)
return lst_dir[rand_index]
def get_wall_dir():
return "/Users/MYOUNG/Pictures/mmt"
def main():
script = "osascript -e 'tell application \"Finder\" to s... | StarcoderdataPython |
3364767 | <gh_stars>10-100
#!/usr/bin/env python
import rospy
import sys
import moveit_commander
from geometry_msgs.msg import PoseStamped, Pose
from moveit_commander import MoveGroupCommander, PlanningSceneInterface
from moveit_msgs.msg import PlanningScene, ObjectColor
from moveit_msgs.msg import Grasp, GripperTranslation, Mo... | StarcoderdataPython |
161128 | <reponame>LR-POR/tools
from conllu import parse
import joblib
DEPRELS = ['nsubj','obj','iobj','xcomp','ccomp','csubj','expl','nsubj:pass','aux:pass']
## Funçoes auxiliares
def binary_search(x,l):
""" Esse algorítmo é o algorítmo de busca binária, mas ele retorna
qual o índice o qual devo colocar o elemento ... | StarcoderdataPython |
3390183 | <reponame>fer-moreira/MYQT<filename>MYQT_Application/assets/UI/Scripts/ConnectorWindow.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\assets\UI\Layout\ConnectorWindow.ui'
#
# Created by: PyQt5 UI code generator 5.12.1
#
# WARNING! All changes made in this file will be lost!
from Py... | StarcoderdataPython |
4832201 | <filename>D_linknet34.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 2 20:31:14 2018
@author: pooh
"""
from torch import nn
import torch
from torchvision import models
import torchvision
from torch.nn import functional as F
def conv3x3(in_, out):
return nn.Conv2d(in_, out, 3, padding=... | StarcoderdataPython |
3399498 | <filename>opencv/misc/simple_demo/BGRvsHSV/BGRvsHSV.py
import cv2
import numpy as np
def nothing(x):
pass
bgr_img = np.zeros((500, 300, 3), np.uint8)
hsv_img = np.copy(bgr_img)
cv2.namedWindow('BGR')
cv2.namedWindow('HSV')
cv2.createTrackbar('B', 'BGR', 0, 255, nothing)
cv2.createTrackbar('G', 'BGR', 0, 255, no... | StarcoderdataPython |
38052 | <filename>crawlers/news/items.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item, Field
from scrapy.loader.processors import TakeFirst, Join
class NewsItem(Item):
url = Fi... | StarcoderdataPython |
3294999 | import maya.cmds as cmds
def multObjImport():
files_to_import = cmds.fileDialog2(fileFilter = '*.obj', dialogStyle = 2, caption = 'import multiple object files', fileMode = 4)
for file_to_import in files_to_import:
names_list = file_to_import.split('/')
object_name = names_list[-1].replace('.o... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.