id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
150961 | import re
patterns = ["term1", "term2"]
text = "This is a string with term1, not the other"
split_term = "@"
email = "<EMAIL>"
# for pattern in patterns:
# print("I'm searching for: " + pattern)
#
# if re.search(pattern, text):
# print("MATCH!")
# else:
# print("NO MATCH!")
print(re.spli... | StarcoderdataPython |
3285420 | class Solution:
def judgeCircle(self, moves: str) -> bool:
U, D, L, R = moves.count('U'), moves.count('D'), moves.count('L'), moves.count('R')
if U == D and L == R:
return True
else:
return False
| StarcoderdataPython |
3237865 | <filename>lingofunk_classify_sentiment/model/naive_bayes/preprocess.py
import itertools
import re
from nltk.collocations import BigramCollocationFinder
from nltk.corpus import stopwords
from nltk.metrics import BigramAssocMeasures
from nltk.tokenize import word_tokenize
def tokenize(text):
"""Splits a text to w... | StarcoderdataPython |
89772 | <gh_stars>0
#
# Copyright (C) Analytics Engines 2021
# <NAME> (<EMAIL>)
#
import pandas as pd
import streamlit as st
st.set_page_config(layout="wide")
import requests
import streamlit_bd_cytoscapejs
from common import login,init_state,base_url,format_request,local_css
init_state(['jwt','login_request'])
local_css("... | StarcoderdataPython |
1700020 | import sys
with open(sys.argv[1]) as input_file:
for problem in input_file.readlines():
print(problem.strip().split(' ')[-2])
| StarcoderdataPython |
3286564 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import xbmc
import xbmcgui
import time
import threading
import traceback
MONITOR = None
class BaseFunctions:
xmlFile = ''
path = ''
theme = ''
res = '720p'
width = 1280
height = 720
usesGenerate = False
def __init__(self):
self.isOpen =... | StarcoderdataPython |
1661271 | # Generated by Django 2.1.2 on 2018-10-20 11:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('incidentes', '0003_auto_20181020_0817'),
]
operations = [
migrations.RenameField(
model_name='t... | StarcoderdataPython |
109783 | <filename>codebase_analizer/project.py
import os
import shutil
import tempfile
from contextlib import contextmanager
# Python 2/3 compatibility
from builtins import object
class Project(object):
def __init__(self, project_location):
self._project_location = project_location
self._tmpdir = tempfil... | StarcoderdataPython |
1651950 | <reponame>antoine-moulin/rlberry
import logging
import gym.spaces as spaces
import numpy as np
from rlberry.agents import IncrementalAgent
from rlberry.agents.adaptiveql.tree import MDPTreePartition
from rlberry.utils.writers import PeriodicWriter
logger = logging.getLogger(__name__)
class AdaMBAgent(IncrementalAge... | StarcoderdataPython |
16977 | import os, time, mimetypes, glob
from django.utils.translation import gettext_lazy as _
from django.urls import reverse
from task.const import *
from task.models import Task, detect_group
from rusel.base.config import Config
from rusel.base.forms import CreateGroupForm
from rusel.context import get_base_context
from ru... | StarcoderdataPython |
3261873 | import mock
import testtools
from shakenfist import config
from shakenfist import exceptions
class ConfigTestCase(testtools.TestCase):
@mock.patch('socket.getfqdn', return_value='a.b.com')
@mock.patch('socket.gethostbyname', return_value='1.1.1.1')
def test_hostname(self, mock_hostname, mock_fqdn):
... | StarcoderdataPython |
3327797 | import gensim.downloader
import numpy as np
from gensim.corpora import Dictionary
from gensim.models import TfidfModel
from argparse import ArgumentParser
from logging import Logger
from pathlib import Path
from typing import List
from speechless.edit_context.common import TimelineChange
from speechless.processing.an... | StarcoderdataPython |
3379303 |
import re
from sqlalchemy import or_,and_
from sqlalchemy import Column, String, Integer, Boolean, Float, ForeignKey,PrimaryKeyConstraint
from sqlalchemy.orm import relationship
from fr.tagc.rainet.core.util.sql.Base import Base
from fr.tagc.rainet.core.util.sql.SQLManager import SQLManager
from fr.tagc.rainet.core... | StarcoderdataPython |
3358693 | import os
import tensorflow as tf
from tensorkit.log import logger, Color
class Restore(object):
def __init__(self):
self._var_list = None
self._restore_saver = None
self._restore_optimistic = False
self.restore_ckpt_file = None
self._inited = False
def init(self, va... | StarcoderdataPython |
1724031 | """
Implementation of Eccles, Tom, et al. "Biases for Emergent Communication in Multi-agent
Reinforcement Learning." Advances in Neural Information Processing Systems. 2019.
"""
import gym
import numpy as np
from ray.rllib import SampleBatch
from ray.rllib.agents.impala import vtrace
from ray.rllib.agents.impala.vtra... | StarcoderdataPython |
3324117 | <filename>binreconfiguration/itemgenerator/intuniform.py
"""Item generator: integer uniform distribution"""
from .itemgenerator import ItemGenerator
import random
class IntUniform(ItemGenerator):
def __init__(self, lower_bound, upper_bound):
self._lower_bound = lower_bound
self._upper_bound = upper_bound
def ... | StarcoderdataPython |
1639463 | import os
from IPython.core.magic import register_line_magic
os.system('wget -qO tldr https://github.com/dbrgn/tealdeer/releases/download/v1.3.0/tldr-linux-x86_64-musl')
os.system('chmod +x tldr')
os.system('mv tldr /usr/local/bin')
os.system('tldr --update') # need once
@register_line_magic
def tldr(line):
get_... | StarcoderdataPython |
3338189 | <reponame>wtriplett/lonestar4_launch<gh_stars>1-10
#!/usr/bin/env python
# launch script for stampede
# deals with both command files for parametric launcher and with single commands
import argparse
import sys,os
from tempfile import *
import subprocess
import math
MAXCORES=4104
MAXNODES=171
# set up argument args
... | StarcoderdataPython |
3345944 | from __future__ import print_function
import time
# import board
# import busio
# import adafruit_ads1x15.ads1015 as ADS
# from adafruit_ads1x15.analog_in import AnalogIn
# import Adafruit_DHT
import pyowm
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db as fb_db
from datetime ... | StarcoderdataPython |
133563 | import sqlite3
from config.constants import DB_NAME
if __name__ == '__main__':
conn = sqlite3.connect(str(DB_NAME), detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS nodes
(node_number INTEGER PRIMARY KEY ,
node_name... | StarcoderdataPython |
1653209 | <reponame>ECSLab/ES_IoT_Cloud
import urllib.parse
import urllib.request
import time
def postt(posturl, data):
req = urllib.request.Request(posturl, data)
return urllib.request.urlopen(req)
if __name__ == '__main__':
posturl = 'http://127.0.0.1:9000/upload'
dd = urllib.parse.urlencode({
'api_k... | StarcoderdataPython |
30532 | <reponame>vanish125/DS1054_BodePlotter
"""Unit tests for fygen module."""
import unittest
import six
import fygen
import fygen_help
from wavedef import SUPPORTED_DEVICES
# pylint: disable=too-many-public-methods
# pylint: disable=invalid-name
# pylint: disable=too-many-lines
class FakeSerial(object):
... | StarcoderdataPython |
130000 | <reponame>RileyWClarke/flarubin<gh_stars>0
# Tuples of RA,dec in degrees
ELAISS1 = (9.45, -44.)
XMM_LSS = (35.708333, -4-45/60.)
ECDFS = (53.125, -28.-6/60.)
COSMOS = (150.1, 2.+10./60.+55/3600.)
EDFS_a = (58.90, -49.315)
EDFS_b = (63.6, -47.60)
def ddf_locations():
"""Return the DDF locations as as dict. RA an... | StarcoderdataPython |
171743 | <filename>NPC.py
import sys, pygame, math
class NPC(pygame.sprite.Sprite):
def __init__(self, maxSpeed, pos = [0,0]):
pygame.sprite.Sprite.__init__(self, self.containers)
#Images From: URL: http://opengameart.org/content/classic-knight-animated
playerSize = [25,25]
self.rightImages ... | StarcoderdataPython |
1749063 | <gh_stars>1-10
#
# MIT License
#
# Copyright 2017 Launchpad project contributors (see COPYRIGHT.md)
#
# 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 without restriction, including without li... | StarcoderdataPython |
13707 | import pixiedust
my_logger = pixiedust.getLogger(__name__)
| StarcoderdataPython |
45004 | def mergeSort(elements):
if len(elements) == 0 or len(elements) == 1:
# BASE CASE
return elements
middle = len(elements) // 2
left = mergeSort(elements[:middle])
right = mergeSort(elements[middle:])
if left == [] or right == []:
return left or right
result = []
i, ... | StarcoderdataPython |
1653117 | <filename>src/borg/platform/base.py
import os
"""
platform base module
====================
Contains platform API implementations based on what Python itself provides. More specific
APIs are stubs in this module.
When functions in this module use platform APIs themselves they access the public
platform API: that way... | StarcoderdataPython |
177507 | <gh_stars>10-100
import os
from urllib import request
import numpy as np
from numpy import genfromtxt
from .. import pklhandler
'''
This module contains helper functions to download and load
the boston housing dataset.
'''
def get():
'''
Downloads the boston dataset from
https://archive.ics.uci.edu/ml/m... | StarcoderdataPython |
3398720 | <filename>tests/unit/test_core_driver.py<gh_stars>1-10
import sys
import pytest
from ssh2net.exceptions import UnknownPrivLevel
from ssh2net.core.driver import BaseNetworkDriver
from ssh2net.core.cisco_iosxe.driver import PRIVS
IOS_ARP = """Protocol Address Age (min) Hardware Addr Type Interface
Inte... | StarcoderdataPython |
3336180 | <filename>AtCoder/ABC/153/D. Caracal Vs Monster.py
def f(x):
if x == 1:
return 1
else:
k = f(x//2)
return 1+2*k
H = int(input())
print(f(H)) | StarcoderdataPython |
1676698 | from __future__ import division
from __future__ import print_function
import time
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import torch.optim as optim
from pygcn.utils import load_data, accuracy
from pygcn.models import GCN, MLP
from sklearn.preprocessing import StandardScaler
... | StarcoderdataPython |
3274340 | # -*- coding: utf-8 -*-
import scrapy
import re
import datetime
from ..items import LianjiaChengjiaoItem
class ChengjiaoSpider(scrapy.Spider):
name = 'chengjiao'
allowed_domains = ['cd.lianjia.com']
start_url = "https://cd.lianjia.com/xiaoqu/"
#分小区页面
next_region_url = "https://cd.lianjia.com{}pg{}/... | StarcoderdataPython |
50097 | <reponame>evi1hack/viperpython
# -*- coding: utf-8 -*-
# @File : SimpleRewMsfModule.py
# @Date : 2019/1/11
# @Desc :
#
#
from PostModule.lib.Configs import *
from PostModule.lib.ModuleTemplate import TAG2CH, PostMSFRawModule
from PostModule.lib.OptionAndResult import Option, register_options
# from PostModule.li... | StarcoderdataPython |
1749506 | <reponame>J-81/dp_tools
from collections import defaultdict
import copy
import enum
import gzip
import logging
import math
from pathlib import Path
from statistics import mean, median, stdev
import subprocess
from typing import Callable, DefaultDict, Dict, List, Set, Tuple, Union
import pandas as pd
from dp_tools.comp... | StarcoderdataPython |
3230471 | #for chrom in ["chr1", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr2", "chr20", "chr21", "chr22", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9", "chrX", "chrY"]:
#for chrom in ["chr19", "chr2", "chr20", "chr21", "chr22", "chr3", "chr4", "chr5", "c... | StarcoderdataPython |
3343925 | """Spectral Embedding."""
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse
from scipy.linalg import eigh
from scipy.sparse.linalg import eigsh
from scipy.sparse.csgraph import connected_components
from scipy.sparse.csgraph impo... | StarcoderdataPython |
1638317 | import calendar
import csv
import datetime
from datetime import date
from io import StringIO
import xlrd
from beancount.core import data
from beancount.core.data import Note, Transaction
from . import (DictReaderStrip, get_account_by_guess,
get_income_account_by_guess)
from .base import Base
from .dedu... | StarcoderdataPython |
1695596 | <filename>tanit/master/core/worker/worker_manager.py
import logging as lg
from datetime import datetime
from threading import RLock
from .worker import WorkerState
from .worker_monitor import WorkerMonitor
_logger = lg.getLogger(__name__)
class WorkerManager(object):
"""Monitor and Maintain workers states.
... | StarcoderdataPython |
3235354 | <filename>docs/hyperpython/hp03.py
from hyperpython import h
from htm import htm
# start
@htm
def html(tag, props, children):
if callable(tag):
return tag()
return h(tag, props, children)
def Heading():
return html('<header>Hello World</header>')
result03 = str(html("""
<{Heading}><//>
"... | StarcoderdataPython |
3214099 | <filename>setup.py
# -*- coding: utf-8 -*-
import os
from setuptools import setup, find_packages
with open(os.path.join('flagging_site', '__init__.py'), encoding='utf8') as f:
version = re.search(r"__version__ = '(.*?)'", f.read()).group(1)
with open('README.md', encoding='utf8') as f:
readme = f.read()
se... | StarcoderdataPython |
95883 | from urllib.parse import urlparse
from django.test import TestCase
# Create your tests here.
from smart_bookmarks.core.utils import url_guid
def test_foo():
guid = url_guid(
"https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute/3278104?q=alamakota#1234567"
)
pri... | StarcoderdataPython |
3211695 | <reponame>Melykuti/sh-pixel-labelling
# This is the code to define the graphical user interface (GUI) with Tkinter
from datetime import datetime, timedelta
import json
import numpy as np
import os
from PIL import Image, ImageTk
import tkinter as tk
from utils.downloading import SH_TCI_retrieve_successor
from utils.uti... | StarcoderdataPython |
67416 | <reponame>sunway513/Tensile<gh_stars>0
################################################################################
# Copyright (C) 2016-2019 Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documenta... | StarcoderdataPython |
4818722 | <reponame>hoaiphun96/Leet-Code-Problems
"""
Given a sorted list of integer ranges (see Range in Use Me) and a new range as inputs, insert the new range at the correct position and merge all overlapping ranges.
Note: Check out the Use Me section to get the structure of the Range class.
Example:
Input : [[1,10], [5,8]... | StarcoderdataPython |
172369 | <reponame>FelixWeichselgartner/PiHeld
# https://github.com/fidoriel/pyMCP23017
import pyMCP23017
from time import sleep
mcp = pyMCP23017.MCP23017(0x20)
pin=7
mcp.setup(pin, mcp.OUT)
pin2=8
mcp.setup(pin2, mcp.OUT)
while 1:
sleep(1)
mcp.output(pin, mcp.HIGH)
mcp.output(pin2, mcp.LOW)
sleep(1)
mcp... | StarcoderdataPython |
4812083 | <reponame>bobosoft/intrepyd
import unittest
from intrepyd.iec611312py.expression import ConstantOcc, VariableOcc
from intrepyd.iec611312py.variable import Variable
from intrepyd.iec611312py.datatype import Primitive
from intrepyd.iec611312py.expression import Expression
from intrepyd.iec611312py.inferdatatype import In... | StarcoderdataPython |
3208313 | <filename>application.py
import sys
import click
import os
import glob
from flask import Flask, Markup, Response, render_template, render_template_string, send_from_directory, current_app, safe_join
from flask_flatpages import FlatPages, pygmented_markdown, pygments_style_defs
from flask_frozen import Freezer
app = F... | StarcoderdataPython |
138828 | <reponame>Next-Gen-UI/Code-Dynamics
class MyHashSet:
def __init__(self):
self.set = [False] * 1000001
def add(self, key: int) -> None:
self.set[key] = True
def remove(self, key: int) -> None:
self.set[key] = False
def contains(self, key: int) -> bool:
return self.set[key]
| StarcoderdataPython |
90079 | from handler.base_plugin import BasePlugin
class AutoSender(BasePlugin):
__slots__ = ("text", )
def __init__(self, text):
"""Answers with text `text` to user without any conditions."""
super().__init__()
self.text = text
async def check_message(self, msg):
return True
... | StarcoderdataPython |
1785250 | """Wrapper class for WPWithin Service."""
import os
import time
import sys
import threading
from pkg_resources import resource_filename
import thriftpy
from thriftpy.rpc import make_client
from thriftpy.protocol.binary import TBinaryProtocolFactory
from thriftpy.transport.buffered import TBufferedTransportFactory
fro... | StarcoderdataPython |
3227209 | <filename>projecteuler/fastdoublingfib.py
def _fib(n):
if n==0:
return (0, 1)
else:
a, b = _fib(n//2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return(c, d)
else:
return(d, c + d)
print(200)
end = time.time()
print(end-start) | StarcoderdataPython |
30158 | <reponame>capellaspace/console-client<filename>tests/test_search.py<gh_stars>10-100
#!/usr/bin/env python
import pytest
from .test_data import get_search_test_cases, search_catalog_get_stac_ids
from capella_console_client import client
from capella_console_client.validate import _validate_uuid
from capella_console_cl... | StarcoderdataPython |
1629385 | <gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import openpyxl
import os, sys, shutil
import json
from datetime import datetime
from optparse import OptionParser
config = {}
def row_to_data(row):
data = {
'label': row[config['label']].value,
'file': row[config['file']].value,
'tra... | StarcoderdataPython |
3262000 | import requests
from requests.auth import HTTPBasicAuth
from .errors import *
from .config import config as target_config
class TargetApiClient(object):
def __init__(self, account_sid, access_token):
self.config = target_config
self.set_config({
'account_sid': account_sid,
... | StarcoderdataPython |
1678355 | <reponame>luminousmen/grokking_concurrency
#!/usr/bin/env python3
"""Implementing parking garage using semaphore for control critical section"""
import time
from threading import Thread, Semaphore
CAPACITY = 5
# shared memory
BUFFER = ["" for i in range(CAPACITY)]
mutex = Semaphore()
empty = Semaphore(CAPACITY)
ful... | StarcoderdataPython |
173914 | <filename>storemanager/users/admin.py
from django.contrib import admin
from .models import User,UserProfile
admin.site.register(User)
admin.site.register(UserProfile)
| StarcoderdataPython |
1655519 | <reponame>yawatajunk/Wi-Sun_EnergyMeter<filename>sem_com.py
#!/usr/bin/python3
# coding: UTF-8
import argparse
import binascii
import datetime
import glob
import json
import threading
import time
import os
import pickle
import socket
import sys
import RPi.GPIO as gpio
from y3module import Y3Module
from echonet_lite i... | StarcoderdataPython |
1623868 |
fileLines = open('exercise101.py','r')
lines = fileLines.readlines()
for line in range(len(lines)-1,0, -1):
lineStr = lines[line]
if len(lineStr.strip()) > 0 :
print(lineStr, end="") | StarcoderdataPython |
3350123 | <gh_stars>1-10
def solution(r):
answer = 0
for i in range(1, r):
for j in range(1, r):
if i ** 2 + j ** 2 <= r ** 2:
answer += 1
return answer * 4
def main():
r = int(input())
print(solution(r))
if __name__ == '__main__':
main()
| StarcoderdataPython |
192991 | import math
from tf_pwa.err_num import *
def test_add():
a = NumberError(1.0, 0.3)
b = NumberError(2.0, 0.4)
c = a + b
assert c.value == 3.0
assert c.error == 0.5
d = b - a
assert d.value == 1.0
assert d.error == 0.5
e = -a
assert e.value == -1.0
assert e.error == 0.3
... | StarcoderdataPython |
1793278 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 26 16:56:08 2018
@author: lenovo
"""
from sklearn.svm import SVC
clf = SVC()
clf.fit(sel.x_train, sel.y_train)
pred=clf.predict(test_data)
pred[pred==1]=0
pred[pred==3]=1
a=pred-test_label.T
a=a.T
sum(a==0)/206 | StarcoderdataPython |
3375166 | <gh_stars>1000+
class UnableToReadBaselineError(ValueError):
"""Think of this as a 404, if getting a baseline had a HTTPError code."""
pass
class InvalidBaselineError(ValueError):
"""Think of this as a 400, if getting a baseline had a HTTPError code."""
pass
class InvalidFile(ValueError):
"""Thi... | StarcoderdataPython |
49264 | from __future__ import annotations
from edutorch.typing import NPArray
from .batchnorm import BatchNorm
class SpatialBatchNorm(BatchNorm):
def forward(self, x: NPArray) -> NPArray:
"""
Computes the forward pass for spatial batch normalization.
Inputs:
- x: Input data of shape (N... | StarcoderdataPython |
4814464 | #!/usr/bin/python
# Copyright 2015 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# gen_texture_format_table.py:
# Code generation for texture format map
#
import json
import pprint
template = """// GENERATED FIL... | StarcoderdataPython |
1630216 | <reponame>Zhenye-Na/LxxxCode<gh_stars>10-100
class Solution:
"""
@param: nums: An integer array
@return: A list of integers includes the index of the first number and the index of the last number
"""
def continuousSubarraySum(self, nums):
# write your code here
if not nums or len(num... | StarcoderdataPython |
4841846 | # type: ignore
__all__ = ["conda_search_reqs"]
def conda_search_reqs(requirements) -> set:
conda_reqs = set()
for req in requirements.registered_imports:
# look up req (imported module name) in database compiled in advance
pass
return conda_reqs
| StarcoderdataPython |
15058 | import sys
import io
input_txt = """
44
"""
sys.stdin = io.StringIO(input_txt)
tmp = input()
# copy the below part and paste to the submission form.
# ---------function------------
def fibonacci(n):
if n <= 1:
return 1
fib_array = [1] * 45
for i in range(2, n+1):
fib_ar... | StarcoderdataPython |
196377 | <gh_stars>1-10
import discord
from discord.ext import commands
from datetime import datetime
class ChannelCommands(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(manage_channels=True)
async def lock(self, ctx, channel... | StarcoderdataPython |
3286050 | <reponame>alexbigkid/ingredients_for_cooking<gh_stars>0
"""Main program for displaying ingredients list for shopping with the recipes liked"""
# Standard library imports
import sys
# Third party imports
from colorama import Fore, Style
# Local application imports
from ingredients_input import IngredientsInput
from s... | StarcoderdataPython |
107791 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
requirements = ('numpy', 'opencv-python', 'solt==0.1.8', 'pyyaml',
'torch>=1.3.1', 'tqdm', 'scikit-learn', 'tensorboard', 'dill', 'matplotlib',
'pandas', 'pretrainedmodels... | StarcoderdataPython |
3221976 | #!/usr/bin/python3
# INP 1A Nancy Tetris
import pygame
pygame.init()
pygame.font.init()
from game import Game
game = Game()
game.run() | StarcoderdataPython |
3392357 | <reponame>vt-sailbot/sailbot<gh_stars>1-10
import socket, sys, json, time, modules.utils, autonomous, logging
from modules.utils import SocketType, socket_connect
logger = logging.getLogger('log')
# Define the global values, as generated by the configuration file
values = {}
def main():
arduino_sock = socket_co... | StarcoderdataPython |
3386092 | <filename>examples/matplotlib_chart.py
# Make it run from the examples directory
import sys
sys.path.append("..")
import pandas as pd
import numpy as np
from liquer import *
import liquer.ext.lq_pandas
import liquer.ext.lq_matplotlib
from flask import Flask
import liquer.blueprint as bp
app = Flask(__name__)
app.regis... | StarcoderdataPython |
3200792 | # EMACS settings: -*- tab-width: 2; indent-tabs-mode: t; python-indent-offset: 2 -*-
# vim: tabstop=2:shiftwidth=2:noexpandtab
# kate: tab-width 2; replace-tabs off; indent-width 2;
#
# ==============================================================================
# Authors: <NAME>
#
# Python Class: Base c... | StarcoderdataPython |
125312 | <reponame>dynamicguy/photomatic
__author__ = 'ferdous'
import celery
from celery.task import PeriodicTask
from datetime import timedelta, datetime
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@celery.task
class AlbumTask(PeriodicTask):
"""
A periodic task that import ph... | StarcoderdataPython |
1731031 | from jchart import Chart
from .models import Customer
class TaxSubPieChart(Chart):
chart_type = 'pie'
responsive = False
def get_datasets(self, **kwargs):
print(f'{kwargs}')
tax_pay = Customer.objects.filter(vat__in=['ctvrtletne', 'mesicne'])
submitted = tax_pay.filter(submitted_t... | StarcoderdataPython |
1748406 | import sys
import os
currentdir = os.path.dirname(__file__)
homedir = os.path.join(currentdir,"..")
sys.path.append(homedir)
| StarcoderdataPython |
3249948 | <gh_stars>1-10
# coding=utf-8
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', 'oecloud_dashboard.views.login'),
]
| StarcoderdataPython |
132700 | <reponame>adrianboratyn/TripRecommendations
import pandas as pd
import os.path
from django.core.management.base import BaseCommand, CommandError
import logging
from travels.models import Trip, TripDates
import datetime
import random
class Command(BaseCommand):
"""
Klasa do tworzenia typów wycieczek
"""
... | StarcoderdataPython |
103541 | import os
import cv2 as cv
import numpy as np
import tensorflow as tf
CWD_PATH = os.getcwd()
MODEL_NAME = "scribbler_graph_board_v3/"
# PATH_TO_CKPT = '{}frozen_inference_graph.pb'.format(MODEL_NAME)
PATH_TO_CKPT = "{}opt_graph.pb".format(MODEL_NAME)
PATH_TO_LABELS = "object-detection.pbtxt"
cvNet = cv.dnn.readNetF... | StarcoderdataPython |
3337350 | import abc
from zipline import protocol
from zipline.finance import asset_restrictions
from pluto.coms.utils import conversions
from pluto.control.controllable import synchronization_states as ss
from protos import clock_pb2
class Market(abc.ABC):
@abc.abstractmethod
def add_blotter(self, session_id):
... | StarcoderdataPython |
3261956 | from django.contrib import admin
from .models import Post,reviewsData,reportPost,Comments
# Register your models here.
admin.site.register(Post)
admin.site.register(reviewsData)
admin.site.register(reportPost)
admin.site.register(Comments) | StarcoderdataPython |
3366989 | # Define the application directory
import os
# Statement for enabling the development environment
DEBUG = True
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are working with
DATABASE = {
"engine": "mysql",
"database": "app",
"host": "localhost",
"port": "3306",
... | StarcoderdataPython |
112281 | <reponame>telefonicaid/fiware-cloto<gh_stars>1-10
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright 2014 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance... | StarcoderdataPython |
3273 | from typing import *
import attr
from dlms_cosem.hdlc import validators
@attr.s(auto_attribs=True)
class HdlcAddress:
"""
A client address shall always be expressed on one byte.
To enable addressing more than one logical device within a single physical device
and to support the multi-drop configurat... | StarcoderdataPython |
48916 | from typing import Callable, Awaitable
CoroutineFunction = Callable[..., Awaitable]
| StarcoderdataPython |
198197 | <gh_stars>0
"""
settings.py
-----------
Implements functions for reading and writing UI configuration using a QSettings object.
"""
from PyQt5 import QtWidgets
from instruments import triggering
import re
MPTS_trigger_file = ".config/MPTS_config.txt"
regex = re.compile('(\S+)[\s*]=[\s*]"(\S+)"')
def rea... | StarcoderdataPython |
184661 | <filename>AC-OhmsLaw/polar.py
# This is a partial program to run interactively from the command line, e.g.
# linux: python3 -i polar.py
# win: python -i polar.py
import numpy
# Euler's Formula for Polar (magnitude, degrees) to Rectangular (x, yj) on complex plane.
def Pd2R(A, deg):
return A*( numpy.cos(numpy.deg2... | StarcoderdataPython |
1768710 | <filename>Evernote_Django/evernote/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.core.files.uploadedfile import InMemoryUploadedFile
from .models import *
class AddNoteForm(forms.ModelForm):
class Meta:
model = Note
fields... | StarcoderdataPython |
3294533 | from pathlib import Path
import random
import numpy
from pyrr import matrix44
import moderngl
import moderngl_window
from moderngl_window.opengl.vao import VAO
class Boids(moderngl_window.WindowConfig):
"""
An attempt to make something boid-list with GL3.3.
Not currently working as intended,... | StarcoderdataPython |
108198 | <gh_stars>1-10
num = int(input('Type a number between 0 and 9999: '))
u = num % 10
t = num // 10 % 10
h = num // 100 % 10
th = num // 1000 % 10
print(f'Unity: {u} \n'
f'Ten: {t} \n'
f'Hundred: {h} \n'
f'Thousand: {th}')
| StarcoderdataPython |
1629975 | <gh_stars>10-100
# coding: utf-8
from asyncio import Protocol, get_event_loop
from config import cg_end_mark, cg_bytes_encoding
class TcpServer():
def __init__(self):
self.transports = set()
self.server = None
def register(self, transport):
self.transports.add(transport)
def unreg... | StarcoderdataPython |
1713680 | <gh_stars>1-10
import lark
from lark.visitors import Transformer # pip3 install lark-parser
# EBNF
grammar = r"""
start : value
?value : "true" -> true
| "false" -> false
| "null" -> null
| array
| object
| NUMBER
| STRING
array : "[" (value ("," value)*)? "]"
ob... | StarcoderdataPython |
1657627 | <filename>combine_files.py<gh_stars>1-10
import glob2
#######################################################################
# find all file names with a .txt extension
filenames = glob2.glob('data/political_news/fake_headlines/*.txt')
# concatenate all individual files into one file
with open("fake_headlines.txt"... | StarcoderdataPython |
3370508 | """
Functionality for declaring and cross-referencing
`Sphinx events
<https://www.sphinx-doc.org/en/master/extdev/appapi.html#sphinx-core-events>`_.
Sphinx events occur at specific points in the Sphinx build. When an event
is reached a signal is emitted with `sphinx.application.Sphinx.emit` that causes
the build to "p... | StarcoderdataPython |
3261265 | <gh_stars>1-10
#!/usr/bin/env python
import asyncio
import click
from nempy.sym.network import NodeSelector
@click.command()
@click.option('-h', '--host', 'hosts', default=tuple('google.com'), type=str, multiple=True, help='host to check latency')
@click.option('-p', '--port', default=443, help='port to check')
@cl... | StarcoderdataPython |
6581 | <reponame>rodlukas/UP-admin<filename>admin/migrations/0041_course_color.py
# Generated by Django 2.2.3 on 2019-07-31 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("admin", "0040_auto_20190718_0938")]
operations = [
migrations.AddField(
... | StarcoderdataPython |
191262 | import numpy as np
from ccgowl.models.functions.function import Function
from ccgowl.models.functions.owl import OWL
def _get_off_diagonal_entries(x):
lt_indices = np.tril_indices_from(x, -1)
lt_indices = list(zip(*lt_indices))
return lt_indices, np.array([x[i][j] for i, j in lt_indices])
class GOWL(Fu... | StarcoderdataPython |
3227514 | <reponame>netcadlabs/ndu-gate<gh_stars>1-10
import math
import cv2
import numpy as np
def is_inside_polygon(polygon, point):
# ref:https://stackoverflow.com/a/2922778/1266873
# int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
# {
# int i, j, c = 0;
# for (i = 0, j = ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.