id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
183047 | # Generated by Django 2.1.8 on 2019-04-15 09:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('froide_crowdfunding', '0004_contribution_public'),
]
operations = [
migrations.AddField(
model_name='crowdfunding',
... | StarcoderdataPython |
3329082 | import json
from base64 import b64encode
from types import ModuleType
from requests import session
from . import resources
from .constants import URL, Stage
from .utils import capitalize_camel_case
from .version import VERSION
RESOURCE_PREFIX = "_resource_"
RESOURCE_CLASSES = {}
for name, module in resources.__dict... | StarcoderdataPython |
3270178 | import databench
class Parameters(databench.Analysis):
@databench.on
def test_fn(self, first_param, second_param=100):
"""Echo params."""
yield self.emit('test_fn', (first_param, second_param))
@databench.on
def test_action(self):
"""process an action without a message"""
... | StarcoderdataPython |
3244840 | #!/usr/bin/env python
# Copyright (c) 2012 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.
""" Source file for floating builder testcases."""
import calendar
import datetime
import itertools
import os
import time
import u... | StarcoderdataPython |
3229461 | <filename>venv/lib/python3.7/site-packages/scapy/modules/p0f.py
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) <NAME> <<EMAIL>>
# This program is published under a GPLv2 license
"""
Clone of p0f passive OS fingerprinting
"""
from __future__ import absolute... | StarcoderdataPython |
1776476 | import unittest
from solutions.TST import one
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(one.get(), 1)
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
154487 | from requests.auth import HTTPBasicAuth
def apply_updates(doc, update_dict):
# updates the doc with items from the dict
# returns whether or not any updates were made
should_save = False
for key, value in update_dict.items():
if getattr(doc, key, None) != value:
setattr(doc, key, v... | StarcoderdataPython |
39030 | <filename>hermione/module_templates/__IMPLEMENTED_BASE__/src/ml/preprocessing/preprocessing.py
import pandas as pd
from ml.preprocessing.normalization import Normalizer
from category_encoders import *
import logging
logging.getLogger().setLevel(logging.INFO)
class Preprocessing:
"""
Class to perform data pre... | StarcoderdataPython |
1608688 | <filename>tests/ea/plotters/progress/conftest.py
import pandas as pd
import pytest
import stk
from .case_data import CaseData
def _get_topology_graph() -> stk.polymer.Linear:
return stk.polymer.Linear(
building_blocks=(
stk.BuildingBlock('BrCCBr', [stk.BromoFactory()]),
),
re... | StarcoderdataPython |
174501 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import edward as ed
from edward.models import Normal, Empirical
from scipy.special import erf
import importlib
import utils
importlib.reload(... | StarcoderdataPython |
3384052 | # Copyright (c) 2020 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 applic... | StarcoderdataPython |
3324600 | <filename>peacock/configure.py
#!/usr/bin/env python3
from build import ninja_common
build = ninja_common.Build("peacock")
build.generate(["regroup"], "peacock/build-regroup.sh", ["regroup.c"])
build.chicken_lib("fishbowl", [
"fishbowl/queue.scm",
"fishbowl/fishbowl.scm",
], where="peacock/fishb... | StarcoderdataPython |
64252 | # pylint: disable=wrong-import-position, wrong-import-order, invalid-name
"""
Invoke build script.
Show all tasks with::
invoke -l
.. seealso::
* http://pyinvoke.org
* https://github.com/pyinvoke/invoke
"""
###############################################################################
# Catch exceptions an... | StarcoderdataPython |
109655 | <filename>hydra/file.py
import os
class File:
def __init__(self, name=None, location=None):
"""
Create and store information about name and location of file.
Note:
Do not pass the file name and location as parameters if
you want to create a 'main.db' file in your d... | StarcoderdataPython |
3276733 | _msgs = []
def clear():
_msgs.clear()
def get():
return ",".join(_msgs)
def put(msg):
_msgs.append(msg)
| StarcoderdataPython |
3296958 | <reponame>neelpawarcmu/deep-learning-library<filename>homework-3/hw3p1/mytorch/gru_cell.py
import numpy as np
from activation import *
class GRUCell(object):
"""GRU Cell class."""
def __init__(self, in_dim, hidden_dim):
self.d = in_dim
self.h = hidden_dim
h = self.h
d = self.d... | StarcoderdataPython |
10538 | <gh_stars>0
'''
说明: loc和iloc有几个功能
1. 可以获取一行或者多行数据
2. 可以获取1列或多列数据
3. 可以获取某个单元格的数据
对应dataframe来说, 在不指定index和columns的情况下,iloc和loc一样
区别在于,iloc根据索引下标取值, loc根据索引值取值
'''
import numpy as np
import pandas as pd
def test_1():
# 按行取值
pf = pd.DataFrame([[1, 2], [3, 4]])
iloc_0 = pf.iloc[0]
loc_0 = pf.loc[0]
... | StarcoderdataPython |
3351441 | """empty message
Revision ID: 59f3082483dd
Revises: <PASSWORD>
Create Date: 2019-09-21 15:52:11.556530
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
# revision identifiers, used by Alembic.
revision = '<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def... | StarcoderdataPython |
4812928 | import pandas as pd
import numpy as np
from scipy import sparse
import os
import sys
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix, f1_score
import src.utils as utils
class HinDroid():
def __init__(self, B_mat, P_mat,... | StarcoderdataPython |
102355 | # -*- coding: utf-8 -*-
# Copyright: <NAME> <<EMAIL>>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import zipfile, os
import unicodedata
from anki.utils import tmpfile, json
from anki.importing.anki2 import Anki2Importer
class AnkiPackageImporter(Anki2Importer):
def run(self):
... | StarcoderdataPython |
129237 | <reponame>Giving-Tuesday/wbpy<filename>wbpy/tests/indicator_data.py
# -*- coding: utf-8 -*-
import datetime
import wbpy
class TestData(object):
""" API response data for testing. """
def __init__(self):
self.dataset = wbpy.IndicatorDataset(self.response, self.url, self.date)
class Yearly(TestData):
... | StarcoderdataPython |
1613661 | """
Easy PTVSD Module.
Contains any decorators or convenience functions for PTVSD.
"""
import ptvsd
class wait_and_break:
"""
Decorator to create ptvsd server, wait for attach, break into debugger, continue.
This pattern of using a class to make a decorator cleans up the double nested
functions need... | StarcoderdataPython |
174192 | from django.core.validators import MinValueValidator, MaxValueValidator
from PIL import Image
# to use own user class
from django.conf import settings
from django.db import models
class Ticket(models.Model):
class Meta:
ordering = ["-time_created"]
title = models.CharField(max_length=128)
descri... | StarcoderdataPython |
3299300 | import numpy as np
import numpy.linalg as LA
import scipy.io as sio # not working for me
import networkx as nx
import scipy as sp
import matplotlib.pyplot as plt
from matplotlib import cm
#from scipy.stats import entropy
from time import time
import random, math
# magic numbers
_smallnumber = 1E-6
class SNMF():
... | StarcoderdataPython |
1662827 | # Sample local settings file
# Copy this to localsettings.py and edit settings as needed
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: don't run... | StarcoderdataPython |
3372513 | <gh_stars>0
# Django settings for project.
import os
import urlparse
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = os.path.exists('.debug') or (os.environ.has_key('DEBUG') and os.environ['DEBUG'] == "1")
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('<NAME>', 'dontspamme'),
)
MANAGERS = ADMINS
import dj_d... | StarcoderdataPython |
1748863 | # By manish.17, contest: ITMO Academy. Двоичный поиск - 2, problem: (C) Very Easy Task
# https://codeforces.com/profile/manish.17
n, x, y = map(int, input().split())
alpha, omega = min(x, y), 10**18
if n == 1:
print(min(x, y))
quit()
while alpha < omega:
mid = (alpha + omega)//2
if (mid - min(x, y))/... | StarcoderdataPython |
8810 | import copy
import inspect
import json
import logging
import pytest
import re
import os
import shutil
import subprocess
import time
from datetime import datetime, timedelta
from configparser import ConfigParser, ExtendedInterpolation
from typing import Dict, List, Optional
from pyhttpd.certs import CertificateSpec
f... | StarcoderdataPython |
1762499 | """
TF-explain Library
The library implements interpretability methods as Tensorflow 2.0
callbacks to ease neural network's understanding.
"""
__version__ = "0.2.1"
try:
import cv2
except:
raise ImportError(
"TF-explain requires Opencv. " "Install Opencv via `pip install opencv-python`"
) from No... | StarcoderdataPython |
3282396 | from datetime import datetime, date, timedelta
import unittest
from businesstime import BusinessTime
from businesstime.holidays.usa import USFederalHolidays
class BusinessTimeTest(unittest.TestCase):
def setUp(self):
"""
Tests mostly based around January 2014, where two holidays, New Years Day
... | StarcoderdataPython |
1608608 | <reponame>ricklentz/tdw
from typing import Optional, Union, Tuple
from pathlib import Path
import os
from platform import system
from subprocess import check_output, Popen, call
import re
from psutil import pid_exists
class AudioUtils:
"""
Utility class for recording audio in TDW using [fmedia](https://stsaz.... | StarcoderdataPython |
1793245 | from django.http import HttpResponse
from django.shortcuts import render
from shoppingcartproject.productmodels import productmodel
from django.contrib import messages
def displayproduct(request):
return render(request, 'products.html') | StarcoderdataPython |
1753143 | import argparse
import os
import random
import shutil
import time
import warnings
import numpy as np
from progress.bar import (Bar, IncrementalBar)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.o... | StarcoderdataPython |
1619937 | from autodesk.scheduler import Scheduler
from autodesk.states import UP, DOWN
from pandas import Timedelta
def test_active_for_30minutes_with_60minute_limit_and_desk_down():
active_time = Timedelta(minutes=30)
limits = (Timedelta(minutes=60), Timedelta(minutes=30))
scheduler = Scheduler(limits)
delay... | StarcoderdataPython |
3339105 | <reponame>parikshitgupta1/leetcode<gh_stars>0
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
def invert(root):
if root == None:
return
else:
# temp = root
root.left, root.right = root.right, root.left
... | StarcoderdataPython |
1795400 | class Classification:
def __init__(self, decision=0, indexList=0):
self.cObject = ""
self.listOfClassifiedCorrectly = 0
self.listOfClassified = 0
def setCObject(self, a):
self.cObject = a
def setListOfClassifiedCorrectly(self, a):
self.listOfClassifiedCorrectly = a... | StarcoderdataPython |
3363824 | import os, platform, sys
import IDLC.idldocument as IDLDocument
import IDLC.idlproperty as IDLProperty
import IDLC.idlprotocol as IDLProtocol
import sjson
import IDLC.filewriter
import genutil as util
import ntpath
class IDLCodeGenerator:
def __init__(self):
self.document = None
self.documentPath =... | StarcoderdataPython |
1692686 | <reponame>Xiaoming94/TIFX05-MScThesis-HenryYang
import utils
import ANN as ann
import os
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import utils.digitutils as dutils
import cv2
import keras.callbacks as clb
import keras.optimizers as opt
network_model1 = '''
{
"input_shape" : [7... | StarcoderdataPython |
3318756 | # Copyright (c) 2019 Works Applications Co., Ltd.
#
# 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 a... | StarcoderdataPython |
1712168 | # This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if ... | StarcoderdataPython |
1628615 | """
A Python dictionary containing information to be associated with the twelve keys on a
MacroPad.
"""
from adafruit_macropad import MacroPad
macropad = MacroPad()
"""
** Understanding the Dictionary **
The following explains how to configure each entry below.
Sound:
Can be an integer for a tone in Hz, e.g.196, OR, a... | StarcoderdataPython |
2102 | from django.conf import settings
def less_settings(request):
return {
'use_dynamic_less_in_debug': getattr(settings, 'LESS_USE_DYNAMIC_IN_DEBUG', True)
}
| StarcoderdataPython |
193142 | from django.contrib import admin
from .models import (
EveCategory,
EveConstellation,
EveGroup,
EveMoon,
EvePlanet,
EveRegion,
EveSolarSystem,
EveType,
)
class EveUniverseEntityModelAdmin(admin.ModelAdmin):
def has_module_permission(self, request):
return False
def ha... | StarcoderdataPython |
3326179 | class Solution:
def heightChecker(self, heights: List[int]) -> int:
sortedH = sorted(heights)
count = 0
for i in range(len(heights)):
if sortedH[i] != heights[i]:
count +=1
else:
pass
return count | StarcoderdataPython |
1729230 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='api_ai_graph',
version='0.1.0',
description='Render graphs based on API.AI intents.',
long_description=readme,
a... | StarcoderdataPython |
42570 | import matplotlib.pyplot as plt
from string import ascii_uppercase
def countSpecific(_path, _letter):
_letter = _letter.strip().upper()
file = open(_path, 'rb')
text = str(file.read())
return text.count(_letter) + text.count(_letter.lower())
def countAll(_path):
file = open(_path, "rb")
text =... | StarcoderdataPython |
1716720 | <reponame>Keeper-Security/secrets-manager
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Secrets Manager
# Copyright 2021 Keeper Security Inc.
# Contact: <EMAIL>
class Context:
def __init__(self, transmission_key, client_id, clien... | StarcoderdataPython |
106638 | import numpy as np
import matplotlib.pyplot as plt
import ReinforcedPy as rp
import matplotlib.patches as mpatches
concreto28 = rp.Concreto()
acero420 = rp.AceroRefuerzo()
viga=rp.Elemento(0.3,0.6,[concreto28,acero420],6)
viga.generarDesdeCarga(50)
viga._test_secciones()
print(viga.secciones[0].momentoNominal())
pr... | StarcoderdataPython |
92145 | try:
from json import load
from math import floor
from os import path
from random import choice, sample, randrange
except ImportError:
raise ImportError
class Fighter:
def __init__(self, as_str, as_con, as_dex,
as_int, as_wis, as_cha, char_race, char_background, level):
... | StarcoderdataPython |
105505 | <reponame>gcewing/PyGUI
#
# Python GUI - Menus - Gtk version
#
from gi.repository import Gtk
from gi.repository import Gdk
from GUI.Globals import application
from GUI.GMenus import Menu as GMenu, MenuItem
def _report_accel_changed_(*args):
print "Menus: accel_changed:", args
class Menu(GMenu):
def __init__(self... | StarcoderdataPython |
182573 | <reponame>hirusha-adi/GifGang<gh_stars>0
import random
from datetime import datetime
import discord
from discord.ext import commands
from module import nsfw
class Nsfw(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
@commands.command()
async def eporner(self, ctx, *... | StarcoderdataPython |
142524 | <filename>python_code_examples/scraping/xkcd_url_scrape.py<gh_stars>10-100
from bs4 import BeautifulSoup
import requests
start = "https://xkcd.com/2260/"
page = requests.get(start)
soup = BeautifulSoup(page.text, 'html.parser')
prevLink = soup.select('a[rel="prev"]')[0]
print(prevLink)
print( prevLink.get('href') )
... | StarcoderdataPython |
3282458 | <reponame>zimagi/zima<filename>app/data/log/models.py
from django.utils.timezone import now
from systems.models.index import Model, ModelFacade
class LogFacade(ModelFacade('log')):
def get_field_message_render_display(self, instance, value, short):
from systems.commands import messages
display ... | StarcoderdataPython |
4838472 | <reponame>coderMaruf/leetcode-1
'''
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you ... | StarcoderdataPython |
1783386 | <filename>lambkin/zip.py
from __future__ import absolute_import
import os
import zipfile
import lambkin.metadata as metadata
# REF: http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html
def create_zip(zip_file_path):
if not zip_file_path:
function = metadata.get... | StarcoderdataPython |
57413 | import logging
from dataclasses import dataclass
from unittest.mock import patch
import pytest
from tests.utils.mock_backend import (
ApiKey,
BackendContext,
Run,
Project,
Team,
User,
)
from tests.utils.mock_base_client import MockBaseClient
###################################... | StarcoderdataPython |
15709 | <filename>oriskami/test/resources/test_router_data.py
import os
import oriskami
import warnings
from oriskami.test.helper import (OriskamiTestCase)
class OriskamiAPIResourcesTests(OriskamiTestCase):
def test_router_data_update(self):
response = oriskami.RouterData.update("0", is_active="true")
sel... | StarcoderdataPython |
3334480 | <filename>app/api/models/route.py
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import Dict, List # noqa: F401
from app import util
from app.api.models.base_model_ import Model
class Route(Model):
"""NOTE: This class is auto generated by t... | StarcoderdataPython |
3355016 | <filename>beam_search.py
"""Beam search implementation in PyTorch."""
#
#
# hyp1#-hyp1---hyp1 -hyp1
# \ /
# hyp2 \-hyp2 /-hyp2#hyp2
# / \
# hyp3#-hyp3---hyp3 -hyp3
# ========================
#
# Takes care of beams, back poin... | StarcoderdataPython |
118216 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 22 14:15:18 2017
@author: <NAME>
"""
import numpy as np
import pickle
matrixShape = ##Shape##
matrixDType = ##Dtype##
workingDir = "##workingDir##"
fileNameString = "##fileNameString##"
datafile = open(workingDir+fileNameString+"_... | StarcoderdataPython |
1618683 | # -*- coding:utf8 -*-
###############################################################################
# #
# SYMBOLS, TABLES #
# ... | StarcoderdataPython |
3398874 | <filename>tests/test_hse.py
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021 Micron Technology, Inc. All rights reserved.
import unittest
from hse2 import hse
from common import UNKNOWN
class HseTests(unittest.TestCase):
def test_param(self):
for args in (("socket.enabled", "false"), ("this-... | StarcoderdataPython |
132616 | <gh_stars>0
import speech_recognition as SpeechRecog
import pyaudio
from random_word import RandomWords
import random
import time
import threading
init_rec = SpeechRecog.Recognizer()
score = 0
num_ques = 0
lang = {
1: 'en-US',
2: 'hi-IN',
3: 'ta-IN',
4: 'te-IN',
5: 'kn-IN',
6: 'zh-CN',
7: ... | StarcoderdataPython |
3269928 | import sys
"""Functions to support backwards compatibility.
Basically where we have functions which differ between python 2 and 3, we provide implementations here
and then Python-specific versions in backward2 and backward3.
"""
if sys.hexversion >= 0x03000000: # Python 3+
from stomp.backward3 import *... | StarcoderdataPython |
4829700 | <reponame>FrNecas/ogr
from requre.online_replacing import record_requests_for_all_methods
from tests.integration.pagure.base import PagureTests
from ogr.abstract import IssueStatus
@record_requests_for_all_methods()
class Issues(PagureTests):
def setUp(self):
super().setUp()
self._long_issues_pro... | StarcoderdataPython |
3319423 | # Subcommand completion with the readline module.
#
# Tested with Python 3.4
#
# <NAME> [http://eli.thegreenplace.net]
# This code is in the public domain.
import glob
import readline
def make_subcommand_completer(commands):
def custom_complete(text, state):
# Simplistic parsing of the command-line so far.... | StarcoderdataPython |
3293670 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
If your log file is in a standard format, then this module can help you filter
out log information that you care aboue.
**中文文档**
如果你的日志格式是标准的 "%(asctime)s; %(levelname)-8s; %(message)s"。那么本
模块中的函数能够帮助您从日志中轻松的找到你感兴趣的结果。
"""
from __future__ import print_function
cla... | StarcoderdataPython |
1775689 | <gh_stars>1-10
import unittest
from .realParser import eval
from .realParser import parse
class functionXTest(unittest.TestCase):
def test_one(self):
self.assertEqual(7, parse("((2)+(5))"))
self.assertEqual(-3, parse(" (2)-(5)"))
self.assertEqual(28, parse("+3 +5*5*(+1)")) ... | StarcoderdataPython |
167130 | from meteor_reasoner.utils.parser import *
from collections import defaultdict
def load_dataset(lines):
"""
Read string-like facts into a dictionary object.
Args:
lines (list of strings): a list of facts in the form of A(x,y,z)@[1,2] or A@[1,2)
Returns:
A defaultdict object, in whic... | StarcoderdataPython |
1635375 | from lichtenberg.util import draw_blur
from PIL import Image
from random import randint
from pathlib import Path
def main():
width, height = 600, 600
img = Image.new("RGB", (width, height))
blur_params = [(0, 1.0), (1, 4.0), (2, 8.0)]
color = (1.2, 1.0, 1.0)
num_line = 50
for i in range(num_... | StarcoderdataPython |
85115 | import json
import os
import sys
import albumentations as A
import numpy as np
import pandas as pd
import timm
import torch
import ttach as tta
from albumentations.augmentations.geometric.resize import Resize
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader
from tqdm import ... | StarcoderdataPython |
70046 | # Copyright 2018 DeepMind Technologies Limited. 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 |
3289464 | '''KELFI code is adapated from https://github.com/Kelvin-Hsu/kelfi '''
import numpy as np
import tensorflow as tf
import pandas as pd
import pickle, time, os, sys
from os import path
import elfi
from elfi.examples import dgp_funcs, bdm_dgp, navworld
from kelfi.utils import halton_sequence
from kelfi.kernel_means_inf... | StarcoderdataPython |
3214952 | import psycopg2
import gmplot
db_conn = psycopg2.connect("dbname='yelp' host='' user='' password=''")
cur = db_conn.cursor()
cur.execute("select latitude, longitude from business where postal_code='89109';")
lat_long = cur.fetchall()
latitude = []
longitude = []
for i in range(len(lat_long)):
latitude.append(lat_lon... | StarcoderdataPython |
3300267 | <reponame>Couso99/EEG-Environment
# Author: <NAME> (<EMAIL>)
from PyQt5 import QtWidgets, QtCore, QtGui
from GUI.select_subject import SubjectSelection
from GUI.ui_subject_details_no_details import Ui_NoDetails
from GUI.ui_subject_details_show import Ui_Details
class NoDetails(QtWidgets.QWidget):
def __init__(se... | StarcoderdataPython |
3294351 | # Generated by Django 3.2.3 on 2021-05-19 08:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20210519_0849'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='year',
... | StarcoderdataPython |
3211452 | <filename>tirelire-account/tests/unit/tests_account.py
from unittest import TestCase
from datetime import date
from app.domain.model import (
Currency,
Category,
Account,
Operation
)
class TestAccount(TestCase):
def test_hashes_must_be_identical(self):
account = Account("abc", Curr... | StarcoderdataPython |
1706663 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Laboratoire de Recherche et
# Développement de l'Epita (LRDE).
#
# This file is part of Spot, a model checking library.
#
# Spot is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
#... | StarcoderdataPython |
3302037 | <reponame>lapras-inc/disk-embedding
import luigi
import named_tasks as named
import pandas as pd
import target
class _GatherResults(luigi.Task):
def run(self):
results = []
for req in self.requires():
if not req.complete():
continue
inp = ... | StarcoderdataPython |
3282788 | <filename>eynnyd/internal/wsgi/empty_response_body.py
from eynnyd.internal.wsgi.abstract_response_body import AbstractResponseBody
class EmptyResponseBody(AbstractResponseBody):
def get_body(self):
return []
| StarcoderdataPython |
1690308 | <gh_stars>1-10
"""Helper functions to load knowledge graphs."""
from .datasets import load_from_csv, load_from_rdf, load_fb15k, load_wn18, load_fb15k_237, load_from_ntriples, \
load_yago3_10, load_wn18rr
__all__ = ['load_from_csv', 'load_from_rdf', 'load_from_ntriples', 'load_wn18', 'load_fb15k',
'load... | StarcoderdataPython |
34693 | from ctypes.util import find_library as _find_library
print(_find_library('sndfile'))
print('test fine')
| StarcoderdataPython |
3240044 |
def rgb_to_xy(red, green, blue):
""" conversion of RGB colors to CIE1931 XY colors
Formulas implemented from: https://gist.github.com/popcorn245/30afa0f98eea1c2fd34d
Parameters:
red (float): a number between 0.0 and 1.0 representing red in the RGB space
green (float): a number between 0.0... | StarcoderdataPython |
3285300 | '''functions to work with contrasts for multiple tests
contrast matrices for comparing all pairs, all levels to reference level, ...
extension to 2-way groups in progress
TwoWay: class for bringing two-way analysis together and try out
various helper functions
Idea for second part
- get all transformation matrices ... | StarcoderdataPython |
38626 |
music = {
'kb': '''
Instrument(Flute)
Piece(Undine, Reinecke)
Piece(Carmen, Bourne)
(Instrument(x) & Piece(w, c) & Era(c, r)) ==> Program(w)
Era(Reinecke, Romantic)
Era(Bourne, Romantic)
''',
'queries': '''
Program(x)
''',
}
life = {
'kb': '''
Musician(x) ==> Stressed(x)
(Student(x) & Te... | StarcoderdataPython |
3357414 | # Uses python3
import sys
def get_fibonacci_last_digit(n):
if n < 2:
return n
prev = 1
cur = 1
for i in range(2, n):
prev, cur = cur, prev + cur % 10
return cur % 10
if __name__ == '__main__':
print(get_fibonacci_last_digit(int(input())))
| StarcoderdataPython |
192423 | import networkx as nx
import matplotlib.pyplot as plt
import random
def bipartite(numNodes):
odds=[]
evens=[]
colours=[]
for i in range(1,numNodes+1,2):
odds.append(i)
colours.append('red')
for i in range(2,numNodes+1,2):
evens.append(i)
colou... | StarcoderdataPython |
1683551 | <gh_stars>0
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
import pandas as pd
from helper_funcs import getTOlist
def print_solution(data, manager, routing, solution):
"""Prints solution on console."""
total_distance = 0
total_load = 0
for vehicl... | StarcoderdataPython |
1789318 | <filename>calico/etcddriver/protocol.py<gh_stars>1-10
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 Tigera, 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
#
# ... | StarcoderdataPython |
1687530 | from django.shortcuts import render
from django.http import HttpResponse
import datetime
# Create your views here.
def home_view(request, *args,**kwargs):
# TODO: write code...
print('request:', request)
print('request user:', request.user)
print(args, kwargs)
return render(request,"home.html",{})
... | StarcoderdataPython |
3326067 | <gh_stars>0
#
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (47.06%)
# Likes: 2942
# Dislikes: 85
# Total Accepted: 333.7K
#... | StarcoderdataPython |
3308187 | import base64
import datetime
import json
import os
import pickle
import struct
import sys
import unittest
import uuid
from tornado import testing
import umsgpack
from sprockets.mixins.mediatype import content, handlers, transcoders
import examples
class UTC(datetime.tzinfo):
ZERO = datetime.timedelta(0)
d... | StarcoderdataPython |
83222 | # coding: utf-8
""" Some photometry tools for stellar spectroscopists """
from __future__ import (division, print_function, absolute_import,
unicode_literals)
import numpy as np
from scipy import interpolate
from astropy.io import ascii
from .robust_polyfit import polyfit
import logging
import ... | StarcoderdataPython |
1602680 | <reponame>garywei944/AlphaSMILES
import json
import os
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Draw
from mcts import parameters as p
from tools.plot_wavelength import plot_wl
def select(data, starting_with='', wl_min=0, wl_max=float('inf'), unit="nm", f_min=0.0):
"""
Sel... | StarcoderdataPython |
3382605 | <filename>iaflash/app/app.py
import os
from PIL import Image
import cv2
import json
from flask import Flask, render_template, Response, render_template_string, send_from_directory, request
import pandas as pd
from iaflash.environment import ROOT_DIR
from iaflash.filter import read_df, dict2args
WIDTH = 600
HEIGHT = 40... | StarcoderdataPython |
1635222 | <gh_stars>1-10
import pytest
from dataframe_generator.data_type import LongType, StringType, ByteType, IntegerType, DateType, TimestampType, \
ShortType, DecimalType
from dataframe_generator.struct_field import StructField
from dataframe_generator.struct_type import StructType
from tests.matchers import assert_str... | StarcoderdataPython |
1675498 | <reponame>shubh2ds/DSA_Python
def partition_for_quick_sort(arr,sidx,eidx):
pivot=arr[sidx]
c=0
for i in range(sidx,eidx+1):
if arr[i]<pivot:
c=c+1
arr[sidx+c],arr[sidx] = arr[sidx],arr[sidx+c]
pivot_idx=sidx+c
i=sidx
j=eidx
while i<j:
if arr[i]<pivot:
i=i+1
elif arr[j]>=pivot:
... | StarcoderdataPython |
135588 | <gh_stars>10-100
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import pytest
import os
from reco_utils.recommender.newsrec.newsrec_utils import prepare_hparams
from reco_utils.recommender.deeprec.deeprec_utils import download_deeprec_resources
from reco_utils.recommende... | StarcoderdataPython |
3364410 | <reponame>Ixyk-Wolf/aiohttp-demos
import pickle
from collections import namedtuple
import numpy as np
_model = None
Scores = namedtuple("Scores", ["toxic", "severe_toxic",
"obscence", "insult", "identity_hate"])
def warm(model_path):
global _model
if _model is None:
w... | StarcoderdataPython |
1795157 | <reponame>jhson989/jhML<filename>playground/step2/config.py<gh_stars>0
class Config:
enable_backprop = True
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.