id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
3364575 | <filename>app/main/views.py
from flask import render_template,request,redirect,url_for
from . import main
from ..request import get_sources,get_articles
@main.route('/')
def index():
'''
This is the view root page function that returns the index page and its data
'''
business_news = get_sources('busine... | StarcoderdataPython |
8158905 |
import __future__
import os
import sys
import types
def compile_source_file(source_file, flags):
with open(source_file, "r") as f:
source = f.read()
return compile(source, os.path.basename(source_file), 'exec', flags)
if __name__ == "__main__":
# Compile and run test_pathlib.py as if
# "fro... | StarcoderdataPython |
6542971 | from __future__ import unicode_literals
from django.db import models
from Global_Equipment_library.models import LABEL_SIZES
FONT_TYPES = [('Impact','Impact'),
('Palatino','Palatino'),
('Tahoma','Tahoma'),
('Century Gothic', 'Century Gothic'),
('Lucida S... | StarcoderdataPython |
9651997 | # ==============================================================================
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
fro... | StarcoderdataPython |
372179 | # Copyright 2017 SrMouraSilva
#
# 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 |
6591883 | from typing import Callable, Any
from core.exceptions import StateException
from core.message import Message
from core.node import Node
from core.topic import Topic
def mitm(node1: Node, node2: Node, topic: Topic, node_name: str, interface_func: Callable[[Message, Topic], Any]):
"""
Publish subscribe agnosti... | StarcoderdataPython |
1818407 | import logging
from autogluon.core.constants import REGRESSION
from autogluon.core.utils.try_import import try_import_rapids_cuml
from .knn_model import KNNModel
logger = logging.getLogger(__name__)
# FIXME: Benchmarks show that CPU KNN can be trained in ~3 seconds with 0.2 second validation time for CoverType on ... | StarcoderdataPython |
11322715 | def uniqueValues(aDict):
'''
aDict: a dictionary
returns: a sorted list of keys that map to unique aDict values, empty list if none
'''
# Your code here
count = 0
l = []
l2 = []
l3 = aDict.values()
for key in aDict:
count = 0
value = aDict[key]
for i in l3... | StarcoderdataPython |
3516605 | #! /usr/bin/env python
import ConfigParser
import os
import sys
from distutils import dir_util
from redshell.constants import *
# Set default values
REDSHELL_DIR = os.path.expanduser(DEFAULT_REDSHELL_DIR)
REDSHELL_HISTORY = os.path.expanduser(DEFAULT_REDSHELL_HISTORY)
REDSHELL_REPORTS = os.path.expanduser(DEFAULT_REDS... | StarcoderdataPython |
1787841 | <reponame>vsocrates/medtype
from helper import *
from joblib import Parallel, delayed
import requests, re
######################### Dump Ground Truth in required format for evaluation
def groundtruth_dump(doc_list):
base_dir = './results/{}'.format(args.data); make_dir(base_dir)
fname = './results/{}/ground_{}.tx... | StarcoderdataPython |
9791127 | <reponame>GeorgeKandamkolathy/LocaltoSpotify
import eyed3
import os
import requests
import json
import webbrowser
import http.server
import sys
from io import StringIO
import base64
import urllib.parse
import re
CLIENT_ID = "128418d86c274651af8cdc709df1c143"
CLIENT_SECRET = "<KEY>"
def main():
unsuccesful = [] ... | StarcoderdataPython |
9754739 | import matplotlib.pyplot as plt
import numpy as np
with open('/home/ganesh/Desktop/class_acc.txt','r') as myfile:
data = myfile.read()
actor_list=list()
accuracy_list=list()
x = data.strip().split('\n')
for i in range(len(x)):
y=x[i].split(',')
print(y)
actor_list.append(y[0... | StarcoderdataPython |
8034953 | <reponame>andela/ah-django-unchained<filename>authors/apps/usernotifications/views.py<gh_stars>0
import jwt
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.http import Http404
from rest_framework import status
from rest_framework.generics import (
ListAPIView,
Updat... | StarcoderdataPython |
3544386 | """Setup the package."""
# Parse requirements
# ------------------
import pkg_resources
import pathlib
def parse_requirements(path: str) -> 'list[str]':
with pathlib.Path(path).open() as requirements:
return [str(req) for req in pkg_resources.parse_requirements(requirements)]
# Setup package
# -------... | StarcoderdataPython |
1664194 | <reponame>RivtLib/replit01
import operator
from typing import Union
from .exceptions import InvalidVersion
from .legacy_version import LegacyVersion
from .version import Version
OP_EQ = operator.eq
OP_LT = operator.lt
OP_LE = operator.le
OP_GT = operator.gt
OP_GE = operator.ge
OP_NE = operator.ne
_... | StarcoderdataPython |
270236 | <reponame>bg459/gan-ensembling-loader<filename>data/data_cars.py
import torch
import numpy as np
import os
from data.image_dataset import ImageDataset
from torch.utils.data import Subset
from torchvision import transforms
from PIL import Image
import random
import math
from mat4py import loadmat
from collections impor... | StarcoderdataPython |
1941564 | <reponame>gdialektakis/Statistical-Dialogue-Systems-with-Adversarial-AutoEncoders<filename>autoencoder/adversarial_autoencoder/lib/precision.py
_author__ = """<NAME> (<EMAIL>)"""
# Copyright (C) 2016 by
# <NAME> <<EMAIL>>
# All rights reserved.
# Computer Science Department, University of Crete.
import ten... | StarcoderdataPython |
360926 | from flask import (
Blueprint,
Response,
render_template,
current_app,
request,
redirect,
jsonify
)
import requests
frontend = Blueprint('frontend', __name__, template_folder='templates')
headers = {'Content-type': 'application/json'}
@frontend.route('/')
def index():
country_registe... | StarcoderdataPython |
6582067 | <reponame>brentp/bcbio-nextgen<filename>bcbio/provenance/versioncheck.py<gh_stars>1-10
"""Check specific required program versions required during the pipeline.
"""
import subprocess
from bcbio.pipeline import config_utils
from bcbio.log import logger
def samtools(config):
"""Ensure samtools has parallel processi... | StarcoderdataPython |
3524407 | from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SubmitField
from wtforms.validators import DataRequired
class LcdForm(FlaskForm):
lcd_text = StringField('LcdText', validators=[DataRequired()])
submit = SubmitField('Display')
class LcdRowForm(FlaskForm):
lcd_text = StringFi... | StarcoderdataPython |
1743805 | <gh_stars>0
import serial
import logging
port = "/dev/ttyUSB0"
baud = 115200
#log = logging.getLogger("serialM4")
class serialM4():
def __init__(self):
#log.info("SerialM4 constructor called")
self.com = serial.Serial(port, 115200)
def run(self):
#log.info("Receive thread started")
while True:
self.s... | StarcoderdataPython |
1652072 | <filename>stack_overseer/question_monitor/config/api_config.example.py
# Remove .example, change to api_config.py
API_KEY = "GET API KEY HERE https://stackapps.com/apps/oauth/register" # for stackExchange API
GEO_CODER_API = "Whatever service endpoint APIKEY!" # GEOCODER
GEO_CODER_API_ENDPOINT = "A API Endpoint Url"
| StarcoderdataPython |
5061396 | # -*- coding: utf-8 -*-
"""insult_train.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/11OTc2Q2mXQ1a3O0vljL4FhhZhqJqQzT_
"""
from google.colab import drive
drive.mount('/content/drive')
from numpy import array
from keras.preprocessing.text impo... | StarcoderdataPython |
9609614 | from flask import Flask, url_for, render_template, redirect, jsonify, json, request
from requests import get
import urllib.request, urllib.error, urllib.parse, json, webbrowser, requests
# reference: https://github.com/pacman2020/Pokemon-flask-API
def pretty(obj):
return json.dumps(obj, sort_keys=True, indent=2)
... | StarcoderdataPython |
4930627 | import logging
import tempfile
import os
import torch
from collections import OrderedDict
from tqdm import tqdm
from maskrcnn_benchmark.modeling.roi_heads.mask_head.inference import Masker
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
... | StarcoderdataPython |
68564 | import datetime
from subprocess import CalledProcessError # nosec
from threading import Thread
from typing import Dict, List, Optional, Set
import boto3
import click
import pytz
import semver
from botocore.config import Config
from botocore.exceptions import ClientError
from colored import attr, fg
from opta.amplitu... | StarcoderdataPython |
9625243 | <reponame>Twilighters/test_task_with_email
import logging
from selenium.webdriver.remote.webelement import WebElement
from common.constants import EmailConstants
from locators.email_page_locators import EmailPageLocators
from locators.login_page_locators import LoginPageLocators
from models.auth import AuthData
from... | StarcoderdataPython |
114325 | <gh_stars>0
#!/usr/bin/python
#coding:utf-8
from mylogistic import *
import numpy as np
import sys
import argparse
def MultiClassification(train_file_x, train_file_y, test_file_x, test_file_y):
train_data = np.loadtxt(train_file_x, delimiter = ',', dtype = np.float)
train_label_data = np.loadtxt(train_file_y, de... | StarcoderdataPython |
12864461 | import scrapy
from bs4 import BeautifulSoup
from lab3.items import Lab3Item
class QuoteSpider(scrapy.Spider):
name = 'quotes'
start_urls = ['http://quotes.toscrape.com/page/1/']
page_num = 1
# 对爬取到的信息进行解析
def parse(self, response, **kwargs):
soup = BeautifulSoup(response.body, 'html.parse... | StarcoderdataPython |
3577858 | import os
from typing import List, Union, Optional, Any, Tuple
import asyncio
import aiohttp
import json
from configparser import ConfigParser
# import websocket
from slack.web.client import WebClient
from slack.signature.verifier import SignatureVerifier
from slack.web.slack_response import SlackResponse
from slack.... | StarcoderdataPython |
6625967 |
"""
Functions for basic reading and writing of PENMAN graphs.
"""
from typing import Union, Iterable, List
from pathlib import Path
from penman.codec import PENMANCodec
from penman.model import Model
from penman.graph import Graph
from penman.types import (Variable, file_or_filename)
def decode(s: str,
... | StarcoderdataPython |
9727396 | <reponame>denisri/soma-workflow
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import six
import os
import inspect
import importlib
class Scheduler(object):
'''
Allow to submit, kill and get the status of jobs.
The Scheduler class is an abstract cla... | StarcoderdataPython |
318275 | /home/runner/.cache/pip/pool/1f/25/29/96266bdb681f6a20eae8a895c4d0785df90bfbe7af62a169fbb690708a | StarcoderdataPython |
1879686 | """
Created on 2018-08-04
@author: <NAME>
<EMAIL>
"""
import time
import warnings
from concurrent import futures
from typing import Dict, List, Type
import numpy as np
import torch
import torch.nn as nn
from nord.configurations.all import Configs
from nord.neural_nets import NeuralDescri... | StarcoderdataPython |
8164280 | #!/usr/bin/env python3
"""
Using two template images, align images from one template space to another.
"""
import subprocess
from os import PathLike
from pathlib import Path
from typing import List
def main(from_images: List[PathLike], from_template: PathLike, to_template: PathLike, to_dir: PathLike, suffix: str = "_... | StarcoderdataPython |
6525560 | <filename>expenseApp/urls.py<gh_stars>0
from django.urls import path
from . import views
urlpatterns = [
path('', views.userList, name='index'),
path('create/', views.create, name='create'),
path('create/<int:pk>/deposit', views.deposit, name='deposit'),
path('create/<int:pk>/expense', views.expense, n... | StarcoderdataPython |
11361500 | <filename>qa/rpc-tests/test_framework/cashlib/__init__.py<gh_stars>100-1000
# Copyright (c) 2018 The Bitcoin Unlimited developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from .cashlib import init, bin2hex, signTxInput, sig... | StarcoderdataPython |
11240668 | <filename>src/model/rule_transformation.py
from sqlalchemy.sql.expression import null
from sqlalchemy.sql.schema import ForeignKey
from sqlalchemy.ext.hybrid import hybrid_property
from database import BaseModel
from sqlalchemy.orm import relationship
from sqlalchemy.sql.sqltypes import Integer, String
from sqlalchemy ... | StarcoderdataPython |
6478190 | import peewee
from awsanalysis.a_loader import ALoader
import boto3
class SgLoader(ALoader):
def dep(self):
return set()
def setup(self):
db = self._dbMgr.getDB()
class SgTable(peewee.Model):
id = peewee.CharField(primary_key=True)
name = peewee.CharField()
... | StarcoderdataPython |
6534942 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Threshold
# 正交投影。。。。。。
# 坐标*外参,将坐标转变到相机坐标系下,然后用正交投影+双线性插值,获取每个点的所有的特征(遮挡问题怎么处理???,这里都没有深度测试,没有考虑遮挡)
class GraphProjection(nn.Module):
"""Graph Projection layer, which pool 2D features to mesh
The layer pr... | StarcoderdataPython |
6577227 | """Parse info about Perecrestok supremarket: `https://www.perekrestok.ru`."""
from time import sleep
from typing import Dict, Optional, NamedTuple, Set, NoReturn
import requests as req
from selenium import webdriver # type: ignore
from bs4 import BeautifulSoup # type: ignore
import pandas as pd # type: ignore
Categ... | StarcoderdataPython |
6649264 | <gh_stars>1-10
"""
This example exhibits some of the functionality of a peripheral BLE device,
such as reading, writing and notifying characteristics.
This peripheral can be used with one of the central examples running on a separate nordic device,
or can be run with the nRF Connect app to explore the contents of... | StarcoderdataPython |
8002073 | """
Render setup overrides and collections can be enabled and disabled.
Disabling an override removes its effect, but keeps the override itself.
Disabling a collection disables all the overrides in its list, as well
as disabling any child (nested) collection it may have.
To implement this behavior, overrides and col... | StarcoderdataPython |
1709316 | <filename>app/main.py
# encoding=utf-8
import json
import logging
import webapp2
import appengine_config
from google.appengine.api import modules
from google.appengine.api import app_identity
import telegram
import telegram_token
from service import WordCountService
# Creating the bot and getting basic info of i... | StarcoderdataPython |
6505000 | N = int(input())
s = set(input() for i in range(N))
print (len(s)) | StarcoderdataPython |
3553723 | #!/usr/bin/env python
# Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | StarcoderdataPython |
5053001 | #!/usr/bin/python
#FOG - update IP
# Adjust /opt/fog/.fogsettings
# Change Mysql values and update password from environment
# - DB - fog
# - globalSettings
# - update globalSettings set settingValue='??' where settingKey='FOG_TFTP_HOST';
# - update globalSettings set settingValue='??' where settingK... | StarcoderdataPython |
3201478 | from dash import html
from dash.dependencies import Input, Output, State
def get_postal_code(click_data: dict) -> str:
"""
Helper function for the callbacks
Gets postal code from map click_data.
---
Args:
click_data (dict): user click information
Returns:
postal_code (str): ... | StarcoderdataPython |
8064112 | <filename>config.py
# токен бота
TOKEN = ''
# admin -@Flaiers
admin_id = _
# telegram api id
api_id = _
# telegram api hash
api_hash = ''
# telegram name session
name = 'session'
# фразы
unknown = ['Я тебя не понимаю 😐', 'Мне непонятно 🙃',
'Твоё сообщение мне непонятно 😕', 'Я не могу понять 🙃',
'Пожалуйста, ... | StarcoderdataPython |
11352012 | <reponame>fluiddyn/fluiddyn<gh_stars>10-100
"""
Utilities for creating figures (:mod:`fluiddyn.output.figs`)
=============================================================
.. currentmodule:: fluiddyn.output.figs
Provides
.. autoclass:: Figure
:members:
.. autoclass:: Figures
:members:
"""
import os
import s... | StarcoderdataPython |
3279630 | <gh_stars>1-10
""" game class """ # noqa
# We want only one implementation of the Game Class.
# To do this, create a single instance of the Game class on import. Then
# each time we try to instanciate Game(), we just return a reference to
# the game class.
import cmd
from datetime import datetime
import pprint
impo... | StarcoderdataPython |
88627 | >>> print ( '\n'.join(''.join(x) for x in zip('abc', 'ABC', '123')) )
aA1
bB2
cC3
>>>
| StarcoderdataPython |
4971428 | <filename>python/reactive_planners/dcm_reactive_stepper.py
#!/usr/bin/env python
""" @namespace Controller using the dcm_vrp_planner.
@file
@copyright Copyright (c) 2017-2019,
New York University and Max Planck Gesellschaft,
License BSD-3-Clause
"""
import numpy as np
from reactive_planners_cpp ... | StarcoderdataPython |
1713330 | from django import forms
from .models import DailyNote, WeeklyNote
class DailyNoteEdit(forms.ModelForm):
class Meta:
model = DailyNote
exclude = [
'created_by',
'updated_by',
'valid_date'
]
class WeeklyNoteEdit(forms.ModelForm):
class Meta:
model = WeeklyNote
exclude = [
'created_by',
'u... | StarcoderdataPython |
226859 | <gh_stars>0
import csv
import os
directory = "/Volumes/Disk2/Dropbox/HPC/results/Office/learn/"
all = []
for file in os.listdir(directory):
if file.endswith(".csv"):
with open(directory+file, 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
count = 0
... | StarcoderdataPython |
5123408 | from pygments.style import Style
from pygments.styles.default import DefaultStyle
from pygments.token import Error
class SimpleStyle(Style):
styles = dict(DefaultStyle.styles.items())
SimpleStyle.styles[Error] = "border:"
| StarcoderdataPython |
1787427 | influencer = {
'mahathir': [
'tun mahathir',
'madey',
'dr mahathir',
'tun m',
'mahathir',
'madir',
'dr m',
'mahathir muhamad',
],
'anwar ibrahim': ['anwar ibrahim', 'anwar'],
'najib razak': [
'najib razak',
'ajib',
'... | StarcoderdataPython |
369956 | from django.contrib.auth.models import Group
from django.test import TestCase
from apps.bot.classes.Command import Command
from apps.bot.classes.bots.tg.TgBot import TgBot
from apps.bot.classes.consts.Consts import Platform
from apps.bot.classes.consts.Exceptions import PWarning, PError
from apps.bot.classes.events.Tg... | StarcoderdataPython |
4864729 | # -*- coding: utf-8 -*-
from yapsy.IPlugin import IPlugin
class Wklej(IPlugin):
def execute(self, channel, username, command):
if not command:
yield channel, ("Nie bądź noobem i wklej na: "
"https://gist.github.com/")
| StarcoderdataPython |
3442133 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PYTHON_ARGCOMPLETE_OK
"""Command Line Interface (CLI) for the geomodels package."""
import sys
from . import cli
sys.exit(cli.main())
| StarcoderdataPython |
8106353 | <reponame>COLAB2/midca
from datetime import datetime
import os, sys, copy
import platform, string
class Logger:
logFolderOptions = ["log", "_log"]
def __init__(self, keys = [], filesStayOpen = False, verbose=2):
'''
creates a new logger for a MIDCA run. The folder where the individual log fi... | StarcoderdataPython |
9641439 | def format_int_kind(x):
return 'int({0})'.format(x)
with printoptions(formatter={'int_kind': format_int_kind}):
print(np.random.randint(-100, 100, 10)) | StarcoderdataPython |
1612644 | from pysensationcore import *
import sensation_helpers as sh
import Scan
# Inner blocks
scan = createInstance("Scan", "scan")
comparator = createInstance("Comparator", "ComparatorInstance")
# Inner block connections
connect(Constant((0, 0, 0)), comparator.returnValueIfAGreaterThanB)
connect(Constant((1, 0, 0)), comp... | StarcoderdataPython |
9689744 | #
# Visual Cryptography Cookbook
# for UVA GenCyber 2018
#
# <NAME>
# 14 June 2018
#
### python3 visualcrypto.py --seed 1629 --xsize 80 --image message.bmp
### convert message-share.svg message-share.pdf
### print scale to 64%
### This requires the svgwrite and PIL modules are installed.
### If they are not already ... | StarcoderdataPython |
3217571 | import warnings
import argparse
from torch import optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from dogsvscats.data import get_datasets
from dogsvscats.model import train_model, load_model, MODELS
from dogsvscats.callbacks import EarlyStopping
from dogsvscats import config
warning... | StarcoderdataPython |
8154388 | <reponame>balcilar/SemiSupervisedMarkowRandomWalk<filename>sslMarkovRandomWalks.py
import numpy as np
def sslMarkovRandomWalks(xl,yl,xu,k=10,gamma=1,t=10,improvement=10e-5):
# Written by <NAME>, <EMAIL>, France
# xl is nxd size matrix shows inputs of known data. n is number of data d is dimension
# yl ... | StarcoderdataPython |
5139362 | """
q7.py
Created on 2020-08-21
Updated on 2020-10-30
Copyright <NAME> 2020
Description: A file which holds the designated question class.
"""
# IMPORTS
from sympy import latex, binomial
from sympy.parsing.sympy_parser import parse_expr
from the_challenge.questions.questionClasses.questionBaseClass import Question... | StarcoderdataPython |
8133183 | <reponame>kevingduck/transmission
# Copyright 2019 ShipChain, Inc.
#
# 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... | StarcoderdataPython |
9708230 | <reponame>mickypaganini/IPRNN
import glob
import pandas as pd
import numpy as np
from numpy.lib.recfunctions import stack_arrays
from root_numpy import root2rec
def root2panda(files_path, tree_name, mask = False, **kwargs):
'''
Args:
-----
files_path: a string like './data/*.root', for example
... | StarcoderdataPython |
1958187 | import logging
import os
import time
import numpy as np
from simulation import sim as vrep
from utils import utils
class SimRobot:
def __init__(self, sim_port, obj_mesh_dir, num_obj, workspace_limits,
is_testing, test_preset_cases, test_preset_file, place_enabled):
self.sim_port = sim_... | StarcoderdataPython |
9621756 | #-*- coding:utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
import paddle.fluid as fluid
from utils import *
import utils
import contextlib
import os
import math
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
class multires_unet(object):
... | StarcoderdataPython |
102192 | <gh_stars>1-10
#! /home/johk/anaconda3/envs/slam/bin/python
import numpy as np
import OpenGL.GL as gl
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import pangolin
import pickle
class D3Engine:
def __init__(self):
self.realPoints = []
self.creative_mode = True
... | StarcoderdataPython |
6618057 | <reponame>mukul20-21/python_datastructure
n = int(input())
item = list(map(int,input().split()))
uqi = set(item)
print(len(uqi)) | StarcoderdataPython |
6698680 | <filename>disaster_response_classifier/disaster_response_classifier/train_classifier.py
# import libraries
import os
import argparse
import pandas as pd
import numpy as np
import re
import pathlib
from sqlalchemy import create_engine
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy... | StarcoderdataPython |
11373048 | import matplotlib.pyplot as plt
from collections import Counter
def pieChart(cats):
labels = []
percentages = []
most = Counter(cats).most_common(n=10)
cat_sum = sum([value for i, (key, value) in enumerate(most)])
for i, (a, b) in enumerate(most):
labels.append(a)
percentages.append... | StarcoderdataPython |
9610406 | <filename>wplay/save_chat.py
# region IMPORTS
from pathlib import Path
from wplay.utils import browser_config
from wplay.utils import target_search
from wplay.utils import target_select
from wplay.utils.helpers import save_chat_folder_path
from wplay.utils.Logger import Logger
# endregion
# region LOGGER
__logger = ... | StarcoderdataPython |
1715805 | import tensorflow as tf
global_step = tf.train.get_or_create_global_step()
a=tf.constant([
[[1.0,2.0,3.0,4.0],
[5.0,6.0,7.0,8.0],
[9,10,11,12],
[13,14,15,16]],
[[17,18,19,20],
[21,22,23,24],
[25,26,27,28],
[29,30,31,32]]
])
... | StarcoderdataPython |
9697010 | class DecisionNode:
"""
A Decision Node asks a question.
This holds a reference to the question, and to the two child nodes.
"""
def __init__(self,
question,
true_branch,
false_branch):
self.question = question
self.true_branch = t... | StarcoderdataPython |
11260985 | import random
class Chromosome:
def __init__(self, genes, fitness):
self.Genes = genes
self.Fitness = fitness
def createPop(popSize, min, max):
D = len(min)
pop = []
for i in range(0, popSize):
chrom = []
for j in range(0, D):
chrom.append(random.uniform(min... | StarcoderdataPython |
1862614 | <gh_stars>1-10
from config import *
import pandas as pd
import numpy as np
import networkx as nx
import scipy.stats
from sklearn import metrics
import bct
import matplotlib.pyplot as plt
def get_adjmtx(corrmtx,density,verbose=False):
assert density<=1
cutoff=scipy.stats.scoreatpercentile(corrmtx[np.... | StarcoderdataPython |
337598 | import unittest
from unittest import TestCase
from pytheons.pyunit.decorators.test import test
class ExampleTest(TestCase):
@test
def something(self):
self.assertEqual(True, False)
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
4832782 | # Generated by Django 2.0 on 2018-04-04 10:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mixnet', '0002_auto_20180216_1617'),
]
operations = [
migrations.AddField(
model_name='mixnet',
name='auth_position',
... | StarcoderdataPython |
12859296 | from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from products.models import Product
def productList(request, productName):
"""产品的列表页"""
submenu = productName
if productName == 'robot':
productName = '家用机器人'
elif p... | StarcoderdataPython |
1923624 | <reponame>luposdate/reviz<filename>reviz.py
import argparse
from grobid.grobid import run_grobid
from model.graph_model import run_graph
from views.flow_diagram_view import run_flow
from views.bibliography_view import run_bib
import os
import json
from views.graph_view import view_sugiyama, view_sugiyama_summary
from u... | StarcoderdataPython |
76142 | import os
import argparse
import pyautogui
import time
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--path", help="absolute path to store screenshot.", default=r"./images")
parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or s (in seconds)", default='h')
parser.add_argument("-f... | StarcoderdataPython |
11382764 | <gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# # Methods & Results
# We are going to use multiple analysis to classify the type of the animals using 16 variables including hair, feathers, eggs, milk, airborne, aquatic, predator, toothed, backbone, breathes, venomous, fins, legs, tail, domestic, catsize as our ... | StarcoderdataPython |
4820939 | <gh_stars>1-10
from natsbeat import BaseTest
import os
class Test(BaseTest):
def test_base(self):
"""
Basic test with exiting Natsbeat normally
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/log/*"
)
natsbeat_proc = self.s... | StarcoderdataPython |
3266685 | <filename>hooks/check_missing_requirements.py<gh_stars>1-10
"""Checks to see if the package requirements are all present in the current
python environment.
"""
import subprocess
import sys
from pathlib import Path
from typing import List
import requirements
from .utils import Hook
def _parse_package_name(name: str)... | StarcoderdataPython |
5150846 | <gh_stars>1-10
# Copyright The PyTorch Lightning team.
#
# 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... | StarcoderdataPython |
11297870 | <filename>space_shooter.py
import pygame as pg
import random
import math
import os
WIDTH,HEIGHT=600,400
pg.init()
screen=pg.display.set_mode((WIDTH,HEIGHT),0,32)
def write(msg,color=(255,255,255)):
font=pg.font.SysFont("none",15)
text=font.render(msg,True,color)
text.convert()
return te... | StarcoderdataPython |
8098992 | <filename>pxtrade/compliance/base.py
"""
Before trades can be sent for execution they need to pass
any defined compliance rules. These rules may include position
limits, restricted securities, ...
Here compliance rules have been arranged using a composite pattern
to check portfolio positions should the trade be fully e... | StarcoderdataPython |
1634342 | <reponame>romulus97/HYDROWIRES
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 31 14:31:32 2018
@author: YSu
"""
from __future__ import division
from scipy.optimize import differential_evolution
import pandas as pd
import numpy as np
from datetime import datetime
# ORCA flow data
df_flows = pd.read_excel('reservoi... | StarcoderdataPython |
86629 | <reponame>brewst001/RAPID
from django.conf.urls import patterns, include, url
from django.contrib import admin
import core.urls
import profiles.urls
import pivoteer.urls
import monitors.urls
urlpatterns = patterns('',
url(r'^$', core.views.HomePage.as_view(), name="home"),
url(r'^navigation/', include(core.ur... | StarcoderdataPython |
1743971 | <reponame>sensenatchanan/flood-warning-system
from .utils import sorted_by_key
from floodsystem.analysis import slope_finder
#from .station import typical_range_consistent, relative_water_level
def stations_level_over_threshold(stations, tol):
output_list = []
for station in stations:
if st... | StarcoderdataPython |
1776473 | <filename>sentiment-analysis/backend/src/pca/pca-transcribe-eventbridge.py<gh_stars>0
import json
import boto3
import time
import os
TABLE = os.environ["TableName"]
# Total number of retry attempts to make
RETRY_LIMIT = 2
def lambda_handler(event, context):
# Pick off our event values
transcribe = boto3.cli... | StarcoderdataPython |
3413692 | # -*- coding: utf-8 -*-
#####################################################################################
#
# Copyright (c) <NAME>. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the r... | StarcoderdataPython |
4938589 | <reponame>tristone13th/pdf-annotations
import argparse
import datetime
import io
import os
import sys
import re
from pathlib import Path
from typing import List
import pdfminer.pdftypes as pdftypes
import pdfminer.settings
import pdfminer.utils
from pdfminer.converter import TextConverter
from pdfminer.layout import L... | StarcoderdataPython |
1945113 | #!/usr/bin/python
#
#
#
import sys
import os
import datetime
import commands
import re
import time
import simplejson as json
from optparse import OptionParser
def run(inJsonFilename):
inJson = open(inJsonFilename).read()
data = json.loads(inJson)
# Add a name for the output file that will be generated
... | StarcoderdataPython |
11214783 | import argparse
import logging
from . import __version__
from . import constants as c
from .main import latex2plos
def main():
# Setup command line option parser
parser = argparse.ArgumentParser(
description='Automated preparation of your LaTeX paper for submission in PLOS journals',
)
parser... | StarcoderdataPython |
3434386 | import logging
import os
import pickle
import re
import requests
import scrapy
from functools import partial
from . import base_path, config, notification
seen_directory = os.path.join(base_path, 'seen')
os.makedirs(seen_directory, exist_ok=True)
seen_filename_template = os.path.join(seen_directory, '{name}.pickle'... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.