id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
48279 | <gh_stars>0
try:
from urlparse import urlparse, parse_qs
except ImportError:
from urllib.parse import urlparse, parse_qs
from oauthlib.common import add_params_to_uri
def instagram_compliance_fix(session):
def _non_compliant_param_name(url, headers, data):
# If the user has already spec... | StarcoderdataPython |
4802020 | from django import template
register = template.Library()
def value_range(value,range):
if len(value) > range:
return value[0:range-3]+'...'
else:
return value
register.filter('value_range', value_range) | StarcoderdataPython |
3228183 | <gh_stars>0
# Generated by Django 4.0.4 on 2022-05-08 17:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Blog',
fields=[
... | StarcoderdataPython |
1779337 | import codecs
import pickle
chars = ['']
for i in range(32, 256): # 512
c = chr(i)
if c not in chars:
chars.append(c)
en_es = open('src/main/resources/dic/en-es.xml').read()
for c in en_es:
if c not in chars:
print(c)
chars.append(c)
es_en = open('src/main/resources/dic/en-es.xml... | StarcoderdataPython |
1679564 | <gh_stars>0
from ..dxConfig import dxConfig;
from ..mCP437 import fsCP437HTMLFromString;
gbDebugIO = False; # Used for debugging cdb I/O issues
def cCdbWrapper_fCdbStdErrHelperThread(oCdbWrapper):
sLine = "";
while 1:
s0Line = oCdbWrapper.oCdbConsoleProcess.oStdErrPipe.fs0ReadLine();
if s0Line is None:
... | StarcoderdataPython |
124594 | from .astra import Astra
from .denoise import Denoise
from .implyloss import ImplyLoss
from .weasel import WeaSEL
| StarcoderdataPython |
22485 | PRIMES = [3]
def next_prime():
num = PRIMES[-1] + 2 # odd + 2 is the next odd, don't check evens for primality
is_prime = False
while True:
lim = num**0.5 # don't check for prime factors larger than this
for p in PRIMES:
if p > lim:
is_prime = True
... | StarcoderdataPython |
1600702 | """Tests for the Subscriptions API class."""
import unittest
import mws
from .utils import CommonAPIRequestTools
class SubscriptionsTestCase(CommonAPIRequestTools, unittest.TestCase):
"""Test cases for Subscriptions."""
api_class = mws.Subscriptions
# TODO: Add remaining methods for Subscriptions
| StarcoderdataPython |
1710795 | import numpy as np
import cv2
class StrokeWidthDistanceTransform(object):
def __init__(self,
dark_on_bright=True,
clean_ccs=2):
self._dark_on_bright = dark_on_bright
self._clean_ccs = clean_ccs
def apply_swt_dist_trafo(self, img_file):
swt_dist_trafo ... | StarcoderdataPython |
1710792 | <gh_stars>1-10
# _*_ codig utf8 _*_
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
#线性回归,解析式求解
class DirectResolverLR():
def __init__(self):
sel... | StarcoderdataPython |
3319012 | from functools import reduce as _reduce
def gen_cand_and_clean(votes):
"""
params:
- votes (list (dict {'a : Ord 'b})): The list of votes, which are
candidates mapped to a preference
returns:
- candidates (set 'a): The set of candidates
- cleaned votes (list (dict {'a : Ord 'b}))
This utility function ... | StarcoderdataPython |
1730920 | <filename>lab3/lab3.py
# MIT 6.034 Lab 3: Games
# Written by <NAME> (dxh), <NAME> (jmn), and 6.034 staff
from game_api import *
from boards import *
INF = float('inf')
def is_game_over_connectfour(board) :
"Returns True if game is over, otherwise False."
# check if vertical win exists
height = board.num_c... | StarcoderdataPython |
3267067 | <filename>engine/rooms/room_procgen.py
import random, uuid, pprint, copy
from engine.global_lists import *
from engine.lex import Lex
from engine.room import Room
from engine.item import Item
from engine.update_client import Update_Client
from engine.join_tables.join_table_items import *
from engine.rooms.room_regi... | StarcoderdataPython |
3220916 | <reponame>huzidabanzhang/Python<gh_stars>1-10
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
@Description: SocketIO配置
@Author: Zpp
@Date: 2020-05-19 14:43:38
@LastEditors: Zpp
@LastEditTime: 2020-05-21 16:12:45
'''
from flask import request
from flask_socketio import emit, Namespace
client = []
class MyCustomNames... | StarcoderdataPython |
4800534 | import argparse
from collections import Counter
from unidecode import unidecode
import progressbar
import pandas as pd
from graphbrain.hypergraph import HyperGraph
from graphbrain.funs import *
import graphbrain.nlp.parser as par
import graphbrain.synonyms.synonyms as syn
MAX_PROB = -12
def read_predicate_table(fil... | StarcoderdataPython |
37565 | # Commenting syntax errors.
print("Printing out a message!") # This is a comment.
floating_point_number = 1.5 * 2.7
| StarcoderdataPython |
3236454 | <filename>slac/utils.py
import math
import torch
from torch import nn
def create_feature_actions(feature_, action_):
N = feature_.size(0)
# Flatten sequence of features.
f = feature_[:, :-1].view(N, -1)
n_f = feature_[:, 1:].view(N, -1)
# Flatten sequence of actions.
a = action_[:, :-1].view(... | StarcoderdataPython |
3259330 | from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from .models import Post
... | StarcoderdataPython |
1636852 | <gh_stars>0
import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Categories(models.Model):
category = models.CharField(max_length=30)
def __str__(self):
return self.category
class Expenses(models.Model):
expense = models.CharField(max_len... | StarcoderdataPython |
3233525 | from napari_plugin_engine import napari_hook_implementation
from qtpy.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QPushButton, QLineEdit, QListWidget, QListWidgetItem, QLabel, QFileDialog
from qtpy.QtCore import QEvent, Qt
from qtpy.QtCore import Signal, QObject, QEvent
from magicgui.widgets import FileEdit
fro... | StarcoderdataPython |
141120 | import flask
from robostat.rulesets.xsumo import XSumoRuleset
from robostat.rulesets.rescue import RescueRuleset
from robostat.rulesets.tanssi import DanceInterviewRuleset, DancePerformanceRuleset
from robostat.rulesets.haastattelu import HaastatteluRuleset
from robostat.web.views.timetable import event_renderer
@even... | StarcoderdataPython |
3202187 | #!/usr/bin/env python2.7
#-*- coding: utf-8 -*-
import subprocess
class CEosAccount:
def __init__(self, account):
self.set(account)
def set(self, account):
if len(account) != 12:
raise ValueError("unvalid format of @account")
self.a = account
def __str__(self):
... | StarcoderdataPython |
1746606 | <gh_stars>0
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or d... | StarcoderdataPython |
1682993 | <filename>examples/tiling_pattern/fitness_over_time.py<gh_stars>0
import csv
import os
import pickle
import matplotlib.pyplot as plt
import gym
from examples.experiment_functions import SMSwarmExperimentRunner
from neat import Config, DefaultSpeciesSet, DefaultStagnation, DefaultReproduction
from neat.state_machine_g... | StarcoderdataPython |
1637173 | <filename>TwitterSearch/TwitterSearchOrder.py
# -*- coding: utf-8 -*-
import datetime
from .TwitterSearchException import TwitterSearchException
from .TwitterOrder import TwitterOrder
from .utils import py3k
try:
from urllib.parse import parse_qs, quote_plus, unquote # python3
except ImportError:
from urlpar... | StarcoderdataPython |
1691075 | <filename>nn_dataflow/core/pipeline_segment_timing.py
""" $lic$
Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of
Stanford University
This program is free software: you can redistribute it and/or modify it under
the terms of the Modified BSD-3 License as published by the Open Source
Initiativ... | StarcoderdataPython |
4802461 | # v: 2021-05-23T1343 AU
# Issue: "ai.py:51: UserWarning: nn.init.kaiming_normal is now deprecated in favor of nn.init.kaiming_normal_."
# Resolution: renamed `kaiming_normal` to `kaiming_normal_`
import torch.nn as nn
import torch
import random
import numpy as np
import copy
import os
class Network(nn.Module):
... | StarcoderdataPython |
3241359 | from pynput import keyboard
from counter.key_counter import key_counter
def on_press(key):
try:
# judge the type of key pressed
pressed_key = key.char
# pressed alphanumeric key
key_counter.alphanumeric_increment()
except AttributeError:
# pressed special key
ke... | StarcoderdataPython |
3222654 | from common import *
import datetime
import argparse
import time
here = os.path.abspath(os.path.dirname(__file__))
app_dir = os.path.join(here, '../pyg/multi_gpu')
"""
if log_dir is not None, it will only parse logs
"""
def overall_perf_test(log_folder=None, mock=False):
tic = time.time()
if log_folder... | StarcoderdataPython |
169724 | <gh_stars>0
from rest_framework import pagination
from ncore.response import JsonResponse
from ncore.ret_codes import Codes, gen_msg_from_code
class CustomerPagination(pagination.PageNumberPagination):
page_size_query_param = 'limit'
def get_paginated_response(self, data):
return JsonResponse(**gen_m... | StarcoderdataPython |
1642507 | import requests
from opendart.config import SINGLE_FS_XML, QUATER_REPORT_KEYS, FS_DIV_KEYS
from opendart.auth.api import DartAPI
from opendart.objects.fs import FinancialStatement
from opendart.utils.url import make_url
def get_fs(corp: str, year: int, quater: int, div: int = 1) -> FinancialStatement:
"""
Mak... | StarcoderdataPython |
1779748 | from collections.abc import Sequence
import numpy as np
from mmcv.utils import build_from_cfg
from ..registry import PIPELINES
@PIPELINES.register_module()
class Compose(object):
"""Compose a data pipeline with a sequence of transforms.
Args:
transforms (list[dict | callable]):
Either c... | StarcoderdataPython |
110265 | <gh_stars>0
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from content.models import Article
from action.models import Like, Fav, Comment, Reply
@receiver(post_save, sender=Fav)
def add_fav(sender, instance=None, **kwargs):
if instance:
_article ... | StarcoderdataPython |
3347309 | import argparse
import glob
import logging
import platform
import os
import shutil
import struct
import tempfile
from distutils.util import get_platform
__requires__ = ["github_release"]
import github_release
GITHUB_REPO = "fonttools/skia-builder"
ASSET_TEMPLATE = "libskia-{plat}-{arch}.zip"
DOWNLOAD_DIR = os.path.... | StarcoderdataPython |
2875 | import json
import gzip
import requests
from datetime import datetime
import pendulum
import boto3
from botocore.exceptions import ClientError
from util.log import Log
from settings.aws_settings import AWSSettings
from settings.telegram_settings import TelegramSettings
def lambda_handler(event: dict, context: dict)... | StarcoderdataPython |
1729628 | import pytest
import rabin
import scryptlib.utils
import scryptlib.contract
from scryptlib.types import Int, PubKey, Sig, SigHashPreimage, Bytes
import bitcoinx
from bitcoinx import PrivateKey, TxOutput, SigHash, pack_byte, Script
contract = './test/res/rabin.scrypt'
compiler_result = scryptlib.utils.compile_contr... | StarcoderdataPython |
9973 | <reponame>nagylzs/syncflux
import copy
import datetime
import sys
import os
import time
import argparse
import traceback
import pytz
import syncthing
from influxdb import InfluxDBClient
import yaml
from yaml2dataclass import Schema, SchemaPath
from typing import Optional, Dict, Type, List
from dataclasses import data... | StarcoderdataPython |
152468 | #!/usr/bin/env python
"""
Example of a confirmation prompt.
"""
import quo
if __name__ == "__main__":
answer = quo.confirm("Should we do that?")
print("You said: %s" % answer)
| StarcoderdataPython |
3244119 | <filename>myModule2.py
myVar = 10
def myFunction():
print(f"This is the function inside in the module!")
# stop code executing on import of module
# if this code is executed as a standalone file then execute the code below in addition to the rest of the code
# if this code is imported as a module then do not execu... | StarcoderdataPython |
3359094 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import codecs
from pelican import signals
from pelican.generators import Generator
from linker import linker
def encode_mailto_link(mailto):
return 'mailto/' + codecs.encode(mailto, 'rot_13') + '/'
class MailtoLinker(linker.LinkerBase):
command... | StarcoderdataPython |
3338214 | # Generated by Django 2.0.7 on 2018-07-04 05:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nodes', '0002_group_enable_password'),
]
operations = [
migrations.AddField(
model_name='node',
name='comment',
... | StarcoderdataPython |
1790157 | """
mht.py
Functions for doing multiple-hypothesis testing
Creator: <NAME>
Date: 17 February 2016
"""
from scipy.stats import binom
from scipy.stats import norm
from scipy.stats import pearsonr
import numpy as np
import matplotlib.pyplot as plt
def pval_binom(data,p):
"""
Computes p-values assuming binomi... | StarcoderdataPython |
118468 | <reponame>monooso/udacity-nd256-project-four
class Node(object):
def __init__(self, id, x, y):
self.__id = id
self.__x = x
self.__y = y
self.reset()
@property
def id(self):
return self.__id
@property
def x(self):
return self.__x
@property
de... | StarcoderdataPython |
3314797 | <filename>src/db/__init__.py
from mongokit import Connection
connection = Connection()
| StarcoderdataPython |
1726516 | from requests_html import HTMLSession
session = HTMLSession()
def test_pagination():
pages = (
'https://xkcd.com/1957/',
'https://reddit.com/',
'https://pornhub.com/',
'https://theverge.com/archives'
)
for page in pages:
r = session.get(page)
assert next(r.... | StarcoderdataPython |
3376062 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import streamlit as st
import re
from IPython.display import display
import numpy as np
import shutil
import posixpath
import plotly.graph_objects as go
# EDA Pkgs
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import joblib
import pickle
import... | StarcoderdataPython |
87681 | import sys
from cv2 import cv2
import numpy as np
import mss
from pynput.mouse import Button, Controller
while True:
stc = mss.mss()
scr = stc.grab(
{
"left": 744,
"top": 152,
"width": 420,
"height": 240,
}
)
frame = np.array(scr)
hsvframe = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_white = np... | StarcoderdataPython |
1721720 | """
*G - Level 8*
"""
from .._pitch import Pitch
__all__ = ["G_8"]
class G_8(
Pitch,
):
pass
| StarcoderdataPython |
3387266 | <reponame>abhishek9sharma/MeetupDataCollection
import os
from datadownloader.queryAPI.GetDataFromAPI import *
from datadownloader.filter_groups import FilterGroups
# cat = 'Tech'
# topictofind = None
cat = None
topictofind = 'sanskrit'
city_country_state = None #Location Requires City+Country in Case of Non US Locat... | StarcoderdataPython |
3270480 | # Dump digis from simulation
# --------------------------
# The simulation pathway is gen->sim->digi1->raw->digi2->[L1->HLT | reco]
# This config examines the digis at 'digi1' level using CSCDigiDump (in CSCDigitizer).
# cf. dumpdigisfromsimraw_cfg.py which examines 'digi2'-level digis.
import FWCore.ParameterSet.Con... | StarcoderdataPython |
25959 | <gh_stars>0
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
class BuiltinOperator(object):
ADD = 0
AVERAGE_POOL_2D = 1
CONCATENATION = 2
CONV_2D = 3
DEPTHWISE_CONV_2D = 4
EMBEDDING_LOOKUP = 7
FULLY_CONNECTED = 9
HASHTABLE_LOOKUP = 10
L2_NORM... | StarcoderdataPython |
1761939 | <gh_stars>1000+
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------... | StarcoderdataPython |
3268637 | import datasets
from tango import Step
from tango.integrations.datasets import DatasetsFormat
from tango.integrations.transformers import Tokenizer
# We need a step to tokenize the raw data. The result of this step will be passed
# directly into the "torch::train" step.
@Step.register("tokenize_data")
class Tokenize... | StarcoderdataPython |
1797077 | <reponame>13rianlucero/CrabAgePrediction
import numpy as np
import pytest
from pandas import (
NaT,
PeriodIndex,
period_range,
)
import pandas._testing as tm
class TestInsert:
@pytest.mark.parametrize("na", [np.nan, NaT, None])
def test_insert(self, na):
# GH#18295 (test missing)
... | StarcoderdataPython |
1618240 | <gh_stars>1-10
from lib.filebase import FileBaseApplication
from config import FIREBASE_URL
def main():
fbapp = FileBaseApplication(FIREBASE_URL, 'temp.json')
todos = fbapp.get('/todos/app/todo398/', 'task')
print(todos)
fbapp.put('/todos/app/', 'todo99113', {'task': "Offline_support", "bounty": 15})
... | StarcoderdataPython |
1764700 | <reponame>hadyanadam/fastapi-project-template<filename>app/main.py
from fastapi import FastAPI
from app.routers import router
from app.db.session import SessionLocal
from app.db.init_db import init_db
app = FastAPI()
@app.on_event('startup')
def init_data():
db = SessionLocal()
init_db(db)
app.include_rout... | StarcoderdataPython |
3399900 | ### DAY 2: Dive! ###
fp = '2_input.txt'
with open(fp) as f:
data = f.readlines()
instructions = [line.rstrip().split(' ') for line in data]
class Sub:
def __init__(self):
self.horizontal = 0
self.depth = 0
def forward(self, forward_value):
self.horizontal += forward_value
def down(self, down_v... | StarcoderdataPython |
3336848 | <gh_stars>1-10
import hashlib
import numpy as np
from librosa import stft
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import (generate_binary_structure,
iterate_structure, binary_erosion)
import fileutils
import visutils as vis
import config as cf... | StarcoderdataPython |
171340 | def _get_owner_from_details(details, default=None):
result = default
if details.get('owner_slackid') is not None:
return '<@{}>'.format(details.get('owner_slackid'))
elif details.get('owner_name') is not None:
return details.get('owner_name')
return result
command_car_usage = 'Lookup c... | StarcoderdataPython |
4820910 | import server
import discord
import urllib.request, json
import random
import json
from replit import db
async def customCheck(message, command, args, client, p, defaultColor, fullArgs):
if command == 'prefix':
if message.author.guild_permissions.administrator == False:
... | StarcoderdataPython |
1647038 | import click
from textkit.utils import output
from unidecode import unidecode
import chardet
@click.command()
@click.argument('file', type=click.File('r'), default=click.open_file('-'))
def transliterate(file):
'''Convert international text to ascii.'''
content = ''.join(file.readlines())
try:
cont... | StarcoderdataPython |
100373 | <reponame>cljung/py-rest-api
from flask import Flask
from flask import request
from flask import Response
from flask.json import jsonify
import json
import logging
import sys, os, tempfile, uuid, time, datetime
import jwtvalidator
import restapihelper
import configparser
import argparse, sys
app = Flask(__name__)
log... | StarcoderdataPython |
27790 | """
This module contains utility functions used in the example scripts. They are
implemented separately because they use scipy and numpy and we want to remove
external dependencies from within the core library.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ impo... | StarcoderdataPython |
3229160 | from dotenv import load_dotenv
load_dotenv()
import os
MQTT_HOST = os.getenv("MQTT_HOST")
MQTT_USER = os.getenv("MQTT_USER")
MQTT_PWD = <PASSWORD>("MQTT_PWD")
SITE_NAME = os.getenv("SITE_NAME")
MQTT_TOPIC = os.getenv("MQTT_TOPIC")
INFLUX_HOST = os.getenv("INFLUX_HOST")
INFLUX_USER = os.getenv("INFLUX_USER")
INFLUX_PWD... | StarcoderdataPython |
144202 | import os
import sys
import platform
def file_dir():
dir = os.path.dirname(__file__)
if len(dir) == 0:
dir = './'
return dir
return dir
def upacker():
sysname = platform.system()
machine = platform.machine()
if sysname == 'Darwin':
if machine == 'x86_64':
re... | StarcoderdataPython |
100682 | <gh_stars>0
#!/usr/bin/env python3
'''
https://codeforces.com/group/H9K9zY8tcT/contest/297852
最长等差数列?
要用二分搜索?
nl = [l[i]-l[i-1] for i in range(1,n)]
n = len(nl)
实际是一个图的问题? 广度优先搜索?
看题解!
[print(*l2[i*n:(i+1)*n]) for i in range(n)]
l2 = ['-']*(n*n) #l2[i*n+j]=k so that v[k]=v[j]+(v[j]-v[i]), v[i]<v[j]<v[k]
#57上面超内存!
内存和... | StarcoderdataPython |
3381429 | '''Explore matrices that respect rank
identity_matrices = RankMatrices(identity_rule)
>>> identity_matrices.print_product_stats(10)
2 1 [(1, 2)]
3 1 [(0, 3), (1, 3)]
4 1 [(0, 10), (1, 5)]
4 2 [(0, 14), (1, 6)]
5 1 [(0, 32), (1, 8)]
5 2 [(0, 39), (1, 9)]
6 1 [(0, 91), (1, 13)]
6 2 [(0, 115), (1, 15)]
6 3 [(0, 101), (1... | StarcoderdataPython |
1777682 | """Adapted from code in https://gist.github.com/feelinc/d1f541af4f31d09a2ec3
Uploads files to S3.
Also uploads Cloudfront Distribution accordingly.
"""
import boto3
import json
import mimetypes
import os
import subprocess
import time
client = boto3.client("s3")
with open("package.json") as json_data:
d = json.lo... | StarcoderdataPython |
4804185 | """Cancels a billing item."""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI.command import SLCommand as SLCommand
from SoftLayer.CLI import environment
from SoftLayer.managers.account import AccountManager as AccountManager
@click.command(cls=SLCommand)
@click.argument('identifier')
... | StarcoderdataPython |
52796 | from __future__ import annotations
import torch
import torch.nn as nn
from typing import Optional
import warnings
warnings.simplefilter("ignore")
class ConvNormRelu(nn.Module):
def __init__(self, in_channels: int, out_channels: int, upsample: Optional[bool] = False) -> None:
super(ConvNormRe... | StarcoderdataPython |
3382035 | <gh_stars>0
import click
import sys
import json
from pathlib import Path
from datetime import date, timedelta
from cas_admin.connect import connect
from cas_admin.usage import compute_daily_charges, apply_daily_charges
from cas_admin.query_utils import query_account
START = date(2022, 2, 20)
YESTERDAY = date.today() -... | StarcoderdataPython |
3326198 | <gh_stars>1-10
from __future__ import print_function
import sys
import csv
import pandas as pd
import numpy as np
import os
import time
from os import listdir
import ntpath
from collections import Set
from collections import defaultdict
import re
# import operator
# from sqlalchemy import create_engine
import configpar... | StarcoderdataPython |
110582 | # This file is part of the DomainSharedContactsEditor (DSCE) application.
#
# DSCE is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.... | StarcoderdataPython |
3255657 | <filename>advanced_report_builder/migrations/0003_auto_20220215_1219.py
# Generated by Django 3.2.7 on 2022-02-15 12:19
from django.db import migrations, models
import time_stamped_model.models
class Migration(migrations.Migration):
dependencies = [
('advanced_report_builder', '0002_auto_20220209_1657')... | StarcoderdataPython |
3291509 | import sys
import os
import numpy as np
sys.path.append('../../..')
from tdcca import *
import matplotlib
matplotlib.pyplot.switch_backend('agg')
import matplotlib.pyplot as plt
from sklearn.preprocessing import scale
n, d_1, d_2, T = 100, 20, 20, 200
ext = str(n) + '_' + str(d_1) + '_' + str(d_2) + '_' + str(T) + ... | StarcoderdataPython |
199901 | <filename>python2/http_load_tools/http_load_multithreaded.py
#!/usr/bin/env python
# Copyright (c) 2008-2009 <NAME> (<EMAIL>)
#
# Multithreaded HTTP Load Generator
import time
import sys
import httplib
from threading import Thread
# URL parameters
USE_SSL = False # HTTPS/SSL support
HOST = 'examp... | StarcoderdataPython |
4805482 | from dynamicprogramming.longest_common_subsequence import *
class TestLongestCommonSubsequence:
def test_recursion(self):
assert lcs_rec("", "") == set()
assert lcs_rec("a", "") == set()
assert lcs_rec("", "a") == set()
assert lcs_rec("a", "a") == {"a"}
assert lcs_... | StarcoderdataPython |
99864 | from HABApp.core.events import ValueChangeEventFilter, ValueUpdateEventFilter
from . import MqttValueChangeEvent, MqttValueUpdateEvent
class MqttValueUpdateEventFilter(ValueUpdateEventFilter):
_EVENT_TYPE = MqttValueUpdateEvent
class MqttValueChangeEventFilter(ValueChangeEventFilter):
_EVENT_TYPE = MqttValu... | StarcoderdataPython |
1683695 | urls = []
with open('urls.txt', 'r') as f:
for url in f.readlines():
if url not in urls:
urls.append(url)
with open('urls.txt','w') as f:
f.writelines(urls)
urls = []
with open('archive.txt', 'r') as f:
for url in f.readlines():
if url not in urls:
urls.append(url)
... | StarcoderdataPython |
1709510 | <filename>results/scratch.py
import pandas as pd
import numpy as np
from scipy.stats import t # sudo pip3 install scipy
t_bounds = t.interval(0.95, len(data) - 1)
raw_data = {'name': ['<NAME>', '<NAME>', '<NAME>', '<NAME>'],
'age': [20, 19, 22, 21],
'favorite_color': ['blue', 'red', 'yellow', "green"],
'g... | StarcoderdataPython |
4843083 | import streamlit as st
import logging
def documentation_page(state):
logging.info({"message": "Loading documentation page."})
st.title("Documentation")
st.markdown("""
Anallyticabot is a simple data app that offers products for designing, analyzing, and optimizing conversational experiences.
... | StarcoderdataPython |
34252 | <gh_stars>0
from telegram import Updater
from twilio.rest import TwilioRestClient
TELEGRAM_TOKEN = "INSERT_YOUR_TOKEN_HERE"
TWILIO_ACCOUNT_SID = "INSERT_ACCOUNT_SID_HERE"
TWILIO_AUTH_TOKEN = "INSERT_AUTH_TOKEN_HERE"
# initialize telegram updater and dispatcher
updater = Updater(token=TELEGRAM_TOKEN)
dispatcher = upda... | StarcoderdataPython |
4825117 | <gh_stars>0
#!/usr/bin/python
# Copyright 2017 Northern.tech AS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | StarcoderdataPython |
1691000 | <gh_stars>0
from rest_framework import serializers
from coreapp import models
class InvoiceSerializer(serializers.Serializer):
invoice_id = serializers.CharField(max_length=30)
amount = serializers.FloatField()
transaction_id = serializers.CharField(max_length=30)
| StarcoderdataPython |
1623317 | from authlib.jose import jwt
from authlib.jose.errors import BadSignatureError, DecodeError
from flask import current_app, jsonify, request
from errors import AuthorizationError, InvalidArgumentError
def get_auth_token():
"""
Parse and validate incoming request Authorization header.
NOTE. This function ... | StarcoderdataPython |
1634286 | <gh_stars>0
from bs4 import BeautifulSoup
import re
def bs_preprocess(html):
"""remove distracting whitespaces and newline characters"""
pat = re.compile('(^[\s]+)|([\s]+$)', re.MULTILINE)
html = re.sub(pat, '', html) # remove leading and trailing whitespaces
html = re.sub('\n', ' ', html) #... | StarcoderdataPython |
1657920 | <gh_stars>0
# -*- coding: utf-8 -*-
"""The glimmerglass module contains a parsers which retrieves information from a Glimmerglass OXC device using TL1"""
# builtin modules
import logging
# local modules
import pynt.protocols.tl1
import pynt.elements
import pynt.xmlns
import pynt.input
import pynt.technologies.wdm ... | StarcoderdataPython |
1794980 | def main():
T=int(input())
while(T>0):
n,m=map(int,input().split())
mat=[[0 for j in range(m)] for i in range(n)]
line1=[int(x) for x in input().strip().split()]
k=0
for i in range(n):
for j in range (m):
mat[i][j]=line1[k]
... | StarcoderdataPython |
1780916 | from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any, Callable, Generator
from meilisearch.client import Client
from meilisearch.config import Config
from meilisearch.errors import MeiliSearchApiError, MeiliSearchError
from meilisearch.index import Index
from meili... | StarcoderdataPython |
1642650 | <reponame>Mozilla-GitHub-Standards/b6d67e88a40f8bf3a3d409382eee26f2b21c3dfdd83a544343ab9629bc3d05d9
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator, InvalidPage
from django.http import Http404, HttpResponse
from django.utils import simplej... | StarcoderdataPython |
3380731 | <reponame>OfficeGlobal/pythoncontacts<filename>contacts/o365service.py
# Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
from urllib.parse import quote
import requests
import json
import base64
import logging
import uuid
import datetime
from con... | StarcoderdataPython |
65924 | <filename>artssat/atmosphere/absorption/__init__.py
"""
Absorption
==========
"""
from abc import ABCMeta, abstractmethod, abstractproperty
from artssat.atmosphere.atmospheric_quantity \
import AtmosphericQuantity, extend_dimensions
from artssat.arts_object import ArtsObject, arts_property
from artssat.jacobian ... | StarcoderdataPython |
52463 | <gh_stars>0
def test_owner_register_success():
assert True
def test_owner_register_failure():
assert True
def test_worker_register_success():
assert True
def test_worker_register_failure():
assert True
def test_login_success():
assert True
def test_login_failure():
assert True
| StarcoderdataPython |
1672318 | <reponame>rfdeoliveira/fi-admin<filename>bireme/api/thesaurus_solr_api.py
# coding: utf-8
'''
Script utilizado para extrair elementos para criacao de XML
http://fi-admin.beta.bvsalud.org/api/desc/index/thesaurus/?format=json&ths=1&decs_code=55123
http://fi-admin.beta.bvsalud.org/api/qualif/index/thesaurus/?format=json... | StarcoderdataPython |
3244792 | <filename>instagram/json_import.py
try:
import simplejson
except ImportError:
try:
import json as simplejson
except ImportError:
try:
from django.utils import simplejson
except ImportError:
raise ImportError('A json library is required to use this python libra... | StarcoderdataPython |
3211495 | <filename>odoo-13.0/addons/l10n_latam_invoice_document/models/ir_sequence.py
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class IrSequence(models.Model):
_inherit = 'ir.sequence'
l10n_latam_journal_id = fields.Many2one('account.journal', 'Journal... | StarcoderdataPython |
39680 | import os
import time
class Var(object):
# Get a bot token from botfather
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
# Get from my.telegram.org
API_ID = int(os.environ.get("API_ID", 12345))
# Get from my.telegram.org
API_HASH = os.environ.get("API_HASH", "")
# To record start time of... | StarcoderdataPython |
3321466 | # CPU: 0.05 s
import sys
time = 0 # in hours
speed = 0
distance = 0
for line in sys.stdin.readlines():
chunks = line.split()
h, m, s = map(int, chunks[0].split(":"))
cur_time = h + m / 60 + s / 3600
time_diff = cur_time - time
distance += time_diff * speed
# Check this line is a statement or a query
if len(chu... | StarcoderdataPython |
175607 | from __future__ import print_function # Python 2/3 compatibility
import json
import boto3
from botocore.vendored import requests
import os
def lambda_handler(event, context):
print("Event:", event)
signalId = event.get('id')
actionId = event.get('actionId')
variables = event.get("variables")
... | StarcoderdataPython |
3212531 | import copy
from LspAlgorithms.GeneticAlgorithms.Chromosome import Chromosome
from LspAlgorithms.GeneticAlgorithms.LocalSearch.LocalSearchNode import LocalSearchNode
from LspInputDataReading.LspInputDataInstance import InputDataInstance
import random
class CrossOverNode:
"""
"""
def __init__(self, parentC... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.