id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1644811 | import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
arr = np.random.logistic(loc=1, scale=2, size=10)
print(arr)
arr = np.random.logistic(size=1000) # DEFUALT loc=0, scale=1
sns.distplot(arr, hist=False)
plt.show()
| StarcoderdataPython |
3255010 | <filename>A_HANDS-ON_GUIDE_TO_REGRESSION_WITH_FASTAI.py
# -*- coding: utf-8 -*-
"""Published-Regression_Using_Fastai.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/17VOQ78Wwj2ByP98M6ojhqpkq0usp3Udt
#Regression With Fastai
---
Published at Anal... | StarcoderdataPython |
4835042 | <gh_stars>0
from flask import Flask, render_template, request
import pickle
import numpy as np
app=Flask(__name__)
loaded_model = pickle.load(open("nycairbnbmodel.pkl","rb"))
@app.route('/')
def home():
return render_template('home.html')
def ValuePredictor(to_predict_list):
to_predict = np.array(to_predic... | StarcoderdataPython |
3394432 | """Tests for the lander.ext.parser.pandoc module's format conversion
functionality.
"""
from __future__ import annotations
from lander.ext.parser.pandoc import convert_text
def test_convert() -> None:
source = r"Hello \emph{world}"
expected = "Hello world\n"
assert expected == convert_text(
con... | StarcoderdataPython |
3260538 | <gh_stars>10-100
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# ... | StarcoderdataPython |
3304768 | from and_register_shifted_register_a1 import AndRegisterShiftedRegisterA1
from eor_register_shifted_register_a1 import EorRegisterShiftedRegisterA1
from sub_register_shifted_register_a1 import SubRegisterShiftedRegisterA1
from rsb_register_shifted_register_a1 import RsbRegisterShiftedRegisterA1
from add_register_shifte... | StarcoderdataPython |
136131 | <reponame>lx120/tinynn<gh_stars>0
"""tinynn implementation of Deep Convolution Generative Adversarial Network."""
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import tinynn as tn
from nets import D_cnn, D_mlp, G_cnn, G_mlp
def get_noise(size):
return np.random.normal(size=size)
... | StarcoderdataPython |
1733390 | <gh_stars>0
from django.test import SimpleTestCase
from django.urls import reverse, resolve
from profiles.views import profile
class TestUserUrls(SimpleTestCase):
def test_profile_url(self):
url = reverse("profile")
self.assertEquals(resolve(url).func, profile)
| StarcoderdataPython |
3271377 | # Copyright (c) 2017 <NAME>
#
# 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 limitation the rights
# to use, copy, modify, merge, publish, distribute, ... | StarcoderdataPython |
1760357 | #
# 1533. Find the Index of the Large Integer
#
# Q: https://leetcode.com/problems/find-the-index-of-the-large-integer/
# A: https://leetcode.com/problems/find-the-index-of-the-large-integer/discuss/765851/Javascript-Python3-C%2B%2B-binary-search-one-xor-two-%22middles%22
#
class Solution:
def getIndex(self, reade... | StarcoderdataPython |
126510 | '''
Created on Nov 29, 2020
@author: manik
'''
import numpy as np
import src.person_properties_util as idx
class Movement():
"""
Class providing abstraction into each movement of the population
"""
def update_persons(self, persons: np.ndarray, size: int,
speed: float = 0.1,
... | StarcoderdataPython |
3292198 | <reponame>sjennewein/MetaDataDistiller<gh_stars>0
import re
import urllib.parse
import glob
import os
import time
from metadata import data
import json
import requests
import zipfile
import sys
from metadata import payload
def touch(fname):
with open(fname, 'a'):
os.utime(fname, None)
input = sys.argv[1]... | StarcoderdataPython |
1688689 | import csv
import logging
import math
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
import uuid
import click
import oval.core
import pandas as pd
from tabulate import tabulate
logger = logging.getLogger(__name__)
@click.group(context_settings={"help_option_names": ['-h', '-... | StarcoderdataPython |
55277 | import numpy as np
import matplotlib.pyplot as plt
import os
import cv2
from tensorflow.python.keras.callbacks import TensorBoard
from tqdm import tqdm
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.lay... | StarcoderdataPython |
181412 | <reponame>johnche/troll-simulator
import numpy as np
import scipy.signal as signal
from pandas import DataFrame, to_datetime
from bokeh.plotting import figure
from bokeh.layouts import column, row
from bokeh.models import ColumnDataSource, Panel
from bokeh.models.widgets import CheckboxGroup, RadioButtonGroup, PreText,... | StarcoderdataPython |
3241965 | <gh_stars>0
from collections import defaultdict
class Solution:
"""
@param cpdomains: a list cpdomains of count-paired domains
@return: a list of count-paired domains
"""
def subdomainVisits(self, cpdomains):
counts = defaultdict(lambda: 0)
for cpdomain in cpdomains:
tim... | StarcoderdataPython |
1690360 | <gh_stars>0
import requests
from sys import argv
file__ = argv[1]
data = {
'email': '<EMAIL>',
'password': <PASSWORD>
}
url = argv[2]
num = 0
with open(file__, 'r') as a_file:
for lines in a_file:
line = lines.strip()
data['password'] = line
print(str(data) + " " + str(num))
... | StarcoderdataPython |
1685900 | <gh_stars>100-1000
import logging
import math
import re
import warnings
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from matplotlib import pyplot as plt, gridspec, cm, colors
import csv
from utils.utils import unscale, unnormalize, get_key_def
from ut... | StarcoderdataPython |
1734445 | <gh_stars>10-100
import pandas as pd
Data = pd.read_csv('train.csv')
mean_age = Data.Age.mean()
print(Data.Age.map(lambda p: p - mean_age))
### USING APPLY() METHOD
def score(row):
row.Age = row.Age - mean_age
return row
print(Data.apply(score, axis="columns").Age) | StarcoderdataPython |
163652 | <reponame>chrisrossx/DotStar_Emulator<filename>DotStar_Emulator/emulator/send_test_data.py
from __future__ import print_function
from multiprocessing.connection import Client
import random
import os
import time
from PIL import Image
import pygame
from .vector2 import Vector2
from DotStar_Emulator.emulator import conf... | StarcoderdataPython |
1623609 | from tkinter import *
from os import system
from platform import system as platform
class UIController:
def __init__(self):
self.root = Tk()
self.root.lift()
self.root.wm_attributes("-topmost", True)
self.root.after_idle(self.root.call, 'wm', 'attributes', '.', "-topmost", False)
... | StarcoderdataPython |
3275657 | <filename>fdm-devito-notebooks/01_vib/exer-vib/bouncing_ball.py
import numpy as np
def solver(H, C_R, dt, T, eps_v=0.01, eps_h=0.01):
"""
Simulate bouncing ball until it comes to rest. Time step dt.
h(0)=H (initial height). T: maximum simulation time.
Method: Euler-Cromer.
"""
dt = float(dt)
... | StarcoderdataPython |
175100 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import bs4 as BeautifulSoup
import json
import os
import requests
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie1976
from colormath.color_objects import LabColor, sRGBColor
from pycolorname.utilities import PROJECT_PATH
class... | StarcoderdataPython |
3313269 | <filename>tests/excerptexport/permission_test_helper.py
import pytest
from osmaxx.profile.models import Profile
@pytest.mark.django_db
class PermissionHelperMixin(object):
def add_email(self):
self.user.email = '<EMAIL>'
self.user.save()
def add_valid_email(self):
self.add_email()
... | StarcoderdataPython |
1681399 | #!/usr/bin/env python3
"""
Contains the QC settings dictionary for all cifti_vis scripts, as well as
a class to make access to settings easy to read.
"""
import os
import sys
import logging
from abc import ABCMeta, abstractmethod
from PIL import Image
import yaml
import ciftify.config as config
from ciftify.utils imp... | StarcoderdataPython |
3382124 | <reponame>wonkalous/dotfiles
import subprocess
import json
import time
import sys
import re
def get_tree():
j_ = subprocess.check_output(
["i3-msg", "-t", "get_tree"]
)
j = json.loads(j_)
return j
def get_wins():
return dict(proc_tree(get_tree()))
def proc_tree(x):
print(x['type'], ... | StarcoderdataPython |
147340 | #!/usr/bin/python3
import sys
sys.path.append('cpp')
import pyattyscomm
print("Searching for Attys")
s = pyattyscomm.AttysScan()
s.scan()
c = s.getAttysComm(0)
if (c == None):
print("No Attys found")
quit()
c.start()
while True:
while (not c.hasSampleAvailable()):
pass
sample = c.getSampleFromB... | StarcoderdataPython |
3272663 | <gh_stars>1-10
import csv
import json
input_path = 'data/timeline.csv'
output_path = '../data/timeline.json'
data = {}
data_list = []
years = []
with open(input_path, encoding="utf8") as cvsFile:
csvReader = csv.DictReader(cvsFile)
for row in csvReader:
print("--------")
data_list.insert(len(data_list),ro... | StarcoderdataPython |
3242017 | <gh_stars>10-100
import os
from pathlib import Path
OUTPUT_FILE = 'constraints.tcl'
design_name = os.environ['design_name']
time_scale = float(os.environ['constr_time_scale'])
cap_scale = float(os.environ['constr_cap_scale'])
main_per = float(os.environ['constr_main_per'])
clk_4x_per = 0.25*main_per*time_scale
outpu... | StarcoderdataPython |
3280682 | from pathlib import Path
from typing import List
import numpy as np
import torch
from tokenizers import Tokenizer
from torch.utils.data import Dataset
from tqdm import tqdm
class TextDataset(Dataset):
def __init__(self, text_files: List[Path], tokenizer_path: str, sequence_length: int = 128, stride: int = 128, ... | StarcoderdataPython |
3383237 | <reponame>yuanz271/PyDSTool<gh_stars>1-10
#!/usr/bin/env python
# <NAME>
# Last Change : 2007-08-24 10:59
"""
Class defining the Rosenbrock function
"""
from __future__ import absolute_import
import numpy
from numpy.testing import assert_almost_equal, assert_array_almost_equal
from PyDSTool.Toolbox.optimizers impor... | StarcoderdataPython |
4813579 | <filename>wrapper/__main__.py
import sys
import io
import argparse
from wrapper import pipeline
import logging
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description='VU Reading Machine pipeline')
parser.add_argument('-c', '--cfg_file', dest='cfg_file', default='./cfg/pipeline.yml', type=str... | StarcoderdataPython |
18024 | <filename>DTL_tests/unittests/test_api.py
import os
import time
import unittest
from DTL.api import *
class TestCaseApiUtils(unittest.TestCase):
def setUp(self):
apiUtils.synthesize(self, 'mySynthesizeVar', None)
self.bit = apiUtils.BitTracker.getBit(self)
def test_wildcardToRe(self)... | StarcoderdataPython |
1691495 | <filename>mlprogram/nn/__init__.py<gh_stars>1-10
from mlprogram.nn.aggregated_loss import AggregatedLoss # noqa
from mlprogram.nn.bidirectional_lstm import BidirectionalLSTM # noqa
from mlprogram.nn.cnn import CNN2d # noqa
from mlprogram.nn.embedding import EmbeddingWithMask # noqa
from mlprogram.nn.function import... | StarcoderdataPython |
3299784 | # Copyright 2019 ducandu GmbH, All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | StarcoderdataPython |
3332204 | import os
basedir = os.path.abspath(os.path.dirname(__file__))
# BASIC APP CONFIG
WTF_CSRF_ENABLED = True
SECRET_KEY = 'We are the world'
BIND_ADDRESS = '0.0.0.0'
PORT = 8080
LOGIN_TITLE = os.getenv( 'ADMIN_LOGIN_TITLE', "PowerDNS" )
# TIMEOUT - for large zones
TIMEOUT = 10
# LOG CONFIG
LOG_LEVEL = 'DE... | StarcoderdataPython |
1633266 | # dictionary microcontrollers
# wykys 2018
from avr import InfoAVR
from collections import OrderedDict
mcu_dict = OrderedDict(sorted({
"atxmega384c3": InfoAVR('392K', '32K', '4K'),
"atxmega384d3": InfoAVR('384K', '16K', '4K'),
"atmega256rfr2": InfoAVR('256K', '32K', '8K'),
"atmega2564rfr2": InfoAVR('2... | StarcoderdataPython |
46939 | <filename>ABC/abc101-abc150/abc117/c.py
# -*- coding: utf-8 -*-
def main():
n, m = map(int, input().split())
xs = sorted(list(map(int, input().split())))
if n >= m:
print(0)
else:
ans = xs[-1] - xs[0]
diff = [0 for _ in range(m - 1)]
for i in range(m - 1)... | StarcoderdataPython |
117003 | <reponame>ciskoinch8/vimrc
# pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring
# pylint: disable=too-few-public-methods
from typing import overload
class ClassA:
@classmethod
@overload
def method(cls, arg1):
pass
@classmethod
@overload
def met... | StarcoderdataPython |
3376386 | from datetime import datetime
from livestyled.models.device import Device
from livestyled.models.reality import Reality
class DeviceReality:
def __init__(
self,
id,
device: Device or str,
reality: Reality or str,
value: str,
created_at: date... | StarcoderdataPython |
1685178 | <filename>tools/hashgen/hashgen.py
#!/usr/bin/env python3
import argparse
import hashlib
def hash(file):
if file[0] == '*':
return bytearray.fromhex(file[1:])
else:
with open(file, 'rb') as f:
return hashlib.sha1(f.read()).digest()
def split_values(x):
s = x.split('=')
ret... | StarcoderdataPython |
120890 | <filename>calculator/use__simpleeval__module.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# pip install simpleeval
from simpleeval import simple_eval
print(simple_eval("21 + 21")) # 42
print(simple_eval("2 + 2 * 2")) # 6
print(simple_eval('10 ** 123')) # 1000000000000000000000000000... | StarcoderdataPython |
3233767 | <filename>src/sizzlews/test/aiohttp_client_test.py
# sizzlews
# Copyright (C) 2020 <NAME>
# The MIT License (MIT)
#
# 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 |
3323688 | <reponame>GordonSo/pyMock-examples
from unittest import mock
import pytest_mock
"""
This tutorial contains a number of test function to demonstrate different ways to mock a function
Each of this function can be run or debug individually and have the following setup:
- class A with has a function do_something that wil... | StarcoderdataPython |
165367 | <reponame>palwolus/Cyder<gh_stars>1-10
from vfssh.vfs.Command import Command
from vfssh.vfs.error import VFSError
from vfssh.vfs.fs_object import FileObject
import requests
class curl(Command):
def __init__(self, vfs=None):
super().__init__('curl')
self.set_vfs(vfs)
def process(self, **kwargs... | StarcoderdataPython |
4813233 | <gh_stars>1-10
import json
import socket
from hashlib import sha256
import time
from bitcoin.wallet import CBitcoinAddress
import bitcoin
import binascii
from typing import Dict, List
from config import Config, NETWORK_TESTNET, NETWORK_MAINNET
import logging
def _request(method, *args):
return {'method': method, '... | StarcoderdataPython |
1622082 | <reponame>mohan-chinnappan-n/ParlAI
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
File for miscellaneous utility functions and constants.
"""
# some of the utilit... | StarcoderdataPython |
1610850 | import json
import tkinter as tk
from tkinter import ttk
import api
import core
CONFIG = 'config.json'
AUTOSAVE = 'autosave.txt'
TF2_WIKI_API = 'https://wiki.teamfortress.com/w/api.php'
WIKIPEDIA_API = 'https://en.wikipedia.org/w/api.php'
def open_config():
try:
file = open(CONFIG, 'r')
file.cl... | StarcoderdataPython |
3212210 | # Generated by Django 2.2.1 on 2019-08-31 10:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("core", "0009_activeplugin_enabled")]
operations = [
migrations.RemoveField(model_name="report", name="config"),
migrations.AddField(
... | StarcoderdataPython |
3370733 | #!/usr/bin/env python
"CNC GUI basic page switching"
import sys
import os
import pygame
import pigpio
import socket
import linecache
from pygame import *
from pygame.transform import scale
from pygame.locals import *
import math
pygame.warn_unwanted_files
main_dir = os.path.dirname(os.path.abspath("__fil... | StarcoderdataPython |
3219665 | import numba as nb
import numpy as np
from dsa.topology.graph.jit.csgraph_to_directed import csgraph_to_directed
from dsa.topology.graph.jit.sort_csgraph import sort_csgraph
# TODO cut below
# DFS
@nb.njit
def connected_components_dfs(n: int, g: np.ndarray):
g = csgraph_to_directed(g)
g, edge_idx, _ = sort_c... | StarcoderdataPython |
3376463 | <reponame>ForwardLine/backup-nanny<filename>backup_nanny/util/lambda_client.py<gh_stars>1-10
from boto3.session import Session
from sys import exit
class LambdaClient(object):
def __init__(self, session=None):
self.client = self.get_client(session)
def get_client(self, session=None):
if not s... | StarcoderdataPython |
1686147 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 - 2019 Karlsruhe Institute of Technology - Steinbuch Centre for Computing
# This code is distributed under the MIT License
# Please, see the LICENSE file
#
import os
import numpy as np
import dogs_breed_det.config as cfg
import dogs_breed_det.dataset.data_utils as dutils
... | StarcoderdataPython |
1754075 | #!/usr/bin/python3
"""defining to_json_string function"""
import json
def to_json_string(my_obj):
"""returns json representation of an object"""
return json.dumps(my_obj)
| StarcoderdataPython |
1640893 | <gh_stars>0
from braces.views import LoginRequiredMixin
from django.views.generic import TemplateView
class LandingPageView(TemplateView):
"""LandingPage for registering and logging in."""
template_name = 'frontend/index.html'
class ArianeView(LoginRequiredMixin, TemplateView):
"""The core view of the ... | StarcoderdataPython |
1688863 | <filename>sudoku.py
# Sudoku class
class Sudoku:
# Constructor
def __init__(self, matrix):
self.board = self.load(matrix)
# Load board with matrix
def load(self, matrix):
if (self.isMatrixValid(matrix)):
return matrix
else:
return [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,... | StarcoderdataPython |
5928 | <reponame>ChidinmaKO/Chobe-bitesofpy
def get_index_different_char(chars):
alnum = []
not_alnum = []
for index, char in enumerate(chars):
if str(char).isalnum():
alnum.append(index)
else:
not_alnum.append(index)
result = alnum[0] if len(alnum) < len(not_alnum)... | StarcoderdataPython |
3285079 | <reponame>lightsey/cinder<gh_stars>1-10
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | StarcoderdataPython |
3363102 | <reponame>mboos/advent-of-code
# Lint as: python3
"""Counts valid passwords
Solution to part 2 of https://adventofcode.com/2020/day/2
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
from absl import app
from absl import flags
FLAGS = flags.F... | StarcoderdataPython |
4825311 | from generator import (
GenerateGemmOperations,
GenerateGemvOperations,
GenerateConv2dOperations,
GenerateDeconvOperations,
)
class GenArg:
def __init__(self, gen_op, gen_type):
self.operations = gen_op
self.type = gen_type
def write_op_list(f, gen_op, gen_type):
if gen_op ==... | StarcoderdataPython |
33788 | import collections
try:
stringtype = basestring # python 2
except:
stringtype = str # python 3
def coerce_to_list(x):
if isinstance(x, stringtype):
return x.replace(',', ' ').split()
return x or []
def namedtuple(name, args=None, optional=None):
args = coerce_to_list(args)
optiona... | StarcoderdataPython |
3385754 | from django.db import models
from datetime import datetime
# Create your models here.
class Container(models.Model):
number = models.CharField(max_length=11)
carrier = models.CharField(max_length=128)
status = models.CharField(max_length=200)
date = models.DateTimeField()
location = models.CharFiel... | StarcoderdataPython |
154524 | from __future__ import absolute_import
import copy
import netlib.tcp
from .. import stateobject, utils, version
from ..proxy.primitives import AddressPriority
from ..proxy.connection import ClientConnection, ServerConnection
KILL = 0 # const for killed requests
class BackreferenceMixin(object):
"""
If an a... | StarcoderdataPython |
1618253 | <reponame>nice-shot/FacebookFilter
from django.db import models
from django.contrib.auth import models as auth_models
from jsonfield import JSONCharField
# Create your models here.
class FacebookPage(models.Model):
"""
Represents a Facebook page, group or any other object that we can subscribe
to
"""
... | StarcoderdataPython |
178899 | <filename>accounts/api.py<gh_stars>0
from rest_framework import generics, permissions
from rest_framework.response import Response
from knox.models import AuthToken
from .serializers import UserSerializer, RegisterSerializer,LoginSerializer
# Register API
class RegisterAPI(generics.GenericAPIView):
serializer_... | StarcoderdataPython |
1753375 | <gh_stars>1-10
x=input("ENTER 1st NUMBER")
y=input("ENTER 2nd NUMBER")
x=int(x)
y=int(y)
z=x+y
print(z)
# another way
result = eval(input('enter en expr')) # enter expression ---> 2 + 6 - 1
print(result)
| StarcoderdataPython |
1742890 | import re
import unicodedata
from datetime import date
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.utils.timezone import now
from django.utils.translation import ugettext as _
EMAIL_VALIDATOR = re.compile(r'[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+')
PHONE_FILTER = re... | StarcoderdataPython |
95254 | import numpy as np
import pandas as pd
import datetime as dt
import math
import seaborn as sns
import matplotlib.pyplot as plt
import glob | StarcoderdataPython |
79907 | from collections import namedtuple
import jax.numpy as jnp
import pytest
from numpy.testing import assert_allclose
from numpyro.infer.einstein.kernels import (
RBFKernel,
RandomFeatureKernel,
GraphicalKernel,
IMQKernel,
LinearKernel,
MixtureKernel,
HessianPrecondMatrix,
PrecondMatrixKe... | StarcoderdataPython |
71397 | <reponame>gopal131072/WormScraper
import bs4 as bs
import urllib.request
import sys
import os.path
# Reads the table of contents to try and generate a sitemap for the serial.
# I would use the actual sitemap but this is easier since the sitemap is in reverse chronological
# order whereas this is in the actual chronol... | StarcoderdataPython |
75355 | # Copyright 2017 The TensorFlow 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... | StarcoderdataPython |
3388218 | import luigi
import luigi.contrib.hadoop
import luigi.contrib.hdfs
class InputFile(luigi.ExternalTask):
"""
A task wrapping the HDFS target
"""
input_file = luigi.Parameter()
def output(self):
"""
Return the target on HDFS
"""
return luigi.contrib.hdfs.HdfsTarget(self.input_file... | StarcoderdataPython |
1653202 | import re
import numpy as np
import warnings
import copy
from .utils import is_pos_int, is_non_neg_int, \
is_proportion, is_positive, is_non_negative, \
inherits
class layout:
def __init__(self,
ncol=None,
nrow=None,
byrow=None,
re... | StarcoderdataPython |
102022 | '''
Classes to represent axis-aligned 3-D bounding boxes and 3-D line segments, and
to perform ray-tracing based on oct-tree decompositions or a linear marching
algorithm.
'''
# Copyright (c) 2015 <NAME>. All rights reserved.
# Restrictions are listed in the LICENSE file distributed with this package.
from .cytools.b... | StarcoderdataPython |
138133 | <filename>testify/test_runner_server.py
# vim: et ts=4 sts=4 sw=4
"""
Client-server setup to evenly distribute tests across multiple processes. The server
discovers all test classes and enqueues them, then clients connect to the server,
receive tests to run, and send back their results.
The server keeps track of the o... | StarcoderdataPython |
3354890 | <reponame>pysrc/fractal
# FASS曲线
from fractal import Pen
p = Pen([420,420])
p.setPoint([10,10])
p.doD0L(omega = "L", P = {"L": "LFRFL-FF-RFLFR+FF+LFRFL", "R": "RFLFR+FF+LFRFL-FF-RFLFR"}, delta = 90, times = 4, length = 200 , rate = 3)
p.wait() | StarcoderdataPython |
4817785 | <reponame>radicalgraphics/Pillow
from tester import *
from PIL import Image
def test_sanity():
bbox = lena().getbbox()
assert_true(isinstance(bbox, tuple))
def test_bbox():
# 8-bit mode
im = Image.new("L", (100, 100), 0)
assert_equal(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75))
... | StarcoderdataPython |
4804152 | """
Django settings for filmer project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from... | StarcoderdataPython |
3352635 | import csv
from random import randint
from datetime import datetime
from datetime import timedelta
from functools import reduce
candidates = ['<NAME>', '<NAME>', '<NAME>']
cuss_words = ['fuck', 'shit', 'ass', 'bitch',
'douche', 'dick', 'damn', 'covfefe']
# Three hours in `interval` second intervals.
i... | StarcoderdataPython |
3260356 | <filename>tools/_generic/randomize-csv.py
#!/usr/bin/env python3
import csv
import re
from argparse import ArgumentParser
from collections import defaultdict
from random import shuffle
from pprint import pprint
config = None
limit = -1
def randomize():
with open(config.srcfile, "r") as csvfile:
reader ... | StarcoderdataPython |
1745419 | from __future__ import unicode_literals
import json
import time
import django
import django.utils.timezone as timezone
from django.test import TestCase, TransactionTestCase
from rest_framework import status
import error.test.utils as error_test_utils
import job.test.utils as job_test_utils
import queue.test.utils as... | StarcoderdataPython |
3365518 | import mercadopago
import json
mp = mercadopago.MP("ACCESS_TOKEN")
payment = mp.post("/v1/payments", {
"transaction_amount": 100,
"token": "<KEY>",
"description": "Title of what you are paying for",
"installments": 1,
"payer": {
"type": "customer",
"id":... | StarcoderdataPython |
1741945 | <filename>pyfileconf_datacode/config.py
from typing import Iterable, Dict, List
from pyfileconf.selector.models.itemview import ItemView
def config_dependencies_for_section_path_strs(
section_path_strs: Iterable[str],
) -> Dict[str, List["ItemView"]]:
from pyfileconf import context
from pyfileconf.select... | StarcoderdataPython |
3355315 | <reponame>rafarbop/Python<gh_stars>0
# Desafio 27 Curso em Video Python
# Este programa ler o nome completo de uma pessoa e mostra o primeiro e o último nome.
# By Rafabr
import os
os.system('clear')
print('\nDesafio 27')
print('Este programa ler o nome completo de uma pessoa e mostra o primeiro e o último nome.\n\... | StarcoderdataPython |
3232867 | from .base import Base
from ..responses import user
class UserCategory(Base):
async def get_me(self, **kwargs) -> user.User:
params = self.get_set_params(locals())
return user.User(
**await self.api.request(
"getMe", params
)
)
| StarcoderdataPython |
3207456 | <gh_stars>1-10
from vedo import Plotter
from morphapi.api.neuromorphorg import NeuroMorpOrgAPI
api = NeuroMorpOrgAPI()
# ---------------------------- Downloading metadata --------------------------- #
# Get metadata for pyramidal neurons from the mouse cortex.
metadata, _ = api.get_neurons_metadata(
size=10, #... | StarcoderdataPython |
150759 | """
The program SUMS all of the NUMBERS entered by the USER,
while ignoring any input that is not a VALID NUMBER.
"""
# Import MATH module
import math
# Acquisition and Control of the DATA entered by the USER
number = input("Enter the NUMBER to add: ")
numbers = []
while number != "":
try:
# Storing the ... | StarcoderdataPython |
4837862 | import matplotlib.pyplot as plt
import mdtraj as md
from contact_map import ContactMap
pdb_list = [ "../pdb_dir_1_500ns/frame0.pdb",
"../pdb_dir_5001_6000ns/frame4164.pdb"]
# Program takes about several minutes to finish
# It is a bit slow;
for i in range(len(pdb_list)):
pdb = md.load_pdb(pdb_list[i])... | StarcoderdataPython |
1625486 | from django.contrib import admin
from django.urls import path, include
from . import views
# /student/..
urlpatterns = [
path('', views.studentDashboard, name="student_dashboard"),
path('postad/<str:pk>/', views.postAd, name="post_ad"),
path('ads/', views.Ads, name="ads"),
path('wishlist/', views.w... | StarcoderdataPython |
1728514 | MYSQL_USER = "root"
MYSQL_DATABASE = "database"
MYSQL_HOST = "127.0.0.1"
MYSQL_PORT = 3306
MYSQL_PASSWORD = "password"
PORT = 8080
HOST = "127.0.0.1"
DEBUG = False
REQUESTS_PER_PAGE = 10
BACKEND_REQUESTS_PER_PAGE = 5
NETEASE_PHONE = "12312345678"
NETEASE_PASSWORD = "password"
NETEASE_BACKEND = "http:/... | StarcoderdataPython |
3251241 | # -*- coding: utf-8 -*-
"""
* TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-蓝鲸 PaaS 平台(BlueKing-PaaS) available.
* Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in complianc... | StarcoderdataPython |
96669 | <reponame>zhichengMLE/python-design-pattern<gh_stars>0
# The observer pattern is a software design pattern in which an object, called the subject,
# maintains a list of its dependents, called observers, and notifies them automatically of
# any state changes, usually by calling one of their methods.
# See more in wiki: ... | StarcoderdataPython |
3212139 | <gh_stars>0
import numpy as np
import probability_initial
import delay_file
def at2u0(pe,l,L, p_arr):
a = l+1
b = -l
temp = a*p_arr[int(L-1-l)][int(pe)]+b*p_arr[int(L-2-l)][int(pe)]
return temp
def cd2u1(u,cx,dx,nx,Eqflag,Syncflag,L=None,PE=None,perPE=None,pstart=None,pend=None,ATolFLAG=None... | StarcoderdataPython |
1713495 | <filename>URI-1042_Sort_Simples.py
/*-------------------*
| <NAME> |
| URI 1042 |
| Sort Simples |
*--------------------*/
# -*- coding: utf-8 -*-
A,B,C = map (int,input().split())
LISTA = [A, B, C]
for x in sorted(LISTA):
print (x)
print("")
print(A)
print(B)
print(C) | StarcoderdataPython |
1744290 | <gh_stars>0
#!/usr/bin/python3
# Author: <NAME>
# License: MIT
# ULR: https://github.com/iblis-ms/python_cmake_build_system
import os
import subprocess
from builtins import staticmethod
import sys
import urllib.request
import logging
from .sysOp import SysOp
class Utils:
"""
Class that helps runnin... | StarcoderdataPython |
16001 | <reponame>marin-leonard/marsha
# Generated by Django 3.0.6 on 2020-05-19 14:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("core", "0018_auto_20200603_0620"),
]
operations = [
migrations.AddField(
model_name="video",
... | StarcoderdataPython |
1701705 | <filename>examples/plugins/workbench/AcmeLabUsingEggs/src/acme.acmelab/acme/acmelab/api.py
from acmelab import Acmelab
| StarcoderdataPython |
1658465 | <filename>abhisek/Separate_word_start_with_P.py
'''
Write a Python program to match if two words from a list of words starting with letter 'P'.
'''
import re
# Sample strings.
words = ["Python PHP", "Java JavaScript", "c c++"]
for word in words:
match = re.search(r'(P\w+)\s{1,}(P\w+)', word)
if match:
p... | StarcoderdataPython |
1747380 | <reponame>pka/ical2json
import argparse
import json
from datetime import date, timedelta, datetime
from icalevents import icalevents, icalparser
def ical_to_json(url, start, days):
end = start + timedelta(days=days)
events = icalevents.events(
url=url,
start=start,
end=end
)
ev... | StarcoderdataPython |
3310070 | <reponame>unistra/eva
from django.conf.urls import url
from .views import DegreeListView, DegreeTypeListView, DegreeTypeCreate, \
DegreeTypeUpdate, DegreeTypeDelete, DegreeCreateView, DegreeUpdateView, \
DegreeDeleteView
from django_cas.decorators import login_required
urlpatterns = [
url(r'^list/(?P<filte... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.