id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
261287 | # Copyright 2016 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | StarcoderdataPython |
1605365 | #!/usr/bin/env python3
# import rospy
import socket
import cv2
import numpy as np
import time
cap = cv2.VideoCapture("udp://10.5.5.9:10000", cv2.CAP_FFMPEG)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
last_message = time.time()
while True:
# Get an image
ret, img = cap.read()
# Do something ... | StarcoderdataPython |
6479247 | <gh_stars>0
lst = [1, 0, 1, 2, 1, 3, 7, 2]
lst1 = [8, 3, 9, 6, 4, 7, 5, 2, 1]
lst7 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
n = 20
k = 2000000000000000000
def main():
shift_4(subtract_4([1,2,3],1,3))
def shift_4(lst):
line_one = []
#print(lst)
reverse_line_two = lst
... | StarcoderdataPython |
91961 | <gh_stars>0
import numpy as np
from copy import *
import vtk
# the minimum square distance for two points to be considered distinct
tolerance = np.square(0.01)
# square distance of two points
def sqr_dist(p1,p2):
return np.square(p1[0]-p2[0]) + np.square(p1[1]-p2[1]) + np.square(p1[2]-p2[2])
# this returns the ... | StarcoderdataPython |
6488212 | <filename>pytorch_lightning_pbt/trainer/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------
# PyTorch Lightning PBT
# Authors: <NAME>
# <NAME>
# Updated: May. 2020
# ---------------------
"""
Population Based Trainer
=========
"""
from pytorch_lightning_pbt.trainer.trainer... | StarcoderdataPython |
6574552 | <gh_stars>1-10
# import all the necessary libraries
import scipy
from scipy.io import wavfile
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
from pydub import AudioSegment
from pydub.utils import make_chunks
from pydub.silence import split_on_silence
import pyaudio
from queue impo... | StarcoderdataPython |
3251645 | import tensorflow as tf
import numpy as np
from preprocess_encode_images import extract_cache_features
from train_data_preparation import tokenizer, train_max_length
from params import attention_features_shape
from config import DIRECTORIES
def predict_single(image, models, image_features_dir, tokenizer,
... | StarcoderdataPython |
11265280 | <gh_stars>0
import subprocess
from briefcase.commands import (
BuildCommand,
CreateCommand,
PackageCommand,
PublishCommand,
RunCommand,
UpdateCommand
)
from briefcase.config import BaseConfig
from briefcase.exceptions import BriefcaseCommandError
from briefcase.integrations.xcode import verify_... | StarcoderdataPython |
110345 | from marshmallow import fields
from marshmallow import Schema
from marshmallow.validate import OneOf
class UsersListFilterSchema(Schema):
sort_key = fields.String(
OneOf(choices=['username', 'email', 'phone_number']),
missing='username')
sort_order = fields.String(missing='asc')
class UsersL... | StarcoderdataPython |
146506 | from smartnlp.classfication.svm_classifier import SVMClassifier
if __name__ == '__main__':
svm_model = SVMClassifier('model/svm/model.pkl',
'./data/imdb/aclImdb.txt',
train=True)
# svm_model = SVMClassifier('model/svm/model.pkl')
svm_model.predict... | StarcoderdataPython |
3260914 | from tkinter import *
from tkinter import messagebox
from webbrowser import get
class CoursesWindow:
LIST_COLORS= ["dark green", "dark blue", "red", "orange", "purple", "brown"]
def __init__(self, database: dict):
self.database= database
self.window = Tk(className=' Classes Selector')
... | StarcoderdataPython |
8067410 | x = 2
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True
name = "John"
age = 23
if name == "John" and age == 23:
print("Your name is John, and you are also 23 years old.")
if name == "John" or name == "Rick":
print("Your name is either John or Rick.")
name = "John... | StarcoderdataPython |
5072859 | <filename>Scripts/simulation/sims/fixup/sim_info_perk_fixup_action.py
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\fixup\sim_info_perk_fixup... | StarcoderdataPython |
123209 | <reponame>Staberinde/data-hub-api
import csv
import io
from contextlib import contextmanager
from chardet import UniversalDetector
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from django.utils.translation import gettext_lazy
cl... | StarcoderdataPython |
9725369 | <filename>Exercicios/ex037.py
"""Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário
escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal."""
n = int(input('Digite um número inteiro'))
print('[1] Binario')
print('[2] Octal')
print('[3] Hexadeci... | StarcoderdataPython |
213025 | <gh_stars>0
#If someone knows a better way to write the next 5 lines, lmk
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
import sys
sys.path.append('../')
from libs import ARTracker
tracker = ARTracker.ARTracker(['/dev/video2'], write=False) #ARTracker requires a list of camera files
while True:
... | StarcoderdataPython |
9767183 | from selenium import webdriver
import os
import subprocess
import sys
import json
import requests
path = 'D:\Chrome Driver\chromedriver.exe' # The path of chromedriver.exe(You can give your own path)
# Class
class GitScraper():
driverPath = ''
url = "https://github.com/login"
add_command = "g... | StarcoderdataPython |
1954031 | from random import randrange
from enum import Enum
import pyxel
class App:
class State(Enum):
TITLE = 0
INGAME = 1
RESULT = 2
def __init__(self):
pyxel.init(160, 120, caption="Flappy Bird")
pyxel.load("assets/flappybird.pyxres")
self.state = App.State.TITLE
... | StarcoderdataPython |
1738110 | import os
import testinfra.utils.ansible_runner
import pytest
import yaml
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
with open('../../defaults/main.yml') as vars_yml:
vars = yaml.safe_load(vars_yml)
with open('converge.yml') as p... | StarcoderdataPython |
3566704 | <gh_stars>0
import logging
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from playlist_creation.forms import PlaylistCreationForm
from playlist_creation.models import Playlist
logger = logging.getLogger(__name__)
... | StarcoderdataPython |
3523344 | <filename>day_10_1.py
from helper import get_input
def main():
data = sorted([int(x) for x in get_input(10).split('\n') if x])
max_val = max(data)
diffs = []
prev = 0
data.append(max_val + 3)
for d in data:
diffs.append(d - prev)
prev = d
print(diffs.count(1) * diffs.count(... | StarcoderdataPython |
6469679 | <gh_stars>1-10
import pytest
from pyspark.sql import DataFrame
from pyspark.sql.types import StringType, IntegerType
import blizz.check
from blizz import Field, Relation
from test.conftest import get_or_create_spark_session, path_student_performance_test
from test.test_spark_feature_library.data_sources import Student... | StarcoderdataPython |
3213996 | # Crie uma lista chamada 'números' e duas funções: sorteia(), que vai sortear 5 números e colocá-los dentro da lista, e soma_par() que vai mostrar a soma entre todos números pares da função anterior
# não tem muita necessidade da primeira função, o sample() já faz isso
from random import sample
from time import slee... | StarcoderdataPython |
6527976 | #!/usr/bin/env python
# Copyright (c) 2016-2017 Spotify AB.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under t... | StarcoderdataPython |
3448253 | <gh_stars>1-10
"""Unit testing of User Created Objects Model"""
from django.forms import ValidationError
from django.test import TestCase, tag
from BookClub.models import ForumPost
from BookClub.models.abstract_user_objects import UserCreatedObject
@tag('models', 'user_created')
class UserCreatedObjectTestCase(TestC... | StarcoderdataPython |
4946437 | import json
import random
import string
import requests
base_url = "https://accounts-new.dev.ukr.net"
url = "https://accounts-new.dev.ukr.net/api/v1/registration/reserve_login"
def test_used_login(get_registration_cookies):
payload = "{\"login\":\"test\"}"
headers = {
'Content-Type': 'application/js... | StarcoderdataPython |
5098379 | <gh_stars>10-100
import logging
from datetime import timedelta
from decimal import Decimal
from typing import Dict
import pytest
from tinkoff.invest import (
CandleInterval,
MoneyValue,
PortfolioPosition,
PortfolioResponse,
Quotation,
)
from tinkoff.invest.strategies.base.account_manager import Ac... | StarcoderdataPython |
6544155 | <reponame>machism0/bimodal-qd-micropillars
import numpy as np
import pandas as pd
def variable_names():
return ['Re(Es)', 'Im(Es)', '|Ew|^2', 'rho', 'n']
def param_names():
return ['kappa_s', 'kappa_w', 'mu_s', 'mu_w', 'epsi_ss', 'epsi_ww', 'epsi_sw', 'epsi_ws', 'beta', 'J_p', 'eta',
'tau_r', 'S... | StarcoderdataPython |
4953234 | <gh_stars>1-10
import tkinter as tk
from .menu import MenuContainer
class Menu(tk.Toplevel):
def __init__(self, master, name, *args, **kwargs):
super().__init__(master, *args, **kwargs)
self.base = master.base
self.master = master
self.configure(bg='#e8e8e8')
self.withdra... | StarcoderdataPython |
3550524 | <reponame>dlu-ch/trac-ticketdependencyplugin
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import pkg_resources
import trac.core
import trac.web.api
im... | StarcoderdataPython |
242392 | <reponame>robertogoes/exercicios-coursera-python
n = int(input("Digite o valor a ser avaliado:"))
ac1 = n%10
achouadjacente = False
n = n//10
while n !=0 and not(achouadjacente):
ac2 = n%10
if ac2 == ac1:
achouadjacente = True
n = n//10
ac1 = ac2
if achouadjacente:
print("Nesse número há d... | StarcoderdataPython |
25690 | <reponame>boyuhou/security-data
import click
import logging
import datetime
import pandas as pd
from security_data import SecurityService
DATE_FORMAT = '%Y%m%d'
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %I:%M:%S')
logger = logging.getLogger(__name__)
@... | StarcoderdataPython |
5162513 | from math import radians, cos, sin, asin, sqrt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import numpy as np
from datetime import date, timedelta
from pandas.tseries.offsets import DateOffset
from math import radians, cos, sin, asin... | StarcoderdataPython |
3483205 | <reponame>sebtelko/pulumi-azure-native
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .... | StarcoderdataPython |
6539036 | """Commands CLI."""
from typing import List, Optional
import click
from statue.cli.cli import statue_cli
from statue.cli.util import (
allow_option,
contexts_option,
deny_option,
silent_option,
verbose_option,
verbosity_option,
)
from statue.configuration import Configuration
from statue.excep... | StarcoderdataPython |
1913510 | <reponame>smueksch/pdf2txt
import re
class NumberFlagger:
""" Flag up lines that contain numbers.
Use this to point out any lines that potentially have left-over footnote
numbers in them but in a way they cannot be removed automatically.
"""
name = 'NumberFlagger'
desc = 'Flag up lines that ... | StarcoderdataPython |
1832189 | <filename>eval/ClassifierTester.py
import tensorflow.compat.v1 as tf
from utils import get_checkpoint_path
import numpy as np
class ClassifierTester:
def __init__(self, model, data_generator, pre_processor):
self.model = model
self.pre_processor = pre_processor
self.data_generator = data_g... | StarcoderdataPython |
6600053 | """
Goal: store application settings.
Notes:
- This file serves as an example only and should be changed
for production deployments.
- The *SALT* value will be provided over the phone.
"""
# Set to False if the a target server has a self-signed certificate
VERIFY_SSL_CERT = False
CLIENT_ID = 'client_1'
CLIEN... | StarcoderdataPython |
208739 | """
Tests for FileCollectionController
"""
import os
import shutil
import tempfile
import platform
from io import open
try:
to_unicode = unicode
except NameError:
to_unicode = str
try:
def to_bytes(val):
return bytes(val)
to_bytes("test")
except TypeError:
def to_bytes(val):
retur... | StarcoderdataPython |
1715430 | # Streamlit Timeline Component Example
import streamlit as st
from streamlit_timeline import timeline
# use full page width
st.set_page_config(page_title="Timeline Example", layout="wide")
# load data
with open('example.json', "r") as f:
data = f.read()
# render timeline
timeline(data, height=800) | StarcoderdataPython |
5137463 | <gh_stars>0
print "hello"
print "whatever"
| StarcoderdataPython |
4809119 | from flask import Flask, escape, request
import requests
import datetime
from dateutil import parser
application = Flask(__name__)
@application.route('/has_peers')
def peer_checker():
try:
r = requests.get('http://127.0.0.1:8732/network/peers')
except requests.exceptions.RequestException as e:
... | StarcoderdataPython |
6458388 | <filename>modules/blocks/pna/__init__.py
from .pna import PNAConv, PNAConvSimple | StarcoderdataPython |
12814062 | from pathlib import Path
from shutil import which
from geopandas.geodataframe import GeoDataFrame
from ipywidgets.widgets import widget
from keplergl import KeplerGl
import pandas as pd
import geopandas as gpd
from typing import Union
from .config import load_config
import contextily as ctx
import matplotlib.pyplot as ... | StarcoderdataPython |
4900313 | <filename>prep.py
from argparse import ArgumentParser
from tempfile import NamedTemporaryFile
from pprint import pprint
import csv, os, pandas
"""
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR... | StarcoderdataPython |
3302620 | <reponame>chrisjsherm/jira-status<gh_stars>0
"""
Math-related utility functions.
"""
def get_percentage(numerator, denominator, precision = 2):
"""
Return a percentage value with the specified precision.
"""
return round(float(numerator) / float(denominator) * 100, precision) | StarcoderdataPython |
4804812 | <filename>dashboard/migrations/0012_auto_20200222_2026.py
# Generated by Django 2.2.5 on 2020-02-22 19:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0011_auto_20200222_2017'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
6650774 | <filename>G_martix_spiral.py
"""
given a m*n matrix, print the matrix spirally clockwise
"""
def print_spiral(matrix):
m, n = len(matrix), len(matrix[0])
top, down = 0, m - 1
left, right = 0, n - 1
while True:
for j in xrange(left, right + 1):
print(matrix[top][j])
top += ... | StarcoderdataPython |
396637 | import math
EARTH_RADIUS = 6370000.
MAG_LAT = 82.7
MAG_LON = -114.4
direction_names = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
directions_num = len(direction_names)
directions_step = 360. / directions_num
def xyz(lat, lon, r=EARTH_RADIUS):
""" Takes sp... | StarcoderdataPython |
5096666 | # coding=utf-8
from gevent import monkey
monkey.patch_all()
import logging.config
import gevent
from gevent import spawn
from gevent.queue import Queue
from retrying import retry
from munch import munchify
from datetime import datetime
from gevent.hub import LoopExit
from restkit import ResourceError
from base_work... | StarcoderdataPython |
5066641 | <filename>source/gateway/runtime/app.py<gh_stars>10-100
import os
from chalice import IAMAuthorizer
from chalice import Chalice, AuthResponse
from chalice import ChaliceViewError, BadRequestError, NotFoundError
import requests
import boto3
from chalice import Response
import json
import jwt
app = Chalice(app_name='aws... | StarcoderdataPython |
6633585 | """Django settings for django-generic-filters demo project."""
from os import environ
from os.path import abspath, dirname, join
# Configure some relative directories.
demoproject_dir = dirname(abspath(__file__))
demo_dir = dirname(demoproject_dir)
root_dir = dirname(demo_dir)
data_dir = join(root_dir, 'var')
# Man... | StarcoderdataPython |
6680193 | """Init file for reader module"""
from typing import AnyStr
import feedparser
from .constants import RSS_FEEDS, \
FEEDPARSER_AGENT
from .utils import get_source, \
send_empty_response, \
send_heading, \
send_response
from ...utils impor... | StarcoderdataPython |
11217805 | <filename>server.py
from flask import Flask, request, send_from_directory
from flask_socketio import SocketIO
from gibbon.project import Project
import configparser
import os, sys, re, json
project = None
app = Flask(__name__)
# global project parameter
DIRECTORY = 'templates/html'
@app.route('/connect')
def conn... | StarcoderdataPython |
3216031 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from auto_nag.bzcleaner import BzCleaner
class Intermittents(BzCleaner):
def __init__(self):
super(Intermi... | StarcoderdataPython |
372022 | <reponame>domingoesteban/robolearn<gh_stars>1-10
from robolearn.models.transitions.transition import Transition
| StarcoderdataPython |
12847034 | <filename>main.py<gh_stars>1-10
import discord as dc
from dotenv import load_dotenv
from os import getenv
import datetime as dt
import json, string
load_dotenv()
#*#*#*# variables #*#*#*#
config_relative_path = getenv("CONFIG")
database_relative_path = getenv("DATABASE")
token = getenv("TOKEN")
#*#*#*#*#*#... | StarcoderdataPython |
330916 | <filename>methods/tools/controller.py<gh_stars>1-10
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
# Some methods used by main methods.
import os
from utils.helpers.file_helper import FileHelper
from utils.tools.logger import Logger as Log
class Controller(object):
@staticmethod
de... | StarcoderdataPython |
11244031 | <reponame>GrowingData/hyper-model
import click
import logging
# from hypermodel.platform.gcp.services import GooglePlatformServices
# from hypermodel.ml.model_container import ModelContainer
from titanic.pipeline.tragic_titanic_training_pipeline import (
FEATURE_COLUMNS,
TARGET_COLUMN,
)
from hypermodel.platfo... | StarcoderdataPython |
1960472 | def ensure_bool(x):
if isinstance(x, bool):
return x
else:
if isinstance(x, str):
if x.lower().startswith('t'):
return True
elif x.lower().startswith('f'):
return False
elif isinstance(x, int):
return bool(x)
raise V... | StarcoderdataPython |
9649583 | <reponame>qinjidong/esp8266-v3.0-msys32<filename>mingw32/bin/doesitcache2-script.py
#!C:/msys32/mingw32/bin/python2.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'CacheControl==0.12.5','console_scripts','doesitcache'
__requires__ = 'CacheControl==0.12.5'
import re
import sys
from pkg_resources import load_entry_point
if __name__ =... | StarcoderdataPython |
3563069 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from datetime import datetime
from common.waterfall import failure_type
from libs.gitiles.blame import Blame
from libs.gitiles.blame import Region
from libs... | StarcoderdataPython |
12842540 | import numpy as np
import matplotlib.pyplot as plt
data = np.load("uv-coverage.npy")
print(data.shape) | StarcoderdataPython |
11374360 | <reponame>cu-swe4s-fall-2019/final-project-swe4s_mc_params_optimization
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 21:44:21 2019
@author: owenmadin
"""
# Create functions that return properties for a given model, eps, sig
def rhol_hat_models(compound_2CLJ, Temp, eps, sig, L, Q):
''... | StarcoderdataPython |
217091 | <gh_stars>1-10
num = []
soma = 0
for i in range(11):
num.append(int(input()))
n = len(num)
for i in num:
soma = soma + i
media = soma / n
print(media)
| StarcoderdataPython |
11388173 | <reponame>rizwanniazigroupdocs/aspose-slides-cloud-python
from slides_configuration import *
request=PutSlidesSlideSizeRequest("test.pptx", width="100", height="100", size_type="OnScreen", scale_type="DoNotScale")
response = slides_api.put_slides_slide_size(request)
print(response) | StarcoderdataPython |
3391971 | <reponame>merkrafter/CopasiTool<gh_stars>0
import logging
def setup_logger(args):
"""
Takes an argparse namespace and returns a logger with the setting specified.
"""
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
formatter = logging.Formatter('[%(levelname)s] %(message... | StarcoderdataPython |
12849938 | from app import create_app
from flask_script import Manager,Server #initialise our extensions and server class that aid in launching of our server
# Creating app instance
app = create_app('development')
manager = Manager(app)
manager.add_command('server',Server) #launch app server
@manager.command
def test():
""... | StarcoderdataPython |
321843 | """All constants related to the ZHA component."""
import enum
import logging
from typing import List
import bellows.zigbee.application
from zigpy.config import CONF_DEVICE_PATH # noqa: F401 # pylint: disable=unused-import
import zigpy_cc.zigbee.application
import zigpy_deconz.zigbee.application
import zigpy_xbee.zigb... | StarcoderdataPython |
4983838 | <filename>hackerrank/algorithms/implementation/easy/lisas_workbook/py/solution.py
def solution(chapters, k):
count = 0
page = 0
for probCount in chapters:
for problem in range(1, 1 + probCount):
if (problem - 1) % k == 0:
page += 1
if pr... | StarcoderdataPython |
121397 | import unittest
import pickle
import sys
import tempfile
from pathlib import Path
class TestUnpickleDeletedModule(unittest.TestCase):
def test_loading_pickle_with_no_module(self):
"""Create a module that uses Numba, import a function from it.
Then delete the module and pickle the function. The fun... | StarcoderdataPython |
356908 | """Utility functions for NumPy-based Reinforcement learning algorithms."""
import numpy as np
from metarl.misc import tensor_utils
def paths_to_tensors(paths, max_path_length, baseline_predictions, discount):
"""Return processed sample data based on the collected paths.
Args:
paths (list[dict]): A l... | StarcoderdataPython |
61518 | #Automation
#Specifically used for small subsets with int64 as their astype
import pandas as pd
my_df = pd.read_csv("subset-1-sous-ensemble-1.csv", encoding = "latin-1")
my_df = my_df.loc[my_df['QUESTION'] == 'Q01']
my_df = my_df.loc[my_df['SURVEYR'] == 2020]
my_df = my_df.iloc[0:,[20, 22]]
print (my_df)
count = my... | StarcoderdataPython |
11221909 | import bleach
import markdown as md
from bleach.linkifier import LinkifyFilter
from django import template
allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'li', 'ol', 'p', 'pre', 'strong', 'ul']
register = template.Library()
cleaner = bleach.Clea... | StarcoderdataPython |
6487370 | <reponame>krislindgren/padre
import fractions
class ManualProgressBar(object):
"""A progress bar you update yourself."""
def reset(self):
pass
def update(self, done_text):
pass
class AutoProgressBar(object):
"""A progress that updates itself (ie. wrapping some iterator)."""
de... | StarcoderdataPython |
5060935 | from .attribute_builder import AttributeBuilder
class SourceLanguage(AttributeBuilder):
"""
Represents 'srclang' attribute.
"""
def __init__(self):
super().__init__()
self.attributes = ["srclang"]
| StarcoderdataPython |
11339179 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Benchmark for the quality of the joint space"""
from argparse import ArgumentParser
import logging
from io import open
from collections import defaultdict
from copy import deepcopy
import cPickle as pickle
from sklearn.linear_model import LinearRegression
from sklearn.nei... | StarcoderdataPython |
1769126 | # Copyright 2010-2018, Sikuli.org, sikulix.<EMAIL>
# Released under the MIT License.
from Sikuli import *
| StarcoderdataPython |
3374467 | <filename>jobs/zip+tar/zipped_python_job/entry.py
import os
import sys
import datetime
from utils.log import Logging
JOB_RUN_OCID_KEY = "JOB_RUN_OCID"
LOG_OBJECT_OCID_KEY = "LOG_OBJECT_OCID"
if __name__ == "__main__":
try:
job = Logging()
job.log(
[
"Start logging for... | StarcoderdataPython |
3460124 | <reponame>yswtrue/pycrunch-trace
from random import Random
from . import AbstractFileFilter
class DefaultFileFilter(AbstractFileFilter):
def should_trace(self, filename: str) -> bool:
# start or end with
exclusions = (
'/Users/gleb/code/pycrunch_tracing/',
'/Users/gleb/cod... | StarcoderdataPython |
3448428 | <gh_stars>0
import argparse
def eval_args():
parser = argparse.ArgumentParser(
description=help_message
) | StarcoderdataPython |
6620906 | #coding=utf-8
from __future__ import print_function
import traceback
import sys
from eccodes import *
#判断字符串Str是否包含序列SubStrList中的每一个子字符串
def IsSubString(SubStrList,Str):
flag=True
for substr in SubStrList:
if not(substr in Str):
flag=False
return flag
#获取当前目录所有指定类型的文件
... | StarcoderdataPython |
11305210 | <filename>src/common/file/ext_xlsx.py<gh_stars>0
# ext_xlsx.py
# Simple tool functions for xlsx files
#
from ..base import *
import openpyxl
def inXlsx(file_, data, level=error, debug=False):
wb = file_
for key in data.keys():
print("Read worksheet %s" % key)
ws = wb.get_sheet_by_name(key)
data[... | StarcoderdataPython |
12825354 | """
Komponent töötajate nimede hägusaks eraldamiseks.
Loodud Rasa Open Source komponendi RegexEntityExtractor põhjal.
https://github.com/RasaHQ/rasa/blob/main/rasa/nlu/extractors/regex_entity_extractor.py
"""
import typing
from components.helper_functions import parse_nlu
from components.levenshtein import manual_leve... | StarcoderdataPython |
3210196 | <gh_stars>0
from app import app
if __name__ == "__main__":
app.run() # No añadir parámetros, modificar directamente en Config
| StarcoderdataPython |
1970388 | """
LBPH-based Face recognition module
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import cv2
import tqdm
import numpy as np
class FaceRecognizer():
"""
Face recognition class ... | StarcoderdataPython |
8147216 | <reponame>astooke/gtimer
"""
All gtimer-specific exception classes.
"""
class GTimerError(Exception):
pass
class StoppedError(GTimerError):
pass
class PausedError(GTimerError):
pass
class UniqueNameError(GTimerError):
pass
class LoopError(GTimerError):
pass
class StartError(GTimerError)... | StarcoderdataPython |
5013224 | # -*- coding: utf-8 -*-
import unittest
class TestList(unittest.TestCase):
def test_indexed(self):
arr = [1, 2, 3]
self.assertEqual(3, arr[2])
self.assertEqual(2, arr[-2])
self.assertEqual(1, [1, 4, 5][0])
def test_slicing(self):
arr = [1, 2, 3, 4, 5]
self.asse... | StarcoderdataPython |
1747707 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from oca.models.base_model_ import Model
from oca import util
class HomeScreenContent(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://... | StarcoderdataPython |
12841832 | <gh_stars>0
from rest_framework.routers import DefaultRouter
from django.urls import path, include
from .views import *
router = DefaultRouter()
router.register('user', User, basename='user')
urlpatterns = [
path('', include(router.urls))
]
| StarcoderdataPython |
4994279 | <filename>migrations/versions/175c80bee699_modelos_actualizado.py
"""modelos actualizado
Revision ID: 1<PASSWORD>
Revises: None
Create Date: 2016-05-19 10:38:47.632650
"""
# revision identifiers, used by Alembic.
revision = '175c<PASSWORD>'
down_revision = None
from alembic import op
import sqlalchemy as sa
def u... | StarcoderdataPython |
6464473 | from flask import Blueprint
welcome = Blueprint('welcome', __name__, url_prefix='/')
from . import views, errors | StarcoderdataPython |
1963466 | # _*_ coding: utf-8 _*_
"""
@copyright Copyright (c) 2014 Submit Consulting
@author <NAME> (@asullom)
@package sad
@Descripcion Registro de los modelos de la app
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.text import capfirst, get_text_list
fro... | StarcoderdataPython |
1808397 | <reponame>Matrixchung/EDAutopilot<filename>.vscode/robigo.py
from game import *
import transitions
pyautogui.FAILSAFE=False
map_bookmark = str(fileRootPath.joinpath("templates/map_bookmark.png"))
map_bookmarkHL = str(fileRootPath.joinpath("templates/map_bookmark_highlight.png"))
map_sothis = str(fileRootPath.joinpath("... | StarcoderdataPython |
1621455 | '''
## Problem 🤔
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
**Example 1**
`Input: lists = [[1,4,5],[1,3,4],[2,6]]`
`Output: [1,1,2,3,4,4,5,6]`
_Explanation_
The linked-lists are:
```
[
1->4->5... | StarcoderdataPython |
12851078 | <reponame>thedrow/ray<filename>doc/examples/doc_code/raysgd_torch_signatures.py
# flake8: noqa
"""
This file holds code for the Pytorch Trainer creator signatures.
It ignores yapf because yapf doesn't allow comments right after code blocks,
but we put comments right after code blocks to prevent large white spaces
in t... | StarcoderdataPython |
1822691 | <gh_stars>1-10
# pip install Pillow
from PIL import Image
# The image we sent
im = Image.open("orig.png")
pix = im.load()
# The image they return (indexed)
im_mod = Image.open("mod.png")
im_mod = im_mod.convert("RGB")
pix_mod = im_mod.load()
for i in xrange(im.size[0]):
for j in xrange(im.size[1]):
print("{0} ... | StarcoderdataPython |
3391400 | from typing import Any, Final, TypedDict
import numpy as np
import numpy.typing as npt
HelloWorldType: Final[Any] = TypedDict("HelloWorldType", {"Hello": str})
IntegerArrayType: Final[Any] = npt.NDArray[np.int_]
| StarcoderdataPython |
1873812 | import signal
def sigterm(x, y):
pass
signal.signal(signal.SIGTERM, sigterm)
print("hello pipenv-docker-development world!", flush=True)
signal.sigwait([signal.SIGTERM])
print("shutdown...", flush=True)
| StarcoderdataPython |
4885236 | <reponame>jaypirates/Pull-Request-Predictor
# Author: <NAME>
import numpy as np
import json
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import os
# Opening the norm_output.json file which contains the normalized data
os.chdir('..')
filepath = os.getcwd()
filepath = filepath + "/d... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.