id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8139976 | <filename>ch08/ans73.py<gh_stars>10-100
import joblib
import numpy as np
import torch
from torch import nn, optim
X_train = joblib.load('ch08/X_train.joblib')
y_train = joblib.load('ch08/y_train.joblib')
X_train = torch.from_numpy(X_train.astype(np.float32)).clone()
y_train = torch.from_numpy(y_train.astype(np.int64)... | StarcoderdataPython |
1884316 | <gh_stars>0
# -*- coding: utf-8 -*-
import logging
from docker.auth import INDEX_NAME, resolve_repository_name
from docker.utils import parse_repository_tag
from .docker_registry import DOCKER_HUP_REGISTRY, LocalRegistry, RemoteRegistry
logger = logging.getLogger(__name__)
class Image(object):
def __init__(s... | StarcoderdataPython |
1821463 | <reponame>3ll3d00d/qvibe
import gzip
import json
import logging
import os
import sys
import time
from model.charts import ColourProvider
from model.measurements import MeasurementStore
from model.rta import RTA
from model.save import SaveChartDialog, SaveWavDialog
from model.spectrogram import Spectrogram
from model.v... | StarcoderdataPython |
8026419 | from const import *
import random
import pygame
class Bonus(pygame.sprite.Sprite):
def __init__(self, bonus_image_dict, meteor_center):
pygame.sprite.Sprite.__init__(self)
self.type = random.choice(['hp', 'gun', 'shield', 'star'])
self.image = bonus_image_dict[self.type]
se... | StarcoderdataPython |
6448961 | import argparse
import os
from os.path import dirname
import subprocess
import time
import json
import datetime
import random
import shlex
import requests
from kafka import KafkaConsumer
from analyze import analyze_kafka_dump
class PopenWrapper:
"""
This class is a context manager that wraps subprocess.Pope... | StarcoderdataPython |
11330954 | """This module contains auxiliary functions for the creation of tables in the main notebook."""
import json
import scipy
import numpy as np
from numpy import nan
import pandas as pd
import pandas.io.formats.style
import seaborn as sns
import statsmodels as sm
import statsmodels.formula.api as smf
import statsmodels.ap... | StarcoderdataPython |
5154681 | # -*- coding: utf-8 -*-
import datetime
from urllib.parse import urlparse
def sources_list(sources, params):
"""
Adds defined list of sources to params
Parameters
----------
sources : list
Payment sources
params : dict
Default params
Returns
-------
dict
p... | StarcoderdataPython |
381619 | ncks -O -d y,17,17,1 WAD_1ts_00010101_00010101_grid_T.nc sshtime.nc
ncks -4 -A -v gdepw_0,ht_wd -d y,17,17,1 -d z,10,10,1 -C mesh_mask.nc sshtime.nc
python2.7 matpoly2.py sshtime.nc
animate wadfr*.png
| StarcoderdataPython |
5106759 | <gh_stars>0
import requests
endpoint = "http://localhost:8000/api/"
get_response = requests.post(endpoint, json={})
print(get_response.json()) | StarcoderdataPython |
150375 | #
# @lc app=leetcode id=75 lang=python3
#
# [75] Sort Colors
#
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
a, i, b = 0, 0, len(nums) - 1
while i <= b:
n_i = nums[i]
if n_i... | StarcoderdataPython |
393109 | <filename>Financely/basic_app/sentiment_analysis.py
from transformers import BertModel, BertTokenizer
import torch
from torch import nn
RANDOM_SEED = 42
torch.manual_seed(RANDOM_SEED)
class_names = ['negative', 'neutral', 'positive']
PRE_TRAINED_MODEL_NAME = 'bert-base-cased'
tokenizer = BertTokenizer.from_pretrained... | StarcoderdataPython |
6631653 |
# https://www.hackerrank.com/challenges//problem
import numpy
if __name__ == '__main__':
N, M = map(int, input().split())
arr = list()
for _ in range(N):
arr.append(list(map(int, input().split())))
numpy_arr = numpy.array(arr)
min_elements = numpy.min(arr, axis = 1)
... | StarcoderdataPython |
5158480 | <filename>gh-pyhwjser/setup.py
import setuptools
setuptools.setup(
name="pyhwjser",
version="0.0.4",
author="KyuzoM",
author_email="<EMAIL>",
description="json-serializable HWSerial",
long_description="json-serializable HWSerial",
url="https://github.com/kyuzom/taskedin",
license="MIT",... | StarcoderdataPython |
6618252 | """
.. _single_electron_test:
Test for Single Electron Module
###############################
.. todo::
* Authors? -RJM
* Docs need love
* Should validate correct instiliation/completion. Right now just spits printouts. -RJM
* Ideally a single test script would test EVERY module, and can be easily ru... | StarcoderdataPython |
8099931 | <filename>Development Resources/Miscellaneous Content/Proto-code Level 3 puzzle.py<gh_stars>0
#The Great Pyramid Treasure Hunt
#Level 3 - Puzzle Door
#Displaying the Puzzle
def puzzle_lines():
print("\n|___|___|___|___|")
print("| | | | |")
print("| ", end="")
def display_puzzle(puzzle):
... | StarcoderdataPython |
1645336 | from sense_hat import SenseHat
import random
import time
sense = SenseHat()
message = "Hello! We are New Media Development :)"
while True:
c_text = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
c_bg = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
sense.show_message(... | StarcoderdataPython |
3230095 | # -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2017 McAfee Inc. - All Rights Reserved.
################################################################################
from dxlclient import _BaseObject
class DxlUtils(object):
"""
... | StarcoderdataPython |
262576 |
def test_create_stat_table():
pass
def test_get_latest_successful_ts():
pass
def test_update_latest_successful_ts():
pass
| StarcoderdataPython |
3276256 | <filename>apps/smart_selects/views.py<gh_stars>1-10
import json
from functools import cmp_to_key
from django.apps import apps
from django.http import HttpResponse
from django.views.decorators.cache import cache_page
from smart_selects.utils import strcoll
@cache_page(60)
def filterchain(request, app, model, field, v... | StarcoderdataPython |
6510188 | """
OpenVINO DL Workbench
Class for ORM model described a Project
Copyright (c) 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LIC... | StarcoderdataPython |
3441721 | <filename>src/basic_gps_driving/src/lane_identification.py
#! /usr/bin/env python
import rospy
from sensor_msgs.msg import Joy
from sensor_msgs.msg import Image
from std_msgs.msg import Float32MultiArray, Float32
import matplotlib.pylab as plt
import cv2
import numpy as np
from cv_bridge import CvBridge
import math
... | StarcoderdataPython |
11240055 | <reponame>Togohogo1/Mathtermind
from classes.classic import Classic
from random import sample
class Custom(Classic):
def __init__(self, ctx, settings):
super().__init__(ctx)
# Changeable variables
self.ranges = []
self.tmp_sets = {"rl": None, "gsl": None, "mg": None, "ca": None}
... | StarcoderdataPython |
3518602 | #!/usr/bin/env python
"""
phylip2clustal.py [options] <input file> <output file>
Author: <NAME>
Date: Tue Jun 5 10:25:24 EST 2007
"""
import os, sys
from optparse import OptionParser
import align
usage = "%prog <input file> <output dir>"
parser = OptionParser(usage=usage, version="%prog - Version 1")
parser.add... | StarcoderdataPython |
1667129 | <filename>api/__init__.py
from flask_restplus import Api, Resource
from .taskController import *
api = Api(
version='1.0',
title='API',
description='api',
)
ns = api.namespace('api', description='task api namespace')
@ns.route('/tasks')
class TaskList(Resource):
@api.doc('get all tasks')
def get... | StarcoderdataPython |
263785 | #!/usr/bin/env python3
import logging
import random
import time
import pygame
from gamelib import logging as gamelog
from gamelib import util as gameutil
from gamelib import Display, GameBoard, colors, fonts, sounds
from gamelib.constants import KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_UP
from pieces import BLANK, SHAPES, ... | StarcoderdataPython |
9623464 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import APITestCase
class OrganizationMemberListTest(APITestCase):
def setUp(self):
self.user_1 = self.create_user('foo@localhost', username='foo')
self.user_2 = self.create_user('bar@localho... | StarcoderdataPython |
4933024 | <reponame>bidfx/bidfx-api-py
import unittest
from bidfx.pricing._subject_builder import SubjectBuilder
class TestPuffinSubjects(unittest.TestCase):
def setUp(self):
username = "jbloggs"
default_account = "MY_ACCT"
self.subject_builder = SubjectBuilder(username, default_account)
def t... | StarcoderdataPython |
256589 | # Check if the given string is a pangram or not
import string
def ispangram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in str.lower():
return False
return True
str = input ()
if(ispangram(str) == True):
print("PANGRAM EXISTS")
... | StarcoderdataPython |
4929707 | # coding:utf-8
# pzw
import pandas as pd
import yaml
f = open('cancerDrugNoTarget.yaml')
conf = yaml.load(f)
df = pd.read_excel(conf['director'] + '\\' + 'temp.xlsx', sheetname = 0, header = 0)
med_stan = pd.read_excel(r'config\DataBase\med.xlsx', sheetname = 0, header = 0)
writer = pd.ExcelWriter(conf['director'] + ... | StarcoderdataPython |
3474074 | <reponame>gedoensmax/delira<gh_stars>0
from delira.data_loading.sampler.abstract import AbstractSampler
class BatchSampler(object):
"""
A Sampler-Wrapper combining the single indices sampled by a sampler to
batches of a given size
"""
def __init__(self, sampler: AbstractSampler, batch_size, drop_... | StarcoderdataPython |
6476805 | <reponame>LifeLaboratory/Task_platform_backend<gh_stars>0
import json
import task_lesson.api.helpers.names as names
from task_lesson.models import User, TeamUser
from django.http import HttpResponse
class RegistrationUser:
@classmethod
def check_request(cls, request):
"""Проверка входных данных на к... | StarcoderdataPython |
216847 | <filename>models/official/detection/modeling/architecture/nn_blocks.py
# Lint as: python2, python3
# Copyright 2019 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 ... | StarcoderdataPython |
5103526 | <reponame>nizD/LeetCode-Solutions<gh_stars>100-1000
"""
Title -> ValidParenthesis (https://leetcode.com/problems/valid-parentheses/)
Approach for the solution :
Initialise a hashmap for mapping brackets and a set for opening parentheses.
Use stack to keep track of opening parentheses.
For each character in string, i... | StarcoderdataPython |
9626360 | <filename>python/math/find_angle_mbc.py
from math import (
atan2,
degrees
)
ab_side = int(input())
bc_side = int(input())
mbc_angle = degrees(
atan2(ab_side, bc_side)
)
print(
'{}°'.format(
int(round(mbc_angle))
)
)
| StarcoderdataPython |
339362 | # coding=utf8
import pathlib
import subprocess
import io
import tempfile
from flask import Flask, request, after_this_request
from flask.helpers import send_file
from pip._vendor.distlib._backport import shutil
app = Flask(__name__)
__ACCEPTED_FORMATS_STR = """docbook, haddock, html, json, latex, markdown, markdown_... | StarcoderdataPython |
308322 | <reponame>StepicOrg/stepik-apps<gh_stars>1-10
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^category/(?P<pk>\d+)/$', views.show_category, name='extensions-show_category'),
url(r'^upload/$', views.upload, name='extensions-upload'),
url(r'^$', views.show_all_extensions, name='e... | StarcoderdataPython |
4907031 | # Copyright 2017 OpenStack.org
#
# 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 writin... | StarcoderdataPython |
1699397 | <gh_stars>1-10
import argparse
import json
import numpy as np
from numpy import linalg
import matplotlib.pyplot as plt
from displ.wannier.bands import Hk, Hk_recip
from displ.wannier.extractHr import extractHr
from displ.pwscf.extractQEBands import extractQEBands
from displ.pwscf.parseScf import alat_from_scf, latVecs_... | StarcoderdataPython |
7547 | <reponame>davelarsen58/pmemtool
#!/usr/bin/python3
#
# PMTOOL NDCTL Python Module
# Copyright (C) <NAME>
# Released under MIT License
import os
import json
from common import message, get_linenumber, pretty_print
from common import V0, V1, V2, V3, V4, V5, D0, D1, D2, D3, D4, D5
import common as c
import time
DEFAULT... | StarcoderdataPython |
4888210 | <filename>sdk/opendp/smartnoise/reader/base.py
import pandas as pd
class Reader:
ENGINE = None
@property
def engine(self):
return self.ENGINE
def execute(self, query):
raise NotImplementedError("Execute must be implemented on the inherited class")
def _to_df(self, rows):
... | StarcoderdataPython |
192593 | """Defines a `Struc' class as a generic represention of molecular structure
"""
from kbase import KBASE
import os
import copy
import hashlib
# Flag indicating which infrastructure we are using.
infrastructure = None # "schrodinger" | "oechem"
class _AtomContainer( object ) :
"""
"""
def __init... | StarcoderdataPython |
76808 | <reponame>lkusch/Kratos
from KratosMultiphysics import *
import KratosMultiphysics.KratosUnittest as UnitTest
import KratosMultiphysics.kratos_utilities as kratos_utils
try:
from KratosMultiphysics.FluidDynamicsApplication import *
have_fluid_dynamics = True
except ImportError:
have_fluid_dynamics = False... | StarcoderdataPython |
6572208 | from django_filters import filters, filterset
from watson import search as watson_search
from grades.models import Course, Grade
class WatsonFilter(filters.CharFilter):
def filter(self, queryset, value):
value = value if value else ""
filtered_queryset = watson_search.filter(queryset, value)
... | StarcoderdataPython |
9686105 | <reponame>DougMHu/SCTA_repo<gh_stars>0
# # What is SCTA?
# __SCTA__ stands for:
#
# __S__atellite, and
#
# __C__ommunications
#
# __T__est
#
# __A__utomation.
#
# It is a Python library for controlling the RF lab equipment and collecting measurements for later analysis. You can use these libraries to write your... | StarcoderdataPython |
6507087 | # -*- coding: utf-8 -*-
import numpy as np
from .config import DTYPE
def compute_RMSE(pred_labels: np.ndarray, obs_labels: np.ndarray) -> DTYPE:
"""Root Mean Squared Error.
"""
return np.sqrt(np.mean(np.square(pred_labels - obs_labels))).astype(DTYPE)
| StarcoderdataPython |
1982965 | <gh_stars>0
from __future__ import unicode_literals
import json
try:
from six.moves import cPickle as pickle
except ImportError:
import pickle
class AbstractSerializer(object):
def dumps(self, obj):
raise NotImplementedError
def loads(self, data):
raise NotImplementedError
class ... | StarcoderdataPython |
1601311 | # Copyright (c) 2017 NVIDIA Corporation
# NOTE from Miguel: The code is the same as in https://github.com/NVIDIA/DeepRecommender/blob/master/run.py
# but I removed the logger
import os
import torch
import argparse
from reco_encoder.data import input_layer
from reco_encoder.model import model
import torch.optim as opti... | StarcoderdataPython |
6667822 | <reponame>bernland/FatSegNet
# Copyright 2019 Population Health Sciences and Image Analysis, German Center for Neurodegenerative Diseases(DZNE)
#
# 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 L... | StarcoderdataPython |
6557108 | from potodo.potodo import exec_potodo
def test_no_exclude(capsys, base_config):
exec_potodo(**base_config)
out, err = capsys.readouterr()
assert not err
assert "file1" in out
assert "file2" in out
assert "file3" in out
def test_exclude_file(capsys, base_config):
base_config["exclude"] = ... | StarcoderdataPython |
8153669 | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... | StarcoderdataPython |
5052769 | <reponame>mikespub-archive/wkornewald-allbuttonspressed
from .models import Blog, Post
from django.template.loader import render_to_string
from docutils import nodes
from docutils.parsers.rst import directives, Directive
class BlogPosts(Directive):
required_arguments = 1
optional_arguments = 0
option_spec ... | StarcoderdataPython |
8036530 | import select_features
from sklearn.model_selection import StratifiedKFold
from sklearn.neighbors import KNeighborsClassifier
# function that does k-fold cross validation of knn algorithm. k is represented by n_splits. it selects k best features where k is represented by k_best_features. parameters for knn - n_neighbo... | StarcoderdataPython |
8009895 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch import nn
from layers import DenseCaps, PrimaryCaps
class CapsuleNet(nn.Module):
"""
Input: (batch, channels, width, height)
Output:((batch, classes), (batch, channels, width, height))
input_size: ... | StarcoderdataPython |
11264218 | #!/usr/bin/env python
# import
from __future__ import print_function
## batteries
import os
import sys
import pytest
## 3rd party
import numpy as np
import pandas as pd
## package
from SIPSim.Commands import Fragment_KDE_cat as Fragment_KDE_cat_CMD
from SIPSim import Utils
# data dir
test_dir = os.path.join(os.path.di... | StarcoderdataPython |
4945835 | # <NAME>
# ID успешной посылки 66033244
def brackets(list_brackets, n):
if(n > 0):
brackets_generatior(list_brackets, 0,
n, 0, 0)
return
def brackets_generatior(list_brackets, position, n,
open, close):
if(close == n):
for i in list_bra... | StarcoderdataPython |
8173098 | <reponame>lmsac/GproDIA
from .pglyco2assay import pGlycoToAssayConverter
from .extract import extract_assays_from_spectra, extract_assays_from_glabel
| StarcoderdataPython |
1662724 | from pyglet.gl import glClearColor
from scenes import SceneManager, UsernameSelectScene
from constants import GRID_SIZE
import pyglet.sprite
USERNAME = ""
window = pyglet.window.Window(width=GRID_SIZE * 5, height=GRID_SIZE * 5 + 50)
window.config.alpha_size = 8
# Create a human player:
scene_manager = SceneManager... | StarcoderdataPython |
3495032 | import pprint
from typing import (
Any,
Dict,
List,
Tuple,
Sequence,
Union
)
from pathlib import Path
import h5py
from ..torchio import DATA, TYPE, INTENSITY, DVF, TypePath
from .image import Image
from .subject import Subject
class HDFSubject(dict):
"""Class to store information about the ... | StarcoderdataPython |
5051098 | #Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/Axiom_AIR_Mini32/AxiomAirMini32.py
from __future__ import with_statement
import Live
from _Framework.ControlSurface import ControlSurface
from _Framework.InputControlElement import MIDI_CC_TYPE, MIDI_NOTE_... | StarcoderdataPython |
262560 | from construct import *
from .common import *
from .doodads import DoodadVisibilityFlags, DoodadItemSet
"""
Formats: doo
Version: 8
The unit doodads file describes units and items present on the map.
It differs from the doodads file even though they use the same "file
extension." It is used for the war3mapU... | StarcoderdataPython |
6527389 | <filename>tests/libs/data_availability_report_test.py
import io
import pandas as pd
from libs.qa import data_availability
def test_build_availability_report():
input_csv = [
"fips,state,aggregate_level,population,field1,field2",
"36061,NY,county,500,1,",
"36062,NY,county,501,0,10",
... | StarcoderdataPython |
8074708 |
from object_bird import Bird
from object_sheep import *
if __name__ == "__main__":
# test1 = Bird()
# test1.ShowType()
test2 = MySheep(1)('test2')
test2.ShowMe()
test3 = MySheep(2)('test3','test3-sheep')
test3.ShowMe()
| StarcoderdataPython |
1676119 | import numpy
from theano import *
import theano.tensor as T
class HiddenLayer(object):
"""
+ The hidden layer transforms the data space.
+ The points are projected onto hyperplanes. A non-linear function of their
distance to the planes forms the coordinates of the points in the new ref... | StarcoderdataPython |
1916206 | #!/usr/bin/env python3
"""
人、狼、羊、菜过河问题,钻了题目空子
"""
if __name__ == '__main__':
print('HS H HW HS HV H HS')
| StarcoderdataPython |
6608675 | <reponame>roshanba/mangal<gh_stars>0
XXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XX
XXXXXXXXX XXXX XXXXXX XXXXXXXXXXXX XXXXX XXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXX
XXXX
XXXX XXXX XX XXXXXXXXXXXXXXX XX XXX XXXX... | StarcoderdataPython |
6443368 | #!/usr/bin/env python
import sys
import os.path
import optparse
import geniutil
import datetime
import subprocess
import uuid
CA_CERT_FILE = 'ca-cert.pem'
CA_KEY_FILE = 'ca-key.pem'
SA_CERT_FILE = 'sa-cert.pem'
SA_KEY_FILE = 'sa-key.pem'
MA_CERT_FILE = 'ma-cert.pem'
MA_KEY_FILE = 'ma-key.pem'
AM_CERT_FILE = 'am-cert.... | StarcoderdataPython |
9670426 | <filename>main.py
# Python
import json
import pprint
import string
import random
# Libraries
import tweepy
import spotipy
import spotipy.oauth2 as oauth2
import spotipy.util as util
# Files
from API.twitter_keys import getKeys
##########################
## Get Twitter API keys ##
##########################
access_toke... | StarcoderdataPython |
5180542 | <gh_stars>1-10
from Qcalculator import QUseless_Calculator
from PyQt5.QtWidgets import QApplication, QWidget # Import the QApplication and QWidget classes
from sys import argv, exit as sys_exit
class Window(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
... | StarcoderdataPython |
3532247 | import getpass
import telnetlib
HOST = ["eng-blr-switch-025","eng-blr-switch-027","eng-blr-switch-031","eng-blr-switch-037","eng-blr-switch-038","eng-blr-switch-126","eng-blr-switch-131","eng-blr-switch-137","eng-blr-switch-146"]
user = ""
password = ""
for i in HOST:
tn = telnetlib.Telnet(i.strip())
tn.writ... | StarcoderdataPython |
9707153 | <gh_stars>10-100
import logging
import random
from banned_exception import BannedException
from constants import AMAZON_BASE_URL
from core_utils import get_soup, extract_product_id
def extract_product_ids_from_link(category_link):
category_link_soup = get_soup(category_link)
products_links_1 = [a.attrs['href... | StarcoderdataPython |
8185178 | <reponame>guillermo-jimenez/fleet-format<filename>examples/generate_random.py
# Copyright 2020 Pure Storage Inc.
# SPDX-License-Identifier: Apache-2.0
# ==============================================================================
# The mock dataset created for this example Fleet file mimics a ECG dataset.
# In thi... | StarcoderdataPython |
276502 | <filename>Part_1_beginner/09_type_list/rozwiazania/exercise_2.py
# Zapytaj użytkownika o 3 ulubione potrawy i zapisz je w postaci listy
# favourite_dishes = []
# dish = input("Jakie jest Twoje ulubione danie nr 1? ")
# favourite_dishes.append(dish)
# dish = input("Jakie jest Twoje ulubione danie nr 2? ")
# favourite_d... | StarcoderdataPython |
11243363 | import os
import ast
import datetime as dt
import cv2
import pandas as pd
import numpy as np
import tensorflow as tf
import keras
import math
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Dropout, Flatten, Activation, Concatenate, Input, Reshape, GlobalAveragePooling2D, GlobalMaxPooling2... | StarcoderdataPython |
9732534 | <gh_stars>0
__author__ = <NAME>
__email__ = <EMAIL>
"""
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have... | StarcoderdataPython |
12860711 | <reponame>tessact/pdftables
"""
Backend abstraction for PDFDocuments
"""
import abc
import os
DEFAULT_BACKEND = "poppler"
BACKEND = os.environ.get("PDFTABLES_BACKEND", DEFAULT_BACKEND).lower()
# TODO(pwaller): Use abstract base class?
# What does it buy us? Can we enforce that only methods specified in an ABC
# are ... | StarcoderdataPython |
1755181 | #!/usr/bin/env python
#<NAME> and <NAME>
#Client for the Checkers Game
import socket
import check
import sys
import getopt
from Tkinter import *
def rotate(boardState,n):
return boardState[n:] + boardState[:n]
def pb(board, color):
out = "";
if color == "red":
out = "Red Players Move\n"
if color == "black"... | StarcoderdataPython |
6556981 | from squadron.service import get_service_actions, get_reactions, react, _checkfiles
import glob
import os
from squadron.fileio.dirio import makedirsp
import shutil
from helper import get_test_path
import pytest
test_path = os.path.join(get_test_path(), 'service_tests')
def test_get_service_actions():
actions = ge... | StarcoderdataPython |
1772503 | import logging
import azure.functions as func
import os
import json
import pickle
import sklearn
from timeit import default_timer as timer
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
localdir = context.function_... | StarcoderdataPython |
1889031 | #!/usr/bin/python
import os
import sys
import platform
import subprocess
import multiprocessing
build_option_param = {
"DYNAMIC": 1,
"IPV4": 1,
"TCP": 1,
"EASYSETUP": 1,
"ST_APP_FW": 1
}
# help message
def helpmsg(script):
helpstr = '''
Usage:
build:
python %s <targetbuild>
... | StarcoderdataPython |
352441 | import pytest
import modbot.input.test as test
TEST_SUBREDDIT = "testsub123"
@pytest.fixture
def create_bot():
test.create_bot(TEST_SUBREDDIT)
def test_create_post(create_bot):
# Test basic commands
test.get_reddit().inbox.add_message(
"mod1",
"/create_post --subreddit=testsub123 --stic... | StarcoderdataPython |
5083039 | <reponame>wolcomm/rptk
# Copyright (c) 2018 Workonline Communications (Pty) Ltd. All rights reserved.
#
# The contents of this file are licensed under the Apache License version 2.0
# (the "License"); you may not use this file except in compliance with the
# License.
#
# Unless required by applicable law or agreed to i... | StarcoderdataPython |
9644652 | class State(object):
def __init__(self, target_instance):
self.target_instance = target_instance
self.transitions = {"Free": self.from_free,
"BusyAddPS": self.from_busy_add_ps,
"BusyAddPL": self.from_busy_add_pl,
"B... | StarcoderdataPython |
152736 | '''
defines all the sources necessary for building cgui.pyd
'''
import os
BUILD_BUDDYLIST_GUI = False
thisdir = os.path.dirname(os.path.abspath(__file__))
sources = '''
src/ctextutil.cpp
src/SplitImage4.cpp
src/ScrollWindow.cpp
src/skinvlist.cpp
src/pyutils.cpp
src/cwindowfx.cpp
... | StarcoderdataPython |
14617 | class Exercises:
def __init__(self, topic, course_name, judge_contest_link, problems):
self.topic = topic
self.course_name = course_name
self.judge_contest_link = judge_contest_link
self.problems = [*problems]
def get_info(self):
info = f'Exercises: {self.topic}\n' \
... | StarcoderdataPython |
3492690 | import os
import re
from lxml import etree
from os import listdir
from os.path import isfile, isdir, exists, join
def ExisteArchivo(archivo):
if exists(archivo):
return True
else:
return False
def CarpetaActual(adicional):
root = join(os.getcwd(),adicional)
return root
def GuardarXML(archivo, doc):
direccio... | StarcoderdataPython |
5163348 | import torch
from torchaudio_unittest.common_utils import skipIfNoCuda, PytorchTestCase
from torchaudio_unittest.models.rnnt_decoder.rnnt_decoder_test_impl import RNNTBeamSearchTestImpl
@skipIfNoCuda
class RNNTBeamSearchFloat32GPUTest(RNNTBeamSearchTestImpl, PytorchTestCase):
dtype = torch.float32
device = to... | StarcoderdataPython |
8023890 | <filename>byurak/accounts/managers.py<gh_stars>0
from django.utils.translation import ugettext as _
from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
def create_user(
self,
name,
email,
phone_number,
nickname,
region_type,
... | StarcoderdataPython |
3565775 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
ind = 0
for i in range(len(nums)):
if nums[i] != nums[ind]:
ind += 1
nums[ind] = n... | StarcoderdataPython |
3597243 |
# don't iterate a list while modifying it
my=[1,2,3,4,5,6,7,8,9]
print(my)
# even slicing isn't safe in this case. causes error as it retains diff list
for i in my[:]:
if(my[i]%2==0):
my.remove(my[i])
my.pop()
print(my)
my=[1,2,3,4,5,6,7,8,9]
print(my)
for i in my:
if(i%2==0):
my.re... | StarcoderdataPython |
8072360 |
import os
from PIL import ImageFont
os.path.realpath
picdir = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'pic'))
def space_mono(style: str, size: int):
return ImageFont.truetype(os.path.join(picdir, 'Space_Mono', 'SpaceMono-' + style + '.ttf'), size)
| StarcoderdataPython |
1840952 | #!/usr/bin/env python3
#
# NAME - hunt-meraki.py
# SYNOPSIS
##
# DESCRIPTION
##
# INPUT:
## stdin for meraki firewall logs
# OUTPUT:
## None
# AUTHOR: <EMAIL>
#
# (c) 2019 GuardSight, Inc.
#
# Import relevent libraries
import sys, re, time, datetime
from FirewallLog import FirewallLog
logs = []
suspicious_ips = []
... | StarcoderdataPython |
8077180 | from flask import Flask, stream_with_context, render_template, request, json
from flask import redirect, Response, url_for, session, abort, flash, jsonify, g
from werkzeug.serving import run_simple
from werkzeug.utils import secure_filename
from PIL import Image
import PIL
from pathlib import Path
from pprint import ... | StarcoderdataPython |
12856791 | <gh_stars>0
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring,unused-import,reimported
import pytest # type: ignore
import tests.context as ctx
import license_screening.license_screening as lis
def test_parse_ok_empty_string():
assert lis.parse('') is NotImplemented
def test_parse_ok_known_tree():
... | StarcoderdataPython |
4962186 | <reponame>pjenpoomjai/LipNet
import numpy as np
from keras.utils import Sequence
import env
from common.files import get_file_name
from core.helpers.video import get_video_data_from_file
class BatchGenerator(Sequence):
__video_mean = np.array([env.MEAN_R, env.MEAN_G, env.MEAN_B])
__video_std = np.array([env.STD_... | StarcoderdataPython |
4889062 | # widgets
from tkinter import *
from tkinter import simpledialog
from tkinter import ttk
from tkinter import messagebox as msg
import tkinter as tk
from tkinter.filedialog import asksaveasfilename as save
from tkinter.filedialog import askopenfilename as openfile
from tkinter.colorchooser import *
from tkinterhtml impo... | StarcoderdataPython |
11308333 | <filename>piece.py
class Piece:
VIDE='.'
nomPiece=(VIDE,'ROI','DAME','TOUR','CAVALIER','FOU','PION')
valeurPiece=(0,0,9,5,3,3,1)
tab120 = (
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, -1,
-1, 8, 9, 10, 11, 12, 13, 14, 15,... | StarcoderdataPython |
11277980 | <reponame>YegorDB/django-channels-auth-token-middlewares<gh_stars>0
class MockConsumer:
async def __call__(self, scope, receive, send):
return scope
| StarcoderdataPython |
1726983 | '''
Check Palindrome
'''
# Palindorme means word == reverse.word ex- TIT = TiT, Tip != piT
user_input = input("Enter the Word: ")
rev_word = user_input[::-1]
# print(rev_word) Will print reverse of user_input
def main():
if user_input == rev_word:
print("Your word is a Palindrome.")
... | StarcoderdataPython |
9616878 | <filename>rules/vulnerabilities/rule_beanstalk-takeover.py
import dns.resolver
from core.redis import rds
from core.parser import ScanParser
class Rule:
def __init__(self):
self.rule = 'VLN_ZZ13'
self.rule_severity = 3
self.rule_description = 'This rule checks for Beanstalk DNS Takeovers'
self.ru... | StarcoderdataPython |
9628444 | import json
import logging
import os
from typing import List
import attr
from attr.validators import instance_of
from requests import Response
from osdu_commons.clients.rest_client import RestClient, HttpClientException
from osdu_commons.clients.retry import osdu_retry
from osdu_commons.model.aws import S3Location
fr... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.