id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
66484 | <reponame>PaulWang1905/tensorflow<filename>tensorflow/python/data/experimental/kernel_tests/serialization/csv_dataset_serialization_test.py
# Copyright 2018 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 w... | StarcoderdataPython |
3275005 | <filename>tests/load_raw/conftest.py<gh_stars>0
import datetime
from copy import deepcopy
import pytest
from power_perceiver.load_raw.data_sources.raw_gsp_data_source import RawGSPDataSource
from power_perceiver.load_raw.data_sources.raw_nwp_data_source import RawNWPDataSource
from power_perceiver.load_raw.data_sourc... | StarcoderdataPython |
3215406 | import torch
import torch.nn as nn
import torch.nn.functional as F
class RCAN(nn.Module):
"""
RCAN:
Image Super-Resolution Using Very Deep Residual Channel Attention Networks,
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
"""
def __init__(self, upscale_factor, input_channels, channel_mas... | StarcoderdataPython |
4605 | <reponame>zjj2wry/dvc<filename>dvc/__init__.py
"""
DVC
----
Make your data science projects reproducible and shareable.
"""
import os
import warnings
VERSION_BASE = '0.23.2'
__version__ = VERSION_BASE
PACKAGEPATH = os.path.abspath(os.path.dirname(__file__))
HOMEPATH = os.path.dirname(PACKAGEPATH)
VERSIONPATH = os.pa... | StarcoderdataPython |
1661996 | from flask import Flask, jsonify
from .db import get_db
def init(app: Flask):
@app.route('/ping')
def ping_api():
return jsonify({ 'message': 'pong' })
@app.route('/db')
def db_api():
db = get_db()
collection = db['temp']
| StarcoderdataPython |
1661331 | <reponame>jindonghuo/Multiphyscs-modelling-of-thermal-plasma-in-Fluent-Solver
import cv2
import numpy as np
import os
import sys
from os.path import isfile, join
import time
# this file is created by Jindong, <EMAIL>
start_time = time.time()
initdirectory = os.getcwd()
fig_path = os.path.join(os.getcwd(), 'f... | StarcoderdataPython |
79172 | from itertools import count
from problem import Problem
from utils.math import factors
from utils.primes import sieve_of_eratosthenes
class HighlyDivisibleTriangleNumber(Problem, name="Highly divisible triangular number", expected=76576500):
@Problem.solution()
def brute_force(self):
for i in count(3... | StarcoderdataPython |
116379 | # @Time : 2020/11/14
# @Author : <NAME>, <NAME>
# @Email : <EMAIL>
# UPDATE
# @Time : 2021/4/12
# @Author : <NAME>
# @Email : <EMAIL>
"""
textbox.evaluator.abstract_evaluator
#####################################
"""
import numpy as np
class AbstractEvaluator(object):
""":class:`AbstractEvaluator` is an ... | StarcoderdataPython |
3375074 | """Routes for logged-in application."""
from flask import Blueprint, render_template, redirect, jsonify, request
from appdb import db
from datetime import date, timedelta, datetime, timezone
from databases.models import Sales, Funnels, Emails
import requests
from decimal import Decimal
from collections import Counter
... | StarcoderdataPython |
83469 |
class CircularBufferError(Exception):
pass
class CircularBuffer(object):
"""Unlike traditional circular buffers, this allows reading and writing
multiple values at a time. Additionally, this object provides peeking and
commiting reads. See test_circular_buffer.py for examples.
The interface is ... | StarcoderdataPython |
1634933 | # =============================
# tomato-clock.py
# this is a simple application to arrange your time more properly
# author @NearlyHeadlessJack (https://github.com/NearlyHeadlessJack)
# copyright (c) 2022 N.H.J.
# =============================
# import=======================
from pyecharts.charts import Bar
import ti... | StarcoderdataPython |
1685330 | # Ex38: MAIOR E MENOR
# ------------------------------
# Escreva um prog que leia dois números inteiros.
# Diga "O 1º número é maior", "O 2º n. é maior" ou "Os números são iguais."
print("Digite dois números: ")
num1 = float(input('>>>\t'))
num2 = float(input('>>>\t'))
if num1 == num2:
print('Os números são iguais.'... | StarcoderdataPython |
146121 | """Publishes multiple messages to a Pub/Sub topic with an error handler."""
import time
from google.cloud import pubsub_v1
# TODO(developer)
project_id = ""
topic_id = "poschairdata"
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)
futures = dict()
def get_callback(f,... | StarcoderdataPython |
1661255 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/12 17:10
# @Author : 云帆
# @Site :
# @File : train_seq2seq.py
# @Software: PyCharm
import dataset
import argparse
from seq2seq import EncoderLayer, DecoderLayer, AttentionLayer, Seq2Seq
import torch
import torch.optim as optim
import torch.nn as... | StarcoderdataPython |
1675062 | from app import create_app
from flask_script import Manager
from flask_migrate import MigrateCommand
import os
# 创建应用实例
app = create_app(os.environ.get('FLASK_CONFIG') or 'default')
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| StarcoderdataPython |
157037 | <reponame>sojin-project/scrape-academy
# type: ignore
from bs4 import BeautifulSoup
from scrapeacademy import context, run
context.request_delay = 1 # wait 1 second between requests
context.headers["User-Agent"] = "Moziiiila"
async def run_simple():
page = await context.get("https://www.python.jp")
soup =... | StarcoderdataPython |
3261796 | <filename>assets/hangman_words.py<gh_stars>0
animals = [
'aardvark',
'aardwolf',
'abyssinian',
'addax',
'ainu',
'ayeaye',
'aussiedor',
'arcticfox',
'amurleopard',
'anchovies',
'babirusa',
'baboon',
'beabull',
'bananaspider',
'barb',
'barnowl',
'beaski'... | StarcoderdataPython |
3279632 | <gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# Write a computer program that implements the Beasley-Springer-Moro algorithm
# imports
import math
import random
# project imports
import rand
import halton
import bfs
# Write a computer program that implements the Beasley-Springer-Moro algorithm
#
# Pseducode... | StarcoderdataPython |
1796666 | <reponame>sferanchuk/d3b_charts<filename>d3b/jscharts/pca.py<gh_stars>0
#!/usr/bin/python
# Turn on debug mode.
import sys
tfp = '/home/sferanchuk/.local/lib/python2.7/site-packages'
if tfp in sys.path:
sys.path.remove( tfp )
import cgi
import cgitb
cgitb.enable()
import csv
import numpy as np
from sklearn import man... | StarcoderdataPython |
49032 | #!/bin/python
# Extracts messages.data into headers and the actual message
import binascii
import pprint
import click
def hexToStr(byte):
return binascii.hexlify(byte).decode()
def printByte(label, byte):
print(label + ':\t' + hexToStr(byte))
@click.command()
@click.argument('path')
def extractMessage(pa... | StarcoderdataPython |
4829311 | """
"""
from django.db.models import Q
from rest_framework import viewsets
from rest_framework.decorators import action
from revibe._helpers import responses
from revibe.exceptions import api
from accounts.models import CustomUser
from accounts.permissions import TokenOrSessionAuthentication
from accounts.referrals.... | StarcoderdataPython |
5856 | # ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
class DashboardInfo:
MODEL_ID_KEY = "id" # To match Model schema
MODEL_INFO_FILENAME = "model_info.json"
RAI_INSIGHTS_MODEL_... | StarcoderdataPython |
1666248 | import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from data.others.home_background_script import script
import visdcc
from building_blocks import *
from callbacks import *
prefix="home"
print("Loading "+prefix.capitalize()+" ...")
layout=dbc.Col([
... | StarcoderdataPython |
3214505 | from typing import Tuple
from sqlalchemy import select, String
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload, aliased
from sqlalchemy import func
from . import models, schemas
async def get_user(async_session: AsyncSession, user_id: int):
result = await async_session.exe... | StarcoderdataPython |
70442 | # Copyright: Copyright (c) 2020., <NAME>
# Author: <NAME> <adam at jakab dot pro>
# License: See LICENSE.txt
import math
from abc import ABC
from abc import abstractmethod
from random import randint
from beets.library import Item
from confuse import Subview
from beetsplug.goingrunning import common
pickers = {
... | StarcoderdataPython |
4813912 | import yaml
import conversion
def yaml_as_python(val):
"""Convert YAML to dict"""
try:
return yaml.safe_load_all(val)
except yaml.YAMLError as exc:
return exc
with open('config.yaml','r') as input_file:
results = yaml_as_python(input_file)
for experiment_info in results:
p... | StarcoderdataPython |
1670335 | <gh_stars>1-10
from aiogram.dispatcher.filters import CommandStart
from aiogram.dispatcher import FSMContext
from create import video_link
from config import unknown
from loader import dp, bot
from aiogram.types import (
InlineKeyboardMarkup,
InlineKeyboardButton
)
from aiogram import types
from state... | StarcoderdataPython |
3254104 | <reponame>migvill5/pharmanager<filename>src/inventory/migrations/0009_auto_20210524_1601.py
# Generated by Django 3.1.7 on 2021-05-24 21:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('inventory', '0008_auto_20210524_1600'),
]
operations = [
... | StarcoderdataPython |
1618280 | <reponame>DeepP2667/DocuMiner
import nltk
from nltk.corpus import stopwords
def TagText(text, splitByWord = True,removeStop = True, removePunc = True):
if splitByWord:
tokens = nltk.word_tokenize(text)
else:
tokens = text
if removeStop:
stop_words = set(stopwords.words('english... | StarcoderdataPython |
23348 | <gh_stars>0
import numpy as np
def convolucion(Ioriginal, kernel):
'''Método encargado de realizar una convolución a una imagen
Entrada:
Ioriginal - imagen original en forma de matríz
kernel - kernel para barrer la imagen
Salida:
res - imagen resultante'''
#fr - filas, cr - columnas
fr = len(Ioriginal)-(len(k... | StarcoderdataPython |
3361292 | #!/usr/bin/env python3
# Copyright 2019 Oath, Inc., see LICENSE.txt for full details
"""
Flurry's Crash service can symbolicate the crashes reported by Flurry's SDK.
This script uploads the symbols required to properly symbolicate crashes from
iOS applications.
How to send iOS symbols
-----------------------
1. Ensure ... | StarcoderdataPython |
1712497 | <gh_stars>1-10
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
# Architectures from Facebook are adjusted such that Crowd Counting can be performed.
import torch
import torch.nn as nn
from functools import partial
from timm.models.vision_transformer import VisionTransformer, _cfg
from timm.models.... | StarcoderdataPython |
1786698 | #!/usr/bin/env python
import argparse
from matplotlib import pyplot as plt
from condel._DEPRECATED_.weights import load_weights
from transfic.cmdhelper import DefaultCommandHelper
def main():
parser = argparse.ArgumentParser(
description="Plot cutoffs")
cmd = DefaultCommandHelper(parser)
parser.add_argument(... | StarcoderdataPython |
1790878 | <reponame>ashidagithub/ASD_WinForms
# -*- coding: UTF-8 -*-
# ------------------------(max to 80 columns)-----------------------------------
# author by : (学员ID)
# created: 2019.11
# Description:
# 初步学习 WinForm 编程 ( Window )
# ------------------------(max to 80 columns)-----------------------------------
import t... | StarcoderdataPython |
3201507 | <filename>chatbot.py
import json
import ibm_watson
import json
import db
INTENT_DOCTOR = 'Register_Doctor'
INTENT_COMMUNITY = 'Register_Community'
with open('config.json') as config_file:
config = json.load(config_file)
service = ibm_watson.AssistantV2(
iam_apikey=config["ibm_assistant"]["iam_apikey"],
v... | StarcoderdataPython |
3226700 | <filename>Plutupus/Types/AssetClass.py
import json
from Plutupus.Types.TokenName import TokenName
from Plutupus.Types.CurrencySymbol import CurrencySymbol
class AssetClass(object):
def __init__(self, currency_symbol, token_name):
self.__currency_symbol = currency_symbol
self.__token_name = token... | StarcoderdataPython |
67445 | <filename>pirates/inventory/InventoryUIWeaponContainer.py
# File: I (Python 2.4)
from direct.gui.DirectGui import *
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from pirates.piratesgui import GuiPanel, PiratesGuiGlobals
from pirates.piratesbase import PiratesGlobals
from pirates.pirat... | StarcoderdataPython |
27044 |
discovery_node_rpc_url='https://ctz.solidwallet.io/api/v3'
request_data = {
"jsonrpc": "2.0",
"id": 1234,
"method": "icx_call",
"params": {
"to": "cx0000000000000000000000000000000000000000",
"dataType": "call",
"data": {
... | StarcoderdataPython |
3389544 | # 1. creati un file nou test_login si acolo faceti teste pt pagina de login
# c) logati-va cu parola gresita -> verificati textul de la eroare
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
def test_login_c():
... | StarcoderdataPython |
1727290 | """When called as a script, consumes the input"""
import sys
if __name__ == '__main__':
for line in sys.stdin:
pass
| StarcoderdataPython |
3353209 | <reponame>13alvone/iphone_backup_parser
import subprocess
import plistlib
import argparse
import sqlite3
import logging
import magic
import math
import time
import re
import os
# Global Variables
start_time = time.time()
report_list = []
url_set = set()
output_database = {}
file_walk_database = {}
sms_db_hash = None
s... | StarcoderdataPython |
1760522 | #Copyright 2016 <NAME>.
#Distributed under the MIT License. See LICENSE in root of project.
"""
Module that holds log functionality.
In general you dont need to include this in your kervi code as the spine class holds a refference
to a fully configured log.
"""
import logging
import os
class BraceMessage(object):
... | StarcoderdataPython |
1630416 |
# Copyright 2019 DeepMind Technologies Limited and Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
3215042 | def have(obj, *arg):
# print(obj)
# print(arg)
stand = obj
try:
for i in range(0, len(arg)):
# print("stand")
# print(stand)
# print("arg[i]")
# print(arg[i])
stand = stand[arg[i]]
# print("stand ==")
# print(sta... | StarcoderdataPython |
105547 | from torch.utils.data import Dataset
from PIL import Image
import os
import glob
from torchvision import transforms
class GanDataset(Dataset):
def __init__(self, data_folder, from_style, to_style, image_size):
self.data_folder = data_folder
self.image_size = image_size
if not os.path.exis... | StarcoderdataPython |
1631431 | <gh_stars>1-10
"""
PyDarshan provides direct log access for reading binary Darshan logs.
PyDarshan also provides a suite of analysis utilities.
"""
__version__ = '3.3.0.3'
__darshanutil_version__ = '3.3.0'
import logging
logger = logging.getLogger(__name__)
options = {
}
#from darshan.backend.cffi_backend import... | StarcoderdataPython |
3340247 | <filename>bot.py
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, Location
import states
import config
import os
import ast
TOKEN = config.TOKEN
def start(update, context):
load_data(update, context)
conte... | StarcoderdataPython |
47045 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Naranjo, <NAME> <<EMAIL>>
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
... | StarcoderdataPython |
3300580 | # Copyright 2020, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | StarcoderdataPython |
10917 | <filename>adsrefpipe/refparsers/handler.py
# -*- coding: utf-8 -*-
from adsrefpipe.refparsers.CrossRefXML import CrossReftoREFs
from adsrefpipe.refparsers.ElsevierXML import ELSEVIERtoREFs
from adsrefpipe.refparsers.JATSxml import JATStoREFs
from adsrefpipe.refparsers.IOPxml import IOPtoREFs
from adsrefpipe.refparsers... | StarcoderdataPython |
4815904 | <filename>plugin/src/test/resources/intentions/afterTypeAnnotation3.py
def g(x: object=None):
return x
| StarcoderdataPython |
3219546 | # Copyright Materialize, Inc. and contributors. All rights reserved.
#
# Use of this software is governed by the Business Source License
# included in the LICENSE file at the root of this repository.
#
# As of the Change Date specified in that file, in accordance with
# the Business Source License, use of this software... | StarcoderdataPython |
184854 | """Module for Bresenham kernel"""
import numpy as np
from copa_map.util.occ_grid import OccGrid
import cv2
class KernelGrid(OccGrid):
"""Class for creating an occupation map with widened walls"""
def __init__(self, base_occ_map: OccGrid, digitize_size=0.2, num_of_borders=2):
"""
Constructor
... | StarcoderdataPython |
3387650 | <reponame>Discngine/rdkit_tethered_minimization<gh_stars>1-10
import sys
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import rdFMCS
from rdkit.Chem.rdMolAlign import AlignMol
#from rdkit.Chem.rdMolTransforms import GetDihedralDeg, SetDihedralDeg
"""Script taking a single reference molecule an... | StarcoderdataPython |
175156 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Title '''
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright IBM Corp. 2020, 2021'
import unittest
import torch
from diffsnn.nonparametric.kernel import Kernel
from diffsnn.nonparametric.basis import Epanechnikov
class TestKernel(unittest.Tes... | StarcoderdataPython |
4835581 | expressao = str(input("informe sua expressao"))
contD =0
contE =0
#expressao.append(str(input("informe sua expressao:")))
for c in range(0,len(expressao)):
if expressao[c] == '(':
contD = contD + 1
elif expressao[c] == ')':
contE = contE +1
print(f"na expressao possui {contE} de esquerda e {c... | StarcoderdataPython |
9179 | <reponame>AlexandruScrob/fast_api_proj_2<gh_stars>0
import pytest
from httpx import AsyncClient
from conf_test_db import app
from tests.shared.info import category_info, product_info
@pytest.mark.asyncio
async def test_new_product():
async with AsyncClient(app=app, base_url="http://test") as ac:
category... | StarcoderdataPython |
1601551 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: one-vs-rest-param.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as... | StarcoderdataPython |
45854 | <reponame>atlan-antillia/EfficientDet-USA-RoadSigns<gh_stars>0
# ==============================================================================
# Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with... | StarcoderdataPython |
1786177 | from pathlib import Path
import imageio
import fsspec
import numpy as np
import matplotlib.pyplot as plt
import datetime
from dateutil import tz
import pandas as pd
from coastcam_funcs import *
from calibration_crs import *
from rectifier_crs import *
def rectify_caco_func(impaths,fs):
"""
Rectify one pair of... | StarcoderdataPython |
1639275 | #!/bin/env/python
import numpy as np
import pandas as pd
from superMASS import batched
import tarfile
def load_file(archive, fp):
"""
Utility function that reads a tar file directly into a numpy array.
Parameters
----------
archive : str
The archive file to read.
fp : str
The... | StarcoderdataPython |
1721128 | <filename>04Aula16-09/ex01.py
for i in range(10):
print(i)
alunos = ['Maria', "daniel", 'joao']
for nome in alunos:
print(nome) | StarcoderdataPython |
104566 | <filename>python/cac_tripplanner/destinations/migrations/0037_auto_20180412_1256.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-12 16:56
from django.db import migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('destinations', '0036_extr... | StarcoderdataPython |
3338931 | <filename>hard-gists/931406/snippet.py<gh_stars>10-100
# -*- coding: utf-8 -*-
import memcache
import random
NS_KEY_RANGE_MAX = 1000000
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
def clear_ns(ns):
mc.incr(_compute_ns_key(ns))
def _compute_key(key, ns=None):
if ns:
return '%s_%d_%s' % (ns... | StarcoderdataPython |
157170 | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.shortcuts import render
from companies.models import Company
from jobapplications.models import JobApplication
from joblistings.models import Job
from accounts.models import Candidate
from django.http import HttpRes... | StarcoderdataPython |
3305982 | <reponame>JR-1991/pyDaRUS<gh_stars>1-10
from pyDaRUS.metadatablocks.astrophysics import Astrophysics
from pyDaRUS.metadatablocks.citation import Citation
from pyDaRUS.metadatablocks.enzymeML import EnzymeMl
from pyDaRUS.metadatablocks.journal import Journal
from pyDaRUS.metadatablocks.engMeta import EngMeta
from pyDaR... | StarcoderdataPython |
1770333 | <reponame>AtharvRedij/leetcode-solutions
'''
URL: https://leetcode.com/problems/water-bottles/
Difficulty: Easy
Description: Water Bottles
Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.
The operation of drinking a full water bottle turns it into an e... | StarcoderdataPython |
1648165 | <reponame>nathanhere/pg_auto_failover
import pgautofailover_utils as pgautofailover
from nose.tools import *
import os
cluster = None
monitor = None
node1 = None
node2 = None
def setup_module():
global cluster
cluster = pgautofailover.Cluster()
def teardown_module():
cluster.destroy()
def check_ssl_fi... | StarcoderdataPython |
177652 | <filename>examples/piston_expander.py
""""
Example simulation for a reciprocating piston expander
(c) <NAME>, 2013
"""
##########################################
### Part 1. Imports ###
##########################################
# Here we import some python packages
from __future__ import division... | StarcoderdataPython |
34475 | import pyaf.Bench.TS_datasets as tsds
import pyaf.Bench.YahooStocks as ys
import warnings
symbol_lists = tsds.get_yahoo_symbol_lists();
y_keys = sorted(symbol_lists.keys())
print(y_keys)
k = "nysecomp"
tester = ys.cYahoo_Tester(tsds.load_yahoo_stock_prices(k) , "YAHOO_STOCKS_" + k);
with warnings.catch_warnings():
... | StarcoderdataPython |
3263818 | """
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
Fixture for clearing out 'MoveOutput' folders from \dev and \dev\PROJECT
"""
# Import builtin libraries
import pyt... | StarcoderdataPython |
3366072 | <filename>python3/05-if.py
#How many years ago did you buy your car?
years = 3
if years <= 3:
print("It's a new car!")
elif years > 10:
print("It's an old car!")
else:
print("It's a car! :)")
# Simplified version
print("It's a new car!" if years <= 3 else "It's an old car!") | StarcoderdataPython |
3263266 | <gh_stars>0
test = ['123']
for thing in test:
print(thing)
| StarcoderdataPython |
1718593 | import logging
from django.utils.deprecation import MiddlewareMixin
from user.models import User
from lib.http import render_json
from common import errors
errorlogger = logging.getLogger('err')
class AuthMiddleware(MiddlewareMixin):
URL_WHITE_LIST = [
'/usr/api/submit_phone',
'/usr/api/submit_vc... | StarcoderdataPython |
75133 | <filename>pyparsvd/parsvd_base.py
import numpy as np
from mpi4py import MPI
# Import custom Python packages
import pyparsvd.postprocessing as post
# For shared memory deployment:
# `export OPENBLAS_NUM_THREADS=1`
class ParSVD_Base(object):
"""
PyParSVD base class. It implements data and methods shared
across t... | StarcoderdataPython |
148664 | import sys
import copy
import logging
import warnings
import collections
from typing import Callable, Union, Any, Type, Dict, Tuple, Iterable
import torch
from torch import nn
from torch.optim.optimizer import Optimizer
from torch.nn.parallel import DataParallel, DistributedDataParallel
import argus
from argus import... | StarcoderdataPython |
128472 | """
In this file you can see examples of how to process the tweets that have been tracked and stored in a file.
Also in this case, you should try to understand the code and, most importantly, how you can reuse it in your implementation.
Note that the Twitter "stream" listener stores tweets in the JSON format. JSON is ... | StarcoderdataPython |
3285701 | <filename>week3/3.04 files/step04 avg.py<gh_stars>1-10
def get_stat(l):
all_avg = [0 for i in range(3)]
all_summ = [0 for i in range(3)]
priv_avg = list()
for s in l:
score = s.split(';')
summ = 0
for i in range(1, len(score)):
summ += int(score[i])
all_s... | StarcoderdataPython |
3240801 | import tensorflow as tf
from tensorflow import keras
import numpy as np
from PIL import Image
import os
print('tensorflow version is {}'.format(tf.__version__))
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images,
test_labels) = fashion_mnist.load_dat... | StarcoderdataPython |
27453 | <reponame>silverriver/Stylized_Dialog<filename>WDJN/eval/svm_eval_acc.py
import torch
import torch.nn as nn
import sklearn
from sklearn import svm
from sklearn import metrics
from sklearn.externals import joblib
import numpy as np
from text import Vocab
import random
import os
import json
from tqdm import tqdm, trange
... | StarcoderdataPython |
134147 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2018-2018 by ExopyI3py Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------... | StarcoderdataPython |
1762322 | <gh_stars>1-10
## Reverse String
# https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/539/week-1-june-1st-june-7th/3350/
#
# ---
#
#### Problem Statement:
#Write a function that reverses a string. The input string is given as an array of characters char[].
#
#Do not allocate extra space for another ... | StarcoderdataPython |
1779444 | from .f1 import F1
async def setup(bot):
cog = F1(bot)
bot.add_cog(cog)
| StarcoderdataPython |
3380401 | nums = list(range(1,10))
for num in nums:
if num == 1:
print('1st')
elif num == 2:
print('2nd')
elif num == 3:
print('3rd')
else:
print(str(num) + 'th') | StarcoderdataPython |
1618506 | import numpy as np
import matplotlib.pyplot as plt
import cvxpy as cvx
from scipy.linalg import circulant
from scipy.stats import norm
import seaborn as sns
import pandas as pd
from scipy.integrate import solve_ivp
from scipy.spatial.distance import cdist
def BinaryRandomMatrix(S,M,p):
r = np.random.rand(S,M)
... | StarcoderdataPython |
1631273 | <filename>config.py
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'app secret key')
@staticmethod
def init_app(app):
pass
class DevelopConfig(Config):
DEBUG = True
class TestConfig(Config):
TESTING = True
class ProdConfig(Config):
pass
config = {
'd... | StarcoderdataPython |
1698412 | """
Short script to send alerts
Usage: python check_abandoned.py source_email target_email user pass database
Note passwords can be piped in:
echo "pass" | python check_abandoned.py source_email target_email user pass database
I won't pretend to know enough about security to know how to do this securely, but
th... | StarcoderdataPython |
176232 | <reponame>Xiretza/pyVHDLParser
from unittest import TestCase
from pyVHDLParser.Token import WordToken, StartOfDocumentToken, SpaceToken, CharacterToken, EndOfDocumentToken
from pyVHDLParser.Blocks import StartOfDocumentBlock, EndOfDocumentBlock
from pyVHDLParser.Blocks.Comm... | StarcoderdataPython |
1665695 | """Removed unique index from repo
Revision ID: 2e455c06266d
Revises: <PASSWORD>
Create Date: 2015-03-20 12:56:42.659248
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alem... | StarcoderdataPython |
3250643 | <reponame>resulemreaygan/codewars
"""
Author: <NAME>
"""
"""
Project Description: Even or Odd
Create a function (or write a script in Shell) that takes an integer as an argument and
returns "Even" for even numbers or "Odd" for odd numbers.
"""
def even_or_odd(number):
return "Even" if number % 2 == 0 else "Odd"... | StarcoderdataPython |
1732636 | <filename>pydsa/bfs.py
# Breadth First Search
# Complexity: O(V+E)
def bfs(graph, start):
"""
Traverses a graph using Breadth First Search Algorithm.
It returns a set of nodes traversed.
"""
visited, queue = set(), [start]
while queue:
node = queue.pop(0)
if node not in visited... | StarcoderdataPython |
16290 | <filename>eda_rf.py
"""
Final Project
EDA
"""
import pandas as pd
import matplotlib.pyplot as plt
from mlxtend.plotting import scatterplotmatrix
import numpy as np
import seaborn as sns
from imblearn.over_sampling import SMOTE
from sklearn.utils import resample
from mlxtend.plotting import heatmap
from sklearn.ensemb... | StarcoderdataPython |
3259698 | <reponame>RideGreg/LeetCode
# Time: O(n)
# Space: O(1)
# 821 weekly contest 81 4/21/2018
# Given a string S and a character C,
# return an array of integers representing the shortest distance
# from the character C in the string.
#
# Example 1:
#
# Input: S = "loveleetcode", C = 'e'
# Output: [3, 2, 1, 0, 1, 0, 0, ... | StarcoderdataPython |
1713513 | import random
invalid = "\n\nInvalid input. Try again?\n"
def diceroll():
while True:
# numdooside = input("What would you like to roll?\n")
# num, doo, side, = numdooside.split(",")
num = int(input("Amount?\n"))
side = int((input("Sides?\n")))
# max = int(side)
# tim... | StarcoderdataPython |
52424 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import logging
import linecache
import copy
from string import Template
logger = logging.getLogger(__name__)
class ExtraDict(dict):
""" Creates a dict-like structure where we can store the new values of
variables, while keeping the old (initial) ones as ... | StarcoderdataPython |
1715987 | from jadi import component
import subprocess
import os
from aj.api.http import url, HttpPlugin
from aj.api.endpoint import endpoint, EndpointError
from reconfigure.configs import HostsConfig
from reconfigure.items.hosts import AliasData, HostData
@component(HttpPlugin)
class Handler(HttpPlugin):
def __init__(sel... | StarcoderdataPython |
3374052 | import discord
import asyncio
import csv
import yokocalc as yoko
import clothing
import sys
if len(sys.argv) < 2:
print ("Please pass in the bot token as a command line argument.")
sys.exit()
hair = yoko.load_wardrobe('wardrobe/hair.csv')
dresses = yoko.load_wardrobe('wardrobe/dresses.csv')
coats = yoko.load_wardro... | StarcoderdataPython |
130737 | # Time: O(nlogk + sqrt(k)^2) = O(nlogk + k)
# Space: O(sqrt(k)), number of factors of k is at most sqrt(k)
import collections
# math, number theory
class Solution(object):
def countPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gc... | StarcoderdataPython |
3392655 | """Example of using hangups to get conversation events."""
import hangups
from common import run_example
MAX_REQUESTS = 3
MAX_EVENTS = 5
async def get_events(client, args):
_, conversation_list = await hangups.build_user_conversation_list(client)
try:
conversation = conversation_list.get(args.con... | StarcoderdataPython |
3205355 | <gh_stars>1-10
from otree.api import Currency as c, currency_range
from . import pages
from ._builtin import Bot
from .models import Constants
import time
from otree.api import Submission
class PlayerBot(Bot):
def play_round(self):
yield pages.Demographics_eng, dict(
age_e = 24,
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.