id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
72658 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def DFS(self, node):
"""
return x_0, x_1
x_0 = the maximal value if we do NOTvisit the curre... | StarcoderdataPython |
3313931 | <gh_stars>1000+
"""
Tests onnxml LabelEncoder converter
"""
from distutils.version import LooseVersion
import unittest
import warnings
import numpy as np
from sklearn.preprocessing import LabelEncoder
import torch
from hummingbird.ml._utils import onnx_ml_tools_installed, onnx_runtime_installed, lightgbm_installed
fr... | StarcoderdataPython |
3278079 | VERSION = '0.0.1'
message = 'Hello World'
| StarcoderdataPython |
124920 | # -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import warnings
import skimage.segmentation
from patchwork._augment import SINGLE_AUG_FUNC
SEG_AUG_FUNCTIONS = ["flip_left_right", "flip_up_down", "rot90", "shear", "zoom_scale", "center_zoom_scale"]
def _get_segments(img, mean_scale=1000, num_samp... | StarcoderdataPython |
1791566 | # This file is part of RCubic
#
# Copyright (c) 2012 Wireless Generation, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... | StarcoderdataPython |
3289816 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 10:00:21 2019
@author: amandaash
"""
#step (1) Sample the function x**2 1000 and 1000 times over the interval 0 to 10
#step (2) sum the samples
#step (3) multiply sum by b-a/number of samples
#step (4) viola an integral
import numpy as np
impor... | StarcoderdataPython |
1600340 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: expandtab:tabstop=4:shiftwidth=4
'''
Custom filters for use in gce-federation scripts
'''
def add_cloudconfig_master(master_config):
for service in ('apiServerArguments', 'controllerArguments'):
for key, val in {'cloud-provider': 'gce', 'cloud-config': '/va... | StarcoderdataPython |
3359301 | def collatz(number):
if number%2 == 0:
col = number//2
else:
col = 3*number+1
print(str(col))
return col
def collatzToOne(number):
col = collatz(number)
while(col != 1):
col = collatz(col)
| StarcoderdataPython |
183956 | <reponame>EnjoyLifeFund/macHighSierra-py36-pkgs
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 <NAME> and <NAME>.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of ... | StarcoderdataPython |
3204932 | #!/usr/bin/env python3
"""
Utility functions and class for sql-extract
"""
import sys
import io
import os
import re
import csv
import openpyxl
import logging
import argparse
from profpy.db import get_cx_oracle_connection
from cx_Oracle import DatabaseError
class SqlExtractHandler(object):
"""
Helper class tha... | StarcoderdataPython |
3215967 | <reponame>rgrosse/convnet<gh_stars>1-10
import ctypes as ct
import math
import pdb
_ConvNet = ct.cdll.LoadLibrary('libcudamat_conv_gemm.so')
def DivUp(a, b):
return (a + b - 1) / b
def AddAtAllLocs(h, b):
batch_size, size_x, size_y, num_channels = h.shape4d
b_shape = b.shape
h.reshape((-1, num_channels))
b.... | StarcoderdataPython |
1673179 | import json
from binance_api.servicebase import ServiceBase
from binance.exceptions import BinanceAPIException
class Account(ServiceBase):
def balance(self, params = {}):
try:
info = self.client.get_account()
except BinanceAPIException as e:
return self._get_except_retstr(e)... | StarcoderdataPython |
169096 | <gh_stars>0
# Calculate weignted average of coins from coinmarketcap.com
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
from influxdb import InfluxDBClient
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
paramet... | StarcoderdataPython |
1656876 | <reponame>rgfaber/dev-toolkit
# -*- coding: utf-8 -*-
#
# (c) Copyright 20013 HP Development Company, L.P.
#
# This program 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 2 of the License, or
#... | StarcoderdataPython |
46038 | <filename>{{ cookiecutter.repo_name }}/{{cookiecutter.source_name}}/core/mixins/pickle_mixin.py
import gzip
import pickle
class PickableMixin:
"""A mixins to make a class a pickable object"""
def dump(self, file_name: str) -> None:
with open('{}.pkl'.format(file_name), 'wb') as f:
pickle.d... | StarcoderdataPython |
3336363 | <filename>tests/constants/test_constants.py<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license, see LICENSE.
"""
Tests for the hepunits.constants.constants module.
"""
from pytest import approx
from hepunits import eV, nanometer, s, THz
from hepunits import *
... | StarcoderdataPython |
3219685 | # -*- coding: utf-8 -*-
""" Calibration animation.
Displays points at ring intersections.
"""
from ..engine import Animation
class Calibration(Animation):
ANIMATION = __name__
ARGS = {
}
RING_COLOURS = [
(255, 0, 0), # red (0)
(0, 255, 0), # green (1)
(0, 0, 255), #... | StarcoderdataPython |
1613375 | <filename>examples/RLC/RLC_generate_test.py
from scipy.integrate import solve_ivp
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
import control.matlab
import pandas as pd
import os
from examples.RLC.symbolic_RLC import fxu_ODE, fxu_ODE_mod
if __name__ == '__main__':
# S... | StarcoderdataPython |
1760610 | <reponame>attila5287/jampayroll_blueprint<gh_stars>1-10
from flask_wtf import (
FlaskForm
)
from wtforms import (
IntegerField, SelectField
)
class TimesheetForm(FlaskForm):
pass
hh_beg_01 = IntegerField(default='09')
mm_beg_01 = IntegerField(default='00')
ap_beg_01 = SelectField(choices=[('0'... | StarcoderdataPython |
3317578 | #!/usr/bin/env nix-shell
#!nix-shell -i python3 -p poppler_utils pdftk python38 python38Packages.numpy python38Packages.pillow
import subprocess
import sys
import os
import glob
import numpy
from PIL import Image, ImageOps
pdffile = sys.argv[1]
pdffile_name = pdffile.rsplit(".",1)[0]
pgmdir_name = pdffile_name+"-pgm... | StarcoderdataPython |
192443 | <filename>lab-523.py
# Histogram of life_exp, 15 bins
plt.hist(life_exp, bins = 15)
# Show and clear plot
plt.show()
plt.clf()
# Histogram of life_exp1950, 15 bins
plt.hist(life_exp1950, bins = 15)
# Show and clear plot again
plt.show()
plt.clf() | StarcoderdataPython |
7784 | from datetime import datetime,timezone
import sys
import boto3
import json
def pipeline_event(event, context):
state = get_final_state(event)
if state is None:
return
event_time = datetime.strptime(event['time'], '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc)
metric_data = []
if eve... | StarcoderdataPython |
4839864 | # -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/11/29 22:39
# @author :Mo
# @function :textrank of textrank4zh, sklearn or gensim
from macropodus.summarize.graph_base.textrank_word2vec import TextrankWord2vec
from macropodus.summarize.graph_base.textrank_gensim import TextrankGensimSum
from macropodus.... | StarcoderdataPython |
48817 | import pathlib
from setuptools import setup, find_packages
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
setup(
description='Data extraction and processing for genre prediction using ML',
long_description=REA... | StarcoderdataPython |
3346539 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
144114 | <gh_stars>1-10
import pytest
from unittest.mock import MagicMock
from django_ontruck.notifiers import AsyncNotifier, Notifier
from ..test_app.notifiers import DummySegmentNotifier, DummySegmentWithIdentityNotifier
@pytest.fixture
def mock_user():
user = MagicMock()
user.uuid = 'uuid'
return user
def tes... | StarcoderdataPython |
72920 | # Copyright (c) 2020 NVIDIA Corporation
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, d... | StarcoderdataPython |
1749316 | <gh_stars>1-10
'''
Set of luigi tasks for the opv project
version 0.3
'''
import os, os.path, sys , copy ,shutil, logging, math, json, csv
import numpy as np
from datetime import datetime
from optparse import OptionParser
import pybel,openbabel
from streamm import *
import logging
logger = logging.getLogger()
l... | StarcoderdataPython |
14802 | <reponame>rassouly/exopy_qm
from exopy.tasks.api import (InstrumentTask)
from atom.api import Unicode, Bool, set_default
import sys
from exopy_qm.utils.dynamic_importer import *
class GetIOValuesTask(InstrumentTask):
""" Gets the IO values
"""
get_io_1 = Bool(True).tag(pref=True)
get_io_2 = Bool(Tru... | StarcoderdataPython |
1792932 | import enum
from typing import Iterable, Optional, Tuple
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from database import BLOCKCHAIN, Database
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
import csv
class ViewMode(enum.Enum):
ASCII_HISTOGRAM = "a... | StarcoderdataPython |
3311758 | <gh_stars>1000+
"""
Copyright 2017-present Airbnb, 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 by applicable law or agreed to... | StarcoderdataPython |
154905 | # -*- coding: utf-8 -*-
# Copyright © 2019 <NAME>, <NAME>
# Made available under the MIT license.
import unittest
from unittest import mock
from urban_eater.importers.thrillist import thrillist
TEST_FILE = "testdata/page.html"
TEST_RESTAURANTS_NAME = "Beast"
TEST_RESTAURANTS_URL = "https://www.beastpdx.com/"
TEST_RE... | StarcoderdataPython |
1600383 | # std
from datetime import datetime
class TestEventStore:
def test_create_eventstore(self, client, new_database_headers):
out = client.post(
"/api/v1/eventstore/test_database",
headers=new_database_headers,
json={"type": "molecule", "data": {"smiles": "abc"}},
)... | StarcoderdataPython |
126061 | # -*- coding: utf-8 -*-
from functools import partial
from datetime import datetime
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.l... | StarcoderdataPython |
3214906 | # Attempts at vectorising the lensing process
# import modules
import numpy as np
import matplotlib.pyplot as plt
import timeit
# %%
# start the timer
start = timeit.default_timer()
# set up some initial parameters
rc = 0.7
eps = 0
dom = 1 # abs() of domain of r values (normally -1, 1 --> 1)
size = 21 # odd for t... | StarcoderdataPython |
150502 | <reponame>NicholasTaylor/HumbleBike<filename>datapull/datapull.py
import json, records_pb2, os, gzip, requests
from datetime import datetime
STATION_INFORMATION = 'https://gbfs.citibikenyc.com/gbfs/en/station_information.json'
STATION_STATUS = 'https://gbfs.citibikenyc.com/gbfs/en/station_status.json'
FILE_STEM = 'rec... | StarcoderdataPython |
93299 | <filename>data_collection/gazette/spiders/sp_sao_roque.py
from gazette.spiders.base.instar import BaseInstarSpider
class SpSaoRoqueSpider(BaseInstarSpider):
TERRITORY_ID = "3550605"
name = "sp_sao_roque"
allowed_domains = ["saoroque.sp.gov.br"]
start_urls = ["https://www.saoroque.sp.gov.br/portal/diar... | StarcoderdataPython |
102543 | from .callbacks import Callback
class Checkpoint(Callback):
def __init__(self, interval=1):
self.interval = interval
def epoch_end(self, stats):
if stats['epoch'] % self.interval == 0:
filename = '{}_{:03d}.h5'.format(stats['name'], stats['epoch'])
stats['model'].save(fi... | StarcoderdataPython |
3203307 | # Copyright 2006 <NAME> and contributors
#
# 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 ... | StarcoderdataPython |
1795532 | from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from django.db.transaction import a... | StarcoderdataPython |
111007 | <reponame>KeyueZhu/XenomatiX
from numpy import genfromtxt
from PIL import Image
import matplotlib.pyplot as plt
from os import listdir
# grey_scale_arr = genfromtxt('grey1314.csv', delimiter=',')
# print(len(grey_scale_arr), len(grey_scale_arr[0]))
# flat = grey_scale_arr.flatten()
# # for i, val in enumerate(flat):... | StarcoderdataPython |
1647485 | <filename>events/models.py
from tabnanny import verbose
from django.db import models
# Create your models here.
class Event(models.Model):
id = models.AutoField(primary_key=True)
class JenisKelamin(models.TextChoices):
LAKI_LAKI = 'L'
PEREMPUAN = 'P'
jenis_kelamin = models.CharField(
... | StarcoderdataPython |
3318003 | size(322, 603)
frog_j = open("froschjap.txt").read()
frog_d = open("froschd.txt").read()
fill(0.2)
rect(0, 0, WIDTH, HEIGHT)
image("frog.jpg", 0, 0, 322, 603)
fill("#5c2018")
font("Garamond-Bold", 32)
text("Frosch-Haiku", 20, 80)
font("Hiragino Kaku Gothic Pro", 14)
text(frog_j, 20, 130)
font("Garamond-Bold", 14)... | StarcoderdataPython |
140205 | # Generated by Django 4.0.3 on 2022-03-24 15:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('inventory', '0012_remove_group_hosts_host_groups'),
]
operations = [
migrations.AlterField(
mod... | StarcoderdataPython |
4802241 | #!/usr/bin/env python
# coding: utf-8
from argparse import ArgumentParser
import json
from pathlib import Path
import joblib
import pyprojroot
import torch
import detection
def main(args):
results_dst = Path(args.results_dst)
results_dir_path = results_dst / args.results_dir
if not results_dir_path.exis... | StarcoderdataPython |
3346125 | <reponame>th3cyb3rc0p/Nettacker
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME> github.com/aman566
# https://support.f5.com/csp/article/K52145254
import socket
import socks
import time
import json
import threading
import string
import random
import sys
import struct
import re
import os
from OpenSSL impo... | StarcoderdataPython |
3354674 | <gh_stars>10-100
""" Normalization layers and wrappers
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class GroupNorm(nn.GroupNorm):
def __init__(self, num_channels, num_groups, eps=1e-5, affine=True):
# NOTE num_channels is swapped to first arg for consistency in swapping norm lay... | StarcoderdataPython |
106354 | <reponame>yujiecong/yjcL<gh_stars>0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@IDE :PyCharm
@Project :yjcL
@USER :yanyin
@File :PrintSomething.py
@Author :yujiecong
@Date :2021/8/31 15:58
'''
import pprint
from restart.Enum.Enum import StatementType, TokenType, ExpressionType
import resta... | StarcoderdataPython |
3236731 | # -*- coding: utf-8 -*-
# Copyright (c) 2020-2021 <NAME>.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
from django.test import TestCase
from django.core import management
from BasisTypen.models import BoogType
from Competitie.models import (Competitie, CompetitieKlasse,... | StarcoderdataPython |
48476 | <reponame>LaudateCorpus1/oneview-python<filename>examples/id_pools_ipv4_ranges.py
# -*- coding: utf-8 -*-
###
# (C) Copyright [2021] Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... | StarcoderdataPython |
162721 | <gh_stars>1-10
# -*- coding: utf-8 -*-
VERSION = (9999, 9999, 9999, 'alpha', 1)
| StarcoderdataPython |
61384 | <gh_stars>10-100
import codecademylib
import pandas as pd
df = pd.read_csv('employees.csv')
total_earned = lambda row: row['hours_worked'] * row['hourly_wage'] if row['hours_worked'] <= 40 else (40 * row['hourly_wage']) + (row['hours_worked'] - 40) * (row['hourly_wage'] * 1.50)
df['total_earned'] = df.apply(total_e... | StarcoderdataPython |
1792030 | from abc import ABC, abstractmethod
import textwrap
from typing import Union, List, Dict
from pydantic import BaseModel
from nmea.nmea_utils import convert_bits_to_int, convert_int_to_bits, get_char_of_ascii_code, convert_decimal_to_ascii_code, \
convert_ascii_char_to_ascii6_code, add_padding, add_padding_0_bits,... | StarcoderdataPython |
3294648 | <filename>config/custom_components/huesyncbox/config_flow.py<gh_stars>100-1000
"""Config flow for Philips Hue Play HDMI Sync Box integration."""
import asyncio
import logging
import voluptuous as vol
from homeassistant import core, config_entries, exceptions
from homeassistant.core import callback
from .const import... | StarcoderdataPython |
1681472 | """
This script is used for course notes.
Author: <NAME>
Date: 10/09/2020
"""
def hint_username(username):
""" If username is less than than 3 characters, print message else
, if valid length, print message. """
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long")
... | StarcoderdataPython |
3336837 | from drkns.generation.templateloading.get_generation_template \
import get_generation_template, _extract_from_tag_prefix
def test_get_generation_template():
get_generation_template('./testprojects/nominalcase')
def test_extract_from_tag_prefix():
faked_content = """
Something to stay in content
... | StarcoderdataPython |
1770571 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from urlparse import urlparse
from xml.sax.saxutils import escape
import httplib
class ReposSolr(object):
'''
Utility methods for common solr core operations in Repos Search handlers.
'''
def __init__(self, svnhookOptions):
self.opt... | StarcoderdataPython |
103659 | <filename>python/decorator/demo.py<gh_stars>10-100
from component import Component
from decorator import Decorator
if __name__ == "__main__":
print("***Demo: pattern Decorator")
print("Creating: a component with name=Bob, age=30")
component = Component("Bob", 30)
print("Decorating: with new state and b... | StarcoderdataPython |
1668305 | <gh_stars>100-1000
#!/usr/bin/env sage
from typing import Any, Dict, Optional, Tuple
from sage.all import (
bsgs,
CRT_list,
EllipticCurve,
factor,
GF,
)
import warnings
import logging
import hashlib
import random
import base64
import json
import sys
# ignore bsgs deprecation
warnings.filterwarning... | StarcoderdataPython |
3296385 | <gh_stars>1-10
from flask import Blueprint
from flask import Flask, abort
from flask import jsonify
from flask import render_template
from flask import request,send_from_directory
import requests
import config as conf
import helpers
argumentation_api = Blueprint('argumentation_api', __name__)
@argumentation_api.rout... | StarcoderdataPython |
1778632 | <reponame>srini009/ascent
###############################################################################
# Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
# Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
# other details. No copyright assignment is required to contr... | StarcoderdataPython |
1774782 | <gh_stars>1-10
import unittest
from rdlmpy import RDLMContextManager
from httpretty import HTTPretty, httprettified
from rdlmpy import RDLMLockWaitExceededException
class SpecialException(Exception):
pass
class TestContext(unittest.TestCase):
context = None
server = "localhost"
port = 8888
baseu... | StarcoderdataPython |
1611598 | """
Author: <NAME>
Version: 1.0
Date: 30.10.2021
Function: run an evolution with the with specific parameter to detect objects in pictures
Partly adopted, inspired and merge from ->
https://github.com/automl/auto-sklearn
https://github.com/automl/Auto-PyTorch
https://github.com/PaulPauls/Tensorflow-Neuroevolution
ht... | StarcoderdataPython |
3242904 | <filename>app/api/pograph.py
# -*- encoding: utf-8 -*-
"""
@File : pograph.py
@Time : 2020/2/28 7:53 下午
@Author : zhengjiani
@Email : <EMAIL>
@Software: PyCharm
"""
from flask import jsonify, request
from app.models import Page,db
from . import api
from bokchoy_pages import po_parse
from .. import dao
from ..... | StarcoderdataPython |
169391 | from sqlalchemy import (
MetaData,
Table,
Column,
Integer,
DateTime,
NVARCHAR,
String,
Index,
Boolean,
)
from migrate.changeset.constraint import ForeignKeyConstraint, UniqueConstraint
meta = MetaData()
field = Table(
"field",
meta,
Column("id", Integer, primary_key=Tr... | StarcoderdataPython |
21406 | from sqlalchemy.orm import Session
from src import crud
from src.core.security import verify_password
from src.schemas.user import UserCreate, UserUpdate
from src.tests.utils.user import create_random_user_by_api
from src.tests.utils.utils import random_lower_string
def test_create_user(db: Session):
username = ... | StarcoderdataPython |
1669610 | <gh_stars>1-10
# 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, software
# d... | StarcoderdataPython |
1745062 | """
hubspot forms api
"""
from hubspot3.base import BaseClient
class FormSubmissionClient(BaseClient):
"""allows acccess to the forms api"""
def __init__(self, *args, **kwargs):
super(FormSubmissionClient, self).__init__(*args, **kwargs)
self.options["api_base"] = "forms.hubspot.com"
def... | StarcoderdataPython |
3206601 | from flask import Blueprint, jsonify, request
from flask_login import login_required, current_user
from macronizer_cores import db
from macronizer_cores.models import Log, FoodItem
from macronizer_cores.log_api.utils import create_food_log
from datetime import datetime
# create blueprint
log_api = Blueprint('log_api... | StarcoderdataPython |
1775003 | <filename>QuickSorting.py<gh_stars>0
from sys import argv
def countNum(filename):
#notFoundFile exception
try:
#open the file
file = open(filename)
#parts = line.split(",")
m = file.readlines()
#get file and return them as string
for line in file:
... | StarcoderdataPython |
177320 | <gh_stars>1-10
from torch import nn, optim
import torch.nn.functional as F
from torchvision import datasets, transforms
import torch
#--------------LOAD THE DATA---------------------------------------
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
... | StarcoderdataPython |
1744449 | #!/bin/sh -e
'''echo'
export PYTHONPATH=.
export DJANGO_SETTINGS_MODULE=run_redisboard
secret() {
tr -cd "[:alnum:]" < /dev/urandom | head -c ${1:-8}
}
chmod u+x run_redisboard.py
if [ "$1" = "--develop" ]; then
shift
REDISBOARD="-e ."
else
REDISBOARD="django-redisboard"
fi
if [ ! -e .redisboard.venv ]... | StarcoderdataPython |
3204944 | <filename>1863_Sum_of_All_Subset_XOR_Totals.py
from typing import List
from itertools import combinations, accumulate
from functools import reduce
class Solution:
def subsetXORSum2(self, nums: List[int]) -> int:
"""making use of the built in combinations function and the accumulate function"""
# R... | StarcoderdataPython |
3379683 | """Allow users to view and modify (add, delete, chnage) material data.
For the convennience of data manipulation and displaying, this application
is built on Django REST Framework.
""" | StarcoderdataPython |
1729661 | import peewee
import datetime
database = peewee.MySQLDatabase('test', host='localhost', port=3306, user='root', passwd='')
class User(peewee.Model):
username = peewee.CharField(unique=True, max_length=50, index=True)
password = peewee.CharField(max_length=50, null=True)
email = peewee.CharField(max_length=50)
... | StarcoderdataPython |
149812 | from django.conf import settings
def version_context_processor(request):
"""
Version context processor
"""
return {'version': settings.APP_VERSION}
| StarcoderdataPython |
1702207 | import json
from src.services.send_email import Email
from src.repository import Repository
if __name__ == "__main__":
address_tokens = []
while True:
init = input("Gostaria de adicionar um novo token? [Y/N] ")
if init.lower() == "n":
break
address = input("Digite um endere... | StarcoderdataPython |
1768871 |
'''Helper to preload vcomp140.dll, vcruntime140.dll and
vcruntime140_1.dll to prevent "not found" errors.
Once vcomp140.dll, vcruntime140.dll and vcruntime140_1.dll are
preloaded, the namespace is made available to any subsequent
vcomp140.dll, vcruntime140.dll and vcruntime140_1.dll. This is
created as part of... | StarcoderdataPython |
1720855 | #!venv/bin python
# -*- coding: UTF-8 -*-
"""
RoEngine_temp is a library for making mundane parts easy and fast.
"""
from .game import *
from .net import *
from .util import *
from .gui import *
from roengine.misc.cursors import *
# NOTE: The following imports are unused
from roengine.misc.maths import *
from roengi... | StarcoderdataPython |
3295452 | <filename>geminidr/core/parameters_resample.py<gh_stars>1-10
# This parameter file contains the parameters related to the primitives located
# in the primitives_GEMINI.py file, in alphabetical order.
from gempy.library import config
class resampleToCommonFrameConfig(config.Config):
suffix = config.Field("Filename ... | StarcoderdataPython |
3214842 | import __future__
from collections import deque
import st, frequencyCounter
class Node(object):
def __init__(self, key, value, N=1, left = None, right = None):
self.key = key
self.value = value
self.left = left
self.right = right
self.N = N
class BST(st.ST):
def __ini... | StarcoderdataPython |
3297531 | <reponame>boucherv/functest
#!/usr/bin/env python
# Copyright (c) 2018 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licen... | StarcoderdataPython |
3223668 | import pickle
import os.path
import email
import base64
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
def search_messages(service, user_id, search_string... | StarcoderdataPython |
1615087 | <filename>db/__init__.py<gh_stars>0
'''
The database module
Base - A base class for all sqlalchemy ORM objects
'''
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
| StarcoderdataPython |
112751 | #!/usr/bin/env python
#
# :History:
#
# 11 Oct 2018: Created
# 18 Oct 2018: Modified to merge CDP-5 format CDPs together to make a new
# CDP-7 format CDP. Added --document and --description parameters.
#
# @author: <NAME> (UKATC)
#
"""
Script `append_lrs_photom` creates a merged photometric CDP for the ... | StarcoderdataPython |
1700248 | import os
import numpy as np
import autoarray as aa
path = "{}/".format(os.path.dirname(os.path.realpath(__file__)))
class TestArray2DEuclid:
def test__euclid_array_for_four_quandrants__loads_data_and_dimensions(
self, euclid_data
):
euclid_array = aa.euclid.Array2DEuclid.top... | StarcoderdataPython |
151583 | <filename>wikis/forms/articles.py
# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _
from django.conf import settings
from wikis.settings import *
from permissions.forms import PermissionForm
if 'taggit' in settings.INSTALLED_APPS:
from taggit import f... | StarcoderdataPython |
50665 | <reponame>lbfederico/gmx_scripts
import sys
def get_line(txt):
file = open('topol.top', encoding='utf8')
for line_num, value in enumerate(file, 1):
if txt in value:
return line_num
if len(sys.argv) < 3:
print('ERROR: put lig and cof names wi... | StarcoderdataPython |
122334 | <reponame>PacRobotic/pekee1r
import serial
import time
import sys
i = 0
while True:
ser = serial.Serial('/dev/ttyACM0',115200)
i +=1
ser.write(str.encode("s{:4}".format(i)))
print("s{:4}".format(i))
time.sleep(0.01)
#running = True;
#while running: # Or: while ser.inWaiting():
# if ser.in_... | StarcoderdataPython |
1612145 | <gh_stars>0
#!/usr/local/bin/python3
# Code block that allows calling sibling subdirectories
from sys import path
from os.path import dirname
path.append(dirname(path[0]))
# End code block
import primary
from lib_dependent import second
if __name__ == '__main__':
primary.first()
second()
| StarcoderdataPython |
3229181 | # vim: sw=4:ts=4:et
import datetime
import json
import logging
import os, os.path
import time
import unittest
import saq
from saq.analysis import _JSONEncoder, RootAnalysis, _get_io_write_count, _get_io_read_count, MODULE_PATH, SPLIT_MODULE_PATH
from saq.modules import AnalysisModule
from saq.modules.test import Bas... | StarcoderdataPython |
117346 | <filename>QueryConstructor.py<gh_stars>0
import sqlite3
import re
#parses query_text to get client system and env and name keywords
#
def get_filters_from_text(query_text):
filter_to_parameter_map = dict()
position_list = list()
filter_list =['client','system','env','name']
for filters in filter_li... | StarcoderdataPython |
1699448 | # -*- coding: utf-8 -*-
from django.db.models import Q
from django_filters import FilterSet, filters
from pipeline.models import PipelineTemplate
from gcloud.label.models import TemplateLabelRelation
from gcloud.tasktmpl3.models import TaskTemplate
class TaskTemplateFilter(FilterSet):
label_ids = filters.CharFilt... | StarcoderdataPython |
1611267 | <gh_stars>0
from typing import Dict
import transaction
from pyparsing import ParseException
from sqlalchemy import String, and_, orm
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import ColumnProperty, Mapper, RelationshipProperty
from sqlalchemy.orm.base ... | StarcoderdataPython |
3320805 | import logging
import os
import random
import numpy as np
import torch
from model import JointPhoBERT, JointXLMR
from seqeval.metrics import f1_score, precision_score, recall_score
from transformers import (
AutoTokenizer,
RobertaConfig,
XLMRobertaConfig,
XLMRobertaTokenizer,
)
MODEL_CLASSES = {
... | StarcoderdataPython |
32025 | <reponame>qiulin/dbt-doris<filename>dbt/adapters/doris/__init__.py
from dbt.adapters.doris.connections import DorisConnectionManager
from dbt.adapters.doris.connections import DorisCredentials
from dbt.adapters.doris.relation import DorisRelation
from dbt.adapters.doris.column import DorisColumn
from dbt.adapters.doris... | StarcoderdataPython |
1629962 | <filename>axiom/test/path_postcopy.py
# -*- test-case-name: axiom.test.test_upgrading.PathUpgrade.test_postCopy -*-
from axiom.attributes import path
from axiom.item import Item
from axiom.upgrade import registerAttributeCopyingUpgrader
class Path(Item):
"""
Trivial Item class for testing upgrading.
"""... | StarcoderdataPython |
3392235 | from flask import render_template
from application import app
from application.samples.models import Sample
from application.albums.models import Album
@app.route("/")
def index():
most_recent_sample = Sample.get_most_recent()
album_with_most_samples = Album.get_album_with_most_samples()
return render_tem... | StarcoderdataPython |
24985 | <reponame>maxuepo/x-review-processor
from __future__ import print_function
from sklearn.feature_extraction.text import TfidfVectorizer
from common.util import ReviewUtil
import numpy as np
import ntpath
import pandas as pd
import os
from common.base_task import BaseTask
class ReviewDedupTask(BaseTask):
def __init... | StarcoderdataPython |
50552 | import time
Q1 = input("Who do you like: ")
Q2 = input("Who do you hate: ")
Answer = f"I love {Q2} but hate {Q1}"
print(Answer)
time.sleep(3) | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.